Coming soon… my new learnings on IBM Websphere

December 30, 2011 Leave a comment

Coming soon my new learnings on IBM Websphere… :) :) :)

Categories: Uncategorized

Configuring Wired LAN(internet) on Ubuntu

December 25, 2011 Leave a comment

Hi,

In this post I will explain the ways we can configure Wired LAN connection on Ubuntu. While configuring any network resource we always need the IP Address to connect to the Domain/Network System. And this IP Address we configure either manually or using DHCP option(DHCP – the Dynamic Host Configuration Protocol – allows network devices to automatically obtain a valid IP address from a server.). There are many networking utilities we can use to configure the network, Now let see Network Interface configuration Using Command-Line.

Step 1: Go to Terminal and Type the below command.

gksudo gedit /etc/network/interfaces (if you have GUI)
OR
sudo vi /etc/network/interfaces (use vi if no GUI installed)

Step 2:
-> Change to set if using DHCP

auto eth0
iface eth0 inet manually
TO
auto eth0
iface eth0 inet dhcp

-> Change to set if using Static IP

auto eth0
iface eth0 inet static
address 192.125.1.10
gateway 192.125.1.2
netmask 255.255.255.0

Step 3: Save the file.

Step 4: After you save the file, Its time to restart networking services.

sudo /etc/init.d/networking restart

Now go to Administration -> System Monitor and click on the Resources Tab and observe the Network History to see the Network connection graph.

Yepeee.. you are now connected :)


Thanks,
R Vashi

Phases of Java Class loading

December 10, 2011 Leave a comment

Hi All,

This post is regarding the phases of class loading in any java based application.  I came across a very good write up material, and thought of sharing with all my blog users.

The loading of a class can essentially be broken down into three phases:
1. Loading
2. Linking
3. Initializing.

Most, if not all, problems relating to class loading can be tracked down to a problem occurring in one of these phases. Therefore, a thorough understanding of each phase helps in the diagnosing of class loading problems. The phases are illustrated in Figure 2

class loading

The loading phase consists of locating the required class file (by searching though the respective classpaths) and loading in the bytecode. Within the JVM, the loading process gives a very basic memory structure to the class object. Methods, fields, and other referenced classes are not dealt with at this stage. As a result, the class is not usable.


Linking
is the most complicated of the three phases. It can be broken down into three main stages:

  • Bytecode verification. The class loader does a number of checks on the bytecodes of the class to ensure that it is well-formed and well-behaved.
  • Class preparation. This stage prepares the necessary data structures that represent fields, methods, and implemented interfaces that are defined within each class.
  • Resolving. In this stage, the class loader loads all the other classes referenced by a particular class. The classes can be referenced in a number of ways:
    • Superclasses
    • Interfaces
    • Fields
    • Method signatures
    • Local variables used in methods

During the initializing phase, any static initializers contained within a class are executed. At the end of this phase, static fields are initialized to their default values.

At the end of these three phases, a class is fully loaded and is ready for use.

Note that class loading can be performed in a lazy manner and therefore some parts of the class loading process may be done on first use of the class rather than at load time.

Hope this helps.


Thanks
R Vashi

Using Log4j to log Hibernate queries with values

December 3, 2011 Leave a comment

Hi All,

Hibernate is one of most used ORM framework across the J2EE Applications, It provides many features which helps us to organize the SQL queries in a very easy manner just by playing with java entity bean properties. In this post I will explain the way we can display the named queries in log file including the run time value bindings,

In bigger applications debugging SQL queries is a very crucial thing came into picture, a query containing more SQL Joins is not that easy to debug in case if some misalignment in data found.  To ease that just follow the below steps to enable this sort of hibernate logging in logger(LOG4J).


In Log4j properties add the below two category entries.

log4j.category.org.hibernate.SQL= STDOUT // this is as equivalent hibernate.show_sql=true
log4j.category.org.hibernate.type= DEBUG// this basically prints the bound parameters among other things.

Output in Logger file

