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: