Friday, 30 December 2016

This week 20/2016

DataNucleus Data Object  is one of JDO implementation. A performance of this implementation is 2 - 10 times slower then Hibernate (link to test).

Apache Isis - supports domain driven design by requirement of preparing model. Other things are generated and shared by configurable wicket GUI. 

EMF - Eclipse Modeling Framework - it is framework to defining and create model of data by eclipse modelling tools and then on basic of model there is generated Java code. 

JDepend - a tool which shows references between packages. Handy tool to check application design.

Classycle - similar tool to JDepend but additionally it allows to check references on class level as well.

Eclipse Metrics plugin - a eclipse plugin to check dependences between classes and cycles in packages.

Hibernate Search - A hibernate solution of full text searching using Apache Lucene engine. In my case I tried standard solution: single instance, standard indexing with result storage in files. I tried to change a language of analysed tokens but I couldn't find Polish dictionary.
Indexing is processed on request and can be executed as a blocking or asynchronous operation.


jMock - another test tool which allows to create mock. I used this tool in a few cases but the same I can do by Mockito. This tool has other order of processing than Mockito (given, when, then). JMock defines mocks and execution listeners then allows to execute tested method. After 4 hour I think, this tool is less flexible then Mockito but require less complex object to test. jMock couldn't create mock of class, it is possible only to mock interface and it is required to mock every used methods. In my cases it required more code and create instance of object - not mocks.

Saturday, 19 November 2016

This week 19/2016

This article is a summary of thoughts about implementing a piece of DDD in my application. This weekend I disinterred an old topic: How can I design something similar to the DDD in my application and don't turn over all existing application? How can I gently get into.
In inherited application there is strongly used hibernate. Entities model looks like it tries to build a full domain model - they have states and behaviours. However all functionalities use entities in view (and Session on view pattern) and it is difficult to do hermetic model especially then all entity attributes has public setters and getters.

My idea were:
  • to retrieves entities only to service level and then map them to immutable dto and dto use in views or if it was necessary map them to mutable Java Plain Object.
  • change access type for data in entitles. Till now there was property access an there was impossible to remove setter method from entity. I prefer field access. It is much more transparent and allow to remove getters and setters which can be implemented by Lombok library.
  • add new layer - application layer which collect a few independent functionalities and share them to controller.
  • I changed packaging of my classes. Classes were included to packages split in order: layer name, functionality. Now I package my classes in order: functionality, layer, but I still thinking about removing layer part of packages and much more granulate functionality.
  • reports contains data from many independent tables. I get data by native sql directly mapped to immutable dto.

Now I was focused on bounded domain model and how to resolve it in my application. In this application I should much more use CQRS pattern.


Anyway I think about some other implementation problems, ex. how should I implement JPA entities of bounded context? One context needs only a few attributes of all model, other needs some other but that attributes are archived in one db table.

I still looking for best solutions:)

Bellow I added a few interesting resources:

ddd series

ddd-in-practice

dddexample

domain-driven-design-with-java-ee-6

ddd-and-spring

Saturday, 12 November 2016

This week 18/2016

When I was at Devoxx 2016 conference, I chose one of DuyHai DOAN's presentation. I was late and I went at 15 minutes. It seemed that he was talking about some DSL framework so I was disappointed and bored. Lucky I tried to watch the presentation one more time and now I know that I didn't understand the context, the first 10 minutes was the most interesting.

However, to the point. Inspirited by DuyHai DOAN's presentation, I have interested in Annotation Processing. I found a good and clear article about this subject and all became easy.
But to the point. what is the Annotation Processing?
It is a phase of Java code compilation to byte code by javac. As you can see at picture bellow


http://openjdk.java.net/groups/compiler/doc/compilation-overview/javac-flow.png
at the beginning of compilation, the code is parsed and there is created a syntax's dictionary. Then there is executed the Annotation Processor which can read Java code or create new one. (There is assumption, the Annotation Processor can't modify existing code but there is some possibility. I will write about it later).
If the Annotation Processor creates new code, all cycle is repeated. If not, all code is analysed and translated to byte code. 

To study the Annotation Processor, I created 3 projects:
  • my annotation 
  • my implementation of the Annotation Processor 
  • some code in which I used my annotation.

Annotation: 
Notice a Retention Policy type.
@Retention(RetentionPolicy.SOURCE)
@Target({ ElementType.TYPE })
public @interface Getter {
}


Annotation Processor:
I created a file "javax.annotation.processing.Processor" in path "META-INF/services" and I put into it a path to implementation of my Annotation Processor 


@SupportedAnnotationTypes("test.annotationprocessor.annotation.Getter")
@SupportedSourceVersion(SourceVersion.RELEASE_6)
public class GetterProcessor extends AbstractProcessor {

    public GetterProcessor() {
        super();
    }

    @Override
    public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) {
        createClassWithVelocityTemplate(roundEnv);
        return true;
    }

    public void createClassWithVelocityTemplate(RoundEnvironment roundEnv) {
        Set<? extends Element> elements = roundEnv.getElementsAnnotatedWith(Getter.class);
        for (Element element : elements) {
            try {
                FileObject in_file = processingEnv.getFiler().getResource(StandardLocation.SOURCE_PATH, "", element.asType().toString().replace(".", "/") + ".java");

                CharSequence data = in_file.getCharContent(false);
                String data1 = addAFewMethods(data).toString();

                FileObject out_file = processingEnv.getFiler().createResource(StandardLocation.SOURCE_OUTPUT, "", element.asType().toString().replace(".", "/") + ".java");
                Writer w = out_file.openWriter();
                w.append(data1);

                velocityGeneration(w);
                w.close();

            } catch (IOException e) {
                e.printStackTrace();
            }
        }
....
    }
}
It reads a source of class with my annotation and create new class with additional code.


