21 Aralık 2011 Çarşamba

log4j NDC

Here is a link about logging best practices:  http://c2.com/cgi/wiki?LoggingBestPractices
The last rule of thumb:
If you're logging the output of a web service or something like that, make sure you log an item which is unique to the session in each log message. With log4j, you can do this using a NDC. (We didn't use the session id, thats too long, we grabbed a unique integer and put it into the session). This way you can trace whats happening to a single session very easily. You can also log the request parameters as well if you're concerned about that sort of thing

for code sample:

public ReturnType method( InputType input) throws ExceptionType{

      try {
         // do something
      } catch(ExceptionType e) {
         throw e;
      } finally {

14 Aralık 2011 Çarşamba

delete log files automatically with log4j

With RollingFileAppender, there is a maxBackupIndex property which specifies the number of log files that will be kept.. Unfortunately, DailyRollingFileAppender does not support such property. Therefore, to use maxBackupIndex with DailyRollingFileAppenderhttp://www.codeproject.com/KB/java/CustomDailyRollingFileApp.aspx (and http://wiki.apache.org/logging-log4j/DailyRollingFileAppender) provides a custom DailyRollingFileAppender.

I included the file http://wiki.apache.org/logging-log4j/DailyRollingFileAppender in my project.. By the way, since some classes used (such as org.apache.log4j.RollingCalendar) is not visible outside the package org.apache.log4j, do not try to put the file in another package..

12 Aralık 2011 Pazartesi

mockito code samples

In a previous post, i promised to publish my own mockito code samples.Now, i have time to do that:

package mypackage;

import static org.junit.Assert.*;
import static org.mockito.Matchers.anyString;
import static org.mockito.Matchers.anyInt;
import static org.mockito.Matchers.anyLong;
import static org.mockito.Matchers.anyList;
import static org.mockito.Matchers.any;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;

// some more imports..

public class MyMockitoTest {
   private MockedClass mocked;
   private TestedClass tested;


public void setup() {

   mocked= mock(MockedClass .class);
   tested = new TestedClass (mocked);

public void test1() {
     // mocked method returns a new MockedReturnClass instance
     when(mocked.test1CallsThis(anyString(), anyLong(), anyInt(), anyList(), any(MyClass.class)).thenReturn(new MockedReturnClass() ));
     TestedReturnClass ret = tested.test1(//...test1 parameters);
     // required assertions
     // verify what parameters test1CallsThis actually called with      
     verify(mocked).test1CallsThis("anyString", 2L, 1, ....);      

public void test2() {
     // mocked method returns a new, prepared MockedReturnClass instance, when called with THIS_PARAM
     when(mocked.test2CallsThis(eq(EnumType.THIS_PARAM) )).thenAnswer(new Answer() {
      public MockedReturnClass answer(InvocationOnMock invocation) throws Throwable {
        MockedReturnClass retClass = new MockedReturnClass();
        // prepare return data
        return retClass ;
     // mocked method returns a new MockedReturnClass instance, when called with THAT_PARAM
     when(mocked.test2CallsThis(eq(EnumType.THAT_PARAM) )).thenReturn(new MockedReturnClass() ));
     TestedReturnClass ret = tested.test2(//...test2 parameters);
     // required assertions
     // verify both calls  

public void test3() {
     when(mocked.test3CallsThis(any(CapturedClass.class)).thenReturn(new MockedReturnClass() ));
     TestedReturnClass ret = tested.test3(//...test3 parameters);
     ArgumentCaptor captor = ArgumentCaptor.forClass(CapturedClass.class);

     // required assertions
     //capture CapturedClass here
     // and do required assertions
     // ... more assertions


public void test4() {
     try {
       // mocked method throws MockedException (return type of test4CallsThis is non-void )
       when(mocked.test4CallsThis(anyString()).thenThrow(new MockedException() ); 
       tested.test4(//...test4 parameters);
     catch(MockedException ex) {
     // ... do required assertions   


public void test5() {
     try {
       // mocked method throws MockedException (return type of test5CallsThisTwiceis void)
       doThrow(new MockedException()).when(mocked.test5CallsThisTwice(anyString()); 
       tested.test5(//...test5 parameters);
       verify(mocked, times(2)).test5CallsThisTwice("anyString");
     catch(MockedException ex) {
     // ... do required assertions   


13 Kasım 2011 Pazar

a winedt/miktex tip

For the last hour, i was wondering why latex could not see my figure file during compilation.. Finally, i figured out that latex working envirenment (where the _temp.pdf is produced during compilation) is not the directory of my current .tex file.. WinEdt/Miktex treated as if all my .tex documents i edited so far, belong to the same project, and assigned the first .tex file (which is under a different directory) as the main file of the project..

In order to correct this, i modified the Main File attribute via Project Manager window in WinEdt/Miktex accordingly.

14 Ekim 2011 Cuma

mockito argument capture

Here ise a good article about argument capture property of mockito: http://blog.james-carr.org/2009/09/28/mockito-verifying-details-of-an-object-passed-to-a-collaborator/

.. and here is more: http://docs.mockito.googlecode.com/hg/org/mockito/ArgumentCaptor.html

when i have enough time, i will publish my own test examples..until then, i must say, unit testing with mockito framework is a great way of doing white box testing and this experience leads you to review & refactor your code accordingly..

7 Ekim 2011 Cuma

modifying latex margins

modify latex margins as follows:


I use those margin values (for informal personal reports) to reduce my printing costs :)

increase tomcat 6.x memory in linux environment

Change CATALINA_OPTS as follows:
export CATALINA_OPTS="-Xms512m -Xmx2048m -XX:MaxPermSize=256m"

and restart tomcat.

endorse tomcat 6.x

In order to endorse tomcat 6.x, make a directory named endorsed under $CATALINA_HOME, and put your .jar files there.

ant create database(sql) task

here is an ant target to create the specified database... unfortunately, sql does not close the connection properly..

<target name="create-db" >
<sql driver="org.postgresql.Driver" classpath="${build.lib}/postgresql-8.4-702.jdbc4.jar" url="jdbc:postgresql://localhost:5432/template1" userid="userid" password="password" autocommit="true" onerror="continue">

         CREATE DATABASE ${database.prefix}_mydatabase;

lowercase ant task

here is ant task to lowercase a property:

<target name="lowercase-NAME" depends="init">
    <taskdef name="stringutil" classname="ise.antelope.tasks.StringUtilTask">
<classpath path="${build.lib}/antelopetasks-3.2.10.jar" />
    <property name="NAME.lowercase" value="${NAME}" />
  <stringutil string="${NAME.lowercase}" property="SURUM.lowercase">
  <lowercase />

tomcat deploy ant task

here is tomcat deploy-undeploy targets:

<target name="tomcat-start">
<exec executable="${tomcat.dir}/bin/startup.sh">
<env key="CATALINA_PID" value="${tomcat.pidfile}" />
<sleep seconds="2" />

<target name="tomcat-deploy" depends="war">
<taskdef resource="org/apache/catalina/ant/catalina.tasks" classpathref="tomcat.classpath" />
<deploy url="${tomcat.manager.url}" username="${tomcat.manager.username}" password="${tomcat.manager.password}" 
war="file:${build.dir}/${name}.war" path="/${name}}" failonerror="true" />
<sleep seconds="2" />

<target name="tomcat-undeploy">
<taskdef resource="org/apache/catalina/ant/catalina.tasks" classpathref="tomcat.classpath" />
<undeploy url="${tomcat.manager.url}" username="${tomcat.manager.username}" password="${tomcat.manager.password}" 
path="/${name}" failonerror="false" />

<target name="tomcat-stop" depends="tomcat-undeploy">
<exec executable="${tomcat.dir}/bin/shutdown.sh">
<env key="CATALINA_PID" value="${tomcat.pidfile}" />
<delete file="${tomcat.pidfile}" />

15 Eylül 2011 Perşembe


BibSonomy (http://www.bibsonomy.org/) is a successful bookmarking and publication sharing system.. In fact, i use the site to gather bibtex format reference entries..

13 Eylül 2011 Salı

logging the stacktrace

logging the stacktrace with log4j:

import org.apache.log4j.Logger;
import org.apache.log4j.PropertyConfigurator;

// ......
static Logger logger = Logger.getLogger(MyClass.class);

// ......
public static void debugException(Exception ex) {
    logger.error("An error occurred in MyClass.", ex);

frames in Latex

in order to print text inside a frame:

    The text that will be printed in frame goes here..

a few tips here: http://www.personal.ceu.hu/tex/spacebox.htm

proguard ant task

proguard (http://proguard.sourceforge.net/) promises for  the following:

  • Creating more compact code, for smaller code archives, faster transfer across networks, faster loading, and smaller memory footprints.
  • Making programs and libraries harder to reverse-engineer.
  • Listing dead code, so it can be removed from the source code.
  • Retargeting and preverifying existing class files for Java 6, to take full advantage of Java 6's faster class loading.

here is code sample:
<target name="proguard" depends="jar">
<taskdef resource="proguard/ant/task.properties" classpath="${lib}/proguard-4.4.jar" />
<proguard configuration="${config}/obfuscate.pro">
<injar file="${build.dir}/prod.jar" />
<outjar file="${build.dir}/prod_obf.jar" />
<libraryjar refid="externals" />

checkstyle ant task

checkstyle (http://checkstyle.sourceforge.net/) is a tool that hels java code to adhere to coding standards.

for checkstyle ant task: http://checkstyle.sourceforge.net/anttask.html

<property name="build.checkstyle.config" value="${config}/sun_checks.xml" />
<property name="build.checkstyle.output" value="${build.dir}/checkstyle_report.xml" />

<path id="checkstyle.classpath">
<pathelement location="${lib}/checkstyle-5.3.jar" />
<pathelement location="${lib}/google-collections-1.0.jar" />
<pathelement location="${lib}/commons-beanutils-core-1.8.3.jar" />
<pathelement location="${lib}/commons-logging-1.1.1.jar" />
<pathelement location="${lib}/antlr-2.7.7.jar" />

<target name="checkstyle" depends="init">
<taskdef resource="checkstyletask.properties" classpathref="checkstyle.classpath" />
<checkstyle failOnViolation="false" config="${build.checkstyle.config}">
<fileset dir="${src.dir}">
<include name="**/*.java" />
<formatter type="xml" tofile="${build.checkstyle.output}" />

about sun-checks.xml configuration file: http://checkstyle.sourceforge.net/config.html
here is a sample config file: http://code.google.com/p/checkstyle-idea/source/browse/trunk/src/main/resources/sun_checks.xml?r=120

cobertura ant task

cobertura (http://cobertura.sourceforge.net/) is a coverage analysis tool which reports what percentage of source code is covered by unit tests.

for cobertura ant task: http://cobertura.sourceforge.net/anttaskreference.html

and here is code sample:

<property name="build.coverage.datafile" value="${build.coverage}/cobertura.ser" />

<path id="instrument.classpath">
<pathelement location="${build.classes}" />

<path id="cobertura.classpath">
<pathelement location="cobertura-" />
<pathelement location="log4j-1.2.4.jar" />
<pathelement location="oro-2.0.8.jar" />
<pathelement location="asm-3.0.jar" />
<pathelement location="asm-tree-3.0.jar" />

<target name="instrument" depends="compile-test">
<taskdef classpathref="cobertura.classpath" resource="tasks.properties" />
<cobertura-instrument todir="${build.instrumented}" datafile="${build.coverage.datafile}">
<includeClasses regex=".*" />
<path refid="instrument.classpath" />

<target name="test" depends="compile-test, instrument">
<junit ..;>
<sysproperty key="net.sourceforge.cobertura.datafile" file="${build.coverage.datafile}" />

<target name="coverage" depends="test">
<taskdef classpathref="cobertura.classpath" resource="tasks.properties" />
<cobertura-report format="xml" destdir="${build.coverage}" srcdir="${src.dir}" datafile="${build.coverage.datafile}" />
<cobertura-check haltonfailure="false" datafile="${build.coverage.datafile}" />

12 Eylül 2011 Pazartesi

findbugs ant task

Findbugs is a static analysis tool that finds existing bugs in java code. Here is a link on how to use it from ant script: http://findbugs.sourceforge.net/manual/anttask.html

and code sample is as follows:

<property name="findbugs.home" value="/home/hilal.tarakci/Desktop/htarakci/environment/other/findbugs-1.3.9"/>
<target name="findbugs-define">
<taskdef name="findbugs" classname="edu.umd.cs.findbugs.anttask.FindBugsTask">
<classpath path="${findbugs.home}/lib/findbugs.jar" />
<!-- ensure that findbugs taskdef is only run once, otw ant will error -->
<property name="findbugs.initialized" value="true" />
<target name="findbugs" if="findbugs.present" depends="findbugs-define, jar" description="Run findbugs">
<findbugs output="xml:withMessages" home="${findbugs.home}" effort="max" outputFile="${build.dir}/findbugs.report.xml">
<fileset dir="${ivy.lib}">
<include name="**/*.jar" />
<exclude name="**/ivy-*.jar" />
<sourcePath path="${src.dir}" />
<class location="${build.dir}/${final.name}.jar" />
<xslt style="${findbugs.home}/src/xsl/fancy-hist.xsl" in="${build.dir}/findbugs.report.xml" out="${build.dir}/findbugs.report.html" />

commenting multiple lines in Latex

In order to comment multiple lines in Latex:


this line is commented out.
this one too..

to comment out just one single line:

% only this line is commented out.

11 Eylül 2011 Pazar

printing special characters in Latex

In order to print the following special characters in Latex output, simply put a \ in front of the char..

 # $ % & ~ _ ^ \ { }

more on http://www.tug.org/tutorials/latex2e/Special_Characters.html

9 Eylül 2011 Cuma

URL in Latex

I can be considered as a Latex newbie, so i try to write a post on every new piece of information about how to use Latex.
Here is sample code for using URLs in Latex:
.tex file



\title{Some Notes}
\author{Author's Name}



\section{Some Notes}

\href{http://hilaltarakci.blogspot.com}{Hilal Tarakci Blog Page}



blogreferences.bib file

    author = "Hilal Tarakci",
    title = "Hilal Tarakci Technical Page",
    howpublished = "Website",
    year = {2011},
    note = {\url{http://hilaltarakci.blogspot.com/}}

and the output is as follows:

7 Eylül 2011 Çarşamba


Mockito is a mocking framework that can be downloaded from http://code.google.com/p/mockito/

An article about mockito:
quote from that article

To create a stub (or a mock), use mock(class). Then use when(mock).thenReturn(value) to specify the stub value for a method. If you specify more than one value, they will be returned in sequence until the last one is used, after which point the last specified value gets returned. (So to have a method return the same value always, just specify it once).

Code samples on that blog are adequate, so i will not reinvent the wheel with more examples..

25 Ağustos 2011 Perşembe

how to continue build with ant despite failure

I am aware of two ways to continue build process despite failure.. The first way is the easy one.. If the task that may fail has failonerror property, simply set it to false. However, not all tasks have that property. In those situations, subant task( http://ant.apache.org/manual/Tasks/subant.html) which is generally used for batch builds come into play. In order to use subant, you have to redesign your build file by moving targets which may-fail during build process in seperate build files. The target names that will be executed wihin subant in main build.xml must be identical..

Here is a subant example:

<subant failonerror="false">
            <fileset dir="." includes="**/build.xml" excludes="build.xml"/>
            <target name="clean"/>
            <target name="build"/>

By the way, if the execution order is important, filelist must be used instead of fileset as follows:

<subant failonerror="false">
<filelist dir="${parent.dir}">
    <file name="project1/build.xml"/>
    <file name="project2/bıild.xml"/>
    <file name="projectn/build.xml"/>
            <target name="clean"/>
            <target name="build"/>

warning: non-varargs call of varargs method with inexact argument type for last parameter

The method i explained in http://hilaltarakci.blogspot.com/2011/01/printing-object-with-reflection-api-for.html is my favorite debug mechanism..
However, it results in the following warning:

warning: non-varargs call of varargs method with inexact argument type for last parameter;
    [javac] cast to java.lang.Object for a varargs call
    [javac] cast to java.lang.Object[] for a non-varargs call and to suppress this warning
    [javac]                             logger.debug("METHOD: " + mBean[i].getName() + " : " + mBean[i].invoke(classItself, null));

In order to prevent the error, simply modify the following line by casting null to Object []:

System.out.println("METHOD: " + m[i].getName() + " : " + m[i].invoke(classItself, (Object [])null));

24 Ağustos 2011 Çarşamba

ant deploy to glassfish for service assemblies

The previous post is about ant deploy of web services to glassfish v2.1 application server. If you are curious, please read http://hilaltarakci.blogspot.com/2011/08/ant-deploy-to-glassfish.html.
This post is about deploying service assemblies to glassfish via ant..

Here is my solution:
jbi_admin.xml, copied from ${glassfish.home}/jbi/bin, modified as follows:

<?xml version="1.0" encoding="UTF-8"?>
 # The contents of this file are subject to the terms
 # of the Common Development and Distribution License
 # (the "License").  You may not use this file except
 # in compliance with the License.
 # You can obtain a copy of the license at
 # https://open-esb.dev.java.net/public/CDDLv1.0.html.
 # See the License for the specific language governing
 # permissions and limitations under the License.
 # When distributing Covered Code, include this CDDL
 # HEADER in each file and include the License file at
 # https://open-esb.dev.java.net/public/CDDLv1.0.html.
 # If applicable add the following below this CDDL HEADER,
 # with the fields enclosed by brackets "[]" replaced with
 # your own identifying information: Portions Copyright
 # [year] [name of copyright owner]

 # @(#)jbi_admin.xml
 # Copyright 2004-2007 Sun Microsystems, Inc. All Rights Reserved.
 Copyright (c) 2004-2007 Sun Microsystems Inc., All Rights Reserved.
@author chikkala
<project basedir="." name="jbi_admin" xmlns:jbi="http://www.sun.com/ns/jbi/jbi-ant/1">
<target name="-pre-jbi-admin-setup">

<target name="-jbi-admin-setup" depends="-pre-jbi-admin-setup">
<taskdef resource="com/sun/jbi/ui/ant/antlib.xml" />
<!-- properties used as attribute values for ant tasks -->
<property name="jbi.target" value="server" />
<property name="jbi.secure" value="false" />
<property name="jbi.username" value="admin" />
<property name="jbi.password" value="adminadmin" />
<property name="jbi.host" value="localhost" />
<property name="jbi.port" value="4848" />
<property name="jbi.show.descriptor" value="false" />
<property name="jbi.task.fail.on.error" value="true" />
<property name="jbi.force.task" value="false" />
<property name="jbi.keep.archive" value="false" />

<target name="init-jbi-admin" depends="-jbi-admin-setup" />

<!-- deployment targets -->
<!-- deploy service assembly targets -->

<target name="-init-deploy-sa">
<condition property="deploy.sa">
<isset property="jbi.deploy.file" />
<isset property="jbi.service.assembly.name" />
<condition property="deploy.sa.from.domain">
<isset property="jbi.service.assembly.name" />
<isset property="jbi.deploy.file" />
<condition property="deploy.sa.option.error1">
<isset property="jbi.service.assembly.name" />
<isset property="jbi.deploy.file" />
<condition property="deploy.sa.option.error2">
<isset property="jbi.service.assembly.name" />
<isset property="jbi.deploy.file" />

<target name="-do-deploy-sa" depends="init-jbi-admin, -init-deploy-sa" if="deploy.sa">
<jbi-deploy-service-assembly username="${jbi.username}" password="${jbi.password}" secure="${jbi.secure}" host="${jbi.host}" port="${jbi.port}" target="${jbi.target}" 
failOnError="${jbi.task.fail.on.error}" file="${jbi.deploy.file}" />

<target name="-do-deploy-sa-from-domain" depends="init-jbi-admin, -init-deploy-sa" if="deploy.sa.from.domain">
<jbi-deploy-service-assembly username="${jbi.username}" password="${jbi.password}" secure="${jbi.secure}" host="${jbi.host}" port="${jbi.port}" target="${jbi.target}" 
failOnError="${jbi.task.fail.on.error}" name="${jbi.service.assembly.name}" />

<target name="-do-deploy-sa-option-error1" depends="init-jbi-admin, -init-deploy-sa" if="deploy.sa.option.error1">
<jbi-deploy-service-assembly username="${jbi.username}" password="${jbi.password}" secure="${jbi.secure}" host="${jbi.host}" port="${jbi.port}" target="${jbi.target}" 
failOnError="${jbi.task.fail.on.error}" file="${jbi.deploy.file}" name="${jbi.service.assembly.name}" />

<target name="-do-deploy-sa-option-error2" depends="init-jbi-admin, -init-deploy-sa" if="deploy.sa.option.error2">
<jbi-deploy-service-assembly username="${jbi.username}" password="${jbi.password}" secure="${jbi.secure}" host="${jbi.host}" port="${jbi.port}" target="${jbi.target}" 
failOnError="${jbi.task.fail.on.error}" />

<!-- main install target for deploy service assembly -->
<target name="deploy-service-assembly" depends="init-jbi-admin, -init-deploy-sa,
        -do-deploy-sa, -do-deploy-sa-from-domain, 
        -do-deploy-sa-option-error1, -do-deploy-sa-option-error2" description="Deploys Service assembly">

<!-- undeploy service assembly target -->
<target name="-init-undeploy-sa" depends="init-jbi-admin">
<!-- default service assembly name value. null or empty for no service assembly dependency in query tasks-->
<property name="jbi.service.assembly.name" value="" />

<target name="undeploy-service-assembly" depends="init-jbi-admin, -init-undeploy-sa" description="Undeploys service assembly">
<jbi-undeploy-service-assembly username="${jbi.username}" password="${jbi.password}" secure="${jbi.secure}" host="${jbi.host}" port="${jbi.port}" target="${jbi.target}" 
failOnError="${jbi.task.fail.on.error}" force="${jbi.force.task}" keepArchive="${jbi.keep.archive}" name="${jbi.service.assembly.name}" />

<target name="-init-sa-lifecycle-options" depends="init-jbi-admin">
<!-- default service assembly name value. null or empty for no service assembly dependency in query tasks-->
<property name="jbi.service.assembly.name" value="" />

<!-- start service assembly target -->
<target name="start-service-assembly" depends="init-jbi-admin, -init-sa-lifecycle-options" description="starts service assembly">
<jbi-start-service-assembly username="${jbi.username}" password="${jbi.password}" secure="${jbi.secure}" host="${jbi.host}" port="${jbi.port}" target="${jbi.target}" 
failOnError="${jbi.task.fail.on.error}" name="${jbi.service.assembly.name}" />

<!-- stop service assembly target -->
<target name="stop-service-assembly" depends="init-jbi-admin, -init-sa-lifecycle-options" description="stops service assembly">
<jbi-stop-service-assembly username="${jbi.username}" password="${jbi.password}" secure="${jbi.secure}" host="${jbi.host}" port="${jbi.port}" target="${jbi.target}" 
failOnError="${jbi.task.fail.on.error}" name="${jbi.service.assembly.name}" />

<!-- shutdown service assembly target -->
<target name="shut-down-service-assembly" depends="init-jbi-admin, -init-sa-lifecycle-options" description="shuts down service assembly">
<jbi-shut-down-service-assembly username="${jbi.username}" password="${jbi.password}" secure="${jbi.secure}" host="${jbi.host}" port="${jbi.port}" target="${jbi.target}" 
failOnError="${jbi.task.fail.on.error}" force="${jbi.force.task}" name="${jbi.service.assembly.name}" />


and the actual build.xml is as follows:

<?xml version="1.0"?>
<project name="myproject" default="zip" xmlns:ivy="antlib:org.apache.ivy.ant" xmlns:cs="antlib:com.puppycrawl.tools.checkstyle">

<import file="./jbi_admin.xml" />
        <!-- some stuff deleted.. -->
<!-- ==================================== -->
<!-- Glassfish tasks                      -->
<!-- ==================================== -->
<target name="glassfish-init" unless="glassfish.initialized">
<path id="jbi.ant.tasks.classpath.id">
<pathelement location="${glassfish.home}/lib/sun-appserv-ant.jar" />
<pathelement location="${glassfish.home}/jbi/lib/jbi-ant-tasks.jar" />
<!-- Load jbi task definitions -->
<taskdef resource="com/sun/jbi/ui/ant/antlib.xml" classpathref="jbi.ant.tasks.classpath.id" />
<taskdef name="unset" classname="ise.antelope.tasks.Unset">
<classpath path="${build.lib}/antelopetasks-3.2.10.jar" />
<!-- ensure that glassfish taskdef is only run once, otw ant will error -->
<property name="glassfish.initialized" value="true" />

<target name="glassfish-password-init" depends="init, glassfish-init">
<!-- do not forget to delete this! -->
<echo message="AS_ADMIN_PASSWORD=adminadmin" file="${build.dir}/password.file" />

<target name="glassfish-prod-deploy-pre" depends="glassfish-init">
<!--<property name="jbi.service.assembly.name" value="" />-->
<unset name="jbi.service.assembly.name"/>
<property name="jbi.task.fail.on.error" value="true" />
<property name="jbi.host" value="${prod.host}" />
<property name="jbi.deploy.file" value="${build.dir}/${name}-${SURUM}.zip" />

<target name="glassfish-start-assembly-pre" depends="glassfish-init">
<property name="jbi.task.fail.on.error" value="true" />
<property name="jbi.service.assembly.name" value="${name}-${SURUM}" />
<property name="jbi.host" value="${prod.host}" />
<unset name="jbi.deploy.file"/>
<!--<property name="jbi.deploy.file" value="" />-->

<target name="glassfish-prod-undeploy-pre" depends="glassfish-init">
<property name="jbi.task.fail.on.error" value="false" />
<property name="jbi.service.assembly.name" value="${name}-${SURUM}" />
<property name="jbi.host" value="${prod.host}" />
<unset name="jbi.deploy.file"/>
<!--<property name="jbi.deploy.file" value="" />-->

<target name="exec-glassfish-prod-deploy" depends="zip, glassfish-prod-deploy-pre, deploy-service-assembly">

<target name="exec-glassfish-start-assembly" depends="glassfish-start-assembly-pre, start-service-assembly">

<target name="glassfish-prod-deploy" depends="exec-glassfish-prod-deploy, exec-glassfish-start-assembly">

<target name="glassfish-prod-undeploy" depends="glassfish-prod-undeploy-pre, shut-down-component, undeploy-service-assembly">


glassfish-prod-deploy target deploys the specified assembly to the application server and starts it.
Likewise, glassfish-prod-undeploy target shutdowns the assembly and undeploys it.

19 Ağustos 2011 Cuma

ant deploy to glassfish

In order to deploy the web service war to glassfish using ant, you can use the following ant snippet:

<target name="glassfish-init" unless="glassfish.initialized">
<taskdef name="sun-appserv-deploy" classname="org.apache.tools.ant.taskdefs.optional.sun.appserv.DeployTask">
<classpath path="${glassfish.home}/lib/sun-appserv-ant.jar" />
<taskdef name="sun-appserv-undeploy" classname="org.apache.tools.ant.taskdefs.optional.sun.appserv.UndeployTask">
<classpath path="${glassfish.home}/lib/sun-appserv-ant.jar" />
<!-- ensure that glassfish taskdef is only run once, otw ant will error -->
<property name="glassfish.initialized" value="true" />

<target name="glassfish-password-init" depends="init, glassfish-init">
<!-- do not forget to delete this! -->
<echo message="AS_ADMIN_PASSWORD=adminadmin" file="${build.dir}/password.file" />

<target name="glassfish-remote-deploy" depends="glassfish-init, glassfish-password-init, war">
<sun-appserv-deploy file="${build.dir}/${name}-${version}.war" name="${name}-${version}" 
user="admin" passwordfile="${build.dir}/password.file" host="remotemachine" port="4848"

<target name="glassfish-remote-undeploy" depends="glassfish-init, glassfish-password-init">
<sun-appserv-undeploy name="${name}-${version}" 
user="admin" passwordfile="${build.dir}/password.file" host="remotemachine" port="4848" 

The point is to use sun-appserv-ant.jar file, which includes glassfish specific ant task definitions, inside glassfish v2.1 home directory. Otherwise, there will be ClassCouldNotBeFound exceptions..

18 Ağustos 2011 Perşembe

hibernate on glassfish

A way of  powering glassfish with hibernate support (instead of toplink) is directly copying hibernate runtime.jar files under glassfish's domain1/lib folder. However, this forces all deployed applications to use the same hibernate version. Therefore, the best solution is packaging hibernate .jars with the application itself.

Here is a useful link which explains how to use hibernate JPA on glassfish: http://javafromthetrenches.wordpress.com/2011/01/15/using-hibernate-jpa-with-glassfish/

The following dependencies worked for me:

<dependency org="antlr"

<dependency org="asm"

<dependency org="asm"

<dependency org="cglib"

<dependency org="commons-collections"

<dependency org="commons-logging"

<dependency org="dom4j"

<dependency org="ehcache"

<dependency org="javax.transaction"

<dependency org="org.hibernate"

<dependency org="org.hibernate"

<dependency org="org.hibernate"

<dependency org="org.hibernate"

<dependency org="javassist"

<dependency org="org.hibernate"

<-- if hibernate cloning api beanlib is going to be used -->
<dependency org="net.sf.beanlib"

<-- if hibernate cloning api beanlib is going to be used -->
<dependency org="net.sf.beanlib"

<!-- if postgresql driver is going to be used -->
<dependency org="it.cnr.isti.domoware"

The listed dependencies are not latest version of hibernate, however it is a working hibernate runtime set of jars. Here is an ongoing discussion about the topic: http://www.java.net/forum/topic/glassfish/glassfish/updating-support-hibernate-glassfish-need-communitys-help

14 Ağustos 2011 Pazar

Latex - referencing a web site

While writing .tex document, the following is a valid web site reference.

author = {W3C Incubator Group},
title = {MPEG-7 and the Semantic Web},
month = aug,
year = {2011},
url = {http://www.w3.org/2005/Incubator/mmsem/XGR-mpeg7/}

and latex output is:

MPEG-7 [1] is one of ..
[1] W3C Incubator Group. Mpeg-7 and the semantic web, August 2011.

9 Ağustos 2011 Salı

reading from properties file

a simple code snippet for reading from properties file:

import java.util.ResourceBundle;

Locale locale = new Locale("en_US");
ResourceBundle bundle = ResourceBundle.getBundle("mypropertiesfile", locale);
String name = bundle.getString("name");
String surname = bundle.getString("surname");

.. and the corresponding mypropertiesfile.properties should be in the classpath:

name = buffy
surname = vampireSlayer

3 Ağustos 2011 Çarşamba

java.lang.NoSuchMethodError: javax.xml.ws.WebFault.messageName()Ljava/lang/String;

After successfully deploying web services to glassfish v2.1 server, the following error comes up while running test client code:
java.lang.NoSuchMethodError: javax.xml.ws.WebFault.messageName()Ljava/lang/String;
at com.sun.xml.ws.model.RuntimeModeler.processExceptions(RuntimeModeler.java:1162)
at com.sun.xml.ws.model.RuntimeModeler.processDocWrappedMethod(RuntimeModeler.java:898)
at com.sun.xml.ws.model.RuntimeModeler.processMethod(RuntimeModeler.java:666)
at com.sun.xml.ws.model.RuntimeModeler.processClass(RuntimeModeler.java:420)
at com.sun.xml.ws.model.RuntimeModeler.buildRuntimeModel(RuntimeModeler.java:254)
at com.sun.xml.ws.client.WSServiceDelegate.createSEIPortInfo(WSServiceDelegate.java:661)
at com.sun.xml.ws.client.WSServiceDelegate.addSEI(WSServiceDelegate.java:649)
at com.sun.xml.ws.client.WSServiceDelegate.getPort(WSServiceDelegate.java:343)
at com.sun.xml.ws.client.WSServiceDelegate.getPort(WSServiceDelegate.java:326)
at com.sun.xml.ws.client.WSServiceDelegate.getPort(WSServiceDelegate.java:308)
at javax.xml.ws.Service.getPort(Service.java:92)

According to this, current JAVA_HOME is pointing to Java 6 SE, which now has a version of WebFault WITHOUT the messageName element ..

In order to fix this situation, endorse mechanism should be applied, similar to this http://weblogs.java.net/blog/ramapulavarthi/archive/2009/04/tip_for_using_j.html

my solution is to add the following to junit ant task:

<jvmarg value="-Djava.endorsed.dirs=${lib.endorsed.dir}"/>

// endorsed folder consists of webservices-api.jar..

2 Ağustos 2011 Salı

running ant JUnitTask

message from ant:

.../build.xml:346: Problem: failed to create task or type junit
Cause: the class org.apache.tools.ant.taskdefs.optional.junit.JUnitTask was not found.
        This looks like one of Ant's optional components.

this is due to lack of  ant-junit.jar file.

one method is to download ant-junit.jar from here: http://www.java2s.com/Code/Jar/ABC/Downloadantjunitjar.htm
and copy it under $ANT_HOME/lib

another method is to download a newer version of ant (http://ant.apache.org/)
ant 1.8.2 comes with that jar file..

http://ant.apache.org/manual/Tasks/junit.html explains how to run junit task..

28 Temmuz 2011 Perşembe

a simple log4j example

the properties file is something like that:


log4j.appender.SampleAppender =org.apache.log4j.FileAppender
log4j.appender.SampleAppender .File=Sample.log
log4j.appender.SampleAppender .layout=org.apache.log4j.PatternLayout
log4j.appender.SampleAppender .layout.ConversionPattern= [%t] %-5p %c{2} %d %x - %m%n


import org.apache.log4j.Logger;
import org.apache.log4j.PropertyConfigurator;

public class Sample {

    static Logger logger = Logger.getLogger(Sample.class);

    public static void debug(String message, boolean debugModeOn) {
        if (debugModeOn) {
            logger.debug( message);

log4j.properties file must be in classpath..
for log format: http://logging.apache.org/log4j/1.2/apidocs/org/apache/log4j/PatternLayout.html

26 Temmuz 2011 Salı

how to use subfigure feature in Latex

In order to use subfigure feature in Latex:

To reference subfigure do Figure ~\ref{fig:second}

\begin{figure} [htp]
    \subfigure[My First Figure]{\label{fig:first}\includegraphics[scale=0.30]{first.PNG}}
    \subfigure[My Second Figure]{\label{fig:second}\includegraphics[scale=0.30]{second.PNG}} \\
  \caption{MAVIS Interfaces}

24 Temmuz 2011 Pazar

writing XML code in Latex

two ways to produce XML code in Latex:

1st way:

    \\ $<$Sem\=anticBase id="Biglia\_Anderlecht\_58\_4" xsi:type="AgentObjectType"$>$ \\
    \>  $<$Lab\=el$>$ \\
    \> \>      $<$Name /$>$ \\
    \>    $<$/Label$>$ \\
    \>    $<$Def\=inition$>$ \\
    \> \>      $<$FreeTextAnnotation /$>$ \\
    \>    $<$/Definition$>$ \\
    \>    $<$Med\=iaOccurrence$>$ \\
    \> \>      $<$Med\=iaLocator xsi:type="TemporalSegmentLocatorType"$>$ \\
    \> \> \>      $<$Med\=iaTime$>$ \\
    \> \> \> \>          $<$MediaTimePoint$>$58$<$/MediaTimePoint$>$ \\
    \> \> \>      $<$/MediaTime$>$ \\
    \> \>      $<$/MediaLocator$>$ \\
    \>    $<$/MediaOccurrence$>$ \\
    \>    $<$Relation type="urn:...:agentOf" target="Corner" /$>$ \\
    \>    $<$Relation type="urn:...:memberOf" target="ANDERLECHT" /$>$ \\
    \>     $<$Age\=nt xsi:type="PersonType"$>$ \\
    \> \>      $<$Nam\=e$>$ \\
    \> \> \>        $<$GivenName$>$ Biglia $<$/GivenName$>$ \\
    \> \> \>        $<$FamilyName /$>$ \\
    \> \>      $<$/Name$>$ \\
    \>    $<$/Agent$>$ \\
      $<$/SemanticBase$>$ \\


2nd way is by using listings style..

18 Temmuz 2011 Pazartesi

how to change web service endpoint at run time

In order to change web service url endpoint at runtime, change call code as follows:
try { // Call Web Service Operation
           MyServiceService service = new MyServiceService();
           MyService port = service.getMyServicePort();
            BindingProvider bp = (BindingProvider)port;
            java.lang.String username = "admin";
            java.lang.String password = "admin";

            ResultType result = port.myServiceOperation(username, password);
        } catch (Exception ex) {

7 Temmuz 2011 Perşembe

error during deploying ws to glassfishesb v2.2.

My environment is as follows:
- The server is on a virtual machine (played by VMWare player).. Operating system of server is OpenSuse 11.4, os of client is OpenSuse 11.2
- The application server is installed with GlassfishESB v2.2 (https://cds.sun.com/is-bin/INTERSHOP.enfinity/WFS/CDS-CDS_SMI-Site/en_US/-/USD/ViewProductDetail-Start?ProductRef=GFESB-22-G-F@CDS-CDS_SMI)

The scenario is :
1) WS project is successfully deployed.
2) Bpel module (CA project with Bpel Module) is successfully deployed.
3) When i tried to redeploy WS project i got this error:

 constituent CLs :: 
 :: asimpl :: optionalChain
 was requested to find class com.sun.enterprise.management.deploy.DeployThread.LogStrings after done was invoked from the following stack trace
        at com.sun.enterprise.loader.EJBClassLoader.findClassData(EJBClassLoader.java:708)
        at com.sun.enterprise.loader.EJBClassLoader.findClass(EJBClassLoader.java:628)

it may be about this: http://java.net/jira/browse/GLASSFISH-11715

My workaround:
When i undeployed bpel project and redeployed ws project afterwards, it worked for me..

5 Temmuz 2011 Salı

VMWare player error: Could not open /dev/vmmon

i got the following error when i tried to reopen vmware on Opensuse 11.2 host:

1. error screen
Could not open /dev/vmmon: No such file or directory.
Please make sure that the kernel module `vmmon' is loaded.
2. error screen
Failed to initialize monitor device.
3. error screen
The virtual machine is busy.

here (http://communities.vmware.com/thread/245998) explains the reason as :
From what I've read, this happens on OpenSUSE. VMware comes with some pre-built binaries which somehow don't work on this OS. So you're deleting them, and by running that tool they are built again, this time for your system.

and the solution is to execute following commands:
sudo mv /usr/lib/vmware/modules/binary /usr/lib/vmware/modules/binary.old
sudo vmware-modconfig --console --install-all --appname="VMware Player" --icon="vmware-player"