Jerry Jacob's Blog

Client IP Address in Java

Posted in Java/ J2EE by jerlinworld on May 6, 2013

//IP address of request's HTTP header ""X-FORWARDED-FOR"

String ipAdr = request.getHeader("X-FORWARDED-FOR");

if (ipAdr == null) {

ipAdr = request.getRemoteAddr();

}

Opensource RESTful API for searching the geolocation of IP Addresses and hostnames.
https://github.com/fiorix/freegeoip (http://freegeoip.net/)

Advertisements
Tagged with:

MongoDB with SpringData

Posted in Java/ J2EE by jerlinworld on August 23, 2012

Here is a simple example to show how easy to write a CRUD Java application using SpringData for MongoDB

First of all install and start MongoDB. You need only 3 files to get things going; The domain object, CRUDInterface and CRUDImplementation
Make sure you have the required mongo and spring-data-mongodb jar files in the classpath.

The domain object

package jerry.jacob.mongo.test;

import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document;

@Document
public class Employee {
	@Id
	private String id;
	private String firstName;
	private String lastName;
	private int age;

	public Employee(String id, String firstName, String lastName,int age) {
		this.id = id;
		this.firstName = firstName;
		this.lastName = lastName;
                this.age = age;
	}

	public String getId() {
		return id;
	}

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

	public String getFirstName() {
		return firstName;
	}

	public void setFirstName(String firstName) {
		this.firstName = firstName;
	}

	public String getLastName() {
		return lastName;
	}

	public void setLastName(String lastName) {
		this.lastName = lastName;
	}

	public int getAge() {
		return age;
	}

	public void setAge(int age) {
		this.age = age;
	}

	@Override
	public String toString() {
		return "Employee [id=" + id + ", first name=" + firstName + ", last name=" + lastName + ", age=" + age + "]";
	}
}

CRUDInterface

package jerry.jacob.mongo.test;

import java.util.List;
import com.mongodb.WriteResult;

public interface CRUDInterface {
	public List getAllObjects();

	public void saveObject(O object);

	public O getObject(String id);

	public WriteResult updateObject(String id, String name);

	public void deleteObject(String id);

	public void createCollection();

	public void dropCollection();
}

CRUDImplementation

package jerry.jacob.mongo.test;

import java.util.List;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import com.mongodb.WriteResult;

public class CRUDImplementation implements CRUDInterface {
	MongoTemplate mongoTemplate;

	public void setMongoTemplate(MongoTemplate mongoTemplate) {
		this.mongoTemplate = mongoTemplate;
	}

	/**
	 * Get all Employees.
	 */
	public List getAllObjects() {
		return mongoTemplate.findAll(Employee.class);
	}

	/**
	 * Saves an Employee.
	 */
	public void saveObject(Employee employee) {
		mongoTemplate.insert(employee);
	}

	/**
	 * Gets an Employee for a particular id.
	 */
	public Employee getObject(String id) {
		return mongoTemplate.findOne(new Query(Criteria.where("id").is(id)),
				Employee.class);
	}

	/**
	 * Updates an Employee name for a particular id.
	 */
	public WriteResult updateObject(String id, String lastName) {
		return mongoTemplate.updateFirst(
				new Query(Criteria.where("id").is(id)),
				Update.update("lastName", lastName), Employee.class);
	}

	/**
	 * Delete an Employee for a particular id.
	 */
	public void deleteObject(String id) {
		mongoTemplate
				.remove(new Query(Criteria.where("id").is(id)), Employee.class);
	}

	/**
	 * Create a Employee collection if the collection does not already exists
	 */
	public void createCollection() {
		if (!mongoTemplate.collectionExists(Employee.class)) {
			mongoTemplate.createCollection(Employee.class);
		}
	}

	/**
	 * Drops the Employee collection if the collection does already exists
	 */
	public void dropCollection() {
		if (mongoTemplate.collectionExists(Employee.class)) {
			mongoTemplate.dropCollection(Employee.class);
		}
	}
}

