Showing posts with label java. Show all posts
Showing posts with label java. Show all posts
Monday, January 30, 2017

Java recipe: Initialize an ArrayList with zeros

It's often useful to have a list filled with zeros of the specified length N.
Why would you want one? Well, it's handy during the work with algorithms, or just to avoid null checks.
Usually, instead of the List filled with 0s an Array is enough: new int[N]
- creates an array of N integers with zero value.
new ArrayList(N) (has the size 0) is NOT the same as new int[N] (has the length N)

- The integer passed to the constructor of list represents its initial capacity (the number of elements it can hold before it needs to resize its internal array) which has nothing to do with the initial number of elements in it.
Whatever, below are the bunch of ways to create the List filled with zeros, if you need one.
In each example we will create a list filled with 100 zeros. (Java8 implementation with StreamAPI included).
Friday, July 15, 2016

Java recipe: Find duplicates in your List

Examples to count and receive duplicate objects in a list.
Wednesday, April 27, 2016

Regex Recipe: Normalize URL

This recipe describes how to replace multiple slashes in URL & avoid replacing the first // in http:// & https://.

Expected behaviour

To send some concatenated url with multiple slashes and recive the clean one.

Given Input:
http://devcdn.some-hub.net/html5//280131/publish///brand/bundle/games/
Expected Output:
http://devcdn.some-hub.net/html5/280131/publish/brand/bundle/games/
Monday, April 11, 2016

Java Recipe: Read resource file as a String.

This recipe shows how to load the file from the resource folder and receive it's content as a String.

Project structure

|--src
|  \--main
|       \--java
|       \--resources 
|          |--lines.json

Get file path from resources folder

In order to receive the resource with given name we need to use java.lang.ClassLoader:
Wednesday, February 10, 2016

Keynotes: Derive JPA query from method name

JPA lookup

The JPA module supports defining a query or native query manually as String (using @NamedQuery/@NativeNamedQuery/@Query annotations) or have it being derived from the method name.

Default lookup strategy is CREATE_IF_NOT_FOUND, which combines combines CREATE and USE_DECLARED_QUERY ones. It looks up a declared query first, and if no declared query is found, it creates a custom method name-based query.
Spring Data repository query building mechanism allows quick query definition by method names & custom-tuning of it by introducing declared queries as needed.
Monday, February 1, 2016

Java: Convert JSON to DTO Object

Use Jakson

U can convert JSON to DTO and back automatically with ObjectMapper:
  • Convert Java object to JSON, writeValue(...)
  • Convert JSON to Java object, readValue(...)
  • Convert JSON to List of Java objects, readValues(...)
U can use field with different name with @JsonProperty(...) annotation.
U can skip unneeded properties with the following method: configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);

Java: Authenticate via HttpClient 4

It's often might be needed to get/post some info from the third party sites via HTTP. But, most of the times you have to be signed into that web-resources.
Friday, January 29, 2016

Check HTTP Response Status for Success

All HTTP 2xx mean successful status codes.
So, it's fairly easy to check, but a bit harder to not duplicate those checks everywhere:)
Tuesday, January 19, 2016

Java: Forget About JSP

I hope that you already have forgotten about JSF (JavaServer Faces) :)
Not long time ago, all feeds were overloaded by post about, why everyone has to stop using JSF. However JSP (JavaServer Pages) is usually a kind of pain in ass for developers as well, because it's badly readable, not reusable, different from html syntax, not obvious, coupled, etc.

So, here is a better way, that should be chosen in favour of JSP:

Themeleaf

Thymeleaf is a Java library. It is a template engine capable of processing and generating HTML, XML, JavaScript, CSS and text, and can work both in web and non-web environments. It is better suited for serving the view layer of web applications, but it can process files in many formats, even in offline environments.

It provides an optional module for integration with Spring MVC, so that you can use it as a complete substitute of JSP in your applications made with this technology, even with HTML5.
As mentioned above, Thymeleaf is well integrated with Spring and allows more intuitive way to handle views part, which makes it's quite easy usable & useful especially for small fast projects.
Monday, January 18, 2016

Web Resource Optimizer for Java (Wro4j)

Wro4j is a tool for analysis and optimization of web resources. It brings together almost all the modern web tools: JsHint, CssLint, JsMin, Google Closure compressor, YUI Compressor, UglifyJs, Dojo Shrinksafe, Css Variables Support, JSON Compression, Less, Sass, CoffeeScript and much more.
So, basically it allows to organize static resources in groups, minify & combine those into common file, which simplifies it's including into your webpages.

See Simple 3 Steps usage explanation directly on Wro4j - Github
Friday, November 13, 2015

