org.mockito.exceptions.base.MockitoException: Checked exception is invalid for this method - mockito

I am trying to test service layer using junit5 with spring boot 2.6.2, and I want to test throwing exception if the account not found,
I wrote the below test method
#Test
void getUserAccountWithUserAccountNotFoundExceptionTest() {
/**
* TODO tried to to test it but getting this error
* Checked exception is invalid for this method
*/
when(this.systemUserRepository.findByEmailAddress(emailAddress)).thenThrow(UserAccountNotFoundException.class);
Assertions.assertThrows(UserAccountNotFoundException.class, ()->{
this.manageUserAccountService.getUserAccount(emailAddress);
});
}
snippet of the service Implementation
#Service
public class ManageUserAccountServiceImpl {
.............
#Override
public UserAccountDto getUserAccount(String emailAddress) throws UserAccountNotFoundException {
......
.......
}
..........
}
User Account not found exception class
public class UserAccountNotFoundException extends UserAccountException {
public UserAccountNotFoundException() {
super();
}
public UserAccountNotFoundException(int errorCode, String errorMessage) {
super(errorCode, errorMessage);
}
public UserAccountNotFoundException(Throwable cause, boolean enableSuppression, boolean writableStackTrace,
int errorCode, String errorMessage) {
super(cause, enableSuppression, writableStackTrace, errorCode, errorMessage);
}
public UserAccountNotFoundException(Throwable cause, int errorCode, String errorMessage) {
super(cause, errorCode, errorMessage);
}
}
User account exception class
public class UserAccountException extends Exception {
/**
*
*/
private static final long serialVersionUID = -591169136507677996L;
protected ErrorInfoDto errorInfoDto;
public UserAccountException() {
super();
}
public UserAccountException(Throwable cause, boolean enableSuppression,
boolean writableStackTrace,int errorCode, String errorMessage) {
this.errorInfoDto = formErrorInfoDto(errorCode, errorMessage);
}
public UserAccountException(int errorCode,String errorMessage) {
this.errorInfoDto = formErrorInfoDto(errorCode, errorMessage);
}
public UserAccountException(Throwable cause,int errorCode, String errorMessage) {
this.errorInfoDto = formErrorInfoDto(errorCode, errorMessage);
}
private ErrorInfoDto formErrorInfoDto(int errorCode, String errorMessage) {
ErrorInfoDto errorInfoDto = null;
errorInfoDto = new ErrorInfoDto();
errorInfoDto.setErrorCode(errorCode);
errorInfoDto.setErrorMessage(errorMessage);
return errorInfoDto;
}
public ErrorInfoDto getErrorInfoDto() {
return errorInfoDto;
}
}
Repository interface
public interface SystemUserRepository extends JpaRepository<SystemUser, Long> {
long countByEmailAddress(String emailAddress);
long countByMobileNo(String mobileNo);
Optional<SystemUser> findByEmailAddress(String emailAddress);
}

The Mockito exception says it alone - the line when(this.systemUserRepository.findByEmailAddress(emailAddress)).thenThrow(UserAccountNotFoundException.class); instructs Mockito to throw exception when systemUserRepository.findByEmailAddress(...) is called.
However, the posted code for SystemUserRepository does declare any checked exception on the method: Optional<SystemUser> findByEmailAddress(String emailAddress);
Note also that SystemUserRepository handles the case of user not found by giving an Optional.empty() and not by throwing an exception.

Related

Problem opening BiometricPrompt android studio

