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

Wednesday, December 28, 2016

internal maven properties

This page extracts a few classical values:
  • ${project.basedir} 
    • This references to the root folder of the module/project (the location where the current pom.xml file is located)
POM properties referencing useful build locations, with default values defined in the Super POM:
  • ${project.build.directory}
    • This represents by default the target folder.
  • ${project.build.outputDirectory}
    • This represents by default the target/classes folder.
  • ${project.build.testOutputDirectory}
    • This represents by default the target/test-classes folder.
  • ${project.build.sourceDirectory}
    • This represents by default the src/main/java folder.
  • ${project.build.testSourceDirectory}
    • This represents by default the src/test/java folder.
You can use further properties like the following:
  • ${project.build.finalName}
    • This is by default defined as ${project.artifactId}-${project.version}.
  • ${project.version}
    • This can be used at locations where you have to write a literal version otherwise, in particular if you are in a multi-modules build for inter modules dependencies.
User Settings
The settings.xml elements could be referenced by using things like this (see also at the Super POM):
  • ${settings.localRepository}
    • which references the location of the local repository. This is by default ${home}/.m2/repository.
Values are evaluated in sequence from different syntaxes:
valueevaluation resultcommon examples
project.*
pom.* (deprecated)
* (deprecated)
POM content (see POM reference)${project.version}
${project.build.finalName}
${project.artifactId}
${project.build.directory}
project.basedir
pom.basedir (deprecated)
basedir (deprecated)
the directory containing the pom.xml file${project.basedir}
project.baseUri
pom.baseUri (deprecated)
the directory containing the pom.xml file as URI${project.baseUri}
build.timestamp
maven.build.timestamp
the UTC timestamp of build start, in yyyy-MM-dd'T'HH:mm:ss'Z' default format, which can be overridden with maven.build.timestamp.format POM property${maven.build.timestamp}
*user properties, set from CLI with -Dproperty=value${skipTests}
*model properties, such as project properties set in the pom${any.key}
maven.homeThe path to the current Maven home.${maven.home}
maven.versionThe version number of the current Maven execution (since 3.0.4). For example, "3.0.5".${maven.version}
maven.build.versionThe full build version of the current Maven execution (since 3.0.4). For example, "Apache Maven 3.2.2 (r01de14724cdef164cd33c7c8c2fe155faf9602da; 2013-02-19T14:51:28+01:00)".${maven.build.version}
*Java system properties (see JDK reference)${user.home}
${java.home}
env.*
*
environment variables${env.PATH}
settings.*Local user settings (see settings reference)${settings.localRepository}

Thursday, July 7, 2016

Log4j : logging one package to log file and another package to another logfile ... on different levels.

Sending the only com.dashboard.process [debug] information to a file.... AND
Sending the info messages of com.dashboard [info] information to another file including the info
messages of com.dashboard.process.


<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE log4j:configuration PUBLIC "-//LOGGER" "http://logging.apache.org/log4j/1.2/apidocs/org/apache/log4j/xml/doc-files/log4j.dtd">
<log4j:configuration>
 <!-- an appender is an output destination, such as the console or a file; names of appenders are arbitrarily chosen -->
 <appender name="stdout" class="org.apache.log4j.ConsoleAppender">
  <layout class="org.apache.log4j.EnhancedPatternLayout">
   <param name="ConversionPattern" value="%d %-5p %c{1} (%F:%L) %m%n" />

  </layout>
 </appender>
 <appender name="stderr" class="org.apache.log4j.ConsoleAppender">
  <param name="target" value="System.err" />
  <layout class="org.apache.log4j.PatternLayout">
   <param name="ConversionPattern" value="%-5p %d [%t][%F:%L] : %m%n" />
  </layout>
 </appender>
 <appender name="file" class="org.apache.log4j.RollingFileAppender">
  <param name="File" value="${log4j.dir}/dashboard.log" />
  <param name="MaxFileSize" value="2Mb" />
  <param name="MaxBackupIndex" value="5" />
  <layout class="org.apache.log4j.PatternLayout">
   <param name="ConversionPattern" value="%-5p %d [%t][%F:%L] : %m%n" />
  </layout>
 </appender>
 <appender name="harvestor" class="org.apache.log4j.RollingFileAppender">
  <param name="File" value="${log4j.dir}/dashboard-harvest.log" />
  <param name="MaxFileSize" value="2Mb" />
  <param name="MaxBackupIndex" value="5" />
  <layout class="org.apache.log4j.PatternLayout">
   <param name="ConversionPattern" value="%-5p %d [%t][%F:%L] : %m%n" />
  </layout>
 </appender>

 <category name="org.springframework.ui.velocity">
  <priority value="WARN" />
 </category>
 <category name="org.springframework.web.servlet.view.velocity">
  <priority value="WARN" />
 </category>
 <category name="org.apache.velocity.runtime">
  <priority value="WARN" />
 </category>
 <category name="org.springframework.web.util" additivity="false">
  <priority value="WARN" />
 </category>
 <category name="org.eclipse.jetty.servlet">
  <priority value="WARN" />
 </category>
 <category name="com.dashboard.process" additivity="false">
  <priority value="DEBUG"></priority>
 </category>
 <category name="com.dashboard" additivity="true">
  <priority value="INFO"></priority>
 </category>

 <!-- the root category -->
 <!-- all log messages of level "debug" or higher will be logged, unless defined otherwise all log messages will be logged to the appender 
  "stdout", unless defined otherwise -->
  
  <logger name="com.dashboard">
    <level value="INFO" />
    <appender-ref ref="file" />
  </logger>

 <logger name="com.dashboard.process" additivity="false">
  <level value="DEBUG" />
  <appender-ref ref="harvestor" />
 </logger>


