Introduction to RESTful Web Services


REST is a “Representational state transfer” and it is firstly introduced by Roy Fielding (Fielding is one of the principal authors of the HTTP specification and a co-founder of the Apache HTTP Server project) in his 2000 doctoral dissertation.

REST-style services (i.e., RESTful services) adhere to a set of constraints and architectural principles that include the following:

  1. RESTful services are stateless. As Fielding writes in Section 5.1.3 of his thesis, “each request from client to server must contain all the information necessary to understand the request, and cannot take advantage of any stored context on the server.”
  2. RESTful services have a uniform interface. This constraint is usually taken to mean that the only allowed operations are the HTTP operations: GET, POST, PUT, and DELETE.
  3. REST-based architectures are built from resources (pieces of information) that are uniquely identified by URIs. For example, in a RESTful purchasing system, each purchase order has a unique URI.

REST components manipulate resources by exchanging representations of the resources. For example, a purchase order resource can be represented by an XML document. Within a RESTful purchasing system, a purchase order might be updated by posting an XML document containing the changed purchase order to its URI

Happy to share 2011 in review


The WordPress.com stats helper monkeys prepared a 2011 annual report for this blog.

Here’s an excerpt:

The concert hall at the Syndey Opera House holds 2,700 people. This blog was viewed about 15,000 times in 2011. If it were a concert at Sydney Opera House, it would take about 6 sold-out performances for that many people to see it.

Click here to see the complete report.

Interface in Java


Interfaces can be used to implement the Inheritance relationship between the non-related classes that do not belongs to the same hierarchy, i.e. any Class and any where in hierarchy.  Using Interface, you can specify what a class must do but not how it does.

  1. A class can implement more than one Interface.
  2. An Interface can extend one or more interfaces, by using the keyword extends.
  3. All the data members in the interface are public, static and Final by default.
  4. An Interface method can have only Public, default and Abstract modifiers…. More

Java Servletes


Servlet is a Java class used to extend the capabilities of servers that host applications accessed via a request-response programming model. Although servlets can respond to any type of request(like HTTP, FTP), they are commonly used to extend the applications hosted by Web servers.
Servlets runs at Server side typically Web Server or Application server, and respond to request by giving the response to user after processing the request…… More

Log4j API – Sample Programs


Log4j Examples:

The basic example to implement the Log4j:

import org.apache.log4j.Logger;

public class LogExample {

public LogExample() {
}
static Logger log = Logger.getLogger(LogExample.class);

public static void main(String argsp[]) {

log.debug(“projectname-modulename-Class-method-Here is some DEBUG”);
log.info(“projectname-modulename-Class-method-Here is some INFO”);
log.warn(“projectname-modulename-Class-method-Here is some WARN”);
log.error(“projectname-modulename-Class-method-Here is some ERROR”);
log.fatal(“projectname-modulename-Class-method-Here is some FATAL”);
log.warn(“projectname-modulename-Class-method-Here is some WARN”);

}
}

 

The sample example to read the log4j configurations from properties file:

import org.apache.log4j.Level;
import org.apache.log4j.Logger;
import org.apache.log4j.PropertyConfigurator;

public class Example2  {

public static void main(String a[])
{
Logger l=Logger.getLogger(Example2.class);

PropertyConfigurator.configure(“src/prop.properties”);

l.setLevel(Level.DEBUG);
l.debug(“Myprojectname-modulename-Class-method-ok executedddddddddddddd”);
l.info(“projectname-modulename-Class-method-some infoooooooooo”);
l.warn(“projectname-modulename-Class-method-warn msg”);
l.error(“projectname-modulename-Class-method-error msg……”);
l.fatal(“projectname-modulename-Class-method-this is some fatal errrrrrrr”);
}
}

Log4j configurations in properties file: prop.properties

log4j.rootLogger=debug, stdout
log4j.appender.stdout=org.apache.log4j.DailyRollingFileAppender
log4j.appender.stdout.File=logs/dailyrollfile3333.txt
log4j.appender.stdout.DatePattern=’.’yyyy-MM-dd-HH-mm
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%r  [%t]  %p  %c  %m  %d  %n

 

Implementing log4j with Console appender :

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

import org.apache.log4j.ConsoleAppender;
import org.apache.log4j.Layout;
import org.apache.log4j.Level;
import org.apache.log4j.Logger;
import org.apache.log4j.SimpleLayout;

