Tuesday Mar 15, 2011

Blog Migration

This blog will be soon moved to Oracle blogs .Let's see if I could blog more frequently after the migration.

Tuesday Nov 23, 2010

java.lang.NoClassDefFoundError: org/codehaus/plexus/classworlds/launcher/Launcher

Recently when I am trying to run some Maven scripts, I am  getting this exception:

Exception in thread "main" java.lang.NoClassDefFoundError: org/codehaus/plexus/classworlds/launcher/Launcher

Caused by: java.lang.ClassNotFoundException: org.codehaus.plexus.classworlds.launcher.Launcher

at java.net.URLClassLoader$1.run(URLClassLoader.java:202)

at java.security.AccessController.doPrivileged(Native Method)

at java.net.URLClassLoader.findClass(URLClassLoader.java:190)

at java.lang.ClassLoader.loadClass(ClassLoader.java:307)

at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:301)

at java.lang.ClassLoader.loadClass(ClassLoader.java:248)

Could not find the main class: org.codehaus.plexus.classworlds.launcher.Launcher.  Program will exit.

After spending some time trying various combinations , I found that this is because I have both M2_HOME and M3_HOME set in my environment variables.Once I removed M2_HOME from my environment variables, I could get this working back again.May be this could save some serious time for  some one.


Tuesday Oct 05, 2010

bean archives in Java EE6

Jave EE6 comes with a new feature called CDI (Context Dependency Injection).This allows you to inject beans and various other J2EE resources in to your application.

For CDI to roll in into your application, there should be a way to tell that the container that you want to use this feature.This is done through beans.xml.

This beans.xml file must be placed  in either META-INF/beans.xml and WEB-INF/beans.xml directory of your application to get it work.This file can be simply a place holder file which tells the run time that this module has beans that need to be used for CDI.Apart from that this file allows you to declare your interceptors, decorators and alternatives that you want to use.

 So any archive that comes with a beans.xml is said to be bean archive and the container only looks into bean archives for beans to be used as a part of CDI .

For more information about bean archive refer this document and for  a good explanation about why you need beans.xml , look here

Monday Jun 28, 2010

error while loading shared libraries: libstdc++.so.5

I have a habit of formatting the hard disk on my laptop every time a new version of Linux operating system or some variant of it is released.Every time I do that and start my work, I face this issue while installing Glassfish V2.

When I try to install Glassfish v2 (and many other applications) it reports with the following error message :

sreekanth@Auriferous:/space/Sreekanth/servers$ ./sges-2_1_1-linux.bin
./sges-2_1_1-linux.bin: error while loading shared libraries: libstdc++.so.5: cannot open shared object file: No such file or directory

So I use our best friend Google to find out a solution.Then forget what I did next time.So I wanted to make a note of it some where this time so that I can refer back and may be it is useful for some other guys out there.So here goes the solution which works for me:

Download the needed libraries from here:

http://packages.debian.org/lenny/i386/libstdc++5/download

and then install using sudo dpkg -i libstdc++5_3.3.6-18_i386.deb

Thats all and If you know or come across a better solution , please post it  here.Thanks for reading.



Wednesday Mar 17, 2010

Custom Validators in Metro Web Services Security

