Saturday, 28 November 2015

Angular Inherence

Writing a code to application like my could cross a point of readability and flexibility if all functions supporting one model of data I put to one controller. I decided to change it. I have to exclude my model to other module's fiction. Some of common methods for a few controllers can be excluded to other parent controller and inherit it.


My idea is to use factory to have in controllers a shared model instance and parent controller to support the most common operations and extend it in children classes.
Ex. var App = angular.module('App', []);
Below is shared model with public api.
App.factory('SharedModel', function () {
    var model = { /* some definition of object */   };
    // public API
    return {
        getValue: function() {
           return model.value;
        },
        updateValue: function(value) {
           model.value = value;
        }
    };
});
Parent controller
App.controller("ParentCtrl", function($scope, MyParentService,SharedModel) {

    $scope.parentMethod = function(){
        SharedModel.updateValue({'par1' : 'myValue'});
        console.info('do something');
    }
});
Child controller. Angularjs support inheritance of controllers.
App.controller("DefaultCtrl", function($scope, $controller, SharedModel, MyService) {
    $controller('ParentCtrl', {$scope: $scope});
  
    $scope.setVal = function(text){
        MyService.setText(text);
        sharedModel.updateValue(text);
    };
    $scope.getVal = function(){
        return SharedModel.getValue();
    };
  
    $scope.getServiceVal = function(){
        return MyService.myBase();
    };
    $scope.getMyServiceVal = function(){
        return MyService.myService();
    };
  
});
Top service body.
function MyBaseService($http) {
    this.text = "MyBaseServiceText";
    this.loaded = false;
    this.myBase = function(){
        console.log("MyBaseService.myBase");
        if(!this.loaded){
            $http({
                method: 'GET',
                url: 'http://localhost/',
            });
            this.loaded = true;
        }
        return this.text;
    }
};
Medium service body.

function MyParentService($http) {
    MyBaseService.call(this,$http);
    this.getSomething = function(){
        return 'something';
    }
};
Child service body used in controller.

function MyService($http) {
    MyBaseService.call(this,$http);
    this.myService = function(){
        console.log("called my service" + this.text);
        $http({
            method: 'GET',
            url: 'http://localhost/',
        });
    }
};
Registration of service body in Angularjs's context.
App.service("MyBaseService", MyBaseService);
App.service("MyParentService", MyParentService);
App.service("MyService", MyService);
It's quite easy..... isn't it ?

Saturday, 21 November 2015

Angularjs and lazy loading

Today I noticed that all DOM model is loaded, even if it is not shown on page ( is ngHiden) and I don't need it. I searched a little in google and I found that there is a other attribute which I should use for this block code - "ngIf".

If it is false, it doesn't include element and children into a DOM model and it wait for change state to true.

Spring Data

Spring Data it is useful framework but in my case sometimes it is too easy. Two years ago, when I worked in some company, my colleague wrote some template of framework like this.

It also have generic implementation for a CRUD operation but you have to write implementation for other types of operations. It is one another class which you have to write. It is easy but it doesn't enforce any convention of methods name.

Other huge advantage is resolving of types returning in methods. Every type has it's own meaning. Ex. You can receive a entity or a Optional<Entity> type. When it is looked for list of elements, there is more options, ex. Stream (JDK8), List, Set and Page<Entity> type where there is a information about count of all elements.

Sunday, 15 November 2015

Life in Germany

Lately I have been to Germany. I will write what phenomena I noticed. 
1. Close to the border, on Polish side, there were many cigarette shops. In Zgorzelec, where I was,  there were three or four shops of this kind at the street next to the border. It was strange because there were more this kind of shops than exchange offices or off-licences in the whole town. There is one conclusion, there is a huge market for product like this in Germany. When we were in a deserted village I even noticed cigarette automates. However, in Stuttgart I saw the same number of people with cigarette in the same age as in Poland, probably there are similar restrictions of customer's age. We weren't in pubs and places like that - we were with half year old baby - so I can't write about prohibitions in that places.



2. The motorway speed limit. In Germany there isn't such limit. There is only recommendation not to exceed 130 km per hour so you can drive as fast as you can without any consequences. I have to confess that it is strange feeling to drive 160 km per hour and overtake a police car.
When I was driving over 145 km per hour on Polish or German motorways my car sounded like a spin-dryer. I don't know exactly what was the reason, probably type of tarmac. Anyway, this sound was a lullaby for my 8 months old daughter.
3. Special road signs. It was common to see speed limit with additional label like "bei Nässe" on the motorway.


It means that this speed limit is applied only when the road surface is wet. I have never seen something like this in Poland.
4. Behaviour on the road. My another observation at the motorways was that drivers who were preparing to overtake,  had changed their lane in long distance ahead of the overtaking car so usually I had overtake them from right lane. It wasn't dangerous because there were still save distances between cars.