I have a code where I call biometrics for password validation, and it ends up working normally, I always have the expected results when I request, but it ends up generating an error on my console that I would like you to solve, but I don't find it in place some.
Follow the code:
Error:
java.lang.IllegalStateException: Must be called from main thread of fragment host
at androidx.fragment.app.FragmentManagerImpl.ensureExecReady(FragmentManagerImpl.java:1668)
at androidx.fragment.app.FragmentManagerImpl.execPendingActions(FragmentManagerImpl.java:1721)
at androidx.fragment.app.FragmentManagerImpl.executePendingTransactions(FragmentManagerImpl.java:183)
at androidx.biometric.BiometricPrompt.authenticateInternal(BiometricPrompt.java:749)
at androidx.biometric.BiometricPrompt.authenticate(BiometricPrompt.java:658)
at com.app.EntryPoint.showBiometricPrompt(EntryPoint.java:832)
at ifractal.ManagingRequests$1.callback(ManagingRequests.java:156)
at ifractal.ManagingRequests.itAllStartsHere(ManagingRequests.java:1598)
at ifractal.JSBridge.query(JSBridge.java:35)
at android.os.MessageQueue.nativePollOnce(Native Method)
at android.os.MessageQueue.next(MessageQueue.java:326)
at android.os.Looper.loop(Looper.java:165)
at android.os.HandlerThread.run(HandlerThread.java:65)
public boolean showBiometricPrompt(String callback, String primeiro_acesso) {
BiometricPrompt.PromptInfo promptInfo =
new BiometricPrompt.PromptInfo.Builder()
.setTitle("Autenticação")
.setSubtitle("Realize o login usando sua biometria")
.setNegativeButtonText("Cancelar")
.build();
BiometricPrompt biometricPrompt = new BiometricPrompt(EntryPoint.this,
executor, new BiometricPrompt.AuthenticationCallback() {
#Override
public void onAuthenticationError(int errorCode, #NonNull CharSequence errString) {
super.onAuthenticationError(errorCode, errString);
asset.log("onAuthenticationError", "Error: " +errString);
}
}
#Override
public void onAuthenticationSucceeded(
#NonNull BiometricPrompt.AuthenticationResult result) {
super.onAuthenticationSucceeded(result);
BiometricPrompt.CryptoObject authenticatedCryptoObject =
result.getCryptoObject();
}
#SuppressLint("WrongConstant")
#Override
public void onAuthenticationFailed() {
super.onAuthenticationFailed();
asset.log("onAuthenticationError", "Failed");
}
});
biometricPrompt.authenticate(promptInfo);
return true;
}

Alaways goin in onFailure in retrofit2.0

