URL Connection via Proxy (the Java 1.5 way)

In enterprises/corporate environments, more often than not, connection to external servers/resources is via a proxy server. While developing applications for such environments, developers need to make sure that their code connects to external sites/resources via the proxy.

In this post, I restrict myself to the HTTP protocol.

The Java development platform provides multiple methods to make HTTP connections via a proxy server. However, prior to Java 1.5, there was just one way available: by setting System properties.

There are two steps involved:

1. Set the http.proxyHost, http.proxyPort, http.proxySet properties as follows:

Properties props = System.getProperties();
props.put("http.proxyPort","8080"); //proxy port
props.put("http.proxyHost","proxy.xyz.co.in"); //the proxy server name or IP
props.put("http.proxySet", "true");

2. Connect to the remote server. The properties set above would be automatically picked up by the JVM.

URLConnection urlConn = null;
BufferedReader reader = null;
String response = "";
String output = "";
URL url = new URL("www.google.com");
urlConn = url.openConnection();
urlConn.connect();
reader = new BufferedReader(new InputStreamReader(urlConn.getInputStream()));
response = reader.readLine();
while (response!=null) {
	output+= response;
	response = reader.readLine();
}	
System.out.println("Output: " + output);

For FTP, HTTPS and SOCKS the following system properties need to be set:

ftp.proxHost
ftp.proxyPort
ftp.nonProxyHosts 

htttps.proxyHost
https.proxyPort 

socksProxyHost
socksProxyPort

Although, this approach is very simple, there are some obvious drawbacks.
1. This is a all or none approach. Once the properties are set, till the time the properties are removed, all connections would happen via the same proxy server.
2. The properties are set VM-wide. This might causing site effects to other parts of the application that might not need the use of the proxy server.
3. If the corporate environment has the restriction that internal systems need to be accessed directly, whereas the external systems need to be accessed via the proxy, then this approach will fail.

With Java 1.5, the developer is provided with a more powerful and flexible approach via the Proxy class.

To define a HTTP proxy using this class, the following code is required:

String proxyHost = "proxy.xyz.co.in"; //replace with your proxy server name or IP
int proxyPort = 8080; //your proxy server port
SocketAddress addr = new InetSocketAddress(proxyHost, proxyPort);
Proxy httpProxy = new Proxy(Proxy.Type.HTTP, addr);

Now, we need to use the above defined proxy while opening a URL Connection. For this, the URL class provides a new overloaded method openConnection(Proxy proxy) that accepts a Proxy instance.

Below is the code for the same:

String proxyHost = "proxy.xyz.co.in"; //replace with your proxy server name or IP
int proxyPort = 8080; //your proxy server port
SocketAddress addr = new InetSocketAddress(proxyHost, proxyPort);
Proxy httpProxy = new Proxy(Proxy.Type.HTTP, addr);

URLConnection urlConn = null;
BufferedReader reader = null;
String response = "";
String output = "";
URL url = new URL("www.google.com");
//Pass the Proxy instance defined above, to the openConnection() method
urlConn = url.openConnection(httpProxy); 
urlConn.connect();
reader = new BufferedReader(new InputStreamReader(urlConn.getInputStream()));
response = reader.readLine();
while (response!=null) {
	output+= response;
	response = reader.readLine();
}	
System.out.println("Output: " + output);

That’s all. No system-wide settings are required.

If, for a particular connection, you want to connect directly (and not go via the proxy) – this would be required for connecting to internal servers, then use the following:

URL intranetURL = new URL("http://internal.xyz.co.in/");
URLConnection conn = intranetURL.openConnection(Proxy.NO_PROXY);

The Proxy.NO_PROXY static member forces the connection to retrieve the defined URL directly bypassing all proxy settings.

The proxy class also allows you to define a SOCKS proxy by using the type Proxy.Type.SOCKS.

Thus, as you can see, with Java 1.5 and above, the developer has more control while connecting via proxies.

Java 1.5 provides another class called the Proxy Selector which gives even more control by allowing dynamic selection of proxies. I will cover that in another post.

Advertisements
Posted in Java | Tagged , , , , , | 2 Comments

Death Speaks

Death Speaks
By W. Somerset Maugham, Jeffrey Archer

There was a merchant in Baghdad who sent his servant to market to buy provisions and in a little while the servant came back, white and trembling, and said, Master, just now when I was in the market-place, I was jostled by a woman in the crowd and when I turned I saw it was Death that jostled me. She looked at me and made a threatening gesture; now, lend me your horse, and I will ride away from this city and avoid my fate. I will go to Samarra and there Death will not find me. The merchant lent him the horse and the servant mounted it, and he dug his spurs in its flanks and as fast as the horse could gallop he went. Then the merchant went down to the market-place and he saw me standing in the crowd and he came to me and said, Why did you make a threatening gesture to my servant when you saw him this morning? That was not a threatening gesture, I said, it was only a start of surprise. I was astonished to see him in Baghdad, for I had an appointment with him tonight in Samarra.