Spring applicationContext.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
	xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context-3.0.xsd">

	<bean id="employeeRepository"
		class="jerry.jacob.mongo.test.CRUDImplementation">
		<property name="mongoTemplate" ref="mongoTemplate" />
	</bean>

	<bean id="mongoTemplate" class="org.springframework.data.mongodb.core.MongoTemplate">
		<constructor-arg name="mongo" ref="mongo" />
		<constructor-arg name="databaseName" value="nature" />
	</bean>

	<!-- Factory bean that creates the Mongo instance -->
	<bean id="mongo" class="org.springframework.data.mongodb.core.MongoFactoryBean">
		<property name="host" value="localhost" />
		<property name="port" value="27017" />
	</bean>

	<!-- Activate annotation configured components -->
	<context:annotation-config />

	<!-- Scan components for annotations within the configured package -->
	<context:component-scan base-package="jerry.jacob.mongo.test">
		<context:exclude-filter type="annotation"
			expression="org.springframework.context.annotation.Configuration" />
	</context:component-scan>
</beans>

Finally Test it

      public static void main(String[] args) {

		ConfigurableApplicationContext context = new ClassPathXmlApplicationContext(
				"classpath:/applicationContext.xml");

		Repository repository = context.getBean(CRUDImplementation.class);

		// cleanup collection before insertion
		repository.dropCollection();

		// create collection
		repository.createCollection();

		repository.saveObject(new Employee("1", "Jerry", "Jacob", 30));
	}
Tagged with: , , , ,

UTF-8: Encoding Fix

Posted in Java/ J2EE by jerlinworld on December 14, 2009

I was trying to get the non-ascii characters from my property file to render correctly in my jsp file. My original property file was encoded using UTF-8 with the spanish translations for my application. While rendering the page, I was getting a few garbled text instead of pulling the proper spanish text from the property file. Here is the simple fix that I came across after researching on it for the whole day.

1. Made a copy of my original property file, messages_es.properties, and named it messages_es.original.properties
2. Run the file, messages_es.original.properties, through native2ascii to convert the characters to its unicode escape form. Here is the command line for this: native2ascii -encoding UTF-8 ages_es.original.properties messages_es.properties

This fix for the property file resolved my issues.

For more info, you may visit, http://java.sun.com/developer/JDCTechTips/2003/tt0506.html

Navigation while using Tiles with JSF

Posted in Java/ J2EE by jerlinworld on October 15, 2009

I would like to post a tip while using Tiles with JSF. I had to spend a few hours to fix the navigation issue that I experianced while coding my App.

I was using the body tile page for the ‘from-view-id’ element while coding the navigation rule. This is wrong and we should be using the actual page name.

Incorrect value for ‘from-view-id’

<navigation-rule>
		<from-view-id>/tilesContent/index_body.jsp</from-view-id>
		<navigation-case>
			<from-action>#{index.loginAction}</from-action>
			<from-outcome>success</from-outcome>
			<to-view-id>/login.jsp</to-view-id>
		</navigation-case>
	</navigation-rule>

Correct value for ‘from-view-id’

<navigation-rule>
		<from-view-id>/index.jsp</from-view-id>
		<navigation-case>
			<from-action>#{index.loginAction}</from-action>
			<from-outcome>success</from-outcome>
			<to-view-id>/login.jsp</to-view-id>
		</navigation-case>
	</navigation-rule>

Web Service Integration using JXPath

Posted in Java/ J2EE by jerlinworld on August 5, 2009

I was successful in integrating two web services using the JXPath API from Apache. My task was to generate a letter using the data obtained from a third party web service. I had to call another web service to get the letter template and the metadata that’s needed for printing the letter. Since these services were in no way related, I had to create a file; mapping the data items in our web service to the actual data in third party web service (key-value). Using this mapping file along with the JXPath API made the integration a piece of cake.

Now let me explain how the JXPath works. Consider this example:

String city = (String)JXPathContext.newContext(vendor).
         getValue("locations[address/zipCode='90210']/address/city");

This XPath expression is equivalent to the following Java code:

String city = null;
Collection locations = vendor.getLocations();
Iterator it = locations.iterator();
while (it.hasNext()){
    Location location = (Location)it.next();
    String zipCode = location.getAddress().getZipCode();
    if (zipCode.equals("90210")){
      city = location.getAddress().getCity();
      break;
    }
}

In my mapping file, I have my values stored as XPath strings. These XPath values were used to fetch the actual data from the third party web service using the JXPath API.

Querying the ‘IBM Content Manager On Demand’ using ODWEK API