</log4j:configuration>


Thursday, March 28, 2013

onliner - JAXBElement XJC Bindings and XMLRootElement creation for any schema

Some schema's do not get generated with the XMLRootElements which can get you into trouble marshalling Java 2 XML. See the error below
Caused by: javax.xml.bind.MarshalException
 - with linked exception:
[com.sun.istack.internal.SAXException2: unable to marshal type "com.tibco.xmlns.applicationmanagement.ApplicationType" as an element because it is missing an @XmlRootElement annotation]
 at com.sun.xml.internal.bind.v2.runtime.MarshallerImpl.write(MarshallerImpl.java:317)
 at com.sun.xml.internal.bind.v2.runtime.MarshallerImpl.marshal(MarshallerImpl.java:243)
 at org.springframework.oxm.jaxb.Jaxb2Marshaller.marshal(Jaxb2Marshaller.java:626)
 ... 25 more
Caused by: com.sun.istack.internal.SAXException2: unable to marshal type "com.tibco.xmlns.applicationmanagement.ApplicationType" as an element because it is missing an @XmlRootElement annotation
 at com.sun.xml.internal.bind.v2.runtime.XMLSerializer.reportError(XMLSerializer.java:216)
 at com.sun.xml.internal.bind.v2.runtime.ClassBeanInfoImpl.serializeRoot(ClassBeanInfoImpl.java:286)
 at com.sun.xml.internal.bind.v2.runtime.XMLSerializer.childAsRoot(XMLSerializer.java:462)
 at com.sun.xml.internal.bind.v2.runtime.MarshallerImpl.write(MarshallerImpl.java:314)
 ... 27 more