5. Grerman cities try to limit air pollution. They introduced special zones called  "Umweltzone". On entrance to that cities, there are special road signs. If you want to get into this zone, you should have a proper striker at your front window. Otherwise you can get a fine (about 80 EUR). There are 3 kinds of sticker: green, yellow and red one determined by ecological norm. This restriction prompts German to buy new car. Strikers are purchasable at Dekra car service or at city hall from 5 EUR after verification of your car registration document.
I got to know about this restriction a week before our trip. I am not sure if foreigner car is required to have a proper sticker but I didn't what to risk a fine, so I bought it in Warsaw for 79zl.
It is easy to guess that it is impossible to meet old car with diesel engine in the city, so I you are looking for some you have to look after it in the village.



6. Accommodation conditions. We came to hotel a few minutes before 6 pm, when our reservation could expire. An entrance and hotel's reception looked as relict of previous age. There was no room for us but receptionist forwarded us to cooperating hotel. I wanted to pay by card but terminal didn't accept my MasterCard. It was some joke, we tried 3 times and finally I had to get cache from cache dispenser. It took me about 30 minutes because nobody at street knew where nearest cache dispenser was.
We lost another 30 minutes to get to target hotel, anyway we stayed next to market promenade. Of course there was no hotel's park place so we have to park at public park house around hotel.
Hotel was small. An entrance and reception looked modernly. We got big 3 bed room with a bath. The furnishing was in style of late 70's. Probably they loved that time and they didn't changed room's arrangement or maybe three-star-hotel was too cheap to update the arrangement. I have seen h which looked better then this three-star-hotel any way we were there not to be excited about the hotel.



7. When I was driving on German ways I had to look out. They didn't infinitely repeat signpost as in Poland. Other difficulty was that Stuttgart is placed amidst the hills so I didn't know if I had to keep right side of the road or went throw tunnel to get to some place. GPS signal was failing as well so to get to next street could take a half hour.



 
8. 
In most market they take a deposit on all kind of bottles, even plastic. Later they collect empty bottles and replace them for money or shopping coupons.



9. We spend last day in Stuttgart on shopping. We went for a walk across main market promenade and we did price research. In my opinion, prices of clothes are twice higher and baby tools similar as at Marszalkowska street in Warsaw.

That's all my remarks after four days trip to Germany.


Sunday, 18 October 2015

My Zk expirience

As I mentioned before I have to do one thing in zk framework. My fillings are quite good comparing them with that filling what I had after developing in GWT. Maybe because ZK is different than GWT. ZK is server side oriented framework otherwise than GWT - client oriented.
Firstly GWT need special compilation after every little change, zk only when interface changed. In other cases hot swap every time works.
In ZK all business logic can is on server side. Forms looks like jsp and are processed by zk dispatcher.
Today I found one thread at stackoverflow.com comparing them. There is one comparison of project developed by two teams, one in ZK and second in GWT.  ZK win, it took one third of developing in GWT. I can say the same about developing in  clean JavaScript and Angular.
Comparing user experience of using application developed with ZK and GWT users didn't see any difference.
Conclusion
If you afraid of JavaScript and your clients can be always online, use ZK, otherwise you can reflect use GWT or domesticate with JavaScript and Angular

Thursday, 15 October 2015

log4j vs slf4j

I didn't know that slf4j is another abstraction for ex. log4j. Slf4j independence application from using ex. log4j or common logs. It doesn't log anything if behind it there isn't any logging library. 
Slf4j gives something useful in its interface - something like string format. You can write

LOGGER.debug("This my log in class {} and method {}", getName(), "my method");
and then, when this class is at higher logging level then debug it doesn't concatenate string)


I think it doesn't  protect us from writing sometime like this:

if(LOGGER.isDebug()){
     String s = someLongExecutionOperation();
     LOGGER.debug(s);
}

Tuesday, 13 October 2015

Data transfer in application

Lately it returns one topic in my mind. How to implement data flow between layers in my application.
My last habit was to convert entity to immutable dto (service layer) and then when I'd like to update object I converted another time dto (at controller layer) to bean. In this case I have 2 mapping. When I need to add some attribute I have to change 3 objects.
I always assume that entity can't go out from service, so my new idea to improve this solution.
Now I try one of case:
  1. use class with excluding interface . 
  2. create builder as now with getters. 

Other idea is to use mutable beans when I plan to update object or immutable in other case.

Thursday, 8 October 2015

Zk framework

Today I started to study zk solutions in application which I support. zk is alternative for famous framework as gwt or JSF. I didn't check performance of zk but as I could expirence, it is comparable.
In zk you request about zul file and this file execute controller class.

Friday, 2 October 2015

Maven 2.x vs 3.x

Today I wanted to know what is difference between version of this tool. I didn't use Maven at advance level so for me it is only some change in pom file.

Anyway I find out:
  1. I can run maven in multi thread mode and processor multicore mode.
  2. I can use maven shell
  3. It is a little faster then before but in my situation it doesn't matter.
  4. Logs are more verbose
