Showing posts with label Java. Show all posts
Showing posts with label Java. Show all posts

Friday, February 10, 2012

Java ClassNotFoundException and NoClassDefFoundError

These responses http://stackoverflow.com/a/3198490/37144 and  http://stackoverflow.com/a/2213496/37144  do not have many up votes but in my opinion they are the best ones.

A very useful tool used for locating class files - JarScan. It has an online version and offline version that can be used for searching local file system. However, the online version's database isn't too big and might not auit everyone'e requirement. For that, one can visit findJar


Tuesday, July 13, 2010

Setup EJB 3 MDB on Weblogic using Eclipse

Setup EJB 3 MDB Project on Eclipse Shown below is a common exception which occurs when class is executed from Eclipse that depends on Weblogic libraries -
Exception in thread "main" java.lang.NoClassDefFoundError: weblogic/kernel/KernelStatus 
    at weblogic.jndi.Environment.,clinit9(Environment.java:78) 
    at weblogic.judi.WLInitialContextFactory.getInitialContext(WLInitialContextFactory.java:117) 
    at javax.naming spi NamingManager.getInitialContext(NamingManager.java:667) 
    at javax.naming InitialContext.getDefaultInitCtx(InitialContext.java:288) 
    at javax.naming.InitialContext.init(InitialContext.java:223) 
    at javax.naming InitialContext.einit,(InitialContext.java:197) 
    at com.MessageGenerator.getInitialContext(MessageGenerator.java:42) 

Tuesday, May 18, 2010

Technical Benefits of C over Java

While C requires more from a programmer, C can do things that Java can't easily do. Build a virtual memory manager, preemptive multi-tasking, a boot loader, a self-contained executable program. We expect an operating system to keep on running after an application crashes. We expect an operating system to reclaim resources after a process ends. We do not yet expect this from Java itself.

Inside Arrays.asList(T… a)

A small article explaining why we cannot add elements to the List returned by Arrays.asList(T... a) method - Inside Java: Arrays.asList(T… a)

Thursday, September 10, 2009

Weblogic 9.2 and Java 6 runtime

When we try to execute and Weblogic J2EE code in Java 6 Runtime using weblogic 9.2 libraries in a small sample code, we get the following exception :

 
[Root exception is java.rmi.UnmarshalException: failed to unmarshal class weblogic.security.acl.internal.AuthenticatedUser; nested exception is: 
 java.io.StreamCorruptedException: invalid type code: 31]
 at weblogic.management.Helper.getMBeanHomeForName(Helper.java:105)
 at weblogic.management.Helper.getAdminMBeanHome(Helper.java:38)
 at WeblogicMBean.main(WeblogicMBean.java:23)


After some search on google, I found the following link which exactly explains the problem :
Serialization error when client app on JDK1.6 access WebLogic on JDK1.5

I tried the suggested solution by starting JVM with the arguments -> -Dsun.lang.ClassLoader.allowArraySyntax=true
and it worked perfectly fine.

Tuesday, December 23, 2008

Xalan, Java, XSLTC

What is difference in xalan XSLT processor and and SUN XSLTC compiler ?
They are completely different products. They are both XSLT processors, but they do the same job in very different ways: Xalan (like nearly all other XSLT processors) is in effect a stylesheet interpreter while XSLTC is a stylesheet compiler: it generates Java bytecodes which can be executed directly by the Java VM.

IBM's JDK includes XSLT4J which is based on Xalan. IBM JDK 1.5 it is based on Xalan Java 2.6.0. So there should be no issue moving from Xalan to the IBM JDK.

SUN's JDK 1.5 contains only XSLTC which does not have all of the features of the Xalan interpretive processor. The main differences are in extension support. XSLTC does not support the following extensions:
  • Dynamic EXSLT extensions
  • NodeInfo extension functions
  • SQL library extension
  • PipeDocument extension
  • Evaluate extension
  • Tokenize extension
  • JavaScript extensions
In addition to the above :
  • It does not support all of the XSLT type to Java type conversions that the interpreter supports. You may be able to work around this by adding an explicit cast (e.g. call to the boolean(), number(), etc. function).
  • It does not work well if you return a Boolean object instead of a boolean from a Java extension, or a Double object instead of a double, etc. You can work around this by returning the primitive types instead of objects.
  • It does not provide a default object when the method being called is not static and no object is provided in the extension call. You can work around this by providing the object in the extension call.
It only supports the abbreviated syntax for Java extension calls (see Using the abbreviated syntax for extensions implemented in Java)

So, when you use SUN's JDK 1.5 or later for Transformation on an XSL like this






You will get the following error:

ERROR: 'The first argument to the non-static Java function 'completeTaskOnExit' is not a valid object reference.'
FATAL ERROR: 'Could not compile stylesheet'
Exception in thread "main" javax.xml.transform.TransformerConfigurationException: Could not compile stylesheet
at com.sun.org.apache.xalan.internal.xsltc.trax.TransformerFactoryImpl.newTemplates(Unknown Source)
at com.sun.org.apache.xalan.internal.xsltc.trax.TransformerFactoryImpl.newTransformer(Unknown Source)
at Transform.main(Transform.java:29)


If you want to continue to use the Xalan interpreter with SUN's JDK you can use the endorsed standards override mechanism - Create the "endorsed" directory in "...\jre\lib\endorsed" and copy the Xalan 2.7 files into it.

If you are using Xalan 2.8, then extracting "xalan.jar" from 'Xerces-J-tools.2.8.1.zip' and copying it into the 'endorsed' directory solves the problem of not finding 'org.apache.xalan.processor.TransformerFactoryImpl'.