Benchmarks in Java (Know what u're measuring)

Accurate Benchmark

It's often needed to know whether the certain operation is faster than another one(especially to argue with somebody on code review:)).
Probably the most of the fast self-written benchmark tests are incorrect because of side factors, that were not considered.
Here are few points we have to consider before start doing better:
  • JVM warmup at start an execution is slow and becomes faster and faster until it goes to steady-state;
  • Just In Time Compiler optimizes the code, so your measures become wrong;
  • Garbage Collector GC could act during your measure so it'll affect the results;
  • Class loading First execution time usually includes the loading of all classes it uses, cause JVM typically loads classes only when they're first used;
  • False Sharing Might happen when u try to read 2 adjacent fields from 2 or more threads at the same time (those could contend with each other on the hardware level)
  • Caching CPU cache, File system cache, Memory access optimizations.

There is a fairly simple and useful Code Tool by Open JDK called JMH supposed to simplify & optimize the benchmarks writing & running (references are in the end of page).
Monday, November 2, 2015

Spring: Validate specific model attributes

Apply @InitBinder to specific commands

Validators will not be called unless your parameter has a @Valid annotation.
By default initBinder method will be invoked for every parameter (model attributes).
@InitBinder has an optional attribute where you can specify the specific attribute(s) to apply the method.

Te value of @InitBinder can be one of the following:
  • name of a model attribute;
  • name of a request parameter;
  • name of the class of parameter can be used, but starting with a small letter. That's how Spring exposes unnamed attributes to the model.
Wednesday, October 28, 2015

Storing created & last updated properties

Created & Last Updated properties

Whenever u're dealing with some accounts, transactions, product items, notes, reviews, etc. it's always useful to know when those where created & last updated/edited/modified.

Notice, that it's always better to fill such properties on the Back-End side rather than on the Front-End. Otherwise, the client can exchange the data & try to store some invalid values. Actually even if the client will send the valid dates, those will not reflect exact time when the data was added in the DB.
Friday, September 25, 2015

Keynote: Use Vagrant - forget "works on my machine" bugs

Vagrant


If you're a developer, Vagrant will isolate dependencies and their configuration within a single disposable, consistent environment, without sacrificing any of the tools you're used to working with (editors, browsers, debuggers, etc.). Once you or someone else creates a single Vagrantfile, you just need to vagrant up and everything is installed and configured for you to work. Other members of your team create their development environments from the same configuration, so whether you're working on Linux, Mac OS X, or Windows, all your team members are running code in the same environment, against the same dependencies, all configured the same way.
Say goodbye to "works on my machine" bugs.
Thursday, August 13, 2015

Java Beans Overview

Thursday, August 6, 2015

Fast check of Cross-domain policy file that server sends to client via socket

Often the socket connection to the certain server or its ports can be restricted by the policy file. It could be also allowed only from the particular list of domains (where the client hosts). So, here the quick way to make a socket connection to the server, request & output the cross-domain policy file (it can be launched via Groovy console right from your IntelijIDEA->Tools->Groovy console):

import javax.net.ssl.SSLSocketFactory

SSLSocketFactory f =(javax.net.SocketFactory) SSLSocketFactory.getDefault();
c = f.createSocket("foo.bar.com", 4855);
c.startHandshake();
c.withStreams { input, output ->
    output << "\0"
    println input.newReader().text}
Here is the output:
@seeAlso Senocular - Cross-domain Policy File Specification
Monday, August 3, 2015

Java Servlets

Wednesday, July 15, 2015

REST (RESTful Webservices)

Wednesday, June 17, 2015

Keynote: Java try-with-resources Statement

The try-with-resources statement ensures that each resource is closed
at the end of the statement.

Otherwords, in try-with-resources statement any catch or finally block is run after the resources declared have been closed.

*Resource - is an object that must be closed after the program is finished with it.
Closing a stream when it's no longer needed is very important to avoid serious resource leaks.
Use try-with-resources or close those in finally block to guarantee that both streams will be closed even if an error occurs.
Monday, May 18, 2015

Keynote: Threads like trains:)

Using the Threads leverage your application speed & flexibility:


A thread can be only in one of five states:
State Description
New When created but not started - not alive yet.
Runnable Eligible to run. either when start() method is invoked or returned or coming back from a blocked, waiting, or sleeping state - alive.
Running The scheduler chooses a thread from the runnable pool and it becomes the currently executing process.
Wait/blocking/sleeping The thread is still alive, but is currently not eligible to run. - considered alive.
Deads run() method completed - it's no longer a separate thread of execution and never be brought back to life! If you invoke start() on a dead Thread instance, you'll get a runtime exception. - not alive.