Archive for 2011

Merging PDF files in Java

I was just looking for some way to merge PDFs generated from different sources to one final deck. iText library was one obvious choice but when I looked into PDFBox library I was stunned with the simplicity and ease with which PDFs can be merged. I tried merging three different PDF files and to my surprise it took less than 15 lines of code as shown below:



package com.gognamunish.test;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import org.apache.pdfbox.util.PDFMergerUtility;

/**
 * Merges pdf files into one final pdf.
 * 
 * @author Munish Gogna
 */
public class PDFMerge {

 public static void main(String[] args) throws Exception {
  // Get the byte streams from any source (maintain order)
  List<InputStream> sourcePDFs = new ArrayList<InputStream>();
  sourcePDFs.add(new FileInputStream(new File("pdf1.pdf")));
  sourcePDFs.add(new FileInputStream(new File("pdf2.pdf")));
  sourcePDFs.add(new FileInputStream(new File("pdf3.pdf")));

  // initialize the Merger utility and add pdfs to be merged
  PDFMergerUtility mergerUtility = new PDFMergerUtility();
  mergerUtility.addSources(sourcePDFs);
  // set the destination pdf name and merge input pdfs
  mergerUtility.setDestinationFileName("merged.pdf");
  mergerUtility.mergeDocuments();
 }
}

The library is rich and provides many options out of the box that can be useful when it comes to playing with PDFs, worth a try !!!

http://pdfbox.apache.org/index.html
 cheers, Munish Gogna
Saturday, November 5, 2011
Posted by Munish Gogna

Windows 8 - carbon copy of Apple's business model...all in ones

I am personally not impressed with what Windows 8 has to offer. In short here is the Summary:
  • Responsive start and shut down time - more like Apple devices.
  • Slider UIs copied from iPhone and similar mobile devices.
  • Metro UI - It's boring over time and just gets in the way.
  • Integrated App Store, create an app and sell it for 99 paise :) Finally Microsoft realized the power of developers.
  • Notifications concept copied from Facebook. Blue Screen of Death gets makeover for Windows 8, I am not sure from wehere Microsoft copied “Blue Screen of Death”, any ideas guys?

HOME SCREEN

DESKTOP

CONTROL PANEL

ERRORS
Sunday, September 18, 2011
Posted by Munish Gogna

Performance Analysis for Enterprise Java Applications

Users come to you and shout "Why Trades page is taking too much time to load?" Now you may say because I call Trade Service so it might be taking time to return the response in timely fashion. You approach developer of the Service and ask - Can you please tell how much time is being taken for getTrades(userId) to return trades from database for XYZ user? Developer will say Yes I can - let me check you in the logs as I have put System.currentTimeMillis(); statements in my code as shown below:

public static List<Trade> getTrades(String userId)
			throws TradeServiceException {
		long start = System.currentTimeMillis();
		// separate component running in separate JVM
		authenticate(userId);
		// separate component running in separate JVM
		authorize(userId);

		List<Trade> trades = TradeDao.getTrades(userId);
		long end = System.currentTimeMillis();
		System.out.println("Method took " + ((end - start) / 1000) + " seconds");
		return trades;

	}
As you can see in the code snippet that this method relies on external components (common to all services) for actual task. So answering the question "Why Trades page is slow?" requires investigating multiple components and execution paths, and it requires detailed performance data from all of the application components used. It may be due to poor performance of component that perform authorization for user.

The developer here forgot that the total time printed in logs is basically sum of time taken for authentication, authorization and actual database call. So he may change the code to add few more System.currentTimeMillis(); statements around authenticate and authorize methods to come up with the individual timings for each component (He feels happy and relaxed).

Later on, though, architects find they want more information, such as aggregated performance statistics like mean, minimum, maximum, standard deviation and transactions per second over a set time span. They would like graphs of these values in real time to detect problems on a running server, or they would like to expose performance metrics through JMX so that monitors can be set up to alert when performance degrades. In addition, they want their timing statements to work with the common logging frameworks like log4j (so that they can be enabled and disabled at run time).

Can someone save this developer from pain? The answer is YES - It's Perf4J.
"Perf4J is to System.currentTimeMillis() as log4j is to System.out.println()"

Perf4J provides above features and more:
  • A simple stop watch mechanism for succinct timing statements.
  • A command line tool for parsing log files that generates aggregated statistics and performance graphs.
  • Easy integration with the most common logging frameworks and facades: log4j, java.util.logging, Apache Commons Logging and SLF4J.
  • Custom log4j appenders to generate statistics and graphs in a running application (custom java.util.logging handlers coming soon).
  • The ability to expose performance statistics as JMX attributes, and to send notifications when statistics exceed specified thresholds.
  • A servlet for exposing performance graphs in a web application. Note: that Graphs for average execution time and transactions per second are generated as URLs to the Google Chart Server.

    Let's change our code to use Per4J configured along with log4j
    	public static List<Trade> getTrades(String userId)
    			throws TradeServiceException {
    		StopWatch stopWatch = new Log4JStopWatch();
    		stopWatch.start("TradeService.getTrades");
    		authenticate(userId);
    		authorize(userId);
    		List<Trade> trades = TradeDao.getTrades(userId);
    		stopWatch.stop("TradeService.getTrades");
    		return trades;
    
    	}
    
    As seen above the code is more clean and maintainable. The logs now will be written to log file (e.g. server.log) automatically as shown below:
    INFO  TimingLogger - start[1315017679678] time[1000] tag[getTrades_authenticate]
    INFO  TimingLogger - start[1315017680679] time[1001] tag[getTrades_authorize]
    INFO  TimingLogger - start[1315017681681] time[2000] tag[getTrades_db]
    INFO  TimingLogger - start[1315017679678] time[4003] tag[TradeService.getTrades]
    Note: The logs are self explanatory.
    

    The Performance statistics can be obtained as: java -jar perf4j-0.9.13.jar server.log

    I hope and wish some of us can adapt Per4J sooner or Later !!!

    Have a nice day !!!!