To be drawing subject to the end, it is good to mention in a nutshell: 

  1. Annotation Processing is supported by IDEs like Eclipse or IntelliJ. It is required to check this option in project settings.
  2. As I mentioned above, the Annotation Processor can read and create new code, however authors of Lombok library have found a bypass to this limit. Their library works as it could change a code. They modifies a syntax's dictionary and inject their code. 
  3. Javac doesn't use JVM but it is possible to debugging code in your IDE. When a debug option is added to execute command, javac shares an interface like JVM for remote connections.

Monday, 31 October 2016

This week 17/2016

SmartParam (v.1.1.2) is a powerful framework to parametrise an application.

1. Source of configuration
It is possible to load configuration from text file, database or create it dynamically.  Framework supports directly H2, MySql and Postgesql databases.


example of configuration file:

{
  name: "simpleCase",  inputLevels: 2,  cachable: true,  nullable: true,  arraySeparator: ";",
  levels: [
    {name: "registrationDate", type: "date",   matcher: "between/ie" },     
    {name: "name",                     type: "string" }, 
    {name: "value",                     type: "integer" }, 
    {name: "value2",                   type: "integer" }
  ]
}
registrationDate;name;value;value2
*: 2013-12-01;Adam;20*: 2013-12-01;Monia;5
 


2. Number of input/output parameters
At the beginning it is required to define structure of parameters:
  • name - name of configuration,
  • inputLevels - count of input parameters, which are used to wind exact output parameters,
  • nullable - by default it is false and if any rule match input parameters, it throws exception
  • levels - defines types of input and output parameters.
3. Supported parameters
Framework supports simple types of data, however it is possible to define your own type. There are two ways to do that: do converter or  type holder.
Type holder ex.
@ParamType("localdate")
public class LocalDateType implements Type<LocalDateHolder> {
.....
}
 
public class LocalDateHolder extends AbstractValueHolder {
    private final LocalDate date;
    public LocalDateHolder(LocalDate date) {
        this.date = date;    }
....
} 

4. Matcher
Framework provides all needed matchers but there is possible to create your own matcher.
ex.
@ParamMatcher("mymatcher")
public class MyMatcher implements Matcher {

    @Override    public <T extends ValueHolder> boolean matches(String s, String s1, Type<T> type) {

        return s.toString().equals(s1.toString());    }
}

One of useful matcher is BetweenMatcher. It supports defining a ranges of dates, numbers and defines default value by *

5. Other Notices
Framework presents itself great but project looks to be extinct.

Saturday, 22 October 2016

This week 16/2016

How works a synchronisation of some object in a nutshell.

My goal is to synchronise a block of code by some string which is a parameter of a function.

At the begging I wasn't sure how synchronisation mechanism works. Is it using equals and hash code to compare object or memory address where object is allocated.
So synchronisation doesn't use equal method but memory address where object is allocated to.

So how to synchronise part of code when I have many instances of the same object (ex. string)?

A solution is to use some container for synchronized objects and retrieves instance of  that object to use it to synchronization. In this case the best choose is map where it is possible to find object by key and get its value or if it not exists yet, add it.

So we need some kind of cache but how to manage this cache? We need only object instance when the synchronisation block is executed.
I think the easiest way on a single jvm is to use a weak reference. In this case I create a cache manager with WeakHashMap. The manager has a synchronized method findOrAdd and returns an instance of string object included to map.
What is important the WeakHashMap use weak reference only for key object so it is required to put as a value a WeakReference instance with my object.

Map map = new WeakHashMap();
map.put(myString, new WeakReference(myString));
Now, if instance of myString hasn't any reference to any other object or is not used to synchronisation, it will be removed from memory so removed from map as well.

Saturday, 8 October 2016

This week 15/2016

Protractor framework.

The Protractor (v4.0.x) is perfect tool to testing Angular JS application. The main advantage is that it transparently supports asynchronous tasks. You don't care of timeout for Angular asynchronous operation, Protractor is synchronising itself for you. Big advantage is that framework can make snapshot of screen and save it to ex. PNG file.

Saturday, 17 September 2016

This week 14/2016

A few weeks ago I started doing a Angular 2 tutorial. Angular2 is extremely different to first beta version. I chose coding in TypeScript which is recommended language. It is possible to coding in JavaScript or Dart as well but it is less popular.

In my case I chose TypeScript which is compiled to JavaScript and then interpreted by browser. Writing in TypeScript is nice for developer with Java grounds.

Angular 2 defines 4 types of objects: Component, Service, Module and Pipe. 

Before the first final release was published, the concept how to bootstrap application had changed. As I remember, first version of Angular2 allows to execute project without using main module. Later it was changed.
My experience is that the most difficult thing is to match collaborative versions of libraries. I spend much time on selecting exact version of libraries to run some easy application.

And one more think. To create and build production version of code I recommend to use angular-cli.