[ERROR] 
With the XJC bindings we can fix this however can be tedious going thru all the elements.... Boring.... so lets make a oneliner.... Here a one liner that will solve that and will generate the annotation section for your xcj.bindings or jaxb.bindings... Generating the XMLRootElement on bindings (requirements for perl will be XML::Simple see cpan)
perl -MXML::Simple -e 'BEGIN { use Data::Dumper; } $x=XMLin("./src/main/schema/5.5/ApplicationManagement.xsd");foreach (keys %{$x->{"complexType"}}) { printf "<jaxb:bindings node=\"xs:complexType[\@name=%c%s%c]\">
<annox:annotate><annox:annotate annox:class=\"javax.xml.bind.annotation.XmlRootElement\" name=\"%s\"/></annox:annotate></jaxb:bindings>\n",0x27,$_,0x27,$_ if $_; };'
Generates the output on the console:
<jaxb:bindings node="xs:complexType[=ActionType]"><annox:annotate><annox:annotate annox:class="javax.xml.bind.annotation.XmlRootElement" name="ActionType"/></annox:annotate></jaxb:bindings>
<jaxb:bindings node="xs:complexType[=ServiceType]"><annox:annotate><annox:annotate annox:class="javax.xml.bind.annotation.XmlRootElement" name="ServiceType"/></annox:annotate></jaxb:bindings>
<jaxb:bindings node="xs:complexType[=ServiceInstanceType]"><annox:annotate><annox:annotate annox:class="javax.xml.bind.annotation.XmlRootElement" name="ServiceInstanceType"/></annox:annotate></jaxb:bindings>
<jaxb:bindings node="xs:complexType[=anyObject]"><annox:annotate><annox:annotate annox:class="javax.xml.bind.annotation.XmlRootElement" name="anyObject"/></annox:annotate></jaxb:bindings>
<jaxb:bindings node="xs:complexType[=ApplicationType]"><annox:annotate><annox:annotate annox:class="javax.xml.bind.annotation.XmlRootElement" name="ApplicationType"/></annox:annotate></jaxb:bindings>
<jaxb:bindings node="xs:complexType[=NVPairType]"><annox:annotate><annox:annotate annox:class="javax.xml.bind.annotation.XmlRootElement" name="NVPairType"/></annox:annotate></jaxb:bindings>
<jaxb:bindings node="xs:complexType[=RepoInstanceType]"><annox:annotate><annox:annotate annox:class="javax.xml.bind.annotation.XmlRootElement" name="RepoInstanceType"/></annox:annotate></jaxb:bindings>
<jaxb:bindings node="xs:complexType[=RemoteRepoInstanceType]"><annox:annotate><annox:annotate annox:class="javax.xml.bind.annotation.XmlRootElement" name="RemoteRepoInstanceType"/></annox:annotate></jaxb:bindings>
<jaxb:bindings node="xs:complexType[=EventType]"><annox:annotate><annox:annotate annox:class="javax.xml.bind.annotation.XmlRootElement" name="EventType"/></annox:annotate></jaxb:bindings>
<jaxb:bindings node="xs:complexType[=BWServiceType]"><annox:annotate><annox:annotate annox:class="javax.xml.bind.annotation.XmlRootElement" name="BWServiceType"/></annox:annotate></jaxb:bindings>
Signings-MacBook-Pro:tibco-appmanage-schema $ 
THe end result as a XJC bindings file... which can be included in your XJC generation, in my case the maven plugin:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<jaxb:bindings xmlns:jaxb="http://java.sun.com/xml/ns/jaxb"
  xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:xjc="http://java.sun.com/xml/ns/jaxb/xjc"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:annox="http://annox.dev.java.net"
  xsi:schemaLocation="http://java.sun.com/xml/ns/jaxb http://java.sun.com/xml/ns/jaxb/bindingschema_2_0.xsd"
  version="2.1">
  <jaxb:bindings schemaLocation="ApplicationManagement.xsd"
    node="/xs:schema">
    <jaxb:globalBindings generateIsSetMethod="true"
      collectionType="java.util.ArrayList">
    </jaxb:globalBindings>
    <jaxb:bindings node="xs:complexType[@name=ActionType]">
      <annox:annotate>
        <annox:annotate annox:class="javax.xml.bind.annotation.XmlRootElement"
          name="ActionType" />
      </annox:annotate>
    </jaxb:bindings>
    <jaxb:bindings node="xs:complexType[@name=ServiceType]">
      <annox:annotate>
        <annox:annotate annox:class="javax.xml.bind.annotation.XmlRootElement"
          name="ServiceType" />
      </annox:annotate>
    </jaxb:bindings>
    <jaxb:bindings node="xs:complexType[@name=ServiceInstanceType]">
      <annox:annotate>
        <annox:annotate annox:class="javax.xml.bind.annotation.XmlRootElement"
          name="ServiceInstanceType" />
      </annox:annotate>
    </jaxb:bindings>
    <jaxb:bindings node="xs:complexType[@name=anyObject]">
      <annox:annotate>
        <annox:annotate annox:class="javax.xml.bind.annotation.XmlRootElement"
          name="anyObject" />
      </annox:annotate>
    </jaxb:bindings>
    <jaxb:bindings node="xs:complexType[@name=ApplicationType]">
      <annox:annotate>
        <annox:annotate annox:class="javax.xml.bind.annotation.XmlRootElement"
          name="ApplicationType" />
      </annox:annotate>
    </jaxb:bindings>
    <jaxb:bindings node="xs:complexType[@name=NVPairType]">
      <annox:annotate>
        <annox:annotate annox:class="javax.xml.bind.annotation.XmlRootElement"
          name="NVPairType" />
      </annox:annotate>
    </jaxb:bindings>
    <jaxb:bindings node="xs:complexType[@name=RepoInstanceType]">
      <annox:annotate>
        <annox:annotate annox:class="javax.xml.bind.annotation.XmlRootElement"
          name="RepoInstanceType" />
      </annox:annotate>
    </jaxb:bindings>
    <jaxb:bindings node="xs:complexType[@name=RemoteRepoInstanceType]">
      <annox:annotate>
        <annox:annotate annox:class="javax.xml.bind.annotation.XmlRootElement"
          name="RemoteRepoInstanceType" />
      </annox:annotate>
    </jaxb:bindings>
    <jaxb:bindings node="xs:complexType[@name=EventType]">
      <annox:annotate>
        <annox:annotate annox:class="javax.xml.bind.annotation.XmlRootElement"
          name="EventType" />
      </annox:annotate>
    </jaxb:bindings>
    <jaxb:bindings node="xs:complexType[@name=BWServiceType]">
      <annox:annotate>
        <annox:annotate annox:class="javax.xml.bind.annotation.XmlRootElement"
          name="BWServiceType" />
      </annox:annotate>
    </jaxb:bindings>
  </jaxb:bindings>
</jaxb:bindings>
And the declaration of the maven plugin....
      <plugin>
        <groupId>org.jvnet.jaxb2.maven2</groupId>
        <artifactId>maven-jaxb2-plugin</artifactId>
        <version>0.8.3</version>
        <executions>
          <execution>
            <id>generate-domain1</id>
            <goals>
              <goal>generate</goal>
            </goals>
          </execution>
        </executions>
        <configuration>
          <strict>true</strict>
          <schemaDirectory>src/main/schema/${schema.version}</schemaDirectory>
          <schemaIncludes>
            <value>scm-tibco-project.xsd</value>
          </schemaIncludes>
          <bindingIncludes>
            <include>xjc.bindings</include>
          </bindingIncludes>
          <verbose>true</verbose>
          <extension>true</extension>
          <args>
            <arg>-Xannotate</arg>
            <arg>-Xequals</arg>
            <arg>-XtoString</arg>
            <arg>-XhashCode</arg>
          </args>
          <generateDirectory>${project.build.directory}/generated-sources/xjc
          </generateDirectory>
          <plugins>
            <plugin>
              <groupId>org.jvnet.jaxb2_commons</groupId>
              <artifactId>jaxb2-basics</artifactId>
              <version>0.6.0</version>
            </plugin>
            <plugin>
              <groupId>org.jvnet.jaxb2_commons</groupId>
              <artifactId>jaxb2-basics-annotate</artifactId>
              <version>0.6.0</version>
            </plugin>
          </plugins>
        </configuration>
      </plugin>