Saturday, September 3, 2011
Posted by Munish Gogna

Maintain your daily Logs with Notepad

Do you wish to keep notes where the notes keep the date automatically? Well here is an awesome trick for you. All you need is notepad.


1) Open a blank notepad file.
2) Type .LOG in all caps at the top and hit enter.
3) Now save the file.
4) After closing the file, reopen it and notice that the date & time is now listed on the second line.
5) Also notice that the cursor is ready for you to start typing on the very next line.
6) Now every time you open it, type something on the next line and then save it, when you reopen it, it will have automatically saved the date and time on the last line.

It keeps a running record of date and time for each save. Now you have a cheap diary! Congrats!

source:centralbeat
Wednesday, August 31, 2011
Posted by Munish Gogna

Sphinx Search Code is available for download...

Hi Today I got an email from roger.xia from China regarding the Sphinx search article i posted few months back, he requested the source code so I uploaded the same on dzone, Any one who is interested in trying Sphinx free text search code can download it from dzone site.


URL - http://java.dzone.com/articles/using-sphinx-and-java






---------------------------------------
Hi , Munish Gogna

I come from china , and i read your article about Sphinx, it was very useful for me, but i can't find the sample source code, can you send me a copy of the sample complete source code to me?
thank u very much !

best wishes.
roger.xia
20110822
---------------------------------------

Monday, August 22, 2011
Posted by Munish Gogna

Task Scheduling in JBoss Server ...

First thing I would like to admit is - Sorry for being away for so long !!!
Next let's quickly move to second thing which is the topic of today's very simple post - scheduling jobs in JBoss :)

In many projects there is a requirement for cron-like task scheduling, be it for batch processing, automatic system maintenance or some other regular job. Few days back I had to create a cron job to sync data from external source to the local database. I was having so many options to implement the functionality like:
  • java.util.Timer
  • EJB Timers
  • Unix Cron jobs
  • Quartz Scheduler
  • Custom Timer
But in the end I settled for a very simple solution (in terms of time it took to implement the whole stuff) that is as effective as anything mentioned above.

org.jboss.varia.scheduler.Scheduler
----------------------------------------
The good thing is, this Scheduler directly invokes a callback on an instance of a user defined class, or an operation of a user specified MBean. Let's say we want to print 'Hello World!' (our so called task) after every 30 seconds from the the time of deployment.
package com.gognamunish.test;
import org.jboss.varia.scheduler.Schedulable;
/**
* Implement Schedulable interface and override perform() function. 
* @author Munish Gogna
*/
public class HelloWorld implements Schedulable
{
    public void perform( Date now, long remainingRepetitions ) {
        System.out.println("Hello World");
    }
}
Next just copy the following mbean definition in /deploy/scheduler-service.xml file of the Jboss profile.

      true
      com.gognamunish.test.HelloWorld
      0
      30000
      -1
      true    

      
   
Once the deployment is done, this task will be called after every 30 seconds, so easy and simple right? We can also pass input parameters to our target class using 'SchedulableArguments' attribute, just make sure you define the right constructor in the class that implements Schedulable interface. e.g If we want to pass the location and environment of the server, we have to add following lines to the mbean definition:
Singapore,Test
 java.lang.String,java.lang.String

HelloWorld class now has to define a constructor as follow:
public HelloWorld (String location, String environment){
 this.location=location;
 this.environment=environment;
}


Note: This example has dependency on scheduler-plugin.jar which can be obtained from /common/lib folder of $JBOSS_HOME (it is sad that it's not available in maven or jboss repository)

Give it a Try !!!!
Sunday, August 7, 2011
Posted by Munish Gogna

Google+ wishlist..



This is what I would like to have in next release of Google+:
1. Robust developer API (Many users get hooked on games like Farmville, and that would not have been possible without the application platform Facebook provides).
2. 'Import Facebook contacts' functionality (otherwise killing Facebook will take years of user attrition)
3. Integration with other Google offerings like Docs so that I can share selected documents with my circles, Latitude integration etc.
4. Less white space in UI (some how Facebook screens look more elegant and eye catching to me)
5. Seamless integration with popular apps like Twitter at least.

I hope that these features except the second one should be ready by end of this Year and then I would definitely think of giving Google+ a Thumbs up !!!

cheers,
Munish Gogna
Sunday, July 3, 2011
Posted by Munish Gogna

Handling alien Java types in XML messages

Most of times we find ourself in situations where the XML instance doesn't fully comply with the available Java types.

Let's define a near real world problem to understand this.

Problem: Need to process XML message coming from some XYZ source we don't have control on( the message format is shown below). As can be seen dob element has value as date of birth for Nikhil but is surrounded by brackets [ and ]. Now if we want to unmarshal this message to Person object than with this limitation we will have to declare dob as String and then provide some more methods to parse date every time we process this XML message.

So what should we do - declare dob as String?


Nikhil
[1986-08-27]


Answer is NO, we can use adapters, how? be patient ..

Let's first define our domain object
// members are public just to keep it short..
@XmlRootElement
@XmlAccessorType(XmlAccessType.FIELD)
public class Person {

 @XmlElement
 public String name;

 @XmlElement
 @XmlJavaTypeAdapter(DateAdapter.class)
 public Date dob;

}
As can be seen above we have declared dob as of type Date only, but how it can be populated with the kind of values we are getting, you got it - yes it is our DateAdapter class who is going to manage this, let's see how:
/**
  * Our custom dob adapter.
  */
 class DateAdapter extends XmlAdapter<String, Date> {
  
  static SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");

  public DateAdapter() {
  }

  @Override
  public String marshal(Date date) throws Exception {
   // while sending message back to the source we will obey its format
   return "[" + format.format(date) + "]";
  }

  @Override
  public Date unmarshal(String dob) throws Exception {
   // remove unwanted characters and build date
   dob = dob.replace("[", "").replace("]", "");
   return format.parse(dob);
  }

 }

Let's unmarshal the message now:

JAXBContext context = JAXBContext.newInstance(Person.class);
  Unmarshaller unmarshal = context.createUnmarshaller();
// employee file is the source of message in this example
  Person person = (Person) unmarshal.unmarshal(new File("employee"));

  Assert.assertEquals("Nikhil", person.name);
  Assert.assertEquals("Wed Aug 27 00:00:00 SGT 1986", person.dob
    .toString());


and marshalling our new Person object works fine too :)

