Wednesday, December 10, 2014

SAP Netweaver: "Login limit is reached. Try again later"


http://scn.sap.com/thread/1350039


Finding an oracle constraint by name

SELECT owner, table_name
  FROM user_constraints
 WHERE constraint_name = <<your constraint name>>
 
or if you have sysadm privileges: 
 
SELECT owner, table_name
  FROM dba_constraints
 WHERE constraint_name = <<your constraint name>> 

Thursday, March 13, 2014

Grails: Getting the Vaadin plugin to run. "Can not process requests before init() has been called"

I had the problem after I installed the grails-vaadin plugin when starting my application I would get the following error

There is a bug in the GrailsVaadinServlet where you have to add the service.init() call.


 
Fortunately when you install the plugin you edit the source code as it is downloaded to your grails project. Mine was found here:


Generate a Mailto Link in Java with to, bcc, cc, subject and body

This is very simply explained here:

http://java.dzone.com/articles/simple-way-sending-emails-java


Wednesday, March 5, 2014

How to finally solve the Hibernate Lazy Load problem: Make the Collection reconnectable


The problem

After years and years working with hibernate there are a few things I hate about it.

The logging and the error messages are not clear and sometimes misleading (I will not expound now) and then the most common problem of all, the lazy load exception.

There are solutions like SessionInView pattern etc, but I and thousands of others wonder why it is so complicated or bad to make the Collection reconnect itself when needed.

I mean eclipse link does it also with a readonly connection.

The solution

So here is my solution and it finally seems to work. I actually implemented Collection class that does the reconnecting for me.

For this to work i have to do several steps

In the hibernate mapping define field access.


You can do this with annotations or if there is hibernate mapping file it looks like this.

At the top do:
    <hibernate-mapping default-access="field">
..



In the entity in the getter of a relationship I return a wrapper class


public class MyEntity{
 //..
 Collection customers = new HashSet();
 
public Collection getCustomers() {
        return new LazyCollectionWithReconnect

(customers, this, new MyProjectRelationshipInitializer());

    }



The implementation of the wrapper class is in the end of this post

The RelationShipInitializer

The interesting stuff is in MyProjectRelationshipInitializer
We have a generic interface:

public interface RelationshipInitializer {
    void initializeRelationship(Object entity, Object propertyValue);
}

That must be implemented by the project
Here I lookup a Stateless sessionbean that has access to the PersistenceContext and does the loading of the relationship

public class MyProjectRelationshipInitializer implements RelationshipInitializer{
    @Override
    public void initializeRelationship(Object entity, Object propertyValue) {
        MyGenericServiceLocator.inst().getGenericPersistenceService()
        .initializeRelationship(entity, propertyValue);
    }

}

The GenericPersistenceServiceBean that actually initializes the hibernate proxy

looks like this:

@Stateless
@Local(GenericPersistenceService.class)
public class GenericPersistenceServiceBean implements GenericPersistenceService
{

   @PersistenceContext
    protected EntityManager em;
 


@Override
    public void initializeRelationship(Object entity, Object relationShipObject) {
        org.hibernate.Session session = getHibernateSession();
        // the lock method adds the entity back into the Entitymanager makes it  

        //managed.
        try {
            session.lock(entity, LockMode.NONE);

            if(!Hibernate.isInitialized(relationShipObject))
            {
                Hibernate.initialize(relationShipObject);
            }

        } catch (TransientObjectException e) {
            //ignore object that are not saved yet
        }
    }


private Session getHibernateSession() {
        //on web as
        if (em.getDelegate() instanceof Session){
            return (Session) em.getDelegate();
        }
        //in openejb
        if (em.getDelegate() instanceof HibernateEntityManager){
            HibernateEntityManager e = (HibernateEntityManager) em.getDelegate();
            return (Session) e.getDelegate();
        }
        throw new IllegalStateException(String.format("Invalid type of entity manager %s (%s). Expected it to be org.hibernate.Session or org.hibernate.ejb.HibernateEntityManager", em, em.getClass()));
    }


}

Note that the getHibernateSession() is a little bit J2EE Server dependent and might be different for your vendor.

The LazyColletionWithReconnect implementation