I am trying to hit the api : www.xyz.com/abc_cc/cc/userregister/newuser
This is my Code :
public class MainActivity extends AppCompatActivity {
public static final String BASE_URL = "abc.com/abc_cc/cc/";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(BASE_URL)
.client(getUnsafeOkHttpClient())
.addConverterFactory(GsonConverterFactory.create())
.build();
Endpoints endpoints= retrofit.create(Endpoints.class);
endpoints.newuser("{\"full_name\":\"sss\",\"states_id\":\"20\",\"mobile\":\"9876543210\",\"password\":\"******\",\"accept_terms\":true,\"Userid\":\"0\",\"refer\":\"\",\"ip-address\":\"1.2.3.4\",\"device_type\":\"samsung J5\",\"os-version\":\"5.0.1\",\"client\":\"app\",\"secret_key\":\"44\"}")
.enqueue(new retrofit2.Callback<Items>() {
#Override
public void onResponse(retrofit2.Call<Items> call, retrofit2.Response<Items> response) {
System.out.println("onResponse : "+response.message());
System.out.println("onResponse : "+response.body());
System.out.println("onResponse : "+response.code());
System.out.println("onResponse : "+response.errorBody());
System.out.println("onResponse : "+response.isSuccessful());
System.out.println("onResponse : "+response.raw());
System.out.println("onResponse : "+response);
}
#Override
public void onFailure(retrofit2.Call<Items> call, Throwable t) {
System.out.println("onFailure"+call);
}
});
}
public static OkHttpClient getUnsafeOkHttpClient() {
try {
// Create a trust manager that does not validate certificate chains
final TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
#Override
public void checkClientTrusted(
java.security.cert.X509Certificate[] chain,
String authType) throws CertificateException {
}
#Override
public void checkServerTrusted(
java.security.cert.X509Certificate[] chain,
String authType) throws CertificateException {
}
#Override
public java.security.cert.X509Certificate[] getAcceptedIssuers() {
return new java.security.cert.X509Certificate[0];
}
} };
// Install the all-trusting trust manager
final SSLContext sslContext = SSLContext.getInstance("TLS");
sslContext.init(null, trustAllCerts,
new java.security.SecureRandom());
// Create an ssl socket factory with our all-trusting manager
final SSLSocketFactory sslSocketFactory = sslContext
.getSocketFactory();
OkHttpClient okHttpClient = new OkHttpClient();
okHttpClient = okHttpClient.newBuilder()
.sslSocketFactory(sslSocketFactory)
.hostnameVerifier(org.apache.http.conn.ssl.SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER).build();
return okHttpClient;
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
Interface :
public interface Endpoints {
#POST("/userregister/newuser")
#FormUrlEncoded
Call<Items> newuser(#Field("Data") String Data);
}
POJO class :
public class Items {
#SerializedName("Response-Status")
#Expose
private Boolean responseStatus;
#SerializedName("Response-Validate")
#Expose
private Boolean responseValidate;
#SerializedName("Response-Message")
#Expose
private String responseMessage;
#SerializedName("Response-Data")
#Expose
private ResponseData responseData;
public Boolean getResponseStatus() {
return responseStatus;
}
public void setResponseStatus(Boolean responseStatus) {
this.responseStatus = responseStatus;
}
public Boolean getResponseValidate() {
return responseValidate;
}
public void setResponseValidate(Boolean responseValidate) {
this.responseValidate = responseValidate;
}
public String getResponseMessage() {
return responseMessage;
}
public void setResponseMessage(String responseMessage) {
this.responseMessage = responseMessage;
}
public ResponseData getResponseData() {
return responseData;
}
public void setResponseData(ResponseData responseData) {
this.responseData = responseData;
}
}
I am getting this response :
{protocol=http/1.1, code=404, message=Not Found, url=www.xyz.com/userregister/newuser}
I have given the proper url then why is it taking only half of it?
I have tried the example from https://code.tutsplus.com/tutorials/sending-data-with-retrofit-2-http-client-for-android--cms-27845. This example and the link given in the example are working fine, but if I do the same with my url then I get the above error
I Hope kindly check your parsing issues may occurred.
#Override
public void onFailure(retrofit2.Call<Items> call, Throwable t) {
System.out.println("onFailure"+call);
//add this lije you got exceptions.
t.printStackTrace();
}
Change your Endpoints interface for this:
public interface Endpoints {
#POST("userregister/newuser")
#FormUrlEncoded
Call<Items> newuser(#Field("Data") String Data);
}
Note that I removed the trailing slash /. This way Retrofit appends the path you defined to the BASE_URL.
refer to the docs for Retrofit.Builder for a more detailed explanation, but pay particular attention to these bits:
Base URLs should always end in /.
A trailing / ensures that endpoints values which are relative paths
will correctly append themselves to a base which has path components.
...
Endpoint values which contain a leading / are absolute.
Absolute values retain only the host from baseUrl and ignore any
specified path components.
as presently written, the path referenced in your call to Endpoints.newuser() is absolute, and therefore the path segments after the host in your base URL are dropped (as this is the documented behavior).
therefore, you should change your Endpoints interface to use relative paths instead, like so:
public interface Endpoints {
#POST("userregister/newuser")
#FormUrlEncoded
Call<Items> newuser(#Field("Data") String Data);
}

java.lang.ClassCastException: org.apache.log4j.Logger cannot be cast

I extended org.apache.log4j.Logger for implementing logging for method starts and exists.
It works fine, when I don't set the loglevel for a class in my log4j.properties.
When I set
log4j.logger.de.martinm.tools.UniCredit.ExportOperator=INFO
I get an exception:
Exception in thread "main" java.lang.ClassCastException: org.apache.log4j.Logger cannot be cast to de.martinm.tools.Logging.MMLogger
at de.martinm.tools.UniCredit.ExportOperator.(ExportOperator.java:21)
at de.martinm.tools.UniCredit.ExportOperator.main(ExportOperator.java:330)
public class MMLogger extends Logger {
private static MyLoggerFactory myFactory = new MyLoggerFactory();
public MMLogger(String name) {
super(name);
}
public static Category getInstance(String name) {
return Logger.getLogger(name, myFactory);
}
public static Logger getLogger(String name) {
return Logger.getLogger(name, myFactory);
}
public void enter(Logger logger, String method) {
super.debug(method+" enter");
}
public void exit(Logger logger, String method) {
super.debug(method+" exit");
}
public void debug(Logger logger, String method, String text) {
super.debug(method+" "+text);
}
public void warn(Logger logger, String method, String text) {
super.warn(method+" "+text);
}
public void info(Logger logger, String method, String text) {
super.info(method+" "+text);
}
public void error(Logger logger, String method, String text) {
super.error(method+" "+text);
}
}
public class MyLoggerFactory implements LoggerFactory {
/**
The constructor should be public as it will be called by
configurators in different packages. */
public
MyLoggerFactory() {
}
public
Logger makeNewLoggerInstance(String name) {
return new MMLogger(name);
}
}
Here is part of my code
public class ExportOperator {
//public static Logger logger = Logger.getLogger(ExportOperator.class.getName());
public MMLogger Mylogger = (MMLogger) MMLogger.getLogger(ExportOperator.class.getName());
public Connection db_con;
static Utils my_utils = new Utils();
public Properties props = new Properties();
public String output_dir;
public int mid;
public String admin_id;
public int op_id;

JAVA/JAXB : Marshal/UnMarshal using attributes in the xml or class members

I have XML as follows
<request type="1">
<request-header/>
<request-details>
<!-- Some more tags -->
</request-details>
</request>
For mapping this XML I have class structure as follows :
public class Request1
{
private RequestDetail_1;
//other members
}
public class Request2
{
private RequestDetail_2;
//other members
}
public class RequestDetail_1
{
//members
}
public class RequestDetail_2
{
//Members
}
What I want to do is ... If attribute type is 1 then I need to create object of type Request_1 , if type is 2 then object type will be Request_2 and so on.
I have gone through this link for reference but still couldn't figure out a way to do this. I want to use pure JAXB and not MOXY or any other such frame works... :( .
Partial code :
#XmlJavaTypeAdapter(RequestAdaptor.class)
#XmlRootElement(name="request")
public class AuthRequest extends Request
{
private AuthRequestDetails requestDetails;
public RequestDetails getRequestDetails()
{
return requestDetails;
}
#Override
public void setRequestDetails(RequestDetails requestDetails)
{
this.requestDetails = (AuthRequestDetails)requestDetails;
}
}
#XmlAccessorType(XmlAccessType.FIELD)
public class AuthRequestDetails extends RequestDetails
{
#XmlElement(name="user-name")
private String userName;
#XmlElement(name="password")
private String password;
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
#XmlAccessorType(XmlAccessType.FIELD)
#XmlJavaTypeAdapter(RequestAdaptor.class)
public abstract class Request
{
#XmlAttribute
protected String type;
#XmlElement(name="request-header")
protected RequestHeader requestHeader;
public RequestHeader getRequestHeader()
{
return requestHeader;
}
public void setRequestHeader(RequestHeader requestHeader)
{
this.requestHeader = requestHeader;
}
public String getType()
{
return type;
}
public void setType(String type)
{
this.type = type;
}
public abstract void setRequestDetails(RequestDetails requestDetails);
public abstract RequestDetails getRequestDetails();
}
public class RequestAdaptor extends XmlAdapter<RequestDTO, Request>
{
#Override
public RequestDTO marshal(Request v) throws Exception
{
System.out.println("marshal");
RequestDTO lRequestDTO= new RequestDTO();
lRequestDTO.setRequestHeader(v.getRequestHeader());
lRequestDTO.setType(v.getType());
if(v.getType().equals("5"))
{
AuthRequest lRequest = (AuthRequest)v;
}
else
{
PingRequest lRequest = (PingRequest)v;
}
return lRequestDTO;
}
#Override
public Request unmarshal(RequestDTO v) throws Exception
{
System.out.println("unmarshal");
if(v.getType().equals("5"))
{
AuthRequest lRequest = new AuthRequest();
lRequest.setRequestHeader(v.getRequestHeader());
lRequest.setType(v.getType());
return lRequest;
}
else
{
PingRequest lRequest = new PingRequest();
lRequest.setRequestHeader(v.getRequestHeader());
lRequest.setType(v.getType());
return lRequest;
}
}
}
#XmlAccessorType(XmlAccessType.FIELD)
public class RequestDTO
{
#XmlAttribute
protected String type;
#XmlElement(name="request-header")
private RequestHeader requestHeader;
#XmlElement(name="request-details")
private RequestDetails requestDetails;
public RequestHeader getRequestHeader()
{
return requestHeader;
}
public void setRequestHeader(RequestHeader requestHeader)
{
this.requestHeader = requestHeader;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public RequestDetails getRequestDetails() {
return requestDetails;
}
public void setRequestDetails(RequestDetails requestDetails) {
this.requestDetails = requestDetails;
}
}
#XmlAccessorType(XmlAccessType.FIELD)
public class RequestHeader
{
#XmlElement(name="name")
String Name;
public String getName() {
return Name;
}
public void setName(String name) {
Name = name;
}
}
First thing is : Marshal and Unmarshal of Adaptor is not getting called. I am stuck at this point.
You can use a StAX XmlStreamReader to parse the XML. Then advance it to the root element. When it's at the root element event check the value of the type attribute. Use this value to determine which Class you should pass to the unmarshal method that takes a Class and XmlStreamReader to get the result you are looking for.

Accessing secure restful web services using jersey client

I have created web services based on Jersey (auto generated via Netbeans).
I have also created a user names “testClient” with password “secret” and created User group “Users” and used file Realm using glassfish 3.0.1 admin console.
I have also mapped web.xml and sun-web.xml accordingly.
My web services are secured successfully; as I access the web site I receive a security warning and then I am prompt to give username and password to access any content of the website. It is working fine when accessed via web browser.
Now I have written a simple client based on jersey and tried to access the web services offered by the 1st project; the client code is here
Auto generated Jersey client code
public class JerseyClient {
private WebResource webResource;
private Client client;
private static final String BASE_URI = "https://localhost:9028/testsecurity2/resources";
public JerseyClient() {
com.sun.jersey.api.client.config.ClientConfig config = new com.sun.jersey.api.client.config.DefaultClientConfig(); // SSL configuration
// SSL configuration
config.getProperties().put(com.sun.jersey.client.urlconnection.HTTPSProperties.PROPERTY_HTTPS_PROPERTIES, new com.sun.jersey.client.urlconnection.HTTPSProperties(getHostnameVerifier(), getSSLContext()));
client = Client.create(config);
webResource = client.resource(BASE_URI).path("manufacturers");
}
public <T> T get_XML(Class<T> responseType) throws UniformInterfaceException {
return webResource.accept(javax.ws.rs.core.MediaType.APPLICATION_XML).get(responseType);
}
public <T> T get_JSON(Class<T> responseType) throws UniformInterfaceException {
return webResource.accept(javax.ws.rs.core.MediaType.APPLICATION_JSON).get(responseType);
}
public void close() {
client.destroy();
}
public void setUsernamePassword(String username, String password) {
client.addFilter(new com.sun.jersey.api.client.filter.HTTPBasicAuthFilter(username, password));
}
private HostnameVerifier getHostnameVerifier() {
return new HostnameVerifier() {
#Override
public boolean verify(String hostname, javax.net.ssl.SSLSession sslSession) {
return true;
}
};
}
private SSLContext getSSLContext() {
javax.net.ssl.TrustManager x509 = new javax.net.ssl.X509TrustManager() {
#Override
public void checkClientTrusted(java.security.cert.X509Certificate[] arg0, String arg1) throws java.security.cert.CertificateException {
return;
}
#Override
public void checkServerTrusted(java.security.cert.X509Certificate[] arg0, String arg1) throws java.security.cert.CertificateException {
return;
}
#Override
public java.security.cert.X509Certificate[] getAcceptedIssuers() {
return null;
}
};
SSLContext ctx = null;
try {
ctx = SSLContext.getInstance("SSL");
ctx.init(null, new javax.net.ssl.TrustManager[]{x509}, null);
} catch (java.security.GeneralSecurityException ex) {
}
return ctx;
}
}
Code in Main Method; uses auto generated code
JerseyClient client = new JerseyClient();
client.setUsernamePassword("testClient", "secret");
Object response = client.get_XML(String.class);
// do whatever with response
client.close();
Results:
Exception in thread "main" com.sun.jersey.api.client.ClientHandlerException: javax.net.ssl.SSLHandshakeException: Remote host closed connection during handshake
at com.sun.jersey.client.urlconnection.URLConnectionClientHandler.handle(URLConnectionClientHandler.java:128)
at com.sun.jersey.api.client.filter.HTTPBasicAuthFilter.handle(HTTPBasicAuthFilter.java:78)
at com.sun.jersey.api.client.Client.handle(Client.java:457)
at com.sun.jersey.api.client.WebResource.handle(WebResource.java:557)
at com.sun.jersey.api.client.WebResource.access$300(WebResource.java:69)
at com.sun.jersey.api.client.WebResource$Builder.get(WebResource.java:451)
at clients.JerseyClient.get_XML(JerseyClient.java:23)
at clients.NewMain1.main(NewMain1.java:20)
Caused by: javax.net.ssl.SSLHandshakeException: Remote host closed connection during handshake
at com.sun.net.ssl.internal.ssl.SSLSocketImpl.readRecord(SSLSocketImpl.java:808)
at com.sun.net.ssl.internal.ssl.SSLSocketImpl.performInitialHandshake(SSLSocketImpl.java:1112)
at com.sun.net.ssl.internal.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:1139)
at com.sun.net.ssl.internal.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:1123)
at sun.net.www.protocol.https.HttpsClient.afterConnect(HttpsClient.java:434)
at sun.net.www.protocol.https.AbstractDelegateHttpsURLConnection.connect(AbstractDelegateHttpsURLConnection.java:166)
at sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1049)
at java.net.HttpURLConnection.getResponseCode(HttpURLConnection.java:373)
at sun.net.www.protocol.https.HttpsURLConnectionImpl.getResponseCode(HttpsURLConnectionImpl.java:318)
at com.sun.jersey.client.urlconnection.URLConnectionClientHandler._invoke(URLConnectionClientHandler.java:215)
at com.sun.jersey.client.urlconnection.URLConnectionClientHandler.handle(URLConnectionClientHandler.java:126)
... 7 more
Caused by: java.io.EOFException: SSL peer shut down incorrectly
at com.sun.net.ssl.internal.ssl.InputRecord.read(InputRecord.java:333)
at com.sun.net.ssl.internal.ssl.SSLSocketImpl.readRecord(SSLSocketImpl.java:789)
... 17 more
Java Result: 1
I also want to inform that these are two different projects running on different servers both are glassfish 3.0.1. I also tried to run client and services on the same server but all in vain. I am stuck; kindly help me.
Cheers!
i have found a good resource regarding my problem. Here it is
http://wiki.open-esb.java.net/attach/RestBCEchoSSL/SslClient.java
I made few changes in my code regarding the given source and it worked perfectly. Actually I was not passing the certificate and key stores properly.
Here is the full code.
package clients;
import com.sun.jersey.api.client.*;
import javax.net.ssl.*;
import java.io.*;
import java.net.Socket;
import java.security.*;
import javax.ws.rs.core.UriBuilder;
import com.sun.jersey.client.urlconnection.HTTPSProperties;
public class JerseyClient {
private WebResource webResource;
private Client client;
//private static final String BASE_URI = "https://localhost:9028/testsecurity2/resources";
private static final String truststore_path = "D:/Practice Apps/glassfish-3.0.1 Stand Alone/glassfish/domains/domain2/config/cacerts.jks";
private static final String truststore_password = "changeit";
private static final String keystore_path = "D:/Practice Apps/glassfish-3.0.1 Stand Alone/glassfish/domains/domain2/config/keystore.jks";
private static final String keystore_password = "changeit";
private static final String url = "https://localhost:9029/testsecurity2/resources/manufacturers/";
public JerseyClient() {
com.sun.jersey.api.client.config.ClientConfig config = new com.sun.jersey.api.client.config.DefaultClientConfig(); // SSL configuration
// SSL configuration
config.getProperties().put(com.sun.jersey.client.urlconnection.HTTPSProperties.PROPERTY_HTTPS_PROPERTIES, new com.sun.jersey.client.urlconnection.HTTPSProperties(getHostnameVerifier(), getSSLContext()));
client = Client.create(config);
webResource = client.resource(url);
}
public <T> T get_XML(Class<T> responseType) throws UniformInterfaceException {
return webResource.accept(javax.ws.rs.core.MediaType.APPLICATION_XML).get(responseType);
}
public <T> T get_JSON(Class<T> responseType) throws UniformInterfaceException {
return webResource.accept(javax.ws.rs.core.MediaType.APPLICATION_JSON).get(responseType);
}
public void close() {
client.destroy();
}
public void setUsernamePassword(String username, String password) {
client.addFilter(new com.sun.jersey.api.client.filter.HTTPBasicAuthFilter(username, password));
}
private HostnameVerifier getHostnameVerifier() {
return new HostnameVerifier() {
#Override
public boolean verify(String hostname, javax.net.ssl.SSLSession sslSession) {
return true;
}
};
}
private SSLContext getSSLContext() {
TrustManager mytm[] = null;
KeyManager mykm[] = null;
try {
mytm = new TrustManager[]{new MyX509TrustManager(truststore_path, truststore_password.toCharArray())};
mykm = new KeyManager[]{new MyX509KeyManager(keystore_path, keystore_password.toCharArray())};
} catch (Exception ex) {
ex.printStackTrace();
}
SSLContext ctx = null;
try {
ctx = SSLContext.getInstance("SSL");
ctx.init(mykm, mytm, null);
} catch (java.security.GeneralSecurityException ex) {
}
return ctx;
}
/**
* Taken from http://java.sun.com/javase/6/docs/technotes/guides/security/jsse/JSSERefGuide.html
*
*/
static class MyX509TrustManager implements X509TrustManager {
/*
* The default PKIX X509TrustManager9. We'll delegate
* decisions to it, and fall back to the logic in this class if the
* default X509TrustManager doesn't trust it.
*/
X509TrustManager pkixTrustManager;
MyX509TrustManager(String trustStore, char[] password) throws Exception {
this(new File(trustStore), password);
}
MyX509TrustManager(File trustStore, char[] password) throws Exception {
// create a "default" JSSE X509TrustManager.
KeyStore ks = KeyStore.getInstance("JKS");
ks.load(new FileInputStream(trustStore), password);
TrustManagerFactory tmf = TrustManagerFactory.getInstance("PKIX");
tmf.init(ks);
TrustManager tms[] = tmf.getTrustManagers();
/*
* Iterate over the returned trustmanagers, look
* for an instance of X509TrustManager. If found,
* use that as our "default" trust manager.
*/
for (int i = 0; i < tms.length; i++) {
if (tms[i] instanceof X509TrustManager) {
pkixTrustManager = (X509TrustManager) tms[i];
return;
}
}
/*
* Find some other way to initialize, or else we have to fail the
* constructor.
*/
throw new Exception("Couldn't initialize");
}
/*
* Delegate to the default trust manager.
*/
public void checkClientTrusted(X509Certificate[] chain, String authType)
throws CertificateException {
try {
pkixTrustManager.checkClientTrusted(chain, authType);
} catch (CertificateException excep) {
// do any special handling here, or rethrow exception.
}
}
/*
* Delegate to the default trust manager.
*/
public void checkServerTrusted(X509Certificate[] chain, String authType)
throws CertificateException {
try {
pkixTrustManager.checkServerTrusted(chain, authType);
} catch (CertificateException excep) {
/*
* Possibly pop up a dialog box asking whether to trust the
* cert chain.
*/
}
}
/*
* Merely pass this through.
*/
public X509Certificate[] getAcceptedIssuers() {
return pkixTrustManager.getAcceptedIssuers();
}
}
/**
* Inspired from http://java.sun.com/javase/6/docs/technotes/guides/security/jsse/JSSERefGuide.html
*
*/
static class MyX509KeyManager implements X509KeyManager {
/*
* The default PKIX X509KeyManager. We'll delegate
* decisions to it, and fall back to the logic in this class if the
* default X509KeyManager doesn't trust it.
*/
X509KeyManager pkixKeyManager;
MyX509KeyManager(String keyStore, char[] password) throws Exception {
this(new File(keyStore), password);
}
MyX509KeyManager(File keyStore, char[] password) throws Exception {
// create a "default" JSSE X509KeyManager.
KeyStore ks = KeyStore.getInstance("JKS");
ks.load(new FileInputStream(keyStore), password);
KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509", "SunJSSE");
kmf.init(ks, password);
KeyManager kms[] = kmf.getKeyManagers();
/*
* Iterate over the returned keymanagers, look
* for an instance of X509KeyManager. If found,
* use that as our "default" key manager.
*/
for (int i = 0; i < kms.length; i++) {
if (kms[i] instanceof X509KeyManager) {
pkixKeyManager = (X509KeyManager) kms[i];
return;
}
}
/*
* Find some other way to initialize, or else we have to fail the
* constructor.
*/
throw new Exception("Couldn't initialize");
}
public PrivateKey getPrivateKey(String arg0) {
return pkixKeyManager.getPrivateKey(arg0);
}
public X509Certificate[] getCertificateChain(String arg0) {
return pkixKeyManager.getCertificateChain(arg0);
}
public String[] getClientAliases(String arg0, Principal[] arg1) {
return pkixKeyManager.getClientAliases(arg0, arg1);
}
public String chooseClientAlias(String[] arg0, Principal[] arg1, Socket arg2) {
return pkixKeyManager.chooseClientAlias(arg0, arg1, arg2);
}
public String[] getServerAliases(String arg0, Principal[] arg1) {
return pkixKeyManager.getServerAliases(arg0, arg1);
}
public String chooseServerAlias(String arg0, Principal[] arg1, Socket arg2) {
return pkixKeyManager.chooseServerAlias(arg0, arg1, arg2);
}
}
}
and code to run the client in main class
public static void main(String[] args) {
JerseyClient client = new JerseyClient();
client.setUsernamePassword("testClient", "secret");
Object response = client.get_XML(String.class);
System.out.println(response);
// do whatever with response
client.close();
}

Resources