About Me

My photo
Ernakulam, Kerala, India
I am Sajadh, author of this blog. I run this with loads of passion.
If you are into java, you may find lot of interesting things around ...
Advance thanks for your queries to sajadhaja90@gmail.com.

Wednesday, 2 October 2013

REST with Java (JAX-RS) using Jersey

Refer From :- http://www.vogella.com/articles/REST/article.html

REST is an architectural style which is based on web-standards and the HTTP protocol.
In a REST based architecture everything is a resource. A resource is accessed via a common interface based on the HTTP standard methods.
In a REST based architecture you typically have a REST server which provides access to the resources and a REST client which accesses and modify the REST resources.
Every resource should support the HTTP common operations. Resources are identified by global IDs

HTTP methods
The PUT, GET, POST and DELETE methods are typical used in REST based architectures.

JAX-RS with Jersey

JAX-RS:- Java defines REST support via the Java Specification Request 311

Jersey :- contains basically a REST server and a REST client.

On the server side Jersey uses a servlet which scans predefined classes to identify RESTful resources. Via the web.xml configuration file for your web application, registers this servlet which is provided by the Jersey distribution 

The base URL of this servlet is:
http://your_domain:port/display-name/url-pattern/path_from_rest_class 

This servlet analyzes the incoming HTTP request and selects the correct class and method to respond to this request. This selection is based on annotations in the class and methods.

Table 1. JAX-RS annotations
Annotation
Description
@PATH(your_path)
Sets the path to base URL + /your_path. The base URL is based on your application name, the servlet and the URL pattern from the web.xml" configuration file.
@POST
Indicates that the following method will answer to a HTTP POST request
@GET
Indicates that the following method will answer to a HTTP GET request
@PUT
Indicates that the following method will answer to a HTTP PUT request
@DELETE
Indicates that the following method will answer to a HTTP DELETE request
@Produces(MediaType.TEXT_PLAIN [, more-types ])
@Produces defines which MIME type is delivered by a method annotated with @GET. In the example text ("text/plain") is produced. Other examples would be "application/xml" or "application/json".
@Consumes(type [, more-types ])
@Consumes defines which MIME type is consumed by this method.
@PathParam
Used to inject values from the URL into a method parameter. This way you inject for example the ID of a resource into the method to get the correct object.
Please Refer Site : - http://www.vogella.com/articles/REST/article.html

Friday, 5 April 2013

My Stuff Doc - jasper-export-1.0.jar


1 .Export To PDF

Tools needed :-  jasper-export-1.0.jar  (owner : Mohammed Sajadh N.A)
4 Steps :-
         1. Take Connection from database
           eg:-  Connection con = new com.sajadhaja.connection.DatabaseConnection().getConnection();
         2.  Set all dynamic parameters that in jrxml file to Hash Map like
           eg:-  Map<String, Object> hm = new HashMap<String, Object>();
                   hm.put("p1_in_jrxml", 1);
                   hm.put("p2_in_jrxml ", "12 Aug 2013");
        3. Import class JasperExport  from my jar (jasper-export-1.0.jar)   and set  all parameters like
                  eg:- JasperExport jp = new JasperExport("jrxml/jasper file location",
                                                                  "out PDF file location",connection, hashmap);
       4. Call function exportToPDF()

Sample Example :-
Public class ExportToPDF{
public static void main(String args[]) {
        Connection con = new com.sajadhaja.connection.DatabaseConnection().getConnection();
        Map<String, Object> hm = new HashMap<String, Object>();
        hm.put("p1", 1);
        hm.put("p2", "");
        JasperExport jp = new JasperExport("D:\\sample.jasper", "D:\\sample.pdf", con, hm);
        jp.exportToPDF();
    }
}

OTHER FUNCTIONS

To customize PDF for having following functions:-
1.      Default Magnification
2.      Encrypt PDF
3.      Setting MetaData
4.      Compress PDF
Replace function used in STEP 4 with   exportToCustomPDF(JasperPDFParam pm);
Where class JasperPDFParam contain all funtions to do the same.
1.      Default Magnification
To open the PDF doc in default zoom level, you can set it here
Syntax:-  void setDefaultZoom(int Zoompercentage)
Eg:-
JasperPDFParam pm = new JasperPDFParam();
pm.setDefaultZoom(100);  
2.      Encrypt PDF
Syntax:- void setEncryption(boolean is128bitkey, String userPassword, String ownerPassword, int permissions)
Where field ‘permissions’ have following values
                 JasperPDFParam.PERMISSION_AllowPrinting
                 JasperPDFParam.PERMISSION_AllowModifyContents
                 JasperPDFParam.PERMISSION_AllowCopy
                 JasperPDFParam.PERMISSION_AllowModifyAnnotations
                 JasperPDFParam.PERMISSION_AllowFillIn
                 JasperPDFParam.PERMISSION_AllowScreenReaders
                 JasperPDFParam.PERMISSION_AllowAssembly
                 JasperPDFParam PERMISSION_AllowDegradedPrinting
