Showing posts with label java. Show all posts
Showing posts with label java. Show all posts

Monday, December 17, 2012

Problems reading Log4j.xml from outside web application


Problems reading Log4j.xml from outside web application


If you try to read the log4j.xml from outside the Spring application/classpath, you might get the following errors, if you are deploying a war file:

Stack trace


org.springframework.web.util.Log4jConfigListener failed: java.lang.IllegalStateException: Cannot set web app root system property when WAR file is not expanded.
java.lang.IllegalStateException: Cannot set web app root system property when WAR file is not expanded
                        at org.springframework.web.util.WebUtils.setWebAppRootSystemProperty(WebUtils.java:137)
                        at org.springframework.web.util.Log4jWebConfigurer.initLogging(Log4jWebConfigurer.java:117)
                        at org.springframework.web.util.Log4jConfigListener.contextInitialized(Log4jConfigListener.java:45)


The explanation is given below:

Summary -  org.springframework.web.util.Log4jConfigListener only works if the WAR file is exploded
The same with HDIV

Configuration


log4jConfigLocation
file:/${CONFIG_LOCATION}/log4j.xml
 

Solution

To override this we need to add the following to the web.xml

<context-param></context-param>
    <param-name>log4jExposeWebAppRoot</param-name>
<param-value>false</param-value>

Tuesday, January 31, 2012

Tuples in Java

I came across the concept of tuples in C# which is quite interesting and useful. A tuple is a data structure that has a specific number and sequence of elements.  C# introduced this feature since .NET 3.5. It supports upto 8 generic objects. Unfortunately Java haven't got one yet.


In my current project there was a need for a similar Data-structure, where I had to pass back a large amount of data of a particular object. But I was interested only in just two properties of that object. I could have created a proxy class, but that would have ben a sort of over engineering (Which I don't want to do). At that time I thought of a simple attempt to write a Tuple. I wrote one and it's really reusable and clean. You can find the  the code snippet below.

public abstract class Tuple<T1, T2, T3, T4>{


    protected T1 t1;
    protected T2 t2;
    protected T3 t3;
    protected T4 t4;
    
    public static    < T1, T2> Tuple <T1, T2, ?, ?> create(T1 aT1, T2 aT2){
        return new MultipleTuple(aT1, aT2);
    }
    
    public  T1 getFirstItem(){
        return t1;
    }
    
    public T2 getSecondItem(){
        return t2;
    }
    
    public T3 getThirdItem(){
        return t3;
    }
    
    public T4 getFourthItem(){
        return t4;
    }

}

A MultiTuple


final class MultipleTuple<T1, T2> extends Tuple {
    
     MultipleTuple(T1 aT1, T2 aT2) {
        t1 = aT1;
        t2 = aT2;
    }
}


Example


String employee = "Diego Maradona";
double renumeration = 56.5;
        
Tuple  tuple = Tuple.create(employee, renumeration);


System.out.println(tuple.getFirstItem());
System.out.println(tuple.getSecondItem());




You can extend as many classes you want to create. You might need to restrict the visiblilty and make them final so that it's secure. Or you could even extend the MultipleTuple(Hoping it's no longer final) class for the next tuples. Make sure the create method is overloaded with the right parameters.




Happy Hacking.

Thursday, January 12, 2012

Generated keys not requested. You need to specify Statement.RETURN_GENERATED_KEYS to Statement.executeUpdate() using Spring JdbcTemplate

My colleague was getting this exception for a Spring JdbcTemplate based code which I had written for some simple Mysql dao functionalities. The funny point was that we were both using the same version of Mysql drivers, but I was using 32bit Mysql 5.5 but my colleague was using the 64bit version.

This quick fix solves the problem:


KeyHolder keyHolder = new GeneratedKeyHolder();
jdbcTemplate.update(new PreparedStatementCreator() {
@Override
 public PreparedStatement createPreparedStatement(Connection aConnection) throws SQLException {
                    PreparedStatement preparedStatement = aConnection.prepareStatement(SAVE_USER,
PreparedStatement.RETURN_GENERATED_KEYS);
                    preparedStatement.setString(....);
                    ....
                         preparedStatement.setString(....);
                    return preparedStatement;
                }
            }, keyHolder);
 user.setId(keyHolder.getKey().intValue());

A few other fellow bloggers had given suggestions like switching the Mysql dirvers, but it's didn't help me at all. I had tried all the last 10 Mysql driver releases. I am not sure if its a programming error or a Mysql bug, but the above code does fix the problem!

Happy Hacking :)

Thursday, June 23, 2011

Error: Unable to transcode assets/xyz.png

