Thursday 17 November 2016

Gradle Signing Jar File

Problem:
How to sign jar file in gradle , same like jarsigner command line tool ?

Solution:
 we can make use of AntBuilder of Gradle (which is inherited from AntBuilder <- Groovy).
Gradle supports all ant tasks in build file with ease.

You can add task extension to jar task like this.

  jar.doLast {
         new File('build/sign').mkdirs();
         ant.signjar(
         destDir: 'build/sign',
         jar: 'build/libs/*.jar',
         alias:"anyAlias",
         storetype:"jks",
         keystore:"keystore.jks",
         storepass:"keystore_password",
         preservelastmodified:"true")
  }


Now if run below command u will see singed jar file in build/sign directory, but you have to create keystore before running gradle command and copy to root project directory.

>gradle clean jar


Friday 7 October 2016

Apache Camel - https Rest

Problem:

Hi Guys I have assigned an task on adding https for Rest in Apache Camel. I spent more time on this to get ti working , finally achieved. I thought of sharing with community  for easy to go.

Solution:


  1. We need to add SSL Context Parameters
  2. Add "CamelContextId" to SSLContextParameters Section.
  3. Add "Id" to SSLContextParameters which it later can be linked to where ever we need in the Camel Context defined.

   

 <sslcontextparameters camelcontextid="RestLab" id="sslContext_rest" xmlns="http://camel.apache.org/schema/spring">
  <keymanagers keypassword="keypassword">
   <keystore password="keystorePassword" resource="yourKeystore.jks">
   </keystore>
  </keymanagers>
  <serverparameters clientauthentication="WANT">
   <clientparameters>
    <ciphersuitesfilter>
     <include>.* </include>
    </ciphersuitesfilter>
   </clientparameters>
  </serverparameters>
 </sslcontextparameters>

 <camelcontext id="RestLab">
  <restconfiguration bindingmode="auto" component="restlet" enablecors="true" port="8080" scheme="https">

   <endpointproperty key="sslContextParameters" value="#sslContext_rest">
    <corsheaders key="Access-Control-Allow-Origin" value="*">
     <corsheaders key="Access-Control-Allow-Headers" value="Origin, Accept, X-Requested-With,
                                Content-Type, Access-Control-Request-Method, Access-Control-Request-Headers">
      <corsheaders key="Access-Control-Allow-Methods" value="PUT,POST,GET,DELETE,OPTIONS">
      </corsheaders>
     </corsheaders>
    </corsheaders>
   </endpointproperty>
  </restconfiguration>
 </camelcontext>
 



XML Assistance in Eclipse - Apache Camel or for Any XSD

Problem:
I have a problem with xml assistance while writing camel routes and tried all the ways I didn't able to get it .


Solution:
In order to get assistance from eclipse using "ctrl+space" , you have to add namespace prefix for expected namespace . Then Eclipse will give you xml assistance.

Error:
<?xml version="1.0" encoding="UTF-8"?>
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:util="http://www.springframework.org/schema/util"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd

<camel:sslContextParameters camelContextId="" id="">
<camel:cipherSuites ></camel:cipherSuites>
</camel:sslContextParameters>
<!-- No XMl Assistance here  ->


</beans>



Solved:

<?xml version="1.0" encoding="UTF-8"?>
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:camel="http://camel.apache.org/schema/spring"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:util="http://www.springframework.org/schema/util"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd

<camel:sslContextParameters camelContextId="" id="">
<camel:cipherSuites ></camel:cipherSuites>
</camel:sslContextParameters>

<!--  XML Assistance working here -->

</beans>


Wednesday 24 August 2016

Apache Camel - https4 Component SSL Trust Store issue

Problem:
 javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: No trusted certificate found

in apache camel https4 component


Solution:

