Coming soon… my new learnings on IBM Websphere
Coming soon my new learnings on IBM Websphere…
Configuring Wired LAN(internet) on Ubuntu
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
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
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
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
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
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
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…
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
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;
}
|
|
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
}
|
|
ExemploARM arm=new ExemploARM();
try {
arm.copyFile(origem, destino);
} catch (FileNotFoundException | IOException ex) {
ex.printStackTrace();
System.out.println(“It’s can’t copy file”);
}
|
|
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
|
|
@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
}
|
|
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”);
}
|
|
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);
}
|
|
try (BufferedWriter writer = Files.newBufferedWriter(file, charset)) {
writer.write(s, 0, s.length());
} catch (IOException x) {
System.err.format(“IOException: %s%n”, x);
}
|
- The new java.util.Objects class provides some nice static convenience methods as described in my blog post JDK 7: The New Objects Class.
- Three new convenience methods have been added to the already useful Collections class:Collections.emptyIterator(), Collections.emptyListIterator(), andCollections.emptyEnumeration().
- New static methods for comparing primitives [similar to the already existingDouble.compare(double,double) and Float.compare(float,float)] are now available for additional numeric/boolean types: Byte.compare(byte, byte), Integer.compare(int,int),Long.compare(long,long), Short.compare(short,short), andBoolean.compare(boolean,boolean).
- Calendar gets some Java 7 attention (even if it’s not the overhaul many of us had hoped for): Calendar.isWeekDateSupported(), Calendar.getWeekYear(),Calendar.setWeekDate(int,int,int), and Calendar.getWeeksInWeekYear(). TheTimeZone.observesDaylightTime() method has also been added. The implementation of this interface that most of us use, GregorianCalendar, has these methods implemented now.
- There are several changes related to Java reflection:
- The java.lang.reflect.Modifier class has new static methods: classModifiers(),interfaceModifiers(), constructorModifiers(), methodModifiers(), andfieldModifiers().
- I have written a more detailed blog post on the new ReflectionOperationExceptionclass.
- ConcurrentLinkedDeque and LinkedTransferQueue are now available.
- The java.util.ConcurrentModificationException has two new constructors that each accept acause and one of them accepts a detailed message as well.
- The java.net.ProtocolFamily interface is new as is the enum StandardProtocolFamily that implements this interface.
- The class InetAddress has a new method called getLoopbackAddress(). The methodInetAddress.isLoopbackAddress() has been available since JDK 1.4.
- ProcessBuilder gets a new nested class called Redirect, which itself contains a nested Typeenum.
- The Character class now contains a nested UnicodeScript enum.
- BitSet.valueOf(long[])
- Multiple JDBC enhancements:
- The Statement interface prescribes two new methods: closeOnCompletion() andisCloseOnCompletion().
- The java.sql.DatabaseMetaData interface has two new methods:getPseudoColumns() and generatedKeyAlwaysReturned().
- JDBC’s CallableStatement gets two new overloaded getObject() methods that get an object based on provided name or index along with the expected object’s class type.
- The Driver class got a new method Driver.getParentLogger() that returns ajava.util.logging.Logger. CommonDataSource gets the same new method.
- File.toPath() provides a java.nio.file.Path.
- There are several new classes and interfaces related to security:
- The new java.security.AlgorithmConstraints interface “specifies constraints for cryptographic algorithms, keys (key sizes), and other algorithm parameters.”
- The new CertificateRevokedException ”indicates an X.509 certificate is revoked.”
- CertPathValidatorException got a new constructor that accepts an implementation of the new nested CertPathValidatorException.Reason interface as a parameter and there is a method to get this reason. The newCertPathValidatorException.BasicReason enum implements theCertPathValidatorException.Reason interface and “enumerates the potential reasons that a certification path of any type may be invalid.”
- The new invokedynamic feature requires new support:
- The new java.dyn.InvokeDynamicBootstrapError is thrown “to indicate that aninvokedynamic instruction” has had some sort of problem (not found or other problem). The MethodHandle class and related functionality are further described in A glimpse at MethodHandle and its usage.
- There is a new reflection exception called WrongMethodTypeException.
- Two new methods have been added to Throwable to support the new try-with-resourcesfeature: addSuppressed(Throwable) and getSuppressed(). Because both Exception andError extend
Throwable, all exceptions and errors can support providing the suppressed exceptions as appropriate. - AssertionError has a new constructor accepting a cause.
- Numerous Swing/AWT-related changes.
- Numerous NIO-related changes (NIO.2).
- Applet even gets something in Java 7: Applet.isValidateRoot().
- New JMX features include the PlatformManagedObject interface and theManagementFactory.getAllPlatformMXBeanInterfaces() method, both of which I discussed in my blog post JDK 7 JMX Platform Management Beans: A First Peek.
- There are numerous new concurrency support constructs coming to JDK 7 above and beyond some I highlighted above.
- The Locale class documentation mentions “1.7″ sixteen times! The 1.7 changes to the class are called out in the class’s main description. One significant method is toLanguageTag()that provides “a well-formed IETF BCP 47 language tag representing this locale.” The static method forLanguageTag(String) provides an instance of Locale corresponding to the provided String representing the “specified IETF BCP 47 language tag.” The very extensive documentation for this method points out an important caveat: “there is no guarantee that toLanguageTag and forLanguageTag will round-trip.” The Java Tutorials’ Creating a Localeis already updated to reflect using Java 7 features of this class. Among other things, it highlights the new nested Locale.Builder class and the new nested Locale.Category enum.
[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
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

Recent Comments