 is rather boring:

public class LazyCollectionWithReconnect implements Collection {
   
    private Collection srcCollection;
    private Object surroundingEntity;
    private RelationShipInitializer relationShipInitializer;
   

    public LazyCollectionWithReconnect(Collection srcCollection, Object surroundingEntity, RelationShipInitializer relationShipInitializer) {
        super();
        this.srcCollection = srcCollection;
        this.surroundingEntity = surroundingEntity;
        this.relationShipInitializer = relationShipInitializer;
    }


  

     protected void reconnectIfNecessary() {
        ensureRelationIsLoaded(

           this.surroundingEntity, 
           this.srcCollection, 
           this.relationShipInitializer
        );
    }


          public static boolean ensureRelationIsLoaded(
       Object entity, 
       Object propertyValue, 
       RelationShipInitializer initializer) {
        boolean wasLoaded = false;
        //    first check
        if(!Hibernate.isInitialized(propertyValue)){
            initializer

            .initializeRelationship(entity, propertyValue);
            wasLoaded = true;
        }
        return wasLoaded;
    } 

    public boolean add(E e) {
        reconnectIfNecessary();
        return srcCollection.add(e);
    }
   public boolean addAll(Collection c) {
        reconnectIfNecessary();
        return srcCollection.addAll(c);
    }
    public void clear() {
        reconnectIfNecessary();
        srcCollection.clear();
    }
    public boolean contains(Object o) {
        reconnectIfNecessary();
        return srcCollection.contains(o);
    }
    public boolean containsAll(Collection c) {
        reconnectIfNecessary();
        return srcCollection.containsAll(c);
    }
    public boolean equals(Object o) {
        return srcCollection.equals(o);
    }
    public int hashCode() {
        return srcCollection.hashCode();
    }
    public boolean isEmpty() {
        reconnectIfNecessary();
        return srcCollection.isEmpty();
    }

    public Iterator iterator() {
        reconnectIfNecessary();
        return srcCollection.iterator();
    }
    public boolean remove(Object o) {
        reconnectIfNecessary();
        return srcCollection.remove(o);
    }

    public boolean removeAll(Collection c) {
        reconnectIfNecessary();
        return srcCollection.removeAll(c);
    }

    public boolean retainAll(Collection c) {
        reconnectIfNecessary();
        return srcCollection.retainAll(c);
    }

    public int size() {
        reconnectIfNecessary();
        return srcCollection.size();
    }


    public Object[] toArray() {
        reconnectIfNecessary();
        return srcCollection.toArray();
    }
    public
T[] toArray(T[] a) {
        reconnectIfNecessary();
        return srcCollection.toArray(a);
    }

}



Some common problems

HibernateException "reassociated object has dirty collection reference" 

This error message actually can be misleading. In my case it stemmed from that the entity with the collection did not have equals and hashCode overriden
 











deep cloning

Here is a small utility to really clone an object by writing it first to outputstream and back.

    public static Object deepClone(Object src) throws IOException,ClassNotFoundException{
            ByteArrayOutputStream baos = new ByteArrayOutputStream(4096);
            ObjectOutputStream oos = new ObjectOutputStream(baos);
            oos.writeObject(src);
            ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());
            ClassLoaderObjectInputStream ois = new  ClassLoaderObjectInputStream(src.getClass().getClassLoader(),bais);
            Object deepCopy = ois.readObject();
            return  deepCopy;
    }

The class ClassLoaderObjectInputInputStream is needed to resolve the class if it is not in the same jar as the utility method deepClone

import java.io.ObjectInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectStreamClass;
import java.io.StreamCorruptedException;

