package org.kodejava.io;
import java.io.File;
public class EmptyDirCheck {
public static void main(String[] args) {
File file = new File("D:/Downloads");
// Check to see if the object represent a directory.
if (file.isDirectory()) {
// Get list of file in the directory. When its length is not zero
// the folder is not empty.
String[] files = file.list();
if (files != null && files.length > 0) {
System.out.println(file.getPath() + " is not empty!");
}
}
}
}
How do I format a date in a JSP page?
This example show how to format date in JSP using format tag library. We create a date object using the <jsp:useBean> taglib. To format the date we use the <fmt:formatDate> taglib. We assign the value attribute to the date object, set the type attribute as date and define the pattern how the date will be formatted.
<%@ taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt" %>
<!DOCTYPE html>
<html lang="en">
<head>
<title>Date Format</title>
</head>
<body>
<jsp:useBean id="date" class="java.util.Date"/>
Today is: <fmt:formatDate value="${date}" type="date" pattern="dd-MMM-yyyy"/>
</body>
</html>
Maven Dependencies
<dependencies>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>4.0.1</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
</dependencies>
How do I get cryptographic security providers?
package org.kodejava.security;
import java.security.Provider;
import java.security.Security;
import java.util.Set;
import java.util.HashSet;
public class SecurityProvider {
public static void main(String[] args) {
// Create a set so that we can have a unique results.
Set<String> results = new HashSet<>();
// Returns an array containing all the installed providers.
Provider[] providers = Security.getProviders();
for (Provider provider : providers) {
// Get provider's property keys
Set<Object> keys = provider.keySet();
for (Object key : keys) {
String data = (String) key;
data = data.split(" ")[0];
// Service type started by the "Alg.Alias" string
if (data.startsWith("Alg.Alias")) {
data = data.substring(10);
}
data = data.substring(0, data.indexOf('.'));
results.add(data);
}
}
for (Object object : results) {
System.out.println("Service Type = " + object);
}
}
}
The example result of our code:
Service Type = Policy
Service Type = Configuration
Service Type = AlgorithmParameterGenerator
Service Type = TransformService
Service Type = CertificateFactory
Service Type = KeyInfoFactory
Service Type = CertPathBuilder
Service Type = MessageDigest
Service Type = KeyAgreement
Service Type = SecretKeyFactory
Service Type = KeyGenerator
Service Type = KeyFactory
Service Type = XMLSignatureFactory
Service Type = SaslServerFactory
Service Type = TerminalFactory
Service Type = SecureRandom
Service Type = SaslClientFactory
Service Type = KeyPairGenerator
Service Type = SSLContext
Service Type = KeyStore
Service Type = Mac
Service Type = Provider
Service Type = KeyManagerFactory
Service Type = CertPathValidator
Service Type = Signature
Service Type = TrustManagerFactory
Service Type = Cipher
Service Type = CertStore
Service Type = GssApiMechanism
Service Type = AlgorithmParameters
How do I decrypt an object with DES?
On the previous example How do I encrypt an object with DES? we encrypt an object. In this example we will decrypt the stored object.
package org.kodejava.crypto;
import java.io.*;
import javax.crypto.SecretKey;
import javax.crypto.Cipher;
import javax.crypto.SealedObject;
public class ObjectDecrypt {
public static void main(String[] args) throws Exception {
// Read the previously stored SecretKey.
SecretKey key = (SecretKey) readFromFile("secretkey.dat");
// Read the SealedObject
SealedObject sealedObject = (SealedObject) readFromFile("sealed.dat");
// Preparing Cipher object from decryption.
if (sealedObject != null) {
String algorithmName = sealedObject.getAlgorithm();
Cipher cipher = Cipher.getInstance(algorithmName);
cipher.init(Cipher.DECRYPT_MODE, key);
String text = (String) sealedObject.getObject(cipher);
System.out.println("Text = " + text);
}
}
// Method for reading object stored in a file.
private static Object readFromFile(String filename) {
try (FileInputStream fis = new FileInputStream(filename);
ObjectInputStream ois = new ObjectInputStream(fis)) {
return ois.readObject();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}
How do I encrypt an object with DES?
This example demonstrate encrypting an object using DES algorithm. After the object was encrypted we store it in a file which will be decrypted in the next example here How do I decrypt an object with DES.
package org.kodejava.crypto;
import java.io.*;
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SealedObject;
import javax.crypto.SecretKey;
public class ObjectEncrypt {
public static void main(String[] args) throws Exception {
// Generating a temporary key and store it in a file.
SecretKey key = KeyGenerator.getInstance("DES").generateKey();
writeToFile("secretkey.dat", key);
// Preparing Cipher object for encryption.
Cipher cipher = Cipher.getInstance("DES");
cipher.init(Cipher.ENCRYPT_MODE, key);
// Here we seal (encrypt) a simple string message (a string object).
SealedObject sealedObject = new SealedObject("THIS IS A SECRET MESSAGE!", cipher);
// Write the object out as a binary file.
writeToFile("sealed.dat", sealedObject);
}
// Store object in a file for future use.
private static void writeToFile(String filename, Object object) throws Exception {
try (FileOutputStream fos = new FileOutputStream(filename);
ObjectOutputStream oos = new ObjectOutputStream(fos)) {
oos.writeObject(object);
}
}
}
How do I determine whether a string is a palindrome?
This code checks a string to determine if it is a palindrome or not. A palindrome is a word, phrase, or sequence that reads the same backward as forward.
package org.kodejava.lang;
public class PalindromeChecker {
public static void main(String[] args) {
String text = "Sator Arepo Tenet Opera Rotas";
PalindromeChecker checker = new PalindromeChecker();
System.out.println("Is palindrome = " + checker.isPalindrome(text));
}
/**
* This method checks the string for palindrome. We use StringBuilder to
* reverse the original string.
*
* @param text a text to be checked for palindrome.
* @return <code>true</code> if a text is palindrome.
*/
private boolean isPalindrome(String text) {
System.out.println("Original text = " + text);
String reverse = new StringBuilder(text).reverse().toString();
System.out.println("Reverse text = " + reverse);
// Compare the original text with the reverse one and ignoring its case
return text.equalsIgnoreCase(reverse);
}
}
How do I create a thread by implementing Runnable interface?
Here is the second way for creating a thread. We create an object that implements the java.lang.Runnable interface. For another example see How do I create a thread by extending Thread class?.
package org.kodejava.lang;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
public class TimeThread implements Runnable {
private final DateFormat df = new SimpleDateFormat("hh:mm:ss");
// The run() method will be invoked when the thread of this runnable object
// is started.
@Override
public void run() {
while (true) {
Calendar calendar = Calendar.getInstance();
System.out.format("Now is: %s.%n", df.format(calendar.getTime()));
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public static void main(String[] args) {
TimeThread time = new TimeThread();
Thread thread = new Thread(time);
thread.start();
}
}
An example result of this code are:
Now is: 07:18:39.
Now is: 07:18:40.
Now is: 07:18:41.
Now is: 07:18:42.
Now is: 07:18:43.
How do I create a thread by extending Thread class?
There are two ways that we can use tho create a thread. First is by extending the java.lang.Thread class and the second way is by creating a class that implements the java.lang.Runnable interface. See How do I create a thread by implementing Runnable interface?
In this example we’ll extend the Thread class. To run a code in a thread we need to provide the run() method in our class. Let’s see the code below.
package org.kodejava.lang;
public class NumberPrinter extends Thread {
private final String threadName;
private final int delay;
public NumberPrinter(String threadName, int delay) {
this.threadName = threadName;
this.delay = delay;
}
// The run() method will be invoked when the thread is started.
@Override
public void run() {
for (int i = 0; i < 10; i++) {
System.out.println("Thread [" + threadName + "] = " + i);
try {
Thread.sleep(delay);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public static void main(String[] args) {
NumberPrinter printerA = new NumberPrinter("A", 1000);
NumberPrinter printerB = new NumberPrinter("B", 750);
printerA.start();
printerB.start();
}
}
The example result of our code is:
Thread [B] = 0
Thread [A] = 0
Thread [B] = 1
Thread [A] = 1
Thread [B] = 2
Thread [A] = 2
Thread [B] = 3
Thread [B] = 4
Thread [A] = 3
Thread [B] = 5
Thread [A] = 4
Thread [B] = 6
Thread [A] = 5
Thread [B] = 7
Thread [B] = 8
Thread [A] = 6
Thread [B] = 9
Thread [A] = 7
Thread [A] = 8
Thread [A] = 9
How do I compare two dates?
In this example you’ll see the utilization of SimpleDateFormat class for comparing two dates for equality. We convert the date object into string using the DateFormat instance and then compare it using String.equals() method.
package org.kodejava.util;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
public class ComparingDate {
public static void main(String[] args) {
// Create a SimpleDateFormat instance with dd/MM/yyyy format
DateFormat df = new SimpleDateFormat("dd/MM/yyyy");
// Get the current date
Date today = new Date();
// Create an instance of calendar that represents a new year date
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.DATE, 1);
calendar.set(Calendar.MONTH, Calendar.JANUARY);
calendar.set(Calendar.YEAR, 2021);
String newYear = df.format(calendar.getTime());
String now = df.format(today);
// Using the string equals method we can compare the date.
if (now.equals(newYear)) {
System.out.println("Happy New Year!");
} else {
System.out.println("Have a nice day!");
}
}
}
How do I search for files recursively using Apache Commons IO?
This example demonstrates how we can use the FileUtils class listFiles() method to search for a file specified by their extensions. We can also define to find the file recursively deep down into the subdirectories.
package org.kodejava.commons.io;
import org.apache.commons.io.FileUtils;
import java.io.File;
import java.util.Collection;
public class SearchFileRecursive {
public static void main(String[] args) {
File root = new File("F:/Wayan/Kodejava/kodejava-example");
try {
String[] extensions = {"xml", "java", "dat"};
// Find files within a root directory and optionally its
// subdirectories, which match an array of extensions. When the
// extensions are null, all files will be returned.
//
// This method will return matched file as java.io.File
Collection<File> files = FileUtils.listFiles(root, extensions, true);
for (File file : files) {
System.out.println("File = " + file.getAbsolutePath());
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
Maven Dependencies
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.14.0</version>
</dependency>
