Apache HttpClient Examples

This article shows you how to use Apache HttpClient to send an HTTP GET/POST requests, JSON, authentication, timeout, redirection and some frequent used examples. P.S Tested with HttpClient 4.5.10 pom.xml <dependency> <groupId>org.apache.httpcomponents</groupId> <artifactId>httpclient</artifactId> <version>4.5.10</version> </dependency> 1. Send GET Request 1.1 Close manually. HttpClientExample1_1.java package com.mkyong.http; import org.apache.http.HttpEntity; import org.apache.http.HttpHeaders; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.CloseableHttpClient; …

Read more

According to TLD, tag form:input must be empty, but is not

Problem Developing a search form with the Spring MVC framework. /WEB-INF/pages/tools/webserver.jsp – Spring mvc + form tag <form:form method="post" commandName="searchForm" action="${pageContext.request.contextPath}/tools/webserver/" class="navbar-form pull-left" id="search-form"> Type a website : <form:input path="domainName" type="text" width="165px" placeholder="example – google.com" /> <button type="submit" class="btn btn-top-margin">Search</button> </form:form> Spring Controller @Controller @RequestMapping(value = "/tools", method = RequestMethod.GET) public class ToolsController { @RequestMapping(value …

Read more

ASCII Art Java example

A funny Java example to create an ASCII art graphic. The concept is simple, get the image’s rgb color in “integer mode”, later, replace the color’s integer with ascii text. P.S This example is credited for this post ASCIIArtService.java package com.mkyong.service; import java.awt.*; import java.awt.image.BufferedImage; import java.io.IOException; public class ASCIIArtService { public static void main(String[] …

Read more

New Relic for PHP, with cPanel + VPS

Here’s my journey to install “New Relic for PHP” to monitor my WordPress’s blog performance. Below is my server environment : Operating system CentOS 6.x 64-bit, VPS with root access cPanel 11.x Apache version 2.x PHP version 5.3.13 WordPress 3.5.1 P.S The New Relic is a web application performance tool. First, see how “New Relic …

Read more

Spring asm dependency issue in Spring Data

Using Spring Data MongoDB 1.2.1.RELEASE and Spring core 3.2.2.RELEASE, while system is starting, it hits some weird spring-asm IncompatibleClassChangeError errors : java.lang.IncompatibleClassChangeError: class org.springframework.core.type.classreading.ClassMetadataReadingVisitor has interface org.springframework.asm.ClassVisitor as super class pom.xml <properties> <spring.version>3.2.2.RELEASE</spring.version> <springdata.version>1.2.1.RELEASE</springdata.version> </properties> <dependencies> <!– Spring Core –> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-core</artifactId> <version>${spring.version}</version> </dependency> <!– Spring Data for MongoDB –> <dependency> <groupId>org.springframework.data</groupId> <artifactId>spring-data-mongodb</artifactId> <version>${springdata.version}</version> …

Read more

Display a list of countries in Java

In this article, we show you how to use the Locale class to play around the list of countries. P.S Tested with JDK 1.6 1. List of Countries The Locale.getISOCountries() will return a list of all 2-letter country codes defined in ISO 3166. ListCountry.java package com.webmitta.model; import java.util.Locale; public class ListCountry { public static void …

Read more

MongoDB import and export example

In this tutorial, we show you how to backup and restore MongoDB with the commands : mongoexport and mongoimport. 1. Backup database with mongoexport Few examples to show you how to use the mongoexport to back up the database. Review some of the common use options. $ mongoexport Export MongoDB data to CSV, TSV or …

Read more

Spring Data MongoDB : Save binary file, GridFS example

In MongoDB, you can use GridFS to store binary files. In this tutorial, we show you how to use Spring Data’s GridFsTemplate to store / read image in / from MongoDB. 1. GridFS – Save example (Spring config in Annotation) Gat an image file and save it into MongoDB. SpringMongoConfig.java package com.mkyong.config; import org.springframework.context.annotation.Bean; import …

Read more

Java HttpURLConnection follow redirect example

The HttpURLConnection‘s follow redirect is just an indicator, in fact it won’t help you to do the “real” http redirection, you still need to handle it manually. URL obj = new URL(url); HttpURLConnection conn = (HttpURLConnection) obj.openConnection(); conn.setInstanceFollowRedirects(true); //you still need to handle redirect manully. HttpURLConnection.setFollowRedirects(true); 1. Java Http Redirect Example If a server is …

Read more

Download JDK Source code for Mac OS X

The JDK source code is packaged in a src.jar, and should be in the JDK/Home folder. However, some JDK versions in Mac OSX didn’t include the source code or Javadoc. Try find it : sudo find / -name src.jar If you couldn’t find the src.jar, then get it from Apple developer website. 1. Download from …

Read more

How to get HTTP Response Header in Java

This example shows you how to get the Http response header values in Java. 1. Standard JDK example. URL obj = new URL("https://mkyong.com"); URLConnection conn = obj.openConnection(); //get all headers Map<String, List<String>> map = conn.getHeaderFields(); for (Map.Entry<String, List<String>> entry : map.entrySet()) { System.out.println("Key : " + entry.getKey() + " ,Value : " + entry.getValue()); } …

Read more

MongoDB Authentication example

This guide shows you how to enable authentication in MongoDB. The authentication is disabled by default. To configure it, you must first add a user to the “admin” database. > show dbs admin #add single user to this database testdb Note Users with normal access in “admin” database, HAVE read and write access to all …

Read more

MongoDB : couldn’t open /data/db/yourdb.ns errno:13 Permission denied

Starting MongoDB server, it shows error “Permission denied” on one of the database and shutdown the server automatically. $ mongod Fri Mar 8 22:54:46 [initandlisten] MongoDB starting : pid=13492 port=27017 dbpath=/data/db/ 64-bit host=Yongs-MacBook-Air.local //… Fri Mar 8 22:54:46 [initandlisten] journal dir=/data/db/journal Fri Mar 8 22:54:46 [initandlisten] recover : no journal files present, no recovery needed …

Read more

How to install MongoDB on Mac OS X

A guide to show you how to install MongoDB on Mac OS X. MongoDB 2.2.3 Mac OS X 10.8.2 1. Download MongoDB Get MongoDB from official website, extracts it : $ cd ~/Download $ tar xzf mongodb-osx-x86_64-2.2.3.tgz $ sudo mv mongodb-osx-x86_64-2.2.3 /usr/local/mongodb 2. MongoDB Data By default, MongoDB write/store data into the /data/db folder, you …

Read more

How to set environment variables on Mac OS X

In Mac OS X, you can set the environment variables in one of the following files : ~/.bashrc ~/.bash_profile ~/.profile By default, Mac OS X does not has above files, you need to create it manually. $PATH example This example shows you how to set “mongodb/bin” folder to the existing $PATH environment variable. $ echo …

Read more

Maven $JAVA_HOME is not defined correctly on Mac OS

This article shows how to fix the Maven error JAVA_HOME is not defined correctly. Terminal $ mvn -version Error: JAVA_HOME is not defined correctly. We cannot execute /usr/libexec/java_home/bin/java Further Reading How to set $JAVA_HOME environment variable on macOS 1. $JAVA_HOME and macOS 10.15 Catalina, macOS 11 Big Sur On macOS 10.15 Catalina and later, the …

Read more

Due to limitations of the BasicDBObject, you can’t add a second ‘$and’

Problem Using Spring data and Mongodb, below is a function to find data within a date range. public List<RequestAudit> findByIpAndDate(String ip, Date startDate, Date endDate) { Query query = new Query( Criteria.where("ip").is(ip) .andOperator(Criteria.where("createdDate").gte(startDate)) .andOperator(Criteria.where("createdDate").lt(endDate)) ); return mongoOperation.find(query, RequestAudit.class); } It hits following error message : org.springframework.data.mongodb.InvalidMongoDbApiUsageException: Due to limitations of the com.mongodb.BasicDBObject, you can’t add …

Read more

How to Set $JAVA_HOME environment variable on macOS

This article shows how to set the $JAVA_HOME environment variable on older Mac OS X and the latest macOS 11. Topics macOS release history What is /usr/libexec/java_home $JAVA_HOME and macOS 11 Big Sur $JAVA_HOME and Mac OS X 10.5 Leopard $JAVA_HOME and older Mac OS X Switch between different JDK versions Solution Steps to set …

Read more

How to get client Ip Address in Java

In Java, you can use HttpServletRequest.getRemoteAddr() to get the client’s IP address that’s accessing your Java web application. import javax.servlet.http.HttpServletRequest; String ipAddress = request.getRemoteAddr(); 1. Proxy Server or Cloudflare For web application which is behind a proxy server, load balancer or the popular Cloudflare solution, you should get the client IP address via the HTTP …

Read more

Access restriction: The type BASE64Encoder is not accessible due to restriction

Problem Downloaded a Java sample from Alexa API on Amazon service, imports it into Eclipse, but unable to compile and hits following “Access restriction” errors : Access restriction: The type BASE64Encoder is not accessible due to restriction on required library /System/Library/Java/JavaVirtualMachines/1.6.0.jdk/Contents/Classes/classes.jar P.S Using JDK 1.6 and Eclipse IDE 4.2 import sun.misc.BASE64Encoder; // Access restriction error …

Read more

Spring REST @RequestMapping extract incorrectly if value contains ‘.’

Problem See following Spring REST example, if a request such as “http://localhost:8080/site/google.com” is submitted, Spring returns “google“. Look like Spring treats “.” as file extension, and extract half of the parameter value. SiteController.java package com.mkyong.web.controller; import org.springframework.stereotype.Controller; import org.springframework.ui.ModelMap; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; @Controller @RequestMapping("/site") public class SiteController { @RequestMapping(value = "/{domain}", method …

Read more

How to get Alexa Ranking In Java

In this example, we show you how to use Java and DOM XML parser to get the Alexa ranking from below the undocumented API : http://data.alexa.com/data?cli=10&url=domainName 1. Alexa API For example, type following URL in your browser : http://data.alexa.com/data?cli=10&url=mkyong.com Alexa will return back following XML result : <ALEXA VER="0.9" URL="mkyong.com/" HOME="0" AID="="> <DMOZ> <SITE BASE="mkyong.com/" …

Read more

How to get Google PageRank (PR) in Java

In this example, we will show you how to get Google PageRank (PR) in Java. To request a PageRank for “mkyong.com”, you just need to send following HTTP request : http://toolbarqueries.google.com/tbr?client=navclient-auto&hl=en&ch=6236440745 &ie=UTF-8&oe=UTF-8&features=Rank&q=info:mkyong.com P.S Above URL is used by Google toolbar plugin. The tricky part is following hashing value : ch=6236440745 Google is using Bob Jenkins …

Read more

How to run a MySQL Script using Java

In this tutorial, I will show you how to run a MySQL script file using ibatis ScriptRunner class. First, download the ibatis and Mysql JDBC Driver, and add the jar files into your classpath. Now, run below code. It will execute a script.sql file. RunSqlScript.java package com.mkyong; import java.io.BufferedReader; import java.io.FileReader; import java.io.Reader; import java.sql.Connection; …

Read more

web.xml deployment descriptor examples

The web.xml is a configuration file to describe how a web application should be deployed. Here’re 5 web.xml examples, just for self-reference. 1. Servlet 3.1 deployment descriptor Java EE 7 XML schema, namespace is http://xmlns.jcp.org/xml/ns/javaee/ web.xml <web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" version="3.1"> </web-app> 2. Servlet 3.0 deployment descriptor Java EE 6 XML schema, namespace is …

Read more

Convert Java Project to Web Project in Eclipse

This tutorial shows you how to convert a Java project to Java web application project in Eclipse 4.2, it should work in older version as well. 1. Java Project A simple Java project. 2. Project Facets Right click on the project properties. Select “Project Facets“, and click “convert to faceted form…” Check “Dynamic Web Module” …

Read more

Review : Java 7 Concurrency Cookbook

The Java 7 Concurrency Cookbook, containing over 60 examples show you how to do multithreaded programming in Java. It shows varies threading topics from beginner level to advanced level, including thread management like create, interrupt and monitor thread, using Java 5 Executor frameworks to run or schedule threads, and the latest Java 7 fork/Join Frameworks …

Read more

Search directories recursively for file in Java

Here’s an example to show you how to search a file named “post.php” from directory “/Users/mkyong/websites” and all its subdirectories recursively. FileSearch.java package com.mkyong; import java.io.File; import java.util.ArrayList; import java.util.List; public class FileSearch { private String fileNameToSearch; private List<String> result = new ArrayList<String>(); public String getFileNameToSearch() { return fileNameToSearch; } public void setFileNameToSearch(String fileNameToSearch) { …

Read more

Spring and Java Thread example

Here are 3 examples to show you how to do “threading” in Spring. See the code for self-explanatory. 1. Spring + Java Threads example Create a simple Java thread by extending Thread, and managed by Spring’s container via @Component. The bean scope must be “prototype“, so that each request will return a new instance, to …

Read more

How to execute shell command from Java

In Java, we can use ProcessBuilder or Runtime.getRuntime().exec to execute external shell command : 1. ProcessBuilder ProcessBuilder processBuilder = new ProcessBuilder(); // — Linux — // Run a shell command processBuilder.command("bash", "-c", "ls /home/mkyong/"); // Run a shell script //processBuilder.command("path/to/hello.sh"); // — Windows — // Run a command //processBuilder.command("cmd.exe", "/c", "dir C:\\Users\\mkyong"); // Run a …

Read more

Add color to the bash terminal in Mac OS X

By default, the bash terminal in Mac OSX looks plain. bash terminal, profile = Homebrew 1. Add Color To Bash To make the bash terminal console more colorful, you need to create or edit a ~/.bash_profile file, and configure the LSCOLORS value. See following example to show you how to create a new .bash_profile and …

Read more

How to count duplicated items in Java List

A Java example to show you how to count the total number of duplicated entries in a List, using Collections.frequency and Map. CountDuplicatedList.java package com.mkyong; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.TreeMap; public class CountDuplicatedList { public static void main(String[] args) { List<String> list = new …

Read more

Java : getResourceAsStream in static method

To call getResourceAsStream in a static method, we use ClassName.class instead of getClass() 1. In non static method getClass().getClassLoader().getResourceAsStream("config.properties")) 2. In static method ClassName.class.class.getClassLoader().getResourceAsStream("config.properties")) 1. Non Static Method A .properties file in project classpath. src/main/resources/config.properties #config file json.filepath = /Users/mkyong/Documents/workspace/SnakeCrawler/data/ FileHelper.java package com.mkyong; import java.io.IOException; import java.io.InputStream; import java.util.Properties; public class FileHelper { public static …

Read more