Friday, March 9, 2018

plant UML maven problem - Cannot run program "/usr/bin/dot": error=2

Recently I had problem to generate UML diagram by maven plugin 'plantuml-maven-plugin'. There was exception:

java.io.IOException: Cannot run program "/usr/bin/dot": error=2, No such file or directory
 at java.lang.ProcessBuilder.start(ProcessBuilder.java:1048)
 at java.lang.Runtime.exec(Runtime.java:620)
 at net.sourceforge.plantuml.cucadiagram.dot.ProcessRunner$MainThread.startThreads(ProcessRunner.java:165)
 at net.sourceforge.plantuml.cucadiagram.dot.ProcessRunner$MainThread.runJob(ProcessRunner.java:125)
 at net.sourceforge.plantuml.api.TimeoutExecutor$MyThread.run(TimeoutExecutor.java:77)
Caused by: java.io.IOException: error=2, No such file or directory
 at java.lang.UNIXProcess.forkAndExec(Native Method)
 at java.lang.UNIXProcess.(UNIXProcess.java:247)
 at java.lang.ProcessImpl.start(ProcessImpl.java:134)
 at java.lang.ProcessBuilder.start(ProcessBuilder.java:1029)
 ... 4 more
java.io.IOException: Cannot run program "/usr/bin/dot": error=2, No such file or directory
 at java.lang.ProcessBuilder.start(ProcessBuilder.java:1048)
 at java.lang.Runtime.exec(Runtime.java:620)
 at net.sourceforge.plantuml.cucadiagram.dot.ProcessRunner$MainThread.startThreads(ProcessRunner.java:165)
 at net.sourceforge.plantuml.cucadiagram.dot.ProcessRunner$MainThread.runJob(ProcessRunner.java:125)
 at net.sourceforge.plantuml.api.TimeoutExecutor$MyThread.run(TimeoutExecutor.java:77)
Caused by: java.io.IOException: error=2, No such file or directory
 at java.lang.UNIXProcess.forkAndExec(Native Method)
 at java.lang.UNIXProcess.(UNIXProcess.java:247)
 at java.lang.ProcessImpl.start(ProcessImpl.java:134)
 at java.lang.ProcessBuilder.start(ProcessBuilder.java:1029)
 ... 4 more

For me was surprising that sequence diagrams works fine without graphviz. Activity UML diagrams caused this exception. Solution is simple just install graphviz. At mac run:

brew install graphviz
brew link --overwrite graphviz
And it's done.

Sunday, February 11, 2018

How to use google fonts in JavaFX

There are some resources on internet but not all of them works for me. Following method works for me. Here is my step-by-step guide. Google fonts are at https://fonts.google.com. I wasn't able to download fonts directly from this site, I didn't found link to download. luckily there is a github repository where are all fonts available to download. It's at https://github.com/google/fonts/

Download font

Get font and download it to you project at src/main/resources/font/.

Make font available in JavaFX

Now I have to tell JavaFX something like look at there is new font called 'Cardo'. It could be done by static method loadFont on javafx.scene.text.Font class.

Here is a example:

Font f = Font.loadFont(Main.class.getResource("/font/Cardo-Regular.ttf").toExternalForm(), 12);

Use font in UI

Defined font could be used from css file and directly from java code.

from css

Font can be used from css file like this:

final Scene scene = new Scene();
scene.getStylesheets().add("gui/myStyle.css");
And than set all text in application to new font:
.root {
  -fx-font-family: Cardo;
}

From java FX code

Following code write to give Graphics object text black "Hello world":

graphics.setFont(f);
graphics.setTextAlign(TextAlignment.CENTER);
graphics.setTextBaseline(VPos.CENTER);
graphics.setFill(Color.BLACK);
graphics.fillText("Hello world", 100, 50);

Thursday, June 23, 2016

JMeter - how to call external groovy script

Recently was problem to call external script from JMeter. It's really useful to have shared library between different scrips in JMeter. Recently I have to create separate maven project producing jar which should be placed to JMeter. It was quite time expensive and difficult to maintain and fragile. Call external script from BeanShell script is possible but it's not easy.

