Showing posts with label Java. Show all posts
Showing posts with label Java. Show all posts

June 28, 2016

How to invoke HTTP methods like PUT,PATCH and DELETE using HttpURLConnection

     I am invoking REST web services using HttpURLConnection. Few of the rest services have operations like PUT, PATCH, and DELETE. While passing these methods in setRequestMethod() of HttpURLConnection object, I am getting the below error in response. Invalid HTTP method: PATCH

     To avoid this error and to let the HttpURLConnection execute these methods, there is a workaround which is to override the http method we are invoking. And the procedure to do it is,
  • Invoke any accepted http method like GET or POST
  • Pass the new method value to the header parameter "X-HTTP-Method-Override" to Override the method 
Below is the example: 
            URL url = new URL(mcsPatchAPIURL);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestProperty("Accept", "application/json");
            conn.setRequestProperty("Content-Type", "application/json; charset=utf-8");
            conn.setRequestProperty("X-HTTP-Method-Override", "PATCH");

To get an idea about these methods:

GET: To get the details of a resource
PUT: To update the existing resource
POST: To create a new resource
PATCH: To update the existing resource partially
DELETE: To delete the existing resource

July 16, 2015


WriteFiles is a java tool to integrate several textual files to a single file. In some scenarios like where we need to copy all source code  or text files into a document or a text file. It is difficult to copy the content of all the files manually. For example, if you take java application where there will be several source files under different packages, it starts from a root directory (package), includes sub directories and their sub directories and so on. Each directory or sub  directory may have their individual java classes. If you want to copy all these source files including the files in the sub folders, think how difficult it is to do so. WriteFiles tool can help you to do the same.

Below is the GUI screenshot of the tool.

Click here to download the tool and also the source code of the tool can be downloaded from here.

June 24, 2015

Word Type Count

"Word Type Count" is a tool developed in Java, useful to count number of occurrences of each word in the given String. It also counts the total number of words in the given string. The tool would look like as below. 
Download the java program from here.

For example, in the above screen, we could see the input string "This is to count number of occurrences of each word in a given String". When the button "Count Words" is pressed, it will display the result in the output text box as shown in the screen in which we could see each word of the given input string and count of their occurrences. And also we could see at the end of the result, the total count (shown with the word "Size") of words in the input string. 

June 19, 2015

Java program to create Zip files

In this post, I wanted to show how to create a zip file using a java program.
In this example, input to the program is test.html and out put would be which contains the given test.html.

The same program can be downloaded from here.

June 15, 2015

FAQ Creator

"FAQ Creator" is a tool developed in java helps to create FAQ (Frequently Asked Questions) html files. This tool provides an user interface as below  and the procedure to add this tool is:

  • Provide a file name including path to which the content will be written.
  • Enter a question and its answer in the corresponding text fields.
  • Click on "Save&Next" to save the question and answer to the buffer. And the same will be added to the list box in the left side of the GUI. 
  • If you want to edit the question or answer, select the question from the list box. The question and the answer will be displayed in the corresponding text boxes, so that they can be modified, or click on the "Delete" button to delete the same question from the list or buffer.  
  • Once all the questions and answers are entered in the tool, click on the button "Done". It will write the content from the tool to the file with the given name. 

Below is the sample output of the tool.

Click here to download the tool. And source code of this tool also can be downloaded from here.

June 5, 2015

Tool to import data from Excel To Database


                 ExcelToDB is a tool developed in java to import data from MS-Excel to different data bases like MS-Access or Oracle. Currently this tool supports only these two database, but you can extend it to other databases if you required.

Click here to download the tool. You can also get the source code of this tool here and you are free to edit the code as per your need.

  • Double click on the executable jar file ExcelToDB.jar or run the java command “jar –d ExcelToDB.jar” to open the tool

  • Choose the source excel file (.xls or .xlsx) from which the data to be copied
  • Enter the sheet name of the excel file where the data is existed (Default value is Sheet1)
  • Select the data base type either MS-Access or Oracle 
  • If Access is selected, the window will be as follows
  • Choose the target MS-Access database file
  • And also pass the table name, user name and password of the database
  • If the databse type is selected as Oracle then the window will be changed as below
  • Pass the host name of the oracle server, table name to which the data to be copied, user name and password of the database to the tool
  • Click on “Click the button to import” to start the process of importing data from excel to the database

June 4, 2015

Box Game

BoxGame is a  number game developed in java, which opens a window with 16 cells filled with numbers from 1 to 15 and a blank cell filled with green color. All these numbers including blank cell are arranged randomly across the window. Use the arrow keys to play the game. When you press any arrow key, the blank cell will move accordingly.

For example, if you press left arrow key, the blank cell will move left, if you press up arrow key, the blank cell will move up. When the blank cell is moved, it will swap its position with the corresponding cell. By this process, you have to arrange the numbers from 1 to 15 in an ascending order, ignoring the blank cell, which means blank cell can be in the first position or at the last position.

Click here to download the game.

December 26, 2014

Sending Parameters to URL or web service in POST Method

Below code snippet explains how to send parameters to a web url in the POST method.
URL url = new URL(“http://testulr/searchuser”);
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
String params=”userid=”+userid+”&username=”+name;
OutputStream out = new BufferedOutputStream(urlConnection.getOutputStream());
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(out));
InputStream in = new BufferedInputStream(urlConnection.getInputStream());
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
StringBuilder st = new StringBuilder();
String line = "";
while ((line = reader.readLine()) != null) {
System.out.println("Result: "+st);
If the url is secured then replace HttpURLConnection class with HttpsURLConnection in the above code.

October 16, 2014

URL Encoding in Java

Whenever we are passing data to any url or web services, some characters of the data might be un recognised. Hence, it is always better to encode data before sending to URLs or web services, which we call as URL encoding. We have pre defined apis in java to do this encoding.

Below is an example to show how to encode a string in java.

String str="Hello World";, "UTF-8");