Posted in Java/ J2EE by jerlinworld on July 23, 2009

The IBM Content Manager OnDemand Web Enablement Kit (ODWEK) API’s provide a development environment for client access to Content Manager OnDemand (OD) servers. This API provide access to Servers, Folders, Criteria, and Hits, making it easy for Web application developers to logon, search and retrieve OD content. Here is the code that I used to query the CMOD folder with a specific criteria.

private int validateClaimInfo(final String ssnNumber, final String cDate) {
	final int port = 2345;
	final ODServer odServer = new ODServer(new ODConfig());
	try {
		................. 
		.................
		//Logon to specified server
		odServer.setConnectType(ODConstant.CONNECT_TYPE_TCPIP);
		odServer.setServerName(this.cmodProps.getString("cmod.server") .trim());
		odServer.setPort(port);
		odServer.setUserId(this.cmodProps.getString("cmod.userid").trim());
		odServer.setPassword(this.cmodProps.getString("cmod.password").trim());
		odServer.initialize("ClaimsValidationHelper");
		odServer.logon();
		//Search Folder
		return this.isExistingClaim(odServer, ssnNumber, cDate);
	} catch (final ODException e) {
		if (e.getErrorId() == 2107) {
			this.logger.error("OnDemand server " + odServer.getServerName()  + " is alive but: " + e.getErrorMsg());
		} else {
			this.logger.error(" Error code: " + e.getErrorId()+ "Encountered error: " + e.getErrorMsg());
   		}
  	} catch (final Exception e) {
   		e.printStackTrace();
	} finally {
		try {
    			odServer.logoff();
   		} catch (final Exception e) {
   		}
  		 odServer.terminate();
  	}
  	return 0;
 }
private int isExistingClaim(final ODServer odServer, final String ssnNumber, final String cDate) {
	int isExisting = 0;
	try {
		//Opening the folder specified in the property file...
		final ODFolder folder = odServer.openFolder(this.cmodProps.getString("claimings.folder").trim());
		//Getting specified criteria...
		final ODCriteria odCriteriaSsn = folder.getCriteria(this.cmodProps.getString("criteria.ssn").trim());
		//Setting operand...
		odCriteriaSsn.setOperator(ODConstant.OPEqual);
		odCriteriaSsn.setSearchValue(ssnNumber);
		final ODCriteria odCriteriaCDate = folder.getCriteria(this.cmodProps.getString("criteria.cdate").trim());
		odCriteriaCDate.setOperator(ODConstant.OPEqual);
		odCriteriaCDate.setSearchValue(cDate);
		folder.search();
		this.logger.debug("Search results size: "+ folder.searchCountHits());
		if (folder.searchCountHits() &gt; 0) {
			isExisting = 1;
		}
	} catch (final ODException e) {
		this.logger.error("ODException: " + e.getMessage(), e);
	} catch (final Exception e) {
		this.logger.error("Exception: " + e.getMessage(), e);
	}
	return isExisting;
}

Create PDF and RTF reports using Jasper API

Posted in Java/ J2EE by jerlinworld on July 22, 2009

Using Japer, you can create reports in various formats like CSV file, HTML file, PDF file, RTF file, Excel file, XML file etc. First of all, the report needs to be designed using a report designer. I was using the open source report designing tool called, iReport. You can produce a report using the data from a database, parameters, variable expressions etc. If you are generating the report from a custom class file (DAO), include it in the class path of iReport. Using the iReport designing tool, you’ll be able to create a report as a JRXML/XML file; compile the report creating a new file with extension, .jasper called as ‘Jasper file’. We will be using this Jasper file in our java code.

Download the Jasper API with all its dependent jar’s and invoke the report using the API. Here is a sample to generate PDF and RTF reports. Generating other formats are very similar to this. Here I am using a custom datasource inplemented from JRDataSource for generating the reports. Since I was writing a web service to generate reports, I wasn’t rendering the report but returning the report in byte array. The client progran would use the FileOutputStream to render the report from byte array or could directly feed the byte array to the OutputStream of the HttpServletResponse.