Luckily in JMeter 3.0 is functionality JSR223. Now it's easy task.

  • Create configuration element User defined variable and create property 'scriptHome'.
    ${__BeanShell(import org.apache.jmeter.services.FileServer; FileServer   .getFileServer().getBaseDir();)}${__BeanShell(File.separator,)}
    
    From now in JMeter is available variable scriptHome. Variable point to directory where is places .jmx file.
  • In directory where is placed .jmx test file create file 'helloWorld.groovy' with content:
    public class Test{
        def sayHello(){
             println "Hello world"
        }
    }
    
  • Finally create JSR223 Sampler. As script language choose Groovy. Paste following script:
    def scriptHome = vars.get("scriptHome");
    def gcl = new GroovyClassLoader()
    def clazz2 = gcl.parseClass(new File(scriptHome + "helloWorld.groovy"))
    def o = clazz2.newInstance()
    o.sayHello()
    
Now run test, on console will be output 'Hello world'.

Asynchronous thread with timeout

Recently I have problem to start asynchronous process with timeout. More precisely I want main process to start new thread with some computation task. If task execution exceed some given time period than task is killed. I know how to do that in old 1.4 Java with thread instance for task in some thread group and some watchdog thread.

After some time I wrote following code:

@Test
public void scheduler() throws Exception {
 final ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(10);

 FutureTask task = new FutureTask(() -> {
  try {
   System.out.println("task started");
   TimeUnit.SECONDS.sleep(10);
   System.out.println("task je dokoncen");
  } catch (InterruptedException e) {
   System.out.println("interrupted");
   return "task is done with interruption";
  }
  return "task is done";
 });

 scheduler.schedule(task, 100, TimeUnit.MILLISECONDS);

 scheduler.schedule(() -> {
  System.out.println("kill job is started");
  task.cancel(true);
  System.out.println("kill job is done");
  return "";
 } , 2, TimeUnit.SECONDS);

 System.out.println("I'm going to wait for ending both tasks");

 TimeUnit.SECONDS.sleep(20);
}

Friday, June 17, 2016

How to download latest snapshot from maven repository

Previously I had problem to download latest snapshot build from maven repository. It's not about copying file from maven repository home ~/.m2/repository/. It's just part of process. First it's necessary to download latest build from maven repository. Easiest way is to push maven to do it. For example let's have package com.example:billing:1.0.0-SNAPSHOT:war. Command will look like:

mvn org.apache.maven.plugins:maven-dependency-plugin:2.8:get --batch-mode -Dmdep.useBaseVersion=true -Dartifact=com.example:billing:1.0.0-SNAPSHOT:war -DremoteRepositories=example-snapshots::default::http://companynexus.com/nexus/content/repositories/snapshots/

Detail description can by found at http://maven.apache.org/plugins/maven-dependency-plugin/get-mojo.html.

Copy snapshot artifact from local repository can by done like this:

mvn org.apache.maven.plugins:maven-dependency-plugin:2.8:copy -Dmdep.useBaseVersion=true -DoutputDirectory=/opt/billing/ -Dartifact=com.example:billing:1.0.0-SNAPSHOT:war
Description can be found at http://maven.apache.org/plugins/maven-dependency-plugin/copy-mojo.html.

Saturday, December 5, 2015

JMH - ERROR: Unable to find the resource: /META-INF/BenchmarkList

I tried to use micro benchmarking tool called JMH. It look really nice. I used it for speed verification of my B+Tree implementation. It's at https://github.com/jajir/jblinktree. I'm using eclipse for building project and after some time I met following exception:

Exception in thread "main" java.lang.RuntimeException: ERROR: Unable to find the resource: /META-INF/BenchmarkList
	at org.openjdk.jmh.runner.AbstractResourceReader.getReaders(AbstractResourceReader.java:96)
	at org.openjdk.jmh.runner.BenchmarkList.find(BenchmarkList.java:104)
	at org.openjdk.jmh.runner.Runner.internalRun(Runner.java:228)
	at org.openjdk.jmh.runner.Runner.run(Runner.java:178)
	at com.coroptis.jblinktree.performance.MapTestRunner.main(MapTestRunner.java:75)

