Java – How to shuffle an ArrayList

In Java, you can use Collections.shuffle to shuffle or randomize a ArrayList TestApp.java package com.mkyong.utils; import java.util.Arrays; import java.util.Collections; import java.util.List; public class TestApp { public static void main(String[] args) { List<String> list = Arrays.asList("A", "B", "C", "D", "1", "2", "3"); //before shuffle System.out.println(list); // again, same insert order System.out.println(list); // shuffle or randomize Collections.shuffle(list); …

Read more

Spring MVC – How to get client IP address

In Spring framework, you can @Autowired a HttpServletRequest in any Spring managed bean directly, and later get the client’s IP address from the request headers WebUtils.java package com.mkyong.web; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import javax.servlet.http.HttpServletRequest; @Component public class WebUtils { private HttpServletRequest request; @Autowired public void setRequest(HttpServletRequest request) { this.request = request; } private static String …

Read more

Java 8 Streams map() examples

In Java 8, stream().map() lets you convert an object to something else. Review the following examples : 1. A List of Strings to Uppercase 1.1 Simple Java example to convert a list of Strings to upper case. TestJava8.java package com.mkyong.java8; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.stream.Collectors; public class TestJava8 { public static void …

Read more

Java 8 Tutorials

A series of Java 8 tips and examples, hope you like it. FAQs Some common asked questions. Java 8 forEach examples Java 8 Convert List to Map Java 8 Lambda : Comparator example Java 8 method references, double colon (::) operator Java 8 Streams filter examples Java 8 Streams map() examples 1. Functional Interface Java …

Read more

java.lang.NoClassDefFoundError: com/fasterxml/jackson/annotation/JsonMerge

Run a Jackson related project and hits the following JsonMerge not found error. Console java.lang.NoClassDefFoundError: com/fasterxml/jackson/annotation/JsonMerge at com.fasterxml.jackson.databind.introspect.JacksonAnnotationIntrospector.<clinit>(JacksonAnnotationIntrospector.java:50) ~[jackson-databind-2.9.0.pr1.jar:2.9.0.pr1] at com.fasterxml.jackson.databind.ObjectMapper.<clinit>(ObjectMapper.java:292) ~[jackson-databind-2.9.0.pr1.jar:2.9.0.pr1] at com.hostingcompass.core.utils.PrintUtils.<clinit>(PrintUtils.java:9) ~[main/:na] at com.hostingcompass.app.run.TurtleApp.run(TurtleApp.java:25) ~[main/:na] at com.hostingcompass.app.Main.run(Main.java:42) [main/:na] at org.springframework.boot.SpringApplication.callRunner(SpringApplication.java:776) [spring-boot-1.5.2.RELEASE.jar:1.5.2.RELEASE] at org.springframework.boot.SpringApplication.callRunners(SpringApplication.java:760) [spring-boot-1.5.2.RELEASE.jar:1.5.2.RELEASE] at org.springframework.boot.SpringApplication.afterRefresh(SpringApplication.java:747) [spring-boot-1.5.2.RELEASE.jar:1.5.2.RELEASE] at org.springframework.boot.SpringApplication.run(SpringApplication.java:315) [spring-boot-1.5.2.RELEASE.jar:1.5.2.RELEASE] at org.springframework.boot.SpringApplication.run(SpringApplication.java:1162) [spring-boot-1.5.2.RELEASE.jar:1.5.2.RELEASE] at org.springframework.boot.SpringApplication.run(SpringApplication.java:1151) [spring-boot-1.5.2.RELEASE.jar:1.5.2.RELEASE] at com.hostingcompass.app.Main.main(Main.java:34) [main/:na] at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) …

Read more

Spring Boot Tutorials

Spring Boot makes it quick and easy to create a Spring based applications. *Spring Boot 4 minimum supported versions: Spring Framework 7.0.7 Java 17 (up to Java 26) Jakarta EE 11 (jakarta.*) Maven 3.6.3 or later Gradle 7.6.4 or later, and 8.x Spring Boot 4 supports the following embedded servlet containers: Tomcat 11.0, Servlet 6.1 …

Read more

Spring Boot – Profile based properties and yaml example

In Spring Boot, it picks .properties or .yaml files in the following sequences : application-{profile}.properties and YAML variants application.properties and YAML variants Note For detail, sequence and order, please refer to this official Externalized Configuration documentation. Tested : Spring Boot 2.1.2.RELEASE Maven 3 1. Project Structure A standard Maven project structure. 2. @ConfigurationProperties Read the …

Read more

Spring Boot Profiles example

In this article, we will show you how to use @Profile in Spring Boot and also how to test it. Tested with : Spring Boot 2.1.2.RELEASE Maven 3 1. Project Structure A standard Maven project structure. 2. Project Dependency pom.xml <?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <artifactId>spring-boot-profile</artifactId> <packaging>jar</packaging> <name>Spring Boot Profiles Example</name> …

Read more

Spring Boot Test – How to disable DEBUG and INFO logs

Run the Spring Boot integration test or unit test, many annoying DEBUG and INFO logs are displayed in the console. P.S Tested with Spring Boot 2 Console 2019-03-04 13:15:25.151 INFO — [ main] .b.t.c.SpringBootTestContextBootstrapper : 2019-03-04 13:15:25.157 INFO — [ main] o.s.t.c.support.AbstractContextLoader : 2019-03-04 13:15:25.158 INFO — [ main] t.c.s.AnnotationConfigContextLoaderUtils : 2019-03-04 13:15:25.298 INFO — …

Read more

Gradle is not sync with IntelliJ IDEA

Make some changes in the build.gradle file, but the changes never apply or sync to the IDEA (Tested with 2016.3) 1. Using IDEA plugin build.gradle apply plugin: ‘java’ apply plugin: ‘idea’ apply plugin: ‘org.springframework.boot’ 2. Make changes and issue the Gradle clean and idea command. Console $ gracle clean idea $ gradle cleanIdea idea $ …

Read more

Spring Boot + Spring Data JPA + Java 8 date and time (JSR310)

In Spring Boot + Spring Data JPA application, to support the JSR310 java.time.* APIs, we need to register this Jsr310JpaConverters manually. import org.springframework.boot.autoconfigure.domain.EntityScan; import org.springframework.data.jpa.convert.threeten.Jsr310JpaConverters; @EntityScan( basePackageClasses = {Application.class, Jsr310JpaConverters.class} ) @SpringBootApplication public class Application { //… } P.S Tested with Spring Boot 1.5.1.RELEASE, Spring Data JPA 1.11.0.RELEASE 1. Full Example 1.1 A model contains …

Read more

How to display all beans loaded by Spring Boot

In Spring Boot, you can use appContext.getBeanDefinitionNames() to get all the beans loaded by the Spring container. 1. CommandLineRunner as Interface Application.java package com.mkyong; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.CommandLineRunner; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.context.ApplicationContext; import java.util.Arrays; @SpringBootApplication public class Application implements CommandLineRunner { @Autowired private ApplicationContext appContext; public static void main(String[] args) throws Exception { …

Read more

Spring Data – Add custom method to Repository

In this article, we will show you how to add a custom method to Spring Data JPA CrudRepository and MongoDB MongoRepository 1. CrudRepository 1.1 Review a CustomerRepository, we will add a custom method to this repository. CustomerRepository.java package com.mkyong.dao; import com.mkyong.model.Customer; import org.springframework.data.jpa.repository.Query; import org.springframework.data.repository.CrudRepository; import org.springframework.data.repository.query.Param; import java.util.Date; import java.util.List; import java.util.stream.Stream; public interface …

Read more

Spring Boot + Spring Data MongoDB example

In this article, we will show you how to create a Spring Boot + Spring Data MongoDB application, using Gradle build tool. Spring Boot 1.5.1.RELEASE MongoDB Gradle Java 8 1. Project Structure A standard project structure. 2. Project Dependency 2.1 A Gradle build file. build.gradle buildscript { repositories { mavenCentral() } dependencies { classpath("org.springframework.boot:spring-boot-gradle-plugin:1.5.1.RELEASE") } …

Read more

JPA Insert + Oracle Sequences example

A quick JPA + Oracle sequences example, for self reference. 1. Oracle Database Issue the following SQL script to create a table and a sequence. CREATE TABLE CUSTOMER( ID NUMBER(10) NOT NULL, NAME VARCHAR2(100) NOT NULL, EMAIL VARCHAR2(100) NOT NULL, CREATED_DATE DATE NOT NULL, CONSTRAINT CUSTOMER_PK PRIMARY KEY (ID) ); CREATE SEQUENCE customer_seq MINVALUE 1 …

Read more

Spring Boot – Show Hibernate SQL query

Add the following lines in application.properties to log the Hibernate SQL query. application.properties #show sql statement logging.level.org.hibernate.SQL=debug #show sql values logging.level.org.hibernate.type.descriptor.sql=trace 1. org.hibernate.SQL=debug application.properties logging.level.org.hibernate.SQL=debug 1.1 Select query. Console 2017-02-23 21:36:42 DEBUG org.hibernate.SQL – select customer0_.id as id1_0_, customer0_.created_date as created_date2_0_, customer0_.email as email3_0_, customer0_.name as name4_0_ from customer customer0_ 2. org.hibernate.type.descriptor.sql=trace application.properties logging.level.org.hibernate.SQL=debug logging.level.org.hibernate.type.descriptor.sql=trace …

Read more

Spring Boot + Spring Data JPA + Oracle example

In this article, we will show you how to create a Spring Boot + Spring Data JPA + Oracle + HikariCP connection pool example. Tools used in this article : Spring Boot 1.5.1.RELEASE Spring Data 1.13.0.RELEASE Hibernate 5 Oracle database 11g express Oracle JDBC driver ojdbc7.jar HikariCP 2.6 Maven Java 8 1. Project Structure A …

Read more

WordPress – Disable comments on attachments

After stopped and cleaned the WordPress pingback and trackback spams, those spammers have changed strategy to start spamming comments and trackbacks on the post attachments. Solution 1.1 Stop commenting on new and existing attachment. Add below PHP script in theme’s function.php ${theme_folder}/function.php //disable comments on attachment function filter_media_comment_status( $open, $post_id ) { $post = get_post( …

Read more

Spring Boot JDBC + Oracle database + Commons DBCP2 example

In this article, we will show you how to create a Spring Boot JDBC application + Oracle database + Commons DBCP2 connection pool. Tools used in this article : Spring Boot 1.5.1.RELEASE Oracle database 11g express Oracle JDBC driver ojdbc7.jar Commons DBCP2 2.1.1 Maven Java 8 Note Related – Spring Boot JDBC + MySQL + …

Read more

Spring Boot – How to know which connection pool is used?

In Spring Boot, @Autowired a javax.sql.DataSource, and you will know which database connection pool is using in the current running application. 1. Test Default Spring Boot example to print a javax.sql.DataSource Note Read this official Spring Boot doc – Connection to a production database, to understand the algorithm for choosing a DataSource implementations – Tomcat …

Read more

MySQL – Establishing SSL connection without server’s identity verification is not recommended

Start a Spring Boot application and making a JDBC connection, hits the following warning messages on console : Fri Feb 10 18:43:02 SGT 2017 WARN: Establishing SSL connection without server’s identity verification is not recommended. According to MySQL 5.5.45+, 5.6.26+ and 5.7.6+ requirements SSL connection must be established by default if explicit option isn’t set. …

Read more

Spring Boot non-web application example

In Spring Boot, to create a non-web application, implements CommandLineRunner and override the run method, for example : import org.springframework.boot.CommandLineRunner; @SpringBootApplication public class SpringBootConsoleApplication implements CommandLineRunner { public static void main(String[] args) throws Exception { SpringApplication.run(SpringBootConsoleApplication.class, args); } //access command line arguments @Override public void run(String… args) throws Exception { //do something } } 1. …

Read more

Spring Boot JDBC + MySQL + HikariCP example

In this article, we will show you how to create a Spring Boot JDBC application + MySQL and HikariCP. Tools used in this article : Spring Boot 1.5.1.RELEASE MySQL 5.7.x HikariCP 2.6 Maven Java 8 Note Related – Spring Boot JDBC + Oracle database + Commons DBCP2 example 1. Project Structure A standard Maven project …

Read more

How to stop logback status INFO at the start of every log?

The logbook will output its own status (INFO or WARN) at the start of the program, it’s really annoying! 15:34:46,181 |-INFO in ch.qos.logback.classic.LoggerContext[default] – Could NOT find resource [logback.groovy] 15:34:46,181 |-INFO in ch.qos.logback.classic.LoggerContext[default] – Could NOT find resource [logback-test.xml] 15:34:46,181 |-INFO in ch.qos.logback.classic.LoggerContext[default] – Found resource [logback.xml] at [file:/E:/spring-boot-simple/target/classes/logback.xml] 15:34:46,247 |-INFO in ch.qos.logback.classic.joran.action.ConfigurationAction – debug …

Read more

How to Stop WordPress Pingbacks and Trackbacks Spam

Review my WordPress wp_comments table and find out the file size is containing 500MB++ for around 1 millions++ comments! Dig inside and find out around 900k++ comments was marked as ‘trackback‘ and it linked back to a spammer’s website. The worst is the this type of ‘trackback‘ comments are kept increasing every second! Follow the …

Read more

VirtualBox – Ubuntu slow and laggy UI

To solve the Ubuntu UI slow performance issue on VirtualBox, increase the “Video Memory” and “Enable 3D Acceleration” Environment VirtualBox 5.1.14 Ubuntu 16 Solution 1. Shutdown VM, clicks “Settings” 2. Display –>> Screen tab –>> Increase the “Video Memory” to Max, and checked the “Enable 3D Acceleration” Done. References What is ‘Ubuntu Unity’ (for the …

Read more

VirtualBox – No backlight on CMSTORM keyboard

This article shows you how to enable the backlight feature (Screen Lock key) on a CMSTORM keyboard. Environment VirtualBox 5.1.14 Ubuntu 16 1. Solution – Quick To fix it quickly, run the following command in a terminal, and press the “Screen Lock key” again, the backlight should be enabled. Terminal $ xmodmap -e ‘add mod3 …

Read more

VirtualBox – Copy and Paste between host and guest machine

By default, the copy and paste between host and guest machine is disabled, To enable it, update “Shared Clipboard” to “Bidirectinal“. 1. Steps to enable Copy and Paste 1.1 Shutdown the VM, in VirtualBox Manager, clicks “Settings” 1.2 General –>> Advanced Tab, update the “Shared Clipboard” to “Bidirectinal”. 1.3 Start the VM, the copy and …

Read more

Spring REST API Validation

In Spring MVC, just annotate a @Valid on the @RequestBody to fire the validation process. Note For complete source code, please refer to this – Spring Boot Ajax example P.S Tested with Spring Boot 1.5.1.RELEASE (Spring 4.3.6.RELEASE) 1. JSR 303 Validation Add JSR303 annotations on a bean. package com.mkyong.model; import org.hibernate.validator.constraints.NotBlank; public class SearchCriteria { …

Read more

Spring Boot Ajax example

This article will show you how to use jQuery.ajax to send a HTML form request to a Spring REST API and return a JSON response. Tools used : Spring Boot 1.5.1.RELEASE Spring 4.3.6.RELEASE Maven 3 jQuery Bootstrap 3 Note You may interest at this classic Spring MVC Ajax example 1. Project Structure A standard Maven …

Read more

jQuery Ajax submit a multipart form

A simple jQuery Ajax example to show you how to submit a multipart form, using Javascript FormData and $.ajax() 1. HTML A HTML form for multiple file uploads and an extra field. <!DOCTYPE html> <html> <body> <h1>jQuery Ajax submit Multipart form</h1> <form method="POST" enctype="multipart/form-data" id="fileUploadForm"> <input type="text" name="extraField"/><br/><br/> <input type="file" name="files"/><br/><br/> <input type="file" name="files"/><br/><br/> <input …

Read more

cURL – POST request examples

Some cURL POST request examples for self reference. 1. Normal POST 1.1 To POST without data. $ curl -X POST http://localhost:8080/api/login/ 1.2 To POST with data. $ curl -d "username=mkyong&password=abc" http://localhost:8080/api/login/ 1.3 Spring REST to accept normal POST data. @PostMapping("/api/login") public ResponseEntity<?> login(@RequestParam("username") String username, @RequestParam("password") String password) { //… } @PostMapping("/api/login") public ResponseEntity<?> login(@ModelAttribute …

Read more

cURL – Post JSON data to Spring REST

This article shows you how to use cURL command to POST JSON data to a Spring REST API. 1. Spring REST A Simple Spring REST API to validate a login. LoginController.java package com.mkyong.controller; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.*; @Controller public class LoginController { private final Logger …

Read more

Spring Boot file upload example – Ajax and REST

This article shows you how to upload files in Spring Boot web application (REST structure), using Ajax requests. Tools used in this article : Spring Boot 1.4.3.RELEASE Spring 4.3.5.RELEASE Thymeleaf jQuery (webjars) Maven Embedded Tomcat 8.5.6 Google Chrome Browser (Network Inspect) 1. Project Structure A standard Maven project structure. 2. Project Dependency Declares an extra …

Read more