Please add this truststore logic for verifying certificates from root ca by java itself.


 try {
   
    SSLContext sslContext = SSLContext.getInstance("TLS");
       SSLConnectionSocketFactory sslConnectionSocketFactory = new SSLConnectionSocketFactory(sslContext,
               new String[]{"TLSv1.2", "TLSv1.1", "TLSv1", "SSLv3"}, null, SSLConnectionSocketFactory.getDefaultHostnameVerifier());
       final org.apache.http.config.Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory>create()
               .register("http", PlainConnectionSocketFactory.getSocketFactory())
               .register("https", sslConnectionSocketFactory)
               .build();
     
   
     
        HttpComponent http4 = camelContext.getComponent("https4", HttpComponent.class);
       
        http4.setHttpClientConfigurer(
        new HttpClientConfigurer() {

            @Override
            public void configureHttpClient(HttpClientBuilder builder) {

                builder.setSSLSocketFactory(sslConnectionSocketFactory);

                HttpClientConnectionManager ccm = new  BasicHttpClientConnectionManager(registry);

                builder.setConnectionManager(ccm);
            }
        });
    }catch (Exception e) {
        e.printStackTrace();
    }

Tuesday 12 July 2016

Loading jars from Lib folder for standalone Jar execution


Loading Jars While Booting of application from separate external folder 

I have faced an issue with dynamic jars loading to start the service without giving any classpath in MANIFEST file inside jar file.

I have spent lot much time on this to get on to the solution, but no luck. I found some info on stackoverflow pertaining to this. I wanna share that with you today with slight modifications make use as simple jar file.

Here is the simple class I wrote and also created a simple jar file for direct usage.

Here is the Reference for source code url.

You can also download direct jar file from above URL under "dist"  directory.


Sample Class::


package com.rnd.java.bootup;

import java.io.File;
import java.lang.reflect.Method;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.List;

import org.apache.commons.io.FileUtils;

public class Bootup 
{
 public void run(String[] args) throws Exception 
 {
  
  List jars  =  (List) FileUtils.listFiles(new File(args[1]), null, true);
  URL urls[] =  FileUtils.toURLs(jars.toArray(new File[jars.size()]));
  
  for (int i = 0; i < urls.length; i++) 
  {
   loadMe(urls[i]);
   System.out.println(urls[i]);
  }
  
  Object[] arguments = new Object[]{args};
  Class classToLoad = Class.forName(args[0]);
  Method method = classToLoad.getMethod("main",String[].class);
  Object result = method.invoke (null,arguments);
  System.out.println(result);
 }
 
 
 private void loadMe(URL url) {
  try {
      
      URLClassLoader classLoader = (URLClassLoader)ClassLoader.getSystemClassLoader();
      Method method = URLClassLoader.class.getDeclaredMethod("addURL", URL.class);
      method.setAccessible(true);
      method.invoke(classLoader, url);
  } catch (Exception ex) {
      ex.printStackTrace();
  }

 }
 
 
 /**
  * How to use ?
  * java -jar bootup.jar com.company.application.mainclass lib main 
  * 
  * 
  * @param args
  */
 public static void main(String[] args) 
 {
  if(args.length==0)
  {
   StringBuilder help = new StringBuilder();
   help.append("Usage !!! \n java -jar bootup.jar fullyQualifiedClassName libFolderName method2Call ");
   System.out.println(help.toString());
   throw new IllegalArgumentException("Wrong number of arguments!!!!");
  }else if(args.length==1)
  {
   args = new String[]{args[0],"lib","main"};
  }else if(args.length==2)
  {
   args = new String[]{args[0],args[1],"main"};
  }
  try{
   new Bootup().run(args);
  
  }catch(Exception e)
  {
   e.printStackTrace();
  }
 }

}



Tuesday 5 July 2016

Mocking Http Server in Java for Integration Testing

If you want to create a mock Http server for integration testing to mock external URLS/Servers. Here is the solution for java.

I have gone through the all options like WireMock, nanoHttpd,Mock-Server,LightWeightServer…etc but not full fill my requirements and not easy to use for my use case.

I created my own solution for this problem and of course inspired from other blogs to get into this .

First use  Dependencies:

testCompile group: 'org.mortbay.jetty', name: 'jetty', version: '7.0.0.pre5'
compile 'commons-io:commons-io:2.5'

Mortbay Jetty will do simple and nice job here.