/**
 * A special ObjectInputStream that loads a class based on a specified
 * ClassLoader rather than the system default.
 *
 * This is useful in dynamic container environments.
 *
 * @author Paul Hammant
 * @version $Id: ClassLoaderObjectInputStream.java 437567 2006-08-28 06:39:07Z bayard $
 * @since Commons IO 1.1
 */
public class ClassLoaderObjectInputStream extends ObjectInputStream {
    /** The class loader to use. */
    private ClassLoader classLoader;

    /**
     * Constructs a new ClassLoaderObjectInputStream.
     *
     * @param classLoader  the ClassLoader from which classes should be loaded
     * @param inputStream  the InputStream to work on
     * @throws IOException in case of an I/O error
     * @throws StreamCorruptedException if the stream is corrupted
     */
    public ClassLoaderObjectInputStream(
            ClassLoader classLoader, InputStream inputStream)
            throws IOException, StreamCorruptedException {
        super(inputStream);
        this.classLoader = classLoader;
    }

    /**
     * Resolve a class specified by the descriptor using the
     * specified ClassLoader or the super ClassLoader.
     *
     * @param objectStreamClass  descriptor of the class
     * @return the Class object described by the ObjectStreamClass
     * @throws IOException in case of an I/O error
     * @throws ClassNotFoundException if the Class cannot be found
     */
    protected Class resolveClass(ObjectStreamClass objectStreamClass)
            throws IOException, ClassNotFoundException {
       
        Class clazz = Class.forName(objectStreamClass.getName(), false, classLoader);

        if (clazz != null) {
            // the classloader knows of the class
            return clazz;
        } else {
            // classloader knows not of class, let the super classloader do it
            return super.resolveClass(objectStreamClass);
        }
    }
}



Tuesday, March 4, 2014

Hibernate Lazy Load exception and how to load an relationship



Hibernate and lazy loading sucks. Especially in Web Dynpro where we cannot use the Session in View pattern. Therefore there is handy method can load a collection to make sure that a collection is loaded and load it on demand from the service layer

public abstract class GenericDaoBean implements GenericDao

// ....

public void initializeRelationship(T entity, String property) {
        org.hibernate.Session session = getHibernateSession();
        // the lock method adds the entity back into the Entitymanager makes it managed.
        try {
            session.lock(entity, LockMode.NONE);
            Object collectionProxy = getAttributeValue(entity, property);

            if(!Hibernate.isInitialized(collectionProxy))
            {
                Hibernate.initialize(collectionProxy);
            }
        } catch (TransientObjectException e) {
            //ignore object that are not saved yet
        }
    }

    public org.hibernate.Session getHibernateSession() {
        Object delegate = getEntityManager().getDelegate();
        org.hibernate.Session session = null;
        //This is in SAP J2EE
        if(delegate instanceof org.hibernate.Session){
            session = (org.hibernate.Session) delegate;
        }
        // this is in OpenEJB container
        else if(delegate instanceof HibernateEntityManager){
            HibernateEntityManager hbEm = (HibernateEntityManager) delegate;
            session = hbEm.getSession();
        }
        return session;
    }
}

public static Object getAttributeValue(Object bean, String attributeName){
        Map props = getPropertyDescriptors(bean.getClass(), new String[]{"class"});
        PropertyDescriptor desc = props.get(attributeName);
        if(desc == null) throw new IllegalArgumentException("attribute:" +attributeName + " does not exist in bean "+ bean);
       
        try {
            Object result = desc.getReadMethod().invoke(bean, null);
            return result;
        } catch (IllegalArgumentException e) {
            throw new RuntimeException(e);
        } catch (IllegalAccessException e) {
            throw new RuntimeException(e);
        } catch (InvocationTargetException e) {
            throw new RuntimeException(e);
        }
    }

Wednesday, February 19, 2014

Oracle: How to escape an &