Eg:-
JasperPDFParam pm = new JasperPDFParam();
pm.setEncryption(true, "12345", "0000",
new Integer(JasperPDFParam.PERMISSION_AllowAssembly|JasperPDFParam.PERMISSION_AllowCopy));
       
3.      Setting MetaData
Syntax:- void setMetadata(String tittle, String author, String subject, String keywords, String creator);
Eg:-
JasperPDFParam pm = new JasperPDFParam();
pm.setMetadata("Jasper Notes", "Mohammed", "Export pdf notes", "jasper jar", "sajadhaja.blogspot.in");

4.      Compress PDF
Syntax :- void pm.setCompressed(boolean isCompressed);
Eg:-
JasperPDFParam pm = new JasperPDFParam();
pm.setCompressed(true);


Sample Example :-
Public class ExportToPDF{
public static void main(String args[]) {
Connection con = new com.sajadhaja.connection.DatabaseConnection().getConnection();
            Map<String, Object> hm = new HashMap<String, Object>();
            hm.put("p1", 1);
            hm.put("p2", "");
            JasperExport jp = new JasperExport("D:\\sample.jasper", "D:\\sample.pdf", con, hm);
            JasperPDFParam pm = new JasperPDFParam();
            pm.setMetadata("mohammed tittle", "mohamed author", "mohammed subject", "mohammed keywords", "mohamed    creator");
            pm.setEncryption(true, "12345", "0000", new Integer(JasperPDFParam.PERMISSION_AllowAssembly|JasperPDFParam.PERMISSION_AllowCopy));
            pm.setDefaultZoom(100);
            pm.setCompressed(true);
            jp.exportToCustomPDF(pm);
     }}


Thursday, 4 April 2013

My Stuffs - Jar & Js (Created by Me)

1. Drag-and-Drop File Uploads  (Java Script)
          File Name           :- filedrag.js
          Dated                   :- 10 Jan 2013
          Version                :-  1.0
          Download Link    :-
          Purpose               :- to enable Drag For File Upload

2. Jasper Export to PDF  (Jar)

          File Name              :-  jasper-exports-1.0.jar
          Dated                     :- 04 Apr 2013
          Version                  :- 1.0
          Notes                     :-  Click Here
          Download Link      :-
          Purpose                 :- to use Jasper Technology easier to export PDF


Wednesday, 3 April 2013

Useful Eclipse Plugins that didn't made it to the Top 10 list

Eclipse IDE project is started aiming to provide a universal tool set for development. Open Source IDE, mostly provided in Java, but the development language is independent. Eclipse market place hosts the list of plugins for the worlds most popular IDE. You can see the Top MPC Downloads and Top Favorites plugins are highlighted in the site. In this post I will introduce you some of the coolest eclipse plugins that I have used but were not part of the Top 10 list shown in the marketplace.


Below are my favorite plugins which are already listed in the top 10 list.


1. Mylyn 3.6
2. Maven Integration for Eclipse
3. Subclipse
4. UMLet
5. FindBugs
6. CheckStyle
7. AnyEdit


Givern below the ones that don't made it to the top 10 list but can make it one day!


General Purpose Tools


1. Rabbit


Rabbit is a time tracking plug-in for Eclipse. It runs silently in the background to record how you spend your time within Eclipse and reports the data back to you whenever you want it to - in a useful way.


2. InstaSearch


InstaSearch is an Eclipse plug-in for doing fast text search in the workspace. The search is performed instantly as-you-type and resulting files are displayed in an Eclipse view. It is a lightweight plug-in based on Apache Lucene search engine. Each file then can be previewed using few most matching and relevant lines. A double-click on the match leads to the matching line in the file.


3. Open Extern


This is an eclipse plugin, which you can use to open a shell (either a command prompt - CMD or a linux shell), or a folder (windows explorer, nautilus, konqueror) from eclipse's resource navigator or package explorer. Works on Linux and Windows.


4. Eclipse Todo Editor


Manage your todos in an easy to use text editor with syntax highlighting and code completion. Effectively structure and query your todo lists using projects and custom tags. 


