Java and “& 0xFF” example

Before you understand what is & 0xFF, make sure you know following stuffs : Bitwise AND operator, link. Converts hex to/from binary, and decimal to/from binary. In short, & 0xFF is used to make sure you always get the last 8 bits. Let’s see an example to convert an IP address to/from decimal number. 1. …

Read more

Eclipse – java.lang.OutOfMemoryError: Java heap space

This article shows how to solve the java.lang.OutOfMemoryError: Java heap space in Eclipse IDE. Table of contents 1. Eclipse – OutOfMemoryError: Java heap space 2. Temporary fix – Increase the heap size 3. eclipse.ini 4. The solution, find the reason behind the heap size error. 5. References 1. Eclipse – OutOfMemoryError: Java heap space In …

Read more

Java Date and Calendar examples

This tutorial shows you how to work with java.util.Date and java.util.Calendar. 1. Java Date Examples Few examples to work with Date APIs. Example 1.1 – Convert Date to String. SimpleDateFormat sdf = new SimpleDateFormat("dd/M/yyyy"); String date = sdf.format(new Date()); System.out.println(date); //15/10/2013 Example 1.2 – Convert String to Date. SimpleDateFormat sdf = new SimpleDateFormat("dd-M-yyyy hh:mm:ss"); String …

Read more

Eclipse – How to attach JDK source code

This article shows you how to attach the JDK source code in Eclipse IDE. In Eclipse, select Windows -> Preferences -> Java -> Installed JREs , expands rt.jar, select “Source attachment” and find the src.zip from your disk drive. P.S JDK source code is inside the src.zip. Note You may interest at this article – …

Read more

Where to download Java JDK source code ?

The JDK source code is inside the src.zip, this article shows you how to get it on Windows, Ubuntu (Linux) and Mac OSX. 1. Windows In Windows, visit the Oracle website and download the JDK (not JRE). Install the JDK and the src.zip is inside the JDK installed folder, for example : C:\Program Files\Java\jdk1.7.0_40\src.zip 2. …

Read more

Java – How to calculate leap year

A leap year is a year containing one additional day (366 days a year). Review the leap year algorithm : if year is divisible by 400 then is_leap_year else if year is divisible by 100 then not_leap_year else if year is divisible by 4 then is_leap_year else not_leap_year P.S Algorithm from wikipedia leap year. 1. …

Read more

Java – Time elapsed in days, hours, minutes, seconds

