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());
    }
}


Wednesday, May 22, 2013

Oracle IN OUT cursor with java

Following sample fully developed using
http://www.idevelopment.info/data/Programming/java/jdbc/PLSQL_and_JDBC/RefCursorExample.java
link

How to work with IN/OUT cursor with java
Connection Class
import java.sql.DriverManager;
import java.sql.Connection;
import java.sql.SQLException;

/**
 *
 * @author suresh_inova
 */
public class ConnectionDB {
    final static String driverClass    = "oracle.jdbc.driver.OracleDriver";
    Connection   con                   = null;


    /**
     * Construct a RefCursorExample object. This constructor will create an Oracle
     * database connection.
     */
    public ConnectionDB(String connectionURL, String userID, String userPassword) {

        try {

            System.out.print("  Loading JDBC Driver  -> " + driverClass + "\n");
            Class.forName(driverClass).newInstance();

            System.out.print("  Connecting to        -> " + connectionURL + "\n");
            this.con = DriverManager.getConnection(connectionURL, userID, userPassword);
            System.out.print("  Connected as         -> " + userID + "\n\n");

        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        }

    }
   
    public Connection getConnection() {//TODO have to use singlenton
       return con;
    }
}

Ref Cursor sample with Oracle imports

import java.sql.Connection;
import oracle.jdbc.OracleCallableStatement;
import oracle.jdbc.OracleResultSet;
import oracle.jdbc.OracleTypes;
import test.ConnectionDB;

/**
 *
 * @author suresh_inova
 */
public class RefCursorRBM {

    ConnectionDB conDb = null;
    Connection con = null;

    public RefCursorRBM() {
        ConnectionDB conDb = new ConnectionDB("jdbc:oracle:thin:@172.26.30.89:1521:TEST", "userName", "pwd");
        con = conDb.getConnection();
    }

    public void performRefCursor() {

        OracleCallableStatement oraCallStmt = null;
        OracleResultSet deptResultSet = null;

        try {
            oraCallStmt = (OracleCallableStatement) con.prepareCall("{call RBM_CUSTOM.DBT_GETCOLLECTIONS.GETMONCOLL(?,?,?,?,?)}");
            oraCallStmt.registerOutParameter(1, OracleTypes.CURSOR);
            oraCallStmt.registerOutParameter(1, OracleTypes.CURSOR);
            oraCallStmt.setString(2, "20130501");
            oraCallStmt.setString(3, "20130601");
            oraCallStmt.setString(4, "HEAD");
            oraCallStmt.setString(5, "GSM");
            oraCallStmt.execute();

            deptResultSet = (OracleResultSet) oraCallStmt.getCursor(1);

            while (deptResultSet.next()) {
                System.out.println(
                        " - " + deptResultSet.getString(1) + " - "
                        + deptResultSet.getString(2) + " - "
                        + deptResultSet.getString(3) + " - ");
            }

            oraCallStmt.close();
            closeConnection();

        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    /**
     * Close down Oracle connection.
     */
    public void closeConnection() {

        try {
            System.out.print("  Closing Connection...\n");
            con.close();

        } catch (Exception e) {

            e.printStackTrace();

        }

    }
}

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.