Posts Tagged ‘java’

Java WebStart UnavailableServiceException

Thursday, August 7th, 2008

If you are getting javax.jnlp.UnavailableServiceException from javax.jnlp.ServiceManager.lookup() or if javax.jnlp.ServiceManager.getServicesNames returns null you must be aware that those call only return useful thing when you run your code fromt the Java Web Start environment.

It´s not enough to include the jnlp.jar or javaws.jar in the classpath.

For example to make it work from Netbeans you must enable WebStart in the project and Set Configuration to WebStart.

Typing tilde on Netbeans 6.1 - annoying java bug

Friday, July 11th, 2008

It seems that is imposible to type the ˜ symbol (named also tilde,squiggle,twiddle,not,approx,wiggle,swung,dash,enyay,sqiggle) in Netbeans with a Swedish keyboard at least. It seems that it’s a long known java bug (bug 6353098, bug 6253172). At least I can use the Alt+126 code to type it.

Graph visualization

Wednesday, November 14th, 2007

guess.jpgAfter spending a bunch of time with the graphviz utilities (neato, dot, circo and twopi) trying to create a graph to understand the software dependencies between modules in a project I´ve been I assigned I realized that those tools don´t work well with large graphs. I tried and tried with no luck, I thought that the old linux kernel map poster used graphviz to create the poster but after googling a bit and reading the code for the FCGP project I found that they write PostScript directly. I was looking for something simpler.

After giving up with graphviz I found a bunch of tools for working with graphs most of them are toolkits to develop your own tools but then I hit GUESS. GUESS is a graph browser so to say. You generate a .gdf similar to graphviz’s .dot files and GUESS will layout the graph for you. But the really good thing is that it is a browser you can actually interact with the graph, changing the layout or coloring items, etc. It comes with a scripting language that allow to manipulate the graph very easily and to neat things like change the size of the nodes depending on the value of certain field of the node. All this in runtime. So if you wan to spot all the nodes in your graph where the field “module” is equal to “provisioning” you just enter this in the console

selectednodes = (module == "provisioning) 
selectednode.color = red

Pretty easy doesn´t it

Passing configuration parameter to Axis2 services

Tuesday, October 16th, 2007

One way to pass parameters to you Axis2 service:

1) write a <parameter> tag inside your services.xml

 
<?xml version="1.0" encoding="UTF-8"?>
<!-- This file was auto-generated from WSDL -->
<!-- by the Apache Axis2 version: 1.3  Built on : Aug 10, 2007 (04:45:47 LKT) -->
<serviceGroup>
    <service name="xxxxxxx" class="MyServiceLifeCycleImpl">
 
....
        <parameter name="jdbcConnectionString">jdbc:derby:c:/demoderby2b;create=true;user=a;password=b;</parameter>
        <parameter name="jdbcDriver">org.apache.derby.jdbc.EmbeddedDriver</parameter>
 
...
    </service>
</serviceGroup>

2) Write a ServiceLifeCycle class


public class MyServiceLifeCycleImpl implements ServiceLifeCycle {
    private Log log = LogFactory.getLog(MyServiceLifeCycleImpl.class);