Problem is that class BenchmarkList didn't find file '/META-INF/BenchmarkList'. This file contains list of precompiled benchmark tests. This file was missing because I compile project form eclipse and not from maven. Solution is compile project from command link:

mvn clean install

And from now it's work fine. If you have problem to configure JMH in maven look at https://github.com/jajir/jblinktree/blob/master/benchmark/pom.xml.

Sunday, August 9, 2015

How to install jpf-concurrent module

JPF is tool for static code analysis. I tried to use it for proving that code is thread safe. In multiple thread environment is problem with JVM 'state explosion'. When JPF try to examine all possible JVM states in multiple thread environment number of possible states grow exorbitantly. As documentation say this problem could be solved with module jpf-concurrent.

Because I didn't find guide how to install it here is simple guide.

Prerequisites

Installation steps

  • Go to directory where is jpf-core installed. In my case it's directory '/Users/jan/projects/jpf/'
  • Checkout project
    hg clone http://babelfish.arc.nasa.gov/hg/jpf/jpf-concurrent
  • Build jpf-concurrent project
    ant
  • Edit your site property file. In my case is at '/Users/jan/.jpf/site.properties'. Add there following section:
    # concurrent extension
    jpf-concurrent = ${jpf.home}/jpf-concurrent
    extensions+=,${jpf-concurrent}
    
Ant it's done. Good luck.

[EDIT] - After some time of using jpf-concurrent project I had following problem:

gov.nasa.jpf.jvm.NoUncaughtExceptionsProperty
java.lang.IllegalMonitorStateException
at java.util.concurrent.locks.ReentrantLock.unlock(gov.nasa.jpf.concurrent.peers.JPF_java_util_concurrent_locks_ReentrantLock)
at com.coroptis.jblinktree.NodeLocks.unlockNode(NodeLocks.java:96)
at com.coroptis.jblinktree.NodeStoreImpl.unlockNode(NodeStoreImpl.java:59)

I contacted Nastaran Shafiei via google group, he is creator of jpf-concurrent. He told me, that jpf-concurrent module is outdated and no longer supported. So I removed jpf-concurrent module and path finder start work fine.

So, do NOT install jpf-concurrent module.

Friday, October 31, 2014

java.lang.AbstractMethodError: org.uispec4j.interception.toolkit.UISpecToolkit.getKeyboardFocusManagerPeer()Ljava/awt/peer/KeyboardFocusManagerPeer;

For one old project written in old Java swing I tried to find tool for JUnit testing. Naively I thought that there is lot of mature swing JUnit testing frameworks. Surprisingly there is no much of them. I start with uispec4j.

java.lang.AbstractMethodError: org.uispec4j.interception.toolkit.UISpecToolkit.getKeyboardFocusManagerPeer()Ljava/awt/peer/KeyboardFocusManagerPeer;
 at java.awt.KeyboardFocusManager.initPeer(Unknown Source)
 at java.awt.KeyboardFocusManager.(Unknown Source)
 at java.awt.DefaultKeyboardFocusManager.(Unknown Source)
 at java.awt.KeyboardFocusManager.getCurrentKeyboardFocusManager(Unknown Source)
 at java.awt.KeyboardFocusManager.getCurrentKeyboardFocusManager(Unknown Source)
 at javax.swing.UIManager.initialize(Unknown Source)
 at javax.swing.UIManager.maybeInitialize(Unknown Source)
 at javax.swing.UIManager.getDefaults(Unknown Source)
 at javax.swing.UIManager.put(Unknown Source)
 at org.uispec4j.interception.ui.UISpecLF.init(UISpecLF.java:11)
 at org.uispec4j.UISpec4J.init(UISpec4J.java:32)
 at org.uispec4j.UISpecTestCase.(UISpecTestCase.java:31)

Root of problem

Problem is in class org.uispec4j.interception.toolkit.UISpecToolkit which was created before java 1.7. Class UISpecToolkit implements abstract class org.uispec4j.interception.toolkit.ToolkitDelegate. ToolkitDelegate extends another abstract class SunToolkit. Class SunToolkit is root of problems. In Java 1.7 there is a new abstract method sun.awt.SunToolkit.getKeyboardFocusManagerPeer() returning KeyboardFocusManagerPeer which is not implemented in uispec4j implementing class UISpecToolkit.