If you’re working with webserver clients you will certainly have noticed the difficulty in integration-testing your webserver clients. Building webserver clients can already be quite a complex task, but providing a mock-up webservice backend delivering useful test responses is quite often just to much work, if not impossible, since many web server backends are very complex constructs. Furthermore, setting up a backend for each integration test consumes valuable build time.
As an alternative, one may simply replace the backend with a mock HTTP server that does one thing: deliver the expected webserver response – i.e. XML data – when called by the client. All you need to set this up is a HTTP server and a pre-recorded service response (quite often this comes with WS client specifications). If you don’t have this data, you can record it, for example using a proxy server in between your WS client and a real WS backend, or a tool such as wireshark.

The recorded XML response thus represents your assumptions against which you test the client. This makes your tests fast, lightweight and a lot better to understand.

Server Code Here

package com.java.testing.httpclient;

import static javax.servlet.http.HttpServletResponse.SC_OK;
import static org.apache.commons.io.IOUtils.write;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.io.IOUtils;
import org.apache.http.entity.ContentType;
import org.junit.Ignore;
import org.mortbay.jetty.Handler;
import org.mortbay.jetty.HttpConnection;
import org.mortbay.jetty.Request;
import org.mortbay.jetty.Server;
import org.mortbay.jetty.handler.AbstractHandler;

import com.touchpeak.restclient.util.NullUtil;

/**
 * Used for Mocking Http Server
 * 
 * @author Kumar
 *
 */
@Ignore
public class MockHttpTestServer {

 private int HTTP_PORT = 55556;
 private Server _server;
 private String _responseBody;
 private String _requestBody;
 private String _mockResponseData;
 private Integer _mockResponseStatus;
 private String _mockResponseContentType;
 private String _requestPath;
 private String _requestMethod;
 private Map requestedQueryParams = new HashMap<>();

 public MockHttpTestServer() {
 }

 public MockHttpTestServer(int port) {
  HTTP_PORT = port;
 }

 public MockHttpTestServer(String mockData) {
  setMockResponseData(mockData);
 }

 public void start() throws Exception {
  configureServer();
  startServer();
 }

 private void startServer() throws Exception {
  _server.start();
 }

 protected void configureServer() {
  _server = new Server(HTTP_PORT);
  _server.setHandler(getMockHandler());
 }

 /**
  * Creates an {@link AbstractHandler handler} returning an arbitrary String
  * as a response.
  * 
  * @return never null.
  */
 public Handler getMockHandler() {
  Handler handler = new AbstractHandler() {

   public void handle(String target, HttpServletRequest request,
     HttpServletResponse response, int dispatch)
     throws IOException, ServletException {

    cleanInMemory();
    Request baseRequest = request instanceof Request ? (Request) request
      : HttpConnection.getCurrentConnection().getRequest();
    setRequestMethod(baseRequest.getMethod());
    setRequestPath(baseRequest.getUri().getPath());
    setResponseBody(getMockResponseData());
    setRequestBody(IOUtils.toString(baseRequest.getInputStream(),
      "UTF-8"));
    response.setStatus(getMockResponseStatus());
    response.setContentType(getMockResponseContentType() != null ? getMockResponseContentType()
      : "text/plain");
    write(getResponseBody(), response.getOutputStream(), "UTF-8");
    baseRequest.setHandled(true);
   }
  };
  return handler;
 }

 protected void cleanInMemory() {

  setRequestBody("");
  setRequestPath("");

 }

 public void stop() throws Exception {
  _server.stop();
 }

 public void setResponseBody(String responseBody) {
  _responseBody = responseBody;
 }

 public String getResponseBody() {
  return _responseBody;
 }

 public void setRequestBody(String requestBody) {
  _requestBody = requestBody;
 }

 public String getRequestBody() {
  return _requestBody;
 }

 public static void main(String[] args) {
  MockHttpTestServer server = new MockHttpTestServer();
  try {
   server.start();
  } catch (Exception e) {
   throw new RuntimeException(e);
  }
 }

 public void setMockResponseData(String mockResponseData) {
  _mockResponseData = mockResponseData;
 }

 public String getMockResponseData() {
  return _mockResponseData;
 }

 protected Server getServer() {
  return _server;
 }

 public Map getRequestedQueryParams() {
  return requestedQueryParams;
 }

 public String getRequestPath() {
  return _requestPath;
 }

 public String getMockResponseContentType() {
  return _mockResponseContentType;
 }

