Parleys.com – Great technology videos

For everyone who does not know the website parleys.com:
This is the great site with many useful videos presenting various topics which many programmers may be interested in: including Spring, Google, Cloud computing, etc.

Enjoy!

Posted in Uncategorized | Leave a comment

Hibernate ignores hbm2ddl settings – always set to update

Despite my best effore to enforce setting of hibernate.hbm2ddl.auto to “validate” (only), Hibernate has continously ignored this value and set this to “update”.
I cannot find any obvious mention about this behavior elsewhere on the internet, therefore I started debugging of Hibernate in org.hibernate.tool.hbm2ddl.SchemaUpdate class.
I found out that default setting of hibernate.hbm2ddl.auto is being done in org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter#getJpaPropertyMap method.

The root cause was that altgough I had set the following setting in my persistence.xml:

<property name="hibernate.hbm2ddl.auto" value="validate"/>

I had had another setting of property “generateDdl” to true in configuration of entityManagerFactory elsewhere:

<bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
...
        <property name="jpaVendorAdapter">
            <bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
                <property name="showSql" value="true"/>
                <!-- WATCH OUT when changing "generateDdl" settings to true -> then "hbm2ddl.auto" is automatically set to true
                     regardless of settings in persistence.xml!
                     @see HibernateJpaVendorAdapter -->
                <property name="generateDdl" value="false"/>
                <property name="databasePlatform" value="${db.dialect}"/>
            </bean>
        </property>
    </bean>

This setting caused to custom “hibernate.hbm2ddl.auto” value “validate” be replaced with default value “update”.

Posted in Uncategorized | 2 Comments

Spring WS static WSDL – reveal true location of your WSDL file

New web services in our projects use Spring WS as a replacement for Code-first approach (using Weblogic Web Services). So, basic configuration in a project has already been done, some examples created so it should be easy to create 3 new web services.

Actually, it was not so easy.
All examples use only static XSD schemas and WSDL are generated dynamically. This is ensured by following Spring configuration:

<bean class="org.springframework.ws.server.endpoint.adapter.GenericMarshallingMethodEndpointAdapter">
        <description>Enables the MessageDispatchServlet to invoke methods requiring OXM marshalling.</description>
		<constructor-arg ref="marshaller" />
	</bean>

	<bean id="marshaller" class="org.springframework.oxm.jaxb.Jaxb2Marshaller">
		<property name="contextPaths">
			<list>
				<value>com.example.sample.userws</value>
                                ...
			</list>
		</property>
	</bean>


<bean class="org.springframework.ws.server.endpoint.mapping.PayloadRootAnnotationMethodEndpointMapping">
        <description>An endpoint mapping strategy that looks for @Endpoint and @PayloadRoot annotations.</description>
		<property name="interceptors">
			<list>
				<ref bean="runAsSecurityInterceptor" />
			</list>
		</property>
	</bean>

<!-- WSDL generator -->
    <bean id="UserWS" class="org.springframework.ws.wsdl.wsdl11.DefaultWsdl11Definition">
        <property name="schemaCollection">
            <bean class="org.springframework.xml.xsd.commons.CommonsXsdSchemaCollection">
                <property name="xsds">
                    <list>
                        <value>classpath:com/example/sample/UserWS.xsd</value>
                    </list>
                </property>
                <property name="inline" value="true" />
            </bean>
        </property>
        <property name="portTypeName" value="UserWSPort" />
        <property name="locationUri" value="/sample/user/UserWS" />
    </bean>

    <!-- Service -->
    <bean id="userWsEndpoint" class="net.homecredit.homer.user.service.UserWSEndpoint" init-method="init">
         ....
    </bean>

Ok, I found out, that for my static WSDL files I must use SimpleWsdl11Definition instead:

   
<pre>
    <bean id="CreditWS" class="org.springframework.ws.wsdl.wsdl11.SimpleWsdl11Definition">
        <property name="wsdl" value="classpath:com/example/sample/CreditWS.wsdl" />
    </bean>            
</pre>                 

The main obstacle here was the determination of real URL for WSDL. After I had spent a non-trivial amount of time I realized that the name of bean “CreditWS” is actually the name of WSDL file – notice that name of the bean is “creditWS” therefore the name of WSDL is creditWS.wsdl NOT CreditWS.wsdl!

The final interesting part of code is the CreditWS.wsdl itself:

...
    <wsdl:types>
        <xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema">
            <xsd:import namespace="http://example.com/sample/creditWS" schemaLocation="CreditWS.xsd" />
        </xsd:schema>
    </wsdl:types>
