Angular 2 and OnSen UI based hybrid News feed app

Angular 2 and OnSen UI based hybrid News feed app, the news are fetched from newsapi.org (over 50 sources). The overall native feel of Onsen UI on iOS is amazing but I guess they will have to work hard to match what Ionic has to offer. The Source is available on my github repository for you to clone and enjoy. 


Source Code: https://github.com/gognamunish/ng2-onsen_ui-newsfeed 

Screenshots
Friday, January 6, 2017
Posted by Unknown

Ionic + FireBase based Expenditure tracker app

This time I tried my hands on the Ionic framework, find the details below:
https://github.com/gognamunish/ionic-expenditure-tracker Thanks, Happy New Year !!!
Monday, January 2, 2017
Posted by Unknown

ng2 based Order Entry System for learning purpose

This weekend I could finally manage time to explore Angular 2 framework thanks to Sachin Shah for coming up with idea to explore the hidden gems in modern web technologies.

This project uses a number of open source projects to work properly:
  • [AngularJS] - HTML enhanced for web apps!
  • [Spring Boot] - Awesome boot framework
  • [Spring Data] - We are using JPA repository
  • [Spring Security] - Just for basic authentication
  • [HSQL] - Embedded database.
  • [Ng Material] - Material Design components for Angular 2
  • [Rest Assured] - Testing and validating REST services

Have a look at READ ME page on my Github page below:
Feel free to clone and play with it.
Sunday, December 18, 2016
Posted by Unknown

Acceptance Tests using Cucumber

Most of the Systems are buggy due to lack of Acceptance tests, so in today's post I will try to walk you through a simple Cucumber based acceptance test for the following very common JIRA User story.
As a RM User of the System
I want to make sure that entitlements are properly set
So that I am able to Place Orders in the new Order Entry System.
Each test case in Cucumber is called a scenario, and scenarios are grouped into features. Each scenario contains several steps. The good thing about Cucumber is that your JIRA story can be taken as is to form the basis of acceptance test so that Business and Developers can be in talking terms with each other. I am skipping the Maven wiring for the project and jumping directly into the feature that we want to implement in this post.

Step 1 : Describe behavior of the Test in plain English (roles2functions.feature)
Feature: User Entitlement 

  Scenario:
    User of the Bank in certain role would like 
    to access certain functionality of existing System.

    When The logged In User "U12345" has 
       standard "RM" role
    Then "Place Orders" functionality 
       of "OES" application should be available to him/her
There is a scope for enriching this feature description but for the sake of the goal of this post (introducing you to Cucumber), we are good to go.
In this .feature file We’ve translated one of the acceptance criteria we were given in the JIRA task into a Cucumber scenario that we can ask the computer to run over and over again. The keywords Feature, Scenario, When, and Then are the structure, and everything else is documentation.

Step 2 : Implementing Our Step Definitions
package com.gognamunish;

import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.equalTo;
import java.util.List;
import org.junit.Assert;
import cucumber.api.java.en.Then;
import cucumber.api.java.en.When;

/**
 * A very basic implementation for the Acceptance criteria.
 * @author Munish Gogna
 */
public class EntitlementFixtures {

 String role;
 EntitlementService entitlementService = new EntitlementService();

 @When("^The logged In User \"(.*?)\" has standard \"(.*?)\" role$")
 public void the_logged_In_User_has_role(String userId, String role)
   throws Throwable {
  
  Assert.assertNotNull(role);
  Assert.assertNotNull(userId);
                this.role = role;

  List<String> userRoles = entitlementService.getUserRoles(userId);
  assertThat(true, equalTo(userRoles.contains(role)));
 }

 @Then("^\"(.*?)\" functionality of \"(.*?)\" application should be available to him/her$")
 public void functionality_of_application_should_be_available_to(
   String function, String application) throws Throwable {
  Assert.assertNotNull(function);
  Assert.assertNotNull(application);

  List<String> functions = entitlementService
    .getFunctionsForRoleAndApplication(role, application);
  assertThat(true, equalTo(functions.contains(function)));

 }
}

Let's run our Fixtures using Cucumber runner as shown below:
package com.gognamunish;

import org.junit.runner.RunWith;
import cucumber.api.junit.Cucumber;

@RunWith(Cucumber.class)
public class RunEntitlementTest {
// intentional
}
Well well well - all tests have passed :)
1 Scenarios (1 passed)
2 Steps (2 passed)
0m0.310s