Person person = new Person();
  person.name="Toshi";
  person.dob= format.parse("2010-10-10");
  
  Marshaller marshaller = context.createMarshaller();
  marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
  marshaller.marshal(person, System.out);
// The console output is shown below:

  
      Toshi
      [2010-10-10]
  
This is exactly what we expect, value of dob within brackets. This was just a simple example to demonstrate the power of adapters for handling alien types in Java XML world. Hope you can also use this approach in some of your Projects.

See you later !!!
Saturday, May 14, 2011
Posted by Munish Gogna

Converting JSF <h:dataTable/> to <annaRascla:RajniKant/> table ...



By RajniKant table I mean a readonly table that has all the features (sorting, pagination, searching etc). Most developers who are struck with JSF RI implementation know already how difficult it is to provide all these mentioned features. Suddenly you think of moving to PrimeFaces, RichFaces, BlaBlaFaces etc. but hey stop a while I have something special for you in today's post.

In the next section I will try to convert one simple <h:datatable> to <annaRascla:RajniKant> table as per the description of Rajnikant table.

Let's assume we have an existing JSF data table as shown below and suddenly there is a requirement to provide pagination and sorting capabilities.


   

The table looks exactly same as shown below:

Nothing fancy :(, lets move to make it live.

We will use DataTables plug-in for the jQuery Javascript library to make it happen.

  
  
  
  
 
 
  
   
Points to note
  • The tags htmlhead and htmlbody shown above correspond to usual HEAD and BODY tags of html language (Blogger doesn't allow these tags)
  • The reason for not using table id (form:mytable) in ready(function) is that Datatables plugin doesn't accept id of the table having colon in the name itself :( and we all know that JSF generates Ids like this, so how I provide the id of my table? Simple provide the unique class name of that element :)
  • Use this approach if the table is not very large, for large tables you can use ajax capabilities of the plugin, check Project's home page for more details.
  • All the resources above (css and js) come from the artifacts we downloaded earlier
Having made these changes, let's see how our simple table looks now:


The only word that come to my mind is WOW, as can be seen it has:

> Sorting feature
> Pagination feature
> Search feature
> Simple and clean design

Thanks everyone.
Posted by Munish Gogna

Building RESTful WS with JAX-RS (Jersey) and Tomcat

This post is dedicated to my friend jagdish salgotra who wanted me to write something on RESTful web services and to all starters in this area.

In the REST(REpresentational State Transfer) world, information on the server side is considered a resource, which anyone can access in a uniform way using web URIs (Uniform Resource Identifiers) and HTTP. Because REST uses HTTP as the communication protocol, the REST style is constrained to a stateless client/server architecture. We can map the HTTP methods POST, GET, PUT, and DELETE to create, read, update and delete (CRUD) operations.

There are many ways to write RESTful web services:
> Sun offers a reference implementation for JAX-RS code-named Jersey.
> Spring provides RestTemplate for the same purpose

In this sample example (very basic and naive just to give u all a gentle kick) I will try to explain how we can use DEPARTMENT as representational state in REST using GET method. We will try to map following urls to the particular state we are interested in using Jersey implementation.

/api/departments/Get all departments
/api/departments/{id}Get details of a particular department
/api/departments/employeesGet all departments with employee details
/api/departments/{id}/employeesGet employees of particular department

NOTE: All employees related data will be available under department node (by design)

The output of the Restful web services can be a plain text, html, xml, json or any media type, For our example We will use XML as content type of our service output and will rely on JAXB annotations to provide the required marshaling/unmarshaling services.

Let's start with the root XML element. I chose to call mine GetDepartmentResponse, and use it as a container for a collection of Department objects. This is just to do with the convention I usually follow (no hard fast rules behind this).
package com.mg.rest.hr.resources;

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

import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement
public class GetDepartmentResponse {

 private List<Department> departments;

 @XmlElement(name = "department")
@XmlElementWrapper(name = "departments")
 public List<Department> getAllDepartments() {
  if (departments == null) {
   departments = new ArrayList<Department>();
  }
  return departments;
 }

}

Notice the @XmlElementWrapper annotation on the Department collection. This makes JAXB wrap all of the department XML elements inside of an departments XML element. Also notice that I placed the @XmlElement annotations on the getter methods instead of on the private fields. When placed on the private fields, JAXB will give you an error unless you add @XmlAccessorType(XmlAccessType.FIELD) at the class level.

Next we define our Resources - Department and Employee

package com.mg.rest.hr.resources;

import java.util.List;

import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlElementWrapper;
import javax.xml.bind.annotation.XmlType;

/**
 * 
 * @author Munish Gogna
 *
 */
@XmlType(name = "department")
public class Department {

 private String deptId;
 private String deptName;
 private List<Employee> employees;

 public Department() {
 }

 @XmlElement
 public String getDeptId() {
  return deptId;
 }

 @XmlElement(name = "employee")
 @XmlElementWrapper(name = "employees")
 public List<Employee> getEmployees() {
  return employees;
 }

 @XmlElement
 public String getDeptName() {
  return deptName;
 }

 public void setDeptId(String deptId) {
  this.deptId = deptId;
 }

 public void setEmployees(List<Employee> employees) {
  this.employees = employees;
 }

 public void setDeptName(String deptName) {
  this.deptName = deptName;
 }

}

In the example above, we use @XmlType at the class level instead of @XmlRootElement because it is not the root element

package com.mg.rest.hr.resources;

import java.math.BigDecimal;

import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlType;

/**
 * 
 * @author Munish Gogna
 * 
 */
@XmlType(propOrder = { "empId", "empName", "salary" })
public class Employee {

 private String empId;
 private String empName;
 private BigDecimal salary;

 public Employee() {
 }

 public Employee(String empId, String empName, BigDecimal salary) {
  super();
  this.empId = empId;
  this.empName = empName;
  this.salary = salary;
 }

 @XmlElement
 public BigDecimal getSalary() {
  return salary;
 }

 @XmlElement
 public String getEmpId() {
  return empId;
 }

 @XmlElement
 public String getEmpName() {
  return empName;
 }

 public void setEmpId(String empId) {
  this.empId = empId;
 }

 public void setEmpName(String empName) {
  this.empName = empName;
 }

 public void setSalary(BigDecimal salary) {
  this.salary = salary;
 }

}


Now lets create a JAX-RS RESTful web service that can return above defined object graph in the responses we have defined in the beginning of this article.

JAX-RS defines a resource as any Java class (POJO) that uses JAX-RS annotations to implement a web resource. The annotation @Path identifies a Java class as a resource class as shown below.

package com.mg.rest.hr;

import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;

import com.mg.rest.hr.resources.Department;
import com.mg.rest.hr.resources.GetDepartmentResponse;

/**
 * Service to handle Department and related resources.
 * Just a mock implementation, nothing fancy.
 * @author Munish Gogna
 *
 */
@Path("/api")
public class DepartmentResource {

 @GET
 @Produces("text/xml")
 @Path("/departments/employees")
 public GetDepartmentResponse getAllDepartmentsWithEmployees() {
  GetDepartmentResponse response = new GetDepartmentResponse();
  response.getAllDepartments().addAll(
    FromHeaven.getDeptsWithEmps().values());
  return response;
 }

 @GET
 @Produces("text/xml")
 @Path("/departments/{id}")
 public GetDepartmentResponse getDepartment(@PathParam("id") String id) {
  GetDepartmentResponse response = new GetDepartmentResponse();
  Department dept = FromHeaven.getDepts().get(id);
  response.getAllDepartments().add(dept);
  return response;
 }

 @GET
 @Produces("text/xml")
 @Path("/departments/{id}/employees")
 public GetDepartmentResponse getEmployeesForDepartment(
   @PathParam("id") String id) {
  GetDepartmentResponse response = new GetDepartmentResponse();
  Department dept = FromHeaven.getDeptsWithEmps().get(id);
  response.getAllDepartments().add(dept);
  return response;

 }

 @GET
 @Produces("text/xml")
 @Path("/departments")
 public GetDepartmentResponse getAllDepartments() {
  GetDepartmentResponse response = new GetDepartmentResponse();
  response.getAllDepartments().addAll(FromHeaven.getDepts().values());
  return response;

 }
}


Notice the @Produces("text/xml") annotation, and that the method returns a GetDepartmentResponse object. Since the GetDepartmentResponse is annotated with JAXB annotations, JAX-RS will automatically marshal the response to XML.
Also note that FromHeaven is a utility class that provides dummy departmental data(This class has 2 hard coded departments D1 and D2 with 2 employees in D1 and only single employee in D2)

Let's try some URIs now:

1. http://localhost:8080/rest/api/departments

 
  
   D2
   Human Resource
  
  
   D1
   Finance
  
 


2. http://localhost:8080/rest/api/departments/D1

 
  
   D1
   Finance
  
 


3. http://localhost:8080/rest/api/departments/employees

 
  
   D1
   Finance
   
    
     e1
     Munish Gogna
     1000
    
    
     e2
     Jagdish Salgotra
     2000
    
   
  
  
   D2
   Human Resource
   
    
     e3
     Sahil Gogna
     5000
    
   
  
 


4.http://localhost:8080/rest/api/departments/D1/employees

 
  
   D1
   Finance
   
    
     e1
     Munish Gogna
     1000
    
    
     e2
     Jagdish Salgotra
     2000
    
   
  
 


In order for Jersey to work, we need to configure the JAX-RS Servlet in the web.xml as shown below:


 
  com.mg.rest.hr
  JAX-RS REST Servlet
  com.sun.jersey.spi.container.servlet.ServletContainer
  
   com.sun.jersey.config.property.packagescom.mg.rest.hr
  1
 
 
  JAX-RS REST Servlet
  /*
 


Notice that we have to provide the package name (com.mg.rest.hr) of the resource handler classes to the servlet class.

That's all for now, later some day we will try make these RESTful services secure so that only authorized callers can use these resources.

Please don't forget to provide your valuable feedback, especially you Jagi :)
Sunday, May 8, 2011
Posted by Munish Gogna

Saving ENUM values as String in database using JPA

First of all nothing very fancy or technical about this post :)

Let's say you have an enum declaration as shown below and you want to store these values as String (not the evil ordinals) in the database:

public enum UserSex {
 MALE, FEMALE, UNKNOWN
}

To save this enum as String in database, the table where this enum is referenced should declare a column of type varchar as shown below:
`user_sex` varchar(255) DEFAULT NULL

The entity (say User) should use this enumeration as shown below:

@Entity
@Table(name = "user")
public class User {

private Integer id;
private UserSex userSex;

@Id
public Integer getId() {
 return id;
}

@Enumerated(EnumType.STRING)
 @Column(name ="user_sex")
 public UserSex getUserSex() {
  return userSex;
 }

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

 public void setUserSex(UserSex userSex) {
  this.userSex = userSex;
 }

That's all. Now if you want to load all MALE users, you can use this column in JPA queries as

public List<User> getAllMaleUsers() {
  return entityManager.createQuery(
    "select user from User as user where user.userSex=:userSex")
    .setParameter("userSex", UserSex.MALE).getResultList();
 }

Please note that this will work only in case you have complete control on the database side, in case the column is declared as integer or varchar having length say 1 then you will have to write your own converter or fall back to evil ordinal().

NOTE: I'm guessing but I'm pretty sure that for using ENUM as String hibernate 3.2+ is required. So if anyone out there is interested in knowing my POM dependencies then here are they (specific to JBOSS AS 5.1.0 deployment)


   
javaee
   javaee-api
   5
   compile
  
  

   javax.persistence
   ejb3-persistence
   1.0
   provided
  
  
   org.hibernate
   hibernate-entitymanager
   3.3.1.ga
   
    
     javax.persistence
     persistence-api
    
    
     jboss
     jboss-common-core
    
    
     jboss
     javassist
    
   
  
Sunday, May 1, 2011
Posted by Munish Gogna
Tag : ,

Ready made Template for J2EE project (EJB+JPA+Hibernte+Richfaces) deployed on Jboss AS 5.1.0.GA


This project will serve as a ready made template for all who want to use EJB3, JPA, Hibernate and JSF (Richfaces) in their project deployed over JBoss AS 5+ version.
Who Can use this template?
  • All who want to use above technology stack for the very first time in their new Project.
  • All who want to migrate to JBoss AS from glassfish or tomcat or any other server.
  • All new comers to Java for learning purpose so that they can make maximum out of it.
For more details checkout http://code.google.com/p/template4all/
Sunday, April 17, 2011
Posted by Munish Gogna

Thanking Anna Hazare through JBOSS e-mail Service...

Hi everyone, First of all thanks to Anna Hazare and all who have really fought for lokpal bill.

Today's article is about sending Thanks email to Anna Hazare for his tremendous dedication towards our great nation, it's about setting up SMTP server to send emails from your application hosted on JBOSS Application server.


The focus will be on the Anna Hazare and Jboss setup rather than providing a full fledged Email Service.


Our application will be sending emails over gmail SMTP server.
Please pay attention to comments from now onwards through out this article. :)

Maven dependency : Here is a skelton of our maven project.

 4.0.0
 com.mg.poc.email
 JbossMail
 0.0.1-SNAPSHOT
 ejb
 A Simple project to send Emails using Gmail (service running in JBOSS) 

 
  
   Munish Gogna
   gognamunish@gmail.com
   www.twitter.com\munishgogna
  
 

 
 
  
   javaee
   javaee-api
   5
   provided
  

 
 

  ${basedir}/src
  
   
    ${basedir}/src
    
     **/*.java
    
   
  
  
   
    org.apache.maven.plugins
    maven-ejb-plugin
    
     3.0
    
   
   
    maven-compiler-plugin
    
     1.5
     1.5
    
   
  
 




STEP 1 Define our Gmail based SMTP mail service that we will use in our sample application.

SERVER\deploy\mail-service.xml : Create the service definition as shown below:



  
  
  

  
    java:/GMail
    gognamunish@gmail.com
    
    XXXXXX
    
      
       
            
            
      
      
      
            
            
         
    
    jboss:service=Naming
  

After placing this file in deploy folder, you should see following logs in server.log
15:40:49,985 INFO [MailService] Mail Service bound to java:/GMail

STEP 2 Let's build our sample EJB based application that will consume this service to send emails, time to define our remote interface.

package com.mg.poc.email;

import javax.ejb.Remote;

/**
 * Simple interface for our Mail Service.
 * 
 * @author Munish Gogna
 * 
 */
@Remote
public interface MailSender {

 /**
  * Sends mail using GMAIL Service.
  * 
  * @param envelope
  *            envelope to send
  */
 void sendMail(MailEnvelope envelope) throws GmailException;

}

The Envelope class is a simple class that holds regular stuff we need to send email. It is defined as :

package com.mg.poc.email;

import java.io.Serializable;

/**
 * Contains regular email stuff (with some defaults).
 * 
 * @author Munish Gogna
 *
 */
public class MailEnvelope implements Serializable {

 private static final long serialVersionUID = 1L;
    
 private String subject ="thanks Anna Hazare";
 private String to;
 private String from ="gognamunish@gmail.com";
 private String body ="Anna you are great. We the people of india have won the 1st step against the Govt. & feeling real freedom only Bcoz of you. - love you !!!!";

 /** setters/getters omitted */

}
Now as we have defined the interface for our Email Service, let's provide the implementation of the same.
package com.mg.poc.email;

import javax.annotation.Resource;
import javax.ejb.Stateless;
import javax.mail.Address;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.Message.RecipientType;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

/**
 * Bean to manage simple email functionality.
 * 
 * @author Munish Gogna
 * 
 */
@Stateless
public class MailService implements MailSender {

 /**
  * This resource is defined in mail-service.xml file.
  */
 @Resource(mappedName = "java:/GMail", description = "jndi mapping for our simple mail service")
 Session mailSession;

 public void sendMail(MailEnvelope envelope) throws GmailException {
  
  if(envelope == null){
   throw new GmailException("envelope is null");
  }
  
  Message simpleMessage = new MimeMessage(mailSession);

  try {
   simpleMessage.setFrom(createInternetAddress(envelope.getFrom()));
   simpleMessage.setRecipient(RecipientType.TO, createInternetAddress(envelope.getTo()));
   simpleMessage.setSubject(envelope.getSubject());
   simpleMessage.setText(envelope.getBody());

   Transport.send(simpleMessage);
  } catch (MessagingException e) {
   throw new GmailException(e.getMessage());
  }

 }

 private Address createInternetAddress(String address) throws GmailException {
  try {
   return new InternetAddress(address);
  }catch (AddressException e) {
   throw new GmailException(e.getMessage());
  }
 }

}

That's all we are done.
> Generate jar - mvn clean install
> copy JbossMail-0.0.1-SNAPSHOT.jar to deploy folder.
> server logs should show binding of our EJB Stateless session beans as shown below:

15:41:33,403 INFO [EJBContainer] STARTED EJB: com.mg.poc.email.MailService ejbName: MailService
15:41:33,412 INFO [JndiSessionRegistrarBase] Binding the following Entries in Global JNDI:

MailService/remote - EJB3.x Default Remote Business Interface


Finally we will test the service to make sure it actually sends email.

package com.mg.poc.email.test;

import java.util.Properties;

import javax.naming.Context;
import javax.naming.InitialContext;

import com.mg.poc.email.MailEnvelope;
import com.mg.poc.email.MailSender;

/**
 * Simple Test.
 * 
 * @author Munish Gogna
 * 
 */
public class TestMail {

 public static void main(String[] args) throws Exception {
  Properties properties = new Properties();

  properties.put("java.naming.factory.initial",
    "org.jnp.interfaces.NamingContextFactory");
  properties.put("java.naming.factory.url.pkgs",
    "org.jboss.naming:org.jnp.interfaces");
  properties.put("java.naming.provider.url", "localhost");
  Context context;
  try {
   context = new InitialContext(properties);
   MailSender beanRemote = (MailSender) context
     .lookup("java:MailService/remote");

   MailEnvelope envelope = new MailEnvelope();
   envelope.setTo("anna.hazare@gmail.com");

   beanRemote.sendMail(envelope);
   System.out.println("mail sent successfully !!!");
  } catch (Exception e) {
   e.printStackTrace();
  }
 }
}
Note : In case you want to run this client, make sure you add all the required client libraries in the classpath, do one thing add all jars in JBOSS_HOME/client folder to classpath OR try adding following dependency in the pom file.


jboss
jbossall-client
${jboss.version}
${jboss.home}/client/jbossall-client.jar
system

Creating client jars and managing dependencies\jndi lookups can be nightmare sometimes, not some times but most of the times, please do share your thoughts on the same.

To end discussion on this topic I would once again like to thank everyone who stood with Hazare to fight against corruption.

Thanks.
Saturday, April 9, 2011
Posted by Munish Gogna

Wanna play 'Sheela ki Jawani' when something erroneous happens in your Code??

This post is in continuation of my earlier post - "using log4j for various logging events"

We all are familiar with log4j (if you are not then you can read out here). We all know about different types of appenders available like - File Appender, Console Appender, JDBC Appender, Socket Appender, Telnet Appender etc., but most of us might not know that there is another 'Sound Appender' available which can play wav sound formats when configured log events are fired during runtime.


SoundAppender is a another Log4J appender which play an audio clip created using Applet.newAudioClip when an logging event is received. You can use filters in combination with this appender to control when the appender is trigger.

Let's configure a sample maven Project to test Sound Appender:

 4.0.0

 com.mg.log4j.sound
 log4j_sound
 0.0.1-SNAPSHOT
 jar

 log4j_sound
 http://maven.apache.org
 
  
   Munish Gogna
   http://gognamunish.blogspot.com
   gognamunish@gmail.com
   +8:00 GMT
  
 

 
  UTF-8
 

 
  
   log4j
   apache-log4j-extras
   1.0
  
  
   junit
   junit
   4.0
   test
  
 

Next we will define the SoundAppender in log4j.xml as shown below:


 
  
   
 

 
  
 


SoundAppender 'gameOver' takes a parameter called audioURL (url of the audio file which will be played). LevelMatchFilter decides whether to accept the LoggingEvent or not, I have configured this logger to accept only ERROR event. Now, that we have configured SoundAppender in log4j.xml, we should add log statement in a Java class and see what happens:

package com.mg.log4j.sound;

import org.apache.log4j.Logger;

/**
 * Game Over Man !!!
 * 
 */
public class SoundAppender {

 private static Logger log = Logger.getLogger(SoundAppender.class);

 public static void main(String[] args) throws Exception {
  try {
   somethingSilly();
  } catch (GameOverException e) {
   log.error("Game over man... game over !!!");
   // just to let sound complete
   Thread.sleep(10000);

  }
 }

 private static void somethingSilly() throws GameOverException {
  System.out.println("Doing some silly work !!!");
  throw new GameOverException();
 }

 static class GameOverException extends Exception {
  private static final long serialVersionUID = 1L;

  GameOverException() {
   super();
  }
 }
}

Naturally any one's game will be over when something very serious happens in production, so if you have written some code that can fail in near future you must run this code :)

Now, each time you run this class a sound clip will be played at the log statement.
Now only thing that you need to do is replace audioURL in log4j.xml to point to 'sheela ki jawani.wav' that you might have on your computer somewhere (or can download it from here also)

That's all. Enjoy Sheela ki Jawani with log4j.
Saturday, January 22, 2011
Posted by Munish Gogna

Accessing Social Network using 'Spring Social' and 'Scribe' APIs

Few days back I came across Spring social API library developed to access social networking sites from within the Java programs and finally Today I got chance to explore it :)

The current milestone includes templates for Twitter, Facebook and LinkedIn. These templates provide an easy way to access each social networking site and make integrating with those sites relatively straight forward. Each of these templates extend Spring's RestTemplate which is a generic template for accessing REST based web services. All hard core fans of Spring's JDBCTemplate and HibernateTemplate will love this.

To use Spring social:
1. Set up developer account with target social networking site.
2. Request an OAuth token from the target social networking site for each new user.
3. Use the right Spring Source template (e.g TwitterTemplate), passing in the developer keys (ApiKey and ApiSecret) as well as OAuth key for the current user.
4. Thats all :)

