jConsole – JMX remote access on Tomcat

In this tutorial, we will show you how to use jConsole to remote access a Tomcat instance, for JVM monitoring stuff. Tools and environment used : Ubuntu 13 + Tomcat 7 + 192.168.1.142 Windows 8 + jConsole + 192.168.1.200 1. Tomcat + JMX To connect with jConsole, Tomcat need to enable the JMX options. To …

Read more

Eclipse + Tomcat – java.lang.OutOfMemoryError: Java heap space

In Eclipse IDE, run a Java web application with Tomcat server plugin, but the console prompts Exception in thread "x" java.lang.OutOfMemoryError: Java heap space 1. Solution – Increase Heap Size in Tomcat By default, Tomcat allocated a small amount of heap size. To solve it, you need to increase the Tomcat’s heap size manually. 1.1 …

Read more

Grep for Windows – findstr example

I love grep command on Linux, it helped to search and filter strings easily, always wonder what is the equivalent tool on Windows, and found this findstr recently. In this article, I will share some of my favorite “grep” examples on Linux, and how to “port” it to Windows with “findstr” command. 1. Filter a …

Read more

Find out your Java heap memory size

In this article, we will show you how to use the -XX:+PrintFlagsFinal to find out your heap size detail. In Java, the default and maximum heap size are allocated based on this – ergonomics algorithm. Heap sizes Initial heap size of 1/64 of physical memory up to 1Gbyte Maximum heap size of 1/4 of physical …

Read more

JSP – jsessionid appear in CSS and JS link

In Spring MVC + JSP view page environment. index.jsp <html> <head> <title>Welcome!</title> <c:url var="assets" value="/resources/abc" /> <link href="${assets}/css/style.min.css" rel="stylesheet"> <script src="<c:url value="/resources/js/jquery.1.10.2.min.js" />"> </script> </head> … </html> In the Spring config file, mapped a resource path, mvc-dispatcher-servlet.xml <beans … <context:component-scan base-package="com.mkyong.test" /> <mvc:resources mapping="/resources/**" location="/resources/" /> </beans> 1. Problem After deployed, Spring MVC can’t get …

Read more

Java – Append values into an Object[] array

In this example, we will show you how to append values in Object[] and int[] array. Object[] obj = new Object[] { "a", "b", "c" }; ArrayList<Object> newObj = new ArrayList<Object>(Arrays.asList(obj)); newObj.add("new value"); newObj.add("new value 2"); 1. Object[] Array Example Example to append values with ArrayList : TestApp.java package com.mkyong.test; import java.util.ArrayList; import java.util.Arrays; public …

Read more

Java – Convert int[] to Integer[] example