Posted in General | Tagged , , | Leave a comment

GWT-Ext – Synchronized Scrolling of Grids

I recently had a requirement wherein two grids showing similar information needed synchronized scrolling i.e. if the left grid was scrolled down vertically, the right grid also needed to be scrolled down in the same proportion and vice-versa.

This feature comes in very handy when the user has to compare the changed values across the two grids. Consider the use case of a user viewing his stock portfolio and wants to track the prices of his investments on two different dates.

The screenshot below explains the scenario:

Synchronized scrolling (vertical) of two grids

Synchronized scrolling (vertical) of two grids

In this scenario, we only need to the vertical scroll to be synchronized. However, if there is a horizontal scrollbar present, the horizontal scrolling would also be synchronized.

To implement synchronized scrolling follow the steps below:

1. Declare and initialize the grids:

//Create the right grid
final GridPanel rightGrid = new GridPanel();

//Create the left grid
final GridPanel leftGrid = new GridPanel();

2. Initialize two GridViews and attach them to the respective grids

//Right GridView
GridView gridViewRight = new GridView();
rightGrid.setView(gridViewRight);

//Left GridView
GridView gridViewLeft = new GridView();
leftGrid.setView(gridViewLeft);

3. Set other regular Grid properties like Column Model, Store etc.

4. Add a GridListener to each of the Grids. We only need to implement the onBodyScroll(int scrollLeft, int scrollTop) method of the listener so we will use GridListenerAdapter instead.

The GridView class provides a method
scrollToPosition(int horizontalPosition, int verticalPosition)
which scrolls the Grid scroll-bar to the specified position.
If the grid needs to be scrolled in only one of the direction, then pass the other position value as -1.

//Add a GridListener for the right grid that will
//scroll the left grid scroll bars when the right grid is scrolled.

rightGrid.addGridListener(new GridListenerAdapter(){
public void onBodyScroll(int scrollLeft, int scrollTop) {

//if the right grid scroll bar is moved,
//the left grid scroll bar needs to be moved proportionately

gridViewLeft.scrollToPosition(scrollLeft, scrollTop);
//gridViewLeft.scrollToPosition(-1, scrollTop);
}
});

//Add a GridListener for the left grid that will
//scroll the right scroll bars this grid is scrolled

leftGrid.addGridListener(new GridListenerAdapter(){
public void onBodyScroll(int scrollLeft, int scrollTop) {

//if the left grid scroll bar is moved,
//the right grid scroll bar needs to be moved proportionately

gridViewRight.scrollToPosition(scrollLeft, scrollTop);
//gridViewRight.scrollToPosition(-1, scrollTop);
}
});

That’s it! Now, whenever either of the grids is scrolled up or down, the other grid scroll bar would automatically adjust itself at the same position.

If you want only vertical scrolling to be synchronized, then comment the two lines and uncomment the commented lines in the listener code above.

Posted in GWT, GWT-Ext | Tagged , , , , | Leave a comment

SPRING Quick Tip: Setting application property values dynamically!

Spring provides a very cool feature of passing application property values dynamically using the java -D switch.

All you need to do is define the property in the properties file and leave the value part blank.

When you run the application, say from the command line, use the -D switch to pass the key=value for the property whose value needs to be set dynamically.

This feature is a life-saver in enterprise environments where you need to pass sensitive information to the application (like DB passwords etc.) without the knowledge of the application/developer.

During the development phase you can set the password in the properties file and test the application.

During deployment, just remove the password value from the properties file and pass the password dynamically to the application (of course, you need to have another code that reads the encrypted password from some common repository, decrypts it and then passes the value to your application).

Thus, there is no code change required to read the password dynamically.

Below screen shot provides more details:

Spring - Setting property values dynamically
The value for the password property can be passed at run-time using -Dpassword=bingo

Posted in Java, Quick Tips, Spring | Tagged , | Leave a comment

A simple way to list/filter files

Here is a very simple and elegant way to list or filter the files in a given directory.

For this use the File.listFiles() method of java.io.File class.

The example below deletes all the files that end with the “.tmp” extension.

Below is the code sample:

Code sample to list/filter files within a directory

Code sample to list/filter files within a directory

There are some limitations that you need to be aware of:

1. This code will not recursively list/delete files.

2. It will also list the subfolder names (if any).

Posted in Java | Tagged , | Leave a comment

Retrieving the Process ID (PID) in Java