Once authorized, the application code required to access any given social site is very easy, so easy that even MBA guy can do it!

Check it out:
//Get Twitter template
TwitterTemplate twitter = new TwitterTemplate(apiKey, apiSecret, accessToken, accessTokenSecret);
twitter.updateStatus("Hey, I'm tweeting with #Spring Social! wow");

//Get Facebbook template
FacebookTemplate facebook = new FacebookTemplate(accessToken);
facebook.updateStatus("Hey, I'm posting with #Spring Social! wow");

//Get LinkedIn template
LinkedInTemplate template = new LinkedInTemplate(apiKey, apiSecret, accessToken, accessTokenSecret);
List <linkedinprofile> connections = template.getConnections(); 


The OAuth authorization part is not as clean as I would have liked. SpringSource has created a reference implementation called Greenhouse to demonstrate how to use the API.

Don't know what is OAuth?
So what is up with this OAuth. In just a few words, it is an authentication service. As an application you forward a visitor to the authentication service. The visitor authenticates itself and your application receives the result using a callback. If the result is positive, the visitor has authorized your application to act on the behalf of the visitor. That way you can use services of the provider without knowing who you are dealing with. It is also possible to store the provided authentication for future use (Greenhouse has this featute).

However we can also use some other OAuth libraries to avoid complexities in GreenHouse API and then just use the REST-like APIs of each service by directly manipulating URLs. The most interesting, easy to use and simple I found is Scribe, its a cool API that provides support for Facebook, Google ,Yahoo, LinkedIn, Twitter, Foursquare, Evernote, Vimeo and Yammer.

