Http Client form based authentication

In this post i will explain you how to do form based authentication in Http client. For this tutorial i have used http client 4.1.2 (i.e. httpcomponents).

Form based authentication can be done in three steps as described below.

  1. Access secure page on server. In response to this request you will receive login page with http status code 200. Note that you will receive JSESSIONID cookie with this response which is required for next request.
  2. Now create a post request for “/j_security_check”. Pass j_username and j_password along with this request. In response to this request you will receive blank response with http status code 302. Here htpp status code 302 indicates that login is successful. If you provide wrong username/password then you will receive login page with http status code 200.
  3. Now access secure page on server. In response to this request you will get requested page with http status code 200 because you are authenticated.

Sample code to do form based authentication in Java using http client.

package com.elitejavacoder.http.client;

import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpHost;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.params.ClientPNames;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

public class HttpClientFormAuthentication {
    public static void main(String[] agrs) {
        String host = "yourhostname.com";
        int port = 8080;
        String protocol = "http";

        DefaultHttpClient client = new DefaultHttpClient();

        try {
            HttpHost httpHost = new HttpHost(host, port, protocol);
            client.getParams().setParameter(ClientPNames.DEFAULT_HOST, httpHost);

            HttpGet securedResource = new HttpGet("/secured/index.jsp");            
            HttpResponse httpResponse = client.execute(securedResource);
            HttpEntity responseEntity = httpResponse.getEntity();
            String strResponse = EntityUtils.toString(responseEntity);
            int statusCode = httpResponse.getStatusLine().getStatusCode();
            EntityUtils.consume(responseEntity);

            System.out.println("Http status code for Unauthenticated Request: " + statusCode);// Statue code should be 200
            System.out.println("Response for Unauthenticated Request: n" + strResponse); // Should be login page
            System.out.println("================================================================n");

            HttpPost authpost = new HttpPost("/j_security_check");
            List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
            nameValuePairs.add(new BasicNameValuePair("j_username", "yourusername"));
            nameValuePairs.add(new BasicNameValuePair("j_password", "yourpassword"));
            authpost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

            httpResponse = client.execute(authpost);
            responseEntity = httpResponse.getEntity();
            strResponse = EntityUtils.toString(responseEntity);
            statusCode = httpResponse.getStatusLine().getStatusCode();
            EntityUtils.consume(responseEntity);

            System.out.println("Http status code for Authenticattion Request: " + statusCode);// Status code should be 302
            System.out.println("Response for Authenticattion Request: n" + strResponse); // Should be blank string
            System.out.println("================================================================n");

            httpResponse = client.execute(securedResource);
            responseEntity = httpResponse.getEntity();
            strResponse = EntityUtils.toString(responseEntity);
            statusCode = httpResponse.getStatusLine().getStatusCode();
            EntityUtils.consume(responseEntity);

            System.out.println("Http status code for Authenticated Request: " + statusCode);// Status code should be 200
            System.out.println("Response for Authenticated Request: n" + strResponse);// Should be actual page
            System.out.println("================================================================n");
        }
        catch (Exception ex) {
            ex.printStackTrace();
        }
    }
}

How to sort map by keys/values in Java

This post will explain you how to sort map by keys/values. I have created one Utility class for the same which you can use to sort map by keys or values.

Utility class to sort Map by keys and values

package com.elitejavacoder.util;

import java.util.Comparator;
import java.util.Map;
import java.util.TreeMap;

public class MapUtility {

    public static <K, V extends Comparable<V>> Map<K, V> sortOnValues(Map<K, V> unsortedMap) {
        Map<K, V> sortedMap = new TreeMap<K, V>(new MapValueComparator<K, V>(unsortedMap));
        sortedMap.putAll(unsortedMap);
        return sortedMap;
    }

    public static <K, V extends Comparable<V>> Map<K, V> sortOnKeys(Map<K, V> unsortedMap) {
        Map<K, V> sortedMap = new TreeMap<K, V>();
        sortedMap.putAll(unsortedMap);
        return sortedMap;
    }

}

class MapValueComparator<K, V extends Comparable<V>> implements Comparator<K> {
    Map<K, V> map;

    MapValueComparator(Map<K, V> map) {
        this.map = map;
    }

	public int compare(K key1, K key2) {
		V value1 = map.get(key1);
		V value2 = map.get(key2);

		return value1.compareTo(value2);
	}
}

Sort Map of java objects by keys and values

Map<String, String> unsortedMap = new HashMap<String, String>();  
unsortedMap.put("1", "Z");
unsortedMap.put("2", "C");
unsortedMap.put("7", "E");
unsortedMap.put("4", "A");
unsortedMap.put("6", "B");
unsortedMap.put("5", "N");
unsortedMap.put("3", "P");