Solution

First of all there is no simple solution. It's quite easy to create own version of UISpecToolkit. But it's not easy to persuade uispec4j library to user your own version of UISpecToolkit. It's because UISpecToolkit in class UISpec4J in a following way:

  private static void initToolkit() {
    try {
      Field toolkitField = Toolkit.class.getDeclaredField("toolkit");
      toolkitField.setAccessible(true);
      toolkitField.set(null, new UISpecToolkit());
    }
    catch (Exception e) {
      throw new RuntimeException("Unable to initialize toolkit for interception.", e);
    }
  }

So without new library release or some non trivial effort there is not possible to use uispec4j library at java 1.7.

Sunday, October 19, 2014

Access restriction: The constructor GraphicsConfigTemplate3D() is not accessible due to restriction on required library /System/Library/Java/Extensions/j3dcore.jar

This problem is reported by Eclipse. It's reason why project can't by compiled.

Problem is that default JRE include older 1.5 Java3D implementation which doesn't expose used GraphicsConfigTemplate3D() constructor. Solution is remove from eclipse build old 1.5 Java3D libraries and and new 1.6 to class paths.

How to configure it in eclipse is described it post Mac OS X 10.9 Mavericks how to install Java 3d.

Thursday, July 24, 2014

SingularMatrixException: cannot invert matrix - solved

I have following problem in my Java3D application:

javax.vecmath.SingularMatrixException: cannot invert matrix
 at javax.media.j3d.Transform3D.invertGeneral(Transform3D.java:3099)
 at javax.media.j3d.Transform3D.invert(Transform3D.java:2864)

Occurring of this problem is deterministic and it happen always in same scene processing. Source code of java class Transform3D.java is here. Piece of code where is problem rooted is:

  final void invertGeneral(Transform3D t1) {
 double tmp[] = new double[16];
 int row_perm[] = new int[4];
 int i, r, c;

 // Use LU decomposition and backsubstitution code specifically
 // for floating-point 4x4 matrices.

 // Copy source matrix to tmp
 System.arraycopy(t1.mat, 0, tmp, 0, tmp.length);

 // Calculate LU decomposition: Is the matrix singular?
 if (!luDecomposition(tmp, row_perm)) {
     // Matrix has no inverse
     throw new SingularMatrixException(J3dI18N.getString("Transform3D1"));
 }

 // Perform back substitution on the identity matrix
 // luDecomposition will set rot[] & scales[] for use
 // in luBacksubstituation
 mat[0] = 1.0;  mat[1] = 0.0;  mat[2] = 0.0;  mat[3] = 0.0;
 mat[4] = 0.0;  mat[5] = 1.0;  mat[6] = 0.0;  mat[7] = 0.0;
 mat[8] = 0.0;  mat[9] = 0.0;  mat[10] = 1.0; mat[11] = 0.0;
 mat[12] = 0.0; mat[13] = 0.0; mat[14] = 0.0; mat[15] = 1.0;
 luBacksubstitution(tmp, row_perm, this.mat);

 type = 0;
 dirtyBits = ALL_DIRTY;
}

Obviously piece of resource bundle defining error messages looks like:

Transform3D1=cannot invert matrix

The root of the problem is using of class Transform3D. In my code is this class used like this:

Point3d center = new Point3d();
boundingSphere.getCenter(center);

Transform3D lookAt = new Transform3D();
lookAt.lookAt(new Point3d(0.0, 0.0, -40.0), center, new Vector3d(0.0, 1.0, 0.0));
lookAt.invert();

Than it's easy. Method lookAt have following parameters:

  • eye - the location of the eye (Point3d)
  • center - a point in the virtual world where the eye is looking (Point3d)
  • up - an up vector specifying the frustum's up direction (Vector3d)
When one of eye, scene and center vectors is linear combination of others than matrix is singular.Detect that transformation is singular matrix could be done for example by determinant. So code could be easily fixed. Nice think is that it works fine in Java3D 1.5 release by Sun. This doesn't work in Java3D 1.6 which could be found at github.com/hharrison/java3d-core/.

In my case is solution pretty simple. When center and eye are same points slightly adjust one of them like this:

Point3d center = new Point3d(0.0, 0.0, -40.0);
Point3d eye = new Point3d(0.0, 0.0, -40.0);
Vector3d up = new Vector3d(0.0, 1.0, 0.0);
Transform3D lookAt = new Transform3D();
lookAt.lookAt(eye, center, up);
if (Double.compare(Double.NaN, lookAt.determinant()) == 0) {
    eye = new Point3d(eye.x + 0.001F, eye.y + 0.001F, eye.z + 0.001F);
    lookAt.lookAt(eye, center, up);
}
lookAt.invert();

And than it works fine. One think is strange. Determinant of singular matrix should be zero not specific value "Not a Number". Probably it's because of determinant computing implementation.

Java 3D - differences in rendering on different platform

I have tool for generating images of LEGO models. I works easy user upload LEGO model source file and tool generate with JAVA 3d model and store image or images.

After some time of using this tool I met strange problem when it's deployed on my Mac and on productions system - Debian generated images looks slightly different. When I put these images in one window I was surprised how much images are different. Look at the following picture.

I'll investigate this problem more closely and I'll update this article.

Monday, June 16, 2014

Java 3D problem - No X11 DISPLAY variable was set

I have following exception during Java3D application startup:

No X11 DISPLAY variable was set, but this program performed an operation which requires it.
java.awt.HeadlessException:
No X11 DISPLAY variable was set, but this program performed an operation which requires it.
       at sun.java2d.HeadlessGraphicsEnvironment.getDefaultScreenDevice(HeadlessGraphicsEnvironment.java:77)

Problem is quite easy understand and resolve. Java 3D drive don't know address of X11 windows server. X11 server address should be stored in environment variable "DISPLAY". Environment could be set up like this:

export DISPLAY=:0.0

This will work just in case that your X11 server is at localhost. How to find X11 server address is nicely described at http://stackoverflow.com/questions/784404/how-can-i-specify-a-display

Monday, June 9, 2014

Java 3D exception: TransformGroupRetained : Can't find hashKey

Following exception appears in my Java 3D application:

TransformGroupRetained : Can't find hashKey
Exception in thread "J3D-TransformStructureUpdateThread-1" java.lang.ArrayIndexOutOfBoundsException: -1
 at javax.media.j3d.TransformGroupRetained.updateChildLocalToVworld(TransformGroupRetained.java:979)
 at javax.media.j3d.TransformGroupRetained.updateChildLocalToVworld(TransformGroupRetained.java:961)
 at javax.media.j3d.TransformGroupRetained.processChildLocalToVworld(TransformGroupRetained.java:825)
 at javax.media.j3d.TransformStructure.processCurrentLocalToVworld(TransformStructure.java:306)
 at javax.media.j3d.TransformStructure.processMessages(TransformStructure.java:186)
 at javax.media.j3d.StructureUpdateThread.doWork(StructureUpdateThread.java:83)
 at javax.media.j3d.J3dThread.run(J3dThread.java:250)

In my case I incorrectly used one of available ways to hide and show part of 3D objects graph. I use javax.media.j3d.Link and when I wand to show specific subgraph I call:

link.setSharedGroup(mySharedGroup);

and similary I called when I want to hide some object I called:

link.setSharedGroup(null);

I works fine up to the moment when setSharedGroup was called with same object parameter more than once. It leads to "TransformGroupRetained : Can't find hashKey" Exception. Fix is quite simple:

if(link.getSharedGroup() == null){
    link.setSharedGroup(mySharedGroup);
}

and

if(link.getSharedGroup() != null){
    link.setSharedGroup(null);
}

This should help. Hopefully it will save you some time.

regards

Monday, June 2, 2014

Java 3D problem - java.lang.UnsatisfiedLinkError: Can't load library: /System/Library/Frameworks/gluegen-rt.Framework/gluegen-rt

Correctly set Java 3D in eclipse project could be tricky. I'll try to write down problems that I have met.

Compilation problem

Double check that there are latest (1.6.*) version of Java 3D at class path.

Caused by: java.lang.UnsatisfiedLinkError: Can't load library:

Following exception:
Caused by: java.lang.UnsatisfiedLinkError: Can't load library: /System/Library/Frameworks/gluegen-rt.Framework/gluegen-rt
Means that is class path is not 'gluegen-rt'. Check it in eclipse project setting.