The output for this code would be:


Convert an image to Base64

This post is to show how to generate base64 string to an image file.

Below is the method which will return the base64 string to the given image file.
The input for this method is the full path of the image.

    public String getBase64ForFile(String inFile) throws Exception {
        String base64 = "";
        System.out.println("inFile: " + inFile);
        URL url = new URL(inFile);
        InputStream fin = url.openStream();
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        int next = 0;
        while ((next = != -1) {
        base64 = "" + org.kobjects.base64.Base64.encode(bos.toByteArray());
        System.out.println("Base64: " + base64);

        return base64;

June 16, 2014

java.sql.SQLException: Protocol violation

Exception in thread "main" java.sql.SQLException: Protocol violation: [1]
                at oracle.jdbc.driver.T4CTTIfun.receive(
                at oracle.jdbc.driver.T4CTTIfun.doRPC(
                at oracle.jdbc.driver.T4C7Ocommoncall.doOLOGOFF(
                at oracle.jdbc.driver.T4CConnection.logoff(
                at oracle.jdbc.driver.PhysicalConnection.close(

Connection con=createConnection();

Here, commit() is invoked after the connection is closed, hence the above exception occurred.

java.lang.ArrayIndexOutOfBoundsException while executing batch Statements in Java

I have created a PreparedStatement to execute a batch of insert statements. But while executing,  the below exception occurred.

java.lang.ArrayIndexOutOfBoundsException: 22 at oracle.jdbc.driver.T4CNumberAccessor.unmarshalOneRow( at oracle.jdbc.driver.T4C8Oall.readRXD( at oracle.jdbc.driver.T4CTTIfun.receive( at oracle.jdbc.driver.T4CTTIfun.doRPC( at oracle.jdbc.driver.T4C8Oall.doOALL( at oracle.jdbc.driver.T4CPreparedStatement.doOall8( at oracle.jdbc.driver.T4CPreparedStatement.executeForRows( at oracle.jdbc.driver.OraclePreparedStatement.executeForRowsWithTimeout( at oracle.jdbc.driver.OraclePreparedStatement.executeBatch( at oracle.jdbc.driver.OracleStatementWrapper.executeBatch( at XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX 


After googling, I realized that the PreparedStatement is not accepting more than 6 parameters. Below is the statement I have used.
PreparedStatement stmtQuestions = conDB.prepareStatement("INSERT INTO "+Properties.DB_TABLE +" values(?,?,?,?,?,?,?)");
I changed the statement to below which avoid the above exception and program was executed successfully.
Statement stmtQuestions=conDB.createStatement();
String query="INSERT INTO "+Properties.DB_TABLE +" values('"+id+"',"+sid+","+qid+",'"+sqText+"','"+sqSText+"','"+qType+"','"+qoType+"')";

May 14, 2014

Using excel file as DB and read data from Java

We can use an excel file as a data base. Using java we can create connection to excel file and execute sql query as we do with database. Use the below code to use excel file as a DB and read data from it using java.

String stExcelFile=”c:\\temp\\test.xls”;
String stSheetName=”Sheet1”;
        Connection conExcel =
            DriverManager.getConnection("jdbc:odbc:Driver={Microsoft Excel Driver (*.xls)};DBQ=" +
                                        stExcelFile +
        Statement stmtExcel = conExcel.createStatement();
        ResultSet rsExcel =stmtExcel.executeQuery("Select * from [" + stSheetName + "$]");
while ( {
System.out.println(“id: ”+rsExcel.getString(“id”)));
System.out.println(“name: ”+rsExcel.getString(“name”)));

July 12, 2013


As the name implies when the requested operation is not supported, we get this error.
Below is a sample program to generate this error.

public static void main(String args[])
String st[]={"Hi","Hello","Bye"};
List list=Arrays.asList(st);
list.add(“Anand”); //Get error at this line
System.out.println(" List: "+list);

 If we run this method, we get the below error because we are trying to add a new element to a list which is not updatable.

Caused by: java.lang.UnsupportedOperationException
                at java.util. List.add(
                at java.util. List.add(
                at Test.main(

 I modified the program as below to run without errors.

public static void main(String args[])
String st[]={"Hi","Hello","Bye"};
ArrayList<String> list = new ArrayList<String>();
//List list=Arrays.asList(st);
list.add(“Anand”); //Get error at this line
System.out.println(" List: "+list);

June 22, 2013

Changing End point address of web service

Below code explains how to change the web service end point through program. 

ServiceRequestService serviceRequestService = new ServiceRequestService();
ServiceRequestPortType serviceRequestPortType =
BindingProvider bp = (BindingProvider)serviceRequestPortType;           

 Here is the explanation for this code.
  • Get port object of the web service
  • Type cast the port object to BindingProvider object 
  • BindingProvider class provides a member method getRequestContext() which returns a map
  • This map holds all the attributes of the request context
  • Overwrite end point with new web service url which will replace the new end point with the old one.
Note: This code works only if the client style is RPC.

May 6, 2013

Refreshing JSF page from Java Code

The below code can be useful to refresh JSF page from java code method. 

String currentView = context.getViewRoot().getViewId();
ViewHandler vh = context.getApplication().getViewHandler();
UIViewRoot x = vh.createView(context,currentView);

February 27, 2013

Creating object to inner class in Java

I have a class definition like below and I want to create an object for the inner class.

class outerclass
    public class innerclass{

To create an object for the above innerclass, we should follow the below syntax.

outerclass.innerclass obj=new outerclass().new innerclass();