Hibernate: select emp0_.dept_id as dept2_1_, emp0_.emp_id as emp1_1_, emp0_.emp_id as emp1_0_0_, emp0_.dept_id as dept2_0_0_, emp0_.emp_join_date as emp3_0_0_, emp0_.emp_name as emp4_0_0_, emp0_.bank_name as bank5_0_0_, emp0_.salary as salary0_0_ from Employee emp0_ where emp0_.dept_id=?
2011-12-03 13:08:50,031 DEBUG [main] AbstractBatcher – preparing statement
2011-12-03 13:08:50,031 DEBUG [main] NullableType – binding ’1′ to parameter: 1
2011-12-03 13:08:50,031 DEBUG [main] AbstractBatcher – about to open ResultSet (open ResultSets: 0, globally: 0)

Hope this helps :)


Thanks
R Vashi

Configure Log4j in simple steps

December 3, 2011 Leave a comment

Hi All,

The logging framework always plays a crucial part in your application. In this post i will explain how to configure Log4J in simple steps.
Step1:

Put the Log4j jars file in classpath.

Step 2:
Create a log4j properties | xml file.

# Set root logger level to INFO
log4j.rootLogger=INFO,STDOUT

log4j.appender.STDOUT=org.apache.log4j.ConsoleAppender
log4j.appender.STDOUT.layout=org.apache.log4j.PatternLayout
log4j.appender.STDOUT.layout.ConversionPattern=%d %p [%t] %C{1} - %m\n

log4j.category.org.hibernate.SQL= STDOUT
log4j.category.org.hibernate.type= STDOUT

XML

<!--?xml version="1.0" encoding="UTF-8"?>

Step 3:
Write a program to load and start the logging in application

private static Logger logger = Logger.getLogger(TestJPAConfiguration.class);

public static void main(String[] args) {

//this is for basic loading
BasicConfigurator.configure();

//Use property configurator to explicit load the log4j properties file.
//PropertyConfigurator.configure(“log4j.properties”);

//in case of using XML config, Use DOM Configurator
// DOMConfigurator.configure(“log4j.xml”);

logger.info(“Log4J Configured  successfully”);

}

Hope this helps. :)


Thanks
R Vashi

XML Schema Validation using JAXB

November 26, 2011 Leave a comment

Hi All,

This is a very small post on a very important part of XML Schema validation. While interchanging the data across different systems using XML format, it becomes  more important to validate the XML data with XML schema. As XSD plays a crucial part to validate all the possible combination of data to carry in XML document.

Now lets see an example of performing XSD Validation using JAXB.

//Setting the Validation
Schema schema;
SchemaFactory schemaFactory = SchemaFactory.newInstance( XMLConstants.W3C_XML_SCHEMA_NS_URI ); //W3C XML Schema Namespace URI.
schema = schemaFactory.newSchema(new File(“src/product.xsd”)); //THE XSD Location
marshaller.setSchema(schema); //Register the schema in marshaller
marshaller.marshal(product, System.out); //marshal the object

To list all the validation  issues in logger  or on system console, you can use my previous post on registering ValidationHandler in JAXB.(Read POST http://wp.me/pQKn2-gj )

Hope this helps.


Thanks
R Vashi

Using ValidationEventHandler while converting XML to Java object in JAXB

November 26, 2011 Leave a comment

Hi All,

JAXB as we know is an API  for XML Binding. It is heavily used in JAX-WS web services as a binding standard. XML Data binding describes the conversion of data between its XML and Java representations.

So this post talks about the phase when we convert the XML Data to its corresponding Java objects. It seems easy as just by calling the unmarshaller.unmarshal method. But what goes behind the scene is not that quite easy.

And think about a scenario where you have data payload in XML format of more than 3mb and just seeing some “NullPointerException” during un-marshalling will make you go mad(specially which I had felt so many times :) ).

So to tackle this lets first of all understand what JAXB does during un-marshalling. JAXB reports validation of data through events.  It uses a handler called as “ValidationEventHandler“, And this handler represent an instance of “ValidationEvent” and provides many details about the un-marshalling related issues.

Lets see in an example(I am taking the base example I have posted in this post) http://rocksolutions.wordpress.com/2010/08/04/sample-on-jaxb-using-eclipse/

Step 1: Create a Custom Handler Class

