Java class version

Time to time it might happen that you need to know which version the class files were compiled for. Or to be more specific what target were specified while running javac compiler. As target specifies VM version the classes were generated for. This can be specified in maven as follows:

               <plugin>
                    <artifactId>maven-compiler-plugin</artifactId>
                    <configuration>
                         <target>1.6</target>
                    </configuration>
               </plugin>

It is not a rocket science, right. To find out the version the code were generated for we use javap (java class file disassembler). The following line do the trick:

javap -verbose -classpath versiontest-1.0.jar cz.test.string.StringPlaying

Compiled from "StringPlaying.java"
public class cz.test.string.StringPlaying extends java.lang.Object
  SourceFile: "StringPlaying.java"
  minor version: 0
  major version: 50
  Constant pool:
const #1 = Method       #12.#28;        //  java/lang/Object."<init>":()V
const #2 = String       #29;            //  beekeeper
const #3 = Method       #30.#31;        //  java/lang/String.substring:(II)Ljava/lang/String;

Major version matches java version based on following table


Table taken from Oracle blog

Advertisements

Build Number

One of the most important thing during the SDLC (for sure apart from the other stuff) is to keep control over deployed artifacts to all environments at any given time. Lack of control leads to chaos and generates a lot of extra work to the team, degrades throughput, morale and motivation. No need to even mention that arguments among team members regarding deployed features or fixes definitely do not contribute well to the team spirit.
One of the common approaches mitigating this risk is generating a build number to every single build fully automatically. Let’s take a look at how to accomplish this in common project set up – maven project build on build server e.g. TeamCIty. Sample web application follows.
Common place where to store such kind of info is MANIFEST.MF file. All kind of archives have this file located in /META-INF/MANIFEST.MF. Various technologies like OSGi use this location for various metadata. Taking advantage of maven-war-plugin the content of MANIFEST.MF can be easily customized as follows (${xx} are maven variables):
Manifest-Version: 1.0
Archiver-Version: Plexus Archiver
Created-By: Apache Maven
Built-By: ${user.name}
Build-Jdk: ${java.version}
Specification-Title: ${project.name}
Specification-Version: ${project.version}
Specification-Vendor: ${project.organization.name}
Implementation-Title: ${project.name}
Implementation-Version: ${project.version}
Implementation-Vendor-Id: ${project.groupId}
Implementation-Vendor: ${project.organization.name}

To set up a maven project pom file is pretty easy:

         
            
                org.apache.maven.plugins
                maven-war-plugin
                
                    
                        
                            true
                            true
                        
                        
                            ${build.number}
                        
                    
                
            
        

Where build.number variable gets supplied by build server in arbitrary format, e.g. for TeamCity build server:

Build number is visible in build queue status page as well:
To access these project build specific information simple jsp page can be created:
The controller accessing these information using Spring MVC (simplified example) can look like:
@Controller
 public class ProjectInfoController {

     @RequestMapping("/info")
     public ModelAndView getProjectInfo(HttpServletRequest request, HttpServletResponse response) throws IOException {

         ModelAndView modelAndView = new ModelAndView("projectInfoView");

         ServletContext servletContext = request.getSession().getServletContext();

         Properties properties = new Properties();
         InputStream is = servletContext.getResourceAsStream("/META-INF/MANIFEST.MF");

         properties.load(is);

         modelAndView.addObject("buildBy",properties.getProperty("Built-By"));
         modelAndView.addObject("buildJdk",properties.getProperty("Build-Jdk"));
         modelAndView.addObject("specificationVersion",properties.getProperty("Specification-Version"));
         modelAndView.addObject("specificationTitle",properties.getProperty("Specification-Title"));
         modelAndView.addObject("implementationVendor",properties.getProperty("Implementation-Vendor-Id"));
         modelAndView.addObject("buildNumber",properties.getProperty("Build-Number"));

         return modelAndView;
     }
 }

Accessing MANIFEST.MF in JAR file has a different approach. Motivation taken from Spring source code:

Package  package = someClass.getPackage( );
String version = package.getImplementationVersion();

JSP page or other presentation layer shouldn’t be a problem for anyone.

Prague Java Developer Day 2012 Highlights