I got this error while trying to build a Flex application using Apache ant and Flex 4.5 SDK (Got it even while directly using the MXML command). The strange thing is that, I was able to successfully compile this same project at my office using the very same SDK. I googled and nowhere did I get a satisfactory solution. There were so many threads and links which showed a similar problem:

 Error: unable to resolve 'assets/xyz.png'.

The fact is that, the above error is entirely different from the error I am talking about. The above error is just because the compiler can't resolve the image. A '/' or  '../' before the 'assets' will easily solve the above problem.

But the error:

Error: Unable to transcode assets/xyz.png

is different and frustrating. I happens even though that particular image could be resolved. 

After a few hours of research I finally figured out the problem. The problem was with the underlying JDK.

My Machine is using 64 bit Windows 7, and apparently the JDK  was also a 64 bit. Flex release notes doesn't mention that it supports 64 bit os and now it's clear -It doesn't support. Finally after switching to a 32 bit JDK the project got compiled successfully.

Note- if the above solution doesn't work, you should try downloading the latest 32 bit JDK and try. 


Wednesday, June 22, 2011

org.springframework.beans.FatalBeanException: Could not copy properties from source to target

I came across this irritating issue(While workign on a Spring based project).

org.springframework.beans.FatalBeanException: Could not copy properties from source to target; nested exception is java.lang.IllegalArgumentException: argument type mismatch
at org.springframework.beans.BeanUtils.copyProperties(BeanUtils.java:599)
at org.springframework.beans.BeanUtils.copyProperties(BeanUtils.java:509)

Google took me to this bug which was already logged with SpringSource:

https://jira.springsource.org/browse/SPR-7693 (unfortunately it's still unfixed)

I made a quick fix/workaround for this.

Download/checkout : org.springframework.beans.BeanUtils.java

Add the below line after: writeMethod.invoke(target, value); (Around line 597) if using the 3.1 source.



if(logger.isDebugEnabled()){
logger.debug(MessageFormat.format("Source Property: {0}, Target Property:   {1}, Write method:{2}, Read Method {3} ", sourcePd.getName(),  targetPd.getName(), writeMethod.getName(), readMethod.getName()));
}

Add the file to your project. Now you can happily debug which property in the class is causing  problem.

Monday, June 20, 2011

Flex Builder 3 on Eclipse Ganymede

While this post might be obsolete, I believe its still useful.

I have had a problem this evening configuring Flex builder 3 with Eclipse. On the final step I was getting this annoying error and for that reason the installation fails:

Missing requirement: Flex Debug Plug-in for Eclipse 3.2 3.0.214193 (com.adobe.flexbuilder.debug.e32 3.0.214193) requires 'bundle org.eclipse.debug.ui [3.2.0,3.3.0)' but it could not be found.

The org.eclipse.debug.ui I have is much more higher version, so Flex shouldn't technically complain about this (3.5.x). I saw a lot of google posts asked by various users, but none had a solution. As I finally made it work, I thought it would be worth useful for somebody else out there.

Solution (Well precisely its not a solution, but a workaround)
  • Assuming you have already installed Flex builder.
  • Take a backup of : /com.adobe.flexbuilder.update.site/plugins/com.adobe.flexbuilder.debug.e32_3.0.214193.jar
  • unjar/open: com.adobe.flexbuilder.debug.e32_3.0.214193.jar
  • Edit META-INF/MANIFEST.MF
  • Remove the value : bundle-version="[3.2.0,3.3.0)" (which would be the last Require-Bundle section)
  • Update the Jar with the changes.
  • You might need to replace the modified com.adobe.flexbuilder.debug.e32_3.0.214193.jar into /plugins as well.
  • Restart and continue the flex update from eclipse.
This time the installation should pass. :)



Sunday, March 27, 2011

org.hibernate.util.JDBCExceptionReporter ORA-01407: cannot update (...) to NULL

I faced this issue for a while this afternoon while deleting a row which has a column referenced by a child table.



The cause for this is due to an incorrect JPA mapping:

Solution:
@OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY)
@JoinColumn(name = "FK_QUESTION_ID", updatable=false, insertable=false)

updatable=false - column is not included in SQL INSERT statements generated by the persistence provider.
updatable=false - column is not included in SQL UPDATE statements generated by the persistence provider.

Tuesday, October 26, 2010

SOAP Monitor

Came across this brilliant tool for monitoring SOAP inbound/outbound messages:

http://java-source.net/open-source/web-services-tools/membrane-soap-monitor

This is more like a tunneling software, but purely for SOAP monitoring. It formats requests/responses for easiness.

