Jerry Jacob's Blog

Equinox p2 Repository Mirroring

Posted in eclipse by Jerry Jacob on June 24, 2014

Equinox p2 manages all of its data in repositories. There are two types of repos, artifact and metadata.

The Repository Mirroring applications can be used to mirror artifact and metadata repositories. In addition, users can do selective mirroring of artifacts or metadata either to create a more specific mirror (e.g. only mirror latest code) or merge content into an existing mirror.

Mirroring Metadata

eclipse -nosplash -verbose -application org.eclipse.equinox.p2.metadata.repository.mirrorApplication -source Insert Source URL (e.g. -destination Insert Destination URL (e.g. file:/tmp/3.4milestonesMirror/)

Mirroring Artifacts

eclipse -nosplash -verbose -application org.eclipse.equinox.p2.artifact.repository.mirrorApplication -source Insert Source URL (e.g. -destination Insert Destination URL (e.g. file:/tmp/3.4milestonesMirror/)
Tagged with: , ,

Render Charts in Jasper HTML using Spring

Posted in Java/ J2EE, Uncategorized by Jerry Jacob on January 13, 2014

This is a solution for which I worked for 2 full days searching Google and trying it out by trial and error. The main issue that I was facing was that the charts in my report won’t render in the HTML report, while it was rendering properly in the PDF version.
I would assume that you know how to setup Jasper using Spring. You have to do 4 things to make the graphs appear in your HTML.
1. A new servlet mapping in your web.xml


2. Set the IMAGES_URI parameter in your jasper-view.xml (file where you define your jasper views). The URI path should match the servlet path you defined in web.xml

<util:map id="exportParameterMap">
	         <entry key="net.sf.jasperreports.engine.export.JRHtmlExporterParameter.IS_USING_IMAGES_TO_ALIGN">
	         <entry key="net.sf.jasperreports.engine.export.JRHtmlExporterParameter.IS_WHITE_PAGE_BACKGROUND">
	          <entry key="net.sf.jasperreports.engine.export.JRHtmlExporterParameter.IMAGES_URI">
    	<bean id="roleUsageReport"

3. Extend the JasperReportsMultiFormatView and override the renderReport method as shown below. In this case, I named it com.jerry.util.SpReportsMultiFormatView as you can see in the above xml.

	public class SpReportsMultiFormatView extends JasperReportsMultiFormatView {

	protected void renderReport(JasperPrint populatedReport,
			Map<String, Object> model, HttpServletResponse response)
			throws Exception {
		if (model.containsKey("requestObject")) {
		      HttpServletRequest request = (HttpServletRequest) model.get("requestObject");
		      request.getSession().setAttribute(ImageServlet.DEFAULT_JASPER_PRINT_SESSION_ATTRIBUTE, populatedReport);
		super.renderReport(populatedReport, model, response);


4. In your spring controller, set the ‘requestObject’ in your model.

	JRDataSource JRdataSource = new JRBeanCollectionDataSource(usageList);
	Map<String,Object> parameterMap = new HashMap<String,Object>();
	parameterMap.put("format", "html");
	parameterMap.put("requestObject", req);
        parameterMap.put("datasource", JRdataSource);
        return new ModelAndView("roleUsageReport", parameterMap);

This changes should make the graphs/images render properly in your HTML report.

Oracle – How to find and close connections

Posted in Java/ J2EE, Oracle, Uncategorized by Jerry Jacob on December 4, 2013

Find the users connected to Oracle

  substr(a.spid,1,9) pid,
  substr(b.sid,1,5) sid,
  substr(b.serial#,1,5) ser#,
  substr(b.machine,1,6) box,
  substr(b.username,1,10) username,
  substr(b.osuser,1,8) os_user,
  substr(b.program,1,30) program
FROM v$session b, v$process a
WHERE b.paddr = a.addr
AND type='USER'
ORDER BY spid;

close a specific connection using the above sid and ser#

alter system disconnect session 'sid,ser#' immediate;

Related PL/SQL that I wrote to accomplish this task:

 tmp_sidserial VARCHAR2(15) := '';
 CURSOR cur_user
   SELECT b.sid, b.serial#
   FROM v$session b
   WHERE TYPE = 'USER' AND b.username = 'JJACOB'
   ORDER BY sid;
   FOR user_rec in cur_user
      tmp_sidserial := user_rec.sid || ',' || user_rec.serial#  ;
Tagged with:

Client IP Address in Java

Posted in Java/ J2EE by Jerry Jacob 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. (

Tagged with:

MongoDB with SpringData

Posted in Java/ J2EE by Jerry Jacob 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;


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

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

	public String getId() {
		return id;

	public void setId(String 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;

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


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


package jerry.jacob.mongo.test;

import java.util.List;
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) {

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

	 * 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) {
				.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)) {

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

Spring applicationContext.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns=""
	xmlns:xsi="" xmlns:context=""

	<bean id="employeeRepository"
		<property name="mongoTemplate" ref="mongoTemplate" />

	<bean id="mongoTemplate" class="">
		<constructor-arg name="mongo" ref="mongo" />
		<constructor-arg name="databaseName" value="nature" />

	<!-- Factory bean that creates the Mongo instance -->
	<bean id="mongo" class="">
		<property name="host" value="localhost" />
		<property name="port" value="27017" />

	<!-- 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" />

Finally Test it

      public static void main(String[] args) {

		ConfigurableApplicationContext context = new ClassPathXmlApplicationContext(

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

		// cleanup collection before insertion

		// create collection

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

LDAP(Active Directory) based authentication in JBoss Seam

Posted in Java/ J2EE, Uncategorized by Jerry Jacob on March 13, 2012

Method 1:

Modify your components.xml and add security:identity-manager element and security:ldap-identity-store element.  Authenticator.Authenticate method WILL get called when your user logs in.

<security:rule-based-permission-resolver security-rules="#{securityRules}"/>

<security:identity authenticate-method="#{authenticator.authenticate}" remember-me="true"/>

<security:identity-manager identity-store="#{activeDirectory}"/>

<security:ldap-identity-store name="activeDirectory"
bind-DN="cn=Jacob Jerry,ou=Users,ou=Company,dc=ia,dc=com"

Inject IdentityManager in
IdentityManager identMgr;

and authenticate the user

identMgr.authenticate( credentials.getUsername()+”@”, credentials.getPassword() ));

Why I appended ‘@’ after the username? The user-DN-suffix in my case is actually But it was giving an error in components.xml.


Method 2:

Modify your components.xml and add jaas-config-name attribute to security:identity element.  Normally if you add this attribute authenticate-method attribute will have no effect. But adding a post authenticate event listener action could resolve this issue. Authenticator.Authenticate method WILL get called if you have the action listener specified in here.

<security:identity remember-me="true" jaas-config-name="activeDirectory"/>

<event type="">
   <action execute="#{authenticator.authenticate}"/>

In this method, you will have to define your application policy in the server login-config.xml. You may find your local JBoss login-config.xml in the deployment folder \jboss-eap\jboss-as\server\default\conf. Here is my entry to this file

<application-policy name="activeDirectory">
        <login-module code="" flag="required" >
            <module-option name="java.naming.provider.url">ldap://</module-option>
            <module-option name="bindDN">cn=Jacob\, Jerry,OU=Users,ou=Company,dc=ia,dc=com</module-option>
            <module-option name="bindCredential">password</module-option>
            <module-option name="baseCtxDN">OU=Users,ou=Company,dc=ia,dc=com</module-option>
            <module-option name="baseFilter">(sAMAccountName={0})</module-option>
            <module-option name="rolesCtxDN">OU=Groups,ou=Company,dc=ia,dc=com</module-option>
            <module-option name="roleFilter">(sAMAccountName={0})</module-option>
            <module-option name="roleAttributeID">memberOf</module-option>
            <module-option name="roleAttributeIsDN">true</module-option>
            <module-option name="roleNameAttributeID">cn</module-option>
            <module-option name="searchScope">ONELEVEL_SCOPE</module-option>
            <module-option name="allowEmptyPasswords">false</module-option>

JBoss Seam – ConcurrentRequestTimeoutException: Concurrent call to conversation

Posted in Java/ J2EE by Jerry Jacob on February 17, 2012

This problem is commonly seen in applications that use Ajax in the context of a long-running conversation. If the problem happens when a conversation is still active, it’s because one of the requests could not get a lock on the conversation in the allotted time period. Many developers run into this problem for the first time when using a CRUD application created by seam-gen. This entry explains the problem using the seam-gen application as an example.

Given below the reason why I got this exception:
I made 2 ajax calls one after another.

<h:inputText id="zip" value="#{}">
   <a:support event="onblur" reRender="zipField" bypassUpdates="true" ajaxSingle="true"/>
   <a:support event="onchange" reRender="longitude,latitude" action="#{location.setGeocode()}"/>

The issue can be fixed by serializing the requests sent to the server so that they never contend for the conversation. This can be done using the eventsQueue attribute.
‘eventsQueue’ attribute provide a queue in which events are placed. All events are queued and requests are sent to the server serially. This is useful if the request to the server can take some time to execute (e.g. heavy computation, retrieving information from a slow source)

<h:inputText id="zip" value="#{}">
   <a:support event="onblur" reRender="zipField" bypassUpdates="true" ajaxSingle="true" eventsQueue="default"/>
   <a:support event="onchange" reRender="longitude,latitude" eventsQueue="default" action="#{location.setGeocode()}"/>

Own ID Column for the Model in the Play! Framework

Posted in Java/ J2EE, Play Framework by Jerry Jacob on January 11, 2012

When you create Model entities in the Play! Framework, Play will provide a default id column.  If you need to use your own id column — say if you are given a database schema to work with — then you should extend a different Play class called GenericModel instead of Model class.  In addition to providing an @Id annotation, it also provides @GeneratedValue annotation. Here is its usage both with  Oracle and MySql.

public class Tutorial extends GenericModel {
@GeneratedValue(strategy = GenerationType.AUTO)
public Long tutorial_id;


@GeneratedValue(strategy=SEQUENCE, generator="videoIdSeq")
@SequenceGenerator(name="videoId", sequenceName="video_id_seq", allocationSize=1)
protected Long videoId;

Create zip files in Java

Posted in Java/ J2EE by Jerry Jacob on January 11, 2012

The output of the below Java program will be the creation of a zip file inside c:/ with the name
Taken from

package com.example;
/** This class is a Java tutorial for creating zip file
 * @author Extreme Java
public class Test{
	/** The method creates zip file and also creates an entry inside it
	 * @param args is the command line arguments
	 * @throws IOException 
	public static void main(String[] args) throws IOException  {
		//create a file output stream
		FileOutputStream zipFOS = new FileOutputStream("c://");
		//create a zip output stream from the file output stream created above.
		//zip output stream decorates file output stream
		ZipOutputStream zipoutStream = new ZipOutputStream(zipFOS);
		//creates an zip entry. You can create as many entries as you wish
		//Each entry represent a file with in the zip archive
		ZipEntry zipEntry = new ZipEntry("source1");
		//put the zip entry create above into the zip file
		//write some text into the zip entry created above.
		//Whatever is written will be added to last added zip entry
		//close the zip entry.
		//Finish the creation of zip file.
		//close the file output stream
		//close the zip output stream

Create Word Documents Using Jasper API

Posted in Java/ J2EE by Jerry Jacob on March 9, 2010

All the basics for creating a document using Jasper API remains the same except the Exporter. Please refer to my earlier post to create PDF and RTF reports.

Given below is the code that would return the word document in byte array.
NOTE: You have to use the jasper api version 3.5.x or higher

public byte[] buildDocResume(final String ssnNumber) {

		final String sourceMethod = "buildDocResume";
				sourceMethod, ssnNumber);
		byte[] docResume = null;
		try {
			final Seeker seeker = this.getSeekerBySsn(ssnNumber);
			final JasperPrint jasperPrint = this.renderResume(seeker);

			final JRDocxExporter docExporter = new JRDocxExporter();
			final ByteArrayOutputStream docStream = new ByteArrayOutputStream();
			docExporter.setParameter(JRDocxExporterParameter.FLEXIBLE_ROW_HEIGHT, Boolean.TRUE);
			docResume = docStream.toByteArray();
		} catch (final JRException e) {
					ResumeEngineImpl.sourceClass, sourceMethod,
					"Exception caught:", e);
		} catch (final RuntimeException e) {
					ResumeEngineImpl.sourceClass, sourceMethod,
					"Exception caught:", e);

		return docResume;

Tip: The generated word document will be formatted using several nested tables. If the property, JRDocxExporterParameter.FLEXIBLE_ROW_HEIGHT, is set to false, the table rows do not increase in height automatically and the user has to enlarge them manually in word.