Java philosophy from very first beginning  is “compile once and run everywhere” this seems to be strengthen even more for the next version of java. The key message for java 8 is “write code once and run everywhere” which implies blurring the edge between Java SE and Java ME. The move of Java towards smartphones and tablets etc. is clear. The approach and impact to language constructs will be described briefly as was presented at the conference. As presented nothing is cut in stone at the moment but the main objective is clear.
Huge effort is being spent on a new java modularization system which would reduce an amount of consumed memory by JVM, reduce the size of final archives etc. The solution should be backward compatible with some question to current organization of JDK and potential reorganization. The solution relies on creating of new logical units composed of existing packages, classes etc. Details can  be found on project pages – Project Jigsaw.
JavaFx as a client rich platform went through a huge rewrite with version 2.0. Now supports full interoperability with Java Swing library.JavaFx scene builder released for major platforms.
Java 7 made next step towards better parallelization with fork-join framework which helps you take advantage of multiple processors. Java 8 should move the matters even further with embedding functional style programming with lambda expressions – project Lambda.
The last main feature presented for Java 8 was Type Anonotations as @Nullable, @NotNull etc. This feature is highly desirable by community as this allows better static code analysis. More info can be found here.
The afore mentioned list is neither an extensive list of features nor a final list of enhancements in java 8 but rather a plan.

K-V pairs to java bean re-map

Time to time you need on your projects to remap Key-Value pairs to regular java beans. One really nasty solution to this task is to do it manually. Yea, it works but this approach is not flexible and more over it is error prone. Mapping each field is hard coded and when adding, remove or modify them you have to correct all hard-coded mappings what is really awkward.
Another approach is to use some K-V to bean re-mapper for example ObjectMapper from JASON Jackson library or commons beanutils offer some possibilities as well.
If for some reason you cannot use these libraries e.g. legal problem or simply you don’t find implementation which suits your needs then it is time for your implementation.
Following example implementation re-map to primitives and enums from string representation. Some highlights: java 1.6 doesn’t offer any way how to find the wrapper class for primitives, wrap any problem (Exception) to base RuntimeException is not a good approach. In case of real usage it is suggested to change this. In the context of this example I think it’s fajn.

public class KVBeanRemaper {
    private static final Map wrappers = new HashMap();

    static {
        wrappers.put(byte.class, Byte.class);
        wrappers.put(short.class, Short.class);
        wrappers.put(int.class, Integer.class);
        wrappers.put(long.class, Long.class);
        wrappers.put(float.class, Float.class);
        wrappers.put(double.class, Double.class);
        wrappers.put(boolean.class, Boolean.class);
    }

    public static  T remap(Map keyValue, final Class classMapTo) {

        final Set dataToMap = new HashSet(keyValue.keySet());
        final Field[] fields;

        T res;
        try {
            res = classMapTo.newInstance();
            fields = classMapTo.getDeclaredFields();

            for (Field f : fields) {
                if (!dataToMap.contains(f.getName())) {
                    continue;
                } else {
                    final String key = f.getName();

                    if (f.getType().isEnum()) {
                        findAccessMethod(true, f, classMapTo).invoke(res,
                                Enum.valueOf((Class) f.getType(), keyValue.get(key).toString().toUpperCase()));
                        dataToMap.remove(key);
                    } else if (wrappers.containsKey(f.getType()) || f.getType() == String.class) {
                        Class c = f.getType();
                        if (c.isPrimitive()) {
                            c = wrappers.get(c);
                        }
                        findAccessMethod(true, f, classMapTo).invoke(res, c.cast(keyValue.get(key)));
                        dataToMap.remove(key);
                    }
                }
            }
        } catch (Exception ex) {
            throw new RuntimeException("Error while remapping", ex);
        }
        if (dataToMap.size() > 0) {
            throw new RuntimeException("Complete fieldset hasn't been remapped");
        }
        return res;
    }

    private static Method findAccessMethod(boolean setter, final Field field, final Class klazz) throws IntrospectionException {
        PropertyDescriptor pd = new PropertyDescriptor(field.getName(), klazz);
        if (setter) {
            return pd.getWriteMethod();
        } else {
            return pd.getReadMethod();
        }
    }
}

Spring JAX-WS timeout

When building up a reliable predictable solution you need to manage a “response time” as one of the core principles. This is accomplished by implementing timeout policy. You don’t wanna clients hanging on connection forever. Nowadays very common approach to integration is taking advantage of Spring framework.

Spring JAX-WS web service proxies (JaxWsPortProxyFactoryBean) doesn’t offer a direct possibility to set a service timeout via one of their properties. Following lines documents one of the possibilities how to cope with that requirement.

Java implementation:

public class AbstractJaxWsPortProxyFactoryBean extends JaxWsPortProxyFactoryBean {

    public static final int CONNECT_TIMEOUT = 2500;

    public void setTimeout(final int timeout) {
        // JAX WS
        addCustomProperty("com.sun.xml.ws.connect.timeout", CONNECT_TIMEOUT);
        addCustomProperty("com.sun.xml.ws.request.timeout", timeout);
        // Sun JAX WS
        addCustomProperty("com.sun.xml.internal.ws.connect.timeout", CONNECT_TIMEOUT);
        addCustomProperty("com.sun.xml.internal.ws.request.timeout", timeout);
    }

    @Override
    public void afterPropertiesSet() {
        super.afterPropertiesSet();
    }
}

Spring configuration:

     
        
    

    
        Client