 public void setMockResponseContentType(String _mockResponseContentType) {
  this._mockResponseContentType = _mockResponseContentType;
 }

 public Integer getMockResponseStatus() {
  return NullUtil.isNullOrEmpty(_mockResponseStatus) ? SC_OK
    : _mockResponseStatus;
 }

 public void setMockResponseStatus(Integer _mockResponseStatus) {
  this._mockResponseStatus = _mockResponseStatus;
 }

 public void setRequestPath(String _requestPath) {
  this._requestPath = _requestPath;
 }

 public String getRequestMethod() {
  return _requestMethod;
 }

 public void setRequestMethod(String _requestMethod) {
  this._requestMethod = _requestMethod;
 }
}

Client Code Here
package com.java.testing.httpclient;

import static org.junit.Assert.assertEquals;

import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.touchpeak.restclient.test.MockHttpTestServer;

public class HttpClientTests {

 
 private static final Logger logger = LoggerFactory
   .getLogger(HttpClientTests.class);
 
 private MockHttpTestServer server;

 private String HOST = "127.0.0.1";
 private int PORT =56342;
 private String TEST_BASE_URI = "http://"+HOST+":"+PORT;
 
 @Before
 public  void init() 
 {
  server = new MockHttpTestServer(PORT);
  try {
   server.start();
  } catch (Exception e) {
   logger.error(" While starting Mock Http Server ",e);
  }
 }
 
 
 @After
 public void close() 
 {
  try {
   server.stop();
  } catch (Exception e) {
   logger.error(" While stopping Mock Http Server ",e);
  }
 }

 
 @Test
 public void test_Server_Call() 
 {
  String mockResponse = "Mock Response you expect from server";
  String mockRequestBody ="RequestBody Sent to server from client"; 
  server.setMockResponseData(mockResponse);
  
  //Server will return above expected responses to client call.
  String actualResponse = " write client code here to call server and get the response from server call";
  
  assertEquals("GET", server.getRequestMethod());//Check HTTP METHOD here
  assertEquals("/order/3?area=LONDON", server.getRequestPath());// Check Request URI
  assertEquals(mockRequestBody, server.getRequestBody());//Check RequestBody received by Server
  assertEquals(mockResponse, actualResponse);//check Response from server
  
  
 }

}
Tips: 1. you can also add Listeners to Server class to get control back on client side while executing.

Wednesday 29 June 2016

JAX-RPC vs JAX-WS vs JAX-RS


However practical use case difference and when to use what. Both, JAX-WS and JAX-RS have standard implementations. I have come up with the following differences:

RESTful services (Mostly web integration, mobile phone apps)

Integration over web will be easy with the REST. Popularly used with the AJAX calls.
Not verbose as SOAP services so need less bandwidth hence good to use for the mobile apps.
Web services are completely stateless so only for stateless services.
JAX-WS and JAX-RPC are SOAP based services. (Enterprise web services)

JAX-WS Java EE later versions support this and standards still evolving. - SOAP based services not preferred for mobile app communication because of heavy payload compare to rest. - More suitable for the enterprise web services where you need interoperability, transactions, message delivery and reliability.


JAX-RPC forget about this one. It is the old obsolete standard for Java Web Services

JAX-WS new standard for SOAP-Based web services (also is provided as a reference implementation)

JAX-RS stack for REST-full web services


JAX-WS uses asynchronous features from Java 5.0,J2EE5.0 JAX-RPC is primarily uses features from J2EE 1.4 and is supported in J2EE 5.0 also.

JAX-RPC has its own data mapping model,it covers many and those are not covered are mapped to javax.xml.soap.SOAPElement.

JAX-WS's data mapping model is JAXB that promises mappings for all XML schemas, which has got many advantages like one can use with XSD and using annotations without XSD, it is highly useful with large, complex XML and few limitations also.

There are some differences according Webservice specifications as the specifications has got changed and improved after JAX-RPC and hence Jax-WS got some more features.

One thing is common is both are confusing while using them with J2EE 5.0, JavaEE 6.x. The better is Jax-RS or Jersey for new implementations and re-designs. or You can continue with JAX-RPC or JAX-WS.

JavaEE7.0 promises new light weight, developer and tester friendly approaches for RESTful webservices.

