Java – How to join Arrays

In this article, we will show you a few ways to join a Java Array. Apache Commons Lang – ArrayUtils Java API Java 8 Stream 1. Apache Commons Lang – ArrayUtils The simplest way is add the Apache Commons Lang library, and use ArrayUtils. addAll to join arrays. This method supports both primitive and object …

Read more

Debian – Show apt-get package version

On Debian, you can use apt-cache policy ‘package name’ to check the package version. 1.1 Display Tomcat7 version. $ sudo apt-cache policy tomcat7 tomcat7: Installed: (none) Candidate: 7.0.52-1ubuntu0.3 Version table: 7.0.52-1ubuntu0.3 0 500 http://archive.ubuntu.com/ubuntu/ trusty-updates/main amd64 Packages 500 http://security.ubuntu.com/ubuntu/ trusty-security/main amd64 Packages 7.0.52-1 0 500 http://archive.ubuntu.com/ubuntu/ trusty/main amd64 Packages 1.2 Display OpenJDK-7 version. $ sudo …

Read more

Java – Mutable and Immutable Objects

This article shows you the difference between Mutable and Immutable objects in Java 1. Mutable object – You can change the states and fields after the object is created. For examples: StringBuilder, java.util.Date and etc. 2. Immutable object – You cannot change anything after the object is created. For examples: String, boxed primitive objects like …

Read more

Gradle – How to continue build if test is failed

By default, the Gradle build process will be stopped and failed if any unit test is failed. $ gradle build :clean :compileJava :processResources :classes :compileTestJava :processTestResources UP-TO-DATE :testClasses :test com.mkyong.example.TestExample > test_example FAILED java.lang.Exception at TestExample.java:9 //… 3 tests completed, 1 failed :test FAILED //… BUILD FAILED // <————– see status In this article, we …

Read more

Gradle – How to display test result in the console

By default, gradle test displays only the test summary. Terminal % gradle test BUILD SUCCESSFUL in 4s 6 actionable tasks: 3 executed, 3 up-to-date P.S Gradle test generates the detailed tests’ result at the build/reports/tests/test/index.html page. P.S Tested with Gradle 6.7.1 1. Display test result in the console. 1.1 We add the testLogging events to …

Read more

How to print an Array in Java

In this article, we will show you a few ways to print a Java Array. Table of contents. 1. JDK 1.5 Arrays.toString 2. Java 8 Stream APIs 3. Java 8 Stream APIs – Collectors.joining 4. Jackson APIs 5. References 1. JDK 1.5 Arrays.toString We can use Arrays.toString to print a simple array and Arrays.deepToString for …

Read more

Gradle – Exclude commons-logging from Spring

Gradle example to exclude commons-logging from Spring frameworks. build.gradle compile(‘org.springframework:spring-webmvc:4.2.4.RELEASE’){ exclude group: ‘commons-logging’, module: ‘commons-logging’ } If you have multiple Spring dependencies, you have to exclude for each build.gradle compile(‘org.springframework:spring-webmvc:4.2.4.RELEASE’){ exclude group: ‘commons-logging’, module: ‘commons-logging’ } compile(‘org.springframework:spring-test:4.2.4.RELEASE’){ exclude group: ‘commons-logging’, module: ‘commons-logging’ } A better solution is excluding commons-logging at the project level. build.gradle configurations.all …

Read more

Jenkins – Could not find GradleWrapperMain

Create a Gradle project in Jenkins CI, source management with Git, and build with Gradle Wrapper 1. Problem Jenkins console output, the build is failed – “Could not find org.gradle.wrapper.GradleWrapperMain” [Gradle] – Launching build. [workspace] $ /var/lib/jenkins/jobs/GradleTest/workspace/gradlew clean test Error: Could not find or load main class org.gradle.wrapper.GradleWrapperMain Build step ‘Invoke Gradle script’ changed build …

Read more

How to use Gradle Wrapper

In this tutorial, we will show you how to create Gradle wrapper for your project and how to use it. What is Gradle wrapper? The Gradle wrapper allows you to run a Gradle task without requiring that Gradle is installed on your system. 1. Create a Gradle Wrapper 1.1 Declares a wrapper task. build.gradle task …

Read more

Gradle JaCoCo – Incompatible version 1006

A Gradle build + JaCoCo coverage report. build.gradle apply plugin: ‘java’ apply plugin: ‘eclipse-wtp’ apply plugin: ‘jacoco’ //code coverage repositories { mavenLocal() mavenCentral() } jacoco { toolVersion = "0.7.5+" } jacocoTestReport { reports { html.enabled = true xml.enabled = true csv.enabled = false } } P.S Tested with Gradle 2.10 1. Problem 1.1 Run the …

Read more

Intellij IDEA – Auto reload a web application (hot deploy)

In this tutorial, we will show you how to ‘hot deploy’ or ‘hot swap’ a web application in IDEA. Note Tested with Intellij IDEA 14 and 15 1. Select exploded WAR Go Run –>> Edit Configurations –>> “Deployment” tab, clicks + icon –>> select an “exploded artifact” 2. Update classes and resources Select “Server” tab, …

Read more