...
  <wsdl:service name="CreditWS">
        <wsdl:port binding="CreditWSSOAP" name="CreditWSSOAP">
            <soap:address location="http://example.com/sample/CreditWS" />
        </wsdl:port>
    </wsdl:service>           

Spring WS is configured to replace the service location by the actual URL where the service is deployed:

servlet>
        <servlet-name>spring-ws</servlet-name>
        <servlet-class>org.springframework.ws.transport.http.MessageDispatcherServlet</servlet-class>
        <init-param>
            <param-name>transformWsdlLocations</param-name>
            <param-value>true</param-value>
        </init-param>
    </servlet>

The final url for access the wsdl file is: http://example.com/sample/creditWS.wsdl

Posted in Spring, Web Services | 1 Comment

AOP, Spring & GWT

Recently, I have must gone through quite painful exercise with aspects and their configuration in Spring – especially in an enviroment of web application based on GWT.
Here are some of my quicknotes:

Spring AOP

1) Use Spring AOP support everywhen it is sufficient! It is elegant and simple to use. All you need is adding dependencies on particular jars. For maven, the proper configuration follows:

    <spring.version>3.0.5.RELEASE</spring.version>
    <aspectj.version>1.6.10</aspectj.version>
    
    ...
    <!-- AOP -->
            <dependency>
                <groupId>org.aspectj</groupId>
                <artifactId>aspectjtools</artifactId>
                <version>${aspectj.version}</version>
            </dependency>
            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-aspects</artifactId>
                <version>${spring.version}</version>
            </dependency>
    ...

Eventually, you have to tell Spring that you want to use proxies by following configuration in spring context:

  <aop:aspectj-autoproxy />

Then you can simply use org.aspectj.lang.annotation.Aspect annotation for marking some java class as aspect and another annotations for definition of pointcuts.
I have defined two aspects.
One for automatic logging in case of exceptions – ExceptionLogger:

@Aspect
public class ExceptionLogger {
    private static final Logger LOGGER = LoggerFactory.getLogger(ExceptionLogger .class);

   @AfterThrowing(
            pointcut = "execution(* com.example.sample..*.*(..)) ",
            throwing = "exception")
    public void logExceptionMethod(Exception exception) {
        LOGGER.error("An exception has been thrown.", exception);
    }

}

Whenever arbitary method (i.e. method with any return type in any subpackage of com.example.sample that has any number of any parameters)
is invoked on managed beans and this method throws exception, then this exception is automatically logged.

Another behavior suitable for aspect is measuring time of methods’ execution time. I have marked following class as an aspect:

public class ExecutionTimeLogger {
    private static final Logger LOGGER = LoggerFactory.getLogger(ExecutionTimeLogger.class);

   @Around("execution(* com.example.sample..*.*(..))
    public Object logTimeMethod(ProceedingJoinPoint joinPoint) throws Throwable {

        final StopWatch stopWatch = new StopWatch();
        stopWatch.start();

        final Object retVal = joinPoint.proceed();

        stopWatch.stop();

        final StringBuffer logMessage = new StringBuffer();
        logMessage.append(joinPoint.getSignature().getDeclaringType().getName());
        logMessage.append(".");
        logMessage.append(joinPoint.getSignature().getName());
        logMessage.append("(");
        // append args
        final Object[] args = joinPoint.getArgs();
        for (int i = 0; i  0) {
            logMessage.deleteCharAt(logMessage.length() - 1);
        }

        logMessage.append(")");
        logMessage.append(" execution time: ");
        logMessage.append(stopWatch.getTotalTimeMillis());
        logMessage.append(" ms");
        LOGGER.info(logMessage.toString());
        return retVal;
    }

I copied the code of this aspect from this post: Logging with Spring AOP but with one important exception! Original code uses following snippet of code for logging a class name:

    logMessage.append(joinPoint.getTarget().getClass().getName());

Although it works for instance methods perfectly, this will throw NullPointerException for static methods. Therefore I use the safe variant:

    logMessage.append(joinPoint.getSignature().getDeclaringType().getName());

For more information about aspects and pointcut expressions I encourage you to read Spring official documentation: Spring AOP.

Spring AOP has certain limitations related to the usage of proxy for implementation of aspects. However, in many situations, this is not a big deal.
E.g. When you call some method within another method of the same bean, the aspect won’t be called. Furthermore, the beans must implement some interface (which is prefferable aproach in Spring) – otherwise JDK dynamic proxies cannot be used and CGLib have to be used instead -> This is only a simple change in Spring configuration:

  <aop:aspectj-autoproxy proxy-target-class="true"/>

This comes with some side effects as calling the constructor of created bean twice, but that should not be an issue.

Another reason, why one may be worried about usage of Spring AOP, is performance. Interception of call of proxied method take significantly longer than in case the byte code instrumentation is used. If this is your case, please, read this great post Debunking myths: proxies impact performance and simply don’t worry :).

AspectJ

The main reason why I have been forced to leave Spring AOP and use AspectJ instead was unability of logging methods on domain objects (that means objects not managed by Spring).
After quick check of basic examples I replaced