Sometimes it is necessary for a Java application to retrieve it’s own process id. An example of where this could be required is for logging/debugging purposes. Below is a simple “Java way” (there are other ways to discover the process id but they are more complex and require JNI or some shell scripting) to retrieve the process id:


import java.lang.management.ManagementFactory;

public class ApplicationPID {

public static void main(String [] args){
String name = ManagementFactory.getRuntimeMXBean().getName();
System.out.println("Process ID for this app = " + name);
}
}

This is the output:

Process ID for this app = 2584@MyComp

As you would have noticed from the snippet above, we have used the method: RuntimeMXBean.getName().

However, there is a caveat. As per the Javadoc, this method is JVM implementation dependent. Different implementations of JVM might return different results. Because of this limitation, we cannot use a standard parsing logic to do some automated processing on the PID.
I have tested this on SUN’s JVM, and found it to be working fine.

Returns the name representing the running Java virtual machine. The returned name string can be any arbitrary string and a Java virtual machine implementation can choose to embed platform-specific useful information in the returned name string. Each running virtual machine could have a different name.

Posted in Java | Tagged , | Leave a comment

GWT-Ext Date-Picker widget – Change the start of week

The GWT-Ext Date-Picker widget (the Calendar widget that allows for selection of a date) by default shows the starting day of a week as Sunday.  Moreover, there is no API provided to change it to any other day.  E.g. in one of the financial applications that I was recently working on,  users wanted that the start of week as Monday as they transact business from Monday thru Friday.

However, there is a very simple way to fix this problem. As GWT-Ext uses Ext components internally, we just need to modify the ext-all.js to set the start day as Monday (or any other day).  The only drawback of this solution is that it will change the start of week for all instances of the Date-Picker widget used in the application.

Follow these steps to change the start of week:

1. Open ext-all.js in any text-editor (e.g. WordPad). This file would be present in the public/js/ext folder of your project as shown in the screenshot below:

Ext-all.js file location in a GWT project
Ext-all.js file location in a GWT project

2.  Within the file search for the text “Ext.DatePicker“. This line contains all the default properties for the Date-Picker widget.  The properties are comma-separated.

3. Keep scrolling to the right till you find the property “startDay“. If you have never modified the file before, it should have the value set as “0” (zero). The assignment would look like this:

startDay:0

The days of a week are defined using the following integers: Sunday – 0, Monday -1, Tuesday-2,…,Saturday-6.

4. Set the value of startDay to your desired value. E.g. in my case, I wanted the week to start from Monday, so I set it to 1.

5. Save the changes and redeploy the updated JS file on your Web Server.

6. Restart the application.

You will now find that the start-day has changed to whatever day you had set in the ext-all.js file.

Posted in GWT-Ext | Tagged , , , | 1 Comment

BigDecimal and “java.lang.ArithmeticException: Non-terminating decimal expansion”

In one of my recent projects, I had to use java.math.BigDecimal to divide two values. I had to use BigDecimal instead of double as this was a financial application and required the results to be accurate.

However, after running the application, I encountered the following error intermittenly:

Exception in thread "main" java.lang.ArithmeticException: Non-terminating decimal expansion; no exact representable decimal result.

Below is a sample code which illustrates the issue:

package com.jm.client;

import java.math.BigDecimal;

/**
* Test case for "java.lang.ArithmeticException:
* Non-terminating decimal expansion" error with
* BigDecimal.
*
* @author JM
*
*/
public class TestBigDecimal {

public static void main(String[] args) {

String returnVal = TestBigDecimal.divide("1", "5");

System.out.println("Test #1: returnVal = " + returnVal);

returnVal = TestBigDecimal.divide("1", "2");

System.out.println("Test #2: returnVal = " + returnVal);

// Test(#3) will fail as the quotient (returnVal)
//is a non-terminating decimal value.

returnVal = TestBigDecimal.divide("1", "3");

System.out.println("Test #3: returnVal = " + returnVal);
}

/**
* Divide val1 by val2 and return the result as String.
*
* @param val1
* @param val2
* @return value as String
*/
public static String divide(String val1, String val2) {

BigDecimal v1 = new BigDecimal(val1);

BigDecimal v2 = new BigDecimal(val2);

return v1.divide(v2).toPlainString();

}

}

Below is the output:

Test #1: returnVal = 0.2
Test #2: returnVal = 0.5
Exception in thread “main” java.lang.ArithmeticException: Non-terminating decimal expansion; no exact representable decimal result.
at java.math.BigDecimal.divide(Unknown Source)
at com.jm.client.TestBigDecimal.divide(TestBigDecimal.java:34)
at com.jm.client.TestBigDecimal.main(TestBigDecimal.java:20)

