Monday, October 6, 2014

Create web service project(Implementation as server)



1. First need to create dynamic web project  [You can finish the project after  get bellow screen] also Add the Axis2 facet. Right-click your project and click Properties > Project Facets > Modify project > Axis2 Web Services

 


2. Then, We need to create wsdl file for sample scenario[say sample wsdl file name MyFirst.wsdl file]

 



3. Right click on MyFirst.wsdl to create stub, Need to add web server runtime (Jboss/tomcat..etc) and web service runtime(Axis2) .
 

Select Finish.
Generated Skelton class is used for to future modification [to add custom logic for custom methods in wsdl] for released API (It can be survived as Server).
It Will be deployed in attached server[In this case server is  Tomcat]..


 

Tuesday, September 17, 2013

How to load URL Connection to Client machine using Java servlet

This example explains how to load web result to client browser.Web result mean output of some third party application(Ex:image, bill, any URL..etc).

Implementation steps;
First Create URL object and create HttpURLConnection by using above object.openConnection();Then create BufferedInputStream by passing InputStream to constructer of BufferedInputStream.Finally writes this buffered input stream data to output stream of the servlet.

package com.srccodes.example;
import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;



public class OldBillClient extends HttpServlet {
    private static final long serialVersionUID = 1L;


    public OldBillClient() {
        super();
    }

    /**
     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
     *      response)
     */
    protected void doGet(HttpServletRequest request,
            HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
        //System.out.println("Done");
    }

    HttpURLConnection conn;

    /**
     * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
     *      response)
     */
    protected void doPost(HttpServletRequest request,
            HttpServletResponse response) throws ServletException, IOException {
       
        doDL();//Create URL connection for download and show
       
        BufferedInputStream in = new BufferedInputStream(conn.getInputStream());//Used created connection
        OutputStream sos = response.getOutputStream();
        try {
            int i = 0;
            while ((i = in.read()) != -1) {
                sos.write(i);//Writes data to out put stream
                //System.out.write(i);
            }
            in.close();
            sos.flush();
        } finally {
            if (in != null)
                in.close();
            if (sos != null) {
                sos.flush();
                sos.close();
            }
        }
    }
   
