Sunday, December 13, 2009

Consume Web Service client in EJB

See this article

Example:
@Stateless(mappedName = "ejb/eisAccountingService")
public class EisAccountingServiceBean implements EisAccountingServiceLocal, EisAccountingServiceRemote {
    
    @WebServiceRef(name = "DipexExImServiceSoap", value = DipexExImService.class)
    private DipexExImServiceSoap wsService;
    
    public void addReceiptCard(ReceiptCard receiptCard) {
        MaterialPrijemka mr = new MaterialPrijemka();
        // set mr here
        wsService.materialPrijem(mr);
    }
}

Friday, November 06, 2009

Thursday, October 15, 2009

How to simply write bean objects to String

This utility provide ability to write objects to string. Example says everything:
public class Person {

    private PersonName name;
    private Integer age;

    public static class PersonName {

        private String firstName;
        private String lastName;

        public PersonName(String firstName, String lastName) {
            this.firstName = firstName;
            this.lastName = lastName;
        }

        public String getFirstName() {
            return firstName;
        }

        public void setFirstName(String firstName) {
            this.firstName = firstName;
        }

        public String getLastName() {
            return lastName;
        }

        public void setLastName(String lastName) {
            this.lastName = lastName;
        }
    }

    public Person(PersonName name, Integer age) {
        this.name = name;
        this.age = age;
    }

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }

    public PersonName getName() {
        return name;
    }

    public void setName(PersonName name) {
        this.name = name;
    }

    @Override
    public String toString() {
        return StringUtils.objectToString("person", this);
    }
}


Then we call:
    public static void main(String[] args) {
        System.out.println(new Person(new PersonName("Astar", "Sheran"), 2009));
    }


and output is:
person.age = 2009
person.name = new Person$PersonName()
person.name.firstName = Astar
person.name.lastName = Sheran


Utility implementation:

import java.beans.BeanInfo;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author Michal Hlavac
 */
public class StringUtils {

    private static final Logger log = Logger.getLogger(StringUtils.class.getName());

    private static final void toString(String alias, Object obj, StringBuffer sb, List<Object> objects) {
        if (obj == null) {
            return;
        }
        if (objects.contains(obj)) {
            return;
        }
        objects.add(obj);
        try {
            BeanInfo info = Introspector.getBeanInfo(obj.getClass());
            PropertyDescriptor[] descriptors = info.getPropertyDescriptors();
            for (int i = 0; i < descriptors.length; i++) {
                PropertyDescriptor descriptor = descriptors[i];
                if (descriptor.getReadMethod().getDeclaringClass().equals(Object.class)) {
                    log.fine("property defined on Object class: skipping: " + descriptor.getName());
                    continue;
                }
                Object value = null;
                try {
                    value = descriptor.getReadMethod().invoke(obj, (Object[]) null);
                } catch (Throwable ex) {
                    log.fine("Can't read value of attribute " + obj.getClass().getName() + "." + descriptor.getName());
                }
                if (value == null) {
                    log.fine("property value is null: skipping: " + descriptor.getName());
                    continue;
                }
                Class<?> returnType = descriptor.getReadMethod().getReturnType();
                if (!returnType.isPrimitive() && !returnType.isArray() && !returnType.getName().startsWith("java.") &&
                        !returnType.isEnum()) {
                    log.fine("property is unknown type or not primitive [" + returnType.getName() + "]");
                    String simpleName = value.getClass().getName().substring(returnType.getName().lastIndexOf('.') + 1);
                    sb.append(alias).append(".").append(descriptor.getName()).append(" = new ").append(simpleName).append("()\n");
                    toString(alias + "." + descriptor.getName(), value, sb, objects);
                    continue;
                }
                if (value instanceof java.util.Collection<?>) {
                    try {
                        Iterator<?> iter = ((Collection<?>)  value).iterator();                        int num = 0;
                        while (iter.hasNext()) {
                            Object item = iter.next();
                            toString(alias + "." + descriptor.getName() + "[" + num + "]", item, sb, objects);
                            num++;
                        }
                    } catch (Throwable t) {
                        log.fine("Can't read value of attribute: " + alias + "." + descriptor.getName());
                    }
                    continue;
                } else if (value.getClass().isArray()) {
                    try {
                        Object[] valueArray = (Object[]) value;
                        for (int idx = 0; idx < valueArray.length; idx++) {
                            toString(alias + "." + descriptor.getName() + "[" + idx + "]", valueArray[idx], sb, objects);
                        }
                    } catch (Throwable t) {
                        log.fine("Can't read value of attribute: " + alias + "." + descriptor.getName());
                    }
                    continue;
                }
                sb.append(alias).append(".").append(descriptor.getName()).append(" = ").append(value.toString()).append('\n');
            }
        } catch (Exception e) {
            log.log(Level.SEVERE, "hql example criterion building error", e);
        }
    }

