Ehcache Logging example

Ehcache is using SLF4j logging, to log stuff, put a slf4j implementation in the project classpath, in this example, we use logback. Tools used : Ehcache 2.9 Maven 3 logback 1.0.13 1. Project Directory Structure 2. Project Dependencies pom.xml <dependency> <groupId>net.sf.ehcache</groupId> <artifactId>ehcache</artifactId> <version>2.9.0</version> </dependency> <dependency> <groupId>ch.qos.logback</groupId> <artifactId>logback-classic</artifactId> <version>1.0.13</version> </dependency> 3. Logback.xml Create a logback.xml file …

Read more

Java – Convert Date to Calendar example

In Java, you can use calendar.setTime(date) to convert a Date object to a Calendar object. Calendar calendar = Calendar.getInstance(); Date newDate = calendar.setTime(date); A Full example DateAndCalendar.java import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; public class DateAndCalendar { public static void main(String[] argv) throws ParseException { //1. Create a Date from String SimpleDateFormat sdf …

Read more

Ant and TestNG Task example

In this tutorial, we will show you how to run a TestNG test in Ant build. 1. Run by Classes build.xml <taskdef name="testng" classname="org.testng.TestNGAntTask"> <classpath location="lib/testng-6.8.14.jar" /> </taskdef> <target name="testng" depends="compile"> <!– Assume test.path contains the project library dependencies –> <testng classpathref="test.path" outputDir="${report.dir}" haltOnFailure="true"> <!– Extra project classpath, which is not included in above "test.path" …

Read more

Maven – Get source code for Jar

In Maven, you can get source code for project dependencies in most IDEs like this : $ mvn dependency:sources $ mvn dependency:resolve -Dclassifier=javadoc Get source code for Jar Get javadoc for Jar, normally, developers don’t provide this. 1. Eclipse IDE In Eclipse IDE, it’s better to use the maven eclipse plugin: $ mvn eclipse:eclipse -DdownloadSources=true …

Read more

Ant and jUnit Task example

In this tutorial, we will show you how to run a junit test in Ant build. 1. Run a unit test build.xml <target name="junit" depends="compile"> <junit printsummary="yes" haltonfailure="no"> <!– Project classpath, must include junit.jar –> <classpath refid="test.path" /> <!– test class –> <classpath location="${test.classes.dir}" /> <test name="com.mkyong.test.TestMessage" haltonfailure="no" todir="${report.dir}"> <formatter type="plain" /> <formatter type="xml" /> …

Read more

Must include junit.jar if not in Ant’s own classpath

Declares a junit task in Ant like this build.xml <!– Run jUnit –> <target name="junit" depends="resolve"> <junit printsummary="yes" haltonfailure="no"> <classpath refid="test.path" /> <classpath location="${build.dir}" /> <test name="com.mkyong.test.TestMessage" haltonfailure="no" todir="${report.dir}" outfile="result"> <formatter type="plain" /> <formatter type="xml" /> </test> </junit> </target> Run ant junit, but hits the following error message : BUILD FAILED build.xml:86: The <classpath> for …

Read more

Convert DateTime to Date, but TimeZone is missing?

A code snippet to use Joda Time to convert a java.util.Date to different timezone : //java.util.Date : 22-1-2015 10:15:55 AM //System TimeZone : Asia/Singapore //Convert java.util.Date to America/New_York TimeZone DateTime dt = new DateTime(date); DateTimeZone dtZone = DateTimeZone.forID("America/New_York"); DateTime dtus = dt.withZone(dtZone); //21-1-2015 09:15:55 PM – Correct! //Convert Joda DateTime back to java.util.Date, and print …

Read more

How to install Apache Ant on Windows

To install Apache Ant on Windows, you just need to download the Ant’s zip file, and Unzip it, and configure the ANT_HOME Windows environment variables. Tools Used : JDK 1.7 Apache Ant 1.9.4 Windows 8.1 1. JAVA_HOME Make sure JDK is installed, and JAVA_HOME is configured as Windows environment variable. 2. Download Apache Ant Visit …

Read more

How to Apache Ant on Mac OS X

In this tutorial, we will show you how to install Apache Ant on Mac OSX. Tools : Apache Ant 1.9.4 Mac OSX Yosemite 10.10 Preinstalled Apache Ant? In older version of Mac, Apache Ant may be already installed by default, check if Apache Ant is installed : $ ant -v 1. Get Apache Ant Visit …

Read more

Windows 8.1, black screen with movable cursor

Here’s the scenario, morning wake up and find out my Windows 8.1 is displaying a black screen upon boot, no login screen, but a movable white cursor, random clicks will display the small loading icons? Problem : Black screen upon boot, movable cursor. Unable to display the Windows login screen. Detail : Windows 8.1 64 …

Read more

Ant – How to print classpath from path id

In Ant, you can use pathconvert task to print out the classpath from path : build.xml <path id="project.web.classpath"> <pathelement location="test/lib/junit-4.11.jar"/> <pathelement location="test/lib/hamcrest-core-1.3.jar"/> <fileset dir="${lib.web.dir}"> <include name="**/*.jar" /> </fileset> </path> <target name="print-classpath"> <pathconvert property="classpathInName" refid="project.web.classpath" /> <echo>Classpath is ${classpathInName}</echo> </target> Test : $ ant print-classpath Buildfile: /Users/mkyong/Documents/workspace/AntSpringMVC/build.xml print-classpath: [echo] Classpath is /Users/mkyong/Documents/workspace/AntSpringMVC/test/lib/junit-4.11.jar: /Users/mkyong/Documents/workspace/AntSpringMVC/testlib/hamcrest-core-1.3.jar: …… BUILD SUCCESSFUL …

Read more

Java – Convert String to Enum object

In Java, you can use Enum valueOf() to convert a String to an Enum object, review the following case study : 1. Java Enum example WhoisRIR.java package com.mkyong.whois.utils; public enum WhoisRIR { ARIN("whois.arin.net"), RIPE("whois.ripe.net"), APNIC("whois.apnic.net"), AFRINIC("whois.afrinic.net"), LACNIC("whois.lacnic.net"), JPNIC("whois.nic.ad.jp"), KRNIC("whois.nic.or.kr"), CNNIC("ipwhois.cnnic.cn"), UNKNOWN(""); private String url; WhoisRIR(String url) { this.url = url; } public String url() { …

Read more

Linux – How to extract a tar.gz file

In this tutorial, we will show you how to extract a tar.gz file : tar vxf filename.tar.gz Example For example, apache-ant-1.9.4-bin.tar.gz in your ~/Download folder. $ cd ~ $ pwd /Users/mkyong # Optionally, create a new folder for the archived file. $ mkdir tools $ cd tools $ pwd /Users/mkyong/tools # Copy archived file to …

Read more

Mac OSX – What program is using port 8080

By default, most Java web application servers are listening on port 8080, and it can easily cause the popular 8080 port conflict error. In Mac OSX, you can use sudo lsof -i :8080 | grep LISTEN to find out what program is listening on port 8080 : In terminal $ lsof -i :8080 | grep …

Read more

Mac OSX – What program is using port 80

In Mac OSX, you can use sudo lsof -i :80 to find out what program is using or listening on port 80 : In terminal $ sudo lsof -i :80 Password: COMMAND PID USER FD TYPE DEVICE SIZE/OFF NODE NAME httpd 12649 root 5u IPv6 0xede4ca21f607010b 0t0 TCP *:http (LISTEN) httpd 12650 _www 5u IPv6 …

Read more

Where is Eclipse deploy web application – Tomcat

By default Eclipse deploys web application to a internal plugin folder called wtpwebapps, which is located in the following directory : {Your_Workspace}/.metadata/.plugins/org.eclipse.wst.server.core/tmp{number}/wtpwebapps #Example 1 – Windows C:\Users\mkyong\workspace\.metadata\.plugins\org.eclipse.wst.server.core\tmp0\wtpwebapps #Example 2 – Mac OSX /Users/mkyong/Documents/workspace/.metadata/.plugins/org.eclipse.wst.server.core/tmp0/wtpwebapps How it works In Server view, double clicks on the “Tomcat Server”, the deployment work is defined in the Server Locations To …

Read more

How to debug Ant Ivy project in Eclipse IDE

In this tutorial, we will show you how to debug an Ant-Ivy web project in Eclipse IDE. Technologies used : Eclipse 4.2 Eclipse Tomcat Plugin Ant 1.9.4 Apache IvyDE Spring 4.1.3.RELEASE Note Previous Ant Spring MVC web project will be reused. 1. Install Apache IvyDE Install Apache IvyDE, it integrates Ivy into Eclipse IDE. Restart …

Read more

Ant – Spring MVC and WAR file Example

In this tutorial, we will show you how to use Ant build script to manage a Spring MVC web application project, create a WAR file and deploy to Tomcat. Technologies used : Eclipse 4.2 JDK 1.7 Ant 1.9.4 Ant-Ivy 2.4 logback 1.1.2 jstl 1.2 Spring 4.1.3.RELEASE Tomcat 7 1. Project Directory Review the final project …

Read more

Ant – Create a fat jar file

In this tutorial, we will show you how to use Ant build script to create a big far / uber Jar file, which mean include the entire project external dependencies into a single jar file. Technologies used : Ant 1.9.4 Ant-Ivy 2.4 logback 1.1.2 joda-time 2.5 1. Create a Fat Jar Previous Ant + External …

Read more

Java AWT Layouts

The java.awt library provides 5 basic layouts. Each layout has its own significance and all of them are completely different. Here in this article, we will discuss how to apply any layout to a frame or a panel and also discuss about each layout in brief. The 5 layouts available in the java.awt library are: …

Read more

Ant – How To Create A Jar File with external libraries

In this tutorial, we will show you how to use Ant build script to create a Jar file and working with the project’s external libraries / dependencies. Technologies used : Eclipse 4.2 JDK 1.7 Ant 1.9.4 Ant-Ivy 2.4 logback 1.1.2 joda-time 2.5 P.S Previous Ant Java project will be reused. 1. Project Structure Figure 1.1 …

Read more

Ant – How to create a Java Project

In this tutorial, we will show you how to use Ant build tool to manage a Java project, compile, and package it into a Jar file. Technologies used : Eclipse 4.2 Ant 1.9.4 JDK 1.7 1. Create a Java Project In Eclipse IDE, create a new Java project named “AntDateUtils”. 2. Java Source Code Create …

Read more

Create a fat Jar file – Maven Assembly Plugin

In this tutorial, we will show you how to create a fat/uber jar with Maven Assembly Plugin. Which means create a Jar together with its dependency Jars into a single executable Jar file. Note Maven assembly plugin is not good in producing fat/uber jar, it may cause name conflict issue, it is better to use …

Read more

Maven – Exclude log4j.properties in Jar file

This example shows you how to use Maven to exclude the log4j.properties file from your Jar file. Note Please, DO NOT include the log4j.properties into the final Jar file, it will cause multiple log4j.properties files in the classpath, if someone is depending on your Jar, you may accidentally override their logging configurations, depends which Jar …

Read more

Java – Cron job to run a jar file

Quartz is good, but often times we just need a simple scheduler system to run a jar file periodically. On *unix system, you can use the build-in cron to schedule a scheduler job easily. In this example, we will show you how to create a cron job on *nix to run a jar file, by …

Read more

Create a fat Jar file – Maven Shade Plugin

In this tutorial, we will show you how to use Maven Shade Plugin to create a Jar together with its dependency Jars into a single executable Jar file, so called fat Jar or uber Jar. Note Maven Shade plugin is a better plugin to create fat/uber jar, if compare with assembly plugin, because it provides …

Read more

Gradle – How to skip unit test

Be default, Gradle build is abort if any unit tests is failed. Oftentimes, we still need to build the project even the unit test is failed. To skip the entire unit tests in Gradle build, uses this option-x test gradle build -x test Review a sample output : 1. Default Gradle build : $ gradle …

Read more

Spring MVC hello world example (Gradle and JSP)

This tutorial shows you how to create a Spring Web MVC application with the Jakarta Server Pages (JSP; formerly JavaServer Pages) template. Technologies and tools used: Java 11 Spring 5.2.22.RELEASE JSP JSTL 1.2 Servlet API 4.0.1 Bootstrap 5.2.0 (webjars) IntelliJ IDEA Gradle 7.5.1 Gradle Gretty plugin 3.0.9 for embedded servlet containers (Tomcat 9 and Jetty …

Read more

How to configure hot deploy in Eclipse

In this tutorial, we will show you how to configure Eclipse debugger to support hot deploy, hot swap or hot code replace without restarting the Server, this speed development a lot. Environment : Eclipse 4.4 (Supported in older version as well) Eclipse Tomcat Plugin 1. Hot deploy example Review a simple hot deploy example, code …

Read more

Gradle – Create a Jar file with dependencies

In this tutorial, we will show you how to use Gradle build tool to create a single Jar file with dependencies. Tools used : Gradle 2.0 JDK 1.7 Logback 1.1.2 1. Project Directory Create following project folder structure : By default, Gradle is using the standard Maven project structure. ${Project}/src/main/java/ ${Project}/src/main/resources/ ${Project}/src/test/java/ 2. Java Files …

Read more

Gradle – bootstrap class path not set in conjunction with -source 1.5

My environment : JDK 1.7 Eclipse 4.4 Gradle 2.0 While gradle builld the project, I get following compile warning message : :compileJavawarning: [options] bootstrap class path not set in conjunction with -source 1.5 1 warning Figure : Eclipse console view. Solution The warning is saying you are using JDK 1.7, but try to compile the …

Read more

Gradle : Add Eclipse project nature

Eclipse project natures are configured in the .project file. For example : .project <?xml version="1.0" encoding="UTF-8"?> <projectDescription> <name>hello</name> <comment></comment> <projects> </projects> <buildSpec> <buildCommand> <name>org.eclipse.jdt.core.javabuilder</name> <arguments> </arguments> </buildCommand> </buildSpec> <natures> <nature>org.springsource.ide.eclipse.gradle.core.nature</nature> <nature>org.eclipse.jdt.core.javanature</nature> </natures> </projectDescription> To add a nature, just modify the nature tag, and add whatever nature you want. In Gradle, you can add the Eclipse …

Read more

Maven – Exclude logback.xml in Jar file

This example shows you how to use Maven to exclude the logback.xml file from the final Jar file. Note Please, DO NOT include the logback.xml into the final Jar file, it will cause multiple logback.xml files in the classpath, if someone is using your Jar, you may override other’s logging configurations accidentally. pom.xml <project> <build> …

Read more

Nginx : Block Referrer Spam

In this article, we will show you how to block referrer spam in one of our Nginx web server. 1. Find the Patterns Check the Nginx access.log file, and identify the “referrer spam” patterns. $ sudo tail -f /var/log/nginx/access.log Some patterns : 200 http://???.ru/engine/redirect.php?url=http://mywebsite.com/site/blogspot.com.au 200 http://???.com/tp/out.php?link=alternatevideo&url=http%3A//mywebsite.com/site/readyliftproshop.com 200 http://???.edu/online/redirect.asp?url=http://mywebsite/site/wheretoshophongkong.com We are going to block following patterns …

Read more

Nginx + Apache Tomcat configuration example

This tutorial shows you how to configure Nginx as a reverse proxy to redirect the traffics from port 80 to Apache Tomcat on port 8080. Here is the environment in my Linode server : Debian 7.5 Nginx 1.2.1 Tomcat 7.0.28 P.S Both Nginx and Tomcat are installed via apt-get install. 1. Tomcat Configuration Edit server.xml, …

Read more

Java : Return a random item from a List

Normally, we are using the following ways to generate a random number in Java. 1. ThreadLocalRandom (JDK 1.7) //Generate number between 0-9 int index = ThreadLocalRandom.current().nextInt(10); 2. Random() //Generate number between 0-9 Random random = new Random(); int index = random.nextInt(10); 3. Math.random() //Generate number between 0-9 int index = (int)(Math.random()*10); Note 1. For single …

Read more

Nginx : Block User Agent

In Nginx, you can block certain user agents (normally it is crawler) like this : /etc/nginx/sites-enabled/default server { listen 80; server_name mysite.com; root /etc/tomcat7/webapps/mysite; if ($http_user_agent ~* (ahrefs|wget|crawler|majestic) ) { return 403; } location / { <!– xxx –> } } In above example, for “user agent” that contains one of this pattern : ahrefs|wget|crawler|majestic, …

Read more