In case if the test is failing the logs will have enough information about the Assertion that was made.

Summary from this post
Software teams work best when the developers and business stakeholders are communicating clearly with one another. A great way to do that is to collaboratively specify the work that’s about to be done using automated acceptance tests (and the good thing about Cucumber is that they can be imported directly from User stories in JIRA).

In the next article I would evaluate Fitnesse for the same feature.
Tuesday, August 26, 2014
Posted by Unknown

SphinxQL over JDBC

This is an extension of my earlier blog post about performing free text search with Sphinx (v2.1.6+). This time we are going to access the index via JDBC as opposed to Sphinx API and perform some basic queries to fetch indexed data.

Add following entries to searchd section inside sphinx.conf
listen=9306:mysql41
mysql_version_string=5.0.37

Once done start the sphinx daemon (searchd) so that the search engine can be accessed from external applications on port 9306. Next just get the JDBC connection (no need to specify database details and credentials) as shown below and you are ready to rock.
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager
 .getConnection("jdbc:mysql://localhost:9306");
statement = con.createStatement();
// perform wild search on last names
resultSet = statement
 .executeQuery("select * from addressBookIndex 
where MATCH ('gogna | sharma')"); 

Note:
  • 1. The attributes specified in the sphinx.conf file (e.g. sql_attr_string, sql_attr_uint etc) can not be used with MATCH though they can be part of WHERE clause.
  • 2. Given that now String attributes are supported in order to avoid making a database call define key columns as attributes as well as fields in sql_query.
  • 3. Results from Delta Indexes can be handled using union.
  • 4. Explore RT indexes for real time update scenarios.
For more information about the Sphinx QL syntax visit here.
Saturday, March 15, 2014
Posted by Unknown

Apache Velocity Template to generate CSV (or any other format) file

This post is simple one to generate CSV file from some Source using Velocity Template and to verify the new design for the Blog (Metro Blue). The code (just a running stuff and nothing fancy) provided is simple and doesn't need any explanation and is dedicated to a dear friend Sachin Shah.






Java Class
package com.gognamunish.test;

import org.apache.velocity.app.Velocity;
import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;

import java.io.File;
import java.io.FileWriter;
import java.io.StringWriter;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class CSVFeedGeneration {

  static DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");

  static DataFeed dataFeed;
 static {
  // prepare some static data
  dataFeed = new DataFeed();
  List<Map<String, Object>> dataList = new ArrayList<Map<String, Object>>();
  Map<String, Object> data = new HashMap<String, Object>();
  data.put("TransactionId", 1);
  data.put("Amount", new Integer(2312));
  data.put("Currency", "SGD");
  data.put("ExecutionDate", dateFormat.format(new Date()));
  dataList.add(data);
  data = new HashMap<String, Object>();
  data.put("TransactionId", 2);
  data.put("Amount", new Integer(1212));
  data.put("Currency", "INR");
  data.put("ExecutionDate", dateFormat.format(new Date()));
  data.put("Status", "Active");
  dataList.add(data);

   dataFeed.getFeedData().add(dataList);

  }

  public static void main(String[] args) throws Exception {
  VelocityContext context = new VelocityContext();
  FileWriter writer = new FileWriter(new File("feed.csv"));
  
  // inject the objects to be used in template
  context.put("feed", dataFeed);
  context.put("DELIMETER", ",");
  context.put("NEWLINE", "\n");

  Velocity.init();
  Template template = Velocity.getTemplate("csvfeed.vm");
  template.merge(context, writer);
  writer.flush();
  writer.close();

  }

}
Template File (csvfeed.vm)
TransactionId${DELIMETER}Amount${DELIMETER}ExecutionDate ${DELIMETER}Currency${DELIMETER}Status$NEWLINE
#foreach( $rowSet in $feed.feedData)
#foreach( $row in $rowSet )
$!row.get("TransactionId")$DELIMETER$!row.get("Amount") $DELIMETER$!row.get("ExecutionDate")$DELIMETER $!row.get("Currency")$DELIMETER$!row.get("Status")$NEWLINE
#end
#end
Output File (feed.csv)
TransactionId,Amount,ExecutionDate,Currency,Status
1,2312,2013-08-18T14:29:35,SGD,
2,1212,2013-08-18T14:29:35,INR,Active
The main advantage of this approach is that you can change the data format any time without changing or touching any Java code.
POM Dependency
<dependency>
   <groupId>org.apache.velocity</groupId>
   <artifactId>velocity</artifactId>
   <version>1.7</version>
  </dependency>
In case you are interested in exploring more, reach out here http://velocity.apache.org/engine/devel/index.html
Sunday, August 18, 2013
Posted by Unknown

Configuring IBM MQ in JBoss


In today's post I will explain how to install the WebSphere MQ resource adapter on JBoss.

Installing WebSphere MQ resource adapter:
To install WebSphere MQ resource adapter, copy the file wmq.jmsra.rar (from installation directory) to the server's deploy directory, for example <install path>/server/default/deploy The resource adapter will be automatically picked up by the server.

Installing the WebSphere MQ Extended Transactional Client:
The WebSphere MQ Extended transactional client lets you use XA distributed transactions with CLIENT mode connections to a WebSphere MQ queue manager. To install it on JBoss, copy the file com.ibm.mqetclient.jar ( from installation directory ) to the server lib directory, for example <install path>/server/default/lib.

Configuring the resource adapter for your application:
The WebSphere MQ resource adapter lets you define a number of global properties. Resource definitions for outbound JCA flows are defined in a JBoss -ds.xml file named wmq.jmsra-ds.xml. The outline form of this file:

  
  
  
  



As can be seen above JCA connection factories are defined in the <tx-connection-factory> element and JMS queues and topics are defined as JCA administered object mbeans.

A complete example for our sample application defining two queues - inbound and outbound is given below:

    
        jms/MyAppConnectionFactory
        wmq.jmsra.rar
        true
        javax.jms.QueueConnectionFactory
        8
        36
        ${channel}
        ${hostName}
        1414
        ${queueManager}
        CLIENT
        munish
        JmsXARealm
        
    
    
  jms/IncomingQueue
  jboss.jca:name='wmq.jmsra.rar',service=RARDeployment
  javax.jms.Queue
  
   baseQueueManagerName=${queueManager}
   baseQueueName=MY.APP.INBOUND.QUEUE
    
    
    
        jms/OutgoingQueue
        jboss.jca:name='wmq.jmsra.rar',service=RARDeployment
        javax.jms.Queue
        
            baseQueueManagerName=${queueManager}
            baseQueueName=MY.APP.OUTBOUND.QUEUE
        
    



The place holder properties are defined in the JBoss start script as:
-Dchannel=MQTEST -DhostName=localhost -DqueueManager=TST_MGR

Configuring inbound message delivery:
Message delivery to a Message-Driven Enterprise JavaBean (MDB) is configured using a JBoss-specific file named jboss.xml, located in the MDB .ear file. The contents of this file will vary, but will be of the form:

jboss.xml:

 
  
   MyMessageBean
    
     
                     
                             DestinationType
                             javax.jms.Queue
                     
                     
                             destination
                             MY.APP.INBOUND.QUEUE
                     
                     
                             channel
                             ${channel}
                     
                     
                             hostName
                             ${hostName}
                     
                     
                             port
                             1414
                     
                     
                             queueManager
                             ${queueManager}
                     
                     
                             transportType
                             CLIENT
                     
                     
                             username
                             munish
                     
              
               
           wmq.jmsra.rar
     
 


The DestinationType and Name properties must be specified. Other properties are optional, and if omitted, take on their default values.

A simple MDB definition for the inbound message is shown below:
/**
 * This message driven bean is used to collect asynchronously received messages.
 *
 * @author Munish Gogna
 */
@MessageDriven(mappedName = "jms/IncomingQueue")
public final class MyMessageBean implements javax.jms.MessageListener {
  private static final org.apache.log4j.Logger LOGGER = org.apache.log4j.Logger.getLogger(MyMessageBean.class);
  public void onMessage(final javax.jms.Message message) {
    LOGGER.info("Received message: " + message);
    // TODO - do processing with the message here
  }
}


A plain java class to send message to the output queue is shown below.
/**
 * This class is used to send text messages to a queue.
 *
 * @author Munish Gogna
 */
public final class MessageSender {
  private static final org.apache.log4j.Logger LOGGER = org.apache.log4j.Logger.getLogger(MessageSender.class);
  /**
   * A coarse-grained method, nothing fancy. In actual applications please re factor the code and
   * handle the exceptions properly.
   *
   * @throws Exception
   */
  public void send(final String message) throws Exception {
    if (message == null) {
      throw new IllegalArgumentException("Parameter message cannot be null");
    }
    javax.jms.QueueConnection connection = null;
    javax.jms.Session session = null;
    try {
      javax.naming.Context fContext = new javax.naming.InitialContext();
      javax.jms.QueueConnectionFactory fConnectionFactory = (javax.jms.QueueConnectionFactory) fContext
          .lookup("java:jms/MyAppConnectionFactory");
      connection = fConnectionFactory.createQueueConnection();
      session = connection.createSession(false, javax.jms.Session.AUTO_ACKNOWLEDGE);
      final javax.naming.Context jndiContext = new javax.naming.InitialContext();
      final javax.jms.Destination destination = (javax.jms.Destination) jndiContext.lookup("jms/OutgoingQueue");
      final javax.jms.MessageProducer messageProducer = session.createProducer(destination);
      final javax.jms.TextMessage textMessage = session.createTextMessage(message);
      messageProducer.send(textMessage);
      messageProducer.close();
    } catch (Exception nex) {
      throw nex;
    } finally {
      if (session != null) {
        try {
          session.close();
        } catch (JMSException e) {
          LOGGER.error("Failed to close JMS session", e);
        }
      }
      if (connection != null) {
        try {
          connection.close();
        } catch (JMSException e) {
          LOGGER.error("Failed to close JMS connection", e);
        }
      }
    }
  }
}
A utilty called RFHUTILC.EXE can be used to connect to remote queues.

That's all.
Monday, June 4, 2012
Posted by Unknown

Saving development time with local EntityManager in JPA

In almost all real world projects (non Spring + We are not considering Arquillian or any similar framework) where you are using JPA (Hibernate implementation), the data source binding happens by JNDI and the services are provided by EJBs, which means to test your entities for any CRUD operation you have to deploy the bundle (ear, ejb or war) into the application server which adds time to your development efforts each time you make any change. So in this post we will see how we can temporarily inject entity manager into your business class so that you can test all the operations you want to perform on entities without deploying the application or restarting server quite often.

persistence.xml: The configuration for entity managers both inside an application server and in a standalone application reside in a persistence archive. In the next section we focus on standalone configuration.

 
  org.hibernate.ejb.HibernatePersistence
  com.gognamunish.test.Entity
  
   
   
   
   
   
  
 

Please Note:
  • The database dialect we have chosen is MySQL for obvious reasons.
  • Persistence unit has name test_unit and the type is RESOURCE_LOCAL and not JTA.
  • com.gognamunish.test.Entity is the entity which we want to test later.
  • As we are running without a JNDI available datasource, we must specify JDBC connections with Hibernate specific properties
Next in your business class you can get reference to the entity manager as follow:
EntityManagerFactory factory ;
factory = Persistence.createEntityManagerFactory("test_unit");
EntityManager manager = factory.createEntityManager();
That's all you need , after obtaining the reference focus only on your entity and the operation you want to perform on it.
Let's try one sample example:
/* Sample Entity class */
@javax.persistence.Entity
@Table(name = "Entity")
public class Entity {
 @Id
 private Long id;
 @Column
 private String value;
}
package com.gognamunish.test;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;

/**
 * Sample Test - nothing fancy.
 * 
 * @author Munish Gogna
 * 
 */
public class LocalEntityManager {
 static EntityManager manager;
 static {
  EntityManagerFactory factory = Persistence
    .createEntityManagerFactory("test_unit");
  manager = factory.createEntityManager();
 }

 public static void main(String[] args) {

  System.out.println("Before Entities: " + getEntities());

  manager.getTransaction().begin();
  Entity entity = new Entity();
  entity.setId(1l);
  entity.setValue("my first value");
  saveOrUpdate(entity);
  manager.getTransaction().commit();

  System.out.println("After Entities: " + getEntities());

 }

 private static Entity saveOrUpdate(Entity entity) {
  return manager.merge(entity);
 }

 @SuppressWarnings("unchecked")
 private static List<Entity> getEntities() {
  return manager.createQuery("from Entity").getResultList();
 }
}

LOGS:
Hibernate: select entity0_.id as id0_, entity0_.value as value0_ from Entity entity0_
Before Entities: []
Hibernate: select entity0_.id as id0_0_, entity0_.value as value0_0_ from Entity entity0_ where entity0_.id=?
Hibernate: insert into Entity (value, id) values (?, ?)
Hibernate: select entity0_.id as id0_, entity0_.value as value0_ from Entity entity0_
After Entities: [Id:1, Value:my first value]
Sunday, April 29, 2012
Posted by Unknown

Reverse a String in Java

One of the frequently asked questions in interviews, let's try few ways available in JDK to reverse a string:





import java.util.Stack;
public class StringReverse {

 public static String reverse1(String s) {
  int length = s.length();
  if (length <= 1)
   return s;
  String left = s.substring(0, length / 2);
  String right = s.substring(length / 2, length);
  return reverse1(right) + reverse1(left);
 }

 public static String reverse2(String s) {
  int length = s.length();
  String reverse = "";
  for (int i = 0; i < length; i++)
   reverse = s.charAt(i) + reverse;
  return reverse;
 }

 public static String reverse3(String s) {
  char[] array = s.toCharArray();
  String reverse = "";
  for (int i = array.length - 1; i >= 0; i--)
   reverse += array[i];

  return reverse;
 }

 public static String reverse4(String s) {
  return new StringBuffer(s).reverse().toString();
 }

 public static String reverse5(String orig) {
  char[] s = orig.toCharArray();
  int n = s.length - 1;
  int halfLength = n / 2;
  for (int i = 0; i <= halfLength; i++) {
   char temp = s[i];
   s[i] = s[n - i];
   s[n - i] = temp;
  }
  return new String(s);
 }

 public static String reverse6(String s) {

  char[] str = s.toCharArray();

  int begin = 0;
  int end = s.length() - 1;

  while (begin < end) {
   str[begin] = (char) (str[begin] ^ str[end]);
   str[end] = (char) (str[begin] ^ str[end]);
   str[begin] = (char) (str[end] ^ str[begin]);
   begin++;
   end--;
  }

  return new String(str);
 }

 public static String reverse7(String s) {
  char[] str = s.toCharArray();
  Stack<Character> stack = new Stack<Character>();
  for (int i = 0; i < str.length; i++)
   stack.push(str[i]);

  String reversed = "";
  for (int i = 0; i < str.length; i++)
   reversed += stack.pop();

  return reversed;
 }

}


Feel free to suggest other ways if you have.
Sunday, March 4, 2012
Posted by Unknown

Merging PDFs while retaining the fill able forms inside them

My previous post was about merging the PDF files into single file using PDFBox, the limitation of that approach was if you had fill able form inside any PDF file it was lost, to over come that issue here is an updated version of the same post using iText library.







import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;

import com.lowagie.text.pdf.AcroFields;
import com.lowagie.text.pdf.PdfCopyFields;
import com.lowagie.text.pdf.PdfReader;

/**
 * Merges the PDF files while retaining the fillable forms within them. It also
 * renames form field (to avoid conflicts) which can have an impact if form is
 * submitted to server but for printing purpose should be OK.
 * 
 * @author Munish Gogna
 * 
 */
public class PDFMerge {
 private static int counter = 0;

 public static void merge(List<InputStream> sourcePDFs,
   OutputStream targetPDF) throws Exception {
  if (sourcePDFs != null && targetPDF != null) {
   PdfCopyFields copy = new PdfCopyFields(targetPDF);

   for (InputStream stream : sourcePDFs) {
    PdfReader pdfReader = new PdfReader(stream);
    renameFields(pdfReader.getAcroFields());
    copy.addDocument(pdfReader);
    stream.close();
   }
   copy.close();
  }
 }

 private static void renameFields(AcroFields fields) {
  Set<String> fieldNames = fields.getFields().keySet();
  String prepend = String.format("_%d.", counter++);

  for (String fieldName : fieldNames) {
   fields.renameField(fieldName, prepend + fieldName);
  }
 }

 public static void main(String[] args) {
  try {
   List<InputStream> pdfs = new ArrayList<InputStream>();
   pdfs
     .add(new URL(
       "http://thewebjockeys.com/TheWebJockeys/Fillable_PDF_Sample_from_TheWebJockeys_vC5.pdf")
       .openStream());
   pdfs
     .add(new URL(
       "http://help.adobe.com/en_US/Acrobat/9.0/Samples/interactiveform_enabled.pdf")
       .openStream());
   OutputStream output = new FileOutputStream("merged.pdf");

   merge(pdfs, output);

  } catch (Exception e) {
   e.printStackTrace();
  }
 }

}

The iText jar can be downloaded here

Thanks.
Sunday, January 15, 2012
Posted by Unknown

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 Unknown

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 Unknown

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 Unknown

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 Unknown

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 Unknown

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 Unknown

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 Unknown

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 Unknown

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 Unknown

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 Unknown

Popular Post

Labels

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