Monday, December 15, 2014

Mockito notes

Mocking

Scenario:

In service class you want to mock dao call.
In service class make dao class package private (no modifier - optional).
Write test in same package (under test subfolder, not main).
Dao class has method called testingMockito(String someString);

Code example:

SomeService service; //injected
SomeDao dao = Mockito.mock(SomeDao.class);
service.setDao(dao); // or service.dao = dao;
//throw Exception when calling dao class
Mockito.doThrow(someException).when(dao).testingMockito(Mockito.anyString());

Verify

Mockito.verify(simCardServiceMock, Mockito.times(1)).findSimCard(simIdentifier);


Mock void methods:
1st service returns some response, 2nd service calls void method.

CustomerSearchService customerSearchService = Mockito.mock(CustomerSearchService.class);
Mockito.when(customerSearchService.searchSubscription(providerId, searchCriteria)).thenReturn(subscription);

final SubscriptionService subscriptionService = Mockito.mock(SubscriptionService.class);
Mockito.doNothing()
.when(subscriptionService)
.activateSubscription(providerId, subscription.getId());


Ref:
https://stackoverflow.com/questions/14889951/how-to-verify-a-method-is-called-two-times-with-mockito-verify
http://www.baeldung.com/mockito-behavior
https://stackoverflow.com/questions/2276271/how-to-make-mock-to-void-methods-with-mockito

Wednesday, October 22, 2014

Redis notes

KEYS * - Returns all keys matching pattern.
FLUSHDB - Delete all the keys of the currently selected DB
FLUSHALL - Delete all the keys of all the existing databases, not just the currently selected one.


Hashes

Hashes are maps between string fields and string values, so they are the perfect data type to represent objects
(eg: A User with a number of fields like name, surname, age, and so forth)
HGETALL key - lists all fields


Sets

Sets are an unordered collection of Strings.
SMEMBERS key - Get all the members in a set


Sorted Sets

Sorted Sets are, similarly to Redis Sets, non repeating collections of Strings. The difference is that every member of a Sorted Set is associated with score, that is used in order to take the sorted set ordered, from the smallest to the greatest score. While members are unique, scores may be repeated.
ZCARD key - Get the number of members in a sorted set
ZRANGE key start stop [WITHSCORES] - Return a range of members in a sorted set, by index

Ref:
Redis homepage
Redis for the real world (IBM - Java development 2.0)

Tuesday, October 21, 2014

Quartz notes

The key interfaces of the Quartz API are:

Scheduler - the main API for interacting with the Scheduler.
Job - an interface to be implemented by components that you want the Scheduler to execute.
JobDetail - used to define instances of Jobs.
The JobDataMap can be used to hold any amount of (serializable) data objects which you wish to have made available to the job instance when it executes.
Trigger - a component that defines the schedule upon which a given Job will be executed.
(Quartz ships with a handful of different trigger types, but the most commonly used types are SimpleTriggerand CronTrigger.)
JobBuilder - used to define/build JobDetail instances, which define instances of Jobs.
TriggerBuilder - used to define/build Trigger instances.

Misfire Instructions

A misfire occurs if a persistent trigger misses its firing time because of the scheduler being shutdown, or because there are no available threads in Quartz's thread pool for executing the job.
The different trigger types have different misfire instructions available to them. By default they use a 'smart policy' instruction - which has dynamic behavior based on trigger type and configuration. When the scheduler starts, it searches for any persistent triggers that have misfired, and it then updates each of them based on their individually configured misfire instructions.

For CronTriggers: The 'smart policy' instruction is interpreted as MISFIRE_INSTRUCTION_FIRE_NOW

Note that if a trigger's time to fire arrives, and there isn't an available thread, Quartz will block (pause) until a thread comes available, then the Job will execute some number of milliseconds later than it should have.
This may even cause the thread to misfire if there is no available thread for the duration of the scheduler's configured “misfire threshold”.

Listeners

Listeners are objects that you create to perform actions based on events occurring within the scheduler.
As indicated by their names, TriggerListeners receive events related to triggers, and JobListeners receive events related to jobs.
Trigger-related events include: trigger firings, trigger misfirings, and trigger completions (the jobs fired off by the trigger is finished).

JobDataMap

JobDetail contains various property settings for the job, as well as a JobDataMap, which can be used to store state information or provide properties/configuration for a given instance of your Job class.
Triggers may also have a JobDataMap associated with them. A JobDataMap is useful for passing to a job parameters that are specific to the firings of the trigger.

The JobDataMap that is found on the JobExecutionContext during Job execution serves as a convenience.
It is a merge of the JobDataMap found on the JobDetail and the one found on the Trigger, with the values in the latter overriding any same-named values in the former.