The latest version is 1.0.9 that should include Facebook API (as per GitHub), as of now this change is not available for 1.0.9 version in maven, I built it manually getting source from github repository.
You can pull scribe from a maven repository, just add this to your pom.xml file.

org.scribe
scribe
1.0.9


Now its time to create the OAuthService object
The OAuthService is the one you use to sign your requests. You create it using Scribe’s ServiceBuilder like shown below.

You can use the Facebook 'SpringSocialAPI' app that I created, details are:
Application ID: 175348469171013
Application Secret: c3301704fdd6da30b5b8ab68f9808b09

String apiKey = "c97dc03050b89baf893347f40f177d55";
    String apiSecret = "c3301704fdd6da30b5b8ab68f9808b09";
    OAuthService service = new ServiceBuilder()
                                  .provider(FacebookApi.class)
                                  .apiKey(apiKey)
                                  .apiSecret(apiSecret)
                                  .callback("http://localhost:8080/social/callback.jsp")
                                  .build();
The token will be generated and will be available on the mentioned callback url.

You need to get a request token, like this:
Token requestToken = service.getRequestToken();
String your_token = requestToken.getToken();

Now go authorize it! for this make a request to the authorize url (this varies between apis).
For Facebook this is it: https://graph.facebook.com/me?oauth_token=YOUR_TOKEN_HERE

