Tuesday, 21 May 2013

No Name Matching localhost found Error : Tomcat and CAS configuration

javax.net.ssl.SSLHandshakeException: java.security.cert.CertificateException: No name matching localhost found
This error occurs when we try to connect to https enabled web service using standalone java program for localhost configuration.
This Post provides the solution by adding javax.net.ssl.HostnameVerifier in the java program.
But , sometimes we can not change the code because of third party code restriction . For example , setting up and configuring CAS. CAS also uses http client to connect to the CAS server war application deployed on server.
To overcome this problem , we can import the certificate for localhost in our java environment by following these simple steps :
First of all , create a keystore by using keytool present in your $JDK_HOME/bin directory.
keytool -genkey -alias tomcat -keystore ./keystore -keyalg RSA

Enter keystore password:
Re-enter new password:
What is your first and last name?
  [Unknown]:  localhost
What is the name of your organizational unit?
  [Unknown]:  localhost
What is the name of your organization?
  [Unknown]:  localhost
What is the name of your City or Locality?
  [Unknown]:  localhost
What is the name of your State or Province?
  [Unknown]:  localhost
What is the two-letter country code for this unit?
  [Unknown]:  in
Is CN=localhost, OU=localhost, O=localhost, L=localhost, ST=localhost, C=in correct?
  [no]:  yes


make sure you enter localhost for first name and last name .
Now copy the generated key to tomcat home directory and configure the tomcat to enable SSL like this :
<Connector port="8443" protocol="HTTP/1.1" SSLEnabled="true"
 maxThreads="150" scheme="https" secure="true" keystoreFile="keystore" keystorePass="changeit"
               clientAuth="false" sslProtocol="TLS" />

Now restart tomcat and you should be able to access https on https://localhost:8443 Now export the certificate of this localhost:8443 to disk using your browser.(In mozilla you will find option to export in certificate viewer tab )
Now use the keytool in your jdk to import this certificate in your jvm certificates.
keytool -importcert -alias tomcat -file ${PATH_WHERE_CERT_IS_EXPORTED} -keystore $JDK_HOME\jre\lib\security\cacerts

That's it . Now you can run your standalone java program without modifying it.
Post your comments and Suggestions !!!


Post JSON request Using JQuery 1.9 And AJAX

Create a json string from user inputs in html form and post it using ajax :
To create a json string from user inputs , first create a javascript map object and put name value pairs in the map , then use Json 2to create a json string from this json object .To post the request , use $.ajax function of jquery . If you want to block the screen while ajax response comes from the server , you can use Block UI in the beforeSend function.Here is the code

var jsonMap = new Object();
     
     jsonMap['maps'] = map;
     jsonMap['input1'] = $("#formInput1").val();
     jsonMap['input2']="input2";
     
         
     var datastring = JSON.stringify(jsonMap,null);
      
     var request=$.ajax({
        type: 'POST',
        url: "rest/executerequest#!",
        data: datastring,
        contentType: 'application/json; charset=utf-8',
        dataType:'json',
        beforeSend:function(xhr){
         $.blockUI({ message: '<h1><img src="images/loader.gif" /> Just a moment...</h1>' });
        
        }
        });

 request.done(function(msg) {
  alert('success');
      }
       );

Post Comments !!

Thursday, 9 May 2013

Create Json Rest Service in RestEasy

Creating rest web services with rest easy is very simple , you can read more about this in this post. Now if you want to add json support in rest you have to add following dependency in your pom.xml
<dependency>
       <groupId>org.jboss.resteasy</groupId>
       <artifactId>resteasy-jackson-provider</artifactId>
       <version>2.3.2.Final</version>
    </dependency>
And this is the Rest class
@Path("/test")
 @POST
 @Consumes(MediaType.APPLICATION_JSON)
 @Produces(MediaType.APPLICATION_JSON)
 public Response getResult(Input in) {
  Output out = new Output();
  out.setMessage("success");
  return Response.status(Status.OK).entity(out).build();
 }