    /**
     * set URL connection
     */
    private void doDL() {
        try {
            URL obj = new URL("https://www.google.lk/#q=Test");//Ex : http://170.26.29.180/com/test/?para_1=value_1&para_2=value_2
            conn = (HttpURLConnection) obj.openConnection();
            conn.setReadTimeout(5000);
        } catch (java.io.IOException ioE) {
            ioE.getMessage();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}

Wednesday, September 11, 2013

Java - Generate PDF file using local machine's .txt file

Following sample explain how to create pdf file using iText.jar(used iText 5.0.4 for following sample)

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.util.Date;

import com.itextpdf.text.Document;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.pdf.PdfWriter;

public class GeneratePDF {

    public static void main(String[] args) {
        try {
            OutputStream file = new FileOutputStream(new File("D:\\Test.pdf"));

            Document document = new Document();
            PdfWriter.getInstance(document, file);

            document.open();
            document.setMargins(50, 50, 50, 50);
            document.add(new Paragraph("Page 1"));
            document.add(new Paragraph(new Date().toString()));

            document.newPage();// new Page
            document.add(new Paragraph("Page 2"));

            document.newPage();// new Page
            document.add(new Paragraph("Page 3 : Added external text file"));

            // read file from location and add to same PDF
            File fileIn = new File("D:\\sampleTextFileInYourMachine.txt");
            FileInputStream fi = new FileInputStream(fileIn);

            String text = getFileContent(fi);
            document.add(new Paragraph(text));
            document.close();
            file.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static String getFileContent(FileInputStream fis) {
        try {
            BufferedReader br = new BufferedReader(new InputStreamReader(fis));
            StringBuilder sb = new StringBuilder();
            String line;
            while ((line = br.readLine()) != null) {
                sb.append(line);
                sb.append('\n');
            }
            return sb.toString();
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return null;
    }

}

Tuesday, July 16, 2013

Create a Web Service Client using Axis2 - Command Prompt(CMD)

Use following URL to download Apache Axis2
http://axis.apache.org/axis2/java/core/download.cgi
Steps :
1.UnZip the downloaded Axis2 (Ex:Unzipped to drive C)
2.Set Axis home as a system or user variable(AXIS2_HOME, C:\DOWNLOADED_AXIS2)
3.Run following command using CMD
%AXIS2_HOME%\bin\WSDL2Java -uri D:\Path_For_WSDL\test.wsdl
Ex:
C:\GenerateStubs>%AXIS2_HOME%\bin\WSDL2Java -uri D:\Path_For_WSDL\test.wsdl

Web service client will generate in GenerateStubs folder

ref :
http://axis.apache.org/axis2/java/core/tools/CodegenToolReference.html

To generate stub class separately
%AXIS2_HOME%\bin\WSDL2Java -uri D:\wsdl\CMUEnterprise.wsdl -p org.apache.axis2.axis2userguide -ss -g

To generate Stub class separately  with services.xml
%AXIS2_HOME%\bin\WSDL2Java -uri D:\wsdl\TestDialogService.wsdl -p org.apache.axis2.axis2userguide -ss -g -sd

Wednesday, June 26, 2013

How to create web service client using wsdl file(IDE : Eclipse)

To create client stub for wsdl file use following steps.
1.File --> New --> Java project
2.Create web service client(Right click on the above project --> File --> New --> Other --> Web Service Client)
3.Then enter the directory path as follows and press next and finish

file:///C:\Documents and Settings\suresh_inova\Desktop\TestWS_nip\CustomECAwsdl0.0.29\wsdl\CUSTOMECA\CUSTOMECA.wsdl

You can check the created stub for provided wsdl file

Tuesday, June 4, 2013

How to run jar file from command prompt

First go to directory where the jar file is present and execute the following command
java -jar YourSample.jar

If you got following error add MANIFEST.MF file and following entry

Error:Failed to load Main-Class manifest attribute from

Answer : (Enter as Main-Class:package.MainClassName)
manifest-Version: 1.0
Main-Class: com.java.TestSuresh
Ref from: http://stackoverflow.com/questions/2848642/how-to-setup-main-class-in-manifest-file-in-jar-produced-by-netbeans-project

Java Create URL connection

Following is the sample for creating the URL connection when proxy is present

 Test Class

package com.java;
import java.io.InputStream;
import java.io.OutputStreamWriter;
import java.net.Authenticator;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;

//import org.apache.commons.codec.binary.Base64;

public class RClient {

      public static void main(String[] args) {
          Map proxyData = new HashMap();
          proxyData.put("pHost", "proxy.site.com");
          proxyData.put("pPort", "8080");
          proxyData.put("pUser", "USERNAME");
          proxyData.put("pPwd", "PWD");

          Map mailData = new HashMap();
          mailData.put("pQuery", "variable1=G&variable2=7120189&variable3=B");
          mailData.put("pUrl", "http://IP/sample/");

          String a = new RClient().sendPostRequest(proxyData, mailData);
      }

      /**
       * @param args :
       */
      public String sendPostRequest(Map proxyData, Map mailData) {
            String data = mailData.get("pQuery");

            try {
                  Authenticator.setDefault(new ProxyAuthenticator(proxyData.get("pUser"), proxyData.get("pPwd")));
                  System.setProperty("http.proxyHost", proxyData.get("pHost"));
                  System.setProperty("http.proxyPort", proxyData.get("pPort"));
                 
                  URL url = new URL(mailData.get("pUrl"));
                  HttpURLConnection con = (HttpURLConnection) url.openConnection();
                  con.setRequestMethod("POST");
                  con.setDoOutput(true);
                  con.setDoInput(true);

                  OutputStreamWriter writer = new OutputStreamWriter(con.getOutputStream());
                 
                  //write parameters
                  writer.write(data);
                  writer.flush();

                  if (con.getResponseCode() == HttpURLConnection.HTTP_OK) {//response code is 200
                        return "OK";
                  } else {
                      return "ERROR: "+ con.getResponseCode();
                  }

            } catch (Exception e) {
                  return "ERROR: "+ e.getMessage();
            }
      }
     
}


================================================
Proxy authenticator class     
     
package com.java;
import java.net.Authenticator;
import java.net.PasswordAuthentication;

class ProxyAuthenticator extends Authenticator {

    private String user, password;

    public ProxyAuthenticator(String user, String password) {
        this.user = user;
        this.password = password;
    }

    protected PasswordAuthentication getPasswordAuthentication() {
        return new PasswordAuthentication(user, password.toCharArray());
    }
}


This site providing you to JAVA Language easy way. I think if you are beginner to JAVA refer this to implements you knowledge using only with very simplest codes.