System.out.println("Unsorted Map: " + unsortedMap);

Map<String, String> sortedMapByKeys = MapUtility.sortOnKeys(unsortedMap);
System.out.println("Sorted Map by Keys: " + sortedMapByKeys);

Map<String, String> sortedMapByValues = MapUtility.sortOnValues(unsortedMap);
System.out.println("Sorted Map by Values: " + sortedMapByValues);

Run above sample code which is using map utility to test map sorting on keys and values. You will get following output so we can see that map is sorted as expected.

Unsorted Map: {3=P, 2=C, 1=Z, 7=E, 6=B, 5=N, 4=A}
Sorted Map by Keys: {1=Z, 2=C, 3=P, 4=A, 5=N, 6=B, 7=E}
Sorted Map by Values: {4=A, 6=B, 2=C, 7=E, 5=N, 3=P, 1=Z}

Sort Map of user defined objects by keys and values

To test Map utility against user defined objects I have created Employee class which implements Comparable interface. I have overridden compareTo() method to compare Employee objects on name so Employee objects should be sorted on name. Employee class is as follow:

package com.elitejavacoder.util;

public class Employee implements Comparable&lt;Employee&gt; {
    long id;
    String name;

    Employee(long id, String name) {
        this.id = id;
        this.name = name;
    }
    
    public long getId() {
        return id;
    }

