Montag, 4. Januar 2016

Jackson @JsonIdentityInfo, ObjectIdGenerators, bidirectional references

Recently we had a big issue with sending JSON in our Java Web App with Jackson. We had a pretty complex entity model and bidirectional references and used therefore @JsonIdentityInfo. @JsonManagedReference and @JsonBackReference didn't work because it was bidirectional.
At first we had the problem with duplicate properties:

{
    "links": [{
            "id": 2,
            "section1": {
                ...
            },
            "section2": {
                ...
            },
            "listLinkLabel": [{
                    "linkLabel": 1,
                    "linkLabel": "after"
                }]
        }, {
            "id": 5,
            "section1": {
                ...
            },
            "section2": {
                ...
            },
            "listLinkLabel": [{
                    "linkLabel": 2,
                    "linkLabel": "before"
                }, {
                    "linkLabel": 3,
                    "linkLabel": "overlap"
                }, 1]
        }, {
            "id": 3,
            "section1": {
                ...
            },
            "section2": {
                ...
            },
            "listLinkLabel": [3]
        }
}

As you can see linkLabel appears twice. This was because we used an IntSequenceGenerator on a String attribute:

@Entity
@JsonIdentityInfo(
        generator = ObjectIdGenerators.IntSequenceGenerator.class,
        property = "linkLabel")
public class LinkLabel implements Serializable {

    private static final long serialVersionUID = 1L;
    @Id
    @JsonFormat(shape = JsonFormat.Shape.STRING)
    @Column(name = "LinkLabel")
    @GeneratedValue(strategy = GenerationType.AUTO)
    private String linkLabel;

Then we had the problem that with the once encountered objects in the JSON are replaced by there ids with @JsonIdentityInfo:

{
    "objects": [{
            "id": 1,
            "otherObj": [{
                    "id": 1,
                    ...
                }, {
                    "id": 3,
                    ...
                }]
        },
            "id": 2,
            "otherObj": [1] <-- referencing otherObj with id 1
    ]
}


This is the Java Entity:


@Entity
@JsonIdentityInfo(
        generator = ObjectIdGenerators.IntSequenceGenerator.class,
        property = "linkLabel")
public class LinkLabel implements Serializable {
   //...
}

This behavior was a big problem on the JavaScript/ AngularJS client side. Fortunately we found the Jackson-Jsog plugin https://github.com/jsog/jsog-jackson. It can handle bidirectional references easily and can be used on client side as well.
So the code now looks like this:
import com.fasterxml.jackson.annotation.JsonIdentityInfo;
import com.voodoodyne.jackson.jsog.JSOGGenerator;

@Entity
@JsonIdentityInfo(generator=JSOGGenerator.class)
public class LinkLabel implements Serializable {

    private static final long serialVersionUID = 1L;
    @Id
    @Column(name = "LinkLabel")
    @GeneratedValue(strategy = GenerationType.AUTO)
    private String linkLabel;

}

Simply add it in your pom.xml and on client side in your bower.json. It works like a charm!

Unity Pokemon

I had a bit time over the Christmas period and wanted to get familiar with Unity. So I decided to clone the Pokemon game with Unity. This is the result so far:



Link to the repository: https://bitbucket.org/JeanneDark/pokemonunity

Some time ago I tried the same with the Unreal Engine 4, but compared with Unity, it was much harder to create this game with UE4. This hardens the opinion that Unity is better with 2D games than UE4.

Dienstag, 1. Dezember 2015

GlassFish glassfish-resources.xml

---There are currently problems with posting xml or html--- I had a lot of trouble to create jdbc resources and connection pools via glassfish-resources.xml, but finally it works! The method to config the GlassFish application server within your webapp is much better than via the console oder admin gui.
glassfish-resources.xml:



    
        
        
        
        
        
        
        
        
        
    
    



persistence.xml:
org.eclipse.persistence.jpa.PersistenceProvider java:app/jdbc/WebApp classes true

Place the glassfish-resources.xml in the WEB-INF (not META-INF!) folder. Only this configuration worked for me. I tried almost every combination and read through all the forums and posts. I had the following error when it didn't work:
org.glassfish.deployment.common.DeploymentException: Invalid resource : { ResourceInfo : (jndiName=java:app/jdbc/WebApp__pm), (applicationName=repro-ear) } at org.glassfish.javaee.full.deployment.EarDeployer.prepare(EarDeployer.java:166)
It worked for me with NetBeans8.1, GlassFish 4.0 and PostreSQL 9.3.

Mittwoch, 30. September 2015

Swift 2 – Introduction and Comparison

Swift is a new programming language created by Apple with a couple of interesting programming paradigms and differences to the big established languages. Like Objective-C Swift is created for iOS, OS X and watchOS development und should be a safer, faster and more powerful alternative to Objective-C.

If you want to know more about, click on this blog post, published on NovaTec's blog (the company I'm working for):
http://blog.novatec-gmbh.de/swift-2-introduction-comparison/

Dienstag, 11. August 2015

Previsit a datastructure

Recently I had to write a small and relatively simple compiler and came across a problem. For the function prologue the stack pointer should be decreased by 4 * number of local variables. Compilers work with a datastructure so called "Abstract Syntax Tree". The important part is that it was realized with the Visitor design pattern. I was looking for a simple solution to know the number of local variables in the moment I want to decrease the stack pointer. I couldn't think of non-complex code and came across this elegant and simple solution:

Here we have the normal Visitor:
public interface ASTVisitor {

    public void visit(FunctionDefinitionExpression e);
    public void visit(DeclarationStatement s);
    // ...

}
All subtypes implement the accept method for the Visitor:
public class PrimaryExpression extends Expression {

    // ...
 
    @Override
    public void accept(ASTVisitor v) {
        v.visit(this);
    }

}
Here we have the implemention and the main logic:
public class ASTVisitorImpl implements ASTVisitor {

    @Override
    public void visit(FunctionDefinitionExpression e) {

        int n = 0;

        // here we will use our custom PreVisitor
        // and override our desired method
        funcDefinition.accept(new PreVisitor() {
         
            @Override
            public void visit(DeclarationStatement decl) {

                // add here your logic e.g.
                n++;
    
            }
         });

    }
}
That's our simple PreVisitor:
public class PreVisitor implements ASTVisitor {

    @Override
    public void visit(DeclarationStatement declarationStatement) {
    }

    @Override
    public void visit(BinaryExpression binaryExpression) {
        binaryExpression.elem1.accept(this);
        binaryExpression.elem2.accept(this);
    }

    // ...

}

So the solution was simply to create another subtype of the the same ASTVisitor interface and implement there all methods and just the logic to traverse the whole datastructure (Abstract Syntax Tree). At the moment you want to have a specific information without continuing at this point, you call the PreVisitor and override the desired method - et voilà you have an elegant solution!

Montag, 10. August 2015

Apple Swift: Getting Started #1

Apple released a newer version of its new programming Language Swift. Here are a few starter links and hints, when working with the new version Swift 2:

This link is your headquarter:
https://developer.apple.com/swift/resources/
from there you get the recommendable book "The Swift Programming Language (Swift 2 Prerelease)" and many code examples. The book's writing style is casual and animates to read more.
Unfortunately the code examples are not updated (I hope they will be in future) and this was the main reason to create this blog post, to give absolute beginners help with the start up. In all code samples you can use the converter, which automatically converts the older syntax 1.2 to the newer syntax, but there are still some errors in the samples left.

Adventure: Building a SpriteKit Game Using Swift:
AdventureScene.swift before
// ...

override init(size: CGSize) {
    leafEmitterATemplate = SKEmitterNode(fileNamed: "Leaves_01")
    leafEmitterBTemplate = SKEmitterNode(fileNamed: "Leaves_02")
    projectileSparkEmitterTemplate = SKEmitterNode(fileNamed: "ProjectileSplat")
    spawnEmitterTemplate = SKEmitterNode(fileNamed: "Spawn")
        
    super.init(size: size)

    players[0] = defaultPlayer
}

// ...

func loadWorld() {
    // ...
    let templateWorld = scene.children.first!.copy() as! SKNode
    // ...
}

// ...

func configureConnectedGameControllers() {
    // ...
    assignPresetController(controller, toIndex: playerIndex)
    // ...
}

// ...

func gameControllerDidConnect(notification: NSNotification) {
    // ...
    assignPresetController(controller, toIndex: playerIndex)
    // ...
}

// ...

func assignUnknownController(controller: GCController) {
    // ...
    controller.playerIndex = index
    // ...
}

// ...

func configureController(controller: GCController, forPlayer player: Player) {
    // ...
    loadHUDForPlayer(player, atIndex: player.controller!.playerIndex)
    // ...
}

AdventureScene.swift after
// ...

override init(size: CGSize) {
    leafEmitterATemplate = SKEmitterNode(fileNamed: "Leaves_01")!
    leafEmitterBTemplate = SKEmitterNode(fileNamed: "Leaves_02")!
    projectileSparkEmitterTemplate = SKEmitterNode(fileNamed: "ProjectileSplat")!
    spawnEmitterTemplate = SKEmitterNode(fileNamed: "Spawn")!
        
    super.init(size: size)

    players[0] = defaultPlayer
}

// ...

func loadWorld() {
    // ...
        let templateWorld = scene!.children.first!.copy() as! SKNode
    // ...
}

// ...

func configureConnectedGameControllers() {
    // ...
    assignPresetController(controller, toIndex: playerIndex.rawValue)
    // ...
}

// ...

func gameControllerDidConnect(notification: NSNotification) {
    // ...
    assignPresetController(controller, toIndex: playerIndex.rawValue)
    // ...
}

// ...

func assignUnknownController(controller: GCController) {
    // ...
    controller.playerIndex = GCControllerPlayerIndex(rawValue: index)!
    // ...
}

// ...

func configureController(controller: GCController, forPlayer player: Player) {
    // ...
    loadHUDForPlayer(player, atIndex: player.controller!.playerIndex.rawValue)
    // ...
}

All other errors are of the same kind "value of optional type" and you can simply click the QuickFix.

Sonntag, 26. Juli 2015

Java: How to read files quickly

Recently I had a project in which a graph with nodes and edges had too be build. The biggest file was even to big for Eclipse to open. It contained about 2.970.000 lines. The lines began with 'N' or 'E' and had additional fields like identifier etc. The first approach was really slow and took about 17 seconds to read in the big file. So I was forced to research for faster methods to read in files.
Here we go:

Surprisingly the MappedByteReader was slower than the BufferedReader. In average it took 1.873 seconds to read the large file.

MappedByteReader and StringTokenizer:
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.CharBuffer;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.channels.FileChannel.MapMode;
import java.nio.charset.Charset;
import java.util.StringTokenizer;

...

FileInputStream file = null;
InputStreamReader ir = null;
BufferedReader br = null;
  
final String charsetName = "UTF-8";
  
try {
   
   file = new FileInputStream(Path);
   ir = new InputStreamReader(file);
   br = new BufferedReader(ir);
   FileChannel ch = file.getChannel();
   MappedByteBuffer mbb = ch.map(MapMode.READ_ONLY, 0L, ch.size());
   
   String text = null;
   
   while (mbb.hasRemaining())  {
    
      CharBuffer cb =  Charset.forName(charsetName).decode(mbb);
      text = cb.toString();
      strTokenizer = new StringTokenizer(text);
    
      while (strTokenizer.hasMoreTokens()) {
    
         String nextToken = strTokenizer.nextToken();
         // put in here your logic
      }
    
   }
   
   file.close();
   ir.close();
   br.close();
   
   } catch (FileNotFoundException e) {
      e.printStackTrace();
   } catch (IOException e) {
      e.printStackTrace();
   }
}