Although its simple to implement, here are the steps to implement plain text username/password validator for your web services security using Netbeans 6.8  and Glassfishv3 for those who were unable to get this work.
  1.  Create a new Netbeans Web Application project as shown and select the target server and click Finish.


  2. Right click on the project just created and then New --> Web Service, Enter web service name and package information and then click on Finish button.
  3. Click on Design tab of the web service and then in the GUI click on  Advanced  button to view QoS window .
  4. Select check box with name Secure Service and select User name Authentication with Symmetric Key as Security mechanism .Also select Use Development defaults.Click on ok.
  5. Now create your validator using new class wizard which extends PasswordValidationCallback.DerivedKeyPasswordValidator class.
  6. Goto Web pages and then WEB-INF folder and then open your webservice config file.This would be the file with naming pattern - wsit-<packagename>.<webservicename>.xml
  7. Locate the keystore configuration section in the wsit config file and add the below lines and save it.

    <sc:ValidatorConfiguration wspp:visibility="private">
                        <sc:Validator name="usernameValidator" classname="simple.server.SimpleValidator"/>
                    </sc:ValidatorConfiguration>
  8. Now deploy the application.
  9. Now create a client app using new webapplication wizard similar to step 1  
  10. Now create a webservice client --> check the Project radio button -->Click on Browse and select the webservice which we created earlier and click on Finish .
  11. Traverse to Webservice reference section in your client app and then open Webservice reference folder and then right click on the webservice and then select Edit Webservice attributes .
  12. Under security section , select the check box, use development defaults and click ok.
  13. Now goto Source packages in the Client project and then open the client wsit config file.Here PingWebServiceservice.xml and modify the section

     <sc:CallbackHandlerConfiguration wspp:visibility="private">
                        <sc:CallbackHandler default="wsitUser" name="usernameHandler"/>
                        <sc:CallbackHandler default="changeit" name="passwordHandler"/>
                    </sc:CallbackHandlerConfiguration>

    to use your username and password like:


     <sc:CallbackHandlerConfiguration wspp:visibility="private">
                        <sc:CallbackHandler default="sreekanth" name="usernameHandler"/>
                        <sc:CallbackHandler default="sreekanth" name="passwordHandler"/>
                    </sc:CallbackHandlerConfiguration>

  14. Now create a servlet program to test the webservice
  15. Modify the servlet code to call the webservice.(webservice can be called using the keyboard shortcut: alt+insert->Call Webservice operation and then select the web service operation in the popup window as appropraite)
  16. Now deploy your client app and run.In the attached client project , the servlet is called with the url http://localhost:8080/CustomValidatorClient/TestServlet
  17. Check to see if your Validator is called.

References/Resources:

  1. To know about how validators work refer to section "Configuration for Plain-Text Username/Password Validation " in this blog and "Configuring Validators " in this article.
  2. Sample Netbeans server and client application that is created for the demo purpose can be downloaded  from here.





Thursday Dec 10, 2009

Configuring Keystore dynamically in WebServices using Metro

    In most secure webservice scenarios we configure keystore using the keystore confuguration tag in the service policy file.But at times we may want to configure the keystore dynamically at run time as to which keystore to use basing on some condition.
In such cases we can use another variant of keystore configuration where we can specify the callback handler that can be used to select and load the keystore.

<sc:Keystore
   alias={the certificate alias from the  keystore to be used for Signatures}
   aliasSelector={the fully qualified classname of a class implementing com.sun.xml.wss.AliasSelector interface}?
   callbackHandler={fully qualified classname of a class implementing javax.security.auth.callback.CallbackHandler, should be able to handle  com.sun.xml.wss.impl.callback.KeyStoreCallback and  com.sun.xml.wss.impl.callback.PrivateKeyCallback}
/>

For more information refer to Dynamic KeyStore configuration section in Kumar's blog.

Here is a short description of such as case.

   1. Create a simple webservice using Netbeans.
   2. Now configure it to be a secure service.If you aren't aware of how to configure webservice security , refer to metro guide.Here I configured the service to use UserName authentication with Symmetric Key.
   3. Now open the service policy file and try to find the Keystore configuration tag:(similar to the one below)

<sc:KeyStore wspp:visibility="private" location="/space/Sreekanth/servers/glassfishv3/glassfish/domains/domain1 /config/keystore.jks" type="JKS" storepass="changeit" alias="xws-security-server"/>

   4. Now modify that keystore configuration to use "callbackhandler" attribute as below:
<sc:KeyStore wspp:visibility="private" type="JKS"   alias="bob" callbackHandler="simple.server.MyKeyStoreCallbackHandler"/>
   5. Write your own CallbackHandler to handle KeystoreCallback and PrivateKey call back.This is how handle() method of my callbackhandler looks like:

public class MyKeyStoreCallbackHandler implements CallbackHandler {

...