If you add setter methods to your job class that correspond to the names of keys in the JobDataMap, then Quartz's default JobFactory implementation will automatically call those setters when the job is instantiated, thus preventing the need to explicitly get the values out of the map within your execute method.

JobStores

JobStores are responsible for keeping track of all the work data you give to the scheduler: jobs, triggers, calendars, and so forth.



How to fire scheduled job asap?

Example:

select * from qrtz_triggers;
           trigger_name           | trigger_group |           job_name           | job_group | is_volatile | description | next_fire_time | prev_fire_time | priority |
trigger_state | trigger_type |  start_time   | end_time | calendar_name | misfire_instr | job_data
----------------------------------+---------------+------------------------------+-----------+-------------+-------------+----------------+----------------+----------+-
--------------+--------------+---------------+----------+---------------+---------------+----------
 portReconciliationProcessTrigger | DEFAULT       | portReconciliationProcessJob | DEFAULT   | f           |             |  1426579200000 |  1426492800000 |        5 |
WAITING       | CRON         | 1378612922000 |        0 |               |             0 | \x


next fire time:     1426579200000 -> http://www.epochconverter.com/ ->
GMT: Tue, 17 Mar 2015 08:00:00 GMT
Your time zone: 3/17/2015, 9:00:00 AM GMT+1:00

Fire it in near future: 13.3.2015 15:00 -> converter ->
Epoch timestamp: 1426518000
Timestamp in milliseconds: 1426518000000

Update db
UPDATE qrtz_triggers SET next_fire_time = '1426518000000' WHERE trigger_name = 'portReconciliationProcessTrigger';

Delete triggers from db
delete from qrtz_cron_triggers;
delete from qrtz_triggers;
delete from qrtz_job_details;

Ref:
Quartz_Scheduler_Developer_Guide v2.2.1
Quartz scheduler misfire instructions explained

Quartz 1.8.x to Quartz 2.0 Migration Guide
Spring - Task Execution and Scheduling

Friday, October 17, 2014

svn tips

status

$ svn status

update

$ svn up

revert

$ svn revert *

revert to previous version (undo commit)

$ svn merge -r HEAD:12345 .

ignore files

$ svn propset svn:ignore "someFile" .

link to another/external directory as part of your project

set property:
$ svn propset svn:externals https://myServer/build/common common

checkout

$ svn checkout repositoryURL destinationDirectory

Ref

How do I ignore files in Subversion?
Revert to a Previous Version in Subversion

Thursday, August 28, 2014

Dependency injection in Spring

Injecting beans

@org.springframework.beans.factory.annotation.Autowired
@javax.inject.Named("beanId")


Injecting properties file values

@org.springframework.beans.factory.annotation.Value("${key.in.file}")
private String hostName;

Injecting util: list, set, map

@javax.annotation.Resource(name="mySet")
private Set<Action> allTrafficActions;

set is defined in xml:
<util:set id="mySet" set-class="java.util.HashSet"
value-type="com.api.types.Action">
<value>DATA</value>
<value>SMS_MO</value>
<value>MMS_MO</value>
</util:set>
com.api.types.Action is enum.


Inject list from properties file:
internal.operators.ids=10005,216,217
you can inject it with expression:
@org.springframework.beans.factory.annotation.Value("#{'${internal.operators.ids}'.split(',')}")
private List<String> internalOperators;

Use @Value as optional.
There is no need to be specified/defined in properties file.
E.g.
@Value("${external.createsim:true}")
boolean notifyExternalHandler = true;


Use property as message template
template.file=/opt/polite/{0}.prov

In code inject value and use MessageFormater to replace {0}:
@Value("${template.file}")
String postpaidFilename = "/opt/{0}.prov";

String filename = java.text.MessageFormat.format(postpaidFilename, "123");

Result filename is /opt/polite/123.prov


Ref:
http://kh-yiu.blogspot.com/2013/08/spring-injecting-properties-file-values.html
http://samaratips.blogspot.com/2011/07/spring-autowired.html
https://stackoverflow.com/questions/12576156/reading-a-list-from-properties-file-and-load-with-spring-annotation-value
http://www.captaindebug.com/2012/01/autowiring-using-value-and-optional.html
http://www.baeldung.com/2012/02/06/properties-with-spring/

Wednesday, August 27, 2014

Count

Using criteria API:

session.createCriteria(Book.class).setProjection(Projections.rowCount()).uniqueResult();

or native SQL:

session.createQuery("select count(*) from Book").uniqueResult()

Wednesday, August 6, 2014

Web services

Abbreviations


WWW World Wide Web
HTTP HyperText Transfer Protocol
W3C World Wide Web Consortium
IETF Internet Engineering Task Force

