Maven Jetty Plugin Examples

Few Maven Jetty 8.x and 9.x plugin examples, just for quick reference. 1. Maven Jetty Plugin 9.x Note You need to use Maven 3 and Java 1.7 for Maven Jetty 9.x plugin. 1.1 The ‘groupId’ is org.eclipse.jetty, by default, it runs on port 8080, in root context ‘/’. pom.xml <plugin> <groupId>org.eclipse.jetty</groupId> <artifactId>jetty-maven-plugin</artifactId> <version>9.2.11.v20150529</version> </plugin> To …

Read more

Python 3 : Convert string to bytes

Code snippets to show you how to convert string to bytes and vice versa. 1. To convert a string to bytes. data = "" #string data = "".encode() #bytes data = b"" #bytes 2. To convert bytes to a String. data = b"" #bytes data = b"".decode() #string data = str(b"") #string P.S Tested with …

Read more

How to convert String to int in Java

In Java, we can use Integer.parseInt(String) to convert a String to an int; For unparsable String, it throws NumberFormatException. Integer.parseInt("1"); // ok Integer.parseInt("+1"); // ok, result = 1 Integer.parseInt("-1"); // ok, result = -1 Integer.parseInt("100"); // ok Integer.parseInt(" 1"); // NumberFormatException (contains space) Integer.parseInt("1 "); // NumberFormatException (contains space) Integer.parseInt("2147483648"); // NumberFormatException (Integer max 2,147,483,647) …

Read more

Maven – Display project dependency

In Maven, you can use mvn dependency:tree to display the project dependencies in tree format. 1. Maven Project Review a simple Maven project, declared Spring and logback dependencies. pom.xml <properties> <spring.version>4.1.6.RELEASE</spring.version> <logback.version>1.1.3</logback.version> <jcl.slf4j.version>1.7.12</jcl.slf4j.version> </properties> <dependencies> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-core</artifactId> <version>${spring.version}</version> <exclusions> <exclusion> <groupId>commons-logging</groupId> <artifactId>commons-logging</artifactId> </exclusion> </exclusions> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.slf4j</groupId> <artifactId>jcl-over-slf4j</artifactId> <version>${jcl.slf4j.version}</version> …

Read more

Java – Display double in 2 decimal places

In Java, there are few ways to display double in 2 decimal places. Table of contents. 1. DecimalFormat("0.00") 2. String.format("%.2f") 3. BigDecimal 4. References Possible Duplicate How to round double / float value to 2 decimal places 1. DecimalFormat(“0.00”) We can use DecimalFormat("0.00") to ensure the number is round to 2 decimal places. DecimalExample.java package …

Read more

Java – Math.pow example