      <aop:aspectj-autoproxy />

with

    <context:load-time-weaver/>

and try to run the code. But problems arised. When running my tests the aspects were not called at all. So configuration of maven-surefire plugin must be modified. The great post about this is Running Spring AspectJ Tests with Maven.
This helped me to fixed the issues with tests and aspects were applied. But, unfortunately, after real start of (GWT) web application on the server problems arised. Issues are related to the usage of GWT framework and it seems there is no solution (at this time) for using LTW (Load-time Weaving) with this framework

. Further googling provided me with solution – use Compile-time weaving instead. Proper configuration for both the Ant and Maven is described at this post.
My final configuration looks as follows (I replaced usage of @Aspect annotation with definition of aspects in Spring configuration file).

Spring configuration

 <aop:config>
        <!-- pointcuts -->
        <aop:pointcut id="allProjectClasses" expression="execution(* cz.poptavka.sample..*.*(..))" />

        <!-- aspects -->
        <aop:aspect id="exceptionLoggerAspect" ref="exceptionLogger">
            <aop:after-throwing  throwing="exception"  pointcut-ref="allProjectClasses" method="logExceptionMethod" />
        </aop:aspect>
        <!-- ExecutionTimeLogger is only for performance monitoring and debugging - normally it is disabled -->
        <aop:aspect id="executionTimeLoggerAspect" ref="executionTimeLogger">
            <aop:around pointcut-ref="allProjectClasses" method="logTimeMethod" />
        </aop:aspect>

    </aop:config>

    <!-- aspects' beans' -->
    <bean id="exceptionLogger" class="cz.poptavka.sample.application.logging.ExceptionLogger" />
    <bean id="executionTimeLogger" class="cz.poptavka.sample.application.logging.ExecutionTimeLogger" />

Maven configuration

...
    <aspectj.version>1.6.10</aspectj.version>
    <aspectj-maven-plugin.version>1.3</aspectj-maven-plugin.version>
    <maven-surefire-plugin.version>2.7.1</maven-surefire-plugin.version>
...
 <!-- AOP -->
            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-aspects</artifactId>
                <version>${spring.version}</version>
            </dependency>
            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-instrument</artifactId>
                <version>${spring.version}</version>
            </dependency>
            <dependency>
                <groupId>org.aspectj</groupId>
                <artifactId>aspectjtools</artifactId>
                <version>${aspectj.version}</version>
            </dependency>
            <dependency>
                <groupId>aspectj</groupId>
                <artifactId>aspectjrt</artifactId>
                <version>${aspectj.version}</version>
            </dependency>
            <dependency>
                <groupId>aspectj</groupId>
                <artifactId>aspectjweaver</artifactId>
                <version>${aspectj.version}</version>
            </dependency>
...

    <build>
      </plugins>
....

<!-- aspectj -->
            <plugin>
                <groupId>org.codehaus.mojo</groupId>
                <artifactId>aspectj-maven-plugin</artifactId>
                <version>${aspectj-maven-plugin.version}</version>
                <configuration>
                    <source>${maven.compiler.source}</source>
                    <target>${maven.compiler.target}</target>
                    <XnoInline>true</XnoInline>
                    <aspectLibraries>
                        <aspectLibrary>
                            <groupId>org.springframework</groupId>
                            <artifactId>spring-aspects</artifactId>
                        </aspectLibrary>
                    </aspectLibraries>
                    <showWeaveInfo>true</showWeaveInfo>
                    <proceedOnError>false</proceedOnError>
                    <verbose>true</verbose>
                    <outxml>true</outxml>
                </configuration>
                <executions>
                    <execution>
                        <goals>
                            <goal>compile</goal>
                            <goal>test-compile</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>