Java Architecture for XML Binding (JAXB) is an XML-to-Java binding technology that simplifies the development of web services by enabling transformations between schema and Java objects and between XML instance documents and Java object instances



The fundamental problem with RPC is coupling. RPC clients become tightly coupled to service implementation in several ways and it becomes very hard to change service implementation without breaking clients:


  • Clients are required to know procedure names;
  • Procedure parameters order, types and count matters. It's not that easy to change procedure signatures(number of arguments, order of arguments, argument types etc...) on server side without breaking client implementations;
  • RPC style doesn't expose anything but procedure endpoints + procedure arguments. It's impossible for client to determine what can be done next.
  • etc...

On the other hand in REST style it's very easy to guide clients by including control information in representations(HTTP headers + representation). For example:

  • It's possible (and actually mandatory) to embed links annotated with link relation types which convey meanings of these URIs;
  • Client implementations do not need to depend on particular procedure names and arguments. Instead, clients depend on message formats. This creates possibility to use already implemented libraries for particular media formats (e.g. Atom, HTML, Collection+JSON, HAL etc...)
  • It's possible to easily change URIs without breaking clients as far as they only depend on registered (or domain specific) link relations;
  • It's possible to embed form-like structures in representations, giving clients the possibility to expose these descriptions as UI capabilities if the end user is human;
  • Support for caching is additional advantage;
  • Standardised status codes;
  • etc...
  • There are many more differences and advantages on the REST side.
REST is often compared with RPC, but the truth is they are not comparable entities. In the most common meaning REST is a concrete architectural style bound to the HTTP protocol, whereas RPC is a generic abstract protocol whose only contract is to perform remote method invocations.

All Collected from different blogs...Aggregated here...

Refer:
http://maxivak.com/rest-vs-xml-rpc-vs-soap/

Tuesday 14 June 2016

Update Ivy xml generated in Ivy publication in Gradle




How to update Version in Ivy xml generated in Gradle ?


Solution:

In Gradle it uses  groovy scripting API.
So think like groovy guy .
To update this Ivy XML::
  1. Go to  Interface IvyPublication
  2. Go to Method > IvyPublication>descriptor
  3. Where descriptor takes IvyModuleDescriptorSpec
  4. Go to above interface, u will find wihXML which returns XMLProvider
  5. XMLProvider has asNode() method which returns Root node.

Usage :
publishing {
publications {
       
Ivy(IvyPublication) {
organisation "$project.group"
                                module "$project.name"
                                revision "$project.version"
from components.java
descriptor.withXml {
asNode().info[0].appendNode("description", project.name)
asNode().dependencies.dependency.findAll{ it.@org.startsWith("com.group")}.each{ it.@rev = "$project.version" }
               }
             }
    }
    repositories {
       mavenLocal()

    }
}

Thursday 2 June 2016

Eclipse Static imports


There are two preferences that work together to enable this feature. The first one just needs verification:
  1. Go to Window > Preferences > Java > Editor > Content Assist.
  2. Make sure the option Use static imports (only 1.5 or higher) is enabled (it should be enabled by default, but it’s good to verify this anyway).
Here’s an example of how it should look:


Next you have to tell Eclipse which classes you’d like to add as static imports. Here’s how to do this:
  1. Go to Window > Preferences > Java > Editor > Content Assist > Favorites.
  2. Click New Type. This brings up a dialog where you can enter the fully qualified type.
  3. Enter org.junit.Assert and click Ok (you could also use the Browse… if you want to search for the type). Eclipse will add an entry to the list which reads org.junit.Assert.*.
  4. Click Ok on the preferences dialog to save and close the preferences.
Here’s what my list currently looks like:


You can add an entry for any other static import you’d like, even for a static Utils class you’ve written yourself.
Now, to test that it works you can add a JUnit test, type assertEquals, press Ctrl+Space and press Enter on the appropriate entry. Eclipse will now add the static import org.junit.Assert.assertEquals (or org.junit.Assert.*, depending on your Organize Imports preferences).
As I mentioned before, this only works for autocomplete and not for organise imports commands (eg. Ctrl+Shift+O), but it is already a lot better than having to enter the import yourself and should do the job most of the time.