Archive for January 2011

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

Maven - creating a Jar from contents of another Jar file

Recently I came across a situation where I had to create a jar file with similar contents as of some other available jar. As using maven we cannot copy one jar file within another and also I didn't want to reinvent the wheel again so here is how I achieved the same.


Let's say there is an artifact 'sandeep-ejb-client' (some client ejb jar which has some dependency on some other artifacts say log4j and junit)
What I am interested is in creating a new jar file that has all the ejb client classes without including dependencies of 'sandeep-ejb-client'.


Here is the POM file to achieve the same:

<project xmlns="http://maven.apache.org/POM/4.0.0" 
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
      xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">

 <modelVersion>4.0.0</modelVersion>
 <groupId>com.test.gognamunish</groupId>
 <artifactId>Test</artifactId>
 <version>1_0_0</version>
 <name>Test JAR</name>
 <packaging>jar</packaging>
 <build>
  <plugins>
   <plugin>
    <artifactId>maven-dependency-plugin</artifactId>
    <executions>
     <execution>
      <id>${project.artifactId}-fetch-deps</id>
      <phase>generate-sources</phase>
      <goals>
       <goal>unpack-dependencies</goal>
      </goals>
      <configuration>
       <outputDirectory>${project.build.outputDirectory}</outputDirectory>
       <stripVersion>true</stripVersion>
       <excludeTransitive>true</excludeTransitive>
       <excludeArtifactIds>log4j,junit</excludeArtifactIds>
      </configuration>
     </execution>
    </executions>
   </plugin>
  </plugins>
 </build>

 <dependencies>
  <dependency>
   <groupId>com.ejb.sandeepkadyan</groupId>
   <artifactId>sandeep-ejb-client</artifactId>
   <version>1_0_0</version>
  </dependency>
 </dependencies>

</project>




That's All, Simple? If anyone has got better approach please feel free to discuss !!!


- Munish
Sunday, January 2, 2011
Posted by Munish Gogna

Using log4j for various logging events ...

We all are familiar with log4j and use it in our projects to log various information. One of the most stunning features of log4j API is its manageability. Once the log statements have been inserted into the code, they can be controlled with configuration files. They can be selectively enabled or disabled, and sent to different and multiple output targets in user-chosen formats. Though there is nothing special in today's post yet it could be helpful to most of people out there. 
So let's get started....
Log4j has three main components: loggers, appenders and layouts.These three types of components work together to enable developers to log messages according to message type and level, and to control at runtime how these messages are formatted and where they are reported.
Loggers: are named entities. Logger names are case-sensitive and they follow the hierarchical naming rule. For example, the logger named "com.mg.log4j.test" is a parent of the logger named "com.mg.log4j.test.Log4j"  same as "java" is a parent of "java.util" and an ancestor of "java.util.Vector". This naming scheme is familiar to most of us. Loggers may also be assigned levels. The set of possible levels, that is: TRACE, DEBUG, INFO, WARN, ERROR and FATAL (For the standard levels, we have DEBUG < INFO < WARN < ERROR < FATAL)
Appenders and Layouts: The ability to selectively enable or disable logging requests based on their logger is only part of the picture. Log4j allows logging requests to print to multiple destinations. In log4j speak, an output destination is called an appender. Currently, appenders exist for the console, files, GUI components, remote socket servers, JMS, NT Event Loggers, and remote UNIX Syslog daemons. It is also possible to log asynchronously.
The PatternLayout, part of the standard log4j distribution, lets the user specify the output format according to conversion patterns similar to the C language printf function.
For example, the PatternLayout with the conversion pattern "%r [%t] %-5p %c - %m%n" will output something akin to:
12 [main] INFO  com.mg.log4j.test - Happy New Year !!!
The first field is the number of milliseconds elapsed since the start of the program. The second field is the thread making the log request. The third field is the level of the log statement. The fourth field is the name of the logger associated with the log request. The text after the '-' is the message of the statement.
Also more than one appender can be attached to a logger.
Lets understand all with some example.
log4j.xml (should be in classpath, for a quick eclipse run keep it in src folder)
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE log4j:configuration SYSTEM "log4j.dtd">
<log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/">

 <!-- Append messages to the console -->
 <appender name="console" class="org.apache.log4j.ConsoleAppender">
  <param name="Target" value="System.out" />
  <param name="Threshold" value="DEBUG" />
  <layout class="org.apache.log4j.PatternLayout">
   <param name="ConversionPattern" value="%d{ABSOLUTE} %5p [%c{1}:%L] - %m%n" />
  </layout>
 </appender>

 <!--
  Append messages to the file file.log , creating a new file once the
  size of file exceeds 1KB
 -->
 <appender name="file" class="org.apache.log4j.RollingFileAppender">
  <param name="file" value="C:/devel/workspace/log4j/file.log" />
  <param name="MaxFileSize" value="1KB" />
  <param name="Threshold" value="DEBUG" />
  <param name="Append" value="true" />
  <!-- maximum number of backup files that will be created -->
  <param name="maxBackupIndex" value="5" />
  <layout class="org.apache.log4j.PatternLayout">
   <param name="ConversionPattern" value="%d{dd-MMM-yy HH:mm:ss} %5p [%c{1}] - %m%n" />
  </layout>
 </appender>


 <!-- The level is set to WARN -->
 <logger name="com.mg.log4j">
  <level value="WARN" />
  <appender-ref ref="console" />
 </logger>


 <!-- The level is set to DEBUG -->
 <logger name="FileAppener">
  <level value="DEBUG" />
  <appender-ref ref="file" />
 </logger>

 <root>
  <priority value="ALL" />
 </root>

</log4j:configuration>
Let's test this configuration...
package com.mg.log4j.test;

import org.apache.log4j.Logger;

public class Log4j {

 public static void main(String[] args) {
  // Get the default console appender, level is WARN
  // Note as you can see there is no such appender
  // 'com.mg.log4j.test.Log4j' defined in log4j.xml file, it fall backs on
  // the parent package
  Logger logger = Logger.getLogger("com.mg.log4j.test.Log4j");

  // Remember: The hierarchy is DEBUG < INFO < WARN < ERROR < FATAL

  // This request is not enabled as INFO < WARN
  logger.info("INFO");
  // This request is not enabled as DEBUG < WARN
  logger.debug("DEBUG");
  // This request is enabled as FATAL > WARN
  logger.fatal("FATAL");
  // This request is enabled as ERROR > WARN
  logger.error("ERROR");
  // This request is enabled as WARN >= WARN
  logger.warn("WARN");

  // // let's write to file appender now, level is DEBUG meaning it will
  // log everything
  logger = Logger.getLogger("FileAppener");
  for (int i = 1; i < 100; i++)
   logger.info("log me to file please, i want to see what happens after the size exceeds 1KB");

 }

}

OUTPUT:
11:44:35,984 FATAL [Log4j:21] - FATAL
11:44:35,987 ERROR [Log4j:23] - ERROR
11:44:35,987 WARN [Log4j:25] - WARN
and six log files - file.log, file1.log, file2.log, file3.log, file4.log and file5.log ( ignoring rest of the log statements after file5.log file because our threshhold limit for backup files was 5)


Please make sure that in real code you always check before logging, something like:
if(logger.isDebugEnabled())
logger.debug("Log only if debug is enabled");


Hope this small capsule will be helpful in some or other way. For more detailed understanding of log4j please visit official page at -  http://logging.apache.org/log4j/index.html

Wish you all a happy new year !!!!
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)