Where Input.java and Output.java will be beans which will be converted in to/from json by jackson. If you forget to add dependency you might get error like this in tomcat :
EVERE: Failed executing POST /test
org.jboss.resteasy.spi.BadRequestException: Could not find message body reader for type: class com.onlinehttpclient.bean.Input of content type: application/json;charset="utf-8"
 at org.jboss.resteasy.core.MessageBodyParameterInjector.inject(MessageBodyParameterInjector.java:153)
 at org.jboss.resteasy.core.MethodInjectorImpl.injectArguments(MethodInjectorImpl.java:124)
 at org.jboss.resteasy.core.MethodInjectorImpl.invoke(MethodInjectorImpl.java:147)
 at org.jboss.resteasy.core.ResourceMethod.invokeOnTarget(ResourceMethod.java:257)
 at org.jboss.resteasy.core.ResourceMethod.invoke(ResourceMethod.java:222)
 at org.jboss.resteasy.core.ResourceMethod.invoke(ResourceMethod.java:211)
 at org.jboss.resteasy.core.SynchronousDispatcher.getResponse(SynchronousDispatcher.java:525)
 at org.jboss.resteasy.core.SynchronousDispatcher.invoke(SynchronousDispatcher.java:502)
 at org.jboss.resteasy.core.SynchronousDispatcher.invoke(SynchronousDispatcher.java:119)
 at org.jboss.resteasy.plugins.server.servlet.ServletContainerDispatcher.service(ServletContainerDispatcher.java:208)
 at org.jboss.resteasy.plugins.server.servlet.HttpServletDispatcher.service(HttpServletDispatcher.java:55)
 at org.jboss.resteasy.plugins.server.servlet.HttpServletDispatcher.service(HttpServletDispatcher.java:50)
 at javax.servlet.http.HttpServlet.service(HttpServlet.java:722)
 at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:305)
 at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
 at com.onlinehttpclient.filter.CrawlServlet.doFilter(CrawlServlet.java:105)
 at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:243)
 at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
 at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:225)
 at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:123)
 at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:472)
 at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:168)
 at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:98)
 at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:927)
 at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
 at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:407)
 at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1001)
 at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:579)
 at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:312)
 at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
 at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
 at java.lang.Thread.run(Thread.java:722)



Post your comments !!

Friday, 3 May 2013

Create File Upload Functionalty using Jersey in Mule

Creating Rest services in Mule is very easy as Jersey is shipped with mule runtime[Read more]. Now , if you want to create a Multipart Rest service using Mule , you have to add following dependencies in your mule Runtime. Make sure the versions of jersey-multipart.jar , mimepull.jar matches with the existing jersey version in mule runtime. For example , Mule Server 3.3.1 CE comes with Jersey version 1.6 , so i have downloaded jersey-multipart 1.6.
<dependency>
   <groupId>com.sun.jersey.contribs</groupId>
   <artifactId>jersey-multipart</artifactId>
   <version>1.6</version>
  </dependency>

<groupId>org.jvnet</groupId>
  <artifactId>mimepull</artifactId>
  <version>1.6</version>

This is the Rest Jersey Component :
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import javax.servlet.http.HttpServletRequest;
import javax.ws.rs.Consumes;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;

import com.sun.jersey.core.header.FormDataContentDisposition;
import com.sun.jersey.multipart.FormDataParam;

@Path("/application")
public class FileUploadService {

 
 @POST
 @Path("/upload")
 @Consumes(MediaType.MULTIPART_FORM_DATA)
 public Response uploadFile(
  @FormDataParam("file") InputStream uploadedInputStream,
  @FormDataParam("file") FormDataContentDisposition fileDetail) {
 
  String uploadedFileLocation = "D://" + fileDetail.getFileName();
 
  // save it
  writeToFile(uploadedInputStream, uploadedFileLocation);
 
  String output = "File uploaded to : " + uploadedFileLocation;
 
  return Response.status(200).entity(output).build();
 }
 
 // save uploaded file to new location
 private void writeToFile(InputStream uploadedInputStream,
  String uploadedFileLocation) {
  OutputStream out=null;
  File f = new File(uploadedFileLocation);
  try {
   
   out = new FileOutputStream(f);
   int read = 0;
   byte[] bytes = new byte[1024];
 
   out = new FileOutputStream(new File(uploadedFileLocation));
   while ((read = uploadedInputStream.read(bytes)) != -1) {
    out.write(bytes, 0, read);
   }
   out.flush();
  } catch (IOException e) {
 
   e.printStackTrace();
  }
  finally{
   if(out !=null)
    try {
     uploadedInputStream.close();
     out.close();
    } catch (IOException e) {
     // TODO Auto-generated catch block
     e.printStackTrace();
    }
  }
 
 }

 
}