Sunday, November 4, 2012

java.security single vs double 'equals' specifying java.policy

Just because I have seen conflicting messages regarding '=' vs '==' as in
-Djava.security.policy==my.policy
or
-Djava.security.policy=my.policy
. The names of the default policy files When the default implementation of the Policy class reads in permissions, it will read them from the URLs listed as this set of properties:
policy.url.1=file:${java.home}/lib/security/java.policy
policy.url.2=file:${user.home}/.java.policy
You may specify any number of files in this manner, but the list must start at 1 and be numbered consecutively. The set of permissions will be the aggregate of all permissions found in these URLs. Remember that these URLs contain only global permissions. You may also specify on the command line a file containing policies with the -Djava.security.policy argument. If the name following the -Djava.security.policy argument begins with an equals sign, the URLs listed in the java.security file are ignored:
-Djava.security.policy=/globals/java.policy (NO APPEND)
adds the policies in the /globals/java.policy file to the set of policies in force, but:
-Djava.security.policy==/globals/java.policy (APPEND AFTER policy.url's listed in java.security)
sets the policy only to the entries contained in the /globals/java.policy file. The -Djava.security.policy argument must be with the -Djava.security.manager; if you want to use only the files listed in the java.security file, specify -Djava.security.manager without -Djava.security.policy. Other implementations of the Policy class may or may not use these properties.

Saturday, November 3, 2012

java.security.debug property syntax logging

A number of Java debugging flags are available to assist you in determining how the security manager is using your security policy file, and what policy files are contributing permissions. Running the VM as follows shows the possible debugging flag settings:
[bin]$ java -Djava.security.debug=help

all            turn on all debugging
access         print all checkPermission results
combiner       SubjectDomainCombiner debugging
configfile     JAAS ConfigFile loading
configparser   JAAS ConfigFile parsing
gssloginconfig GSS LoginConfigImpl debugging
jar            jar verification
logincontext   login context results
policy         loading and granting
provider       security provider debugging
scl            permissions SecureClassLoader assigns

The following can be used with access:

stack         include stack trace
domain        dump all domains in context
failure       before throwing exception, dump stack
              and domain that didn't have permission

The following can be used with stack and domain:

permission=
              only dump output if specified permission
              is being checked
codebase=
              only dump output if specified codebase
              is being checked
Running with -Djava.security.debug=all provides the most output, but the output volume is acutely verbose. This might be a good place to start if you don't understand a given security failure at all. For less verbose output that will still assist with debugging permission failures, use -Djava.security.debug=access,failure.

Tuesday, September 4, 2012

Whats the encoding of my file? Compile complaints....

on Linux use... file -bi option
[cpcdev@dpcpca01 cpc]$ file -bi ./src/main/java/com/fedex/ground/dispatch/cpcs/actions/OnCallDetailActionHandler.java
text/x-java; charset=unknown
[cpcdev@dpcpca01 cpc]$ 
Or in Mac OSX
file -I --mime-encoding /prod/PersistanceLayer/src/java/domain/server/toplink/Equipment.java

Class Magic Number And Bytecode compatibility on Linux

Based on the general layout (see item #7)we need the 8th hex number to get the value. And then match the major version number with the JDK version compatibility.
major version number of the class file format being used.
J2SE 7 = 51 (0x33 hex),
J2SE 6.0 = 50 (0x32 hex),
J2SE 5.0 = 49 (0x31 hex),
JDK 1.4 = 48 (0x30 hex),
JDK 1.3 = 47 (0x2F hex),
JDK 1.2 = 46 (0x2E hex),
JDK 1.1 = 45 (0x2D hex).
In this case
[me@hostandre]$ xxd -p  org/apache/xmlbeans/impl/xsd2inst/SampleXmlUtil.class  | head -n 1 | cut -c-16
cafebabe00000030
[me@hostandre]$
The answer is: JDK 1.4 compiled and compatible...

Friday, August 17, 2012

Adding XmlRootElement

 
  <plugin>
    <groupId>org.jvnet.jaxb2.maven2</groupId>
    <artifactId>maven-jaxb2-plugin</artifactId>
    <version>0.7.4</version>
    <executions>
     <execution>
      <id>generate-domain1</id>
      <goals>
       <goal>generate</goal>
      </goals>
      <configuration>
       <strict>true</strict>
       <schemaDirectory>src/main/schema</schemaDirectory>
       <schemaIncludes>
        <value>*.xsd</value>
       </schemaIncludes>
       <bindingIncludes>
        <include>bindings.xjb</include>
       </bindingIncludes>
       <verbose>true</verbose>
       <extension>true</extension>
       <args>
        <arg>-Xannotate</arg>
       </args>
       <generateDirectory>${project.build.directory}/generated-sources/xjc</generateDirectory>
       <plugins>
        <plugin>
         <groupId>org.jvnet.jaxb2_commons</groupId>
         <artifactId>jaxb2-basics</artifactId>
         <version>0.6.0</version>
        </plugin>
        <plugin>
         <groupId>org.jvnet.jaxb2_commons</groupId>
         <artifactId>jaxb2-basics-annotate</artifactId>
         <version>0.6.0</version>
        </plugin>
       </plugins>
      </configuration>
     </execution>
    </executions>
   </plugin>

Wednesday, March 14, 2012

Please Log Everything with a Log4j.xml to my screen....

It's sad to put this down however every time I need it, I forget the syntax... whats the proper syntax to answer my "please log everything to the screen" question...
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE log4j:configuration PUBLIC "-//LOGGER" "http://logging.apache.org/log4j/1.2/apidocs/org/apache/log4j/xml/doc-files/log4j.dtd">
<log4j:configuration>
    <!-- 
         an appender is an output destination, such as the console or a file;
         names of appenders are arbitrarily chosen
    -->
    <appender name="stdout" class="org.apache.log4j.ConsoleAppender">
        <layout class="org.apache.log4j.PatternLayout">
   <param name="ConversionPattern"  value="%d %-5p %c (%F:%L) %m%n"/>  

        </layout>
    </appender>
     <appender name="stderr" class="org.apache.log4j.ConsoleAppender">
        <param name="target" value="System.err"/>
        <layout class="org.apache.log4j.PatternLayout">
            <param name="ConversionPattern" value="%-5p %d [%t][%F:%L] : %m%n" />
        </layout>
    </appender>
 
    <!-- the root category -->
        <!-- 
            all log messages of level "debug" or higher will be logged, unless defined otherwise 
            all log messages will be logged to the appender "stdout", unless defined otherwise 
        -->
<root>
        <priority value="ALL"/>
        <appender-ref ref="stdout" />
        <appender-ref ref="stderr" />
    </root>
</log4j:configuration>

Friday, June 3, 2011

Maven XJC generation XMLSchemaType for date / dateTime missing

I've noticed a mishap with the xsd:date and xsd:dateTime conversions to Java objects. There are posts out there to avoid it or just modify the generated code but thats not what I want.

With the xsd defined as:

The 1.1 version of the com.sun.tools.xjc.maven2:maven-jaxb-plugin will not generate the XMLSchemaType "dateTime" however the 1.1.1 version does generate the correct XMLSchemaType.

By comparison if you choose to use the org.jvnet.jaxb2.maven2:maven-jaxb2-plugin it will generate the XMLSchemaType.

Here the comparison between 1.1 and 1.1.1 of the com.sun.tools.xjc.maven2:maven-jaxb-plugin.



<plugin>
                <groupId>com.sun.tools.xjc.maven2</groupId>
                <artifactId>maven-jaxb-plugin</artifactId>
                <version>1.1.1</version>
                <executions>
                    <execution>
                        <phase>generate-sources</phase>
                        <goals>
                            <goal>generate</goal>
                        </goals>
                    </execution>
                </executions>
                <configuration>
                    <removeOldOutput>true</removeOldOutput>
                    <schemaDirectory>src/main/schema/</schemaDirectory>
                    <includeSchemas>
                        <includeSchema>**/*.xsd</includeSchema>
                    </includeSchemas>
                    <strict>true</strict>
                    <verbose>false</verbose>
                    <extension>true</extension>
                    <readOnly>yes</readOnly>
                </configuration>
            </plugin>

Wednesday, November 10, 2010

SQLite Hibernate: Primary Keys and Foreign Keys on generated values

Here a little hint on defining the correct mapping for generated values and their relationships.

If the SQLiteDialect.class is used for the Hibernate dialect and the identity column string returns "integer".

When I generated the database table with
hibernate.hbm2ddl.auto=create
and then read it back with
hibernate.hbm2ddl.auto=validate
I ended up with corrupt foreign key relationships.


Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'sessionFactory' defined in class path resource [orm-layer.xml]: Invocation of init method failed; nested exception is org.hibernate.HibernateException: Wrong column type in APPLICATION for column APPLICATION_ID. Found: integer, expected: bigint
at Caused by: org.hibernate.HibernateException: Wrong column type in APPLICATION for column APPLICATION_ID. Found: integer, expected: bigint
at org.hibernate.mapping.Table.validateColumns(Table.java:284)
at org.hibernate.cfg.Configuration.validateSchema(Configuration.java:1130)
at org.hibernate.tool.hbm2ddl.SchemaValidator.validate(SchemaValidator.java:139)
at org.hibernate.impl.SessionFactoryImpl.(SessionFactoryImpl.java:359)
at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1341)
at


Here the tip of my configuration: just make sure your generated values are "integer" by using the columnDefinition and both "create" and "validate" settings for hibernate.hbm2ddl.auto.

Thursday, October 21, 2010

JAXB Serializable Binding with Maven

Generating the classes from a xsd where the classes implement the java.io.Serializable interface for serialization between nodes.

.   ---> pom.xml
./.settings
./src
./src/main
./src/main/binding
    ---> binding.xjb
./src/main/java
./src/main/java/com
./src/main/java/META-INF
./src/main/resources
    ---> my.xsd

The maven plugin configuration in the pom.xml
<plugins>
            <plugin>
                <groupid>org.jvnet.jaxb2.maven2</groupid>
                <artifactid>maven-jaxb2-plugin</artifactid>
                <version>0.7.4</version>
                <configuration>
                    <extension>true</extension>
                    <args>
                        <arg>-Xfluent-api</arg>
                    </args>
                    <schemadirectory>src/main/resources</schemadirectory>
                    <bindingdirectory>src/main/binding</bindingdirectory>
                    <plugins>
                        <plugin>
                            <groupid>net.java.dev.jaxb2-commons</groupid>
                            <artifactid>jaxb-fluent-api</artifactid>
                            <version>2.1.8</version>
                        </plugin>
                    </plugins>
                </configuration>
                <executions>
                    <execution>
                        <goals>
                            <goal>generate</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
        </plugins>

The content of the binding.xjb
<jxb:bindings 
    version="1.0" 
    xmlns:jxb="http://java.sun.com/xml/ns/jaxb"
    xmlns:xs="http://www.w3.org/2001/XMLSchema"
    xmlns:xjc="http://java.sun.com/xml/ns/jaxb/xjc"
    jxb:extensionBindingPrefixes="xjc">
    <jxb:bindings>
        <jxb:globalBindings>
            <xjc:serializable/>
        </jxb:globalBindings>
    </jxb:bindings>
</jxb:bindings>

The result:

@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "application", propOrder = {
"name",
"version",
"state",
"serverName"
})
public class Application
implements Serializable
{

@XmlElement(required = true)
protected String name;
@XmlElement(required = true)
protected String version;
@XmlElement(required = true)
protected String state;

Wednesday, October 13, 2010

Displaying MANIFEST.MF of multiple jars in directory

Oneliner for bash to dump the MANIFEST.MF information per jar.
find . -name '*.jar' -type f | while read dir; do [ -f META-INF/MANIFEST.MF ] && rm -f META-INF/MANIFEST.MF;echo $dir; md5sum $dir;jar xfv $dir META-INF/MANIFEST.MF; cat META-INF/MANIFEST.MF; done

On MacOSX the md5sum would be md5, and if you do not have the jar util... here the unzip version.. .
find . -name '*.jar' -type f | while read dir; do [ -f META-INF/MANIFEST.MF ] && rm -f META-INF/MANIFEST.MF;echo $dir; md5 $dir;unzip $dir META-INF/MANIFEST.MF; cat META-INF/MANIFEST.MF; done

Thursday, May 6, 2010

Linux Resource Troubleshooting Commands

Command that reveal the inner workings of our machine

ulimit
free
vmstat
netstat
sysstat
mpstat
iostat
ping -c 1
traceroute 
sar

What is the process consuming the most CPU
ps -eo pcpu,pid,user,args | sort -k 1 -r | head -2


What is the memory usage after 16:30 ...
   sar -s 16:30:00 -r
What is the disk paging after 16:30 ..
   sar -s 16:30:00 -B
Another day on I/O and mem usage
sar -f /var/log/sa/sa12 -u -n SOCK -B -r -s 15:30:00 -e 16:10:00

If you used previous versions of jvmstat you may be familiar with some of the older names... Here is a mapping of the old names to the new names:
JDK 5.0
jvmps is now jps, sse docs
jvmstat is now jstat
perfagent is now jstatd
jvmstat 3.0
visualgc is still visualgc

Wednesday, February 17, 2010

Major Minor code of class files

Here a oneliner for finding out the bytecode version. Based on
http://en.wikipedia.org/wiki/Class_(file_format)

perl -pe 'open(FILE,$_);binmode(FILE);sysread(FILE,$buf,2,6);close(FILE);@c=unpack("H*",$buf);foreach(@c){$s.=sprintf "%s",ord($_);};$_=$s'
or
import java.io.*;

public class ClassVersionChecker {
    public static void main(String[] args) throws IOException {
        for (int i = 0; i < args.length; i++)
            checkClassVersion(args[i]);
    }

    private static void checkClassVersion(String filename)
        throws IOException
    {
        DataInputStream in = new DataInputStream
         (new FileInputStream(filename));

        int magic = in.readInt();
        if(magic != 0xcafebabe) {
          System.out.println(filename + " is not a valid class!");;
        }
        int minor = in.readUnsignedShort();
        int major = in.readUnsignedShort();
        System.out.println(filename + ": " + major + " . " + minor);
        in.close();
    }
}

Monday, November 30, 2009

Proxy Java System properties

Networking Properties
Documentation Contents
Java Properties

java.net.preferIPv4Stack (default: false)
If IPv6 is available on the operating system the underlying native socket will be an IPv6 socket. This allows Java(tm) applications to connect too, and accept connections from, both IPv4 and IPv6 hosts.

If an application has a preference to only use IPv4 sockets then this property can be set to true. The implication is that the application will not be able to communicate with IPv6 hosts.

java.net.preferIPv6Addresses (default: false)
If IPv6 is available on the operating system the default preference is to prefer an IPv4-mapped address over an IPv6 address. This is for backward compatibility reasons - for example applications that depend on access to an IPv4 only service or applications that depend on the %d.%d.%d.%d representation of an IP address. This property can be set to try to change the preferences to use IPv6 addresses over IPv4 addresses. This allows applications to be tested and deployed in environments where the application is expected to connect to IPv6 services.

networkaddress.cache.ttl (default: -1)
Specified in java.security to indicate the caching policy for successful name lookups from the name service.. The value is specified as as integer to indicate the number of seconds to cache the successful lookup.

A value of -1 indicates "cache forever".

networkaddress.cache.negative.ttl (default: 10)
Specified in java.security to indicate the caching policy for un-successful name lookups from the name service.. The value is specified as as integer to indicate the number of seconds to cache the failure for un-successful lookups.

A value of 0 indicates "never cache". A value of -1 indicates "cache forever".

http.proxyHost (default: )
http.proxyPort (default: 80 if http.proxyHost specified)
http.nonProxyHosts (default:

ftp.proxyHost (default: )
ftp.proxyPort (default: 80 if ftp.proxyHost specified)
ftp.nonProxyHosts (default: )
http.proxyHost and http.proxyPort indicate the proxy server and port that the http protocol handler will use.

http.nonProxyHosts indicates the hosts which should be connected too directly and not through the proxy server. The value can be a list of hosts, each seperated by a |, and in addition a wildcard character (*) can be used for matching. For example: -Dhttp.nonProxyHosts="*.foo.com|localhost".

ftp.proxyHost and ftp.proxyPort indicate the proxy server and port that the ftp protocol handler will use. ftp.nonProxyHosts is similiar to http.nonProxyHosts and indicates the hosts that should be connected too directly and not through the proxy server.

http.agent (default: Java1.4.0)


Indicates the User-Agent request header sent in http requests.

http.auth.digest.validateServer (default: false)
http.auth.digest.validateProxy (default: false)
http.auth.digest.cnonceRepeat (default: 5)
These system properties modify the behavior of the HTTP digest authentication mechanism. Digest authentication provides a limited ability for the server to authenticate itself to the client (ie. by proving that it knows the users password). However, not all servers support this capability and by default the check is switched off. The first two properties above can be set to true, to enforce this check, for either authentication with an origin, or a proxy server respectively.

It is not normally necessary to set the third property (http.auth.digest.cnonceRepeat). This determines how many times a cnonce value is reused. This can be useful when the MD5-sess algorithm is being used. Increasing the value reduces the computational overhead on both the client and the server by reducing the amount of material that has to be hashed for each HTTP request.

http.auth.ntlm.domain:

NTLM authentication is supported on Windows platforms only (due to licensing restrictions). Similar to other HTTP authentication schemes, NTLM uses the java.net.Authenticator class to acquire usernames and passwords when they are needed. However, NTLM also needs the NT domain name. There are three options for specifying the domain:

1. Do not specify it. In some environments, the domain is not actually required and the application need not specify it.
2. The domain name can be encoded within the username by prefixing the domain name followed by a back-slash '\' before the username. With this method, existing applications that use the Authenticator class do not need to be modified, so long as users are made aware that this notation must be used.
3. If a domain name is not specified as in method 2) and the system property "http.auth.ntlm.domain" is defined, then the value of this property will be used as the domain name.

http.keepAlive (default: true)
Indicates if keep alive (persistent) connections should be supported. Persistent connections improve performance by allowing the underlying socket connection be reused for multiple http requests.

The default is true and thus persistent connections will be used with http 1.1 servers. Set to 'false' to disable the use of persistent connections.

http.maxConnections (default: 5)
If HTTP keep-alive is enabled, this value is the number of idle connections that will be simultaneously kept alive, per-destination.

SOCKS protocol support settings

The SOCKS username and password are acquired in the following way. First, if the application has registered a java.net.Authenticator default instance, then this will be queried with the protocol set to the string "SOCKS5", and the prompt set to to the string "SOCKS authentication". If the authenticator does not return a username/password or if no authenticator is registered then the system checks for the user preferences "java.net.socks.username" and "java.net.socks.password". If these preferences do not exist, then the system property "user.name" is checked for a username. In this case, no password is supplied.

socksProxyHost
socksProxyPort (default: 1080)

Indicates the name of the SOCKS proxy server and the port number that will be used by the SOCKS protocol layer. If socksProxyHost is specified then all TCP sockets will use the SOCKS proxy server to establish a connection or accept one. The SOCKS proxy server can either be a SOCKS v4 or v5 server and it has to allow for unauthenticated connections.

Sun implementation-specific properties

These properties may not be supported in future releases.

sun.net.inetaddr.ttl

This is a sun private system property which corresponds to networkaddress.cache.ttl. It takes the same value and has the same meaning, but can be set as a command-line option. However, the preferred way is to use the security property mentioned above.

sun.net.inetaddr.negative.ttl

This is a sun private system property which corresponds to networkaddress.cache.negative.ttl. It takes the same value and has the same meaning, but can be set as a command-line option. However, the preferred way is to use the security property mentioned above.

sun.net.client.defaultConnectTimeout (default: -1)
sun.net.client.defaultReadTimeout (default: -1)

These properties specify the default connect and read timeout (resp.) for the protocol handler used by java.net.URLConnection.

sun.net.client.defaultConnectTimeout specifies the timeout (in milliseconds) to establish the connection to the host. For example for http connections it is the timeout when establishing the connection to the http server. For ftp connection it is the timeout when establishing the connection to ftp servers.

sun.net.client.defaultReadTimeout specifies the timeout (in milliseconds) when reading from input stream when a connection is established to a resource.

JNDI DNS service provider settings

These properties may not be supported in future releases.

sun.net.spi.nameservice.provider.=

Specifies the name service provider that you can use. By default, Java will use the system configured name lookup mechanism, such as file, nis, etc. You can specify your own by setting this option. takes the value of a positive number, it indicates the precedence order with a small number takes higher precendence over a bigger number. In J2SETM 1.4, we have provided one DNS name service provider through JNDI, which is called "dns,sun".

sun.net.spi.nameservice.nameservers=
You can specify a comma separated list of IP addresses that point to the DNS servers you want to use. If the sun.net.spi.nameservice.nameservers property is not defined, then the provider will use any name servers already configured in the platform DNS configuration.

sun.net.spi.nameservice.domain=
This property specifies the default DNS domain name, for instance, eng.sun.com. If the sun.net.spi.nameservice.domain property is not defined then the provider will use any domain or domain search list configured in the platform DNS configuration.

Copyright © 2002 Sun Microsystems, Inc. All Rights Reserved.
Sun Microsystems, Inc

commons-logging properties simplelog

The commons-logging.properties can configure build-in logging. I always loose track of the properties. Here the
link

commons-logging.properties or simplelog.properties
priority=1
org.apache.commons.logging.LogFactory=org.apache.commons.logging.impl.LogFactoryImpl
org.apache.commons.logging.Log=org.apache.commons.logging.impl.SimpleLog
org.apache.commons.logging.simplelog.defaultlog=debug


SimpleLog sends all (enabled) log messages, for all defined loggers, to System.err. The following system properties are supported to configure the behavior of this logger:

* org.apache.commons.logging.simplelog.defaultlog - Default logging detail level for all instances of SimpleLog. Must be one of:
o trace
o debug
o info
o warn
o error
o fatal
If not specified, defaults to info.
* org.apache.commons.logging.simplelog.log.xxxxx - Logging detail level for a SimpleLog instance named "xxxxx". Must be one of:
o trace
o debug
o info
o warn
o error
o fatal
If not specified, the default logging detail level is used.
* org.apache.commons.logging.simplelog.showlogname - Set to true if you want the Log instance name to be included in output messages. Defaults to false.
* org.apache.commons.logging.simplelog.showShortLogname - Set to true if you want the last component of the name to be included in output messages. Defaults to true.
* org.apache.commons.logging.simplelog.showdatetime - Set to true if you want the current date and time to be included in output messages. Default is false.
* org.apache.commons.logging.simplelog.dateTimeFormat - The date and time format to be used in the output messages. The pattern describing the date and time format is the same that is used in java.text.SimpleDateFormat. If the format is not specified or is invalid, the default format is used. The default format is yyyy/MM/dd HH:mm:ss:SSS zzz.

In addition to looking for system properties with the names specified above, this implementation also checks for a class loader resource named "simplelog.properties", and includes any matching definitions from this resource (if it exists).

Wednesday, October 7, 2009

WebLogic JRockit jrcmd diagnostics

JRockit Diagnostic Commands

Here is a list of other jrockit commands that can be used for performance tuning .


22 export JAVA_HOME=/opt/bea/java/jrockit-R27.1.0-jdk1.5.0_08/
23 export PATH=$PATH:$JAVA_HOME/bin
26 jrcmd `ps auxww | grep -v grep | grep gbrServer | awk '{ print $2 }'` print_threads

Finding Classes In Multiple Jars or Directories

Very simple find with xargs as the icing on top, in this example we are looking for the package webservices.
find . -name '*.jar' | xargs -i{} -t jar tfv {} | grep -i webservices
If you have a problem and do not have access to the jar utility an alternative could be and also ITS BLAZINGLY FASTER
$ find . -name '*.jar' | xargs -i{} -t unzip -l {} | grep -i sun.awt.X11GraphicsEnvironment