    public void setId(long id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int compareTo(Employee obj) {
        return this.name.compareTo(obj.getName()); // Compare on name
    }
    
    @Override
    public String toString() {
        return this.name;
    }
}

// Sort map of user defined objects
Map<Long, Employee> unsortedMap = new HashMap<Long, Employee>();
unsortedMap.put(new Long(9), new Employee(9, "Ankur"));
unsortedMap.put(new Long(6), new Employee(6, "Sanket"));
unsortedMap.put(new Long(4), new Employee(4, "Devang"));
unsortedMap.put(new Long(7), new Employee(7, "Timir"));
unsortedMap.put(new Long(3), new Employee(3, "Jay"));
unsortedMap.put(new Long(1), new Employee(1, "Atul"));

System.out.println("Unsorted Map: " + unsortedMap);

Map<Long, Employee> sortedMapByKeys = MapUtility.sortOnKeys(unsortedMap);
System.out.println("Sorted Map by Keys: " + sortedMapByKeys);

Map<Long, Employee> sortedMapByValues = MapUtility.sortOnValues(unsortedMap);
System.out.println("Sorted Map by Values: " + sortedMapByValues);

Run above sample code which is using map utility to test map sorting on keys and values. You will get following output so we can see that map is sorted as expected.

Unsorted Map: {1=Atul, 3=Jay, 4=Devang, 6=Sanket, 7=Timir, 9=Ankur}
Sorted Map by Keys: {1=Atul, 3=Jay, 4=Devang, 6=Sanket, 7=Timir, 9=Ankur}
Sorted Map by Values: {9=Ankur, 1=Atul, 4=Devang, 3=Jay, 6=Sanket, 7=Timir}

Apache Ant-Contrib Tutorial 2

In second part of ant-contrib tutorial i will explain some more tasks. First part of this tutorial is available here.

Use switch case in ant.

This task provides similar functionality provided by switch case in Java. You could find more details about this task here.

<target name="test-ant-contrib">
	<switch value="${testValue}" caseinsensitive="true">
		<case value="A">
			<echo message="Test value you have specified is A." />
		</case>
		<case value="B">
			<echo message="Test value you have specified is B." />
		</case>
		<default>
			<echo message="Test value you have specified is other then A/B." />
		</default>
	</switch>
</target>

Use following command to test above example.

ant test-ant-contrib -DtestValue=A

ant test-ant-contrib -DtestValue=a

ant test-ant-contrib -DtestValue=C

Note that at least one <case> or <default> is required. The default case must not appear more than once. In above switch i declared caseinsensitive to true so you will get same output for the first two commands. You can try with caseinsensitive = false.

Perform mathematical operations in ant.

This task provides support for all the basic mathematical operations provided by the java.lang.Math class. It supports int, long, float and double data types. You could find more details about this task here.

<target name="test-ant-contrib">
	<fail message="Please provide testValue1, testValue2, operation and datatype.">
		<condition>
			<or>
				<equals arg1="${testValue1}" arg2=""/>
				<not><isset property="testValue1"/></not>
				<equals arg1="${operation}" arg2=""/>
				<not><isset property="operation"/></not>
				<equals arg1="${testValue2}" arg2=""/>
				<not><isset property="testValue2"/></not>
				<equals arg1="${datatype}" arg2=""/>
				<not><isset property="datatype"/></not>
			</or>
		</condition>
	</fail>
	<math result="result" operand1="${testValue1}" operation="${operation}" operand2="${testValue2}" datatype="${datatype}"/>
	<echo message="Result: ${result}" />
</target>

Run above target using ant test-ant-contrib -DtestValue1=11 -Doperation=+ -DtestValue2=39 -Ddatatype=int to test above example. Try some other mathematical operations with this task.

Replace string in ant

This task allows you to perform regular expression operations on an input string, and sets the results to a property. You can replace string with another string based on matching expression. You could find more details about this task here.

<target name="test-ant-contrib">
	<propertyregex property="newValue" input="${testValue}" regexp="." replace="_" casesensitive="false" />
	<echo message="Result: ${newValue}" />
</target>

Run above target using ant test-ant-contrib -DtestValue=A.B.C.D to test above example. Here in this example i replaced “.” with “_” but you can do lot more using this task.

Sort list values in ant

This task provides functionality to sort a delimited list of items in their natural string order. You could find more details about this task here.

<target name="test-ant-contrib">
	<sortlist property="sortedValues" value="${testValues}" delimiter="," casesensitive="false"/>
	<echo message="Sorted Values: ${sortedValues}" />
</target>

Run above target using ant test-ant-contrib -DtestValues=”z,y,x,w,P,b,c” to test above example. Here i defined casesensitive = false, try above example using casesensitive = true.

Mutable Variable or property in ant

This task provides a mutable property to Ant and works much like variable assignment in Java. This task is similar to the standard Ant Property task, except that THESE PROPERTIES ARE MUTABLE. You could find more details about this task here.

<target name="test-ant-contrib">
	<var name="var1" value="20"/>
	<echo message="Initial value: ${var1}" />
	<var name="var1" value="30"/>
	<echo message="New value: ${var1}" />
</target>

Run above target using ant test-ant-contrib to test above example.

Apache Ant-Contrib Tutorial 1

Sometime we need some additional task capabilities which are not available with standard ant. Ant-Contrib is most commonly used task collection library. This post explains some of the tasks of ant.

You can download ant-contrib jar here. I have used ant-contrib-1.0b2 for this tutorial

Install/Include ant-contrib jar

Copy ant-contrib.jar in lib folder of your project and then include taskdef element in your build.xml as follow:

<!-- Include ant-contrib.jar dynamically -->
<taskdef resource="net/sf/antcontrib/antlib.xml">
	<classpath>
		<pathelement location="${basedir}/lib/ant-contrib.jar"/>
	</classpath>
</taskdef>

Sometime we want to perform some task based on conditions. In such situation we can use ant-contrib task to achieve this. Following examples explain you different types of usage of If task.

If-Else

<!-- Usage of if-else -->
<target name="test-ant-contrib">
	<if>
		<equals arg1="${testValue}" arg2="A" />
		<then>
			<echo message="Test value you have specified is A." />
		</then>
		<else>
			<echo message="Test value you have specified is other than A." />
		</else>
	</if> 
</target>

Run above target using ant test-ant-contrib -DtestValue=A and ant test-ant-contrib -DtestValue=B to test above example.

If-Else-If

<!-- Usage of if-else-if -->
<target name="test-ant-contrib">
	<if>
		<equals arg1="${testValue}" arg2="A" />
		<then>
			<echo message="Test value you have specified is A." />
		</then>
		<elseif>
			<equals arg1="${testValue}" arg2="B" />
			<then>
			<echo message="Test value you have specified is B." />
			</then>
		</elseif>
		<else>
			<echo message="Test value you have specified is other than A/B." />
		</else>
	</if>
</target>

Run above target using ant test-ant-contrib -DtestValue=A, ant test-ant-contrib -DtestValue=B and ant test-ant-contrib -DtestValue=C to test above example.

Not Equals

<!-- Usage of not-qauals -->
<target name="test-ant-contrib">
	<if>
		<not><equals arg1="${testValue}" arg2="A" /></not>
		<then>
			<echo message="Test value you have specified is other than A." />
		</then>
		<else>
			<echo message="Test value you have specified is A." />
		</else>
	</if>
</target>

Run above target using ant test-ant-contrib -DtestValue=A and ant test-ant-contrib -DtestValue=B to test above example.

OR Condition

<!-- Usage of or-condition -->
<target name="test-ant-contrib">
	<if>
		<or>
			<equals arg1="${testValue}" arg2="A" />
			<equals arg1="${testValue}" arg2="B" />
		</or>
		<then>
			<echo message="Test value you have specified is A/B." />    
		</then>
		<else>
			<echo message="Test value you have specified is other than A/B." />
		</else>
	</if>
</target>

Run above target using ant test-ant-contrib -DtestValue=A, ant test-ant-contrib -DtestValue=B and ant test-ant-contrib -DtestValue=C to test above example.

AND Condition

<!-- Usage of and-condition -->
<target name="test-ant-contrib">
	<if>
		<and>
			<equals arg1="${testValue1}" arg2="A" />
			<equals arg1="${testValue2}" arg2="B" />
		</and>
		<then>
			<echo message="You have specified A as testValue1 and B as testValue2." />    
		</then>
		<else>
			<echo message="Test values you have specified are not as expected." />
		</else>
	</if>
</target>

Run above target using ant test-ant-contrib -DtestValue1=A -DtestValue2=B and ant test-ant-contrib -DtestValue1=A -DtestValue2=C to test above example.

Loop through values using foreach

Sometime we want to iterate through the list of values separated by some delimiter. In below sample I am iterating through comma separated values.

<!-- Usage of for task --&gt;
<target name="test-ant-contrib">
	<for list="${testValues}" delimiter="," param = "val">
		<sequential>
			<echo message = "Value: @{val}" />
		</sequential>
	</for>
</target>

Run above target using ant test-ant-contrib -DtestValues=”value1,value2,value3,value4,value5″ to test above example.

Replace property values at the time of maven build

This post explains how to replace property values at the time of maven build.

Replace property value in resource files (non-java files) at the time of maven build

Create one resource file filter-test.txt in $PROJECT_HOME/src/main/resources with content as follow.

Hello ${resource.name}

Now add following lines in pom.xml file of your project.

 
<properties>
	<resource.name>RESOURCE</resource.name>
</properties>

<build>  
	<resources>
		<!-- Filter resource files -->
		<resource>
			<directory>src/main/resources</directory>
			<filtering>true</filtering>
		</resource>
	</resources>
	....
</build>

Build your project using following command.

mvn clean install

Check content of filter-test.txt file under $PROJECT_HOME/target/classes. It should be as follow.

Hello RESOURCE

Please note that at the time of build ${resource.name} in filter-test.txt file is replaced with “RESOURCE” which we have defined in pom.xml file as property.

Now you can overwrite property value defined in pom.xml file using command line argument at the time of build. Do build using following command.

mvn clean install -Dresource.name=Atul

Check content of the filter-test.txt file under $PROJECT_HOME/target/classes. It should be as follow.

Hello Atul

Replace property value in java files at the time of maven build

Create one FilterTest.java file under $PROJECT_HOME/src/main/java/com/elitejavacoder/test with content as follow.

package com.elitejavacoder.test;

public class FilterTest {