This is the mule xml configuration :
<?xml version="1.0" encoding="UTF-8"?>

<mule xmlns:jetty="http://www.mulesoft.org/schema/mule/jetty" xmlns:jersey="http://www.mulesoft.org/schema/mule/jersey"
 xmlns:http="http://www.mulesoft.org/schema/mule/http"
 xmlns="http://www.mulesoft.org/schema/mule/core" xmlns:doc="http://www.mulesoft.org/schema/mule/documentation" xmlns:spring="http://www.springframework.org/schema/beans" version="EE-3.3.2" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="
http://www.mulesoft.org/schema/mule/http http://www.mulesoft.org/schema/mule/http/current/mule-http.xsd 
http://www.mulesoft.org/schema/mule/jersey http://www.mulesoft.org/schema/mule/jersey/current/mule-jersey.xsd 
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-current.xsd 
http://www.mulesoft.org/schema/mule/core http://www.mulesoft.org/schema/mule/core/current/mule.xsd 
http://www.mulesoft.org/schema/mule/jetty http://www.mulesoft.org/schema/mule/jetty/current/mule-jetty.xsd ">

<flow name="fileUploadExampleFlow1" doc:name="fileUploadExampleFlow1">
        <http:inbound-endpoint exchange-pattern="request-response" host="localhost" port="8082" doc:name="HTTP"/>
        <jersey:resources doc:name="REST">
            <component class="FileUploadService"/>
        </jersey:resources>
    </flow>


</mule>

And this is the test class to test Multipart Rest service using Jersey client :
import java.io.File;
import java.io.FileInputStream;

import javax.ws.rs.core.MediaType;

import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.WebResource;
import com.sun.jersey.core.header.FormDataContentDisposition;
import com.sun.jersey.multipart.FormDataBodyPart;
import com.sun.jersey.multipart.FormDataMultiPart;
import com.sun.jersey.multipart.file.FileDataBodyPart;

public class TestFileUploadService {

 public static void main(String[] args) {

  try {

   Client client = Client.create();

   WebResource webResource = client
     .resource("http://localhost:8082/application/upload");

   File f = new File("D://soft//depp.JPG");
   FileDataBodyPart fdp = new FileDataBodyPart("file", f,
     MediaType.APPLICATION_OCTET_STREAM_TYPE);

   FormDataMultiPart formDataMultiPart = new FormDataMultiPart();

   formDataMultiPart.bodyPart(fdp);

   String reString = webResource.type(MediaType.MULTIPART_FORM_DATA)
     .accept(MediaType.TEXT_HTML)
     .post(String.class, formDataMultiPart);
   System.out.println(reString);

   System.out.println("Output from Server .... \n");

  } catch (Exception e) {

   e.printStackTrace();

  }

 }

}