Wednesday, May 28, 2014

Mac OS X 10.9 Mavericks how to install Java 3d

At the beginning I would like to point out that it's tricky. This guide helps you to run Java 3D from Eclipse environment.

Remove old Java 3D

At Maverick you can have ORACLE java 1.7 or Apple Java or both. Both of them comes with previous version of Java 3D, but this version is old not not so much useful. First of all this Java 3D versions should be removed from eclipse JRE. It could be done from following dialog "Eclipse" > "Preferences" > "Java" > "Installed JREs".

Find there JRE that will be used click on "Edit" and remove:
  • j3dutils.jar
  • j3dcore.jar
  • vecmath.jar

Get new Java 3D

From http://jogamp.org/deployment/java3d/1.6.0-pre10/ Download new versions of j3dutils.jar, j3dcore.jar and vecmath.jar and store them on disk. Old Java 3D version up 1.5.* which could be get from ORACLE is not compatible with 1.6.*. There is no backward compatibility in Java 1.6.*. Also ORACLE doesn't support Java 3D development.

Install new Java 3D

So open "Project" > "Properties" > "Java build path" and there select "Libraries" tab. Select "Add external jars" and add downloaded Java 3D libraries.

When you are done with it project should compile but not run.

Get latest JOGL

Java 3d is just API. Now you'll need layer between Java 3D API and mac OpenGL libraries. This layer is JOGL. From http://jogamp.org/deployment/jogamp-current/archive/ download file "jogamp-all-platforms.7z". And expand this package somewhere at your disk. For example muCommander could do it for you (for free).

Install latest JOGL

Now go again to project "Java build path" and in "Libraries" tab add external libraries from expanded JOGL package. Namely add:

  • gluegen-rt.jar
  • jogl-all.jar
Native libraries are not necessary until you are not making final distribution package.

Now your Java 3D project should compile and even run. So good luck.

Sunday, April 6, 2014

TOP explained

Very often when I look at linux command top I found difficult to fully understand the result. So following should remind me whats going on there.

top - 20:04:34 up 157 days, 17:22,  1 user,  load average: 2.52, 2.11, 1.23
Tasks: 102 total,   1 running, 101 sleeping,   0 stopped,   0 zombie
Cpu(s): 71.4%us,  0.2%sy,  0.0%ni, 28.3%id,  0.2%wa,  0.0%hi,  0.0%si,  0.0%st
Mem:   1018236k total,  1002152k used,    16084k free,    13600k buffers
Swap:  2064344k total,  1022604k used,  1041740k free,   183736k cached

  PID USER      PR  NI  VIRT  RES  SHR S %CPU %MEM    TIME+  COMMAND                                                                                                                           
11025 honza     18   0  908m 596m 7292 S 285.9 60.0   2129:53 java                                                                                                                              
    1 root      15   0  2160  228  204 S  0.0  0.0   0:22.88 init                                                                                                                               
    2 root      RT  -5     0    0    0 S  0.0  0.0   0:03.42 migration/0                                                                                                                        
    3 root      34  19     0    0    0 S  0.0  0.0   0:00.03 ksoftirqd/0                                                                                                                        
    4 root      RT  -5     0    0    0 S  0.0  0.0   0:00.00 watchdog/0         

I'll describe just part that made me a problem.

Cpu(s) abbreviations

  • us: user cpu time (or) % CPU time spent in user space
  • sy: system cpu time (or) % CPU time spent in kernel space
  • ni: user nice cpu time (or) % CPU time spent on low priority processes
  • id: idle cpu time (or) % CPU time spent idle
  • wa: io wait cpu time (or) % CPU time spent in wait (on disk)
  • hi: hardware irq (or) % CPU time spent servicing/handling hardware interrupts
  • si: software irq (or) % CPU time spent servicing/handling software interrupts
  • st: steal time - - % CPU time in involuntary wait by virtual cpu while hypervisor

Column names