Insert into BRMF_VALUE_CATALOG (ID,TITLE,TYPE,CAN_HAVE_CHILDREN,PARENT_ID) values (322,'&MORE','Generic_Suffix_Basket',0,3);
DOES not work
 

escape the & with || chr(38) ||

Insert into BRMF_VALUE_CATALOG (ID,TITLE,TYPE,CAN_HAVE_CHILDREN,PARENT_ID) values (322,chr(38) || 'MORE','Generic_Suffix_Basket',0,3);




See also
http://stackoverflow.com/questions/1137354/oracle-pl-sql-escape-character-for-a
 

SAP Netweaver: 7.31 ""Log files are not loaded yet. Press Refresh after short time"

Problem:
You want to view the logs on a SAP 7.31 J2EE Engine but you get the message
 "Log files are not loaded yet. Press Refresh after short time"

I found a SAP Note that gives a hint with the security settings.

http://www.stechno.net/sap-notes.html?view=sapnote&id=1631616

Solution: Login to the logview via https then it works

Sunday, January 9, 2011

Implement a simple cache with java

The class LinkedHashMap has the method removeEldestEntry() that is called before
put() method so here you can remove the eldest element from the cache.


Map mapCache = new LinkedHashMap()
{
@Override
protected boolean removeEldestEntry(Entry eldest) {
//remove after 2 hours
Calendar cal = Calendar.getInstance();
long howLongAgoInMs = System.currentTimeMillis()-eldest.getValue().lastTimeTouched;
long twoHoursInMs = 2 * 60 * 60 * 1000;
if(howLongAgoInMs > twoHoursInMs){
return true;
}
return false;
}
};

Saturday, January 8, 2011

SAP NWDS, Web Dynpro: Add Destination/R3 fails

Problem:
In the SAP Netweaver Developer Studio you want to add a Destination
Window->Preferences->Destinations->R3 Destinations.

Applys to: NWDS 7, Windows 7

Cause:

Solution:
-vm
C:\DEV\Java\jdk1.5.0_22\bin\javaw.exe
-showsplash
com.sap.netweaver.developerstudio
--launcher.XXMaxPermSize
256m
-vmargs
-Xmx512m
-Xms128m
-XX:PermSize=32m
-XX:MaxPermSize=256m
-Dfile.encoding=UTF-8
-Dosgi.requiredJavaVersion=1.5
-Dos.name='Windows XP'

SAP NWDI: concurrent-lock-denied check failed

Problem:
When trying to revert an activity you get the error:
concurrent-lock-denied check failed
See also:
http://forums.sdn.sap.com/thread.jspa?threadID=1805846&tstart=15

Solution:
Restart your J2EE Server where the NWDI is running.

Tuesday, January 5, 2010

Thoughts on usable OO software documentation

Documentation is usually a big pain point in every big development project.
Usually developers do not write any or they write useless documentation and most of the time it is outdated.

Javadoc
Javadoc is the API documentation on package, class, field and method level.
It should answer the question how to properly use the classes but are more like a reference
and are not so good in conveying the whole picture.
Nevertheless this is very important and easiest to keep up to date as the documentation
is embedded directly in the source code.

So what is important to document especially in javadoc documentation?

The goal is that another developer can understand what is this class for and how he can use it.

A very helpfull construct for designing OO systems but also for documenting them are CRC cards.

CRC
CRC stands for Class-Responsibility and Collaborations. Basically it works it is very simple way on how to design an OO system. You take a stack of card, each representing an object in your system. You write on the very limited space what is the responsibility of the class.
Because the space is so limited on the card it forces you to only write one responsibility for the class which is also good design principle

"Single Responsibility Principle"
  • Every class should only have one responsibility.
  • As a rule of thumb it should only have one reason why you would want to change something on this class
If you cannot describe the responsibility of the class in one sentence this class does too much and should be split up.