public byte[] buildRtfResume(final String ssnNumber) {
     ResumeEngineImpl.log.debug("Building RTF Resume for " + ssnNumber);
     byte[] rtfResume = null;
     try {
          final Applicant applicant = this.getApplicantBySsn(ssnNumber);
          final JasperPrint jasperPrint = this.renderCV(applicant);
          final JRRtfExporter rtfExporter = new JRRtfExporter();
          final ByteArrayOutputStream rtfStream = new ByteArrayOutputStream();
          rtfExporter.setParameter(JRExporterParameter.JASPER_PRINT,jasperPrint);
          rtfExporter.setParameter(JRExporterParameter.OUTPUT_STREAM,rtfStream);
          rtfExporter.exportReport();
          rtfResume = rtfStream.toByteArray();
     } catch (final JRException e) {
          ResumeEngineImpl.log.error(e.getMessage(), e);
     } catch (final RuntimeException e) {
          ResumeEngineImpl.log.error(e.getMessage(), e);
     }
     return rtfResume;
}
public byte[] buildPdfResume(final String ssnNumber) {
     ResumeEngineImpl.log.debug("Building PDF Resume for " + ssnNumber);
     byte[] pdfResume = null;
     try {
          final Applicant applicant = this.getApplicantBySsn(ssnNumber);
          final JasperPrint jasperPrint = this.renderCV(applicant);
          pdfResume = JasperExportManager.exportReportToPdf(jasperPrint);
     } catch (final JRException e) {
          ResumeEngineImpl.log.error(e.getMessage(), e);
     } catch (final RuntimeException e) {
          ResumeEngineImpl.log.error(e.getMessage(), e);
     }
     return pdfResume;
}

JasperPrint object represents the output, which can be viewed, printed or exported to many different formats.JasperFillManager class is used for report filling process. It takes three arguments to fill a report; Compiled report design, Parameters and Datasources.

public JasperPrint renderCV(Applicant applicant){
     ..........
     ..........
     final JasperReport jasperReport = (JasperReport) JRLoader.loadObject(this.getClass().getClassLoader().getResourceAsStream("jerry/jacob/reports/resume.jasper"));
     final JasperReport empHistSubReport = (JasperReport) JRLoader.loadObject(this.getClass().getClassLoader().getResourceAsStream("jerry/jacob/reports/EmploymentSubReport.jasper"));
     final JasperReport edHistSubReport = (JasperReport) JRLoader.loadObject(this.getClass().getClassLoader().getResourceAsStream("jerry/jacob/reports/EducationSubReport.jasper"));
     .........
     final EmpHistDataSource empHistDataSource = new EmpHistDataSource(empHists);
     final EducationHistDataSource edHistDataSource = new EducationHistDataSource(eduHists);
     .........
     final Map parameters = new HashMap();
     // add sub reports to map
     parameters.put("EmploymentSubReport", empHistSubReport);
     parameters.put("EducationSubReport", edHistSubReport);
     // add data sources to map
     parameters.put("EmploymentDataSource", empHistDataSource);
     parameters.put("EducationDataSource", edHistDataSource);
     return JasperFillManager.fillReport(jasperReport, parameters,applicantDataSource);
}

Making your Spring application, ‘Context Aware’

Posted in Java/ J2EE by jerlinworld on July 20, 2009

Suppose you have some java classes which are unable (or you don’t want it) to be wired to the Spring application context; for example, an auto generated web service client class! But you do want to use the dependency injection feature of Spring to get some of the other beans injected in to this class. How can we make this happen? One way to achieve this would be to use the ApplicationContextAware interface provided by Spring.

Create a class named ApplicationContext which implements  ApplicationContextAware. The inherited method, ‘setApplicationContext(…)’ will get called during the creation of this bean, providing the reference to the context. Our program should store this for a later interaction with the context.

package jerry.jacob;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
public class ApplicationContextProvider implements ApplicationContextAware {
    private static ApplicationContext ctx = null;
    public static ApplicationContext getApplicationContext() {         
        return ctx;    
    }
    public void setApplicationContext(ApplicationContext ctx) throws BeansException {
        // Assign the ApplicationContext into a static method
        this.ctx = ctx;
    }
}

Initialize the new bean in applicationContext.xml

<bean id="applicationContextProvider" class="jerry.jacob.ApplicationContextProvider"></bean>

Now you can call the static method, getApplicationContext(), from any class in your application, to get assess to the Spring ApplicationContext.