Java method to convert a string to proper or initial case

Example: toProperCase(“hello john smith”) will return “Hello John Smith”.

public static String toProperCase(String inputString) {
	String ret = "";
	StringBuffer sb = new StringBuffer();
	Matcher match = Pattern.compile("([a-z])([a-z]*)", Pattern.CASE_INSENSITIVE).matcher(inputString);
	while (match.find()) {
		match.appendReplacement(sb, match.group(1).toUpperCase() + match.group(2).toLowerCase()) ;
	}
	ret = match.appendTail(sb).toString();
	return ret;
}

Java method to round a number to specified decimal places

Example: roundToDecimals(1.23456, 2) will return 1.23.

public static float roundToDecimals(float fl, int roundToThisManyDecimalPoints) {
	float ret = 0;
	float pow = (float) Math.pow(10, roundToThisManyDecimalPoints);
	fl = fl * pow;
	float tmpFl = Math.round(fl);
	ret = (float) tmpFl / pow;
	return ret;
}

Java hashtable sample usage

A hashtable stores key-value pairs. In Java, it can be found in the package java.util.Hashtable. The examples below demonstrates some ways hashtables can be used in Java.

Instantiating a Hashtable

// Generic hashtable
Hashtable hashtable = new Hashtable();
// Hashtable with a specified initial size
Hashtable hashtable = new Hashtable(100);

Adding Data

hashtable.put("A", 1);
hashtable.put("B", 2);

In the example above, “A” and “B” are the keys, and 1 and 2 are the corresponding values.

Displaying Hashtable Info

// General info
System.out.println("Is Empty (returns true/false)?: " + hashtable.isEmpty());
System.out.println("Hashtable size (returns integer): " + hashtable.size());
// Query by key
System.out.print("Contains key \"A\" (returns true/false)?: " + hashtable.containsKey("A"));
// Query by value
System.out.print("Contains value 1 (returns true/false)?: " + hashtable.contains(1));

Getting Data

// Get by a particular key
System.out.print("Value for Key \"A\" is: " + hashtable.get("A"));
// Get all
for (String key : hashtable.values()) {
	// ...
}

Removing Data

hashtable.remove("A");

Get files from a directory in the file system using Java

If provided, any files matching any one of the strings found in the array of string ignore[] will be ignored; this can be useful if you want pick up all files except, for example, those marked with the word “temp” or obsolete files marked with “.old” extension.

/**
 * Get the all files in a directory, ignoring files with file names containing particular strings.
 *
 * @param folderPath : Full path of directory in question, eg. "C:\docs\myFiles\"
 * @param ignore[] : An array of strings containing words with which to ignore files, eg. { "temp","ignore",".old" }
 * @return File[]
 * @author C. Peter Chen of http://dev-notes.com
 * @date 20080610
 */
private static File[] getFiles(String folderPath, String ignore[]) {
	File f = new File(folderPath);
	File[] fList = f.listFiles();
	List retFl = new ArrayList();
	if (fList != null && fList.length > 0) {
		for (File file : fList) {
			boolean pass = true;
			for (String ig : ignore) {
				if (file.getName().indexOf(ig) >= 0) {
					pass = false;
				}
			}
			if (pass) { // Only get the file if none of the ignore strings are present
				retFl.add(file);
			}
		}
	}
	return retFl.toArray(new File[0]);
}

Sort an array of File objects by last modified date in Java

/**
 * Sorts an array of Files by the last modified date property; if the second
 * parameter is "desc", then sorting is done descending order, otherwise
 * it will be ascending. 
 * @param fList : An array of Java "File" objects, not sorted
 * @return File[] : An array of Java "File" objects, sorted by last modified date
 * @author C. Peter Chen http://dev-notes.com
 * @date 20080527
 */
public static File[] sortFilesByLastModDate(File[] fList, String order) {
	Arrays.sort(fList, new Comparator() {
		public int compare(File file1, File file2) {
			if ("desc".equals("order")) {
				return (int)(file2.lastModified() - file1.lastModified());
			}
			else {
				return (int)(file1.lastModified() - file2.lastModified());
			}
		}
	});
	return fList;
}

Encrypt a string using SHA encryption

The following class provides the venue to translate the sample string “mySecr3tP4ssw0rd” into the encrypted string “Nj3lzFVrt9dx2gENZeh2H5xY6PY=”, which would be tougher to crack by brute force than a plain password in case a hackers gets hold of your data store.

import java.security.MessageDigest;
import sun.misc.BASE64Encoder;

/**
 * String encryption related utilities.
 * @author C. Peter Chen of http://dev-notes.com
 * @date 20080512
 */

public class StringEncryptUtil {
	/**
	 * This main() class is used for demo only.
	 * @param args
	 */
	public static void main(String[] args) {
		System.out.println("SHA encrypted mySecr3tP4ssw0rd: " + encryptSha("mySecr3tP4ssw0rd"));
	}
	