SOAP - Simple Object Access Protocol
WSDL - Web Services Description Language (pronounced "whiz dull")
REST - Representational State Transfer

JAX-WS - Java API for XML Web Services
JAX-RS - Java API for RESTful Web Services

WAR - Web ARchive
AJAX - Asynchronous JavaScript with XML

SEI - Service Endpoint Interface
SIB - Service Implementation Bean


Ref:


Expose 2 or more interfaces as one service (wsdl)

Using cxf, wsdl that should have all methos/operation from all interfaces had exposed only methods from first interface!
Solution: 
Make 3rd interface that extends interfaces that one needs to expose and implement it.


Ref:

Thursday, May 22, 2014

Start/stop Tomcat from ANT

<project name="Stop/start Tomcat with local deploy">

<property name="tomcat.home" value="D:/apache-tomcat-7.0.47" />
<property name="project.name" value="samara-provisioning" />
<property name="dist.dir" value="dist/artefacts" />

<!-- deploy-local: delete and copy war -->
<target name="deploy-local" depends="tomcat-stop">

<delete>
<fileset dir="${tomcat.home}/webapps">
<include name="${project.name}.war" />
</fileset>
</delete>
<delete dir="${tomcat.home}/webapps/${project.name}" />

<copy todir="${tomcat.home}/webapps">
<fileset dir="${dist.dir}">
<include name="**/${project.name}.war" />
</fileset>
</copy>

<tstamp>
<format property="TODAY" pattern="HH:mm:ss:sss zzz"
locale="en" />
</tstamp>
<echo> Build Completed At: ${TODAY}</echo>

</target>

<!-- start tomcat, it depends on deploy-local -->
<target name="tomcat-start" depends="deploy-local">
<java classname="org.apache.catalina.startup.Bootstrap"
failonerror="true" fork="true">
<classpath
path="${tomcat.home}/bin/bootstrap.jar:${tomcat.home}/bin/tomcat-juli.jar" />
<jvmarg
value="-Djava.util.logging.manager=org.apache.juli.ClassLoaderLogManager" />
<jvmarg
value="-Djava.util.logging.config.file=${tomcat.home}/conf/logging.properties" />
<jvmarg value="-Dcatalina.home=${tomcat.home}" />
<jvmarg value="-Dcatalina.base=${tomcat.home}" />
<jvmarg value="-Djava.io.tmpdir=${tomcat.home}/temp" />
<arg line="start" />
</java>
</target>

<!--stopping tomcat , if it is found running -->
<target name="tomcat-stop" if="tomcat.running" depends="check-port">
<echo message="Tomcat is running...stopping it" />
<java classname="org.apache.catalina.startup.Bootstrap" fork="true">
<classpath
path="${tomcat.home}/bin/bootstrap.jar:${tomcat.home}/bin/tomcat-juli.jar" />
<jvmarg value="-Dcatalina.home=${tomcat.home}" />
<arg line="stop" />
</java>
</target>

<!-- Check whether Tomcat is running -->

<target name="check-port" description="Check whether Tomcat is running">
<echo message="Checking whether Tomcat is running" />
<condition property="tomcat.running">
<socket server="localhost" port="8080" />
</condition>
</target>

</project>


Ref:
http://techfindouts.blogspot.com/2013/08/how-to-restart-stopstart-tomcat-using.html
http://linuxclicks.blogspot.com/2011/04/java-ant-target-to-startstop-apache.html

Wednesday, May 7, 2014

Hibernate/persistence annotations

Some useful annotations when using
hibernate.hbm2ddl.auto to update | create | create-drop
If hbm2ddl.auto is set to update it will not change type of field!
     postgres:  ALTER TABLE users ALTER COLUMN role TYPE varchar(16);

javax.persistence.Lob with/without org.hibernate.annotations.Type

Using postgres and omitting Type for text lobs will cause numbers in database tables. 
Like operator will not work!
Solution:
@Lob
@Type(type = "org.hibernate.type.TextType")

If there was version without @Type and you want to update/migrate, please share your expirience.
(If you add @Type, old records will be read as plain strings.)
// This was tested with hibernate 3.6.10. and 5.1.0

org.hibernate.annotations.ForeignKey

Very useful for not having generated names as foreign keys.

In JPA 2.1 you can use javax.persistence.ForeignKey
@JoinColumn(foreignKey = @ForeignKey(name = "FK_ORDER_CUSTOMER"))

javax.persistence.Enumerated(javax.persistence.EnumType.STRING)

When using enum, store it in db as string, not a number

javax.persistence.Id with javax.persistence.Column

This combination will cause a lot of problems with hsqldb (column annotation is same like Id constraint). Postgres will not complain.
@Id
@Column(name = "ID", nullable = false, unique = true)