Maven – Deploy web application to WildFly

In Maven, we can use the official JBoss WildFly Maven Plugin to deploy a web application (war file) to the WildFly application server. Technologies tested : Maven 3.3.9 WildFly 9.0.2.final WildFly Maven Plugin 1.1.0.Alpha5 P.S This Spring MVC web application will be used for this deployment test. 1. Deploy WAR To WildFly 1.1 Start WildFly …

Read more

Maven – webxml attribute is required

Maven package a web application and hits the following error message : $ mvn package //… [ERROR] Failed to execute goal org.apache.maven.plugins:maven-war-plugin:2.2:war (default-war) on project spring4-mvc-maven-ajax-example: Error assembling WAR: webxml attribute is required (or pre-existing WEB-INF/web.xml if executing in update mode) -> [Help 1] Solution 1. For servlet container < 3, make sure WEB-INF/web.xml file ...

Read more

Spring MVC + Mustache JS template example

In this tutorial, we will show you a Spring MVC + Mustache JS template web application example. Technologies used : Spring 4.2.4.RELEASE mustache.js JDK 1.8.0_66 Jackson 2.7 Eclipse 4.3 Tomcat 8 Maven 3 Bootstrap 3 Note This solution is still working, but recommend this simple Spring Boot + JMustache solution. In Spring, we can use …

Read more

Jetty – java.net.BindException: Address already in use

Start a Java webapp with Maven Jetty plugin. $ mvn jetty:run 1. Problem But it hits the following error messages : [WARNING] FAILED org.eclipse.jetty.maven.plugin.JettyServer@1f53481b: java.net.BindException: Address already in use at sun.nio.ch.Net.bind0(Native Method) at sun.nio.ch.Net.bind(Net.java:433) at sun.nio.ch.Net.bind(Net.java:425) at sun.nio.ch.ServerSocketChannelImpl.bind(ServerSocketChannelImpl.java:223) at sun.nio.ch.ServerSocketAdaptor.bind(ServerSocketAdaptor.java:74) at org.eclipse.jetty.server.ServerConnector.open(ServerConnector.java:321) at org.eclipse.jetty.server.AbstractNetworkConnector.doStart(AbstractNetworkConnector.java:80) //… 2. Solution By default, the maven-jetty-plugin start Jetty on port …

Read more

jQuery – Ajax request return 200 OK but error event is fired?

