Tuesday, 30 August 2016

Jersey webservice client to access WS via proxy

I have already written a jersey client program to access the Restful WS for one of the projects. Recently, the company has upgraded the securities and so the internet can be accessed only via proxy. After this change, the program stopped working. It was not able to make a connection because of the change in internet connection.

I have modified the program to access the WS via proxy.

ConnectionFactory:

This class defines the proxy and the port to be used and then the same will be used in the client program.


package com.ppc.rest.client;

import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.InetSocketAddress;
import java.net.Proxy;
import java.net.URL;

import com.sun.jersey.client.urlconnection.HttpURLConnectionFactory;

public class ConnectionFactory implements HttpURLConnectionFactory {
 Proxy proxy;

 private void initializeProxy() {
  proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress("haproxy.cfa.vic.gov.au", 3128));
 }

 @Override
 public HttpURLConnection getHttpURLConnection(URL url) throws IOException {
  initializeProxy();
  return (HttpURLConnection) url.openConnection(proxy);
 }

}

ClientLogicWebservice:


package com.ppc.rest.client;

import com.cfa.ppcese.model.LogicTransctions;
import com.cfa.ppcese.util.CFAProperties;
import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.config.ClientConfig;
import com.sun.jersey.api.client.config.DefaultClientConfig;
import com.sun.jersey.api.client.filter.HTTPDigestAuthFilter;
import com.sun.jersey.api.json.JSONConfiguration;
import com.sun.jersey.client.urlconnection.URLConnectionClientHandler;

public class ClientLogicWebservice {

 public static void main(String[] args) {
  // TODO Auto-generated method stub
  // LogicWebServiceJob.getLogicData();
  getLogicData();
 }

 public static void getLogicData() {
  // LOG.debug("Calling the Webservice data load method");
  URLConnectionClientHandler ch = new URLConnectionClientHandler(new ConnectionFactory());

  ClientConfig clientConfig = new DefaultClientConfig();
  String url = CFAProperties.getProp("logic.rest.url");

  clientConfig.getFeatures().put(JSONConfiguration.FEATURE_POJO_MAPPING, Boolean.TRUE);
  // clientConfig.
  Client client = new Client(ch, clientConfig);
  // Client client = Client.create(clientConfig);
  client.addFilter(new HTTPDigestAuthFilter(CFAProperties.getProp("logic.rest.username"), CFAProperties.getProp("logic.rest.password")));

  try {
   url = url + "1025";

   ClientResponse resp = client.resource(url).accept("application/json").type("application/json").get(ClientResponse.class);
   System.out.println(resp.toString());

   LogicTransctions logic = resp.getEntity(LogicTransctions.class);
   if (resp.getStatus() == 200) {
    if (logic.getCount() == 0 && logic.getError().getMessage() == null) {
     System.out.println("There is no data available for this call and the URL is - " + url);
    } else {
     System.out.println("Insert Logic data");
    }
   }

  } catch (Exception e) {

  }
 }
}

Required Libraries:

  • jersey-client-1.19.1.jar
  • jersey-json-1.19.1.jar
  • jersey-server-1.19.1.jar
  • jackson-core-asl-1.19.13.jar
  • jsr311-api-1.1.1.jar


Thursday, 9 June 2016

how to add the local project to a new repository in github

In many cases, I create the project locally, develop it. And then I realize that it would be great if its available it Github. This is more of like, bottom-up approach.

Following is the list of steps to achieve this.

  1. Create the remote repository, and get the URL such as git@github.com:/youruser/somename.git or https://github.com/youruser/somename.git
    If your local GIT repo is already set up, skips steps 2 and 3

  2. Locally, at the root directory of your source, git init
    2a. If you initialize the repo with a .gitignore and a README.md you should do a git pull {url from step 1} to ensure you don't commit files to source that you want to ignore ;)
  3. Locally, add and commit what you want in your initial repo (for everything, git add . then git commit -m 'initial commit comment')

  4. to attach your remote repo with the name 'origin' (like cloning would do)
    git remote add origin [URL From Step 1]
  5. to push up your master branch (change master to something else for a different branch):
    git push origin master
  6. Execute git pull origin master to pull the remote branch so that they are in sync.

Wednesday, 8 June 2016

Generate Service Endpoint for SOAP webservices using Apache CXF

This blog is to explain on how to generate the Web service client interfaces for the SOAP web service using Apache CXF.

1) Generate the WSDL file out of SoapUI tool or through any web browser by giving the WSDL URL. Save the generated the file as PurchaseOrder.wsdl

2) Download the CXF2.7.11 from the apache website into the local drive. Then, refer that path in to Eclipse->Windows->Preferences->Webservices->CXF. Please refer the screenshot below.




3) Create a Dynamic web project named WS-SEI with default values.

4) Add the CXF library files from the downloaded one to the above project, so that wsdl2java program of CXF will run without any issues.
5) Move the wsdl file (PurchaseOrder.wsdl) into the Webcontent of the above project
6) Select the above project->File->New->Other->Web Service Client.
7) Select the WSDL file from the project for which you want to create the web service client files.
Change the Web Service Runtime to Apache CXF 2.x (Default value is Apache Axis)



8) Click Next and then select the source directory of the project where you want to create the client files.
9) Enter the Package name to bundle the client files (in this case, com.cfa.webservice.client.purchaseorder)
10) Select the check box “Specify WSDL Namespace to Package Name Mappings”
11) Select the check boxes that are selected in the attached screen below and then click Next


The new window will open. Just click Finish to generate the client files.


This will generate the list of Java classes with the sample date to invoke the web service. The program can be executed as a Core Java application or can be integrated with the web application to invoke the SOAP web service.