5. MailSnag


With MailSnag, you can debug application generated emails within Eclipse. MailSnag creates a simple SMTP server to capture and inspect emails sent out by an application during development. You can view the email rendered as HTML, text or both. You can also view the raw data, embedded content and attachments.


6. More Clipboard


More Clipboard keeps track of the latest entries copied/cut into clipboard buffer and allows quick pasting from the popup list by pressing a hotkey. Inspired by Multi Clipboard plugin for Eclipse and Visual Assist for MS VS.


7. FileSync 


FileSync plugin for Eclipse is a file synchronisation tool. The main goal is to keep files outside of Eclipse projects in-sync with Eclipse project files. The plugin works as builder in Eclipse and will synchronize all changes on Eclipse project files with mapped external folders. E.g. if a file is created, changed or deleted in Eclipse, then the mapped (external) file will be created, changed or deleted too.


8. AgileReview


AgileReview provides you with an easy possibility to do code reviews in your favorite IDE. Code reviews are a powerful meaning for quality assurance, but switching between spreadsheets and code is very time consuming. With AgileReview you can comment and discuss code without leaving the IDE and more important: without leaving the code.




Tools for Java Developers


9. JAutodoc


JAutodoc is an Eclipse Plugin for automatically adding Javadoc and file headers to your source code. It optionally generates initial comments from element name by using Velocity templates for Javadoc and file headers.


10. JadClipse


 If you use JadClipse the Class File Viewer will be replaced with the JadClipse Class File Viewer that shows the decompiled source of the class. This task is accomplished by decompiling the corresponding class file in the background using Jad. Normal Java syntax highlighting as well as the Outline View are supported.


Unit Testing


11. JUnit Helper


"JUnit Helper" helps JUnit users to cover all tests for public, protected and package local methods by saving much labor to start writing new test cases. Eclipse plugin also has an advantage of making it easier to go back and forth between developing class and test class by "Alt + 8" (test->dev) and "Alt +9"(dev->test).


12. MoreUnit


MoreUnit is an eclipse plugin that should assist you writing more unit test. The following features are implemented: - Decorate classes which have a testcase. - Mark methods in the editor which are under test. - Jump to a testcase in the editor via the menu or a shortcut (and back) - Generate a testmethod stub for the method under cursor-position in the editor via the menu or a shortcut. - Rename/move of classes / methods with corresponding testcases automatically starts refactoring for tests as well.


Looging Helpers


13. Logging code Cleanup for Eclipse


Logging code Cleanup plugin for Eclipse is an extension of the Eclipse Cleaun Ups which detects invocations of logging methods with compound arguments (requiring computation before method call) and prefixes them with corresponding if statements.


14. Log4E


Log4E is an Eclipse Plugin which helps you to set up your logger easily in Java Projects. It assists you in several tasks: logger declaration, logger Insertions at certain method entries, substitution of System out's, modification of already existing logger statements. Log4E has active support for Log4j, Commons Logging and JDK 1.4 Logging. By defining your own templates you might be able to adapt your own logger to the Plugin. 


UML and Code Analysis Tools


15. ModelGoon UML4Java


ModelGoon brings new points of view of a Java project. Thanks to its tight connection and interaction with the Eclipse Java Development Tools JDT. ModelGoon provides also round-trip features on Class Diagrams actually as beta.


16. CodePro AnalytiX


CodePro AnalytiX is the premier Java software testing tool for Eclipse developers who want to be active participants in improving the quality and security of the code they produce. CodePro AnalytiX seamlessly integrates into the Eclipse environment, using automated source code analysis to pinpoint quality issues and security vulnerabilities before code reaches QA, or worse, production!


17. Sonar


Sonar for Eclipse provides comprehensive integration of Sonar into Eclipse. It shows quality issues while browsing the source code. Developers are made aware of quality issues compared to corporate standards without leaving their favorite IDE and thus enabling for continuous improvement with no effort. No propagation of standards changes is required anymore as definition is centralized.


18. MaintainJ


MaintainJ generates the runtime sequence diagrams for a use case. MaintainJ generated diagrams are dynamic, easy to explore and help Java developers to understand, debug and document Java applications.


19. EclEmma Java Code Coverage


EclEmma is a free Java code coverage tool for Eclipse, available under the Eclipse Public License. It brings code coverage analysis directly into the Eclipse workbench


20. eCobertura


eCobertura enables you to launch your applications or tests in Cobertura-covered mode directly from within Eclipse. View your source files colored according to the coverage results. Browse through the detailed coverage results in a tree view.


