MongoDB – Allow remote access

In this tutorial, we will show you how to enable remote access to a MongoDB server. Here is the tested environment : 1. MongoDB Server Private IP – 192.168.161.100 Public IP – 45.56.65.100 MongoDB 2.6.3, port 27017 IpTables Firewall 2. Application Server (Same LAN network) Private IP – 192.168.161.200 Public IP – irrelevant 3. Developers …

Read more

Logback – different log file for each thread

In this tutorial, we will show you how to use Logback Mapped Diagnostic Context (MDC) and SiftingAppender to create a separate log file for each thread. P.S Tested with Logback 1.1.2, should work in earlier version. Note More info, refer to this Logback MDC documentation 1. logback.xml example A logback.xml file to show you how …

Read more

Spring – ${} is not working in @Value

A simple Spring @PropertySource example to read a properties file. db.properties db.driver=oracle.jdbc.driver.OracleDriver AppConfig.java @Configuration @PropertySource("classpath:db.properties") public class AppConfig { @Value("${db.driver}") private String driver; But the property placeholder ${} is unable to resolve in @Value, if print out the driver variable, it will display string ${db.driver} directly, instead of “oracle.jdbc.driver.OracleDriver”. Solution To resolve ${} in Spring …

Read more

Java – Get number of available processors

A code snippet to show you how to get the number of available processors / cores / CPUs in your environment. int processors = Runtime.getRuntime().availableProcessors(); System.out.println(processors); Output 8 P.S Tested with Intel(R) Core(TM) i7-4770 CPU @3.40GHz

How to change Eclipse theme

In this tutorial, we will show you how to change the Eclipse Theme. Tools used : Eclipse 4.4 Luna, works on earlier version. Eclipse Color Theme Plugin Figure : This is how your final Eclipse IDE looks like 1. Install Eclipse Color Theme Plugin Install the theme plugin and restart Eclipse. Eclipse menu -> Help …

Read more

Spring MVC Abstract Controller example

For self-reference, this article shows you how to create a Abstract class for Spring Controller, or a template method design pattern. 1. Abstract Controller In Abstract class, the @Controller annotation is optional, your implemented class will apply it. AbstractResultController.java package com.mkyong.web.controller; import java.util.Map; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.servlet.ModelAndView; …

Read more

logback.xml Example

Here are a few logback.xml examples that are used in my projects, just for sharing. P.S Tested with Logback 1.2.3 1. Send logs to Console All logging will be redirected to console. logback.xml <configuration> <appender name="CONSOLE" class="ch.qos.logback.core.ConsoleAppender"> <layout class="ch.qos.logback.classic.PatternLayout"> <Pattern> %d{HH:mm:ss.SSS} [%t] %-5level %logger{36} – %msg%n </Pattern> </layout> </appender> <logger name="com.mkyong" level="debug" additivity="false"> <appender-ref ref="CONSOLE"/> …

Read more

Jsoup – Check Redirect URL

In this article, we will show you how to use Jsoup to check if an URL is going to redirect. 1. URL Redirection Normally, a redirect URL will return an HTTP code of 301 or 307, and the target URL will be existed in the response header “location” field. Review a sample of HTTP Response …

Read more

Javascript – How to call function inside jQuery code

Review a Javascript code snippet to call a function which declared inside jQuery code : <script> //javascript function submitSearchForm() { updateErrorMessage("Please enter a website url"); } //jquery jQuery(document).ready(function($) { function updateErrorMessage(msg) { $(‘#error’).html(msg).hide().fadeIn(500); } } ); </script> But, browser console shows the updateErrorMessage function is not defined. Uncaught ReferenceError: updateErrorMessage is not defined Solution To …

Read more

Spring Profiles example

Spring @Profile allow developers to register beans by condition. For example, register beans based on what operating system (Windows, *nix) your application is running, or load a database properties file based on the application running in development, test, staging or production environment. In this tutorial, we will show you a Spring @Profile application, which does …

Read more

Import Spring XML files into @Configuration

This is common to mix XML configuration into Spring @Configuration, because developers are used to the XML namespaces. In Spring, you can use @ImportResource to import Spring XML configuration files into @Configuration : AppConfig.java import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.ImportResource; @Configuration @ImportResource("classpath:/config/spring.xml") public class AppConfig { } Another example AppConfig.java import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.ImportResource; import org.springframework.context.annotation.Import; @Configuration …

Read more

MongoDB – Update to upper case

A document, and you want to update all the ‘source’ values to UPPERCASE. whois.json { “_id” : NumberLong(1), “country” : “au”, “source” : “apnic” } { “_id” : NumberLong(2), “country” : “cn”, “source” : “apnic” } { “_id” : NumberLong(3), “country” : “us”, “source” : “arin” } Solution No sure if there is any ready …

Read more

Java – Convert date and time between timezone

In this tutorial, we will show you few examples (ZonedDateTime (Java 8), Date, Calendar and Joda Time) to convert a date and time between different time zones. All examples will be converting the date and time from (UTC+8:00) Asia/Singapore – Singapore Time Date : 22-1-2015 10:15:55 AM to (UTC-5:00) America/New_York – Eastern Standard Time Date …

Read more

Java – Display list of TimeZone with GMT

This Java example shows you how to display a list of TimeZone with GMT in front. P.S Tested with JDK 1.7 Java 8 You may interest at this example – Display all ZoneId and its UTC offset TimeZoneExample.java package com.mkyong.test; import java.util.TimeZone; import java.util.concurrent.TimeUnit; public class TimeZoneExample { public static void main(String[] args) { String[] …

Read more

Spring Caching and Ehcache example

In this tutorial, we will show you how to enable data caching in a Spring application, and integrate with the popular Ehcache framework. Tools used Ehcache 2.9 Spring 4.1.4.RELEASE Logback 1.0.13 Maven 3 / Gradle 2 JDK 1.7 Eclipse 4.4 Note Spring supports caching since version 3.1 Spring cache has been significantly improved since version …

Read more

MongoDB – Remove a field from array

Prior to MongoDB 2.6, there is no official function to $unset a field from array document. Note $unset is not working with arrays $pull is used to remove the entire record, not a particular field. 1. Arrays Documents In this article, we will show you how to remove the field “countryName” from below array. > …

Read more

Ehcache hello world example

In this tutorial, we will show you two examples to help you getting started with Ehcache. Tools used : Ehcache 2.9 Maven 3 Gradle 2 JDK 1.7 P.S Ehcache required JDK 1.5 or above. 1. Project Directory Structure 2. Hello World Assume this is a Maven project : pom.xml <dependency> <groupId>net.sf.ehcache</groupId> <artifactId>ehcache</artifactId> <version>2.9.0</version> </dependency> Read …

Read more

Logback – Duplicate log messages

Review a simple Java application and log a message via Logback. App.java package com.mkyong.test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class App { private static final Logger log = LoggerFactory.getLogger(App.class); public static void main(String[] args) { log.debug("Testing"); } } P.S Tested with Logback 1.1.2 1. Problem A simple logback.xml to log a message to console. logback.xml …

Read more

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

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