Solution:
remove nullable and unique


Tested on hsqldb 2.3.2 (as in memory) and postgres 9.2/9.3

Ref:

Wednesday, November 27, 2013

Java .class version

javap - The Java Class File Disassembler



Usage


   javap -verbose YourClass

Output

  ...
  SourceFile: "YourClass.java"
  minor version: 0
  major version: 50
  flags: ACC_PUBLIC, ACC_SUPER
  ...

Major version

J2SE 7 = 51,
J2SE 6.0 = 50,
J2SE 5.0 = 49,
JDK 1.4 = 48,
JDK 1.3 = 47,
JDK 1.2 = 46,
JDK 1.1 = 45

Ref:
http://reverseengineering.stackexchange.com/questions/1328/find-out-a-java-class-files-compiler-version
http://docs.oracle.com/javase/7/docs/technotes/tools/windows/javap.html

Tuesday, November 12, 2013

Postgres tips

Log to database

psql -p port -U user database

Show databases

\l

Show tables

\d

Describe table

\d+ table_name


Exit

\q

Import script from terminal

(when database was exported in sql file)
psql -p port -U user -d dest_db -a -f fileName.sql
   (psql -U prov -d prov -a -f model-prov.sql)

Select TOP 5 records, char_length

SELECT string1, char_length(string1) FROM table1 ORDER BY createDate DESC LIMIT 5;

Dump (export) database

pg_dump -U user source_db -p port -f fileName.sql

List sequences

\ds
or by using SQL:
SELECT c.relname FROM pg_class c WHERE c.relkind = 'S';

list sequence dependencies

SELECT p.relname, a.adsrc FROM pg_class p JOIN pg_attrdef a ON (p.relfilenode = a.adrelid);

To get last value of a sequence use the following query:

SELECT last_value FROM test_id_seq;

remove a sequence


DROP SEQUENCE sequenceName;

Change column type


