Monday, January 31, 2011

How to use logger in your Java application

How to log Messages in your application?


Java's logging facility has two parts: a configuration file, and an API for using logging services. It is suitable for simple and moderate logging needs. Log entries can be sent to the following destinations, as either simple text or as XML:
· The console
· A file
· A stream
· Memory
· TCP socket on a remote host

The LEVEL class defines seven levels of logging enlightenment :
FINEST, FINER, FINE, CONFIG, INFO, WARNING, SEVERE .ALL and OFF are defined values as well

The levels in code may be modified as required :
· Upon startup, by using CONFIG to log configuration parameters
· During normal operation, by using INFO to log high-level "heartbeat" information
· When bugs or critical conditions occur, by using SEVERE.
· Debugging information might default to FINE, with FINER and FINEST used occasionally, according to user need.


There is flexibility in how logging levels can be changed at runtime, without the need for a restart:
· By simply changing the configuration file and calling LogManager.readConfiguration.
· By changing the level in the body of code , using the logging API ;
For example, one might automatically increase the logging level in response to unexpected events



The logging levels are in descending order SEVERE, WARNING, INFO, CONFIG, FINE, FINER and FINEST. If we specify log level as

INFO then all the log messages which are equal to INFO and greater (WARNING, SEVERE) levels will be logged.


Levels are attached to the following items:
· An originating logging request (from a single line of code)
· A Logger (usually attached to the package containing the above line of code)
· A Handler (attached to an application)

Here is an example of a logging configuration file :
# Properties file which configures the operation of the JDK
# logging facility. # The system will look for this config file, first using
# a System property specified at startup:
# >java -Djava.util.logging.config.file=myLoggingConfigFilePath #
# If this property is not specified, then the config file is retrieved
# from its default location at:
# JDK_HOME/jre/lib/logging.properties
# Global logging properties.
# ------------------------------------------
# The set of handlers to be loaded upon startup.
# Comma-separated list of class names.
# (? LogManager docs say no comma here, but JDK example has comma.)
handlers=java.util.logging.FileHandler, java.util.logging.ConsoleHandler

# Default global logging level.
# Loggers and Handlers may override this level
.level=INFO

# Loggers
# ------------------------------------------
# Loggers are usually attached to packages.
# Here, the level for each package is specified.
# The global level is used by default, so levels
# specified here simply act as an override.
myapp.ui.level=ALL
myapp.business.level=CONFIG
myapp.data.level=SEVERE

# Handlers
# -----------------------------------------
# --- ConsoleHandler ---
# Override of global logging level
java.util.logging.ConsoleHandler.level=SEVERE
java.util.logging.ConsoleHandler.formatter=java.util.logging.SimpleFormatter

# --- FileHandler ---
# Override of global logging level
java.util.logging.FileHandler.level=ALL
# Naming style for the output file:
# (The output file is placed in the directory
# defined by the "user.home" System property.)
java.util.logging.FileHandler.pattern=%h/java%u.log

# Limiting size of output file in bytes:
java.util.logging.FileHandler.limit=50000

# Number of output files to cycle through, by appending an
# integer to the base file name:
java.util.logging.FileHandler.count=1

# Style of output (Simple or XML):
java.util.logging.FileHandler.formatter=java.util.logging.SimpleFormatter

Here is an example of using the logging API :

package myapp.business;
import java.util.logging.*;
/**
* Demonstrate Java's logging facilities, in conjunction
* with a logging config file.
*/
public final class SimpleLogger {

  public static void main(String argv[]) {
    SimpleLogger thing = new SimpleLogger();
    thing.doSomething();
  }
   public void doSomething() {
   //Log messages, one for each level
   //The actual logging output depends on the configured
    //level for this package. Calls to "inapplicable"
    //messages are inexpensive.
     fLogger.finest("this is finest");
    fLogger.finer("this is finer");
    fLogger.fine("this is fine");
    fLogger.config("this is config");
    fLogger.info("this is info");
    fLogger.warning("this is a warning");
    fLogger.severe("this is severe");

    //In the above style, the name of the class and
    //method which has generated a message is placed
    //in the output on a best-efforts basis only.
    //To ensure that this information is always
    //included, use the following "precise log"
    //style instead :
    fLogger.logp(Level.INFO, this.getClass().toString(), "doSomething", "blah");

    //For the very common task of logging exceptions, there is a
    //method which takes a Throwable :
    Throwable ex = new IllegalArgumentException("Some exception text");
    fLogger.log(Level.SEVERE, "Some message", ex);

    //There are convenience methods for exiting and
    //entering a method, which are at Level.FINER :
    fLogger.exiting(this.getClass().toString(), "doSomething");

    //Display user.home directory, if desired.
    //(This is the directory where the log files are generated.)
    //System.out.println("user.home dir: " + System.getProperty("user.home") );
  }

  // PRIVATE //

  //This logger will inherit the config of its parent, and add
  //any further config as an override. A simple style is to use
  //all config of the parent except, perhaps, for logging level.

  //This style uses a hard-coded literal and should likely be avoided:
  //private static final Logger fLogger = Logger.getLogger("myapp.business");

  //This style has no hard-coded literals, but forces the logger
  //to be non-static.
  //private final Logger fLogger=Logger.getLogger(this.getClass().getPackage().getName());

  //This style uses a static field, but hard-codes a class literal.
  //This is probably acceptable.
  private static final Logger fLogger = Logger.getLogger(SimpleLogger.class.getPackage().getName());

}

Friday, January 28, 2011

How to log an exception's stackTrace to log file using logger

Manytimes, we use logger to log messages that help us while debugging our application.
But, do you know, how do we write exception stackTrace to log file?

I tried to look for methods in Exception object, there is a method that writes to PrintWriter. Now how do I get PrintWriter's Object? Definitely, i could use reponse.getWriter(), but what if i want to log stacktrace from a java file, where I do not have access to response object. Moreover in many scenario's I would not like to write the stacktrace to browser, visible to end user.

Then I found a very useful over loaded method, which got skipped everytime before today.

Logger has an overloaded method, with 2 arguments, the second one is object of Throwable or Exception class.

This can be achieved as follows

 ...
 } catch( Exception e ) {
 logger.debug( e.getMessage(), e );
 }
 ...

Wednesday, January 26, 2011

How to download a file using AJAX

I struggled for half of my day finding this.

Actually in our project, there is a CART. The requirement is when we click on downloadCart button, it should download the contents of the cart and clear the cart as well.

The first issue that I faced was...

As the response has a zip file to be downloaded, hence in our Action class, they were writing bytes to the response, and in the end, when they return SUCCESS, (I forgot to tell u, we are using struts in our project) it gives an exception : java.lang.illegalStateException, that is expected.

So, what's the solution...

After discussing this with my friend Sukhbir, he suggested that we can't return any view after we have committed the response. But how to handle this scenario.

He suggested, make 2 calls, using javascript, and put it on onClick event of the button.
One for downloading, and the second one for re-loading the cart (So that it gets refreshed).

I did the code for downloading using AJAX.... $.get and $.ajax
But the issue now came up was....

Ajax calls work in background and it doesn't lets the user see that something has downloaded......no response, no prompt.......nothing........

Now what??

Then I came to know that there are APIs available in jquery for handling binary data when data is coming from server. I googled this also a lot, but, couldn't find anything that worked for me.

I found a very pretty and simple solution on internet now...Here it is...
Thanks to Eric for this help

Source : Google Group Forums Link

Final Solution
function test(url){ 
  var elemIF = document.createElement("iframe"); 
  elemIF.src = url; 
  elemIF.style.display = "none"; 
  document.body.appendChild(elemIF); 
} 



Related posts : http://particletree.com/notebook/ajax-file-download-or-not/

How to reload an iframe from within its source

Hi,

Today I had a requirement where it was desired that on click of a button an iframe should get re-loaded and that button was within the source of that iframe.

I tried everything else on google, but nothing worked.

Finally I found this and it worked

self.location.reload();

Here is the complete code...

abc.html
=========
<html>
<head>
</head>
<body>
 <iframe src="def.html" id="cartFrame"></iframe><BR><BR>
</body>
</html>


def.html
=========
<html>
 <head>
  <!-- Remember, you must be connected to internet to make it work -->
  <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
  <script type="text/javascript">
   $(document).ready(function()
   {
    var d = new Date();
    // set the HTML content of the element with id=time
    $("#time").html(d.getTime());
    
    // define what happens on click of the element with id="download"
    $("#download").click(function()
    {
     // Simply re-load myself :)
     self.location.reload();
    });
    
   });
  </script>
 </head>

 <body>
  <div id="time"></div><BR><BR>
  <button id="download">Download</button>
 </body>
</html>

Thursday, January 20, 2011

Find bugs in your java program

You must be wondering, how to check errors and problems in your application.

Now your worry has come to an end..

Here is a tool, that can analyze compiled versions of your java programs and lets you know, what needs to be fixed in your application.

Have a look

http://findbugs.sourceforge.net/

Sunday, January 16, 2011

How to write this in jquery “window.parent.document.getElementById('parentPrice').innerHTML”?

I have an iframe and I wrote this code

window.parent.document.getElementById('parentPrice').innerHTML

to access parent element. How to get the same result using jquery?
UPDATE: Or how to access iFrame parent page using jquery?

Solution
To find in the parent of the iFrame use:

$('#parentPrice', window.parent.document).html();

The second parameter for the $() wrapper is the context in which to search. This defaults to document.

Courtesy : http://stackoverflow.com/questions/726816/how-to-write-this-in-jquery-window-parent-document-getelementbyidparentprice

Thursday, January 13, 2011

Common pitfalls in Javascript

When you defined script tag in JS

Define it as follows
<script type="text/javascript" src="jquery.js"></script>

And not as
<script type="text/javascript" src="jquery.js"/>


In the second case, it'll not interpret the script tag appropriately and the function defined inside <script>

Tuesday, January 11, 2011

Remove duplicate elements from a comma seperated list (JAVASCRIPT)

 var input = 'a,b,b,said,said, t, u, ugly, ugly';
 var splitted = input.split(',');
 var collector = {};
 for (i = 0; i < splitted.length; i++) {
    key = splitted[i].replace(/^\s*/, "").replace(/\s*$/, "");
    collector[key] = true;
 }
 var out = [];
 for (var key in collector) {
    out.push(key);
 }
 var output = out.join(',');
 alert(output);

Sunday, January 9, 2011

Error 53 SQL Server 2005


Have you recently changed your machine name??

If you face this error while connecting to SQL server, here is the solution

Make sure that the Server Name matches the name of the machine you are trying to connect.

To get your machine name, right click My Computer -> Properties and there you can find Computer Name.

Saturday, January 8, 2011

Not enough arguments [nsIDOMWindowInternal.alert]

<html>
<head>
 <script type="text/javascript">
  function callfn()
  {
   alert();
  }
 </script>
</head>
<body onload="javascript:callfn()">
</body>
</html>

This will give error somewhat similar to

uncaught exception: [Exception... "Not enough arguments [nsIDOMWindowInternal.alert]" nsresult: "0x80570001 (NS_ERROR_XPC_NOT_ENOUGH_ARGS)" location: "JS frame :: http://rae.us.playstation.com/raeus/ps3/index.htm :: :: line 810" data: no]


Please note that this error appears specifically in Firefox. (Not sure about other browsers).

Source : http://www.sitepoint.com/forums/showthread.php?t=182241

Wednesday, January 5, 2011

JSON, AJAX and jQuery

Today I was working on JSON.
1) Requirement was to get the data from a server in a JSON object. Store it into request object.
2) And on an HTML page, it was required to fire an AJAX request, get the data from the Servlet created in step 1.

3) When i fired a request to servlet directly in browser window, it used to print JSON object that it returns. But when i make a request thru AJAX call... the data is never displayed.

SOLUTION/MISTAKE:

JSON object must follow the structure of the JSON object.
You cannot add any extra println in the resulting JSP. It must ONLY and ONLY print JSON object.


You can validate your JSON from www.jsonlint.com

See more : http://api.jquery.com/jQuery.ajax/