Wednesday 26 December 2012

Site with calendar of professional events - lanyrd.com

If you are looking for a conference about development (but not only) look at lanyrd.com. You can there search for events by category or by location. With a host of events around the world, Lanyrd allows you to add events, discover new and exciting conferences and track your friends to see what events they are attending.
Try yourself: http://lanyrd.com/

Tuesday 27 November 2012

RateLimiter - limit amount of actions per seconds

Next useful utility from Guava library

A rate limiter. Conceptually, a rate limiter distributes permits at a configurable rate. Each acquire() blocks if necessary until a permit is available, and then takes it. Once acquired, permits need not be released.

Rate limiters are often used to restrict the rate at which some physical or logical resource is accessed. This is in contrast to Semaphore which restricts the number of concurrent accesses instead of the rate.

You can read more in guava javadoc:
http://docs.guava-libraries.googlecode.com/git/javadoc/com/google/common/util/concurrent/RateLimiter.html

Saturday 17 November 2012

Java Random thread save

Examples:
ThreadLocalRandom.current().nextInt()
ThreadLocalRandom.current().nextDouble()
...

TimeUnit class

If you want your java program to wait for defined time amount use class TimeUnit. It is more clean than using Thread.sleep.
Examples:
TimeUnit.NANOSECONDS.sleep(10)
TimeUnit.SECONDS.sleep(10)

Sunday 4 November 2012

Guava light cache

If you have a need to declare a small cache which have to be cleared periodically you can easily do it using Guava Cache.
We have to define loader that will load cache element and a period after which it will throw an item away. And then next read will use a loader to load an element into cache again. We can also define a cache in the way it will throw away an item if it was not read for a period of time.
Here is an example:
private LoadingCache<String, MyClass> cache;
CacheLoader<String, MyClass> loader = new CacheLoader<String, MyClass> () {
      public MyClass load(String key) throws Exception {
        return ourService.get(key);
      }
    };
cache = CacheBuilder.newBuilder().
        expireAfterWrite(1, TimeUnit.MINUTES).
        build(loader);

More about this subject here: http://code.google.com/p/guava-libraries/wiki/CachesExplained

Defining Mockito mock bean from Spring xml definition

You can define a spring bean in spring xml context that will be a Mockito mock of a given type:

  

But if you want to inject that bean by type, you have to define it as a Proxy of given interface:

    
      
        
      
    
    
      com.example.Repository
    
  

Monday 8 October 2012

Velocity Europe

I have attended Velocity Europe Conference. Here is what I learned:

Tools for web performance
News:
  • HTTP 2.0 - Will be decided what it will include in about a 1,5 year. It will be based mostly on SPDY