    public void startUp(ConfigurationContext confCtx, AxisService axisService) {
        try {


            String jdbcConnectionString = (String) axisService.getParameterValue("jdbcConnectionString");
            String jdbcDriver = (String) axisService.getParameterValue("jdbcDriver");
            Class.forName(jdbcDriver).newInstance();
            Connection connection = DriverManager
                    .getConnection(jdbcConnectionString);
            axisService.addParameter("jdbcConnection", connection);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

....


3) Add init method to your service


....
       private ServiceContext serviceContext;

    public void init(ServiceContext serviceContext) {
        this.serviceContext = serviceContext;

    }
....

4) Access the parameter jdbcConnection from your service through serviceContext


....
        Connection conn = (Connection) serviceContext.getAxisService()
                    .getParameterValue("jdbcConnection");

....

Two web applications sharing the same Derby database

Monday, October 15th, 2007

I just realized that to be able to open/share the same Derby database from two different web applications running in the same Tomcat instance (same JVM) you´ll need to put derby.jar in the $TOMCAT_HOME/common/lib and remove it from your applications WEB-INF/lib. I got the clue from this RIFE web page

the jarfiles you need are derby.jar and derbytools.jar . Due to classloader peculiarities, don’t copy them to your application’s web/WEB-INF/lib/ subdirectory, or to Tomcat’s shared/lib/ directory. Tomcat’s common/lib/ directory works, and probably common/endorsed/ does too.

Dojo, JSON, Xstream and FLEXJSON

Tuesday, October 9th, 2007

I´ve been trying to use XStream to generate JSON to be consumed by Dojo. But I can´t find the way to generate the right JSON from XStream, it keeps adding extraneous {} around. I even tried this but no luck . For example I want to generate this JSON output (taken from Dojo FilteringSelect example) :


{identifier:"abbreviation",
items: [
    {name:"Alaska", label:"Alaska",abbreviation:"AK"},
    {name:"Wyoming", label:"Wyoming",abbreviation:"WY"}
]}

My attempt usign XStream:



package com.rubenlaguna.json;

import java.util.ArrayList;
import java.util.Collection;

import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.io.json.JettisonMappedXmlDriver;

class ItemCollection {
    public String identifier;
    public Collection<Item> items = new ArrayList<Item>();

    public ItemCollection(String identifier) {
        this.identifier = identifier;
    }

    public boolean add(Item arg0) {
        return items.add(arg0);
    }

}

class Item {
    public String name;
    public String label;
    public String abbreviation;

    public Item(String name, String label, String abbreviation) {
        this.name = name;
        this.label = label;
        this.abbreviation = abbreviation;
    }

}

public class WriteXStreamDojoTest {

    public static void main(String[] args) {
        ItemCollection itemCollection = new ItemCollection("abbreviation");
        itemCollection.add(new Item("Alaska","Alaska","AK"));
        itemCollection.add(new Item("Wyoming","Wyoming","WY"));
        
        XStream xstream = new XStream(new JettisonMappedXmlDriver());
        String erroneousJsonStr = xstream.toXML(itemCollection);
        System.out.println(erroneousJsonStr);

    }

}


resulted in the following JSON Output (i added some space and breaklines for readability):


{"com.rubenlaguna.json.ItemCollection":
       {"identifier":"abbreviation",
         "items":{ "@class":"list",
                      "com.rubenlaguna.json.Item":[  
                         {"name":"Alaska","label":"Alaska","abbreviation":"AK"},
                         {"name":"Wyoming","label":"Wyoming","abbreviation":"WY"}
                       ]
                   }
      }
}


I couldn´t figure out how to get XStream to output the desired JSON. The main issue is that I couldn´t make “items” a simple JSON array, it always end up as an object with an array in it. So I decided to give out a try to FLEXJSON. I really found much easier to control the output with this tool. I guess that XStream is more focused on serialization/deserialization and doesn´t allow customization without relaying in custom converters (I didn´t walk that road, too much work). Here is the example source code usign FLEXJSON:


package com.rubenlaguna.json.flexjson;

import flexjson.JSONSerializer;

public class WriteFlexjsonDojoTest {