import javax.xml.bind.ValidationEvent;
import javax.xml.bind.ValidationEventHandler;

public class CustomValidationEventHandler implements ValidationEventHandler {

    public boolean handleEvent(ValidationEvent event) {
        System.out.println("Event");
        System.out.println("Severity:  " + event.getSeverity());
        System.out.println("Message:  " + event.getMessage());
        System.out.println("Linked Exception:  " + event.getLinkedException());
        System.out.println("Locator:::");
        System.out.println("    Line Nbr:  " + event.getLocator().getLineNumber());
        System.out.println("    Column Nbr:  " + event.getLocator().getColumnNumber());
        System.out.println("    Offset:  " + event.getLocator().getOffset());
        System.out.println("    Objct:  " + event.getLocator().getObject());
        System.out.println("    Node:  " + event.getLocator().getNode());
        System.out.println("    URL:  " + event.getLocator().getURL());
        return true;
    }

}


Step 2: Register the Handler with the Unmarshller

unmarshaller.setEventHandler(new CustomValidationEventHandler());


Now run the program and you will see the somewhat similar output.

Severity:  1
Message:  cvc-maxLength-valid: Value 'TESTPRODUCT' with length = '10' is not facet-valid with respect to maxLength '8' for type 'stringWithMaxSize8'.
Linked Exception:  org.xml.sax.SAXParseException: cvc-maxLength-valid: Value 'TESTPRODUCT' with length = '10' is not facet-valid with respect to maxLength '8' for type 'stringWithMaxSize8'.
Locator:::
    Line Nbr:  3
    Column Nbr:  12
    Offset:  -1
    Object:  null
    Node:  null
    URL:  null

One thing which I have observed is that the Node and URL properties are not always available to be set on the locator. This is something which I am investigating will sure post the reasons on the same, would appreciate if somebody share the reason.

Please do share your thoughts about this Post :)


Thanks
R Vashi

Preparing for Java Interview.. well here is the link…

September 4, 2011 Leave a comment

Hi,

Preparing for any interview is one of the toughest job in this universe.  I would like to share one reference link with you all. Hope it helps :)

http://www.java-questions.com/


Thanks
R Vashi

Welcome to Java7 Quick tour

September 3, 2011 Leave a comment

Hi,

While browsing some information about Java 7, I came across a very nice blog covering few major changes in Java 7. Would like to share with all my blog users. Here it goes..

The first example will show switch with String, previously this functionality was only possible  with Enums and integer values. In actual fact the JDK retrieves the hashcode for the String which is an integer. Below is an example of this feature.