Thanks, see u soon!!!
Sunday, January 16, 2011
Posted by Munish Gogna

Understanding Basic Financial System..

From a bird’s eye any financial system looks like as shown below (self explanatory):


In any Financial system we have Accounts, Portfolios, Positions, Orders, and Transaction etc. Let's understand these in details.

EQUITY
The term's meaning depends very much on the context. In finance, in general, you can think of equity as ownership in any asset after all debts associated with that asset (A resource with economic value that an individual, corporation or country owns or controls with the expectation that it will provide future benefit) are paid off. For example, a car or house with no outstanding debt is considered the owner's equity because he or she can readily sell the item for cash. Stocks are equity because they represent ownership in a company.
What Does Equity mean in different context?
1. A stock or any other security representing an ownership interest.
2. on a company's balance sheet, the amount of the funds contributed by the owners (the stockholders) plus the retained earnings (or losses). It is also referred to as "shareholders' equity".
3. In the context of real estate, the difference between the current market value of the property and the amount the owner still owes on the mortgage. It is the amount that the owner would receive after selling a property and paying off the mortgage.
4. In terms of investment strategies, equity (stocks) is one of the principal asset classes. The other two are fixed-income (bonds) and cash/cash-equivalents. These are used in asset allocation planning to structure a desired risk and return profile for an investor's portfolio. 


