How to get the Tomcat home directory in Java

Q : Is there a function in Java to retrieve the Tomcat (Catalina) home directory? A : Yes, Tomcat home directory or Catalina directory is stored at the Java System Property environment. If the Java web application is deployed into Tomcat web server, we can get the Tomcat directory with the following command System.getProperty("catalina.base");

Java – How to convert Char to String

A Java example to show you how to convert a Char into a String and vise verse. ConvertCharToString.java package com.mkyong.utils; public class ConvertCharToString { public static void main(String[] args) { String website = "https://mkyong.com"; //convert a String into char char charH = website.charAt(0); //h char charP = website.charAt(3);//p char charM = website.charAt(11);//m System.out.println(charH); System.out.println(charP); System.out.println(charM); …

Read more

JUnit 4 Vs TestNG – Comparison

JUnit 4 and TestNG are both very popular unit test framework in Java. Both frameworks look very similar in functionality. Which one is better? Which unit test framework should I use in Java project? Here I did a feature comparison between JUnit 4 and TestNG. 1. Annotation Support The annotation supports are implemented in both …

Read more

JUnit – Parameterized Test

In JUnit, you can pass the parameters into the unit test method via the following methods : Constructor Fields injection via @Parameter P.S Tested with JUnit 4.12 1. MatchUtils – Test with multiple parameters A simple add operation. MathUtils.java package com.mkyong.examples; public class MathUtils { public static int add(int a, int b) { return a …

Read more

JUnit – Suite Test, run multiple test cases

In JUnit, you can run multiple test cases with @RunWith and @Suite annotation. Refer to the following examples : SuiteAbcTest.java package com.mkyong; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.Suite; @RunWith(Suite.class) @Suite.SuiteClasses({ Exception1Test.class, //test case 1 TimeoutTest.class //test case 2 }) public class SuiteAbcTest { //normally, this is an empty class } P.S Tested with JUnit 4.12 …

Read more

JUnit – Timeout Test

If a test is taking longer than a defined “timeout” to finish, a TestTimedOutException will be thrown and the test marked failed. See the following example : P.S Tested with JUnit 4.12 1. Timeout Example This timeout example only applies to a single test method. And the timeout value is in milliseconds. TimeoutTest.java package com.mkyong; …

Read more

JUnit – Ignore a Test

In JUnit, to ignore a test, just add a @Ignore annotation before or after the @Test method. P.S Tested with JUnit 4.12 IgnoreTest.java package com.mkyong; import org.junit.Ignore; import org.junit.Test; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.assertThat; public class IgnoreTest { @Test public void testMath1() { assertThat(1 + 1, is(2)); } @Ignore @Test public void testMath2() { …

Read more

JUnit – Expected Exceptions Test

In JUnit, there are 3 ways to test the expected exceptions : @Test, optional ‘expected’ attribute Try-catch and always fail() @Rule ExpectedException P.S Tested with JUnit 4.12 1. @Test expected attribute Use this if you only want to test the exception type, refer below : Exception1Test.java package com.mkyong; import org.junit.Test; import java.util.ArrayList; public class Exception1Test …

Read more

JUnit – Basic annotation examples

Here’re some basic JUnit annotations you should understand: @BeforeClass – Run once before any of the test methods in the class, public static void @AfterClass – Run once after all the tests in the class have been run, public static void @Before – Run before @Test, public void @After – Run after @Test, public void …

Read more

TestNG – Dependency Test

In TestNG, we use dependOnMethods and dependsOnGroups to implement dependency testing. If a dependent method is fail, all the subsequent test methods will be skipped, NOT failed. 1. dependOnMethods Example A simple example, “method2()” is dependent on “method1()”. 1.1 If method1() is passed, method2() will be executed. App.java package com.mkyong.testng.examples.dependency; import org.testng.annotations.Test; public class App …

Read more

TestNG – Parameter Test (XML and @DataProvider)

In this tutorial, we will show you how to pass parameters into a @Test method, via XML @Parameters or @DataProvider. 1. Passing Parameters with XML In this example, the properties filename is passing from testng.xml, and inject into the method via @Parameters. TestParameterXML.java package com.mkyong.testng.examples.parameter; import java.io.IOException; import java.io.InputStream; import java.sql.Connection; import java.sql.DriverManager; import java.util.Properties; …

Read more

TestNG – Run multiple test classes (suite test)

In this tutorial, we will show you how to run multiple TestNG test cases (classes) together, aka suite test. 1. Test Classes Review following three test classes. TestConfig.java package com.mkyong.testng.examples.suite; import org.testng.annotations.AfterSuite; import org.testng.annotations.AfterTest; import org.testng.annotations.BeforeSuite; import org.testng.annotations.BeforeTest; //show the use of @BeforeSuite and @BeforeTest public class TestConfig { @BeforeSuite public void testBeforeSuite() { System.out.println("testBeforeSuite()"); …

Read more

TestNG – Timeout Test

In this tutorial, we will show you how to perform timeout test in TestNG. The “timeout” means if a unit test is taking longer than a specified number of milliseconds to finish, TestNG will abort it and market it as failed. This “timeout” can also use for performance test, to ensure the method is returned …

Read more

TestNG – How to ignore a test method

In this tutorial, we will show you how to ignore a test method with @Test(enabled = false). TestIgnore.java package com.mkyong.testng.examples.ignore; import org.testng.Assert; import org.testng.annotations.Test; public class TestIgnore { @Test //default enable=true public void test1() { Assert.assertEquals(true, true); } @Test(enabled = true) public void test2() { Assert.assertEquals(true, true); } @Test(enabled = false) public void test3() { …

Read more

TestNG – Expected Exception Test

In this tutorial, we will show you how to use the TestNG expectedExceptions to test the expected exception throws in your code. 1. Runtime Exception This example shows you how to test a runtime exception. If the method divisionWithException () throws a runtime exception – ArithmeticException, it will be passed. TestRuntime.java package com.mkyong.testng.examples.exception; import org.testng.annotations.Test; …

Read more

How to detect OS in Java

This article shows a handy Java class that uses System.getProperty("os.name") to detect which type of operating system (OS) you are using now. 1. Detect OS (Original Version) This code can detect Windows, Mac, Unix, and Solaris. OSValidator.java package com.mkyong.system; public class OSValidator { private static String OS = System.getProperty("os.name").toLowerCase(); public static void main(String[] args) { …

Read more

PMD error – Can’t use JDK 1.5 for loop syntax when running in JDK 1.4 mode!

When i integrate Hudson and PMD together to run the PMD static code analysis process in my web project. I hit the following error message. By the way , i’m using Maven 2 to mange my web project. Caused by: net.sourceforge.pmd.ast.ParseException: Can’t use JDK 1.5 for loop syntax when running in JDK 1.4 mode! at …

Read more

CSS Padding property setting

CSS Padding property setting is confusing sometime, because it can accept 1 value, 2 values , 3 or 4 values together. For example, all the padding property setting below is valid. padding: 10px; padding: 10px 8px; padding: 10px 8px 10px; padding: 10px 8px 10px 9px; CSS Padding Rule. 1) CSS padding order is follow clockwise …

Read more

How to read a UTF-8 file in Java

In Java, the InputStreamReader accepts a charset to decode the byte streams into character streams. We can pass a StandardCharsets.UTF_8 into the InputStreamReader constructor to read data from a UTF-8 file. import java.nio.charset.StandardCharsets; //… try (FileInputStream fis = new FileInputStream(file); InputStreamReader isr = new InputStreamReader(fis, StandardCharsets.UTF_8); BufferedReader reader = new BufferedReader(isr) ) { String str; …

Read more

How to write a UTF-8 file in Java

In Java, the OutputStreamWriter accepts a charset to encode the character streams into byte streams. We can pass a StandardCharsets.UTF_8 into the OutputStreamWriter constructor to write data to a UTF-8 file. try (FileOutputStream fos = new FileOutputStream(file); OutputStreamWriter osw = new OutputStreamWriter(fos, StandardCharsets.UTF_8); BufferedWriter writer = new BufferedWriter(osw)) { writer.append(line); } In Java 7+, many …

Read more

focus() is not working in IE ? – solution

The focus() method is used to give focus to a textbox, or other html components. Here is a simple example to make a textbox focus automatically after page load. focus is not working in IE The above code is working fine in Firefox (FF), but not in Internet Explorer (IE). Actually the IE is supporting …

Read more

How to get element by name in HTML – getElementsByName

The getElementsByName() method is use to get the element by name. However be aware of the getElementsByName() method always return an array as output. Caution The method always return an array, and we have to use [] to access the value. For example alert(document.getElementsByName(“myInput”).value); It will prompt out an undefined value alert(document.getElementsByName(“myInput”)[0].value); It will prompt …

Read more

How to suppress unchecked warnings – Java

The ‘unchecked warnings’ is quite popular warning message in Java. However, if you insist this is an invalid warning, and there are no ways to solve it without compromising the existing program functionality. You may just use @SuppressWarnings(“unchecked”) to suppress unchecked warnings in Java. 1. In Class If applied to class level, all the methods …

Read more

How to get div id element in Javascript

In JavaScript, you can use getElementById() fucntion to get any prefer HTML element by providing their tag id. Here is a HTML example to show the use of getElementById() function to get the DIV tag id, and use InnerHTML() function to change the text dynamically. HTML… <html> <head> <title>getElementById example</title> <script type="text/javascript"> function changeText(text) { …

Read more

How to get context-param value in java?

The “context-param” tag is define in “web.xml” file and it provides parameters to the entire web application. For example, store administrator’s email address in “context-param” parameter to send errors notification from our web application. web.xml <context-param> <param-name>AdministratorEmail</param-name> <param-value>[email protected]</param-value> </context-param> We can get the above “AdministratorEmail” context-param value with the following java code. String email= getServletContext().getInitParameter("AdministratorEmail"); …

Read more

Maven – How to skip unit test

In Maven, you can define a system property -Dmaven.test.skip=true to skip the entire unit test. By default, when building project, Maven will run the entire unit tests automatically. If any unit tests is failed, it will force Maven to abort the building process. In real life, you may STILL need to build your project even …

Read more

How to encode a URL string or form parameter in java

This is always advisable to encode URL or form parameters; plain form parameter is vulnerable to cross site attack, SQL injection and may direct our web application into some unpredicted output. A URL String or form parameters can be encoded using the URLEncoder class – static encode (String s, String enc) method. For example, when …

Read more

How to escape special characters in java?

In Java, we can use Apache commons-text to escape the special characters in HTML entities. Special characters as follow: < > ” & pom.xml <dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-text</artifactId> <version>1.8</version> </dependency> EscapeSpecialChar.java package com.mkyong.html; import org.apache.commons.text.StringEscapeUtils; // @deprecated as of 3.6, use commons-text StringEscapeUtils instead //import org.apache.commons.lang3.StringEscapeUtils; public class EscapeSpecialChar { public static void main(String[] args) { …

Read more

How to run a java program in backgroud (unix / Linux)

Oftentimes, we use SSH to remote access into the server to run a Java program. The problem is, we can’t type anything After the Java program is executed like this : $ java -jar example.jar In addition, when the remote access session is expired or terminated, the executed Java program will be killed. Solution To …

Read more

How to convert String to byte[] in Java?

In Java, we can use str.getBytes(StandardCharsets.UTF_8) to convert a String into a byte[]. String str = "This is a String"; // default charset, a bit dangerous byte[] output1 = str.getBytes(); // in old days, before java 1.7 byte[] output2 = str.getBytes(Charset.forName("UTF-8")); // the best , java 1.7+ , new class StandardCharsets byte[] output3 = str.getBytes(StandardCharsets.UTF_8); …

Read more

How to convert byte[] array to String in Java

In Java, we can use new String(bytes, StandardCharsets.UTF_8) to convert a byte[] to a String. // string to byte[] byte[] bytes = "hello".getBytes(StandardCharsets.UTF_8); // byte[] to string String s = new String(bytes, StandardCharsets.UTF_8); Table of contents 1. byte[] in text and binary data 2. Convert byte[] to String (text data) 3. Convert byte[] to String …

Read more

JCE Encryption – Data Encryption Standard (DES) Tutorial

In this article, we show you how to use Java Cryptography Extension (JCE) to encrypt or decrypt a text via Data Encryption Standard (DES) mechanism. 1. DES Key Create a DES Key. KeyGenerator keygenerator = KeyGenerator.getInstance("DES"); SecretKey myDesKey = keygenerator.generateKey(); 2. Cipher Info Create a Cipher instance from Cipher class, specify the following information and …

Read more

Unsupported WTP version: 1.5. This plugin currently supports only the following versions: 1.0 R7

Often times, you may to use “mvn eclipse:eclipse -Dwtpversion=1.5” command to create a web project for Eclipse IDE, but you may encounter the following error messages. Unsupported WTP version: 1.5. This plugin currently supports only the following versions: 1.0 R7 D:\mkyong>mvn eclipse:eclipse -Dwtpversion=1.5 [INFO] Scanning for projects… [INFO] Searching repository for plugin with prefix: ‘eclipse’. …

Read more