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

Count IP address in Nginx access logs

Recently, many referer spam hit on my server, below is the command I used to find and count the IP Address from a Nginx access log file. $ sudo awk ‘{print $1}’ /var/log/nginx/access.log | sort | uniq -c | sort -nr Full example. $ sudo awk ‘{print $1}’ /var/log/nginx/access.log | sort | uniq -c | …

Read more

jsoup : Send search query to Google

This example shows you how to use jsoup to send a search query to Google. Document doc = Jsoup .connect("https://www.google.com/search?q=mario"); .userAgent("Mozilla/5.0") .timeout(5000).get(); Unusual traffic from your computer network Don’t use this example to spam Google, you will get above message from Google, read this Google answer. 1. jsoup example Example to send a “mario” search …

Read more

Java – Read a file from resources folder

In Java, we can use getResourceAsStream or getResource to read a file or multiple files from a resources folder or root of the classpath. The getResourceAsStream method returns an InputStream. // the stream holding the file content InputStream is = getClass().getClassLoader().getResourceAsStream("file.txt"); // for static access, uses the class name directly InputStream is = JavaClassName.class.getClassLoader().getResourceAsStream("file.txt"); The …

Read more

How to change Tomcat manager default path ?

By default, Tomcat’s manager webapp is able to access via yourapp:8080/manager. It is a good practice to change the default /manager to something else, to avoid potential brute force attack. Environment Tomcat 7 (apt-get install) Debian 7.5 1. Solution This article show you how to change / rename the default manager webapp path from “/manager” …

Read more

How to change Tomcat to use JDK 7

The current environment is using Tomcat 7 + JDK 6. How to configure Tomcat to use JDK 7? Environment Tomcat 7 (apt-get install) Debian 7.5 JDK 6 and JDK 7 P.S Tomcat 7 is installed via apt-get Note You may interest at this tutorial – Apache Tomcat 8 + JDK 8 on Debian 1. Solution …

Read more

Eclipse – red-x icon didn’t display on project explorer

In Eclipse IDE, If a project contains errors, a small “red-x” icon will be displayed in the files that are causing the error. This useful feature is supported in Java related perspectives only, for example, “Package Explorer”. 1. Problem Personally, I prefer to use the “Project Explorer” perspective (pure folder structure), but the “red-x” icon …

Read more

Linux : How to gzip a folder

On Linux, gzip is unable to compress a folder, it used to compress a single file only. To compress a folder, you should use tar + gzip, which is tar -z. Note $ tar –help -z, -j, -J, –lzma Compress archive with gzip/bzip2/xz/lzma For example, tar -zcvf outputFileName folderToCompress 1. Tar + Gzip a folder …

Read more

mongoimport unable to import $numberLong