ALTER TABLE ad_hoc_history ALTER COLUMN parameters TYPE text;
(http://www.postgresql.org/docs/9.3/static/sql-altertable.html)

* change the size of a varchar column:
ALTER TABLE simlocation ALTER COLUMN location TYPE varchar(30);

drop constrain (NOT NULL)


ALTER TABLE table ALTER COLUMN column DROP NOT NULL;

Is some range present in system


Table is msisdn and msisdn is key, but it is string.
select count(*) from msisdn where to_number(msisdn,'9999999999999') >=4366305707030 and to_number(msisdn,'9999999999999') <=4366305712029;

Ref:
http://www.postgresqlforbeginners.com/2010/11/interacting-with-postgresql-psql.html
http://www.postgresql.org/docs/9.3/static/app-psql.html
http://www.postgresql.org/docs/9.3/static/functions-string.html
dump:
http://www.thegeekstuff.com/2009/01/how-to-backup-and-restore-postgres-database-using-pg_dump-and-psql/
http://www.postgresql.org/docs/9.3/static/app-pgdump.html
sequences:
http://www.neilconway.org/docs/sequences/
http://blog.sensible.io/2013/08/24/postgresql-sequences-and-array-column-types.html http://www.linuxtopia.org/online_books/database_guides/Practical_PostgreSQL_database/PostgreSQL_x14316_001.htm
http://www.techonthenet.com/postgresql/functions/to_number.php

Linux tips

yum manager

The Yellowdog Updater, Modified (yum) is an open-source command-line package-management utility for Linux operating systems using the RPM Package Manager. Though yum has a command-line interface, several other tools provide graphical user interfaces to yum functionality. Yum allows automatic updates, package and dependency management, on RPM-based distributions. Yum works with software repositories (collections of packages), which can be accessed locally or over a network connection.

install: yum install mvno-paygw
find: yum search mvno-paygw
update: yum update mvno-paygw
info: yum info mvno-paygw  (information about package; what version is on repository)
check-update: Checks to see whether updates are available. If they are, yum displays their names, version and repository area.
provides: searches for which packages provide the requested dependency of file. This also takes wildcards for files. E.g. yum provides */ldapsearch

Process status

ps -ef | grep java

Change password for current user

passwd

Change password for user by using root account

sudo su
passwd someUser

Check if port 80 is open

netstat -tulpn | grep :80

Download web page

wget localhost:80/bugzilla

List hosts file

cat /etc/hosts

Copy file

cp [OPTION]... SOURCE... DIRECTORY
cp /wsdls/EID_Provision-V0.5.wsdl /var/opt/wsdls/EID_Provision-V0.5.wsdl

Delete file

rm fileName

Remove a directory and its contents without prompting you to make sure you want to delete each file in the directory.
rm -rf directory

Zip file

zip dest.zip sourceFile

The following command compresses the file archivefile1.txt and replaces it with the compressed version named "archivefile1.txt.bz2". bzip2 creates smaller files.
bzip2 archivefile1.txt

Read file/logs
[sudo] tail -100f /var/log/someLogFile.log

copy sourceFile.zip to another comp to user directory

 scp ./sourceFile.zip 10.200.0.133:./
(scp source_file_name username@destination_host:destination_folder)


Find 56952849307 that occured at 2015-02-06 10:2x in provisioning.log file
cat provisioning.log | grep "2015-02-06 10:2.*56952849307" | more
grep -A 3 "stringToFind" fileName   // show 3 lines after
grep -B 3 "stringToFind" fileName   // show 3 lines before
grep -C 3 "stringToFind" fileName   // show 3 lines around

Find 56952849307 in all files that begin with provisioning (e.g. provisioning.log.1)
ls provisioning* | xargs cat | grep 56952849307

Find USSD word in all provisioning.log files and show next 5 lines
cat /var/log/provisioning.log.* | grep MOVILB -A 5

grep all files in current directory for exact match:
grep -F "SIM card was deleted. MSISDN" *

dump tcp traffic to file
tcpdump -i any -w /tmp/test_001.pcap

ssh remote host identification has changed
ssh-keygen -R hostname

Change permission on folder
if needed switch to root user
$ sudo su
$ chmod -R 777 folderName

Ref:
15 Practical Grep Command Examples In Linux / UNIX

Unix Less Command: 10 Tips for Effective Navigation
How To Use Linux Screen


Sunday, September 15, 2013

Maven notes

<!-- user defined properties in the pom.xml -->

 <properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  <jdk.version>1.8</jdk.version>
  <log4j.version>1.2.17</log4j.version>
</properties>

<dependencies>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>${log4j.version}</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>1.7.7</version>

</dependency>
</dependencies>

<build>

<plugins>

<!-- specify java version  -->

<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.5.1</version>
<configuration>
<source>${jdk.version}</source>
<target>${jdk.version}</target>
</configuration>
</plugin>

<!--download sources and javadocs -->

<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-eclipse-plugin</artifactId>
<configuration>
<downloadSources>true</downloadSources>
<downloadJavadocs>true</downloadJavadocs>
</configuration>
</plugin>

<!-- create manifest file-->

<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-jar-plugin</artifactId>
<configuration>
<archive>
<manifest>
<addClasspath>true</addClasspath>
<mainClass>hr.samara.mock.StartService</mainClass>
<classpathPrefix>dependency-jars/</classpathPrefix>
</manifest>
</archive>
</configuration>
</plugin>

<!-- copy dependency jars to dependency-jars folder-->

<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-dependency-plugin</artifactId>
<executions>
<execution>
<id>copy-dependencies</id>
<phase>package</phase>
<goals>
<goal>copy-dependencies</goal>
</goals>
<configuration>
<outputDirectory>${project.build.directory}/dependency-jars/</outputDirectory>
</configuration>
</execution>
</executions>
</plugin>

</plugins>

<pluginManagement>
<plugins>

<!-- Ignore/Execute plugin execution -->

<plugin>
<groupId>org.eclipse.m2e</groupId>
<artifactId>lifecycle-mapping</artifactId>
<version>1.0.0</version>
<configuration>
<lifecycleMappingMetadata>
<pluginExecutions>
<!-- copy-dependency plugin -->
<pluginExecution>
<pluginExecutionFilter>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-dependency-plugin</artifactId>
<versionRange>[1.0.0,)</versionRange>
<goals>
<goal>copy-dependencies</goal>
</goals>
</pluginExecutionFilter>
<action>
<ignore />
</action>
</pluginExecution>
</pluginExecutions>
</lifecycleMappingMetadata>
</configuration>
</plugin>
</plugins>
</pluginManagement>

</build>

Install jar file to local repository

mvn install:install-file -Dfile=./mariadb-java-client-1.1.5.jar -DgroupId=org.mariadb.jdbc -DartifactId=mariadb-java-client -Dversion=1.1.5 -Dpackaging=jar


Resolving OutOfMemory Error

export MAVEN_OPTS="-Xmx1024m -XX:MaxPermSize=128m"

Sunday, August 25, 2013

Javadoc tips

Referencing class: 

     {@link hr.samara.RadiusMessageResultEvent RadiusMessageResultEvent}

Referencing public static field: 

     {@link hr.samara.RadiusMessageResultEvent#EVENT_TYPE_ID EventType}

   * if class is within same package there is no need for naming package in link
     {@link RadiusMessageResultEvent}
   * second String is label

Ref:
http://docs.oracle.com/javase/7/docs/technotes/tools/windows/javadoc.html#link

Friday, July 26, 2013

Measuring time

How to measure time elapsed when invoking method or doing some processing.

long start = System.nanoTime();
sum_slow();
long end = System.nanoTime();
long diff = end - start;
System.out.println("Time: " + diff / 1000000000.0 + " seconds");
System.out.println("Time: " + TimeUnit.SECONDS.convert(diff, TimeUnit.NANOSECONDS) + " seconds");

Test:
Time: 18.596630883 seconds
Time: 18 seconds

Wednesday, July 24, 2013

Logging

log4j 1.2


Layouts:

#from mobicents-jainslee-2.7.0.FINAL-jboss-5.1.0.GA
%d{ABSOLUTE} %-5p [%c{1}] (%t) %m%n
21:47:59,146 WARN  [LogTest] (main) Sample warn message

%d [%t] %-5p %c - %m%n
2013-07-24 21:47:40,572 [main] WARN  org.mobicents.slee.test.LogTest - Sample warn message

# Pattern to output the caller's file name and line number.
%5p [%t] (%F:%L) - %m%n
 WARN [main] (LogTest.java:14) - Sample warn message

%d{ISO8601} [%t] %-5p (%F:%L) - %m%n 
 2013-07-24 21:55:03,407 [main] WARN  (LogTest.java:14) - Sample warn message

Appender's treshhold vs category

Treshhold is main filter, everything above Threshold value will go to appender. Then category can filter it further to priority's value.
In bellow example every logger in javax.slee.* package will be printed only if it is at least WARN level.

<appender name="CONSOLE" class="org.apache.log4j.ConsoleAppender">
<param name="Threshold" value="INFO"/>
...
</appender>

<category name="javax.slee">
<priority value="WARN" />
</category>


Ref:


Complete log4j.xml


<?xml version="1.0" encoding="UTF-8"?>

<!DOCTYPE log4j:configuration SYSTEM "log4j.dtd">



<log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/"

debug="true">



<appender name="consoleAppender" class="org.apache.log4j.ConsoleAppender">
<param name="Threshold" value="debug" />
<layout class="org.apache.log4j.PatternLayout">
<param name="ConversionPattern" value="%d [%t] %-5p (%F:%L) - %m%n"/>
</layout>
</appender>

<category name="org.mobicents" additivity="false">
<level value="warn" />
<appender-ref ref="consoleAppender" />
</category>

</log4j:configuration>

Thursday, June 20, 2013

PKI (public key infrastructure)

Public-key cryptography is a cryptographic technique that enables users to securely communicate on an insecure public network, and reliably verify the identity of a user via digital signatures.

Sender and receiver both have pair of private and public keys.

To send encrypted message sender is using reveiver's public key.
Prior to that he can encrypt signature using his private key.

Receiver needs to decrypt message using his private key.
To decrypt signature and to authenticate the sender he is using sender's public key.




Certificate Signing Requests (CSRs)
A CSR consists mainly of the public key of a key pair, and some additional information. Both of these components are inserted into the certificate when it is signed.

Whenever you generate a CSR, you will be prompted to provide information regarding the certificate. This information is known as a Distinguised Name (DN). An important field in the DN is the Common Name (CN), which should be the exact Fully Qualified Domain Name (FQDN) of the host that you intend to use the certificate with.


Ref:

Wednesday, May 8, 2013

Design Principles


  • Encapsulation is breaking your application into logical parts that have a clear boundary that allows an object to hide its data and methods from other objects.
  • Encapsulate what varies.
Information hiding (encapsulation) is important for many reasons, most of which stem from the fact that it decouples the modules that comprise a system, allowing them to be developed, tested, optimized, used, understood, and modified in isolation. This speeds up system development because modules can be developed in parallel. It eases the burden of maintenance because modules can be understood more quickly and debugged with little fear of harming other modules.

The rule of thumb is simple: make each class or member as inaccessible as possible.
  • Code to an interface rather than to an implementation (software is easier to extend).
  • Classes are about behaviour and functionality.
  • Open-Closed Principle (OCP) - classes should be open for extension (new functionality), and closed for modification. (keeps your software reusable, but still flexible) If you want to add new functionality you should extend the entity.
    • open for extension: new behaviour can be added to satisfy the new requirements 
    • close for modification: to extending the new behaviour are not required modify the existing code
  • Don't Repeat Yourself (DRY) - avoid duplicate code by abstracting out things that are common and placing those things in a single location. (DRY is about having each piece of information and behavior in your system in a single, sensible place)
  • Single Responsibility Principle (SRP) - every object in your system should have a single responsibility, and all the object's services should be focused on carrying out that single responsibility. 
    • Each class in your application should have only one reason to change. 
    • Cohesion is another name for SRP. 
    • High cohesion is the desirable state of a class whose members support a single, well-focused role or responsibility.
  • Liskov Substitution Principle (LSP) - subtypes must be substitutable for their base types. (ensures that you use inheritance correctly)
  • Delegation is when you hand over the responsibility for a particular task to another class or method. (If you need to use functionality in another class, but you don't want to change that functionality, consider using delegation instead of inheritance.)
  • Composition lets you choose a behavior from a family of behaviors, often via several implementations of an interface. (the composing object owns the behaviors it uses, and they stop existing as soon as the composing object does)
  • Aggregation is when one class is used as part of another class, but still exists outside of that other class.
  • Dependency inversion principle (DIP)
    • High level modules should not depend upon low-level modules. Both should depend upon abstractions.
    • Abstractions should never depend upon details. Details should depend upon abstractions.
Unlike method invocation, inheritance violates encapsulation. In other words, a subclass depends on the implementation details of its superclass for its proper function. The superclass’s implementation may change from release to release, and if it does, the subclass may break, even though its code has not been touched. As a consequence, a subclass must evolve in tandem with its superclass, unless the superclass’s authors have designed and documented it specifically for the purpose of being extended.
Instead of extending an existing class, give your new class a private field that references an instance of the existing class. This design is called composition because the existing class becomes a component of the new one. Each instance method in the new class invokes the corresponding method on the contained instance of the existing class and returns the results. This is known as forwarding, and the methods in the new class are known as forwarding methods. The resulting class will be rock solid, with no dependencies on the implementation details of the existing class. Even adding new methods to the existing class will have no impact on the new class. 

The features in your system are what the system does (they reflect system's functionality).
Use cases show how the system is used. 
Features and use cases work together, but features are not always reflected in your use cases.

SOLID (single responsibility, open-closed, Liskov substitution, interface segregation and dependency inversion) is a mnemonic acronym introduced by Michael Feathers for the "first five principles" named by Robert C. Martin in the early 2000s that stands for five basic principles of object-oriented programming and design.


Ref: 


Head-First-Object-Oriented-Analysis-Design
Effective Java
10 Object Oriented Design Principles Java Programmer should know
YAGNI - Martin Fowler
Core Design Principles for Software Developers by Venkat Subramaniam
SOLID Principles : The Definitive Guide
The Principles of OOD (UncleBob)

Monday, May 6, 2013

Disk Helper


Utility class for saving, opening and zipping files.

public class DiskHelper
{

/**
* saveToDisk i openFile
*/
public static void printFileObject(FileObject fo)
{
File file = saveToDisk(fo, fo.getFilename());
openFile(file);
}

public static File saveToDisk(FileObject fo, String fileName)
{
String pdfSuffix = "";
if (!fileName.contains(".pdf"))
{
pdfSuffix = ".pdf";
}

File file = new File("c://tmp//" + fileName + pdfSuffix);

int i = 0;
while (file.exists())
{
i++;
file = new File("c://tmp//" + fileName.replace(".pdf", "") + "_" + i + ".pdf");
}

System.out.println("file.exists: " + file.exists());

OutputStream os;
try
{
os = new FileOutputStream(file);
os.write(fo.getContent());
os.flush();
os.close();
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
return file;

}

public static void openFile(File file)
{
StringBuilder sb = new StringBuilder();
sb.append("cmd.exe /C start ");
sb.append(file.getAbsolutePath());
System.out.println("openFile: " + sb);
try
{
Runtime.getRuntime().exec(sb.toString());
}
catch (IOException e)
{
e.printStackTrace();
}
}

private static int byteValue = 1024;

/**
* http://www.mkyong.com/java/how-to-compress-files-in-zip-format/
*/
public static void zipFile(String fileName, File... files)
{
byte[] buffer = new byte[1024];

try
{
File zipfile = new File("C:\\tmp\\" + fileName + ".zip");
FileOutputStream fos = new FileOutputStream(zipfile);
ZipOutputStream zos = new ZipOutputStream(fos);

for (File file : files)
{
System.out.println("file.getName(): " + file.getName() + ", file.length(): " + file.length() / byteValue + " KB");
ZipEntry ze = new ZipEntry(file.getName());
zos.putNextEntry(ze);
FileInputStream in = new FileInputStream(file.getAbsoluteFile());
System.out.println("file.getAbsoluteFile(): " + file.getAbsoluteFile());

int len;
while ((len = in.read(buffer)) > 0)
{
zos.write(buffer, 0, len);
}

in.close();
}

System.out.println("zipfile.getName(): " + zipfile.getName() + ", zipfile.length(): " + zipfile.length() / byteValue + " KB");

zos.closeEntry();
zos.close();

System.out.println("Done");

}
catch (IOException ex)
{
ex.printStackTrace();
}
}

public static void deleteFiles(File... files)
{
for (File file : files)
{
file.delete();
}
}

}



public class FileObject
{
private String filename;
private byte[] content;

public byte[] getContent()
{
return content;
}

public void setContent(byte[] content)
{
this.content = content;
}

public String getFilename()
{
return filename;
}

public void setFilename(String filename)
{
this.filename = filename;
}

}

Wednesday, April 3, 2013

Charts

Web

-using IceFaces 1.8.2 (JSF 1.2)

<ice:form id="chartPopUp">
<ice:panelPopup draggable="true" modal="true" rendered="#{activeBackingBean.chartPopUpVisible}">
  <f:facet name="header">
  <table width="100%">
  <tr>
  <td>
  <ice:outputText value="Grafički prikaz" />
  </td>
  <td align="right">
   
  <ice:commandButton id="closeOdabirButton" styleClass="xButton" actionListener="#{activeBackingBean.closeChartPopUpVisibleAction}" />
  </td>
  </tr>
  </table>
   </f:facet>

  <f:facet name="body">
  <ice:outputChart id="chart" type="pie2D" 

        chartTitle="#{activeBackingBean.title}" 
        colors="green, red" 
        data="#{activeBackingBean.chartData}" 
        labels="#{activeBackingBean.chartLabels}"/>
  </f:facet>
</ice:panelPopup>
</ice:form>

BackingBean

private int totalOkDPTs;
private int totalNotOkDPTs;

public String getChartData()
{
return totalOkDPTs + ", " + totalNotOkDPTs;
}
public String getTitle()

public String getChartLabels()


Result


Jasper report

- using iReport 3.6.2

Select colors:
Pie Chart - Properties - Series Colors ...

Data to display:
Right click Chart and select Chart Data - Details - Pie series
In this example I have 2 series

Parameters:
totalOkDPTsPercentage - String
totalNotOkDPTsPercentage - String
totalOkDPTsPercentageNumber - Double
totalNotOkDPTsPercentageNumber - Double

pieSeries definition:
keyExpression - what displays in bottom (bottom label)
valueExpression - used for calculating and displaying (Number)
labelExpression - label with arrow (String)

jrxml code:

<pieChart>
<chart isShowLegend="true">
<reportElement x="98" y="28" width="375" height="205"/>
<chartTitle>
<titleExpression><![CDATA["Grafički prikaz"]]></titleExpression>
</chartTitle>
<chartSubtitle/>
<chartLegend/>
</chart>
<pieDataset>
<pieSeries>
<keyExpression><![CDATA["Ispravnih DPK - " + $P{totalOkDPTsPercentageNumber} +"%"]]></keyExpression>
<valueExpression><![CDATA[$P{totalOkDPTsPercentageNumber}]]></valueExpression>
<labelExpression><![CDATA["Ispravnih DPK"]]></labelExpression>
</pieSeries>
<pieSeries>
<keyExpression><![CDATA["Pogrešnih DPK - " + $P{totalNotOkDPTsPercentageNumber} +"%"]]></keyExpression>
<valueExpression><![CDATA[$P{totalNotOkDPTsPercentageNumber}]]></valueExpression>
<labelExpression><![CDATA["Pogrešnih DPK"]]></labelExpression>
</pieSeries>
</pieDataset>
<piePlot>
<plot>
<seriesColor seriesOrder="0" color="#00FF33"/>
<seriesColor seriesOrder="1" color="#FF0033"/>
</plot>
<itemLabel color="#000000" backgroundColor="#FFFFFF"/>
</piePlot>
</pieChart>

Result


Stackedbar Chart

I have people and 2 values for them, OK and NOK

Result:
Add stackedbar chart:
- define series colors, Legend position

Define chart details:
- I have added 2 series since I have 2 values (OK and NOK)


The Series expression field is the name of the series. Its value can be any object that implements java.lang.Comparable. In most cases, the value of this field is a string.   --OK

The Category expression field is the label of each value in the chart. The value of this field is typically a string. In our example, each state is a different category, so we will use the state field ($F{state}) as our category expression.   --People's name

The Value expression field is a numeric value representing the value to be charted for a particular category. In our example, the number of aircraft in a particular state is the value we want to chart. Therefore, we use the implicit stateGroup_COUNT variable ($V{stateGroup_COUNT}) as our value expression. --OK in 1 serie and NOK in 2nd

The optional Label Expression field allows us to customize item labels in the chart.