//ConsoleAppender
public class Example1 {

public static void main(String a[])
{
Logger l=Logger.getLogger(Example1.class);
Layout lay=new SimpleLayout();
ConsoleAppender ap=new ConsoleAppender(lay);

l.addAppender(ap);
l.setLevel(Level.DEBUG);

try{
Class.forName(“oracle.jdbc.driver.OracleDriver”);
l.debug(“driver loaded”);
Connection con=DriverManager.getConnection(“jdbc:oracle:thin:@192.168.1.214:1521:XE”,”kiran”,”kiran”);
l.info(“connection established successfully”);

}catch(ClassNotFoundException e)
{
l.fatal(” OOPS………DriverClass Problem(plz check Driverclass)”);
e.printStackTrace();
}catch(SQLException se)
{
l.fatal(“OOPS…………Db Connection Problem”);
se.printStackTrace();
}
catch(Exception se)
{
l.error(“OOPS…………Db Problem”);
se.printStackTrace();
}

}
}

 

File Appender example in Log4j :

import java.sql.Connection;
import java.sql.DriverManager;

import org.apache.log4j.*;

//FileAppender

public class Example2  {

public static void main(String a[])
{
Logger l=Logger.getLogger(Example2.class);
try{
Layout lay=new SimpleLayout();
FileAppender ap=new FileAppender(lay,”sample.log”,true);
l.addAppender(ap);
l.setLevel(Level.DEBUG);
}catch(Exception d)
{
l.debug(“log4j stmts problem”);
}
try{
Class.forName(“oracle.jdbc.driver.OracleDriver”);
l.debug(“driver loaded……”);
Connection con=DriverManager.getConnection(“jdbc:oracle:thin:@192.168.1.214:1521:XE”,”kiran”,”kiran”);
l.info(“connection established successfully……….”);

}catch(Exception e)
{
l.fatal(“Db Problem”);
e.printStackTrace();
}
}
}

Caching in Hibernate


Caching is a Temporary memory or buffer which resides at client side and stores the results sent by server. When client generates same request for multiple number of times, the first request generated results will be stored in cache and this result will be used across the multiple requests. This reduces the round trips between the client and server. Since the result will be collected from cache that is available at client side.

Hibernate supports for 2 levels of cache:

  1. Level one cache
  2. Level two cache.

Level One Cache:

Level 1 cache is inbuilt cache and it will be associated with hibernate session objects. Every session object of hibernate application contains one inbuilt level one cache.

Responsibilities of Level one cache:

a)      If select query executed for multiple no of times with in a session. Only one time query goes to database software gets the result, remaining all the times result will be gathered from cache.

b)      If one of pojo class object is modified for multiple no of times with in a transaction of session object, instead of sending update query for multiple number of times, all the changes done on the object wil be kept tracked and only one update query wil be generated reflecting all the changes at the end of the transaction.

The different ways to remove the level 1 cache from session

i)                    Session.flush() –>  Flushes level one cache content to db software

ii)                   Session.evict() –> Remove the content of level 1 cache

iii)                 Session.close() –> closes level 1 cache, before that it calls session.flush()

A hibernate client application can have multiple level1 caches because a hibernate application can have multiple hibernate session objects.

The data stored in level1 cache, level2 cache will be in full synchronization with table rows.

Level-2 Cache:

It is a configurable cache (Not a built in cache). Third party vendors are supplying supporting jar files for level 2 cache. Level2 cache is global cache and it is visible for all the session objects of the hibernate application.

When level-2 cache is enabled the results gathered for database software will be stored in both level 1 and level 2 caches.

sessionFactory.close() –> Destroys the session factory object and releases level 2 cache.

sessionFactory.evict(arga …) –> Removes pojo class object from session factory.

sessionFactory.evictQueries(args…) –> Cleans queries related data from cache.

If hibernate use same request as second request or different session objects then software tries to collects the results either from leve1/level2 caches.

There are different third party providers for level 2 cache:

  1. Swarm Cache
  2. OS Cache,
  3. EH Cache
  4. JBoss Tree Cache … etc.

Replace String Example in Java


/**
 * @author Mallikarjun G
 *
 */
public class JavaStringReplaceExample {
    /**
     * @param args
     */
    public static void main(String args[]) {      
        String str = “Replace String”;
        System.out.println(str.replace(‘R’, ‘A’));// Replaceing R with a in str
        System.out.println(str.replaceFirst(“Re”, “Ra”));// Replaceing First Re with Ra in str  
        System.out.println(str.replaceAll(“Re”, “Ra”)); // Replaceing All Re with Ra in str   

    }
}

Connecting SQL Server using Java/JDBC


Below program consists of steps to connect SQL server using JDBC

package com.javatutorials;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

public class SqlServerConnection {
public static Connection connection = null;
public static Connection getDbConnection() {
try {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
connection = DriverManager
.getConnection("jdbc:odbc:mydsn;user=sa;password=sa12$");
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
return connection;
}

public static void closeConnection() {
if (connection != null)
try {
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}