The BufferedReader was the fastest solution. It took about 1.451 seconds.

BufferedReader and StringTokenizer:
FileInputStream file = null;
InputStreamReader ir = null;
BufferedReader br = null;
  
try {
   
   file = new FileInputStream(Path);
   ir = new InputStreamReader(file);
   br = new BufferedReader(ir);
   
   String line = null;
   
   while (((line = br.readLine()) != null))  {
    
      strTokenizer = new StringTokenizer(line);
    
      while (strTokenizer.hasMoreTokens()) {
    
         String nextToken = strTokenizer.nextToken();
         // put in here your logic
      }
    
   }
   
   file.close();
   ir.close();
   br.close();
   
   } catch (FileNotFoundException e) {
      e.printStackTrace();
   } catch (IOException e) {
      e.printStackTrace();
   }
}
The java.util.Scanner solution was the slowest one. It took about 17.127 seconds.

Scanner:
FileInputStream file = null;
  
try {
   
    file = new FileInputStream(Path);
    
    scannerFile = new Scanner(file);
    scannerFile.useLocale(Locale.US);
    
    while (scannerFile.hasNext()) {
       // put in here your logic
    }
    
    file.close();
   
    } catch (FileNotFoundException e) {
       e.printStackTrace();
    } catch (IOException e) {
       e.printStackTrace();
    } finally {
       if (scannerFile != null) {
        scannerFile.close();
       }
    }
}

private static Node getNodeFromLine() {
  
   final long item1 = scannerFile.nextLong();
   final double item2 = scannerFile.nextDouble();
   ...
}

private static Edge getEdgeFromLine() {

   final long item1 = scannerFile.nextLong();
   final boolean item2 = getBooleanFromInt(scannerFile.nextInt());
   ...
}



The StringTokenizer solutions shared the same Node and Edge methods:
private static Node getNodeFromLine() {
  
   final long item1 = Long.parseLong(strTokenizer.nextToken());
   final double item2 = Double.parseDouble(strTokenizer.nextToken());
   ...
}

private static Edge getEdgeFromLine() {

   final long item1 = Long.parseLong(strTokenizer.nextToken());
   final boolean item2 = getBooleanFromString(strTokenizer.nextToken());
   ...
}

I removed the whole logic just to focus on the differences between the implementations.

You can easily see that in this case the Scanner wasn't fast enough and the MappedByteReader and the BufferedReader solutions were about 17 times faster. I chose the StringTokenizer because it is supposed to be faster than String.split(), but I didn't test it (have a look here http://stackoverflow.com/questions/691184/scanner-vs-stringtokenizer-vs-string-split).

I hope that give your implementation a performance boost!