YOu could use the SOAP-UI plugin for eclipse, but its quite heavy. One good thing I liked about SOAPUI eclipse plugin is its ability ot crete Junit test case from WSDL.

Monday, May 31, 2010

java.lang.IllegalStateException: Error while loading manipulator

While trying to update eclipse plugins, you might get this error:
java.lang.IllegalStateException: Error while loading manipulator

The underlying error in the\workspace\.metadata\.log - would be something similar to:

!ENTRY org.eclipse.equinox.p2.engine 4 4 2010-06-01 00:19:00.483
!MESSAGE An error occurred while unconfiguring the items to uninstall
!SUBENTRY 1 org.eclipse.equinox.p2.engine 4 0 2010-06-01 00:19:00.483
!MESSAGE session context was:(profile=SDKProfile, phase=org.eclipse.equinox.internal.provisional.p2.engine.phases.Unconfigure, operand=[R]org.eclipse.equinox.common 3.5.0.v20090520-1800 --> [R]org.eclipse.equinox.common 3.5.1.R35x_v20090807-1100, action=org.eclipse.equinox.internal.p2.touchpoint.eclipse.actions.SetStartLevelAction).
!SUBENTRY 1 org.eclipse.equinox.p2.engine 4 0 2010-06-01 00:19:00.483
!MESSAGE Error while loading manipulator.
!STACK 0
java.lang.IllegalStateException: Error while loading manipulator.



Reason:
The eclipse has not loaded the equinox.launcher plugin.

What is Equinox and Why should I bother?

Equinox is the Osgi Framework implementation. So what? Alright, Eclipse uses OSGi as the basis for its plug-in system.

http://www.eclipse.org/equinox/

Solution:

We have to force load this plugin during startup by specifying it in the eclipse.ini.
  • Open the Eclipse.ini
  • Add the following line:
-startup
plugins/org.eclipse.equinox.launcher_1.0.201.R35x_v20090715.jar
  • Restart Eclipse
  • Try updating/installing plugins

Tuesday, November 20, 2007

Helper for Purging Oracle Bpel Instances.

I had written a piece of code during my free time, which I thought would share with some Bpel enthusiasts. There had always been questions regarding purging of Bpel instances, if it's faulted or completed abnormally..

The following code removed all the bpel instances which are:


  • Closed Faulted
  • Stale
  • Cancelled



import com.oracle.bpel.client.IActivityConstants;
import com.oracle.bpel.client.IInstanceHandle;
import com.oracle.bpel.client.Locator;

public class PurgeHelper {

    
public static void purgeInstances(String aDomainId, String aPassword, String aIPAddress) throws Exception {
        
        // initialize the instance handler
        IInstanceHandle instances[] = null;
        try {
            //check if parameters are invalid
            if(aDomainId ==null || aPassword == null )//|| aIPAddress ==null)
                throw new  Exception(" Invalid Parameter");
            // get the instances
            instances = new Locator(aDomainId, aPassword).listInstances(1, -1);
            // check for null
            if (instances == null) {
                throw new Exception("No Instances Retrieved");
            }

            // get the instance length
            int instancesLength = instances.length;
            // iterate
            for (int j = 0; j <=instancesLength;++j)
                // get the instance
                IInstanceHandle tempInstance = instances[j];
                // check for null
                if (tempInstance == null)
                    continue;
                
                //check  the state
                if(tempInstance.getState()!= IActivityConstants.STATE_CLOSED_FAULTED ||
                        tempInstance.getState()!= IActivityConstants.STATE_CLOSED_STALE ||
                        tempInstance.getState()!= IActivityConstants.STATE_CLOSED_CANCELLED)||
                        ){
                    // remove the instance from the Dehydration Store
                    tempInstance.delete();
                }

            }

        } catch (Exception err) {
            // handle exception
        }

    }

/* Some usefull Bpel instance status */

// IActivityConstants.STATE_CLOSED_FAULTED);
     // IActivityConstants.STATE_CLOSED_ABORTED);
     // IActivityConstants.STATE_CLOSED_COMPLETED);
     // IActivityConstants.STATE_CLOSED_CANCELLED);
     // IActivityConstants.STATE_CLOSED_COMPENSATED);
     // IActivityConstants.STATE_CLOSED_FINALIZED);
     // IActivityConstants.STATE_CLOSED_PENDING_CANCEL);
     // IActivityConstants.STATE_CLOSED_STALE);

   

}

Note. You need to add orabpel.jar for compilation.

Monday, January 01, 2007

If volatile why synchronized ?

Did you you have this question in mind????
ok, they are really different mate......

Have a look at the Java Language specification (JLS).

http://java.sun.com/docs/books/jls/second_edition/html/classes.doc.html#36930