Useful tips:
  • Do not implement Javascripts that block. You can use option async + defer (for IE). Then it will not block your page load event, what makes your page beter for google robots and higher in google searches (Google has 3,5 seconds metric for Page Load). Every JS that does not block should be loaded in the bottom of the page and ones that block should be included on the top. Use Modernizr for javascript dependency
  • If you add a resource in the page starting with https://address or http://address, just use //address
  • Add performance metrics to DoD
  • Allow business to measure RUM (Real user monitoring)
  • Learn every day is the reason for working, otherwise change your work! (From facebook guy)
  • Take risk. Otherwise you want learn. (Same guy)
  • Site performance means money for business
  • It is better to develop a native application on the mobile if you want a fully featured one. It is almost impossible to have one fast rendering on Android and IPhone.
  • Do not keep server 200 days without restart. It is not updated or it can broke down. (That's why windows 95 had to be restarted. Some unix also had Magic number bug, so they worked only about 200 days)
See also:

An here is my photo: http://www.flickr.com/photos/oreillyconf/8071104092/in/set-72157631732025793








Thursday 20 September 2012

@RequestMapping view in STS

If you are working with STS and developing Spring MVC applications then you can try option Show View -> @RequestMapping. It will show you what urls are mapped for which Controllers and its methods.

Mercuryapp


Using MercuryApp

MercuryApp is simple to set up and use. It's like keeping a journal -- only simpler and with extra information!

Pick something to track, log your daily feelings, and get data that can help you improve your life and make better decisions.

More here: https://www.mercuryapp.com/get_started

Spring Framework 3.2 M2 Released

It contains changes to @Configuration classes, repackagaging all net.sf.cglib classes to org.springframework.cglib and inline them directly within the spring-core JAR.
Both of these upgrades are good news for JDK7 users writing Spring components in dynamic JVM languages, as these new versions of CGLIB and ASM properly handle the new invokedynamic bytecode instruction introduced in JDK7.

More is here: http://www.springsource.org/node/3654

Wednesday 12 September 2012

Coursera

Coursera is a social entrepreneurship company that partners with the top universities in the world to offer courses online for anyone to take, for free.
Now you can try https://www.coursera.org/course/progfun - Functional Programming Principles in Scala with Martin Odersky (author of Scala)

Saturday 1 September 2012

Java 7 Security Update

Java 7 Update 7 (and the corresponding Java 6 Update 35) are available to download.
It fixes security issue: http://www.oracle.com/technetwork/topics/security/alert-cve-2012-4681-1835715.html

Sunday 26 August 2012

Tools for analysis Garbage Collection

offline:
- GCHisto, GVViewer
online:
- VisualGC for VisualVM

Saturday 25 August 2012

DirtiesContext

Test annotation which indicates that the ApplicationContext associated with a test is dirty and should be closed:
  • after the current test, when declared at the method level
  • after each test method in the current test class, when declared at the class level with class mode set to AFTER_EACH_TEST_METHOD
  • after the current test class, when declared at the class level with class mode set to AFTER_CLASS
Read more here: http://static.springsource.org/spring/docs/3.0.x/javadoc-api/org/springframework/test/annotation/DirtiesContext.html

Jaxp13XPathTemplate - utility for extracting data by XPath fom XML

Jaxp13XPathTemplate - it is a java class from Spring Framework for extracting data by XPath from XML.

Example:
String id = xpathTemplate.evaluateAsString("/products/product/id", productRequest);

More here: http://static.springsource.org/spring-ws/site/apidocs/org/springframework/xml/xpath/Jaxp13XPathTemplate.html

Tuesday 21 August 2012

STS 3.0.0 released

SpringSource Tool Suites 3.0.0 has been released. It is reorganized, open-sourced, and put at GitHub.
Read more here: http://blog.springsource.org/2012/08/13/springsource-tool-suites-3-0-0-released-reorganized-open-sourced-and-at-github/

Saturday 11 August 2012

JDK 6 end of support extended

Oracle has announced that the End Of Public Updates for Oracle's JDK 6 has changed. It will be not November 2012. The last release of a JDK 6 update will be in February 2013.

More info here: https://blogs.oracle.com/henrik/entry/java_6_eol_h_h

Tuesday 7 August 2012

@SafeVarargs in Java 7

If you annotate method with an annotation @SafeVarargs, the compiler will suppress the warning of unsafe operation

Random number in java 7

Since java 7 you should use ThreadLocalRandom.current().nextInt() over Math.random() for generating random numbers. ThreadLocalRandom use random seed per thread, so threads do not compete for it.

Tuesday 31 July 2012

ArgumentCaptor in Mockito

Use it to capture argument values for further assertions.
It should be used during verifications. It is very useful when assert on argument values to complete verification.
It can also be fined through annotation: @Captor
More info here: http://docs.mockito.googlecode.com/hg/org/mockito/ArgumentCaptor.html
and : http://docs.mockito.googlecode.com/hg/org/mockito/Captor.html

Mockito Matchers

When using Mockito you can use MockitoMatchers. You can use predefined ones or create own implementation.
F.e.
assertThat(object, CoreMatchers.equalTo(0));
More examples as well as own implementations here: http://docs.mockito.googlecode.com/hg/org/mockito/Matchers.html

Cannot map request parameters as a Map parameter in Spring MVC

In Spring MVC you cannot map request parameters as a Map parameter in controller method using annotation @RequestParam
It is due to implementation of HandlerMethodInvoker.java, where Spring puts all parameters of the request to the parameter of Map type. Moreover the result map type is MultiValueMap or Linked HashMap.

CachingConnectionFactory for Spring JMS

CachingConnectionFactory is used as the proxy wrapping JMS Connection in the Spring JMS. It prevents from agressively closing and reopening JMS sessions and connections.
It is used for adding caching during usage Spring JMS templates.

<bean id="cachingConnectionFactory" class="org.springframework.jms.connection.CachingConnectionFactory">
  <property name="targetConnectionFactory" ref="connectionFactory"/>
</bean>

Creating directories hierarchical on Linux

Use
mkdir -p directory
to create directory with no error if existing and make parent directories as needed.

Monday 30 July 2012

@InjectMocks - Mockito

It is an annotation used in Mockito on the variable definition telling Mockito to try to inject by type already defined mocks or spies on the annotated object
f.e.:
@InjectMocks private MyService service = new MyService();

More info here: http://docs.mockito.googlecode.com/hg/org/mockito/InjectMocks.html

Actions throwing exceptions in Spring MVC

When an action in the Spring MVC throws exception, you can handle it with specifying http response code, by annotation on the exception class definition: @ResponseStatus(httpStatus).
When you cannot annotate class, f.e. it is not your exception definition, you can add in the controller a method which is annotated with @ExceptionHandler(yourExceptionClass) and @ResponseStatus(httpStatus)

Saturday 28 July 2012

Eclipse TCP/IP Monitor

It is a great tool for debugging Web Services. You can show it using CTRL+3 in the Eclipse. Use properties option for setting port that will forward request to an other port (the one used for the Web Service). You can use type of the output: XML, Byte, Web Browser, Image.

XJC - JaxB compiler

XJC is the compiler for JAXB Web Services. It generates classes from xsd file describing types in the Web Services communication.
Here is detailed information: http://docs.oracle.com/javase/6/docs/technotes/tools/share/xjc.html

Trang - opensource schema converter

You can use it to generate xsd files from example content.
More information here: http://www.thaiopensource.com/relaxng/trang-manual.html

Exposing Web Service WSDL in Spring WS

You can expose WSDL of the Service in the Spring WS using configuration:

<ws:dynamic-wsdl id="definitionName" portTypeName="Type" locationUri="http://host:8080/serviceName/">
<ws:xsd location="/WEB-INF/transfer.xsd"/>
</ws:dynamic-wsdl>

It generates WSDL from XSD file. The wsdl can now be accessed through: http://host:8080/serviceName/definitionName.wsdl

Project Jigsaw deferred until Java 9

Project Jigsaw, java modularity is going to be deferred until Java 9. Java 8 release time is September 2013. There is still to much to do to make the deadline.
The goal is: A standard module system for the Java Platform will ease the construction, maintenance, and distribution of large applications, at last allowing developers to escape the “JAR hell” of the brittle and error-prone class-path mechanism.

Chief Java architect on his blog describes the situation: http://mreinhold.org/blog/late-for-the-train.

Project Jigsaw home page: http://openjdk.java.net/projects/jigsaw/

Sunday 15 July 2012

CountDownLatch

CountDownLatch - A synchronization aid that allows one or more threads to wait until a set of operations being performed in other threads completes.
A CountDownLatch is initialized with a given count. The await methods block until the current count reaches zero due to invocations of the countDown() method, after which all waiting threads are released and any subsequent invocations of await return immediately. This is a one-shot phenomenon -- the count cannot be reset. If you need a version that resets the count, consider using a CyclicBarrier.

Javadoc here: http://docs.oracle.com/javase/1.5.0/docs/api/java/util/concurrent/CountDownLatch.html

CodePro Analytix

CodePro Analytix - is the premier Java software testing tool for Eclipse developers who are concerned about improving software quality and reducing developments costs and schedules. The Java software audit features of the tool make it an indispensable assistant to the developer in reducing errors as the code is being developed and keeping coding practices in line with organizational guidelines.

It is a google product which is free for commercial and non-commercial usage.

Try it whether it helps in your development. F.e. Dead Code function is not working good with Spring applications and annotations. Finding similar code for me is the best!
More info on : https://developers.google.com/java-dev-tools/codepro/doc/

Fidbugs for eclipse

Findbugs is a program which uses static analysis to look for bugs in Java code. It is free software, distributed under the terms of the Lesser GNU Public License. The name FindBugs™ and the FindBugs logo are trademarked by The University of Maryland. FindBugs has been downloaded more than a million times.
You can read hera how to install Fingbugs plugin for Eclipse: http://findbugs.sourceforge.net/manual/eclipse.html

FileCopyUtils

Simple utility methods for file and stream copying. All copy methods use a block size of 4096 bytes, and close all affected streams when done.
More on: http://static.springsource.org/spring/docs/1.2.x/api/org/springframework/util/FileCopyUtils.html

Wiser - for testing mails by JUnit

Wiser is a simple SMTP server that you can use for unit testing applications that send mail. It accepts all messages and stores them in an internal ArrayList. Your unit test code can then examine the messages (or lack thereof) and verify their validity.
More on: http://code.google.com/p/subethasmtp/wiki/Wiser

Saturday 14 July 2012

ResourceDatabasePopulator

ResourceDatabasePopulator - useful class for populating a database from SQL scripts defined in external files.
Javadoc : http://static.springsource.org/spring/docs/3.0.0.M3/javadoc-api/org/springframework/jdbc/datasource/embedded/ResourceDatabasePopulator.html

Friday 13 July 2012

XmlUnit - JUnit testing for XML

XMLUnit for Java provides two JUnit extension classes, XMLAssert and XMLTestCase, and a set of supporting classes (e.g. Diff, DetailedDiff,Transform,SimpleXpathEngine,Validator,NodeTest) that allow assertions to be made about:
  • The differences between two pieces of XML
  • The outcome of transforming a piece of XML using XSLT
  • The evaluation of an XPath expression on a piece of XML
  • The validity of a piece of XML
  • Individual nodes in a piece of XML that are exposed by DOM Traversal
XMLUnit for Java can also treat HTML content (even badly-formed HTML) as valid XML to allow these assertions to be made about the content of web pages too.

More information in the tutorial: http://xmlunit.sourceforge.net/userguide/html/index.html

Hazelcast - more then distributed cache

Hazelcast is an open source clustering and highly scalable data distribution platform for Java, which is:
  • Lightning-fast; thousands of operations/sec.
  • Fail-safe; no losing data after crashes.
  • Dynamically scales as new servers added.
  • Super-easy to use; include a single jar.

With its various distributed data structures, distributed caching capabilities, elastic nature, memcache support, integration with Spring and Hibernate and more importantly so many happy users, Hazelcast is feature-rich, enterprise-ready and developer-friendly in-memory data grid solution.

To run it you just run a single jar file!

Presentation is available here: http://www.hazelcast.com/screencast.jsp

JUnitParams - librabry for JUnit

This project adds a new runner to JUnit and provides much easier and readable parameterised tests for JUnit >=4.6.

Main differences to standard JUnit Parameterized runner:

  • more explicit - params are in test method params, not class fields
  • less code - you don't need a constructor to set up parameters
  • you can mix parameterised with non-parameterised methods in one class
  • params can be passed as a CSV string or from a parameters provider class
  • parameters provider class can have as many parameters providing methods as you want, so that you can group different cases
  • you can have a test method that provides parameters (no external classes or statics anymore)
  • you can see actual parameter values in your IDE (in JUnit's Prameterized it's only consecutive numbers of parameters):

More on project page: http://code.google.com/p/junitparams/

Bending the Java spoon - op4j

op4j is a powerful implementation of the Fluent Interface style of code. It allows you to create chained expressions which apply both predefined or user-defined functions to your objects in a fluid and readable way. This improves the way your code looks and greatly reduces the complexity of executing auxiliary low-level tasks in the highly bureaucratic, statically -and strongly- typed language that Java is.
It is a great library for complicated operations on Collections in one line.
More on: http://www.op4j.org/

Tuesday 10 July 2012

Do not implement/generate getters and setters!

Project lombok is a java library which prevents you from implementing or generating getters and setters for POJOs. You just add annotation on the class or on the individual property. Having such code, that just gets and sets properties is unmaintainable and bad for class clarity.
This library has also some other useful features like f.e. @Delegate - annotation that ease creating classes with delegation methods.

Here you can see examples:http://projectlombok.org/features/index.html

Tomcat startup takes extra 3 minutes. Why?

I have faced a problem of long startup of tomcat 7 that used jvm 7 on the linux server. Tomcat without any application started over 3 minutes. In the catalina.out log there was a message:
May 22, 2012 10:02:48 AM org.apache.catalina.util.SessionIdGenerator createSecureRandom
INFO: Creation of SecureRandom instance for session ID generation
using [SHA1PRNG] took [131,611] milliseconds.
This problem appears due to Tomcat 7+ usage of SecureRandom class to provide random values for its session ids. You can use non-blocking setup, just set the following system property: -Djava.security.egd=file:/dev/./urandom
You can read more on this subject in tomcat wiki: http://wiki.apache.org/tomcat/HowTo/FasterStartUp

Monday 9 July 2012

Invoke dynamic in java 7

Recently I have attended Confitura 2012 a Java Conference in Warsaw. One of the most interesting lectures was the one made by Waldemar Kot. He has introduced subject of the new instruction in Java 7: Invoke dynamic.
He has shown that it has a very big impact on the java development, not only on dynamic languages on JVM. Using invoke dynamic in java you can have dynamic behavior with speed comparable to static invocation.
You can see examples and benchmarks here: https://github.com/waldekkot/Confitura2012_InvokeDynamic

Wednesday 4 July 2012

Let's try implement an algorithm

If you want to train implementing algorithms you can go to the Project Euler.

Project Euler is a series of challenging mathematical/computer programming problems that will require more than just mathematical insights to solve. Although mathematics will help you arrive at elegant and efficient methods, the use of a computer and programming skills will be required to solve most problems.

The motivation for starting Project Euler, and its continuation, is to provide a platform for the inquiring mind to delve into unfamiliar areas and learn new concepts in a fun and recreational context.

Corkboard online

If you want to have a place to stick your notes in the virtual then you can try: http://corkboard.me

Rod Johnson has left SpringSource

Rod Johnson the father of Spring, co-founded SpringSource has decided to leave SpringSource. He grew a company building a Spring Framework a better Java Enterprise Edition.
His leaving post: blog.springsource.org/2012/07/03/oh-the-places-youll-go/

Sunday 1 July 2012

Exposing monitoring by JMX in Spring application

To expose methods as MBeans in the Spring Application by JMX you have to:
  • Declare in the application configuration: <context:mbean-export/>
  • Annotate java class with @ManagedResource
  • Annotate getters or setters with <@ManagedAttribute>
After that you can connect by jconsole to your application and use annotated methods.
You can also use annotations: @ManagedOperation, @ManagedNotification for methods that are not setters or getters.

Wednesday 27 June 2012

Denial of service via hash algorithm collision

A variety of programming languages suffer from a DoS via hash algorithm collision. If the implementation of the hash calculation is expensive, then creating POST request with many collisions can cause DoS. POST request has no limit then 8GB.
Java is affected. Webservers Tomcat and Jetty have been protected by limiting number of POST Request parameters.
More info on: http://www.ocert.org/advisories/ocert-2011-003.html

Friday 22 June 2012

Spring Framework Known Vulnerabilities and Issues

Here is the page where we can read about critical insecure versions of Spring Framework. If you use them better upgrade Spring Framework version. http://www.springsource.com/security/spring-framework

Thursday 14 June 2012

Lucidchart - Comments

Lucidchart has new features:
  • Commenting system - Comments panel for adding comments to the diagram
  • Integration to Confluence OnDemand
More on: http://www.lucidchart.com/blog/2012/06/12/introducing-comments-and-lucidchart-for-ondemand-confluence/

Usefull git commands

  • git config --global color.ui auto - add coloring for git command line
  • git pull --rebase - it makes sense to be the default for pulling from the remote repository
  • git merge --no-ff - does not forget about branch which was merged in even if it was fast forward one
  • git rm --cached file - removing file only from git, not form file system
  • git diff --cached - see what will go in the next commit
  • git branch --no-merged - branched that are not merged
  • git rebase master - rebasing current branch against master
  • git mergetool - invoking tool for merging
  • git stash - hiding temporary files changes e.g. for rebasing
  • git stash pop - uncover changes hidden by stash command
  • git reset HEAD file - reset staged changes to the file
  • git checkout HEAD file - removing changes to the file

Tuesday 3 April 2012

Java performance tuning

On the following page you will find many articles about java performance tuning. Tips, tools descriptions, ...
http://www.javaperformancetuning.com

Monday 26 March 2012

Uncle Bob says

Last week I attended training Clean Code lead by Robert Martin known as Uncle Bob. He is a software professional since 1970, a consultant and an author of many bestsellers concerning software development e.g.
  • Designing Object-Oriented C++ Applications using the Booch Method. Prentice-Hall. 1995. ISBN 0-13-203837-4.
  • Agile Software Development: Principles, Patterns and Practices. Pearson Education. 2002. ISBN 0-13-597444-5.
  • Clean Code: A Handbook of Agile Software Craftsmanship. Prentice Hall PTR. 2008. ISBN 0-13-235088-2.
  • The Clean Coder: A Code of Conduct for Professional Programmers.

Here is my summary of the course:

  • Software engineers' job is to write code. It is the document of the systems we provide.
  • Our work is to do things well. Managers defend the schedule, but our job is to defend the code with equal passion. Quality needs time! They want the truth even if they don't like it.
  • Architecture's aim is separation of relevant things from irrelevant ones.
  • Yoda was right! Do or do not. There is no try. Decide. Don't lose time.
  • The only good measure of clean code is the quantity of WTF per minute while working with this code.
  • To keep in shape as a developer you have to practice. Have your programming Kata. Practice regularly solving programming problems. e.g. try developing sorting of an array.
  • Always start coding by writing a test. TDD allows you to develop faster. Coverage of code written using TDD is nearly 100%! Maintenance of such code is easier and refactoring can be proven to be correct.
  • As test gets more specific, the code gets more general. (Described here: http://cleancoder.posterous.com/the-transformation-priority-premise)
  • Long live variables which are searchable should have long names, short live ones should have short names.
  • Consider factors methods instead of constructors. Complex.FromRealNumber(23.4) oposed to new Complex(23.4). It is more readable.
  • Use methods String.format. It will generate strings with correct end of lines. Just use %n as a line break.
  • Don't use brackets if you don't need to.
  • Write as small functions as possible. If some lines of function can be extracted as another function, do it. Three, four, five lines for a function is best. It will be more readable.
  • Functions should do one thing.
  • While refactoring, remember also to change variables' names to correspond with their usage.
  • Name of the function can be long. It should describe its action. It is better than adding an additional comment.
  • Short function names should be used for bigger scope (like File.open) whereas long function names should be used for small private scopes.
  • Use convention for test methods: whenBuyOneBook. Your method will be like a sentence: When action, we assert results.
  • Use as small arguments of the function as possible. More than a three are rarely justified.
  • Avoid functions with side effects like the ones that change variables of their class, passed arguments or system globals.
  • Prefer exceptions to returning error code.
  • Extract try catch blocks into functions.
  • Clean code doesn't need comments, or only residual ones. Usually we have them too many so IDE changes its color to grey by default. Change color of comments to red, so you will keep them simple, they will strike your eyes.
  • Every use of comment represents a failure of expressing ourselves in code. Use comments as a last resort.
  • When you write bad code, don't comment it. Clean it!
  • Good comments: legal statements, allowed string patterns (like hh:mm:ss), description of intents.
  • Avoid TODO comments. Most frequently they are left forever.
  • Don't add author in comments. Control system is used for this.
  • Don't add html in the comments. It will be harder to read where it is read, I mean in code. If you need it for javadoc then use pre tag.
  • Decouple code into many files. Too long files are wrong.
  • Keep related variables and functions close to each other
  • We prefer 25-40 chars line lengths.
  • Team should agree on the formatting rules. Code should look like written by the team not a group of individuals.

Sunday 25 March 2012

Android Lint - Firebugs for Android applications

Android Lint is a new tool introduced in ADT 16 (and Tools 16) which scans Android project sources for potential bugs. It is available both as a command line tool, as well as integrated with Eclipse. The architecture is deliberately IDE independent so it will hopefully be integrated with other IDEs, with other build tools and with continuous integration systems as well.
http://tools.android.com/tips/lint

Friday 23 March 2012

Synchronized block

In java we can add keyword synchronized on the method definition to allow only one thread to execute all object's methods with synchronized at once.
So it looks like this:
  synchronized void add() {
    // some code
  }
It is the same as:
  void add() {
    synchronized(this){
      // some code
    }
  }

When we want to synchronize on the static method we can synchronize on the class object:
  static void add() {
    synchronized(MyClass.class){
      // some code
    }
  }

But it is much more secure to synchronize on the static private object. So only our object can use this lock. On the class object which is public any thread from any piece of code could do it.
So better use this lock:

  private static final Object lock = new Object(); 

  static void add() {
    synchronized(lock){
      // some code
    }
  }

Lazy initialization in java

Lazy initialization in java can be done in different ways.
  • In java we can use keyword volatile. This attribute on variable guarantees that any thread will see the most recently written value. From Java 5 version it can be used f.e. for lazy initialization in a multi-threaded environment.
  • Another way to do this is to use inner classes. This relies on the fact that inner classes are not loaded until they are referenced. So we can make assignment in the inner class.
  • We can also use synchronized block, but it is estimated to be 100 times slower then using volatile variable.
You can see more examples here: http://en.wikipedia.org/wiki/Double-checked_locking

Wednesday 21 March 2012

GEB - browser automation solution

Geb is a browser automation solution.
It brings together the power of WebDriver, the elegance of jQuery content selection, the robustness of Page Object modelling and the expressiveness of the Groovy language.
Read more on the project home page: http://www.gebish.org/

RemoteWebDriver

You can test UI automation tests with WebDriver for browsers that are not installed on your machine. Use RemoteWebDriver.
Read more on: http://code.google.com/p/selenium/wiki/RemoteWebDriverServer

Cache strategies

  • Write through - write-to-cache operation will return after writing to memory and also writing on disk
  • Write behind - write-to-cache operation will return after modifying memory, but it wont wait until write-to-disk finishes. Writing to disk can be delayed. This strategy allows better performance, but it has to deal with failures.

Saturday 10 March 2012

Analysing Thread Dumps

Tool for Thread Dumps analyzing: TDA - Thread Dump Analyzer. Plugins for JConsole and VisualVM available. More on: http://java.net/projects/tda/

Friday 9 March 2012

Analysing garbage collection from gc.log

If you wish to visualize garbage collection using as a source gc.log file, then try HPjmeter. You will see diagrams, which makes those data more clear.
For more info and download link go to: https://h20392.www2.hp.com/portal/swdepot/displayProductInfo.do?productNumber=HPJMETER

Thursday 8 March 2012

Java 1.6 End Of Life

Oracle has informed about Java 1.6 End Of Life.
The EOL date of Java SE 6 is November 2012. EOL doesn't mean you can't use a Java release. EOL just means the end of public support and fixes, and for that reason, you are encouraged to update to the latest stable release(Java SE 7 has great features and enhancements!). If you need support after the EOL, you can get Java SE Support from Oracle.

Deadline has been changed
See an update here:http://just4java.blogspot.com/2012/08/jdk-6-end-of-support-extended.html

Sunday 4 March 2012

Alfresco Debuts Alfresco Add-ons Market

Alfresco announced the availability of Alfresco Add-ons. The Add-ons marketplace is a large collection of customizations and extensions for the Alfresco platform contributed by the company's global developer community. The new market is designed to be a one-stop shop for Alfresco users looking to extend the functionality of Alfresco with pre-built modules.
More info on: http://www.alfresco.com/media/releases/2012/02/addons/

Thursday 16 February 2012

soapUI

Tool for testing WebServices: soapUI. You can use it as a separate application (which is a paid version) or for free as an Eclipse plugin.
More info on eclipse version is here: http://www.soapui.org/IDE-Plugins/eclipse-plugin.html

Saturday 11 February 2012

Invoke webservice in java

To invoke WebService in java without any WS library, just using HttpURLConnection you can act like here:
   URL url = new URL(address);
   HttpURLConnection rc = (HttpURLConnection) url.openConnection();
   rc.setRequestMethod("POST");
   rc.setDoOutput(true);
   rc.setDoInput(true);
   rc.setRequestProperty("Content-Type", "text/xml; charset=utf-8");
   int len = soapEnvelope.length();
   rc.setRequestProperty("Content-Length", Integer.toString(len));
   rc.setRequestProperty("SOAPAction", soapAction);
   rc.connect();
   OutputStreamWriter out = new OutputStreamWriter(
     rc.getOutputStream());
   out.write(soapEnvelope, 0, len);
   out.flush();
   InputStreamReader read = new InputStreamReader(rc.getInputStream());
   StringBuilder returns = new StringBuilder();
   int ch = read.read();
   while (ch != -1) {
    returns.append((char) ch);
    ch = read.read();
   }
   read.close();
   rc.disconnect();

ExecutorService

To easily run many Threads in java ExecutorService can be used. It is an abstraction for creating a pool of threads for running tasks. Tasks can return results in Future object. We can create Thread pools using methods of class Executors. There are plenty of options: amount of Threads to use, rise of ones,...
More details can be found on: http://docs.oracle.com/javase/6/docs/api/java/util/concurrent/ExecutorService.html

An example of using these construction is here:
import java.util.Date;
import java.util.Random;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class ExecutorServiceExample {

 final int size = 20000000;

 private long[] arr = new long[size];

 class Task implements Callable {

  private int index, range;

  public Task(int index, int range) {
   this.index = index;
   this.range = range;
  }

  public Boolean call() throws Exception {
   boolean ret = false;

   for (int i = index; i < index + range; i++) {

   }

   return ret;
  }

 }

 public ExecutorServiceExample() {
  Random random = new Random(new Date().getTime());
  for (int i = 0; i < size; i++) {
   arr[i] = random.nextLong();
  }
 }

 public static void main(String[] args) {

  ExecutorServiceExample ese = new ExecutorServiceExample();
  ese.findSeq(123456789012345678l);
  ese.findConcur(123456789012345678l);

 }

 private boolean check(int i, long val) {
  if (arr[i] * val * val == val * val * val) {
   System.out.println("Found:" + i);
   return true;
  }
  return false;
 }

 private void findConcur(long val) {
  int range = 100;
  long start = new Date().getTime();
  ExecutorService service = Executors.newFixedThreadPool(100);

  for (int i = 0; i < size / range; i++) {
   service.submit(new Task(i * range, range));
  }
  service.shutdown();
  System.out.println("Seq in " + (new Date().getTime() - start));
 }

 private void findSeq(long val) {
  long start = new Date().getTime();
  for (int i = 0; i < size; i++) {
   check(i, val);
  }
  System.out.println("Seq in " + (new Date().getTime() - start));
 }
}

To run this example you will probably need to add parameter to increase heap size (f.e. -Xmx1300m)

Thursday 9 February 2012

Exposing variables by JMX in Spring Applications

If you wish to expose variable by JMX in the Spring application you have to:
  1. Add in the spring context the tag:
    <context:mbean-export/>
  2. On the managed class add annotation @ManagedResource
  3. On this method you want to be exposed add annotation
    • For getters and setters - @ManagedAttribute
    • For all type of operations - @ManagedOperation

Multitenancy

Multitenancy refers to a principle in software architecture where a single instance of the software runs on a server, serving multiple client organizations (tenants). Multitenancy is contrasted with a multi-instance architecture where separate software instances (or hardware systems) are set up for different client organizations. With a multitenant architecture, a software application is designed to virtually partition its data and configuration, and each client organization works with a customized virtual application instance.

Sunday 5 February 2012

Adding Google Reader subscribe button

If you want to add in the webpage the button to subscribe RSS by Google Reader, then use this page: http://www.google.com/webmasters/add.html. There you can put the url to your RSS in one field and generate the HTML code needed to be inserted into the web page content. That's all!

How to escape HTML?

To escape HTML for usage in blogs, web pages, ... you can use: http://www.blogcrowds.com/resources/parse_html.php

Saturday 4 February 2012

How to highlight code syntax in the blogger? Use SyntaxHighlighter!

I decided to use a library for highlighting code syntax. I have found SyntaxHighlighter. To install it you have to add some script in the html code. For my case I wanted to use it for java and xml code.
Here is what I have added (you can use hosted files or files from your server):
<script src='http://alexgorbatchev.com/pub/sh/current/scripts/shCore.js' type='text/javascript'/>
<script src='http://alexgorbatchev.com/pub/sh/current/scripts/shBrushJava.js' type='text/javascript'/>
<script src='http://alexgorbatchev.com/pub/sh/current/scripts/shBrushXml.js' type='text/javascript'/>

<link href='http://alexgorbatchev.com/pub/sh/current/styles/shCore.css' rel='stylesheet' type='text/css'/>
<link href='http://alexgorbatchev.com/pub/sh/current/styles/shThemeDefault.css ' rel='stylesheet' type='text/css'/>
<script type='text/javascript'>
     SyntaxHighlighter.all()
</script>
Then you just need to put your code inside pre tag:
<pre class="brush: java">
  int add(int a, int b) {
     return a + b;
  }
</pre>
And you will get:
  int add(int a, int b) {
     return a + b;
  }
More info on the SyntaxHighlighter home page: http://alexgorbatchev.com/SyntaxHighlighter/
More on installation is described on: http://alexgorbatchev.com/SyntaxHighlighter/manual/installation.html
List of languages whose syntax are implemented are here: http://alexgorbatchev.com/SyntaxHighlighter/manual/brushes/

Thursday 2 February 2012

Lucidchart diagrams

If you are in need to create a diagram and you have no tool for it, try http://www.lucidchart.com/. Your browser is enough. You can draw Flowcharts, UML Diagrams, Mid Maps, Organisation Diagrams and others.

Thursday 26 January 2012

Spring Integration 2.1

Spring Integration 2.1 has been released. The main new features of 2.1 include: RabbitMQ/AMQP, GemFire, Redis, and MongoDB, JSR-223 Scripting, Stored Procedure, and Spring Payload Enricher. Also included is FTP and SFTP Outbound Gateways and Migrating from Spring Integration 2.0.
Here is Spring Integration Homepage: http://www.springsource.org/spring-integration
Maven configuration for Spring Integration: http://www.springsource.org/node/2962

Tuesday 17 January 2012

AtomicInteger

AtomicLong, AtomicInteger, AtomicBoolean - these are java classes from package java.util.concurrent.atomic that can be used when atomic access to an object is needed.

Guava library

Some useful classes and methods from Guava library:
  • Charset.UTF_8, Charsets.UTF_16, ... - helpers for creating Charset class
  • Defaults.defaultValue(Class) - default value of given class
  • ImmutableSet, ImmutableList, ImmutableMap - builders for collections types f.e. List list = ImmutableList.of("1","2");
  • Joiner - for concatenating Strings
  • Strings.emptyToNull, Strings.nullToEmpty - String converters
  • Objects.equal(val1,val2) - returns if objects are equal
  • Objects.hashCode(...) - generates hashCode from list of objects
  • Objects.toStringHelper - utility for creating toString methods
  • Preconditions - methods for checking conditions on objects, if not meet then an Exception is thrown
  • Files - utility for file operations. copy (coping files), equals (files content is equal), getCheckSum (file check sum), getFileExtension, move (moving file in the file system), newReader (creates reader object on the file), newWriter (creates writer object on the file), readLines (returns list of strings), toBytesArray (array of bytes for file), toString (whole file as string), touch (touch on file in filesystem)
  • Closeables.closeQuietly - close stream without throwing IOException
  • Flushables.flushQuietly - flush without throwing IOException
  • BiMapsm - bidirectional map
  • MultiMaps, MultiLists - many implementations of multimaps multilists
  • Hashing, HashFunction - utilities for creating hash functions, usage of md5 calculation
  • IntMath, LogMath, DoubleMath, BigIntegerMath - operations tested for overflow, using hardware details for efficiency
  • CacheBuilder - for easy creating caches that expire after given time, amount, with other parameters
  • Cache.stats - for getting statistics of the cache object

More details on Guava library home page: http://code.google.com/p/guava-libraries/

Sunday 15 January 2012

Changing CXF WebService address

In the Apache CXF we do not have a constructor to create web service with local wsdl file or address to the web service which would override the default one. But we can do it on the constructed object. Here is an example:
WebServicesSoap port = service.getWebServicesSoap();
BindingProvider bindingProvider = (BindingProvider) port;
bindingProvider.getRequestContext().put(BindingProvider.ENDPOINT_ADDRESS_PROPERTY, webServiceAddress); 

Changing Eclipse project into a Java Project

In the .project file add java nature and builders:
<projectDescription>
    <buildSpec>
        <buildCommand>
                <name>org.eclipse.jdt.core.javabuilder</name>
                <arguments>
                </arguments>
        </buildCommand>
    </buildSpec>
    <natures>
        <nature>org.eclipse.jdt.core.javanature</nature>
    </natures>
</projectDescription>
and in the .classpath file add Java libs reference:
<classpath>
    <classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER"/>
</classpath>

Sunday 8 January 2012

Commons-collections library

Here are some useful features from commons-collections library:
  • CollectionUtils, MapUtils- for intersection, counting, iteration on collections and maps
  • BidiMap - supports bidirectional maps
(Version 3.2.1) More info on: http://commons.apache.org/collections/userguide.html

Common-lang library

Some useful classes and methods from the library commons-lang:
  • StringUtils - methods to manipulate on Strings
  • StringEscapeUtils - methods to escape and unescape Java, JavaScript, HTML, XML and SQL
  • WordUtils - methods to manipulate on Strings on level of words
  • CharEncoding.isSupported - method checking if encoding is supported by System
  • SystemUtils - methods checking java version used, java home, java IO temporary directory, user directory
  • SerializationUtils - methods for object serialization and desarialization
  • ObjectUtils - null-safe implementation of methods comparing objects
  • ClassUtils - helper methods on classes definition
(Version: 3.1) More info on: http://commons.apache.org/lang/userguide.html

How to define an annotation in java?


Just like creating a java interface, create f.e. a file ExampleAnnotation.java with the following code:

@Retention(RetentionPolicy.CLASS)
@Target(ElementType.METHOD)
public @interface ExampleAnnotation
{
// Property Definition here.
}

You have to add the following annotations in the definition:
  • Target - define where annotation can be added (methods, class, fields, properties, constructor, local variable, package, annotation type)
  •  Retention - where annotation will be available (only in source, in class definition, also in runtime)

Tuesday 3 January 2012

Shortcuts for Copy & Paste in Cygwin

After installing Cygwin on Windows system we don't have easy shortcuts for Copy & Paste. In Windows's console window, open the properties dialog. The options contain "Quick edit mode". It must be set. Save the properties. Now selecting with the left-mouse you also copy, and with the middle-mouse you paste.

Sunday 1 January 2012

New release of Astah

There is a new version of Astah, software for building UML 6.5.1
Download is available from: http://www.astah.net/download#professional

We can use also an Astah's plug-in for Atlassian Confluence: https://plugins.atlassian.com/plugin/details/815022