A collection with NumberLong type data as follows : > db.hc_whois.findOne(); { "_id" : NumberLong(3000001), "startIpInLong" : NumberLong(1543503872), "endIpInLong" : NumberLong(1544552447), "name" : "ap-net-1", //… } Export it with mongoexport : server1 $ mongoexport -d mydb -c hc_whois -o whois.json whois.json { "_id" : { "$numberLong" : "3000001" }, "startIpInLong" : { "$numberLong" : "1543503872" …

Read more

servlet-api-2.5.jar – jar not loaded

Deployed a “war” file on Tomcat, and hits following error messages : Jul 17, 2014 7:59:55 PM org.apache.catalina.loader.WebappClassLoader validateJarFile INFO: validateJarFile(D:\apache-tomcat-7.0.53\webapps\hc\WEB-INF\lib\servlet-api-2.5.jar) – jar not loaded. See Servlet Spec 3.0, section 10.7.2. Offending class: javax/servlet/Servlet.class Tools used : JDK1.7 Maven 3 Tomcat 7 1. Reason The Tomcat’s container comes with own version of servlet-api.jar, and the …

Read more

JSF 2 + Log4j Integration Example

In this tutorial, we will show you how to integrate the log4j framework with the JSF 2.x web application. JSF is using java.util.logging, you need extra works to redirect the logging from JSF’s java.util.logging to log4j, with a serious penalty of performance, make sure use this trick only during local development or debugging environment. Review …

Read more

Log4j hello world example

In this tutorial, we will show you how to use the classic log4j 1.2.x to log a debug or error message in a Java application. 1. Project Directory Review the final project structure, a standard Maven style Java project. 2. Get Log4j Declares the following dependencies : pom.xml <dependency> <groupId>log4j</groupId> <artifactId>log4j</artifactId> <version>1.2.17</version> </dependency> For non-Maven …

Read more

Download file from server using SSH

Normally, you use Secure copy or SCP to download a file from another server via SSH connection. For example, scp username@remotehost:remoteFileToDownload localFolderNameToSaveTheFile 1. SCP Examples 1.1 Download File From Server Example to download a log file (hc.audit.log) from server (198.58.x.x), into your current local folder. scp [email protected]:/var/log/tomcat7/hc.audit.log . 1.2 Upload File To Server Example to …

Read more

Debian : Change default Java version

Deployed a Debian 7.5 on Linode server, the default is using OpenJDK 1.6. How to upgrade to OpenJDK 1.7? $ java -version java version "1.6.0_31" OpenJDK Runtime Environment (IcedTea6 1.13.3) (6b31-1.13.3-1~deb7u1) OpenJDK 64-Bit Server VM (build 23.25-b01, mixed mode) Tracing the java, it’s using the Debian’s alternative settings : $ ls -lsa /usr/bin/ | grep …

Read more

log4j.xml Example

Here’s an XML version of log4j properties file, just for sharing. 1. Output to Console Redirect the logging to console. log4j.xml <?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE log4j:configuration SYSTEM "log4j.dtd"> <log4j:configuration debug="true" xmlns:log4j=’http://jakarta.apache.org/log4j/’> <appender name="console" class="org.apache.log4j.ConsoleAppender"> <layout class="org.apache.log4j.PatternLayout"> <param name="ConversionPattern" value="%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L – %m%n" /> </layout> </appender> <root> <level value="DEBUG" /> <appender-ref ref="console" /> …

Read more

Spring Security + Hibernate Annotation Example

In this tutorial, previous Spring Security + Hibernate4 XML example will be reused, and convert it to a annotation-based example. Technologies used : Spring 3.2.8.RELEASE Spring Security 3.2.3.RELEASE Hibernate 4.2.11.Final MySQL Server 5.6 Tomcat 7 (Servlet 3.x container) Quick Note : Create a session factory with LocalSessionFactoryBuilder Inject session factory into a UserDao Integrate UserDao …

Read more

Spring Security + Hibernate XML Example

In this tutorial, we will show you how to integrate Hibernate 4 in Spring Security, XML configuration example. Note For annotation version, please read this Spring Security + Hibernate Annotation Example. Technologies used : Spring 3.2.8.RELEASE Spring Security 3.2.3.RELEASE Hibernate 4.2.11.Final MySQL Server 5.6 JDK 1.6 Maven 3 Eclipse 4.3 Quick Notes Create a session …

Read more

java.lang.ClassNotFoundException: org.hibernate.service.jta.platform.spi.JtaPlatform

Spring 3.2.x + Hibernate 4.3.x integration, hits JtaPlatform ClassNotFoundException, search the project classpath, find out that JtaPlatform is at different package? hibernate-core.4.3.5.Final.jar org.hibernate.engine.transaction.jta.platform.spi.JtaPlatform Error message shows org.hibernate.service.jta.platform.spi.JtaPlatform Caused by: java.lang.NoClassDefFoundError: org/hibernate/service/jta/platform/spi/JtaPlatform at org.springframework.orm.hibernate4.SpringSessionContext.<init>(SpringSessionContext.java:56) ~[spring-orm-3.2.8.RELEASE.jar:3.2.8.RELEASE] … 40 common frames omitted Caused by: java.lang.ClassNotFoundException: org.hibernate.service.jta.platform.spi.JtaPlatform //… pom.xml <!– Hibernate ORM –> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-core</artifactId> <version>4.3.5.Final</version> </dependency> <!– …

Read more

Spring Security : Encoded password does not look like BCrypt

In Spring Security, database authentication with bcrypt password hashing. import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; import org.springframework.security.crypto.password.PasswordEncoder; //… String password = “123456”; PasswordEncoder passwordEncoder = new BCryptPasswordEncoder(); String hashedPassword = passwordEncoder.encode(password); spring-security.xml <authentication-manager> <authentication-provider> <password-encoder hash="bcrypt" /> //… </authentication-provider> </authentication-manager> CREATE TABLE users ( username VARCHAR(45) NOT NULL , password VARCHAR(45) NOT NULL , enabled TINYINT NOT NULL DEFAULT …

Read more