	private static String NAME = "${java.name}";

		public static void main(String[] args) {

		try {
			System.out.println("n Value of name : " + NAME);
		}
		catch (Exception ex) {
			ex.printStackTrace();
		}
	}
}

Now add following lines in pom.xml file of your project.

<properties>
	<java.name>JAVA</java.name>
</properties>

<build>  
	<resources>
		<!-- Filter Java files -->
		<resource>
			<filtering>true</filtering>
			<directory>src/main/java</directory>
			<targetPath>../filtered-sources/java</targetPath>
			<includes>
				<include>**/*.java</include>
			</includes>
		</resource>
	</resources>

	<!-- change default source directory to filtered-sources/java -->
	<sourceDirectory>target/filtered-sources/java</sourceDirectory>
	....
</build>

Please note that in case of java files, we filter java files as resource files and copy them to filtered-sources/java. Then we change default maven source directory to point filtered java files directory using <sourceDirectory>.

Now do a build using following command.

mvn clean install

Run this class to check output. Please note that I have created executable jar so I will run this class using following command from $PROJECT_HOME/target. For information on how to create executable jar please refer this post.

java -jar replace-property-values-at-build-time-1.0.0-SNAPSHOT.jar

The output should be as follow.

Value of name : JAVA

Please note that at the time of maven build, ${java.name} in FilterTest.java is replaced with “JAVA” which we have defined in pom.xml file as property. You can check this in compiled class file as well using any decompiler.

Now you can overwrite this property value defined in pom.xml file using command line argument at the time of build. Do build using following command.

mvn clean install -Djava.name=Atul

Again run this class to check output using following command.

java -jar replace-property-values-at-build-time-1.0.0-SNAPSHOT.jar

The output should be as follow.

Value of name : Atul

I hope this post helps!