Note:- The numbering is arbitrary and does not imply the importance. The description about each plugins is copied from the Eclipse Market Place.

Wednesday, 27 March 2013

Log4j



@Author: Mohammed Sajadh NA
@Dated : 27 Mar 2013
@Version : V1.0

·         Log4j is a Reliable, Fast and Flexible Logging Framework (APIs) written in Java.
·         Log4j has three main components:
1)      loggers: Responsible for capturing logging information.
2)      appenders : Responsible for publishing logging information to various preferred destinations.
3)      layouts: Responsible to format logging information in different styles.

log4j Features:
  • log4j is thread-safe.
  • log4j is optimized for speed.
  • log4j is based on a named logger hierarchy.
  • log4j supports multiple output appenders per logger.
  • log4j supports internationalization.
  • log4j is not restricted to a predefined set of facilities.
  • Logging behavior can be set at runtime using a configuration file.
  • log4j is designed to handle Java Exceptions from the start.
  • log4j uses multiple levels, namely ALL, TRACE, DEBUG, INFO, WARN, ERROR and FATAL.
  • The format of the log output can be easily changed by extending the Layout class.
  • The target of the log output as well as the writing strategy can be altered by implementations of the Appender interface.
  • log4j is fail-stop. However, altough it certainly strives to ensure delivery, log4j does not guarantee that each log statement will be delivered to its destination.

log4j – Installation
step 1 :- Download apache-log4j-x.x.x.tar.gz from  http://logging.apache.org/log4j/.
step 2 :-
to be continued (on preparing ..... )


log4j - Architecture
Log4j API has been designed in layered where each layer provides different object which performs different tasks
There are two type of objects available with Log4j framework.
  • Core Objects: These are mandatory objects of the framework and required to use the framework.
  • Support Objects: These are optional objects of the framework and support core objects to perform addition but important tasks.
Core Objects:
A.    Logger object [Capture log info]:- 
a.       The top level layer is Logger which provides Logger object.
b.      Responsible for capturing logging information and they are stored in a namespace hierarchy
B.   Layout object [Formatting log content] :-
a.       Used to format logging information in different styles
C.   Appender object [Publishing log info]
a.       This is lower level layer which provides Appender object
b.     Responsible for publishing logging information to various preferred destinations such as a database, file, console, UNIX Syslog etc.
Support Objects:
A.   Level object :-
a.       The Level object defines the granularity and priority of any logging information
b.      There are seven levels of logging defined within the API: OFF, DEBUG, INFO, ERROR, WARN, FATAL, and ALL.
B.   Filter object :-
a.       used to analyze logging information and make further decisions on whether that information should be logged or not.
C.   Object Rendered :-
a.        The ObjectRenderer object is specialized in providing a String representation of different objects passed to the logging framework.
b.      This object is used by Layout objects to prepare the final logging information.
D.   Log Manager :-
a.       The LogManager object manages the logging framework.
b.      It is responsible for reading the initial configuration parameters from a system-wide configuration file or a configuration class.

                  

log4j – Configuration
The log4j.properties file is a log4j configuration file which keeps properties in key-value pairs. By default, the LogManager looks for a file named log4j.properties in the CLASSPATH.
Steps:-
1)       Defined level [ALL,DEBUG,INFO,WARN,..] of the root logger and attaches appender[FILE,CONSOLE,..] name to it.
2)       Set the appender name to be a valid appender [FileAppender,ConsoleAppender,..].
3)       Set the layout for the appender .

log4j.properties Syntax:
Following is the syntax of log4j.properties file for an appender X:
# Define the root logger with appender X
log4j.rootLogger  = DEBUG, X            -----------------------------à STEP 1

# Set the appender named X to be a File appender 
log4j.appender.X  = org.apache.log4j.FileAppender -------------------à STEP 2

# Define the layout for X appender
log4j.appender.X.layout = org.apache.log4j.PatternLayout ------------à STEP 3
log4j.appender.X.layout.conversionPattern = %m%n

log4j.properties Example:
# Define the root logger with appender file
log4j.rootLogger = DEBUG, FILE    // level of the root logger defined as DEBUG & attaches appender named FILE to it

# Define the file appender
log4j.appender.FILE=org.apache.log4j.FileAppender // appender FILE is defined as org.apache.log4j.FileAppender log4j.appender.FILE.File=${log}/log.out           // writes to a file named "log.out" located in the log directory

# Define the layout for file appender
log4j.appender.FILE.layout=org.apache.log4j.PatternLayout //layout pattern defined is %m%n, means the printed
log4j.appender.FILE.layout.conversionPattern=%m%n         // logging will be followed by a newline character

Different Types of LEVELS, APPENDERS, LAYOUTS
LEVELS :-
ALL
All levels including custom levels.
DEBUG
Designates fine-grained informational events that are most useful to debug an application.
INFO
Designates informational messages that highlight the progress of the application at coarse-grained level.
WARN
Designates potentially harmful situations.
ERROR
Designates error events that might still allow the application to continue running.
FATAL
Designates very severe error events that will presumably lead the application to abort.
OFF
The highest possible rank and is intended to turn off logging.
TRACE
Designates finer-grained informational events than the DEBUG.


Note: A log request of level Lr  in a logger with level Lc, is enabled if Lr >= Lc.
Where Lr=  requested log
                             Lc= log set in configuration file as root logger
ALL < DEBUG < INFO < WARN < ERROR < FATAL < OFF.

See Example 1.1 in Examples
APPENDERS :-
  • AppenderSkeleton
  • AsyncAppender
  • ConsoleAppender
  • DailyRollingFileAppender
  • ExternallyRolledFileAppender
  • FileAppender
  • JDBCAppender
  • JMSAppender
  • LF5Appender
  • NTEventLogAppender
  • NullAppender
  • RollingFileAppender
  • SMTPAppender
  • SocketAppender
  • SocketHubAppender
  • SyslogAppender
  • TelnetAppender
  • WriterAppender
Each Appender object has different properties associated with it, and these properties indicate the behavior of that object.
Property
Description
layout
Appender uses the Layout objects and the conversion pattern associated with them to format the logging information.
target
The target may be a console, a file, or another item depending on the appender.
level
The level is required to control the filteration of the log messages.
threshold
Appender can have a threshold level associated with it independent of the logger level. The Appender ignores any logging messages that have a level lower than the threshold level.
filter
The Filter objects can analyze logging information beyond level matching and decide whether logging requests should be handled by a particular Appender or ignored.

LAYOUT :-
  • DateLayout
  • HTMLLayout
  • PatternLayout
  • SimpleLayout
  • XMLLayout
Using HTMLLayout and XMLLayout you can generate log in HTML and in XML format as well.

log4j - Sample Program
Following is a simple configuration file created for our example. Let me re-iterate it once again:
  • The level of the root logger is defined as DEBUG and attaches appender named FILE to it.
  • The appender FILE is defined as org.apache.log4j.FileAppender and writes to a file named "log.out" located in the log directory.
  • The layout pattern defined is %m%n, which means the printed logging message will be followed by a newline character.

log4j.properties
# Define the root logger with appender file
log = /usr/home/log4j
log4j.rootLogger = DEBUG, FILE
 
# Define the file appender
log4j.appender.FILE=org.apache.log4j.FileAppender
log4j.appender.FILE.File=${log}/log.out
 
# Define the layout for file appender
log4j.appender.FILE.layout=org.apache.log4j.PatternLayout
log4j.appender.FILE.layout.conversionPattern=%m%n
 
 
web.xml
<servlet>
      <servlet-name>eteam-log4j-init</servlet-name>
      <servlet-class>com.sajadhaja.LoggerEvent</servlet-class>
      <init-param>
            <param-name>log4j-property-file</param-name>
            <param-value>WEB-INF/classes/log4j.properties</param-value>
      </init-param>
      <load-on-startup>1</load-on-startup>
</servlet>
com.sajadhaja.LoggerEvent
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import org.apache.log4j.PropertyConfigurator;

public class LoggerEvent extends HttpServlet
{

 public LoggerEvent (){}

 public void init() throws ServletException
  {  
   String strPropertyFile = getInitParameter("log4j-property-file");
   if(strPropertyFile != null)
   PropertyConfigurator.configure((new   StringBuilder(String.valueOf(getServletContext().getRealPath("/")))).append(strPropertyFile).toString());
  }

    private static final long serialVersionUID = 1L;
}
log4j in Java Program
import org.apache.log4j.Logger;
 
import java.io.*;
import java.sql.SQLException;
import java.util.*;
 
public class log4jExample{
  /* Get actual class name to be printed on */
  static Logger log = Logger.getLogger(
                      log4jExample.class.getName());
 
  public static void main(String[] args)
                throws IOException,SQLException{
   
     log.debug("Hello this is an debug message");
     log.info("Hello this is an info message");
  }
}