Jerry Jacob's Blog

Equinox p2 Repository Mirroring

Posted in eclipse by jerlinworld 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. http://download.eclipse.org/eclipse/updates/3.4milestones/) -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. http://download.eclipse.org/eclipse/updates/3.4milestones/) -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 jerlinworld 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

 	<servlet>
	    <servlet-name>JasperImageServlet</servlet-name>
	    <servlet-class>net.sf.jasperreports.j2ee.servlets.ImageServlet</servlet-class>
	</servlet>
	
	<servlet-mapping>
	    <servlet-name>JasperImageServlet</servlet-name>
	    <url-pattern>/image/*</url-pattern>
	</servlet-mapping>

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">
	                 <value>false</value>
	         </entry>
	         <entry key="net.sf.jasperreports.engine.export.JRHtmlExporterParameter.IS_WHITE_PAGE_BACKGROUND">
	                 <value>false</value>
	         </entry> 
	          <entry key="net.sf.jasperreports.engine.export.JRHtmlExporterParameter.IMAGES_URI">
	             <value>image?image=</value>
	          </entry> 
	</util:map>
	
    	<bean id="roleUsageReport"
          class="com.jerry.util.SpReportsMultiFormatView"
          p:url="/resources/shared/reports/usageAnalytics.jasper"
          p:reportDataKey="datasource"
          p:exporterParameters-ref="exportParameterMap"/>

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 {

	@Override
	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 jerlinworld on December 4, 2013

Find the users connected to Oracle

SELECT
  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:

DECLARE
 tmp_sidserial VARCHAR2(15) := '';
 CURSOR cur_user
 IS
   SELECT b.sid, b.serial#
   FROM v$session b
   WHERE TYPE = 'USER' AND b.username = 'JJACOB'
   ORDER BY sid;
BEGIN
   FOR user_rec in cur_user
   LOOP
      tmp_sidserial := user_rec.sid || ',' || user_rec.serial#  ;
      EXECUTE IMMEDIATE 'ALTER SYSTEM DISCONNECT SESSION ''' || tmp_sidserial || ''' IMMEDIATE';
   END LOOP;
END;
/
Tagged with:

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/)

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: , , , ,

LDAP(Active Directory) based authentication in JBoss Seam

Posted in Java/ J2EE, Uncategorized by jerlinworld 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"
server-address="subdomain.active.directory.org"
server-port="389"
bind-DN="cn=Jacob Jerry,ou=Users,ou=Company,dc=ia,dc=com"
bind-credentials="password"
user-name-attribute="sAMAccountName"
first-name-attribute="givenName"
last-name-attribute="sn"
user-DN-prefix=""
user-DN-suffix="ia.com"
user-context-DN="OU=Users,ou=Company,dc=ia,dc=com"
role-context-DN="OU=Groups,ou=Company,dc=ia,dc=com"
user-role-attribute="memberOf"
role-name-attribute="sAMAccountName"
user-object-classes="person,user,organizationalPerson"
role-object-classes="group"/>

Inject IdentityManager in Authenticator.java
@In(“#{identityManager}”)
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 @ia.com. 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="org.jboss.seam.security.postAuthenticate">
   <action execute="#{authenticator.authenticate}"/>
</event>

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">
    <authentication>
        <login-module code="org.jboss.security.auth.spi.LdapExtLoginModule" flag="required" >
            <module-option name="java.naming.provider.url">ldap://subdomain.active.directory.org:389</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>
        </login-module>
    </authentication>
</application-policy>

JBoss Seam – ConcurrentRequestTimeoutException: Concurrent call to conversation

Posted in Java/ J2EE by jerlinworld 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="#{location.instance.zip}">
   <a:support event="onblur" reRender="zipField" bypassUpdates="true" ajaxSingle="true"/>
   <a:support event="onchange" reRender="longitude,latitude" action="#{location.setGeocode()}"/>
</h:inputText>


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="#{location.instance.zip}">
   <a:support event="onblur" reRender="zipField" bypassUpdates="true" ajaxSingle="true" eventsQueue="default"/>
   <a:support event="onchange" reRender="longitude,latitude" eventsQueue="default" action="#{location.setGeocode()}"/>
</h:inputText>


Own ID Column for the Model in the Play! Framework

Posted in Java/ J2EE, Play Framework by jerlinworld 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.
MySql

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

Oracle

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

Create zip files in Java

Posted in Java/ J2EE by jerlinworld on January 11, 2012

The output of the below Java program will be the creation of a zip file inside c:/ with the name test.zip
Taken from http://extreme-java.com



package com.example;
 
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
 
/** 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://test.zip");
 
		//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
		zipoutStream.putNextEntry(zipEntry);
 
		//write some text into the zip entry created above.
		//Whatever is written will be added to last added zip entry
		zipoutStream.write(1);
 
		//close the zip entry.
		zipoutStream.closeEntry();
 
		//Finish the creation of zip file.
		zipoutStream.finish();
 
		//close the file output stream
		zipFOS.close();
 
		//close the zip output stream
		zipoutStream.close();
	}
}

Create Word Documents Using Jasper API

Posted in Java/ J2EE by jerlinworld 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";
		ResumeEngineImpl.log.entering(ResumeEngineImpl.sourceClass,
				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.JASPER_PRINT,
					jasperPrint);
			docExporter.setParameter(JRDocxExporterParameter.OUTPUT_STREAM,
					docStream);
			docExporter.setParameter(JRDocxExporterParameter.FLEXIBLE_ROW_HEIGHT, Boolean.TRUE);
			docExporter.exportReport();
			docResume = docStream.toByteArray();
		} catch (final JRException e) {
			ResumeEngineImpl.log.logp(Level.WARNING,
					ResumeEngineImpl.sourceClass, sourceMethod,
					"Exception caught:", e);
		} catch (final RuntimeException e) {
			ResumeEngineImpl.log.logp(Level.WARNING,
					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.