The next section is the "Collaborators":
This section answers what others classes does this class need to achieve its responsibility.
I write this class uses object xy to ...
It also states which other objects are using this object and why they depend on it.

It should have an Example:
An example says more than thousands words how to theoretically use the API. Unit tests are usually good examples that show how to use the API and it can be linked to them or the test code can be pasted as an example.

Other questions that are of interest to the developer
Is this class meant for subclassing (if not and most of the time it shouldbe final to avoid subclassing)
Thread safety
How to properly initialize and create the object (is it by a factory, when is it in a proper state?)

Package level documentation
package level document describes all classes in a certain package. Actually a package is for me a module and all classes in a package usually belong together and are coupled in some way and depend on each other. Coupling between packages should be minimized, and subpackages referencing classes from top level packages should be avoided.
Basically package level documentation also can be described in the CRC principle.

Formatting in javadoc
javadoc will become html. I use a comment {@link Class#method(int,String}

Tuesday, September 15, 2009

Vista 64bit Problem mit dem Internet

Habe also nur Probleme mit meinem Vista 64bit system.

Ich hatte schon den Rechner bei Packard Bell eingeschickt, die mir den komplett platt gemacht. Lustigerweise ging das Internet dann nicht. (Vorher hatte ich Probleme mit periodischem komplett ausschalten des Rechners vor allem beim SIMS spielen)

Ich verstehe zwar nicht wieso und warum aber folgendes hat mir geholfen:
Eine Kommandozeile mit Administratorrechten öffnen:
- Auf Start klicken
- unten im Suchfenster cmd eingeben
- STRG+SHIFT+ENTER drücken
- Die Warnmeldung bestätigen Folgendes eingeben:
netsh
winsock
reset

Den Computer neu starten. Jetzt sollte es gehen.

Zu finden in folgendem Forum Post: http://forum.chip.de/windows-vista/vista-64-bit-internet-problem-erstinstallation-1118492.html

Tuesday, September 8, 2009

Openfire login issue

I had problems logging into the admin console of openfire.

Here is solution how to fix:
Check the property admin.authorizedJIDs in the table ofProperty
and add the user name you want to be admin. For me it was cti_david@im.placetel.de

Tuesday, September 1, 2009

Swing repainting issues

I am currently developing a Call Telephony Integration Client for placetel.de on the basis of Spark Instant Messageing client and I noticed several repainting problems in spark.

After long hours researching the web I found the solution. In several component of spark there is the paintComponent(Graphics g) overriden. But they forgot to call ther super.paintComponent(g)
that is why the components always seemed just to write changes on top of the old state so it looked very messy.

public void paintComponent(Graphics g) {
//Super.paintComponent was missing and added by me!
super.paintComponent(g);
double scaleX = getWidth() / (double)backgroundImage.getWidth(null);
double scaleY = getHeight() / (double)backgroundImage.getHeight(null);
AffineTransform xform = AffineTransform.getScaleInstance(scaleX, scaleY);
((Graphics2D)g).drawImage(backgroundImage, xform, this);
}

Friday, July 3, 2009

Ubuntu 64bit, Firefox und Java plugin

Wie man java als plugin unter firefox und linux ans laufen bekommt ist hier beschrieben.

http://blogs.sun.com/joshis/entry/finally_it_s_here_java

Kurzfassung: Wenn die JRE schon installiert ist einfach ins Verzeichnis JRE/lib/amd64 gehen und einen symbolischen Link von der Datei libnpjp2.so erstellen und diesen Link in das Verzeichnis /home/mein-benutzer/.mozilla/plugins verschieben.
Browser neu starten und in der Addresszeile about:plugins eingegen.
Firefox listet alle installierten Plugins und relativ als erstes auch java auf.

Monday, June 22, 2009

Ubuntu 64bit and skype

The download for the skype for a 64bit ubuntu does not work.

Here is the correct package:
http://www.skype.com/go/getskype-linux-ubuntu-amd64