Two Java examples show you how to print the elapsed time in days, hours, minutes and seconds format. 1. Standard JDK Date APIs You need to calculate the elapsed time manually. DateTimeUtils.java package com.mkyong.dateUtils; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; public class DateTimeUtils { public static void main(String[] args) { DateTimeUtils obj = new DateTimeUtils(); …

Read more

Spring Data MongoDB : get last modified records (date sorting)

In Mongodb, you can use sort()to do the date sorting. 1. MongoDB Sorting Examples In Mongodb, to sort a “date” field, issues : //The ‘1’ = sort ascending (oldest to newest) db.domain.find().sort({lastModifiedDate:1}) { "_id" : 1, "lastModifiedDate" : ISODate("2013-08-13T07:18:04.774Z") } { "_id" : 2, "lastModifiedDate" : ISODate("2013-09-03T08:12:16.309Z") } { "_id" : 3, "lastModifiedDate" : ISODate("2013-10-03T08:12:16.309Z") …

Read more

Spring Data MongoDB : like query example

In SQL, the ‘like’ query is looks like this : select * from tags where tagName like ‘%apple%’ In MongoDB console, it looks like this : db.tags.find({"tagName": /apple/}) In Spring data mongodb, it implements with Criteria or BasicQuery : String tagName = "apple"; Query query = new Query(); query.limit(10); query.addCriteria(Criteria.where("tagName").regex(tagName)); mongoOperation.find(query, Tags.class); String tagName = …

Read more

jQuery loop over JSON string – $.each example

Review a simple jQuery example to loop over a JavaScript array object. var json = [ {"id":"1","tagName":"apple"}, {"id":"2","tagName":"orange"}, {"id":"3","tagName":"banana"}, {"id":"4","tagName":"watermelon"}, {"id":"5","tagName":"pineapple"} ]; $.each(json, function(idx, obj) { alert(obj.tagName); }); Above code snippet is working fine, prompts the “apple”, “orange” … as expected. Problem : JSON string Review below example, declares a JSON string (enclosed with single …

Read more

jQuery and Java List example

There is no direct way to iterate over a Java List with jQuery, see the following case study : Spring controller @RequestMapping(value = "/", method = RequestMethod.GET) public ModelAndView getPages() { List<String> list = new ArrayList<String>(); list.add("List A"); list.add("List B"); list.add("List C"); list.add("List D"); list.add("List E"); ModelAndView model = new ModelAndView("somepage"); model.addObject("list", list); return model; …

Read more

How to access JSON object in JavaScript

Below is a JSON string. JSON String { "name": "mkyong", "age": 30, "address": { "streetAddress": "88 8nd Street", "city": "New York" }, "phoneNumber": [ { "type": "home", "number": "111 111-1111" }, { "type": "fax", "number": "222 222-2222" } ] } To access the JSON object in JavaScript, parse it with JSON.parse(), and access it via …

Read more

Spring MVC – find location using IP Address (jQuery + Google Map)

In this tutorial, we show you how to find a location using an IP address, with the following technologies : Spring MVC frameworks. jQuery (Ajax Request). GeoLite database. Google Map. Review the tutorial’s flows A page with a text input and button. Type an IP address, and clicks on the button. jQuery fires an Ajax …

Read more

Java – find location using Ip Address

In this example, we show you how to find a location (country, city, latitude, longitude) using an IP address. 1. GeoLite Database The MaxMind provides a free GeoLite database (IP Address to Location). Get a free GeoLite free Databases – here Get a GeoIP client Java APIs – here Start code it. 2. GeoLite Java …

Read more

Jsoup – Get favicon from html page

There are many ways the favicon can be recognized by the web browser : Example 1 <head> <link rel="icon" href="http://example.com/image.ico" /> </head> Example 2 <head> <link rel="icon" href="http://example.com/image.png" /> </head> Example 3 – weird, but Google use it. <head> <meta content="/images/google_favicon_128.png" itemprop="image" /> </head> 1. Jsoup Example Code snippets to get above favicon with Jsoup. …

Read more

Spring MVC @ExceptionHandler Example

In this tutorial, we show you how to do exception handling in Spring MVC frameworks. Normally, we use @ExceptionHandler to decide which “view” should be returned back if certain exception is raised. P.S This @ExceptionHandler class is available since Spring 3.0 1. Project Structure Review the project directory structure, a standard Maven project. 2. Custom …

Read more

Spring MVC and List Example

In this tutorial, we show you how to print the List values via JSTL c:forEach tag. P.S This web project is using Spring MVC frameworks v3.2 1. Project Structure Review the project directory structure, a standard Maven project. 2. Project Dependencies Add Spring and JSTL libraries. pom.xml <properties> <spring.version>3.2.2.RELEASE</spring.version> <jstl.version>1.2</jstl.version> </properties> <dependencies> <!– jstl –> …

Read more

How to join two Lists in Java

In this article, we show you 2 examples to join two lists in Java. JDK – List.addAll() Apache Common – ListUtils.union() 1. List.addAll() example Just combine two lists with List.addAll(). JoinListsExample.java package com.mkyong.example; import java.util.ArrayList; import java.util.List; public class JoinListsExample { public static void main(String[] args) { List<String> listA = new ArrayList<String>(); listA.add("A"); List<String> listB …

Read more

How to execute JavaScript in Selenium WebDriver

Below code snippet shows you how to execute a JavaScript in Selenium WebDriver. WebDriver driver = new ChromeDriver(); if (driver instanceof JavascriptExecutor) { ((JavascriptExecutor) driver).executeScript("alert(‘hello world’);"); } 1. WebDriver Example In this example, it uses WebDriver to load “google.com”, and executes a simple alert () later. JavaScriptExample.java package com.mkyong.test; import org.openqa.selenium.JavascriptExecutor; import org.openqa.selenium.WebDriver; import org.openqa.selenium.chrome.ChromeDriver; …

Read more

Many chromedriver.exe are left hanging on Windows – Selenium

The Selenium WebDriver is closed, but the “chromedriver.exe” process is left hanging in the system. See figure : Problem Here is the code, a simple WebDriver example to load a URL and exists, but the chromedriver.exe never get killed. LoadWebPageExample.java package com.mkyong.test; import org.openqa.selenium.WebDriver; import org.openqa.selenium.chrome.ChromeDriver; import org.openqa.selenium.chrome.ChromeOptions; import org.openqa.selenium.remote.DesiredCapabilities; public class LoadWebPageExample { public …

Read more

Regular Expression case sensitive example – Java

In Java, by default, the regular expression (regex) matching is case sensitive. To enable the regex case insensitive matching, add (?) prefix or enable the case insensitive flag directly in the Pattern.compile(). A regex pattern example. Pattern = Registrar:\\s(.*) Case Insensitive, add (?) prefix. Pattern = (?)Registrar:\\s(.*) Case Insensitive, add Pattern.CASE_INSENSITIVE flag. Pattern.compile("Registrar:\\s(.*)", Pattern.CASE_INSENSITIVE); 1. …

Read more

Jackson : was expecting double-quote to start field name

A simple example to use Jackson to convert a JSON string to a Map. String json = "{name:\"mkyong\"}"; Map<String,String> map = new HashMap<String,String>(); ObjectMapper mapper = new ObjectMapper(); map = mapper.readValue(json, new TypeReference<HashMap<String,String>>(){}); Problem When the program is executed, it hits following error message org.codehaus.jackson.JsonParseException: Unexpected character (‘n’ (code 110)): was expecting double-quote to start …

Read more

Spring Batch Hello World Example

Spring Batch is a framework for batch processing – execution of a series of jobs. In Spring Batch, A job consists of many steps and each step consists of a READ-PROCESS-WRITE task or single operation task (tasklet). For “READ-PROCESS-WRITE” process, it means “read” data from the resources (csv, xml or database), “process” it and “write” …

Read more

Spring Batch Example – MySQL Database To XML

In this tutorial, we will show you how to read data from a MySQL database, with JdbcCursorItemReader and JdbcPagingItemReader, and write it into an XML file. Tools and libraries used Maven 3 Eclipse 4.2 JDK 1.6 Spring Core 3.2.2.RELEASE Spring OXM 3.2.2.RELEASE Spring Batch 2.2.0.RELEASE MySQL Java Driver 5.1.25 P.S This example – MySQL jdbc …

Read more

Spring Batch listeners example

In Spring batch, there are six “listeners” to intercept the step execution, I believe the class name should be self-explanatory. StepExecutionListener ItemReadListener ItemProcessListener ItemWriteListener ChunkListener SkipListener 1. Listener Example Three listener examples, do nothing but print out a message. CustomStepListener.java package com.mkyong.listeners; import org.springframework.batch.core.ExitStatus; import org.springframework.batch.core.StepExecution; import org.springframework.batch.core.StepExecutionListener; public class CustomStepListener implements StepExecutionListener { @Override …

Read more

Spring Batch Tasklet example

In Spring batch, the Tasklet is an interface, which will be called to perform a single task only, like clean or set up resources before or after any step execution. In this example, we will show you how to use Tasklet to clean up the resource (folders) after a batch job is completed. P.S The …

Read more

Run Spring batch job with CommandLineJobRunner

A quick guide to show you how to run a Spring batch job with CommandLineJobRunner. 1. Spring Batch Job Example A simple job. resources/spring/batch/jobs/job-read-files.xml <?xml version="1.0" encoding="UTF-8"?> <beans … <import resource="../config/context.xml"/> <job id="readJob" xmlns="http://www.springframework.org/schema/batch"> <step id="step1"> <tasklet> <chunk reader="flatFileItemReader" writer="flatFileItemWriter" commit-interval="1" /> </tasklet> </step> </job> <!– … –> </beans> 2. Package Project Use Maven to …

Read more

Domain name regular expression example

Domain Name Regular Expression Pattern ^((?!-)[A-Za-z0-9-]{1,63}(?<!-)\\.)+[A-Za-z]{2,6}$ Above pattern makes sure domain name matches the following criteria : The domain name should be a-z | A-Z | 0-9 and hyphen(-) The domain name should between 1 and 63 characters long Last Tld must be at least two characters, and a maximum of 6 characters The domain …

Read more