Monday, 6 June 2016

Different functionalities on Dropdown or Select box

I have listed down all the possible combinations of using Dropdown box using jQuery.

Pre-Select:

The dropdown is filled with the values and when the form is loaded, a particular value needs to be highlighted (The value may come from database or the default value).

$("#myList option[value='"+ MY_VALUE+"']").prop('selected',true);

----------------------------------------------------------------------------------------------------------------------

Create List:

Sometimes, there are cases where the list need to be created at run time. Following is the piece of code to create the list.

var options = '<option value="' + "ALL" + '">'
                  + "ALL" + '</option>';
         $.each(myList, function( index, value) {
      options += '<option value="' + value+ '">'
                      + value+ '</option>';
      });
     
        $("select#finalList").html(options);

----------------------------------------------------------------------------------------------------------------------

Default to First Item:

$('#myList').get(0).selectedIndex = 0;

----------------------------------------------------------------------------------------------------------------------

Enable/Disable or grey out the fields using jQuery

Even after working on many applications, I tend to google for disabling some of the fields in the application using jQuery. Following is the list of components and the way to disable/enable or grey out the fields.

Input Box:

$("#title").attr('readonly', true); -- To Disable
$("#title").attr('readonly', false); -- To Enable

Check Box:

$("#title").attr('disable', true); -- To Disable
$("#title").attr('disable', false); -- To Enable

Select or Dropdown Box:

$('select#myList').attr('disabled', true); - To Disable
$('select#myList').attr('disabled', false); - To Enable

Span:

$("#mySpan").css("pointer-events", "none"); - To Disable
$("#mySpan").css("pointer-events", "auto"); - To Enable

Button:

$("#myButton").prop('disabled','disabled'); - To Disable
$("#myButton").prop('disabled',''); - To Enable

Wednesday, 25 May 2016

How to reset the sequence number of a table in Sql Server

The sequence numbers are used as primary keys in most of the table. Main purpose of this is to generate a unique sequential number. During the development, we would face many situations where we need to reset or reseed the sequence number. The syntax varies in different Database software like DB2, Oracle, Sql Server, MySQL and so on.

We are going to see how to reset this.

use 'Database Name'
dbcc checkident('Schema.Table',RESEED,0);

The above command will reset it to 0. The sequence will start from 1.

Monday, 16 May 2016

Implement Basic Authentication in RESTful web service using web.xml

Hi,

I had been searching for the materials that teach me to implement the different authentications in RESTful web services. I could not find any handful of materials. I am going to write a blog on all types of implementations of different Authentications in RESTful services.

Here, I am going to explain the RESTful web services implementing the Basic Authentication using web.xml (old way of doing this). The user and role details are available in the Tomcat servers.

tomcat-users.xml
<role rolename="member" />
<role rolename="admin"></role>

<user username="anand" password="anand" roles="member"></user>
<user username="kumar" password="kumar" roles="admin"></user>

web.xml

<!DOCTYPE web-app PUBLIC
 "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
 "http://java.sun.com/dtd/web-app_2_3.dtd" >

<web-app>

 <!-- <context-param> <param-name>contextConfigLocation</param-name> <param-value>WEB-INF/beans.xml</param-value> 
  </context-param> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> 
  </listener> -->

 <!-- JERSEY -->
 <servlet>
  <servlet-name>jersey-serlvet</servlet-name>
  <servlet-class>com.sun.jersey.spi.container.servlet.ServletContainer</servlet-class>
  <init-param>
   <param-name>com.sun.jersey.config.property.packages</param-name>
   <param-value>com.anand.restfuljersey.rest</param-value>
  </init-param>
  <init-param>
   <param-name>com.sun.jersey.api.json.POJOMappingFeature</param-name>
   <param-value>true</param-value>
  </init-param>
  <!-- <init-param> <param-name>com.sun.jersey.spi.container.ResourceFilters</param-name> 
   <param-value>com.sun.jersey.api.container.filter.RolesAllowedResourceFilterFactory</param-value> 
   </init-param> -->
  <load-on-startup>1</load-on-startup>
 </servlet>

 <servlet-mapping>
  <servlet-name>jersey-serlvet</servlet-name>
  <url-pattern>/rest/*</url-pattern>
 </servlet-mapping>
 <security-constraint>
  <web-resource-collection>
   <web-resource-name>Test</web-resource-name>
   <description>Test</description>
   <url-pattern>/rest/*</url-pattern>
   <http-method>GET</http-method>
  </web-resource-collection>
  <auth-constraint>
   <role-name>member</role-name>
  </auth-constraint>
 </security-constraint>
 <login-config>
  <auth-method>BASIC</auth-method>
 </login-config>
</web-app>

JerseyService.java

/**
 * 
 */
package com.anand.restfuljersey.rest;

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 com.anand.restfuljersey.vo.Track;

/**
 * @author Anand
 *
 */
@Path("/json/metallica")
public class JerseyService {

 @GET
 @Path("/get")
 @Produces(MediaType.APPLICATION_JSON)
// @RolesAllowed("Admin")
 public Track getTrackInJSON()
 {
  Track track = new Track();
  track.setTitle("Anand");
  track.setSinger("Metallica");

  return track;
 }

 @POST
 @Path("/post")
 @Consumes(MediaType.APPLICATION_JSON)
 public Response createTrackInJSON(Track track)
 {
  String result = "Track saved :" + track;
  return Response.status(201).entity(result).build();
 }
}

When the service is hit in the browser or in the any REST client app like postman, the credentials should be entered to access the resource
the URL - http://localhost:8080/RestfulWSJerseyServices/rest/json/metallica/get
Credentials should match with the ones in tomcat-users.xml file. In this case, user name is anand and password is anand