ACCOUNTS
What Does Account Mean?
1. An arrangement by which an organization accepts a customer's financial assets and holds them on behalf of the customer at his or her discretion.
 2. A statement summarizing the record of transactions in the form of credits, debits, accruals and adjustments that have occurred and have an affect on an asset, equity, liability or past, present or future revenue.
 3. A relaying of happenings from one party to another.
Account may also have sub accounts:
A sub account is often used to compartmentalize larger accounts, thereby allowing for better tracking of various budget details and expenses. For example, a company might set up sub accounts for each of its departments for ease of record keeping.
Account Types:
Accounts can be of various types and I am sure most of us are aware of at least two very common types saving and current. We can have other types also like:
  • Joint Account – Account having multiple owners.
  • Cash Account: The basic account where you deposit cash to buy stocks, bonds, mutual funds, etc. 
  • Margin Account: - Margin basically allows you to borrow from your broker against the cash and securities in your account. Profits can diminish quickly when you use margin, so be very careful!
  • Forex Account etc.

PORTFOLIO
In simple words a portfolio is a collection of investments held by an institution or an individual. Before we dive into more details it is very important to understand risk-limiting strategies called Diversification and Hedging.

In finance, diversification means reducing risk by investing in a variety of assets. The simplest example of diversification is provided by the proverb "don't put all your eggs in one basket". Dropping the basket will break all the eggs. Placing each egg in a different basket is more diversified. There is more risk of losing one egg, but less risk of losing all of them. In finance, an example of an undiversified portfolio is to hold only one stock. This is risky; it is not unusual for a single stock to go down 50% in one year. It is much less common for a portfolio of 20 stocks to go down that much, even if they are selected at random. If the stocks are selected from a variety of industries, company sizes and types (such as some growth stocks and some value stocks) it is still less likely.

Hedging
Making an investment to reduce the risk of adverse price movements in an asset is called hedging. The best way to understand hedging is to think of it as insurance. When people decide to hedge, they are insuring themselves against a negative event. This doesn't prevent a negative event from happening, but if it does happen and you're properly hedged, the impact of the event is reduced. So, hedging occurs almost everywhere, and we see it everyday. For example, if you buy house insurance, you are hedging yourself against fires, break-ins or other unforeseen disasters. If you take LIC policy, you are hedging your family’s dependency on you (in terms of money matters only).
Another classical example is if you are married and are in Singapore then you would like your partner to also earn some money to hedge against your job loss J
Investors use this strategy when they are unsure of what the market will do. A perfect hedge reduces your risk to nothing (except for the cost of the hedge).
If you are reading these lines it means you have now understanding of why an account will have different portfolios. It is as simple as it can get - avoid risk and make more profits.
Any portfolio could include these assets - bank accountsstocksbondsoptionswarrantsgold certificatesreal estatefutures contracts, production facilities, or any other item that is expected to retain its value. All these assets belong to a specific class, let’s understand asset classification now.