A simple Math.pow example, display 2 to the power of 8. In Math 2^8 = 2x2x2x2x2x2x2x2 =256 In Java Math.pow(2, 8) Note In Java, the symbol ^ is a XOR operator, DON’T use this for the power calculation. TestPower.java package com.mkyong.test; import java.text.DecimalFormat; public class TestPower { static DecimalFormat df = new DecimalFormat(".00"); public static …

Read more

Gradle – Create Java project structure automatically

To quick start a new Gradle Java project, type gradle init –type java-library $ gradle init –type java-library :wrapper :init BUILD SUCCESSFUL Total time: 4.866 secs The following files and folders will be created automatically. P.S Tested with Gradle 2.0 1. Java Project Structure Both src/main/java and src/test/java folders are created. The Library*.java is a …

Read more

Spring Data MongoDB – Aggregation Grouping Example

In this tutorial, we will show you how to do the data grouping with Spring Data + MongoDB aggregation framework. 1. Test Data domain.json { "_id" : 1, "domainName" : "test1.com", "hosting" : "hostgator.com" } { "_id" : 2, "domainName" : "test2.com", "hosting" : "aws.amazon.com"} { "_id" : 3, "domainName" : "test3.com", "hosting" : "aws.amazon.com" …

Read more

Gradle Application Plugin – APP_HOME in applicationDefaultJvmArgs

In Gardle, the application plugin, you can pass the system properties via applicationDefaultJvmArgs : gradle.build apply plugin:’application’ mainClassName = "com.mkyong.analyzer.engine.hydra.entryPointForJar" applicationName = ‘analyzer’ distZip { archiveName ‘analyzer-‘ + version + ‘.zip’ } applicationDefaultJvmArgs = ["-Dlogback.configurationFile=logback.xml"] The problem is how to get the APP_HOME for logback.xml? gradle.build applicationDefaultJvmArgs = ["-Dlogback.configurationFile=APP_HOME/logback.xml"] You can hard code the APP_HOME, …

Read more

Spring MVC – Beans loaded twice

A Spring MVC web application, noticed all the Spring’s beans are loaded twice!? package com.mkyong.config.db; @Configuration public class MongoDevConfig { private final static Logger logger = LoggerFactory.getLogger(MongoDevConfig.class); @Bean MongoDbFactory mongoDbFactory() throws Exception { logger.debug("Init…… MongoDbFactory() in production mode!"); //… return new new SimpleMongoDbFactory(mongo, "db");; } } During Application startup : 2015-03-05 17:52:32 DEBUG c.m.config.MongoLiveConfig – …

Read more

Spring Data MongoDB – Select fields to return

In MongoDB console, you can use field:1 to select the fields to return from a query : > db.hosting.find({},{domain:1, count:1}); In Spring Data for MongoDB, you use query.fields().include : HostingDaoImpl.java package com.mkyong.core.hosting.dao; import java.util.List; import org.springframework.data.domain.Sort; import org.springframework.data.mongodb.core.query.Criteria; import org.springframework.data.mongodb.core.query.Query; import org.springframework.data.mongodb.core.query.Update; import org.springframework.stereotype.Repository; import com.hostingcompass.core.db.dao.MongoDaoImpl; @Repository public class HostingDaoImpl extends MongoDaoImpl<Hosting> implements HostingDao { …

Read more

Gradle War Plugin – Change output WAR filename

In Gradle, the WAR plugin will generate the final WAR file with the following pattern: ${baseName}-${appendix}-${version}-${classifier}.${extension} Example : hello.1.0.war To change the default WAR filename, update war.archiveName. For example : build.gradle project(‘:web’) { apply plugin: ‘war’ war { archiveName ‘hello-gradle.war’ } dependencies { compile project(‘:core’) providedCompile ‘javax.servlet:servlet-api:2.5’ providedCompile ‘org.apache.tomcat:tomcat-jsp-api:7.0.55’ //… } } Build it… $ …

Read more

How to pass System Properties in web.xml

In Java standalone application, you can use -D option to pass in the system properties : $ java -Dgeoip.file="/home/mkyong/geoip/test.db" test.jar In Java web application, you can pass the system properties via context-param in web.xml : web.xml <web-app> <context-param> <param-name>geoip.file</param-name> <param-value>/home/mkyong/geoip/test.db</param-value> </context-param> </web-app>

Spring @Value – Import a list from properties file

In this tutorial, we will show you how to import a “List” from a properties file, via Spring EL @Value Tested with : Spring 4.0.6 JDK 1.7 Spring @Value and List In Spring @Value, you can use the split() method to inject the ‘List” in one line. config.properties server.name=hydra,zeus server.id=100,102,103 AppConfigTest.java package com.mkyong.analyzer.test; import java.util.List; …

Read more

Spring @PropertySource example

Spring default loads application.properties into the application’s environment, and we can use @PropertySource to load custom .properties files. file.properties file.path=/server1/file/path Application.java @Configuration @PropertySource("classpath:file.properties") public class Application { @Value("${file.path}") private String path; //… } Table of contents: 1. Project Structure 2. Properties Files 3. @PropertySource and @Value 4. Loads property files from multiple sources 5. Placeholder …

Read more

Spring @Value default value

This article shows how to provide a default value for the @Value annotation. In the below code, if the property.name doesn’t exist in the application properties or environment, defaultValue will be assigned to the propertyName field. SimpleComponent.java import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Component; @Component public class SimpleComponent { @Value("${property.name:defaultValue}") private String propertyName; // getters, setters, etc } …

Read more

Multiple SSH private keys Examples

To allow multiple private keys connect to different servers, edit ~/.ssh/config : ~/.ssh/config Host 10.10.10.1 IdentityFile ~/.ssh/linode_rsa Host 200.20.20.2 IdentityFile ~/.ssh/id_rsa If you SSH to 10.10.10.1, private key ~/.ssh/linode_rsa will be used. If you SSH to 200.20.20.2, private key ~/.ssh/id_rsa will be used. 1. Single Private Key for Multiple Servers 1.1 You have following public …

Read more

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