Column names abbreviations:
  • PID -- Process Id The task's unique process ID, which periodically wraps, though never restarting at zero.
  • PR -- Priority The priority of the task.
  • NI -- Nice value The nice value of the task. A negative nice value means higher priority, whereas a positive nice value means lower priority. Zero in this field simply means priority will not be adjusted in determining a task's dispatchability.
  • P -- Last used CPU (SMP) A number representing the last used processor. In a true SMP environment this will likely change frequently since the kernel intentionally uses weak affinity. Also, the very act of running top may break this weak affinity and cause more processes to change CPUs more often (because of the extra demand for cpu time).
  • %CPU -- CPU usage The task's share of the elapsed CPU time since the last screen update, expressed as a percentage of total CPU time. In a true SMP environment, if 'Irix mode' is Off, top will operate in 'Solaris mode' where a task's cpu usage will be divided by the total number of CPUs. You toggle 'Irix/Solaris' modes with the 'I' inter- active command.
  • TIME -- CPU Time Total CPU time the task has used since it started. When 'Cumulative mode' is On, each process is listed with the cpu time that it and its dead children has used. You toggle 'Cumulative mode' with 'S', which is a command-line option and an interactive command. See the 'S' interactive command for additional information regarding this mode.
  • TIME+ -- CPU Time, hundredths The same as 'TIME', but reflecting more granularity through hundredths of a second.
  • %MEM -- Memory usage (RES) A task's currently used share of available physical memory.
  • VIRT -- Virtual Image (kb) The total amount of virtual memory used by the task. It includes all code, data and shared libraries plus pages that have been swapped out. (Note: you can define the STATSIZE=1 environment variable and the VIRT will be calculated from the /proc/#/state VmSize field.) VIRT = SWAP + RES.
  • SWAP -- Swapped size (kb) The swapped out portion of a task's total virtual memory image.
  • RES -- Resident size (kb) The non-swapped physical memory a task has used. RES = CODE + DATA.
  • CODE -- Code size (kb) The amount of physical memory devoted to executable code, also known as the 'text resident set' size or TRS.
  • DATA -- Data+Stack size (kb) The amount of physical memory devoted to other than executable code, also known as the 'data resident set' size or DRS.
  • SHR -- Shared Mem size (kb) The amount of shared memory used by a task. It simply reflects memory that could be potentially shared with other processes.
  • nFLT -- Page Fault count The number of major page faults that have occurred for a task. A page fault occurs when a process attempts to read from or write to a virtual page that is not currently present in its address space. A major page fault is when disk access is involved in making that page available.
  • nDRT -- Dirty Pages count The number of pages that have been modified since they were last written to disk. Dirty pages must be written to disk before the corresponding physical memory location can be used for some other virtual page.
  • S -- Process Status The status of the task which can be one of:
    • 'D' = uninterruptible sleep
    • 'R' = running
    • 'S' = sleeping
    • 'T' = traced or stopped
    • 'Z' = zombie

Monday, March 24, 2014

DBunit table record counting

During unit testing is useful to verify that requested operation was really performed in db. Lets have a simple test for deleting method. This method just delete user record in database. Test could look like:

public void testDelete() throws Exception{
 userDao.delete(5);
 restartSession();
 
 assertEquals(getConnection().createDataSet().getTable("user").getRowCount(),
  getDataSet().getTable("user").getRowCount() - 1);
}

This test look clear. however there is possible problem. Running this code could ends with exception:

org.dbunit.database.AmbiguousTableNameException: user
 at org.dbunit.dataset.AbstractDataSet.getTable(AbstractDataSet.java:101)
 at org.dbunit.dataset.ReplacementDataSet.getTable(ReplacementDataSet.java:182)
 ...

When you look at exception source problem is clear. The problem are testing data. When you have testing data in XML file in following shape:

 <user id_user="3" login_name="john" user_name="John" password="e"
  public_profile="1" app_right="1" />

 <color id_color="1" />
 <color id_color="2" />

 <user id_user="5" login_name="clara" user_name="Clara" password="e"
  public_profile="1" app_right="1" />

Thank DBunit took it as two table user definition. Each definition have it's own list of rows with data. So solution is obvious, just re-order data definition XML file.
 <user id_user="3" login_name="john" user_name="John" password="e"
  public_profile="1" app_right="1" />
 <user id_user="5" login_name="clara" user_name="Clara" password="e"
  public_profile="1" app_right="1" />

 <color id_color="1" />
 <color id_color="2" />

Thursday, March 13, 2014

Java3D and headless mode

Java3D headless mode is a way how to tell Java that there is not physical screen device and that there is no graphics acceleration. Headless model could be set in this way:

java -Djava.awt.headless=true 

In headless mode some object can't be instantiated, especially UI related objects from java.awt package like Button. More about headless could be found at http://www.oracle.com/technetwork/articles/javase/headless-136834.html.

Java3D application usually build 3D model and that draw it to Canvas3D. Sometimes server need to generate some images which are using Canvas3D. Sadly in headless mode it's not possible. Because it's not possible to instantiate Canvas3D. Lets look at following code:

public void testSimple() throws Exception {
 System.setProperty("java.awt.headless", "true");
 GraphicsConfigTemplate3D template = new GraphicsConfigTemplate3D();
 GraphicsConfiguration config = GraphicsEnvironment.getLocalGraphicsEnvironment().getDefaultScreenDevice().getBestConfiguration(template);
 Canvas3D canvas3d = new Canvas3D(config, true);
}

In headless mode GraphicsEnvironment.getLocalGraphicsEnvironment() return instance of HeadlessGraphicsEnvironment. Method HeadlessGraphicsEnvironment is implemented in following way:

   public GraphicsDevice getDefaultScreenDevice()
         throws HeadlessException {
         throw new HeadlessException();
    }

So it always throw HeadlessException. Because of that it seems that Java3D can't be used with enabled headless mode.

Wednesday, March 12, 2014

Raspberry PI - create installed SD card

Here will be described some basic steps with raspberry PI. Following text is just notes that helps me later reproduce all steps.

Install Raspbian image to SD card

It's important find exact name device name of SD card. Try to remove and insert SD card and look at changes in /dev/ directory. Also look at "System Information" application. Final command for copy image to SD card is following:
sudo dd bs=1m if=/Users/jan/Downloads/2014-01-07-wheezy-raspbian.img of=/dev/rdisk2

How to perform install in details is described at elinux.org/RPi_Easy_SD_Card_Setup.

Backup SD card to image file

It's similar to previous example

sudo dd bs=1m if=/dev/rdisk2 of=/Users/jan/Downloads/backup-2014-3-19.img

Before copying backup to another SD card, it's necessary remove all partitions that will be overwritten. For examples I would like to put image at /dev/rdisk2 so I have to execute:

diskutil unmountDisk /dev/rdisk2s1
diskutil unmountDisk /dev/rdisk2s2

Replace SD card with backup:

sudo dd bs=1m if=/Users/jan/Downloads/backup-2014-3-19.img of=/dev/rdisk2
More details about dd command could be found at en.wikipedia.org/wiki/Dd_(Unix)

sudo apt-get update sudo apt-get upgrade sudo raspi-config http://www.raspberrypi.org/camera

Friday, February 21, 2014

release:prepare - You don't have a SNAPSHOT project in the reactor projects list.

Sometimes during executing mvn release:prepare following error ocures:
[INFO] ------------------------------------------------------------------------
[INFO] BUILD FAILURE
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 3.995s
[INFO] Finished at: Fri Feb 21 11:19:01 CET 2014
[INFO] Final Memory: 11M/241M
[INFO] ------------------------------------------------------------------------
[ERROR] Failed to execute goal org.apache.maven.plugins:maven-release-plugin:2.3.2:prepare (default-cli) on project cubiculus-ldraw: You don't have a SNAPSHOT project in the reactor projects list. -> [Help 1]
org.apache.maven.lifecycle.LifecycleExecutionException: Failed to execute goal org.apache.maven.plugins:maven-release-plugin:2.3.2:prepare (default-cli) on project [project-name]: You don't have a SNAPSHOT project in the reactor projects list.

In other words it say that your pom.xml file is not in SNAPSHOT version (for example 1.4-SNAPSHOT) but contains release version (for example 1.4.3). One to the reasons of this problem could be that previous attempt to release project failed and during it's work changed project version to release version. Check your repository that there is correct SNAPSHOT versions and synchronise repo. In case of SVN "svn revert -R ."