Examples show you how to convert between int[] and its’ wrapper class Integer[]. 1. Convert int[] to Integer[] public static Integer[] toObject(int[] intArray) { Integer[] result = new Integer[intArray.length]; for (int i = 0; i < intArray.length; i++) { result[i] = Integer.valueOf(intArray[i]); } return result; } 2. Convert Integer[] to int[] public static int[] toPrimitive(Integer[] …

Read more

CloudFlare + WordPress admin, Cache issue

Below is my website environment : WordPress 3.8.1 CloudFlare Pro Plan 1. Problem I’m unable to login WordPress after changing my custom DNS to CloudFlare, below is the error message : ERROR: Cookies are blocked or not supported by your browser. You must enable cookies to use WordPress P.S The browser’s cookies are enabled. Here’s …

Read more

Java AWT – Drawing rectangle, line and circle

The java.awt libraries are set of classes provided by Java in order to draw shapes on a window. The abbreviation AWT stands for Abstract Windowing Toolkit. Today, the library has been converted into a huge set of classes which allows the user to create an entire GUI based application. The visual appearance of these classes …

Read more

TestNG + Spring Integration Example

In this tutorial, we will show you how to test Spring’s components with TestNG. Tools used : TestNG 6.8.7 Spring 3.2.2.RELEASE Maven 3 Eclipse IDE 1. Project Dependencies To integrate Spring with TestNG, you need spring-test.jar, add the following : pom.xml <properties> <spring.version>3.2.2.RELEASE</spring.version> <testng.version>6.8.7</testng.version> </properties> <dependencies> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-core</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-test</artifactId> <version>${spring.version}</version> …

Read more

TestNG – Groups Test

In this tutorial, we will show you how to do the group testing in TestNG. 1. Groups on Methods Review a test group example. runSelenium() and runSelenium1() are belong to group selenium-test. testConnectOracle() and testConnectMsSQL() are belong to group database. runFinal() will be executed if groups selenium-test and database are passed. TestGroup.java package com.mkyong.testng.examples.group; import …

Read more

MongoDB – Aggregate and Group example

In this tutorial, we will show you how to use MongoDB aggregate function to group documents (data). 1. Test Data Data in JSON format, shows the hosting provider for website. website.json { “_id” : 1, “domainName” : “test1.com”, “hosting” : “hostgator.com” } { “_id” : 2, “domainName” : “test2.com”, “hosting” : “aws.amazon.com”} { “_id” : …

Read more

Maven + Emma code coverage example

Emma is a free Java code coverage tool. In this tutorial, we will show you how to use Maven to generate the Emma code coverage report for your project, and also how to integrate the Emma report into the Maven project site. 1. Generate Emma Code Coverage Report Do nothing, just type the following Maven …

Read more

Maven site build is very slow – dependency report

Creating a Maven site, but the build is very slow to generate the dependency report. C:\mkyong_projects\>mvn site [INFO] Scanning for projects… [INFO] [INFO] ————————————– [INFO] Building Maven Webapp 1.0-SNAPSHOT [INFO] ————————————– [INFO] //… [INFO] Generating "Project License" report [INFO] Generating "Project Team" report [INFO] Generating "Project Summary" report [INFO] Generating "Dependencies" report //…… Hanging here… …

Read more

Emma – Class x appears to be instrumented already

Review the “maven-emma-plugin” in pom.xml : pom.xml <project> //… <build> <plugins> <plugin> <groupId>org.codehaus.mojo</groupId> <artifactId>emma-maven-plugin</artifactId> <version>1.0-alpha-3</version> <inherited>true</inherited> <executions> <execution> <phase>process-classes</phase> <goals> <goal>instrument</goal> </goals> </execution> </executions> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-surefire-plugin</artifactId> <inherited>true</inherited> <configuration> <forkMode>once</forkMode> <reportFormat>xml</reportFormat> <classesDirectory> ${project.build.directory}/generated-classes/emma/classes </classesDirectory> </configuration> </plugin> </plugins> </build> </project> 1. Problem When I run the command mvn emma:emma to generate the code coverage report, …

Read more

The type DefaultHttpClient is deprecated

Eclipse IDE prompts warning on new DefaultHttpClient, mark this class as deprecated. package com.mkyong.web.controller; import org.apache.http.Header; import org.apache.http.HttpResponse; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.DefaultHttpClient; public class WebCrawler { public static void main(String[] args) throws Exception { HttpClient client = new DefaultHttpClient(); HttpGet request = new HttpGet("https://mkyong.com"); HttpResponse response = client.execute(request); //… } } Solution Dive …

Read more

Java – Check if web request is from Google crawler

If a web request is coming from Google crawler or Google bot, the requested “user agent” should look similar like this : Mozilla/5.0 (compatible; Googlebot/2.1; +http://www.google.com/bot.html) or (rarely used): Googlebot/2.1 (+http://www.google.com/bot.html) Source : Google crawlers 1. Java Example In Java, you can get the “user agent” from HttpServletRequest. Example : Service hosted at abcdefg.com @Autowired …

Read more

How To Get HTTP Request Header In Java

This example shows you how to get the HTTP request headers in Java. To get the HTTP request headers, you need this class HttpServletRequest : 1. HttpServletRequest Examples 1.1 Loop over the request header’s name and print out its value. WebUtils.java package com.mkyong.web.utils; import javax.servlet.http.HttpServletRequest; import java.util.Enumeration; import java.util.HashMap; import java.util.Map; public class WebUtils { …

Read more

Java – Write directly to memory

You have been told a lot that you can’t manage memory in Java. Well, it has changed since HotSpot release of the Java VM. There is a way to directly allocate and deallocate memory as well as write and read it… Of course we are talking about the JVM memory where the Java program runs. …

Read more

Donate to Charity

If you like my works and tutorials on “mkyong.com”, please consider making a donation of $10 or whatever you can to protect and sustain the following charities : Thanks. 1. Doctors Without Borders The Doctors Without Borders works in nearly 70 countries providing medical aid to those most in need regardless of their race, religion, …

Read more

Java Custom Annotations Example

In this tutorial, we will show you how to create two custom annotations – @Test and @TestInfo, to simulate a simple unit test framework. P.S This unit test example is inspired by this official Java annotation article. 1. @Test Annotation This @interface tells Java this is a custom annotation. Later, you can annotate it on …

Read more

TestNG Hello World Example

A classic example, show you how to get started with TestNG unit test framework. Tools used : TestNG 6.8.7 Maven 3 Eclipse IDE 1. TestNG Dependency Add TestNG library in the pom.xml. pom.xml <dependency> <groupId>org.testng</groupId> <artifactId>testng</artifactId> <version>6.8.7</version> <scope>test</scope> </dependency> 2. TestNG Example Review a simple class, has a method to return a fixed email “[email protected]”. …

Read more

Java – String vs StringBuffer

This article shows the difference in time taken for similar operations on a String object and StringBuffer object. String being an immutable class, it instantiates a new object each time an operation is performed on it StringBuffer being a mutable class, the overhead of object instantiation during operations is removed. Hence, the time taken for …

Read more

Java and “& 0xFF” example

Before you understand what is & 0xFF, make sure you know following stuffs : Bitwise AND operator, link. Converts hex to/from binary, and decimal to/from binary. In short, & 0xFF is used to make sure you always get the last 8 bits. Let’s see an example to convert an IP address to/from decimal number. 1. …

Read more

Eclipse – java.lang.OutOfMemoryError: Java heap space

This article shows how to solve the java.lang.OutOfMemoryError: Java heap space in Eclipse IDE. Table of contents 1. Eclipse – OutOfMemoryError: Java heap space 2. Temporary fix – Increase the heap size 3. eclipse.ini 4. The solution, find the reason behind the heap size error. 5. References 1. Eclipse – OutOfMemoryError: Java heap space In …

Read more

Java Date and Calendar examples

This tutorial shows you how to work with java.util.Date and java.util.Calendar. 1. Java Date Examples Few examples to work with Date APIs. Example 1.1 – Convert Date to String. SimpleDateFormat sdf = new SimpleDateFormat("dd/M/yyyy"); String date = sdf.format(new Date()); System.out.println(date); //15/10/2013 Example 1.2 – Convert String to Date. SimpleDateFormat sdf = new SimpleDateFormat("dd-M-yyyy hh:mm:ss"); String …

Read more

Eclipse – How to attach JDK source code

This article shows you how to attach the JDK source code in Eclipse IDE. In Eclipse, select Windows -> Preferences -> Java -> Installed JREs , expands rt.jar, select “Source attachment” and find the src.zip from your disk drive. P.S JDK source code is inside the src.zip. Note You may interest at this article – …

Read more

Where to download Java JDK source code ?

The JDK source code is inside the src.zip, this article shows you how to get it on Windows, Ubuntu (Linux) and Mac OSX. 1. Windows In Windows, visit the Oracle website and download the JDK (not JRE). Install the JDK and the src.zip is inside the JDK installed folder, for example : C:\Program Files\Java\jdk1.7.0_40\src.zip 2. …

Read more

Java – How to calculate leap year

A leap year is a year containing one additional day (366 days a year). Review the leap year algorithm : if year is divisible by 400 then is_leap_year else if year is divisible by 100 then not_leap_year else if year is divisible by 4 then is_leap_year else not_leap_year P.S Algorithm from wikipedia leap year. 1. …

Read more

Java – Time elapsed in days, hours, minutes, seconds

Two Java examples show you how to print the elapsed time in days, hours, minutes and seconds format. 1. Standard JDK Date APIs You need to calculate the elapsed time manually. DateTimeUtils.java package com.mkyong.dateUtils; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; public class DateTimeUtils { public static void main(String[] args) { DateTimeUtils obj = new DateTimeUtils(); …

Read more

Spring Data MongoDB : get last modified records (date sorting)

In Mongodb, you can use sort()to do the date sorting. 1. MongoDB Sorting Examples In Mongodb, to sort a “date” field, issues : //The ‘1’ = sort ascending (oldest to newest) db.domain.find().sort({lastModifiedDate:1}) { "_id" : 1, "lastModifiedDate" : ISODate("2013-08-13T07:18:04.774Z") } { "_id" : 2, "lastModifiedDate" : ISODate("2013-09-03T08:12:16.309Z") } { "_id" : 3, "lastModifiedDate" : ISODate("2013-10-03T08:12:16.309Z") …

Read more

Spring Data MongoDB : like query example

In SQL, the ‘like’ query is looks like this : select * from tags where tagName like ‘%apple%’ In MongoDB console, it looks like this : db.tags.find({"tagName": /apple/}) In Spring data mongodb, it implements with Criteria or BasicQuery : String tagName = "apple"; Query query = new Query(); query.limit(10); query.addCriteria(Criteria.where("tagName").regex(tagName)); mongoOperation.find(query, Tags.class); String tagName = …

Read more

jQuery loop over JSON string – $.each example

Review a simple jQuery example to loop over a JavaScript array object. var json = [ {"id":"1","tagName":"apple"}, {"id":"2","tagName":"orange"}, {"id":"3","tagName":"banana"}, {"id":"4","tagName":"watermelon"}, {"id":"5","tagName":"pineapple"} ]; $.each(json, function(idx, obj) { alert(obj.tagName); }); Above code snippet is working fine, prompts the “apple”, “orange” … as expected. Problem : JSON string Review below example, declares a JSON string (enclosed with single …

Read more