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

How to convert Date in BeanWrapperFieldSetMapper

Read following Spring batch job, it reads data from “domain.csv“, and map it to a domain object. job-example.xml <bean class="org.springframework.batch.item.file.FlatFileItemReader" > <property name="resource" value="file:outputs/csv/domain.csv" /> <property name="lineMapper"> <bean class="org.springframework.batch.item.file.mapping.DefaultLineMapper"> <property name="lineTokenizer"> <bean class="org.springframework.batch.item.file.transform.DelimitedLineTokenizer"> <property name="names" value="id, domainName, lastModifiedDate" /> </bean> </property> <property name="fieldSetMapper"> <bean class="org.springframework.batch.item.file.mapping.BeanWrapperFieldSetMapper"> <property name="prototypeBeanName" value="domain" /> </bean> </property> </bean> </property> </bean> <bean …

Read more

How to add copyright to Eclipse automatically

A quick guide to show you how to add @Copyright comment to new and existing Java files in Eclipse IDE. Solution 1. Eclipse Code Templates Go to preferences -> Java -> Code Style -> Code Templates, expands Code and select “New Java Files”, edit the template to add whatever copyright messages you want. Now, that …

Read more

jobParameters cannot be found on object of type BeanExpressionContext

Create a simple Spring batch job to write data to a csv file. The csv file name depends on the pass in job’s parameters, interprets by Spring EL . job-sample.xml <bean id="csvFileItemWriter" class="org.springframework.batch.item.file.FlatFileItemWriter"> <!– write to this csv file –> <property name="resource" value="file:outputs/csv/domain.done.#{jobParameters[‘pid’]}.csv" /> <property name="appendAllowed" value="false" /> <property name="lineAggregator"> <bean class="org.springframework.batch.item.file.transform.DelimitedLineAggregator"> <property name="delimiter" value="," …

Read more

How to find Java class in Eclipse?

In Eclipse IDE, you can type CTRL + SHIFT + T in Windows or *nix or Command + SHIFT + T in Mac OSX to prompt an Open Type dialog box to find details about a specified Java class. For example, if you want to know the detail of this Java class – FlatFileItemWriter (Spring …

Read more

NoSuchBeanDefinitionException : No qualifying bean of type JobLauncherTestUtils

Following the official Spring batch unit testing guide to create a standard unit test case. @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(locations = { "classpath:spring/batch/jobs/job-abc.xml", "classpath:spring/batch/config/context.xml"}) public class AppTest { @Autowired private JobLauncherTestUtils jobLauncherTestUtils; @Test public void launchJob() throws Exception { JobExecution jobExecution = jobLauncherTestUtils.launchJob(); assertEquals(BatchStatus.COMPLETED, jobExecution.getStatus()); } } P.S spring-batch-test.jar is added to the classpath. Problem When launches above …

Read more

Spring Batch unit test example

In this tutorial, we will show you how to unit test Spring batch jobs with jUnit and TestNG frameworks. To unit test batch job, declares spring-batch-test.jar, @autowired the JobLauncherTestUtils, launch the job or step, and assert the execution status. 1. Unit Test Dependencies To unit test Spring batch, declares following dependencies : pom.xml <!– Spring …

Read more

How to convert String to Date – Java

In this tutorial, we will show you how to convert a String to java.util.Date. Many Java beginners are stuck in the Date conversion, hope this summary guide will helps you in some ways. // String -> Date SimpleDateFormat.parse(String); // Date -> String SimpleDateFormat.format(date); Refer to table below for some of the common date and time …

Read more

Convert String with commas to Long – Java

A short guide to show you how to convert a String with commas to a long type. 1. For a normal String, you can use Long.valueOf to convert it directly. String bigNumber = "1234567899"; long result = Long.valueOf(bigNumber); 2. For a String with commas, you can use java.text.NumberFormat to convert it. String bigNumber = "1,234,567,899"; …

Read more

Spring Batch metadata tables are not created automatically?

If jobRepository is created with MapJobRepositoryFactoryBean (metadata in memory), the Spring batch jobs are running successfully. spring-config.xml <bean id="jobRepository" class="org.springframework.batch.core.repository.support.MapJobRepositoryFactoryBean"> <property name="transactionManager" ref="transactionManager" /> </bean> Problem After changing the jobRepository to store metadata into database : spring-config.xml <bean id="jobRepository" class="org.springframework.batch.core.repository.support.JobRepositoryFactoryBean"> <property name="dataSource" ref="dataSource" /> <property name="transactionManager" ref="transactionManager" /> <property name="databaseType" value="mysql" /> </bean> <bean id="jobLauncher" …

Read more

Spring Batch : A job instance already exists and is complete for parameters={}

Working with Spring Batch 2.2.0.RELEASE, and launches the job with Spring Scheduler. CustomJobLauncher.java package com.mkyong.batch; import org.springframework.batch.core.Job; import org.springframework.batch.core.JobExecution; import org.springframework.batch.core.JobParameters; import org.springframework.batch.core.launch.JobLauncher; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; @Component public class CustomJobLauncher { @Autowired JobLauncher jobLauncher; @Autowired Job job; public void run() { try { JobExecution execution = jobLauncher.run(job, new JobParameters()); System.out.println("Exit Status : " + …

Read more

Java Whois example

In this tutorial, we will show you how to use Java library – “Apache Commons Net” to get WHOIS data of a domain. 1. Simple Java Whois Example For domain registered under internic.net, you can get the whois data directly. WhoisTest.java package com.mkyong.whois.bo; import java.io.IOException; import java.net.SocketException; import org.apache.commons.net.whois.WhoisClient; public class WhoisTest { public static …

Read more

Reporting in Java using DynamicReports and JasperReports

This example shows how to generate a simple report using DynamicReports and JasperReports. DynamicReports is a Java reporting library that allows you to produce report documents that can be exported into many popular formats. It is based on the well-known JasperReports library. Tools used in this article : DynamicReports 3.1.3 JasperReports 5.0.4 MySQL 5.5 Maven …

Read more

How to send HTTP request GET/POST in Java

In this article, we will show you a few examples to make HTTP GET/POST requests via the following APIs Apache HttpClient 4.5.10 OkHttp 4.2.2 Java 11 HttpClient Java 1.1 HttpURLConnection (Not recommend) 1. Apache HttpClient In the old days, this Apache HttpClient is the de facto standard to send an HTTP GET/POST request in Java. …

Read more