If you forgot to include jersey-mutipart.jar or mimepull.jar , you may get error warnings like this on server side :
SEVERE: A message body reader for Java class com.sun.jersey.multipart.FormDataMultiPart, and Java type class com.sun.jersey.multipart.FormDataMultiPart, and MIME media type multipart/form-data; boundary=Boundary_1_1409104443_1367490786430 was not found
May 02, 2013 4:03:06 PM com.sun.jersey.spi.container.ContainerRequest getEntity
SEVERE: The registered message body readers compatible with the MIME media type are:
*/* ->
  com.sun.jersey.core.impl.provider.entity.FormProvider
  com.sun.jersey.core.impl.provider.entity.MimeMultipartProvider
  com.sun.jersey.core.impl.provider.entity.StringProvider
  com.sun.jersey.core.impl.provider.entity.ByteArrayProvider
  com.sun.jersey.core.impl.provider.entity.FileProvider
  com.sun.jersey.core.impl.provider.entity.InputStreamProvider
  com.sun.jersey.core.impl.provider.entity.DataSourceProvider
  com.sun.jersey.core.impl.provider.entity.XMLJAXBElementProvider$General
  com.sun.jersey.core.impl.provider.entity.ReaderProvider
  com.sun.jersey.core.impl.provider.entity.DocumentProvider
  com.sun.jersey.core.impl.provider.entity.SourceProvider$StreamSourceReader
  com.sun.jersey.core.impl.provider.entity.SourceProvider$SAXSourceReader
  com.sun.jersey.core.impl.provider.entity.SourceProvider$DOMSourceReader
  com.sun.jersey.json.impl.provider.entity.JSONJAXBElementProvider$General
  com.sun.jersey.core.impl.provider.entity.XMLRootElementProvider$General
  com.sun.jersey.core.impl.provider.entity.XMLListElementProvider$General
  com.sun.jersey.core.impl.provider.entity.XMLRootObjectProvider$General
  com.sun.jersey.core.impl.provider.entity.EntityHolderReader
  com.sun.jersey.json.impl.provider.entity.JSONRootElementProvider$General
  com.sun.jersey.json.impl.provider.entity.JSONListElementProvider$General
  com.sun.jersey.json.impl.provider.entity.JacksonProviderProxy
And at the client side you may get 415 status code :
com.sun.jersey.api.client.UniformInterfaceException: POST http://localhost:8082/application/upload returned a response status of 415


Post Comments And Suggestions !!

Wednesday, 1 May 2013

Creating Rest Services With Rest Easy In Web application

RestEasy is implementation of JAX-RS API created by JBoss. This post is about how to create and expose rest services in your existing web application. First of all , add the dependency in your pom.xml for RestEasy.If you are not using jboss[jboss AS 7.1 is shipped with rest easy] as your application server , remove Scope tag from this.
                 <dependency>
			<groupId>org.jboss.resteasy</groupId>
			<artifactId>resteasy-jaxrs</artifactId>
			<version>2.3.2.Final</version>
			<scope>provided</scope> 
		</dependency>
Now create a root rest service. By default it returns Empty set of classes in getClasses method which means whole web Application will be scanned to find jax rs annotations.
package rest;

import java.util.Set;

import javax.ws.rs.core.Application;

public class RootRestService extends Application{
	
	public Set> getClasses()
	{
		return super.getClasses();
	}

}
This is our sample Rest Class .
package rest;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.Status;



@Path("/application")
public class RestService {

	HttpClient cl = new HttpClient();
	@Path("/test")
	@GET
	@Produces(MediaType.TEXT_PLAIN)
	public Response test() {
		return Response.status(Status.OK).entity("working").build();
	}
}



Now in your web.xml , you have to define a servlet to dispatch your request to rest service. Provide url pattern for the dispatcher. in our case it is /rest/* , accordingly you have to define the prefix in context parameter . So if the url pattern is /rest/* then prefix will also be /rest.If you map the dispatcher to /* pattern , then you will not be able to access other resources in your web app like html ,css,jsp ,servlets etc . because every request will go through the rest easy dispatcher and you will get 404 error .So ,it's better to have a separate prefix for rest services in web app.
<context-param>
		<param-name>resteasy.servlet.mapping.prefix</param-name>
		<param-value>/rest</param-value>
	</context-param>
	
	
	
	<context-param>
		<param-name>resteasy.resources</param-name>
		<param-value>rest.RestService</param-value>
	</context-param> 
 
	<servlet>
		<servlet-name>resteasy-servlet</servlet-name>
		<servlet-class>
			org.jboss.resteasy.plugins.server.servlet.HttpServletDispatcher
         </servlet-class>
		<init-param>
			<param-name>javax.ws.rs.Application</param-name>
			<param-value>rest.RootRestService</param-value>
		</init-param>
	</servlet>
You may get error like this : Could not find resource for relative : /application/test of full path: http://localhost:8080/onlinehttpclient/rest/application/test
To resolve this error , you have to define resteasy.resource context param with the full path of Rest class.
Post Comments And Suggestions !!

Wednesday, 17 April 2013

Create Collapsible Content Using Jquery UI

We can create collapsible content quite easily by using Jquery UI Accordion plugin First download and add jquery ui support in your page .
Here is the code to create sample collapsible content .First the html code :
<div id="content">
</div>
<input type="button" value='Submit' id='submit'></input>
Now write below code in your script tag which uses jquery ui to make and display collapsible content. When user clicks on submit button, this method will be called which will add content to the content div. Whatever you add in h1 tag will become the title of collapsible content and the content will be written in p tag.You can customize the appearance of your collapsible content. For example , if you don't want to show any content , unless user clicks on it , then set active variable as false in accordion method.Similarly , the heightStyle option create content which will have auto scroll functionality. You can read all the methods and options Here.
$(document).ready(function(){
     $("#submit").click(function () {
              
$( "#content").html('<h1>Content Title</h1><p>Collapsible Content which will be shown once user clicks on the Content Title</p>');
 $( "#content" ).accordion({
                collapsible: true,
                active:false}
           );
         
         
     });
});
Now when you run this , if you click on the button first time , it works fine. you see a button with Content Title and collapsible content , but when you click the button second time , it is not working .The reason behind this behavior is jquery do not clean up objects it created. So we have to clear contents and also clean up collapsible functionality. For this , we need to use destroy functionality provided in accordion . Here's the code :
$(document).ready(function(){
     $("#submit").click(function () {
     var resVar = $( "#content").find('h1');
     if(resVar.length == 1 )
     {
         alert('destroying');
         $( "#content" ).accordion("destroy");
         $( "#content" ).empty();
     }
         
$( "#content").html('<h1>Res Header</h1><p>sdsdd</p>');
 $( "#content" ).accordion({
                collapsible: true,
                active:false}
           );
         
         
     });
});
Now it works fine. So if you are using ajax call or using jquery to fill in the details in accordion components , make sure to clean up every time . You can see the running output Here

Post Comments and Suggestions !!

Friday, 5 April 2013

Creating Rest Service Using Mule ESB 3.3

Creating Rest Services with Mule is very easy as mule provides built in support for Jersey.

Create mule flow in mule studio like this .


create a Rest class like this and link it to rest component :
import javax.ws.rs.Path;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.Status;


@Path("restClass")
public class RestClass {

 public Response getExample(@QueryParam("param1")String param1)
 {
  return Response.status(Status.OK).entity("hello " + param1).build();
 }
 
}
This is how the Mule flow xml will look like :
<?xml version="1.0" encoding="UTF-8"?>

<mule xmlns:jersey="http://www.mulesoft.org/schema/mule/jersey" 
xmlns:http="http://www.mulesoft.org/schema/mule/http" 
xmlns="http://www.mulesoft.org/schema/mule/core"
xmlns:doc="http://www.mulesoft.org/schema/mule/documentation" 
xmlns:spring="http://www.springframework.org/schema/beans" version="CE-3.3.1" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="
http://www.mulesoft.org/schema/mule/http http://www.mulesoft.org/schema/mule/http/current/mule-http.xsd 
http://www.mulesoft.org/schema/mule/jersey http://www.mulesoft.org/schema/mule/jersey/current/mule-jersey.xsd 
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-current.xsd 
http://www.mulesoft.org/schema/mule/core http://www.mulesoft.org/schema/mule/core/current/mule.xsd ">
    <flow name="restTestFlow1" doc:name="restTestFlow1">
        <http:inbound-endpoint exchange-pattern="request-response" 
host="localhost" port="8081" doc:name="HTTP"/>
        <jersey:resources doc:name="REST">
            <component class="RestClass"/>
         </jersey:resources>
    </flow>
</mule>
If you want to use spring created bean in the rest Component , then first declare the component as spring bean , and then refer it in the jersey-resource using spring-object tag , like this :
<flow name="restTestFlow1" doc:name="restTestFlow1">

     <http:inbound-endpoint exchange-pattern="request-response" host="localhost"
 port="8081" doc:name="HTTP"/>
       <spring:bean id="testBean" class="TestSpringBean"></spring:bean>
    <spring:bean id="restClass">
      <spring:property name="bean" ref="testBean"></spring:property>
    </spring:bean>

        <jersey:resources doc:name="REST">
            <component doc:name="rest component">
             <spring-object bean="restClass">
            </component>
        </jersey:resources>
</flow>
You can use multiple rest classes also , like this :
<jersey:resources doc:name="REST">
   <component>
    <spring-object bean="restService" />
   </component>
   <component>
    <spring-object bean="restService1" />
   </component>
  </jersey:resources>
Mule Studio throws error "Required attribute class is not defined in component" , you can ignore this error, as it runs perfectly fine.

Post your suggestions !!