       public void handle(Callback[] callbacks) throws IOException, UnsupportedCallbackException {

        for (Callback callback : callbacks) {

            if (callback instanceof KeyStoreCallback) {

                java.io.FileInputStream fis = null;

                try {

                    keystore = KeyStore.getInstance(KeyStore.getDefaultType());

                    String AS_HOME = System.getProperty("com.sun.aas.installRoot");

                    System.out.println("AS_HOme..." + AS_HOME);

                    fis = new java.io.FileInputStream(AS_HOME + "/xws-security/etc/server-keystore.jks");

                    keystore.load(fis, "changeit".toCharArray());

                    System.out.println("Keystore loaded..");

                    ((KeyStoreCallback) callback).setKeystore(keystore);

                } catch (NoSuchAlgorithmException nsae) {

                    System.out.println("Exception : " + nsae.getMessage());

                    nsae.printStackTrace();

                } catch (KeyStoreException kse) {

                    System.out.println("Exception : " + kse.getMessage());

                    kse.printStackTrace();

                } catch (CertificateException ce) {

                    System.out.println("Exception : " + ce.getMessage());

                    ce.printStackTrace();

                } finally {

                    if (fis != null) {

                        fis.close();

                    }

                }

            } else if (callback instanceof PrivateKeyCallback) {

               PrivateKey privateKey = null;

                Properties properties = new Properties();

                this.keyStorePassword = properties.getProperty("keystore.password");

                Certificate certs[] = null;

                try {

                    privateKey = (PrivateKey) keystore.getKey("bob", "changeit".toCharArray());

                    certs = keystore.getCertificateChain("bob");

                } catch (KeyStoreException ex) {

                    System.out.println("KeyStoreException : " + ex.getMessage());

                    ex.printStackTrace();

                } catch (NoSuchAlgorithmException nsae) {

                    System.out.println("NoSuchAlgorithmException : " + nsae.getMessage());

                    nsae.printStackTrace();

                } catch (UnrecoverableKeyException uke) {

                    System.out.println("UnrecoverableKeyException : " + uke.getMessage());

                    uke.printStackTrace();

                }          

                ((PrivateKeyCallback) callback).setKey(privateKey);

                System.out.println("Private Key callback Handled...");

            }

        }

}
   6. Now deploy your service
   7. Create a sample webservice client and invoke the client.
   8. Now you see the keystore is loaded from the callback handler we wrote.
   9. If you deploy a jsr109 webservice, then metro will try to search for the default keystores in glassfish server.Try using non 109 app.





Wednesday Nov 25, 2009

Using Simple Framwork to Serialize Java Objects to XML and Deserialize from XML to Java

Today I came across 2 different Java frameworks: First one is Play and the other is Simple.

I skimmed through the documentation for Play for a few minutes and then I had to go to my lunch and then I completely forgot about that until I decided to write this blog.Will have to give a try this later.Actually while looking at the Play documentation and some other articles in the recent days, I see a clear trend moving  from Centralised repositories like CVSNT ,SVN to Decentralised versioning control systems like Mercurial,GIT,Bazaar(Bazaar says it supports multiple workflows and there is no reason to choose from CVS or DCVS ) etc.

Now lets talk about Simple.Simple is a small Java framework used to serialize Java objects to XML and deserializes XML back to Java(Not sure if there are any other use cases).The home page says "This framework aids the development of XML systems with minimal effort and reduced errors. It offers full object serialization and deserialization, maintaining each reference encountered."

If you look at the javadocs, you will get a clear idea how the various parts of a Java Class are transformed from Java to XML.

For example look at ElementList .This is how object of Type ArrayList are converted.

    <list class="java.util.ArrayList">
       <entry name="one"/>
       <entry name="two"/>
       <entry name="three"/> 
    </list>

Similarly a Map:

    <map class="java.util.HashMap">
       <entry key="one">value one</entry>
       <entry key="two">value two</entry>
       <entry key="three">value three</entry>
    </map>

If you have worked with Spring, this may not be a new thing to you at all.I found the java docs self explanatory and recommend to go through various classes and annotations so that you will get an idea what features we have in this framework.

To start with you need to know about Serializer and Persister classes.Serializer is the interface used to serialize an object to XML and deserialize an object back from XML to Java and Persister is a concrete implementation class for Serializer.

The 2 processes are pretty simple and straight forward.Lets see how can serialize a java object.

1) Get  a Serializer
Serializer serializer = new Persister();

2)Now play with your class that needs to be serialized, like instantiation and then some operations on it or what ever you want.
MyClass myObj = new MyClass("Some data", "any thing you want");

3)Now create a File object to store the serialized XML file.
File targetFile = new File("MyObject.xml");

4)And finally serialize it.
serializer.write(myObj,targetFile);

After this you will see that the object is serialized to an XML file you specified.Similary for deserialization,all you need to do is :

Serializer serializer = new Persister();
File source = new File("MyObject.xml");
MyClass myObj = serializer.read(MyClass.class, source);

Here are some important annotations that you need to know to transform your Java object to XML

   1. @Root (Will be the class)
   2. @Element
   3. @Attribute

If you want to give your own name to the transformed XML  tags ,you can use "name" attribute of the annotations.
Some times you may want to specify some elements as optional.Then you can use "required=false" attribute of Attribute annotation.

 Other annotations that you will need is to convert the Collection objects like ArrayList,Map etc.Here are a few examples:

@ElementArray
private Address[] addresses;

@ElementMap(entry="property", key="key", attribute=true, inline=true)
   private Map<String, String> map;

There are many other important features that you will need if want to use this.If you want to continue learn more about this framework, then visit the nice tutorial page those guys have put up about this framework.Happy reading.


Thursday Nov 05, 2009

Servlet [ActivationCoordinatorPortTypeImpl] and Servlet [RegistrationPortTypeImpl] have the same url pattern

Last Friday while I was creating a web service client application using Glassfish V3 and Netbeans 6.8, I had come across this problem/exception.

SEVERE: Servlet [CoordinatorPortTypeImpl] and Servlet [CompletionCoordinatorPortTypeImpl] have the same url pattern: [/WSATCoordinator]
SEVERE: Exception while deploying the app
java.lang.IllegalStateException: Servlet [CoordinatorPortTypeImpl] and Servlet
[CompletionCoordinatorPortTypeImpl] have the same url pattern:
[/WSATCoordinator]at org.glassfish.apf.AnnotationInfo@15c9b76
       at
com.sun.enterprise.deployment.archivist.Archivist.readAnnotations(Archivist.java:478)
       at
com.sun.enterprise.deployment.archivist.Archivist.readAnnotations(Archivist.java:420)
       at
com.sun.enterprise.deployment.archivist.WebArchivist.postAnnotationProcess(WebArchivist.java:309)
       at
com.sun.enterprise.deployment.archivist.WebArchivist.postAnnotationProcess(WebArchivist.java:81)
       at
com.sun.enterprise.deployment.archivist.Archivist.readRestDeploymentDescriptors(Archivist.java:397)
       at
com.sun.enterprise.deployment.archivist.Archivist.readDeploymentDescriptors(Archivist.java:373)
       at com.sun.enterprise.deployment.archivist.Archivist.open(Archivist.java:238)
       at com.sun.enterprise.deployment.archivist.Archivist.open(Archivist.java:247)
       at com.sun.enterprise.deployment.archivist.Archivist.open(Archivist.java:208)
       at
com.sun.enterprise.deployment.archivist.ApplicationFactory.openArchive(ApplicationFactory.java:148)
       at ...

Actually I wanted to use some subclass of WebServiceFeature in my client program,but netbeans wrongly imported internal api classes instead of actual classes like com.sun.xml.internal.ws.developer.BindingTypeFeature instead of com.sun.xml.ws.developer.BindingTypeFeature.(This was due to metro has apis that are not in api package, nor are separated from the big implementation bundle)

So  I started renaming the wrongly imported classes to actual classes,but Netbeans editor showed classpath problems. So in order to overcome the problem, I added webservices-osgi.jar to netbeans clients projects compile time  libraries.Then when I tried to deploy the application, GF V3 throwed the above exception.

I reported this to Fabian and he told me this problem was because we have the WS-AT servlet code in webservices-osgi.jar and that is clashing with the WS-AT servlet that already comes with glassfish and this may be resolved in the next releases of Metro.

So for now the workaround is to add webservices-osgi.jar to the projects compile time libraries with out packaging them to the final war file that we deploy as shown below.

Note: The package check box is not selected .

Even then if problem persists , clean your project and then run.

Wednesday Nov 04, 2009

Performance Testing for Web Services

If you are working on a project and you have some web services involved in your application, at some stage during your project time frame , you may want to see how they perform.

Here is a link I just found and want to share with others who would like to do some  performance testing for  their web services.I haven't completely gone through it, but will check it once I get some time later today.




Saturday Oct 31, 2009

mirror a website locally using wget

Recently my Favourite actor Chiranjeevi came to the office I used to work earlier to collect funds for flood relief(Last month we had floods in South India which made some thousands home less in the states of Andhra Pradesh and Karnataka). I asked my old colleague to share some photos he had of the visit.Then he kept the photos in a folder and shared them  in his php server and gave me the link to view the photos.

But I wanted to download all the files he shared. So I thought of searching in the google for a for a suitable program that could help me to get the files.Luckily there was a newsletter from zdnetasia in my inbox the same day about how to use wget to mirror a website locally.

Its a single line of command in my ubuntu notebook that did the job:

$ wget -rkp -l6 -np -nH -N http://example.com/

Refer to man page of wget to know what each option does if you really care or visit this link see the original post.

Friday Aug 21, 2009

How well are you aware of Caching,its terminology and algorithms used?