OR you can also force the SUN JDK to use Xalan by setting the System property :

System.setProperty("javax.xml.transform.TransformerFactory", "org.apache.xalan.processor.TransformerFactoryImpl");

References:
Ad xslt-sample (not working on Java 1.5 & 1.6) ...
what is difference in xalan XSLT processor and and SUN XSLTC compiler
jdk1.5 and Xalan.jar differences?

Friday, November 28, 2008

Java code to execute a command etc

Java code to execute a command and enter input to that command and view output of that command.


import java.io.*;

public class CommandInput {
public static void main(String args[]) throws Exception{
String cmd = "java HelloWorld";
String passwd = "P@ssw0rd";
Runtime rt = Runtime.getRuntime();
Process p = rt.exec(cmd);
(new ConsolePrint(p.getInputStream())).start();
(new ConsolePrint(p.getErrorStream())).start();
BufferedWriter commandWriter = new BufferedWriter(new OutputStreamWriter(p.getOutputStream()));
commandWriter.write(passwd);
commandWriter.close();
}
}

class ConsolePrint extends Thread{
InputStream is ;
ConsolePrint(InputStream is){
this.is = is;
}
public void run(){
BufferedReader br = new BufferedReader (new InputStreamReader(is));
String line = "";
try{
while ((line=br.readLine())!=null) {
System.out.println(line);
}
}catch(IOException ioe){
System.out.println(ioe.getMessage());
}
}
}

Friday, October 24, 2008

JSP KeepGenerated in Weblogic 9 and 10

By default Weblogic deletes the java files generated during the transation phase of a jsp. It just retains the .class files. These java files are sometimes very useful in debugging a jsp.

It can be achieved by modifying the weblogic.xml in the following way :

<jsp-descriptor>
<precompile>false</precompile>
<precompile-continue>false</precompile-continue>
<keepgenerated>true</keepgenerated>
<verbose>true</verbose>
<working-dir>c:/temp/bea</working-dir>
</jsp-descriptor>

If this does not work, then login to Weblogic Admin Console. Go to Deployments. Select your application. If it is an enterprise application you may have to choose the sub-module. Go to Configuration. Apply Lock and Edit. Check the Keepgenerated flag and save the changes.

You may have to restart the server !!!

Sunday, October 5, 2008

GDuration & Duration manipulation

There is a lot of difference between the Java Bean generated for xsd:duration using Apache xbean.jar and Weblogic weblogic ant target jwsc/wsdlc.

While the Apache translates it to org.apache.xmlbeans.GDuration, Weblogic translates it to java.lang.String. Since a String can be anything, it is recommended to use the toString() method in Java XML datatype API javax.xml.datatype.Duration to have consistent behaviour.

So, if there is a requirement to have both the xml beans, then create javax.xml.datatype.Duration using any of the methods present in javax.xml.datatype.DatatypeFactory and then convert it to the required formats.


Duration duration = DatatypeFactory.newInstance().newDuration(durationInMillis);
//for Apache
GDuration gDuration = new GDuration(1, duration.getYears(), duration.getMonths(), duration.getDays(),duration.getHours(),duration.getMinutes(),duration.getSeconds(), null);
//for Weblogic
String s = duration.toString();

Notice that the sign of the duration(positive or negative) is hard-coded as 1(positive). The getSign() method in javax.xml.datatype.Duration returns -1,0,+1. But the passing 0 to the GDuration(int,int,int,int,int,int,int,java.math.BigDecimal) constructor throws an IllegaArgumentException. Also, javax.xml.datatype.Duration does not have a method to return fraction part of the duration unlike the getFraction() method in org.apache.xmlbeans.GDuration.

To get the total number of milliseconds from javax.xml.datatype.Duration, we just need to call either getTimeInMillis(java.util.Calendar)
or getTimeInMillis(java.util.Date). However there is no equivalent API in org.apache.xmlbeans.GDuration.

To get the total number of milliseconds from org.apache.xmlbeans.GDuration, we need to do the following :


GDuration gDuration = new GDuration(durationString);
Calendar cal = Calendar.getInstance();
cal.setTimeInMillis(0);
GDate base = new GDate(cal);
GDate d = base.add(gDuration);
long durationInMillis = d.getDate().getTime();

Monday, July 21, 2008

Remove duplicates from a List


Set set = new HashSet();
set.addAll(list);

// avoid overhead :D
if(set.size() < list.size()) {
list.clear();
list.addAll(set);
}

Wednesday, July 2, 2008

Find the path of class being loaded


java.net.URL codeBase = (Class).getClass().getProtectionDomain().getCodeSource().getLocation();
System.out.println(codeBase.getPath());

Monday, December 10, 2007

Java Interview FAQ

Below is a list of most frequently asked interview questions in Java. I am not furnishing any answers here because you can easily find them on google for one reason. And for many questions there is no single correct answer. So people are free to post their versions in the comments. Also, please do add to the list any other FAQ which I might have missed.
  1. Why is Java Platform independent? How does it acheive it?
  2. abstract class vs interface
  3. What is polymorphism?
  4. What is multiple inheritance? Does Java support it?
  5. overloading vs overriding
  6. String vs StringBuffer
  7. Why is String immutable? How do you make a class immutable?
  8. Hashtable vs HashMap
  9. What is multi-threading?
  10. How do you make a program multi-threaded?
  11. What is synchronized?
  12. What is final?
  13. final vs finally vs finalize
  14. How are Exceptions handled in Java?
  15. Checked Exception vs Unchecked/Runtime Exception
  16. What is serialization?
  17. What is singleton design pattern?
  18. What are inner classes?