Upon some ‘googling’ and looking at the Java Doc for BigDecimal, I found that this happens due to a couple of reasons:
1. The BigDecimal by default always tries to return the exact result of an operation.
2. Due to this, certain division operations like 1 divided by 3, the exact quotient will have an infinitely long decimal expansion. This will cause the division operation to fail and throw the error as described above.

This is also described in the BigDecimal Java Doc quoted below:
“In the case of divide, the exact quotient could have an infinitely long decimal expansion; for example, 1 divided by 3. If the quotient has a nonterminating decimal expansion and the operation is specified to return an exact result, an ArithmeticException is thrown. Otherwise, the exact result of the division is returned, as done for other operations.”

To fix the issue, we need to provide a scale (i.e. the precision) for the quotient and also the rounding mode to the BigDecimal.divide(). In the sample below, I have used a scale of 2 and the rounding mode as RoundingMode.HALF_UP. You can increase the scale if you want a greater precision.

package com.jm.client;

import java.math.BigDecimal;
import java.math.RoundingMode;

/**
* Test case for "java.lang.ArithmeticException:
* Non-terminating decimal expansion" error with
* BigDecimal.
*
* @author JM
*
*/
public class TestBigDecimal {

public static void main(String[] args) {

String returnVal = TestBigDecimal.divide("1", "5");

System.out.println("Test #1: returnVal = " + returnVal);

returnVal = TestBigDecimal.divide("1", "2");

System.out.println("Test #2: returnVal = " + returnVal);

// Test(#3) will now work as we have provided a scale
// and a rounding mode to the divide() method

returnVal = TestBigDecimal.divide("1", "3");

System.out.println("Test #3: returnVal = " + returnVal);

}

/**
* Divide val1 by val2 and return the result as String.
*
* @param val1
* @param val2
* @return value as String
*/
public static String divide(String val1, String val2) {

BigDecimal v1 = new BigDecimal(val1);

BigDecimal v2 = new BigDecimal(val2);

return v1.divide(v2, 2, RoundingMode.HALF_UP).toPlainString();

}

}

The output of the above program now is as desired:

Test #1: returnVal = 0.20
Test #2: returnVal = 0.50
Test #3: returnVal = 0.33

Posted in Java | Tagged , | 54 Comments

Retrieving unique items from a List in Java

Here is a very simple and efficient way to retrieve unique items from a java.util.List.

All you need to do is put all the items in the java.util.List into a java.util.Set and then create a new java.util.Listfrom the Set. Since a Set does not allow duplicate entries, the new List created would only have the unique items.

Below is an example:
//the initial List
ArrayList list = new ArrayList();
list.add("ID_1");
list.add("ID_2");
list.add("ID_3);
list.add("ID_2); //duplicate entry - needs to be removed
//convert the List into a Set
Set set = new HashSet(list);
//create a new List from the Set
ArrayList uniqueList = new ArrayList(set);

Note that the order of the items in the unique list will not be the same as those in the original.
To maintain the order of the initial items use a java.util.LinkedHashSet instead of a java.util.HashSet.
To sort the items in the java.util.List use a java.util.TreeSet instead.

For further details, have a look here.

Posted in Java | Tagged , , | 1 Comment

Gone are the days……..

Gone are the days……..but not the memories

Received this in an email from someone. It is beautifully written and as you read, it actually transports you back to the good old school days.

Gone are the days……..

Gone are the days
When the school reopened in June,
And we settled in our new desks and benches.

Gone are the days
When we queued up in book depot,
And got our new books and notes.

Gone are the days
When we wanted two Sundays and no Mondays, yet
Managed to line up daily for the morning prayers.

Gone are the days
When we chased one another in the corridors in intervals,
And returned to the classrooms drenched in sweat.

Gone are the days
When we had lunch in classrooms, corridors,
Playgrounds, under the trees and even in cycle sheds.

Gone are the days
When a single P.T. period in the week’s Time Table,
Was awaited more eagerly than the monsoons.

Gone are the days
Of fights but no conspiracies,
Of Competitions but seldom jealousy.

Gone are the days
When we used to watch Live Cricket telecast,
In the opposite house in Intervals and Lunch breaks.

Gone are the days
When few rushed at 5:30 to
“Conquer” window seats in our School bus.

Gone are the days
Of Sports Day, and the annual School Day,
And the one-month long preparations for them.

Gone are the days
Of the stressful Quarterly, Half Yearly and Annual Exams,
And the most enjoyed holidays after them.

Gone are the days
We learnt, we enjoyed, we played, we won, we lost,
We laughed, we cried, we fought, we thought.

Gone are the days
With so much fun in them, so many friends,
So much experience, all this and more.

Gone are the days
But not the memories, which will be
Lingering in our hearts for ever and ever and
Ever and ever and Ever.

Posted in Uncategorized | Tagged | Leave a comment