Some times in our day to day work, we talk about cache.We know that cache is the temporary memory area where data (may be retrieved from a remote server miles away from you or a database ) is stored for easy and fast retrieval.One good example is web cache where typically a proxy server or  a browser stores data from a remote web server in its own allocated memory space and tries to re-use it the second time the same resource is accessed with out taking the pain of contacting the remote resource and getting the same set of data and presenting to the user.Again here conditions apply.Some sort of mechanism should be in place so as to make sure that the data presented to the user is not stale.

In some cases when an application we use become sluggish or not performing well we try to see if there is a way to change the memory settings of the program.We do that and done.We now see that the performance increases and we are happy with it.

But when some one asks you to implement caching as a part of your work or in a job interview, how well can you do it?Are you equipped with the algorithms's and terminology associated with it? If answer is NO, I would like you to refer to this blog entry that describes the terminology like  Cache Miss, Cache Invalidation, Storage Cost, Replacement Policy etc , the algorithms and criteria that can be used or to be kept in mind while implementing your own version of Cache.I really liked the way its presented in a conversational style between a Java Programmer and an Interviewer.Read it.Enjoy.

Tuesday Aug 18, 2009

Creating facebook applications

After using facebook for so many days, I wanted to try what it takes to write a facebook application.After googling for some time, I found a variety of ways I could actually start creating one.

One Simple and easy one I found is Zembly. Zembly is offered as PaaS( Platform as a Service) to create social applications using various platforms like Facebook ,Orkut etc.Again as a proud employee of Sun Microsystems I want to boast that Zembly is a really cool product from my company.

Now I started creating a sample application following the documentation and wiki pages from Zembly and found that it was very simple to setup and create your application using wizard driven environment at Zembly.The most useful part of documentation to me is series of Videos that are hosted at the site.If you can't wait to read all the documentation I recommend watching the video and following them , you are almost done with creating your application.

One best thing about Zembly is you don't need any seperate IDE to create your application.All you need is a browser with Java plugin enabled in the browser for the built-in editor to help you with auto code-completion and syntax checking.

Although it is simple to create and setup your facebook application, since zembly is template based you may need to do a bit of work to customise the application according to your needs and one good thing is you have a very good reference for the functions you need to use to do various operations on facebook and other social platforms in Zembly.You can even test drive your application from the site and see how it works and then make the application public once you are done with it.I feel writing more about would be a duplication effort.So if are like me and want to get a feel of creating your own social application go ahead and start using Zembly.

Wednesday May 13, 2009

Copy a directory from one machine to another from command line

Today I have to run some tests on various machines and have to post the results to a common directory in another machine.Since most of the machines are accessed through command line,I dont have any GUI to copy and paste.

Again making a zip file to the directory and then ftp it to target macine and then unzipping it , looked odd.So I googled out to find a simple way and found the below command to copy an entire directory in a single go:

tar -cf - <dir-to-be-copied> | ssh <user-name>@<target-machine> "cd target_dir; tar -xf -"

Now it asks for the user password and once you key in the password and hit enter, its done!!!

The above command copies the whole directory to the target machine. But this needs the machine has ssh setup on it.

Friday Apr 24, 2009

Reason 442 : Failed to enable Virtual Adapter

This Summer I had to go to my native place for some reason and I went home with my office laptop so that I can work remotely.After I reached home and tried to check my emails and some internal Sun sites, I could not connect to my VPN using Cisco VPN Client .So I immediately reached my PC Support guys and they could not help either.So I tried  googling for the problem,tweaked some settings in Symantec Endpoint Protection before getting to this link.This link has a very good desciption with nice screenshots.If you have also faced problem like me,you go ahead and visit this site.

After a quick restart, now I am able to connect to VPN and browse our local intranet sites.

In Summary(or for some reason the above link is broken) this worked for me,

  1. Start Menu
  2. Network
  3. Click on Network Sharing
  4. Click on Manage Networks in the new window opened
  5. Right Click on Cisco Adapter and click on Diaognise.
  6. Reset the Network adapter
  7. Now it says there is limited connectivity.Ignore it and restart the machine.
  8. Now try connecting to VPN.Thats all.Now you are connected.
  9. If you still unable to connect,Click here and search for the problem ;-).
About

This is my personal blog.All the information here reflects my own thoughts and feelings and should not be taken as official information from Oracle.

Search

Archives
« April 2014
SunMonTueWedThuFriSat
  
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
   
       
Today