Other useful option:
  1. I can convert pom file into some other JVM languages script like grove.
There are more changes but I'm not going into great details here.

Wednesday, 30 September 2015

Spring Validation - collection max index.

Since Spring 3 DataBinder have aditional validation of collections which prevents out of memeory attack. This validation default limits collection size to 256 elements of collection.
If you need to increase this limit you have to use method setAutoGrowCollectionLimit before you register custom editors.

Tuesday, 29 September 2015

Angular structure and remote templates

At weekend I tried to clean my Angular project and move modules to separate files and folders. I did this but at the beginning nothing was working. I defined separate modules like:

angular.module('App', []);

In this square brackets I have to put names of other modules that are required to use in that App. That modules are injected by name.

angular.module('App', ['MyValidators','MyFilters']);


I exclude html templates to external files and use them by url.

<div .... ng-include="'templates/myTemplate.tpl.html'" />

Tuning Oracle queries with null values

Today I tested two queries in Oracle database. I noticed that when I execute query there column value is null, oracle engine directly use full access to table. I created index like:

create index MY_IDX on MY_TABLE (COLUMN_CAN_BE_NULL, -1);
and I have to use hint to use that index. Automatically oracle used full access, even when I counted statistic for this table.
However when it used index like this, it took much more then full access.

I have to dwell on a subject....

Friday, 25 September 2015

log4j and additional log param

I didn't know that so easy you can add to logs for example http session id. You need only put into MDC object value and later set log pattern as %X{sessionId}.

When I did that I had to find good place to put into MDC my sessionId parameter. I created web filter to archive that. Filter is simple and should be executed in correct order in chain.

LINK


I have to admit I had problem with logging exception stack trace. I implemented ThrowableRenderer and have set throwableRenderer tag.

SRC

AngularJS interceptor

I created AngularJS service and connection to server. On server side was Spring Security and I used CSRF. I'd like natty add this token to every request.

The best way to do that was create interceptor "csrfInterceptor"

App.config(["$httpProvider", function($httpProvider) {
    $httpProvider.interceptors.push("csrfInterceptor");
}]);

and push it into provider interceptor.

AngularJs filters

How it is easy to create in AngularJS filter I got to know when I need some special conditions.
I need to filter list of elements like this:


item in ptfs | showFilter: searchCriteria

I created filter called "showFilter" with filter criteria "searchCriteria".

Filter looks like:

App.filter('showFilter', [function($filter) {
   
    function isNotEmpty(obj){
        return obj != null && obj.trim().length > 0;
    }
   
   
    return function(inputArray, searchCriteria){      
       ....
       return data;

     };

}]);


Function returning data is a filtered copy of input data.

Thursday, 24 September 2015

ehcache and junit

Yesterday I upgraded ehcache lib to 2.8.4 in supported by me application. I have run tests and I saw in logs a few lines of notice.

Notice says, there is another CacheManager in JVM. I had to think a while. I changed configuration files and I gave them a name but it didn't fix it. I debugged this and I saw that every test is run there is loading new instance of configuration and there is created new CacheManager with known name.

I searched a little in google and I found out that I can downgrade libs to version 2.4.x or turn off cache during the test. I chose first solution.

Thursday, 17 September 2015

Language loophole

Yesterday I was arguing with my colleague about meaning of sentence. Sentence is like:
You have put A instead of B.
I understood this sentence what I have to do something instead of I have done something. Little difference in sentence but huge difference in meaning.

Tuesday, 15 September 2015

SQL and null conditions

Today I found in my SQL package code one bug. I created function/procedure with a few input parameters and used them in simple sql query as condition. In some cases that input parameters are null. I used that parameters with = sign. However oracle interpret construction like:
some_column = input_val
even column and input_value are null as not fulfill condition.

In older oracle sql it is possible to use function decode(some_column, input_val, -1) = -1 but it is not performance
In newer oracle db you can create index like:

create index some_index_name for table_name (some_column, -1)

You have to look out for possible values in some_column.

Monday, 14 September 2015

JPA 2.0

JPA 2.0 has a few useful things like:
  1. API to basic caching
  2. Unify database source parameters, ex username or password
  3. Improve lock modes
  4. Use advanced JPQL language to create queries
  5. Extends presisting API

ResultSet by Hibernate

In hibernate you can use 3 types of Scrollable ResultSet:
  1. TYPE_SCROLL_INSENSITIVE - it is possible to get selected row of data and retrieve data forward and backward. There is not sensitive for external changes in db, so as I got to know refresh is impossible.
  2. TYPE_SCROLL_SENSITIVE - the same as above but it is sensitive for external changes in db. After calling refresh you get new entity from db.
  3. TYPE_FORWARD_ONLY - it is possible to get data only forward order, you can't get selected row. It is necessary to go in loop by next method.

My first post

Today I thought that I can collect notes about new things I get to know this day. I'd like to write this blog mostly in English or other languages which aren't my native language.