What's New Here?

javafx-logo

JavaFX Tip 2: Sharp Drawing with Canvas API

When I initially started out working with the Canvas API I noticed that the results of my rendering code were somewhat blurry and even worse, inconsistent. Some lines were blurry, others sharp. Coming from Swing it took me some time to realize that this was caused by the coordinate system of JavaFX, which allows for double precision rendering. To solve this problem all that is needed is to use coordinates “in the middle”. So in my code you now find a lot of methods called snapXZY() (similar methods can be found in the JavaFX code itself), which first casts the given coordinate to an integer and then adds .5 to it. The following screenshot shows the difference when using this approach.    The code below was used for this example: import javafx.application.Application; import javafx.geometry.Insets; import javafx.scene.Scene; import javafx.scene.canvas.Canvas; import javafx.scene.canvas.GraphicsContext; import javafx.scene.control.Label; import javafx.scene.layout.VBox; import javafx.scene.paint.Color; import javafx.stage.Stage;/** * Tip 2: How to render sharp lines in a canvas. */ public class Tip2DrawingSharpLinesInCanvas extends Application {class MyCanvas extends Canvas {public MyCanvas(boolean drawSharpLines) {setWidth(150); setHeight(150);double w = getWidth(); double h = getHeight();GraphicsContext gc = getGraphicsContext2D(); gc.clearRect(0, 0, w, h);gc.setStroke(Color.GRAY); gc.strokeRect(0, 0, w, h);for (double y = 20; y <= h - 20; y += 10) { if (drawSharpLines) { // Snap the y coordinate gc.strokeLine(10, snap(y), w - 10, snap(y)); } else { gc.strokeLine(10, y, w - 10, y); } } }private double snap(double y) { return ((int) y) + .5; } }@Override public void start(Stage stage) throws Exception { MyCanvas canvasBlurry = new MyCanvas(false); MyCanvas canvasSharp = new MyCanvas(true);Label labelBlurry = new Label("Blurry"); Label labelSharp = new Label("Sharp");VBox.setMargin(canvasBlurry, new Insets(10)); VBox.setMargin(canvasSharp, new Insets(10));VBox.setMargin(labelBlurry, new Insets(10, 10, 0, 10)); VBox.setMargin(labelSharp, new Insets(10, 10, 0, 10));VBox box = new VBox(); box.getChildren().add(labelBlurry); box.getChildren().add(canvasBlurry); box.getChildren().add(labelSharp); box.getChildren().add(canvasSharp);stage.setScene(new Scene(box)); stage.setTitle("Tip 2: Sharp Lines in Canvas"); stage.show(); }public static void main(String[] args) { launch(args); } }Reference: JavaFX Tip 2: Sharp Drawing with Canvas API from our JCG partner Dirk Lemmermann at the Pixel Perfect blog....
javafx-logo

JavaFX Tip 1: Resizable Canvas

While working on FlexGanttFX I had to deal a lot with the JavaFX Canvas node. I am using it to render activities on a timeline. Each row in the Gantt chart is a Canvas node. The user has the option to resize each row individually. So I had to figure out the best way to resize a canvas, which out-of-the-box is not resizable. The listing below shows how this can be accomplished.             The main steps needed are:Create a subclass of Canvas. Override the isResizable() method and return true. Override the prefWidth() and prefHeight() methods. Return the values of Canvas.getWidth() and Canvas.getHeight(). Add listeners to the width and height properties of Canvas in order to trigger a redraw when the size of the canvas changes. Bind the width and height properties of Canvas to the width and height properties of the parent pane.import javafx.application.Application; import javafx.scene.Scene; import javafx.scene.canvas.Canvas; import javafx.scene.canvas.GraphicsContext; import javafx.scene.layout.StackPane; import javafx.scene.paint.Color; import javafx.stage.Stage;/**  * Tip 1: A canvas resizing itself to the size of * the parent pane.  */ public class Tip1ResizableCanvas extends Application {class ResizableCanvas extends Canvas {public ResizableCanvas() { // Redraw canvas when size changes. widthProperty().addListener(evt -> draw()); heightProperty().addListener(evt -> draw()); }private void draw() { double width = getWidth(); double height = getHeight();GraphicsContext gc = getGraphicsContext2D(); gc.clearRect(0, 0, width, height);gc.setStroke(Color.RED); gc.strokeLine(0, 0, width, height); gc.strokeLine(0, height, width, 0); }@Override public boolean isResizable() { return true; }@Override public double prefWidth(double height) { return getWidth(); }@Override public double prefHeight(double width) { return getHeight(); } }@Override public void start(Stage stage) throws Exception { ResizableCanvas canvas = new ResizableCanvas();StackPane stackPane = new StackPane(); stackPane.getChildren().add(canvas);// Bind canvas size to stack pane size. canvas.widthProperty().bind( stackPane.widthProperty()); canvas.heightProperty().bind( stackPane.heightProperty());stage.setScene(new Scene(stackPane)); stage.setTitle("Tip 1: Resizable Canvas"); stage.show(); }public static void main(String[] args) { launch(args); } } When run you should see the following:  Reference: JavaFX Tip 1: Resizable Canvas from our JCG partner Dirk Lemmermann at the Pixel Perfect blog....
scala-logo

Memoization of Scala Streams

I learnt the hard way that scala internally uses memoization with Streams. This was my first attempt at a solution to Euler Problem 5                 def from(n: Int): Stream[Int] = n #:: from(n + 1)def isDivisibleByRange(n: Int, r: Range) = { r.forall(n % _ == 0) }val a = from(21) val o = a.find(isDivisibleByRange(_, Range(2, 21))) o match { case Some(i) => println(i) case None => println("Nothing found!") } I was a little mystified by why this code was throwing an OutOfMemoryError, realized thanks to Stackoverflow that since the answer to this problem is quite high 232792560, all the integers in this range will be memoized within the different nodes of the stream and hence the issue. This is actually easy to see, let me first modify the stream generator function with a side effect: def from(n: Int): Stream[Int] = {println(s"Gen $n"); n #:: from(n + 1)} val s = from(1) s.take(10).toList s.take(10).toList The second statement would not print anything. Given this memoization behavior there are a few possible fixes, the simplest is to not keep a reference to the head of the stream anywhere and to use the find method of iterator instead: from(1).iterator.find(isDivisibleByRange(_, Range(1, 21))) On a related note, Java 8 streams are not memoized and a solution using Java 8 streams (admittedly can be improved massively) is the following: @Test public void testStreamOfInts() { Stream<Integer> intStream = Stream.generate(from(1)); List<Integer> upto20 = IntStream.rangeClosed(1, 20).boxed().collect(Collectors.toList()); Predicate<Integer> p = (i -> isDivisibleOverRange(i, upto20)); Optional<Integer> o = intStream.filter(p).findFirst(); o.ifPresent(i -> System.out.println("Found: " + i)); }private Supplier<Integer> from(Integer i) { AtomicInteger counter = new AtomicInteger(0); return () -> counter.incrementAndGet(); }private boolean isDivisibleOverRange(Integer n, List<Integer> l) { return l.stream().allMatch(i -> n % i == 0); }Reference: Memoization of Scala Streams from our JCG partner Biju Kunjummen at the all and sundry blog....
java-logo

Dubious Aspects of Features of JDK 8

Most of us who develop with Java are generally enthusiastic for the features and improvements that come with JDK 8. However, there have been several recent posts that have pointed out some features that can be misused and abused and might lead to some additional issues in the future. These features, which remind me of the introduction of autoboxing in J2SE 5, have their useful situations, but can also lead to issues when not correctly understood and applied. In this post, I use references to other peoples’ posts written about these dubious features. Note that this post is not about the “normal” known issues that are associated with any release. Lambda expressions seem to be the biggest new feature of JDK 8, but Tal Weiss has written a post called The Dark Side Of Lambda Expressions in Java 8. In that post, Weiss writes about a “dark side” to lambda expressions and the Nashorn JavaScript engine (which he argues is the second biggest feature of JDK 8). He talks about the “distance between your code and the runtime” and points out that “we’re paying the price for shorter, more concise code with more complex debugging, and longer synthetic call stacks.” In Love and hate for Java 8, Andrew C. Oliver and Michael Brush provide a nice introduction to some of the main new features of JDK 8. They are argue that default methods on interfaces “allow a form of multiple inheritance” and will “probably [be] the detail that will concern most people in Java 8.” He concludes the article with the assessment, “The feature that is going to be dangerous is functional interfaces. If they are not used properly, they could cause a lot of headaches.” Peter Verhas has written a detailed analysis of the potential issues with default methods on interfaces in the posts Java 8 default methods: what can and can not do? and How not to use Java 8 default methods. In one post, he states, “Adding a default method to an interface may render some class unusable.” In the other post, he adds, “The default method is a technological mistake” and references the fact that default methods were added to Java interfaces to support backward compatibility of existing implementations with methods that need to be added to interfaces to support new JDK 8 features. Lukas Eder‘s The Dark Side of Java 8 post expresses different concerns about default methods: the inability to make a default method final or synchronized and introduction of the “default” keyword. Another interesting “caveat” pointed out in this post is the effect lambda expressions have on overloading. Another Tal Weiss post, New Parallelism APIs in Java 8: Behind The Glitz and Glamour, looks at some issues Weiss observed when measuring performance of the “new Java 8 parallel operation APIs” under load. Weiss observes, “adding threads in what already is a multi-threaded environment doesn’t help you” and reminds us, “While these are very strong and easy-to-use APIs, they’re not a silver bullet. We still need to apply judgment as to when to employ them.” Lukas Krecan warns Think twice before using Java 8 parallel streams and writes, “The problem is that all parallel streams use common fork-join thread pool and if you submit a long-running task, you effectively block all threads in the pool.” To deal with this, Krecan advises either “[ensuring] that all tasks submitted to the common fork-join pool will not get stuck and will finish in a reasonable time” or “not use parallel streams and wait until Oracle allows us to specify the thread pool to be used for parallel streams.” Edwin Dalorzo‘s post Why There’s Interface Pollution in Java 8 looks at how type erasure, checked exceptions, and lack of value types (JEP 169) led to design decisions in JDK 8 that have “polluted” Java interfaces. The post mixes quotes from Brian Goetz regarding JDK 8 design decisions with the author’s own commentary to make the point that “there are good explanations for the dark side to exist.” There are, of course, issues between newly released JDK 8 and tools built on Java. For example, in the post Hello Java 8 (and how it makes GlassFish speechless…), Cay Horstmann documents GlassFish 4 not writing any stack trace whatsoever when he had “[compiled] the WAR with the wrong version of Java.” Although the referenced posts point out legitimate issues of concern related to some of JDK 8′s most anticipated features such as lambda expressions, streams, interface default methods, and the Nashorn JavaScript engine, I am still excited about the brave new world of Java development with JDK 8. The posts highlighted in this post are reminders to use these new features carefully and judiciously so that we enjoy the advantages they bring while mitigating as much as possible the new dangers and costs they present when used less wisely.Reference: Dubious Aspects of Features of JDK 8 from our JCG partner Dustin Marx at the Inspired by Actual Events blog....
java-logo

ClassNotFoundException: is it slowing down your JVM?

Most Java developers are familiar with the infamous and very common java.lang.ClassNotFoundException. While the sources of this problem are generally well understood (missing classes/libraries in classpath, class loader delegation problems etc.), the impact to the overall JVM and performance is often unknown. This situation can lead to significant impacts to your application response time and scalability. Large Java EE enterprise systems with multiple applications deployed are the most exposed to this type of problem due to the large number of different application classloaders active at runtime. This increases the risk of facing “undetected” ClassNotFoundException unless a clear business impact is identified and close log monitoring is implemented, results: on-going performance impact along with possible JVM class loading IO and Thread lock contention. The following article and sample programs will demonstrate that any occurrence of ClassNotFoundException found from your client production systems should be taken very seriously and addressed promptly. Java class loading: the missing link for optimal performanceProper understanding of this performance problem starts with proper knowledge of the Java class loading model. ClassNotFoundException essentially means a failure of the JVM to locate and/or load a particular Java class such as:The Class.forName() method The ClassLoader.findSystemClass() method The ClassLoader.loadClass() methodWhile class loading of your application Java classes should occur only once in the JVM life-cycle (or through dynamic re-deploy functions), some applications also rely on dynamic class loading operations. Regardless, repetitive valid and “failing” class loading operations can be quite intrusive, especially when the loading process is attempted by the default JDK java.lang.ClassLoader itself. Indeed, the default JDK 1.7+ behaviour, due to backward compatibility, will allow only one class to be loaded at the time, unless the class loader is tagged as “parallel capable”. Please keep in mind the even if the synchronization is done at the Class level only, a repetitive class loading failure against the same class name is still going to trigger thread lock contention depending of the Java thread concurrency level you are dealing with. The situation was much worst back with JDK 1.6 with synchronization done systematically at the class loader instance level.For this reason, Java EE containers such as JBoss WildFly 8  are using their own internal concurrent class loaders for the loading of your application classes. These class loaders implements locking at a finer level of granularity, thus allowing loading different classes from the same instance of the class loader concurrently. This is also aligned with the latest JDK 1.7+ improvement introducing the support for Multithreaded Custom Class Loaders which also help prevent certain class loader deadlock scenarios. That being said, class loading of system level classes such as java.* and Java EE container modules still fall back on the default JDK ClassLoader. This means that repetitive class loading failure for the same class name e.g. ClassNotFoundException can still trigger severe thread lock contention. This is precisely what we will replicate and demonstrate for the rest of the article. Thread lock contention – problem replicationIn order to recreate and simulate this problem, we created a simple application as per below specifications:A JAX-RS (REST) Web Service executing Class.forName() against a dummy Class name “located” from the system package level:String className =”java.lang.WrongClassName”; Class.forName(className);JRE: HotSpot JDK 1.7 @64-bit Java EE container: JBoss WildFly 8 Load testing tool: Apache JMeter Java monitoring: JVisualVM Java concurrency troubleshooting: JVM Thread Dump analysisThe simulation essentially executes concurrently with 20 threads the JAX-RS Web service. Each invocation generates a ClassNotFoundException. The logging was fully disabled in order to reduce impact on IO and focus on the class loading contention only. Now let’s look at the results from JVisualVM from our 30-60 seconds run. We can clearly see a lot of BLOCKED threads waiting to acquire a lock on an Object monitor.Analysis of the JVM thread dump is clearly exposing the problem: Thread lock contention. We can see from the execution stack trace that JBoss delegates the loading of the class to the JDK ClassLoader…why? This is because our wrong Java class name is detected to be part of the system class path e.g. java.*. In this situation, JBoss will delegate the loading to the system class loader, triggering systematic synchronization for that particular class name and waiters from the other threads waiting to acquire a lock to load the same Class name. Many threads waiting to acquire LOCK 0x00000000ab84c0c8… "default task-15" prio=6 tid=0x0000000014849800 nid=0x2050 waiting for monitor entry [0x000000001009d000] java.lang.Thread.State: BLOCKED (on object monitor) at java.lang.ClassLoader.loadClass(ClassLoader.java:403) - waiting to lock <0x00000000ab84c0c8> (a java.lang.Object) // Waiting to acquire a LOCK held by Thread “default task-20” at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:308) at java.lang.ClassLoader.loadClass(ClassLoader.java:356) // JBoss now delegates to system ClassLoader.. at org.jboss.modules.ConcurrentClassLoader.performLoadClass(ConcurrentClassLoader.java:371) at org.jboss.modules.ConcurrentClassLoader.loadClass(ConcurrentClassLoader.java:119) at java.lang.Class.forName0(Native Method) at java.lang.Class.forName(Class.java:186) at org.jboss.tools.examples.rest.MemberResourceRESTService.SystemCLFailure(MemberResourceRESTService.java:176) at org.jboss.tools.examples.rest.MemberResourceRESTService$Proxy$_$$_WeldClientProxy.SystemCLFailure(Unknown Source) at sun.reflect.GeneratedMethodAccessor15.invoke(Unknown Source) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke(Method.java:601) …………………….. Culprit thread – default task-20 "default task-20" prio=6 tid=0x000000000e3a3000 nid=0x21d8 runnable [0x0000000010e7d000] java.lang.Thread.State: RUNNABLE at java.lang.Throwable.fillInStackTrace(Native Method) at java.lang.Throwable.fillInStackTrace(Throwable.java:782) - locked <0x00000000a09585c8> (a java.lang.ClassNotFoundException) at java.lang.Throwable.<init>(Throwable.java:287) at java.lang.Exception.<init>(Exception.java:84) at java.lang.ReflectiveOperationException.<init>(ReflectiveOperationException.java:75) at java.lang.ClassNotFoundException.<init>(ClassNotFoundException.java:82) // ClassNotFoundException! at java.net.URLClassLoader$1.run(URLClassLoader.java:366) at java.net.URLClassLoader$1.run(URLClassLoader.java:355) at java.security.AccessController.doPrivileged(Native Method) at java.net.URLClassLoader.findClass(URLClassLoader.java:354) at java.lang.ClassLoader.loadClass(ClassLoader.java:423) - locked <0x00000000ab84c0e0> (a java.lang.Object) at java.lang.ClassLoader.loadClass(ClassLoader.java:410) - locked <0x00000000ab84c0c8> (a java.lang.Object) // java.lang.ClassLoader: LOCK acquired at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:308) at java.lang.ClassLoader.loadClass(ClassLoader.java:356) at org.jboss.modules.ConcurrentClassLoader.performLoadClass(ConcurrentClassLoader.java:371) at org.jboss.modules.ConcurrentClassLoader.loadClass(ConcurrentClassLoader.java:119) at java.lang.Class.forName0(Native Method) at java.lang.Class.forName(Class.java:186) at org.jboss.tools.examples.rest.MemberResourceRESTService.SystemCLFailure(MemberResourceRESTService.java:176) at org.jboss.tools.examples.rest.MemberResourceRESTService$Proxy$_$$_WeldClientProxy.SystemCLFailure(Unknown Source) ………………………………… Now let’s replace our Class name by a Java class tagged as part of the “application” package and re-run the test under the same load conditions. String className = "org.ph.WrongClassName"; Class.forName(className);As we can see, we are no longer dealing with BLOCKED threads…why is that? Let’s have a look at the JVM thread dump to better understand this change of behaviour. "default task-51" prio=6 tid=0x000000000dd33000 nid=0x200c runnable [0x000000001d76d000] java.lang.Thread.State: RUNNABLE at java.io.WinNTFileSystem.getBooleanAttributes(Native Method) // IO overhead due to JAR file search operation at java.io.File.exists(File.java:772) at org.jboss.vfs.spi.RootFileSystem.exists(RootFileSystem.java:99) at org.jboss.vfs.VirtualFile.exists(VirtualFile.java:192) at org.jboss.as.server.deployment.module.VFSResourceLoader$2.run(VFSResourceLoader.java:127) at org.jboss.as.server.deployment.module.VFSResourceLoader$2.run(VFSResourceLoader.java:124) at java.security.AccessController.doPrivileged(Native Method) at org.jboss.as.server.deployment.module.VFSResourceLoader.getClassSpec(VFSResourceLoader.java:124) at org.jboss.modules.ModuleClassLoader.loadClassLocal(ModuleClassLoader.java:252) at org.jboss.modules.ModuleClassLoader$1.loadClassLocal(ModuleClassLoader.java:76) at org.jboss.modules.Module.loadModuleClass(Module.java:526) at org.jboss.modules.ModuleClassLoader.findClass(ModuleClassLoader.java:189) // JBoss now fully responsible to load the class at org.jboss.modules.ConcurrentClassLoader.performLoadClassUnchecked(ConcurrentClassLoader.java:444) // Unchecked since using JDK 1.7 e.g. tagged as “safe” JDK at org.jboss.modules.ConcurrentClassLoader.performLoadClassChecked(ConcurrentClassLoader.java:432) at org.jboss.modules.ConcurrentClassLoader.performLoadClass(ConcurrentClassLoader.java:374) at org.jboss.modules.ConcurrentClassLoader.loadClass(ConcurrentClassLoader.java:119) at java.lang.Class.forName0(Native Method) at java.lang.Class.forName(Class.java:186) at org.jboss.tools.examples.rest.MemberResourceRESTService.AppCLFailure(MemberResourceRESTService.java:196) at org.jboss.tools.examples.rest.MemberResourceRESTService$Proxy$_$$_WeldClientProxy.AppCLFailure(Unknown Source) at sun.reflect.GeneratedMethodAccessor60.invoke(Unknown Source) ………………. The above execution stack trace is quite revealing:Since the Java class name was not detected to be part of the Java system package, no ClassLoader delegation was performed, thus no synchronization. Since JBoss considers JDK 1.7+ as a “safe” JDK, the ConcurrentClassLoader .performLoadClassUnchecked() method was used, not triggering any Object monitor lock. No synchronization means no Thread lock contention triggered as a result of the non-stop ClassNotFoundException error.It is still important to note that while JBoss is doing a great job at preventing Thread lock contention in this scenario, the repetitive class loading attempt will still degrade the performance to a certain degree due to IO overhead associated with excessive JAR file search operations, again re-enforcing the need to take immediate corrective actions. Final words I hope that you enjoyed this article and now have a better understanding of potential performance impacts due to excessive class loading operations. While JDK 1.7 and modern Java EE containers brought great improvements on class loader related issues such as deadlocks and thread lock contention, potential problematic scenarios still remain. For this reason, I highly recommend that you closely monitor your application behaviour, logs and ensure that class loader related errors such as java.lang.ClassNotFoundException and java.lang.NoClassDefFoundError are aggressively corrected. I’m looking forward for your comments and please share your troubleshooting experience with Java class loaders.   Reference: ClassNotFoundException: is it slowing down your JVM? from our JCG partner Pierre Hugues Charbonneau at the Java EE Support Patterns blog. ...
docker-logo

A Docker Maven Plugin for Integration Testing

What is Docker? Docker is the buzzword that is taking the DevOps world. If you don’t know yet what is Docker, be warned, you will find yourself using it one way or another very soon. The rest of this post assumes some basic understanding of Docker, but if you are not familiar with it now, I’m sure you will come back later and read this. Docker is ideal for integration testing, complex demos of distributed systems or even running production systems. It is an open source software container. You can imagine it as a very lightweight and ultra fast virtual machine.   An example Inspired by the “Integration testing with Maven and Docker” article and using Docker Java API I’ve created a simple Docker Maven Plugin that can manage Docker containers. Given a Docker image, the plugin will create a container from it and start it as part of maven build process and stop and remove the container when the build process is finished. If the image is not available locally it will pull it down from the public Docker registry before creating a container from it. The following integration test in Apache Camel is ignored because it requires a running Redis instance: package org.apache.camel.component.redis;import org.apache.camel.impl.JndiRegistry; import org.junit.Ignore; import org.junit.Test; import org.springframework.data.redis.connection.jedis.JedisConnectionFactory; import org.springframework.data.redis.core.RedisTemplate;@Ignore public class RedisProducerIntegrationTest extends RedisTestSupport { private static final JedisConnectionFactory CONNECTION_FACTORY = new JedisConnectionFactory();static { CONNECTION_FACTORY.afterPropertiesSet(); }@Override protected JndiRegistry createRegistry() throws Exception { JndiRegistry registry = super.createRegistry(); redisTemplate = new RedisTemplate(); redisTemplate.setConnectionFactory(CONNECTION_FACTORY); redisTemplate.afterPropertiesSet();registry.bind("redisTemplate", redisTemplate); return registry; }@Test public void shouldSetAString() throws Exception { sendHeaders( RedisConstants.COMMAND, "SET", RedisConstants.KEY, "key1", RedisConstants.VALUE, "value");assertEquals("value", redisTemplate.opsForValue().get("key1")); }@Test public void shouldGetAString() throws Exception { redisTemplate.opsForValue().set("key2", "value"); Object result = sendHeaders(RedisConstants.KEY, "key2", RedisConstants.COMMAND, "GET");assertEquals("value", result); } } To make it pass, we can use docker-maven-plugin with a Redis image and 6379 port accessible for the test: <plugin> <groupId>com.ofbizian</groupId> <artifactId>docker-maven-plugin</artifactId> <version>1.0.0</version> <configuration> <images> <image> <name>dockerfile/redis</name> <hostConfig> <![CDATA[ { "PortBindings": { "6379/tcp": [ { "HostIp": "0.0.0.0", "HostPort": "6379" } ] } } ]]> </hostConfig> </image> </images> </configuration> <executions> <execution> <id>start-docker</id> <phase>pre-integration-test</phase> <goals> <goal>start</goal> </goals> </execution> <execution> <id>stop-docker</id> <phase>post-integration-test</phase> <goals> <goal>stop</goal> </goals> </execution> </executions> </plugin> The plugin will start a Docker container at compile phase that has a running Redis instance and shut it down at post-integration-test phase. This is a very simple example, but the plugin can support more advanced scenarios with multiple images configured differently and started/stopped at different phases. Enjoy.Reference: A Docker Maven Plugin for Integration Testing from our JCG partner Bilgin Ibryam at the OFBIZian blog....
apache-olingo-logo

Apache Olingo is now a top-level project

The Apache Software Foundation recently announced that Apache Olingo has graduated from the Apache Incubator to become a Top-Level Project, thus signifying that the project’s community and products have been well-governed under the ASF’s meritocratic process and principles. Apache Olingo is an open-source, generic Java client and server library implementation of the OData (Open Data Protocol) standard for interoperable querying and sharing of data across applications in enterprise, Cloud, and mobile environments. It provides generic Java and JavaScript libraries that implement the Open Data Protocol (OData), the standardized data access protocol used for creating and consuming data APIs in an interoperable manner across applications and devices. OData provides a uniform way to expose full-featured data APIs by building on core protocols such as HTTP as well as commonly accepted methodologies such as REST. Apache Olingo serves client and server aspects of OData 2.0, and will serve as a code base for OData 4.0, the OASIS standard of the protocol (OASIS OData TC). It is used by browser-based user interfaces to query data residing on servers. It is also used to synchronize data to mobile devices, and exchange data between server systems, and is part of the technical foundation of SAP NetWeaver Gateway technology, among other enterprise solutions. Apache Olingo supports multiple languages, including Java and JavaScript for OData clients and servers, namely OData 2.0 in Java, OData 4.0 in Java, and OData 4.0 in JavaScript. The extensions part of Olingo contain additional features, such as the support of Java Persistence API (JPA) or annotated bean classes. The project comes with full documentation, that includes examples of implementing a custom OData service, including a sample Web application built with Apache Maven that can be deployed to any Java Platform, Enterprise Edition (JEE)-compliant Web application server, such as Apache Tomcat. Olingo had entered the Apache Incubator in July 2013, seeded by code from SAP (Java server libraries for OData 2.0) and Microsoft Open Technologies (Java client libraries for OData 3.0 and JavaScript libraries for OData 3.0). Apache Olingo software is released under the Apache License v2.0, and is overseen by a self-selected team of active contributors to the project. A Project Management Committee (PMC) guides the Project’s day-to-day operations, including community development and product releases. ...
java-logo

How much faster is Java 8?

Java SE 8 was released yesterday. Traditionally, every new major JRE version comes with a free performance boost. Do we get another free lunch? And how big is the gain this time? Let’s benchmark it.             Benchmark methodologyRun the same code with 3 different JRE versions (SunJDK 1.6.0_26, OpenJDK 1.7.0_51 and OpenJDK 1.8.0). The code itself was written for Java 6 (both in syntax and JDK API’s usage) and compiled for Java 6 with OpenJDK 1.7. Each run takes about 55 minutes. VM arguments: -Xmx1536M -server Software: Linux 3.2.0-59-generic-pae Hardware: Intel® Xeon® CPU W3550 @ 3.07GHz Each run solves 13 planning problems with OptaPlanner. Each planning problem runs for 5 to minutes. Up to 2 planning problems are solved in parallel. Solving a planning problem involves no IO (except a few milliseconds during startup to load the input). A single CPU is completely saturated. It constantly creates many short lived objects, and the GC collects them afterwards. The benchmarks measure the number of scores that can be calculated per millisecond. Higher is better. Calculating a score for a proposed planning solution is non-trivial: it involves many calculations, including checking for conflicts between every entity and every other entity.To reproduce this benchmark locally, build optaplanner from source and run the main class GeneralOptaPlannerBenchmarkApp. Benchmark results Executive summaryMy observations:On the biggest dataset (Machine Reassignment B10), which dwarfs any of the other datasets in size, Java 8 is 20% faster than Java 7, which was already 17% faster than Java 6. In some cases, Java 8 is slower than Java 7. Specially for the course scheduling datasets, Java 8 is 6% slower than Java 7. Hopefully new releases of Java 8 will resolve this performance regression soon. On average, Java 8 is only 1% faster than Java 7. This while Java 7 is already 16% faster than Java 6. Despite that this is the first final release of OpenJDK 8, I did not find any regressions in Java 8. OptaPlanner’s examples are 100% reproducible, so as expected, the different JRE’s give the exact same results at every single iteration.Raw benchmark numbersJDK Cloud balancing 200c Cloud balancing 800c Machine reassignment B1 Machine reassignment B10 Course scheduling c7 Course scheduling c8 Exam scheduling s2 Exam scheduling s3 Nurse rostering m1 Nurse rostering mh1 Sport scheduling nl14SunJDK 1.6.0_26 46462 44963 94567 28655 5473 6989 6954 3785 3232 2948 1977OpenJDK 1.7.0_51 53683 49798 116553 33733 6182 7848 8243 4606 3645 3377 2445OpenJDK 1.8.0 54687 51625 135102 40529 5798 7357 8048 4441 3637 3324 23216 ⇒ 7 15.54% 10.75% 23.25% 17.72% 12.95% 12.29% 18.54% 21.69% 12.78% 14.55% 23.67%7 ⇒ 8 1.87% 3.67% 15.91% 20.15% -6.21% -6.26% -2.37% -3.58% -0.22% -1.57% -5.07%Dataset scale 120k 1920k 500k 250000k 217k 145k 1705k 1613k 18k 12k 4kConclusion On the big datasets, Java 8 is clearly faster. And this without changing a line of code. On average, the result is less convincing (with the current release), but a free lunch is always welcome.Reference: How much faster is Java 8? from our JCG partner Geoffrey De Smet at the OptaPlanner blog....
java-logo

Constructor/Method Parameters Metadata Available Via Reflection in JDK 8

One of the lesser advertised new features of JDK 8 is the optional ability to include parameter metadata in compiled Java classes [JDK Enhancement Proposal (JEP) 118]. This feature allows Java applications to access this parameter metadata information at runtime via reflection. The Java Tutorials‘ Reflection API trail includes a lesson called Obtaining Names of Method Parameters that discusses and demonstrates how to apply this new feature in Java 8. The lesson includes an example Java class MethodParameterSpy that can be run against a provided Java class to indicate characteristics of method and constructor parameters. This lesson also emphasizes that this is an optional feature because storing additional parameter metadata in .class files increases the size of those files. The lesson also points out that there may be some cases where parameter names have sensitive information that the developer does not want available in the compiled .class files. The additional parameter metadata can be included in .class files compiled in Java 8 by passing the -parameters option to the javac compiler. This -parameters option is also shown when one types javac -help as shown in the next screen snapshot.The Oracle TechNotes page on javac indicates how this additional method/constructor parameter data can be accessed at runtime: “Stores formal parameter names of constructors and methods in the generated class file so that the method java.lang.reflect.Executable.getParameters from the Reflection API can retrieve them.” The following code snippet (class called ParameterDisplayer) demonstrates this (emphasis is on the displayParametersMetadata(String[]) method). ParameterDisplayer.java package dustin.examples.jdk8;import static java.lang.System.out; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.lang.reflect.Parameter;/** * Uses JDK 8 Parameter class to demonstrate metadata related to the parameters * of the methods and constructors of the provided class (includes private, * protected, and public methods, but does not include methods inherited from * parent classes; those classes should be individually submitted). * * @author Dustin */ public class ParameterDisplayer { private static void displayParametersMetadata(final String[] classesNames) { for (final String className : classesNames) { try { final Class clazz = Class.forName(className);// Get all class's declared methods (does not get inherited methods) final Method[] declaredMethods = clazz.getDeclaredMethods(); for (final Method method : declaredMethods) { writeHeader( "Method " + method.toGenericString() + " has " + method.getParameterCount() + " Parameters:"); int parameterCount = 0; final Parameter[] parameters = method.getParameters(); for (final Parameter parameter : parameters) { out.println( "\targ" + parameterCount++ + ": " + (parameter.isNamePresent() ? parameter.getName() : "Parameter Name not provided,") + (isParameterFinal(parameter) ? " IS " : " is NOT ") + "final, type " + parameter.getType().getCanonicalName() + ", and parameterized type of " + parameter.getParameterizedType() + " and " + (parameter.isVarArgs() ? "IS " : "is NOT ") + "variable." ); } } } catch (ClassNotFoundException cnfEx) { out.println("Unable to find class " + className); } } }private static void writeHeader(final String headerText) { out.println("\n=========================================================="); out.println("= " + headerText); out.println("=========================================================="); }/** * Indicate whether provided Parameter is final. * * @param parameter Parameter to be tested for 'final' modifier. * @return {@code true} if provided Parameter is 'final'. */ private static boolean isParameterFinal(final Parameter parameter) { return Modifier.isFinal(parameter.getModifiers()); }public static void main(final String[] arguments) { if (arguments.length < 1) { out.println("You must provide the fully qualified name of at least one class."); System.exit(-1); }displayParametersMetadata(arguments); } } I had initially thought about running this class against a well-known class of the JDK, but realized that would not be too helpful because those classes are not likely to have been built with the -parameters option. Therefore, I have created a simple example class to aid with the demonstration. It is called ManyMethods and is shown next. ManyMethods.java package dustin.examples.jdk8;import java.util.List;/** * Class with numerous methods intended to be used in demonstrating JDK 8's new * Parameter class. * * @author Dustin */ public class ManyMethods { public ManyMethods() {}private void addArrayOfStrings(String[] strings) {}private void addManyStrings(final String ... strings) {}private void addListOfStrings(final List<String> strings) {}@Override public String toString() { return "ManyMethods"; } } The next two screen snapshots demonstrate running ParameterDisplayer against instances of ManyMethods compiled without and with the -parameters option. The most notable differences are that the parameter names are not provided when compiled without the -parameters option. Also, there is no trusted information on whether the parameter is final when compiled without the -parameters option. The Parameter.getModifiers() method does not include final when compiled without -parameters whether or not the parameter is actually final.The ParameterDisplayer class uses Parameter.isNamePresent() to programmatically identify that the parameter name is not present (when not compiled with the -parameters option). Had that check not been made, the parameter name returned by Parameter.getName() would have been “arg” plus the number of the parameter (arg0 for the first parameter, arg1 for the second parameter, and so on). Two of the three methods in ManyMethods class that had a parameter had the final modifier on that parameter. These cases were correctly identified by reflection using Parameter.getModifiers() only when the class was compiled with the -parameters option. Slightly Related Side Note: Sun/Oracle tools documentation has always consisted of a “windows” page and a “solaris” page, with the latter typically being used to describe how the particular tool works on all flavors on Linux and Unix. I noted that this has changed with the Java 8 documentation. This documentation still has a “windows” version, but the Unix/Linux version now has “unix” in its URL. To illustrate this, here are the URLs for Java SE 7 and Java SE 8 javac tool pages:http://docs.oracle.com/javase/8/docs/technotes/tools/windows/javac.html http://docs.oracle.com/javase/8/docs/technotes/tools/unix/javac.html http://docs.oracle.com/javase/7/docs/technotes/tools/windows/javac.html http://docs.oracle.com/javase/7/docs/technotes/tools/solaris/javac.htmlReturning to the new (with Java 8) Parameter class, it’s worth noting that there is an increase in compiled .class files that store this additional parameter metadata. For my ManyMethods class shown above, the .class file was enlarged from 909 bytes to 961 bytes. Constructor, like Method, extends Executable, and so the Constructor class enjoys the same getParameters method as Method. Java 8 provides more detail on method and constructor parameters when the code is explicitly compiled with that extra information.Reference: Constructor/Method Parameters Metadata Available Via Reflection in JDK 8 from our JCG partner Dustin Marx at the Inspired by Actual Events blog....
html5-logo

HTML5: Offline upload of images

I am currently working on an application which has needs to work offline. This has the beneficial side effect, we use the different HTML5 storage capabilities. One of the is the File API, which we are using to store images locally – before queuing them for upload to a backend server. In this article, I will share some code how we did this. The example works in Google Chrome – for DOM manipulation I will use JQuery. Starting simple, we have one file input for images and an area to show the uploaded images.   <body> <input type="file" accept="image/*" class="js-image-upload"/> <div class="js-image-container"></div> </body> When the user select a file, we want to store the image. $(document).on('change', '.js-image-upload', function (event) { var file = event.target.files[0]; var fileName = createTempName(file);writeImage(fileName, file); }); The image storage is handled by this method. function writeImage(fileName, file) { getFileSystem(function (fileSystem) { fileSystem.root.getFile(fileName, {create: true}, function (fileEntry) { fileEntry.createWriter(function (fileWriter) { fileWriter.onwriteend = writeSuccessFull; fileWriter.onerror = errorFct; fileWriter.write(file); }, errorFct); }); }); } What is happening here?Retrieve the file system Create a file by the specificied name on its root Create a writer for this file Configure a success and error callback when the asynchronous file write happend Write the blob of the file using the writerThe retrieval of the file system is a two step procedure. We need to request quota from the browser and than get the file system. var SIZE = 100 * 1024 * 1024; // 100 MB var getFileSystem = function (successFct) { navigator.webkitPersistentStorage.requestQuota(SIZE, function () { window.webkitRequestFileSystem(window.PERSISTENT, SIZE, successFct, errorFct); }, errorFct); }; The user will be asked to grant the website the access to a persistent storage. There are some errors you can get, e.g. when the user does not accept our request. But let’s assume the user trusts us. Then we want to react to the successful write and show the image. We can use a local file storage url and add the file to a queue to upload the file to the server. var showImage = function (fileName) { var src = 'filesystem:' + window.location.origin + '/persistent/' + fileName; var img = $('<img />').attr('src', src); $('.js-image-container').append(img); };var writeSuccessFull = function () { addToSyncQueue(fileName); showImage(fileName); }; I’m omitting the queue logic here. You can keep a queue of images for uploaded in the web storage or IndexedDB of your application. To read the image from storage you can use something like this var readImage = function (fileName, successFct) { getFileSystem(function (fileSystem) { fileSystem.root.getFile(fileName, {}, function (fileEntry) {fileEntry.file(successFct, errorFct);}, errorFct); } ); };So this is a brief overview of what we did here. The working example code can be found here: https://gist.github.com/jthoenes/3668856a188d600e02d6Hope it has been useful to a few people dealing with similar issues. Feel free to ask questions, when something pops up in your mind.Reference: HTML5: Offline upload of images from our JCG partner Johannes Thones at the Johannes Thönes blog blog....
Java Code Geeks and all content copyright © 2010-2014, Exelixis Media Ltd | Terms of Use
All trademarks and registered trademarks appearing on Java Code Geeks are the property of their respective owners.
Java is a trademark or registered trademark of Oracle Corporation in the United States and other countries.
Java Code Geeks is not connected to Oracle Corporation and is not sponsored by Oracle Corporation.

Sign up for our Newsletter

15,153 insiders are already enjoying weekly updates and complimentary whitepapers! Join them now to gain exclusive access to the latest news in the Java world, as well as insights about Android, Scala, Groovy and other related technologies.

As an extra bonus, by joining you will get our brand new e-books, published by Java Code Geeks and their JCG partners for your reading pleasure! Enter your info and stay on top of things,

  • Fresh trends
  • Cases and examples
  • Research and insights
  • Two complimentary e-books