        </plugins>
    </build>
Posted in AOP, Programming, Spring | Leave a comment

WS-I Compliance failure – missing SOAPAction transport header and Spring WS

One of my colleague ask me for help when testing Spring WS on Weblogic application server.

Error message:

org.springframework.ws.soap.client.SoapFaultClientException: BEA-382031: WS-I Compliance failure (R2744): The value of the SOAPAction transport header must be double-quoted and have the following value: ....

With great help of other colleague the solution was found early.
The WSDL for that WS (call it ActionWS) contains soapAction definition for WS method that caused an error.
But this action has not been specified in ActionWS therefore an error was rised by our OSB (Oracle Service Bus), which checks the compliance to the standard WS-I.
The solution is to set this soapAction in WS method as follows:

public void marshalWithSoapActionHeader(MyObject o) {

    webServiceTemplate.marshalSendAndReceive(o, new WebServiceMessageCallback() {

        public void doWithMessage(WebServiceMessage message) {
            ((SoapMessage)message).setSoapAction("http://tempuri.org/Action");
        }
    });
}

Further information at http://static.springsource.org/spring-ws/site/reference/html/client.html.

Posted in Java, Programming, Spring | Leave a comment

JRebel and log4j plugin problem

Today,

I’ve tried to run our web application which configuration has been changed significantly.
I’m using the JRebel to reload automatically my changes in code.
Unfortunately, the problem with JRebel’s log4j plugin arised :

org.zeroturnaround.bundled.javassist.NotFoundException: log(..) is not found in org.apache.log4j.Category

Fortunately, there is a quick and easy solution if this plugin is not important for you. You can disable this plugin as described on Zero Turnaround forum. You don’t have to specify the VM argument but you can also use the GUI configuration wizard for JRebel to disable log4j plugin.

Posted in Java, Programming, Uncategorized | Leave a comment

Correct display of border in HTML

Problem: There is a DIV element which has a CSS class “controls-ct” defined.

<div class="controls-ct">
    <div class="controls">
        <div>
            <div wicket:id="goodsCategory"/>

            <div wicket:id="goodsDetail"/>

            <div wicket:id="goodsName"/>

            <div wicket:id="goodsProducerName"/>

            <div wicket:id="goodsModel"/>

            <div wicket:id="goodsSerialNumber"/>
        </div>
        <div>
            <div wicket:id="goodsPrice"/>

            <div wicket:id="goodsInsuranceProgram"/>

            <div wicket:id="goodsInsurancePremiumSum"/>

            <div>
                <!-- List of all insurance premiums -->
                <div wicket:id="insurancePremiumsListPanel" />

                <!-- List of all insurance risks -->
                <div wicket:id="insuranceRisksListPanel" />
            </div>
        </div>

    </div>
    <!-- ADD BR TAG TO FORCE THE CORRECT DISPLAY OF BORDER -->
    <br clear="all"/>
</div>

Without usage of BR tag the display was as follows:

And after the BR tag was added:

Posted in HTML, Programming | Leave a comment

Convert special HTML and JavaScript characters

For convenient conversion of special HTML and JavaScript  characters such as “<“, “>” etc., the following conversion tool can be used: http://text-symbols.com/tools/escape-chars/

I’ve already use it for posts on this blog :).

Posted in HTML | Leave a comment

Free agile web-based project management application

If you look for a tool which enables agile planning of software project try to look at Rally.
It provides tools for planning releases, iterations, creating tasks, monitoring progress, creating reports (i.e. different charts) and so on.

The community version is free up to 10 people assigned to the project.

Posted in Project Management | Leave a comment

Version conflicts among commons-logging, logback and slf4j

After adding new dependency (hereinafter NEW_DEP) to our multi-module Maven project, we’ve encountered a strange problem. On local jetty server, everything seems to run fine, but when deploying to test enviroment on Weblogic server whoops – java.lang.AbstractMethodErrror: log.

After I had spent non-trivial amount of time by looking for causes I discovered  conflicts in versions of logging libraries. There was new transitive depenency required by NEW_DEP that uses newer version of commons-logging than our Maven project.

First of all, I excluded commons-logging in parent pom from all conflicting dependencies:

<exclusions>
    <exclusion>
        <groupId>commons-logging</groupId>
        <artifactId>commons-logging</artifactId>
    </exclusion>
</exclusions>

and added new dependency on commons-logging with updated version to our project:

<dependency>
    <groupId>commons-logging</groupId>
    <artifactId>commons-logging</artifactId>
    <version>1.1.1</version>
</dependency>

However, the problem still did not completely dissappear – a new error occured: “multiple bindings for slf4j”.

The next step was an upgrade of logback (which is used in our project as a logging framework with slf4j facade) to the most recent version. Suddenly, the problem disappeared and deployment was succesful.

Posted in Maven | Leave a comment