    public static final String objectToString(String alias, Object obj) {
        StringBuffer buff = new StringBuffer();
        toString(alias, obj, buff, new ArrayList<Object>());
        return buff.toString();
    }

    public static final String collectionToString(String alias, Collection<?> collection) {
        StringBuffer buff = new StringBuffer();
        int idx = 0;
        for (Object obj : collection) {
            toString(alias + "[" + idx++ + "]", obj, buff, new ArrayList<Object>());
        }
        return buff.toString();
    }

    public static final String toStringLine(Object obj) {
        if (obj == null) {
            return "";
        }
        String clazz = obj.getClass().getName();
        String simpleClazz = clazz.substring(clazz.lastIndexOf('.') + 1);
        StringBuffer sb = new StringBuffer(simpleClazz).append("[");
        try {
            BeanInfo info = Introspector.getBeanInfo(obj.getClass());
            PropertyDescriptor[] descriptors = info.getPropertyDescriptors();
            for (int i = 0; i < descriptors.length; i++) {
                PropertyDescriptor descriptor = descriptors[i];
                if (descriptor.getPropertyType() == null ||
                        Collection.class.isAssignableFrom(descriptor.getPropertyType())) {
                    log.fine("collection handling not supported: skipping property: " + descriptor.getName());
                    continue;
                }
                if (descriptor.getReadMethod().getDeclaringClass().equals(Object.class)) {
                    log.fine("property defined on Object class: skipping: " + descriptor.getName());
                    continue;
                }
                Object value = descriptor.getReadMethod().invoke(obj, (Object[]) null);
                if (value == null) {
                    log.fine("property value is null: skipping: " + descriptor.getName());
                    continue;
                }
                Class<?> returnType = descriptor.getReadMethod().getReturnType();
                if (!returnType.isPrimitive() && !returnType.getName().startsWith("java.") && !returnType.isEnum()) {
                    log.fine("property is unknown type or not primitive [" + returnType.getName() + "]");
                    continue;
                }
                sb.append(descriptor.getName()).append(" = ").append(value).append(" | ");
            }
        } catch (Exception e) {
            log.log(Level.SEVERE, "hql example criterion building error", e);
            return null;
        }
        sb.append("]");
        return sb.toString();
    }
}

Tuesday, August 11, 2009

Native2Ascii plugin for netbeans 6.7

You can download version for netbeans 6.7 from kenai page.

Saturday, August 08, 2009

XDXF Parser Library & Maven

Now you can use latest snapshot of xdxf parser library in maven projects. You need to add new repository and dependency to library.
1. Add repository
<repositories>
  <repository>
      <id>xdxf-snapshots</id>
      <name>XDXF Snapshots</name>
      <layout>default</layout>
      <url>https://mvn.datalan.sk/artifactory/libs-releases-snapshots/</url>
      <snapshots>
          <enabled>true</enabled>
      </snapshots>
  </repository>
</repositories>

2. Add dependency
<dependency>
  <groupid>eu.hlavki.xdxf</groupid>
  <artifactid>xdxf-parser</artifactid>
  <version>1.0-SNAPSHOT</version>
</dependency>

v1.9.5 serialVersionUID generator for netbeans 6.7 released

Changelog:

Download here.

Monday, June 15, 2009

XDXF Parser library

I created small library to parse dictionaries stored in XDXF format. API is event based and you can listen to events (dictionary, article) while parser is parsing.
Whole dictiary is not loaded to memory by default, so you can parse large dictionary with small memory footprint. Project is hosted on kenai.com. Binary packages will be available soon, but source code is available in kenai browser.

API usage example:

import eu.hlavki.xdxf.parser.DefaultXDXFParser;
import eu.hlavki.xdxf.parser.ParseException;
import eu.hlavki.xdxf.parser.XDXFParser;
import java.io.IOException;
import java.io.InputStream;

public class Sample {

public static void main(String[] args) {
InputStream in = null;
try {
XDXFParser parser = new DefaultXDXFParser();
DictionaryListener listener = new DictionaryListener();
parser.addXDXFEventListener(listener);
in = Sample.class.getResourceAsStream("/test-dict.xdxf");
long startTime = System.currentTimeMillis();
parser.parse(in);
long endTime = System.currentTimeMillis();
System.out.println("Dictionary: " + listener.getDictionary());
System.out.println("Word Count: " + listener.getArticleCount());
System.out.println("Parse time: " + (endTime - startTime) + " ms");
} catch (ParseException e) {
e.printStackTrace();
} finally {
try {
if (in != null) in.close();
} catch (IOException e) {
// should never happened
}
}
}
}

Listener sample code:

import eu.hlavki.xdxf.parser.event.XDXFArticleEvent;
import eu.hlavki.xdxf.parser.event.XDXFDictionaryEvent;
import eu.hlavki.xdxf.parser.event.XDXFEventListener;
import eu.hlavki.xdxf.parser.model.XDXFDictionary;

public class DictionaryListener implements XDXFEventListener {

private int articleCount = 0;
private XDXFDictionary dictionary;

public void onDictionary(XDXFDictionaryEvent evt) {
this.dictionary = evt.getSource();
}

public void onDictionaryChange(XDXFDictionaryEvent evt) {
this.dictionary = evt.getSource();
}

public void onArticle(XDXFArticleEvent evt) {
articleCount++;
}

public int getArticleCount() {
return articleCount;
}

public XDXFDictionary getDictionary() {
return dictionary;
}
}

Friday, May 15, 2009

v1.9.4 serialVersionUID generator for netbeans 6.7 released

Changelog:
  • project moved to Kenai
  • changes to work with Netbeans 6.7
  • fixes in svuid generator
  • new SuppressWarning("serial") hint
Download from plugin site.

Saturday, February 21, 2009

Native2Ascii plugin for netbeans 6.5

After some time of finding myself I am back... 2 days ago my friend and colleague ask me if I know about netbeans feature to convert native characters to ASCII. Same as native2ascii command line but integrated in netbeans editor. Quick answer in my mind: There has to be some plugin, so UTFG... After googling by myself I found only this one. It looks well, but there is no integration with netbeans editor.
So what I did? I wrote plug-in according to my vision. I know it's not good approach to use native characters in java source at all. Better idea is using properties bundles. But sometimes it's OK, when you want to write some small piece of code which is used only by yourself.
Some screenshots:

1. You can use java editor hint:
2. Or just press CTRL+SHIFT+A or right mouse click on selected text:

3. and result is:

You can download this plugin here. Sources can be found in project site.

Friday, February 06, 2009

Dolomity Super Skiing weekend


Exhausting 6 days skiing marathon in Dolomiti SuperSki.

Tuesday, December 30, 2008

New RemoteFS project site

Because I receive some comments on my blog about remotefs plug-in, I decided to create google project where you can create issues about this plug-in. So when you find some bug or feature request, please create issue on project site.

Link for project is:
http://code.google.com/p/nb-remotefs

Issues list:
http://code.google.com/p/nb-remotefs/issues/list

Thursday, October 30, 2008

serialVersionUID generator for netbeans 6.5 released

Changelog:
  • API changes to work with Netbeans 6.5
  • works with JFrame and JPanel in Matisse since issue #140653 fixed
Download from plugin site.

Saturday, September 27, 2008

Rohace in latest summer days 2008


Trip to West Tatras during nice weekend in village Veličná.

Monday, September 08, 2008

I am a netbeans fan, so what...

Time ago I read some blogs about ftp support for php projects in netbeans. I was thinking... Why ftp only? Where's support for SFTP and other protocols? It should be great to have an abstract API for remote file systems and lot of implementations for other protocols. So I started to look into netbeans sources. I found remotefs project in contrib repository. I was thinking: "it's great to see this. Netbeans for PHP must use this". So I started implementation of SFTP protocol. When I was in half of my work I looked into sources of netbeans php modules.
And what I discover? It uses own implementation of FTP protocol. Hmmm, so what now???

Because my primary targer was php module, I didn't know why should I continue write this plug-in. So I decided to rewrite remotefs API and it's implementation to more abstract level because it looks like it's tightly coupled with FTP protocol implementation.

Now I am releasing first alpha quality release. Maybe this is good starting point for integration of this plug-in into existing netbeans features...

You can download it here.
If you are interested in sources are available via mercurial repository.

PS: These modules uses same namespace (package) as mentioned project remotefs in main/contrib. So don't install this modules when you already have it installed.

Screenshots:


Thursday, August 21, 2008

Aliens Exist


This alien was seen near Banska Stiavnica. Look at its brilliant body...

Sunday, July 13, 2008

Holiday in Slovenia and Croatia


This year holiday was trip including hiking in Julian Alps (Slovenia) and sea in Croatia. Enjoy photos.

serialVersionUID generator for netbeans v1.5 released

Changelog:
  • hint configuration was moved to "general" group
  • refactoring in Descriptor class
  • support for SuppressWarrning("serial") annotation
  • abstract classes are excluded from generator and hint
Download from plugin site.

Wednesday, May 28, 2008

SerialVersionUID generator v1.9 for Netbeans 6.5 nightly builds

As I mentioned generator v1.3 is not compatible with api changes in 6.5 dev builds. So I created serialVersionUID generator v1.9 that supports 6.5 nightly builds... You can download nbm here.