ASSET CLASS 
A group of securities that exhibit similar characteristics, behave similarly in the marketplace, and are subject to the same laws and regulations. The three main asset classes are equities (stocks), fixed-income (bonds) and cash equivalents (money market instruments).
It should be noted that in addition to the three main asset classes, some investment professionals would add real estate and commodities, and possibly other types of investments, to the asset class mix. Whatever the asset class lineup, each one is expected to reflect different risk and return investment characteristics, and will perform differently in any given market environment.
Sub-Asset Class
more specific holdings of a general category of assets. A sub-asset class is a collection of assets that have common characteristics within both the asset class and the sub-asset class. For example, stock is an asset class, and large-capitalization stock is a sub-asset class.

POSITIONS
Before we move to Positions lets understand these terms:
Securities: In finance, a security is a fungible, negotiable instrument representing financial value. Securities are broadly categorized into debt securities (such as bonds and debentures) and equity securities, e.g., common stocks; and derivative contracts, such as forwards, futures, options and swaps.
Bonds/Debentures: As discussed earlier, there are a whole host asset classes that are available for investors. A bond is one of them to meet the financial goals of the respective investors. A bond is a debt security or an obligation to repay money. Bonds are usually considered as fixed-income securities because they carry a fixed rate of interest. Bonds provide a steady stream of cash flows to the bondholders. Typically, interest is paid by the issuer at half-yearly intervals. Governments issue bonds to raise money for spending on infrastructure projects or for their day-to-day expenditure. Likewise, companies also raise money through bonds to meet their capital expenditure or working capital needs. In the Indian Securities Market, the term ‘bonds’ is generally used for debt instruments issued by the Central and State Governments and public sector organizations; and the term ‘debentures’ is used for debt instruments issued by the private corporate sector. However, the terms bonds, debentures, and debt instruments are used by the general public inter-changeably. There are two features that set bonds apart from equity investments. First, the promised cash flows on a bond (that is, the coupon payments and the face value of the bond) are usually set at issue and do not change during the life of the bond. Even when they do change, as in floating rate bonds, the changes are generally linked to changes in interest rates. Second, bonds usually have fixed lifetimes, unlike stocks; since most bonds specify a maturity date (perpetual bonds are exception since they do not carry any maturity date).
Yield - The yield on an investment is loosely defined as the income one earns on it as a percentage of what one spent on it. The crucial piece of information to know in order to compare a bond with other potential investments is its ‘yield’, calculated by dividing the amount of interest it will pay during a year by its price.
Futures -  In finance, a futures contract is a standardized contract between two parties to buy or sell a specified asset (e.g. oranges, oil, gold) of standardized quantity and quality at a specified future date at a price agreed today (the futures price). The contracts are traded on a futures exchange. Futures contracts are not "direct" securities like stocks, bonds, rights or warrants. They are still securities, however, though they are a type of derivative contract. The party agreeing to buy the underlying asset in the future assumes a long position, and the party agreeing to sell the asset in the future assumes a short position.
Forwards - In finance, a forward contract or simply a forward is a non-standardized contract between two parties to buy or sell an asset at a specified future time at a price agreed today. This is in contrast to a spot contract, which is an agreement to buy or sell an asset today. It costs nothing to enter a forward contract. The party agreeing to buy the underlying asset in the future assumes a long position, and the party agreeing to sell the asset in the future assumes a short position.
Note: Future contracts are very similar to forward contracts, except they are exchange-traded and defined on standardized assets.

Let’s understand what is Position?
Position - In financial trading, a position is a binding commitment to buy or sell a given amount of financial instruments, such as securities, currencies or commodities, for a given price.
The term "position" is also used in the context of finance for the amount of securities or commodities held by a person, firm, or institution, and for the ownership status of a person's or institution's investments.
There are two basic types of position: a long and a short. Net position is the difference between total open long (receivable) and open short (payable) positions in a given assets (security, foreign exchange currency, commodity, etc...) held by an individual. This also refers the amount of assets held by a person, firm, or financial institution as well as the ownership status of a person's or institution's investments.

ORDERS
An order in a market such as a stock marketbond marketcommodity market or financial derivative market is an instruction from customers to brokers to buy or sell on the exchange.
The Orders relate to buying and selling of stocks in the Stock market. However, before you can start buying and selling stocks, you must know the different types of orders and when they are appropriate. 

Market vs. Limit
Two basic types of orders that we should be aware of are the market order and the limit order.
  • A market order is an order to buy or sell immediately at the best available price. These orders do not guarantee a price, but they do guarantee the order's immediate execution. Typically, if you are going to buy a stock, then you will pay a price near the posted ask. If you are going to sell a stock, you will receive a price near the posted bid. 
  • A limit order sets the maximum or minimum price at which you are willing to buy or sell. For example, if you wanted to buy a stock at $10, you could enter a limit order for this amount. This means that you would not pay a penny over $10 for the particular stock. It is still possible, however, that you buy it for less than the $10.
TRANSACTIONS
An agreement between a buyer and a seller for the exchange of goods or services for payment is Transaction.
You are ready to trade, now what? 
In order to make your trade you have to be specific about how you want the transaction to be performed. The above mentioned order types are most common types you'll encounter when placing an equity order using an online interface or the phone.

For example an Order from XYZ customer can have following four transactions.

Date                             Operation        Stock               Quantity 
January 5, 2011             SELL                MG                   16
January 6, 2011             BUY                 MG                   18
January 7, 2011             SELL                MG                   11
January 8, 2011             BUY                 MG                   10
                                                                                   
That's All.
See you soon.....
Source- wikipedia & encyclopedia


Saturday, January 8, 2011
Posted by Munish Gogna

Popular Post

Labels

enums (1) java (2) JAX-RS (1) JPA (1) mysql (1) request 2 (1) RESTful (1) sphinx (1) tomcat (1) web service (2) ws (2)