    public static void main(String[] args) {
        ItemCollection itemCollection = new ItemCollection("abbreviation");
        itemCollection.add(new Item("Alaska", "Alaska", "AK"));
        itemCollection.add(new Item("Wyoming", "Wyoming", "WY"));

        JSONSerializer serializer = new JSONSerializer().include("items").exclude("*.class");
        String correctJsonStr = serializer.serialize(itemCollection);
        System.out.println(correctJsonStr);

    }

}


that yields the following correct result:


{"identifier":"abbreviation",
  "items":[ {"name":"Alaska","label":"Alaska","abbreviation":"AK"},
              {"name":"Wyoming","label":"Wyoming","abbreviation":"WY"}
            ]}

Eclipse Bug #201116 update: Switch compare viewer for java files

Thursday, September 6th, 2007

I’ve submitted a patch (Attachment #77777 and a couple of screenshots ( Attachment #77774 y Attachment #77776) to Bug #201116. It’s only a preliminary work but it enables the user to select with contentMergeViewer to use with each FileType/ContentType. Now it’s only useful if you use my java formatting compare plugin. Currently the org.eclipse.compare subsystem will allow only one contentMergeViewer per fileType or contentType and you cannot tell which one it will be as Szymon Brandys comments. With this patch the user can select/switch which one he wants to use among all viewer registered for a given file extension/content type.

comparecontenttypeassociationspreferencepage.png

comparefileassociationspreferencepage1.png

Updating the java compare plugin

Thursday, August 23rd, 2007

I received some comments about my java compare plugin about my plugin ignoring preferences for text font and formatter settings. I didn’t address those at the beginning because I didn’t notice so as soon as I realized that was missing I put my hands at work.

The java formatter settings was easy just modifying the old

final Properties options = new Properties();
final CodeFormatter codeFormatter = ToolFactory	.createCodeFormatter(options);

with

final Map options = JavaCore.getOptions();
final CodeFormatter codeFormatter = ToolFactory.createCodeFormatter(options);

That’s easy. The font issue was also easy, just adding the following snippet to the plugin.xml did the trick:

   <extension
         point="org.eclipse.ui.themes">
      <fontDefinition
            categoryId="org.eclipse.compare.contentmergeviewer.TextMergeViewer"
            defaultsTo="org.eclipse.jdt.internal.ui.compare.JavaMergeViewer"
            id="com.rubenlaguna.eclipse.javacompare.JavaFormattingMergeViewer"
            label="Java compare text font (ignore formatting changes)">
         <description>
            The Java compare text font is used by Java compare/merge tools when the ignore formatting changes plugin is loaded.
         </description>
      </fontDefinition>     
   </extension>

Because JavaFormattingMergeViewer extends JavaMergeViewer whick in turns extends TextMergeViewer the code to manager fonts, etc is already in place it’s just a matter of setting it properly in the plugin.xml.

Eclipse Compare. Ignoring java formatting changes not only whitespace.

Saturday, August 18th, 2007

I met some difficulties dealing with the default eclipse java compare. I got involved on a project where everybody likes to commit code to CVS formatted their way, so comparing between CVS revisions is almost impossible.

So I decided to start investigating about Eclipse plugin development to make a Java Compare Viewer that not only ignores whitespace but also all java formatting changes. The result is the following

Before ignore java formatting plugin: comparebefore.png

After ignore java formatting plugin:

compareafter.png

The plugin honors the text font preferences set in General -> Appearance -> Colors and fonts -> Text Compare -> Java compare text font. Also honors the Java Formatter preferences in Java -> Code Style -> Formatter

You can download the plugin and source code tested in Eclipse 3.3 Europa release from here. (The source code is in src folder inside the .jar)

Or you can use Update Manager: http://rubenlaguna.com/javacompare/update-site.

findandinstall.png

To activate/deactivate the plugin all you have to do is press the new icon in the java compare view

comparebutton.png

UPDATE: Depending on your current set of plugins this plugin may or may not work. There is an issue in Eclipse when it comes to registering contentMergeViewers, It seems that when you register more that one contentMergeViewer for a particular file extension (in this case the Eclipse JDT registers org.eclipse.jdt.internal.ui.compare.JavaContentViewerCreator and my plugin registers com.rubenlaguna.eclipse.javacompare.JavaContentViewerCreator) then the CompareUIPlugin.registerExtensions() will only record the last one. I’m trying to figure out how can I force my plugin to register last because right now depending on your configuration my plugin can register before JDT and then JDT will override my contentMergeViewer with his own. I have filed a bug report on eclipse bugzilla about this issue

Java bug producing SAAJ0511 error

Thursday, July 5th, 2007

I run onto the following exception a couple of days ago:

Caused by: org.w3c.dom.DOMException: NAMESPACE_ERR: An attempt is made to create
 or change an object in a way which is incorrect with regard to namespaces.
        at com.sun.org.apache.xerces.internal.dom.CoreDocumentImpl.checkDOMNSErr
(CoreDocumentImpl.java:2421)

the following log trace was also present in the log file

SEVERE: SAAJ0511: Unable to create envelope from given source

Apparently I run onto a known java bug present in jdk1.5.0_08 up to jdk1.5.0_11. Funny, I downgraded to jdk1.5.0_07.