	/**
	 * Performs a SHA encryption process on the incoming string parameter.
	 * @param inputStr
	 * @return SHA-encrypted string if successful, or null if there are problems.
	 */
	public static synchronized String encryptSha(String inputStr) {
		try {
			MessageDigest md = MessageDigest.getInstance("SHA");
			md.update(inputStr.getBytes("UTF-8"));
			byte digest[] = md.digest();
			return (new BASE64Encoder()).encode(digest);
		}
		catch (Exception e) {
			return null;
		}
	}
}

As you will notice, there is no decrypt method, that is because there probably is no need for one. For instance, we have “Nj3lzFVrt9dx2gENZeh2H5xY6PY=” in the data store for the user Scott; when Scott logs in, we should SHA-encrypt the password he had just typed in, and compare the encrypted string with the encrypted string found in the data store.

Use Java to generate Word document from XML template

To accomplish this, we first need a template. I already created a template for the purpose of this sample, which resembles a very simple invoice; please download word_template.xml file should you wish to follow along. In this file, you will see that there are many fields enclosed by “##” markers. For example:

...
<w:r>
<w:t>Invoice Number: ##INVOICENUMBER##</w:t>
</w:r>
...

The “##” markers signify places where the program will substitute in values we will provide when we call the Java program. The Java program code is below, with the main() method being an example we can run. The example shown by main() sets values for each required key in a hashtable, as well as setting up the location and file name of the template and output XML files. When we wish to run this example, place the template file in C: and let it go! The output file should look like the content of word_output.xml.

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.util.Hashtable;

/**
 * This code takes in a hashtable containing key fields required to populate
 * values into a Word template (XML) and output a Word document (also XML).
 * Template should contain ##KEY## fields for each hashtable key with same
 * name (without the ##s); the ##KEY## will be replaced by the value.
 * The main() method is written as an example.
 * Modified from code found at http://dinoch.dyndns.org:7070/WordML/AboutWordML.jsp
 * @author C. Peter Chen of http://dev-notes.com
 * @date 20080327
 */

public class msWordUtils {
	
	/**
	 * This main() method is used for demonstration purposes only.
	 * @param args
	 * @author C. Peter Chen of http://dev-notes.com
	 * @date 20080327
	 */
	public static void main(String[] args) {
		String templatePathFilename = "c:\word_template.xml";
		String outputPathFilename = "c:\word_output.xml";

		Hashtable ht = new Hashtable();
		ht.put("INVOICENUMBER","384123");
		ht.put("CUSTOMERNAME","Some Company, LLC.");
		ht.put("ITEMNAME1","Coffee");
		ht.put("UNITPRICE1","1.50");
		ht.put("QTY1","1");
		ht.put("LINETOTAL1","1.50");
		ht.put("ITEMNAME2","Donut");
		ht.put("UNITPRICE2","1.00");
		ht.put("QTY2","2");
		ht.put("LINETOTAL2","2.00");
		ht.put("INVOICETOTAL","3.50");
		ht.put("DUEDATE","4/1/2008");
		
		generateWordDoc(ht, templatePathFilename, outputPathFilename);
	}
	
	/**
	 * 
	 * @param ht
	 * @param templatePathFileName
	 * @param outputPathFileName
	 * @author C. Peter Chen of http://dev-notes.com
	 * @date 20080327
	 */
	public static void generateWordDoc(Hashtable ht, String templatePathFilename, String outputPathFilename) {	
		try {
			BufferedReader reader = new BufferedReader(new FileReader(templatePathFilename));
			
			File destination = new File(outputPathFilename);
			BufferedWriter writer = new BufferedWriter(new FileWriter(destination));
			
			String thisLine;
			int i = 0;
			
			while ((thisLine = reader.readLine()) != null) {
				System.out.println(i);
				
				for (java.util.Enumeration e = ht.keys(); e.hasMoreElements();) {
					String name = (String) e.nextElement();
					String value = ht.get(name).toString();
					// Use this if we need to XML-encode the string in hashtable value...
					thisLine = thisLine.replaceAll("##" + name.toUpperCase() + "##", XmlEncode(value));
					// ... or this if we do not need to do XML-encode.
					//thisLine= thisLine.replaceAll("##" + name.toUpperCase() + "##", value);
			    }
				writer.write(thisLine);
				writer.newLine();
				i++;
			}
			writer.close();
			System.out.println("done");
		}
		catch (Exception e) {
			System.out.println("exception!=" + e);
		}
	}

	/**
	 * Encodes regular text to XML.
	 * @param text
	 * @return string
	 * @author http://dinoch.dyndns.org:7070/WordML/AboutWordML.jsp
	 * @date 20050328
	 */
	private static String XmlEncode(String text) {
		int[] charsRequiringEncoding = {38, 60, 62, 34, 61, 39};
		for(int i = 0; i < charsRequiringEncoding.length - 1; i++) {
			text = text.replaceAll(String.valueOf((char)charsRequiringEncoding[i]),"&#"+charsRequiringEncoding[i]+";");
		}
		return text; 
	}
	
}

As noted in the JavaDoc, much of the basis for this code came from http://dinoch.dyndns.org:7070/WordML/AboutWordML.jsp. Much thanks to the unnamed author!