Review a jQuery Ajax form submit. $(document).ready(function () { $("#hostingForm").submit(function (e) { e.preventDefault(e); var data = {} data["id"] = $("#id").val(); data["domain"] = $("#domain").val(); data["name"] = $("#name").val(); //… $.ajax({ type: "POST", contentType: "application/json", url: "{{home}}/hosting/update", data: JSON.stringify(data), dataType: ‘json’, timeout: 600000, success: function (data) { console.log("SUCCESS: ", data); }, error: function (e) { console.log("ERROR: ", e); …

Read more

How to start Meteor on different port

By default, Meteor app start on port 3000 $ meteor [[[[[ ~/path-to/meteor/hello ]]]]] => Started proxy. => Started MongoDB. => Started your app. => App running at: http://localhost:3000/ 1. Meteor Port 9999 To start Meteor app on a different port, start Meteor with –port parameter. $ meteor –port 9999 [[[[[ ~/path-to/meteor/app ]]]]] => Started proxy. …

Read more

Spring @PathVariable – Why is value truncated after the last (.)dot?

Review the below @PathVariable example. @RequestMapping("/site") public class SiteController { @RequestMapping(value = "/{q}", method = RequestMethod.GET) public ModelAndView display(@PathVariable("q") String q) { return getModelAndView(q, "site"); } } See the following cases : For input /site/google, q = google For input /site/google.com, q = google where is the .com? For input /site/google.com.my, q = google.com For …

Read more

Meteor hello world example

In this tutorial, we will show you how to create a website with Meteor framework. Tools used : Meteor 1.2.1 Tested with Linux (Debian, Ubuntu or Mint) Tested with Mac OSX 1. Install Meteor Issue curl https://install.meteor.com | sh, everything will be installed and configured. $ curl https://install.meteor.com | sh % Total % Received % …

Read more

Python – How to split a String

Few examples to show you how to split a String into a List in Python. 1. Split by whitespace By default, split() takes whitespace as the delimiter. alphabet = "a b c d e f g" data = alphabet.split() #split string into a list for temp in data: print temp Output a b c d …

Read more

Python – How to loop a List

In this tutorial, we will show you how to use for-in-loop to loop a List in Python. #example 1 frameworks = [‘flask’, ‘pyramid’, ‘django’] #list for temp in frameworks: print temp print "Python framework : %s" %temp #example 2 numbers = [2,4,6,8,10] #list for num in numbers: print num print "Number : %d" %num Output …

Read more

Spring MVC – Refactoring a jQuery Ajax Post example

Reviewing a jQuery Ajax form POST and Spring MVC example, find out the following patterns : <script> jQuery(document).ready( function($) { $("#btn-save").click(function(event) { var id = $(‘#id’).val(); var domain = $(‘#domain’).val(); var name = $(‘#name’).val(); var desc = $(‘#desc’).val(); var tags = $(‘#tags’).val(); var afflink = $(‘#afflink’).val(); var cdn = $("#cdn").prop("checked") ? true : false; var …

Read more

Spring – Inject value into static variables

Spring doesn’t allow to inject value into static variables, for example: import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Component; @Component public class GlobalValue { @Value("${mongodb.db}") public static String DATABASE; } If you print out the GlobalValue.DATABASE, a null will be displayed. GlobalValue.DATABASE = null Solution To fix it, create a “none static setter” to assign the injected value for …

Read more

Java 8 Stream – Read a file line by line

In Java 8, you can use Files.lines to read file as Stream. c://lines.txt – A simple text file for testing line1 line2 line3 line4 line5 1. Java 8 Read File + Stream TestReadFile.java package com.mkyong.java8; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Paths; import java.util.stream.Stream; public class TestReadFile { public static void main(String args[]) { String fileName …

Read more

How to get the environment variables in Java

In Java, the System.getenv() returns an unmodifiable string Map view of the current system environment. Map<String, String> env = System.getenv(); // get PATH environment variable String path = System.getenv("PATH"); Table of contents. 1. Get a specified environment variable 2. UnsupportedOperationException 3. Display all environment variables 4. Sort the environment variables 5. Download Source Code 6. …

Read more

Jackson 2 – Convert Java Object to / from JSON

In this tutorial, we will show you how to use Jackson 2.x to convert Java objects to / from a JSON. 1. Basic 1.1 Convert a Staff object to from JSON. writeValue(…) – Java Objects to JSON ObjectMapper mapper = new ObjectMapper(); // Java object to JSON file mapper.writeValue(new File("c:\\test\\staff.json"), new Staff()); // Java object …

Read more

MongoDB : Sort exceeded memory limit of 104857600 bytes

Performs a large sort operation (Aggregation) in a collection, and hits the following error message : MongoDB Console > db.bigdata.aggregate( {$group : {_id : "$range", total : { $sum : 1 }}}, {$sort : {total : -1}} ); #… aggregate failed at Error (<anonymous>) at doassert (src/mongo/shell/assert.js:11:14) #… Error: command failed: { "errmsg" : "exception: …

Read more

How to split a string in Java

In Java, we can use String#split() to split a string. String phone = "012-3456789"; // String#split(string regex) accepts regex as the argument String[] output = phone.split("-"); String part1 = output[0]; // 012 String part2 = output[1]; // 3456789 Table of contents 1. Split a string (default) 2. Split a string and retain the delimiter 3. …

Read more

Java – How to delay few seconds

In Java, we can use TimeUnit.SECONDS.sleep() or Thread.sleep() to delay few seconds. 1. TimeUnit JavaDelayExample.java package com.mkyong; import java.util.Date; import java.util.concurrent.TimeUnit; public class JavaDelayExample { public static void main(String[] args) { try { System.out.println("Start…" + new Date()); // delay 5 seconds TimeUnit.SECONDS.sleep(5); System.out.println("End…" + new Date()); // delay 0.5 second //TimeUnit.MICROSECONDS.sleep(500); // delay 1 minute …

Read more

Python – How to delay few seconds

In Python, you can use time.sleep(seconds) to make the current executing Python program to sleep or delay a few seconds. import time time.sleep(1) # delays for 1 seconds time.sleep(10) # delays for 10 seconds time.sleep(60) # delays for 1 minute time.sleep(3600) # delays for 1 hour Full example. test_delay.py import time def main(): while True: …

Read more

Python – How to loop a dictionary

In this tutorial, we will show you how to loop a dictionary in Python. 1. for key in dict: 1.1 To loop all the keys from a dictionary – for k in dict: for k in dict: print(k) 1.2 To loop every key and value from a dictionary – for k, v in dict.items(): for …

Read more

Java – Check if key exists in HashMap

In Java, you can use Map.containsKey() to check if a key exists in a Map. TestMap.java package com.mkyong.examples; import java.util.HashMap; import java.util.Map; public class TestMap { public static void main(String[] args) { Map<String, Integer> fruits = new HashMap<>(); fruits.put("apple", 1); fruits.put("orange", 2); fruits.put("banana", 3); fruits.put("watermelon", null); System.out.println("1. Is key ‘apple’ exists?"); if (fruits.containsKey("apple")) { //key …

Read more

Python Whois client example

In this article, we will show you how to create a simple Whois client both in Python 2 and Python 3. Tested Python 2.7.10 Python 3.4.3 1. Python 3 Whois example In Python 3, the socket accepts bytes, so you need to encode() and decode() manually. whois3.py import sys import socket s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) …

Read more

How to check Debian version

On Debian, type cat /etc/debian_version to display the Debian version. Terminal $ cat /etc/debian_version 9.5 Alternatively, cat /etc/issue Terminal $ cat /etc/issue Debian GNU/Linux 9 \n \l The last one, lsb-release -a, it will display the Debian detail. Terminal $ lsb-release -a -bash: lsb-release: command not found $ sudo apt-get install lsb-release $ lsb_release -a …

Read more