String drink=”coffee”;
switch (drink){
case “coffee”:
System.out.println(“So you need milk”);
break;
case “juice”:
System.out.println(“So you need sugar”);
break;
case “refrigerate”:
System.out.println(“So you need ice”);
break;
default:
System.out.println(“unknown drink “);
break;
}
I will now show you the ARM, Automatic Resource management, you don’t need to concern yourself with the resources that will be used in your program because it will automatically close when it exits the Try block. For this just implement the interface java.lang.AutoCloseable, the only method is the Close, The AutoCloseable is the better option than Closeable because an exception is not thrown when you close the resource, in the second picture we can see this.
public void copyFile(File original, File copy) throws FileNotFoundException, IOException {
try (
InputStream in = new FileInputStream(original);
OutputStream out = new FileOutputStream(copy)) {
byte[] buf = new byte[1024];
int n;
while ((n = in.read(buf)) >= 0) {
out.write(buf, 0, n);
}
}// it is automatically close
}
The multi-try, for some people is the most important feature in this version, it now allows many exceptions inside the catch block just separate with a “|” pipe.
ExemploARM arm=new ExemploARM();
try {
arm.copyFile(origem, destino);
catch (FileNotFoundException | IOException ex) {
ex.printStackTrace();
System.out.println(“It’s can’t copy file”);
}
using multy-try
In Java 7 there are some improvements to Generics and collections making it easy to make this type Object. Now it is possible to make generic collections easily with the  diamond operator “<>”
List<Object> diamond=new ArrayList<>(); // diamond
List<Drink> Drinks;
Map<String, List<Drink>> maps=new HashMap<>();
maps.put(“diamond”, drinks=new ArrayList<>() );
maps.put(“other example”, new ArrayList<Bebida>() );
maps.put(“erro”, new ArrayList<>() );
[/code] Picture 4: diamond
Talking more about generic collections there is the annotation @SafeVarargs for ensuring this method is safe.
 Applying this annotation to a method or constructor suppresses unchecked warnings about a non-reifiable variable-arity (vararg) type and suppresses unchecked warnings about parameterized array creation at call sites.
@SafeVarargs
static List asList (T… elements) {
System.out.println(elements);
return null;
}
@SafeVarargs
static void varags(List… stringLists) {
Object[] array = stringLists;
List tmpList = Arrays.asList(42);
array[0] = tmpList; //run with warning
String s = stringLists[0].get(0); // ClassCastException
}
@SafeVarargs
The digit separator allows for good understand when writing big numbers in java code, the only rule is you can’t separate the last and the first number, now you can write separator numbers with the character “_” it is also possible to write Double values and Float values, for example, for the JDK is equals 22 and 2_2. There is also literal in binary, which is most important when programming in embedding devices,  just put “ob” (zero and b) in front of a number, this Features can also use the separator.
long longPrimitive=9_999_999_99;
Long longObjete=9__3234_300l;
double doublePrimitive=232_32.32_12d;
Double doubleObjeto=88_32.32_12d;
int binA=0b01_01;
int binB=0b0101_0111;
if(2222==22_22){
System.out.println(“equals values”);
}
if(binA==5){
System.out.println(“equals binary values”);
}
picture 5: using separator and literal binary.
Other feature interesting is try with resource now it possible instantiate one variable if it does not generate an exception.
BufferedWriter writer=null;
try {
writer = Files.newBufferedWriter(arquivo, charset);
writer.write(s, 0, s.length());
catch (IOException x) {
System.err.format(“IOException: %s%n”, x);
}
Picture 6: before was necessary create the variable
try (BufferedWriter writer = Files.newBufferedWriter(file, charset)) {
writer.write(s, 0, s.length());
catch (IOException x) {
System.err.format(“IOException: %s%n”, x);
}
Picture 7: after using try with resource in java 7 

Some more features..

 

[Source]
http://weblogs.java.net/blog/otaviojava/archive/2011/08/21/welcome-java-7-part-2-jsr-334-coin-0
http://marxsoftware.blogspot.com/2011/03/jdk-7-new-interfaces-classes-enums-and.html


Thanks
R Vashi

javax.persistence.PersistenceException: org.hibernate.PersistentObjectException: detached entity passed to persist

September 3, 2011 Leave a comment

Hi,

One of the issues to get your head around in both Hibernate and JPA is how to handle detached entities. In Hibernate one has to deal with the session object and in JPA it is called the persistence context.

An object when loaded in the persistence context is managed by JPA/Hibernate. You can force an object to be detached (ie. no longer managed by Hibernate) by closing the EntityManager or in a more fine-grained approach by calling the detach() method.

So it is very time consuming to debug when you face “Detached entity” exception being thrown by JPA/HIbernate. THere are few possible things you should look for.

1. See if you trying to persist or merge an entity which has the same id as another entity, and which is already present in the PersistenceContext.

2. See if you you’ve specified that @Id is GENERATED by Hibernate. Do not set an ID before you save/persist it. Hibernate looks at the Entity you’ve passed in and assumes that because it has its PK populated that it is already in the database.
save() and persist() do almost the same things with slightly different semantics . persist() is JPA compliant and save() is a carryover from the original Hibernate. Mainly, save() returns the PK and persist() does not. However, both will generate the PK before the actual SQL INSERT happens (if the PK is generated and not assigned).

One workaround I did to solve this was to first find and then save the entity. See below example.

@PersistenceContext(unitName = “JPAUnit”)
private EntityManager em;

public void saveDetails(EntityManager em, User user){
em.find(User.class, user.getId());
em.persist(user);

}


Thanks
R Vashi

Follow

Get every new post delivered to your Inbox.

Join 55 other followers