String actualValue = "JAVA WAVE";
String lowerCase = actualValue.toLowerCase();
javawaveblogs-20
Sunday, May 3, 2009
Convert a String to Lower Case in Java
Monday, March 9, 2009
Generate a unique identifier with java.util.UUID
import java.util.UUID;
/**
* This class is used to generate UUID and return it as a String object
*
* @author dhanago
*
*/
public class GenerateUUID
{
/**
* method to return UUID as a String object
*
* @return
*/
public static String getUUID()
{
return UUID.randomUUID().toString();
}
}
Tuesday, March 3, 2009
Java utility to read from resource bundle or properties file
/**
* dataSource.properties is loaded to a resource bundle.
*/
public static ResourceBundle resourceBundle = ResourceBundle.getBundle(
"sample.prop.health");
/**
* This method will return the value of the property from the resource
* bundle.
*
* @param key
* property key
* @return property value
*/
public static String getProperty(String key)
{
String value = null;
try
{
value = resourceBundle.getString(key);
}
catch (MissingResourceException missingResourceException)
{
Logger.getLogger(Utility.class.getName()).
log(Level.SEVERE,
"Resource Bundle not found",
missingResourceException);
}
return value;
}
Java method to format the current date to yyyy-MM-dd using SimpleDateFormat.
/**
* This method will format the current date to yyyy-MM-dd.
* @return
* current date as String.
*/
public static String formatedCurrentDate()
{
String toDate = new Date().toString();
SimpleDateFormat formatter = new SimpleDateFormat(
"EEE MMM yyyy hh:mm:ss zzz");
Date date = formatter.parse(toDate,
new ParsePosition(0));
toDate = new SimpleDateFormat("yyyy-MM-dd").format(date);
return toDate;
}
Java method to return a File object from the file path specified
/**
* This method will return a file from the path specified.
*
* @param path
* path of the file name.
* @param fileName
* Name of the file.
* @return File object
*/
public static File readFileFromPath(String path, String fileName)
{
String fileNameWithPath = null;
if (path.endsWith("/"))
{
fileNameWithPath = path + fileName;
}
else
{
fileNameWithPath = path + "/" + fileName;
}
File file = new File(fileNameWithPath);
return file;
}
Reading file as String in Java
/** This method will read a file as String
* @param filePath
* @return file as String
* @throws java.io.IOException
*/
public static String readFileAsString(String filePath)
throws java.io.IOException
{
StringBuffer fileData = new StringBuffer(1000);
BufferedReader reader = new BufferedReader(new FileReader(filePath));
char[] buf = new char[1024];
int numRead = 0;
while ((numRead = reader.read(buf)) != -1)
{
String readData = String.valueOf(buf,
0,
numRead);
fileData.append(readData);
buf = new char[1024];
}
reader.close();
return fileData.toString();
}
Java method to replace every occurences of a string within another string
/**
* This method will replace every occurences of a string within another
* string.
*
* @param target
* is the original string
* @param from
* is the string to be replaced
* @param to
* is the string which will used to replace
* @return
* changed new string
*/
public static String replace(String target, String from, String to)
{
int start = target.indexOf(from);
if (start == -1)
{
return target;
}
int fromLength = from.length();
char[] targetChars = target.toCharArray();
StringBuffer buffer = new StringBuffer();
int copyFrom = 0;
while (start != -1)
{
buffer.append(targetChars,
copyFrom,
start - copyFrom);
buffer.append(to);
copyFrom = start + fromLength;
start = target.indexOf(from,
copyFrom);
}
buffer.append(targetChars,
copyFrom,
targetChars.length - copyFrom);
return buffer.toString();
}
Friday, October 5, 2007
Code to convert from Xml-String to Document and Document to String
import java.io.IOException;
import java.io.StringReader;
import java.io.StringWriter;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.FactoryConfigurationError;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.Result;
import javax.xml.transform.Source;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.w3c.dom.Document;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
/**
* Code to convert from Xml-String to Document and Document to String.
*
* @author Muthu
*/
public class S2DandD2S
{
public static Document loadXmlFileToDocument( String strXml,
boolean ignoreComments )
{
Document docRet = null;
try
{
DocumentBuilderFactory factory = DocumentBuilderFactory
.newInstance();
factory.setIgnoringComments( ignoreComments );
DocumentBuilder docBuilder = factory.newDocumentBuilder();
docRet = docBuilder.parse( new InputSource( new StringReader(
strXml ) ) );
}
catch (SAXException e)
{
System.out.println( "SAXException" );
}
catch (IOException e)
{
System.out.println( "IOException" );
}
catch (ParserConfigurationException e)
{
System.out.println( "ParserConfigurationException" );
}
catch (FactoryConfigurationError e)
{
System.out.println( "FactoryConfigurationError" );
}
return docRet;
}
/**
* @param args
*/
public static void main( String[] args )
{
try
{
String xml = "Some exception file as string
Document document = loadXmlFileToDocument( xml, false );
TransformerFactory tranFactory = TransformerFactory.newInstance();
Transformer aTransformer = tranFactory.newTransformer();
Source srcDocument = new DOMSource( document );
// Preparing the source which is the document created above.
StringWriter writer = new StringWriter();
Result destxml = new StreamResult( writer );
// Transformingdocument to destination xml.
aTransformer.transform( srcDocument, destxml );
System.out.println( writer.toString() );
System.out.println( "Successfully transformed" );
}
catch (Exception e)
{
System.out.println( "exec " + e );
}
}
}
Parsing Java InputStream To Text and Vice Versa
Here are couple of useful methods to convert from InputStream to String
and vice versa.
Input Stream to String
public String parseISToString(java.io.InputStream is){
java.io.DataInputStream din = new java.io.DataInputStream(is);
StringBuffer sb = new StringBuffer();
try{
String line = null;
while((line=din.readLine()) != null){
sb.append(line+"\n");
}
}catch(Exception ex){
ex.getMessage();
}finally{
try{
is.close();
}catch(Exception ex){}
}
return sb.toString();
}
String to InputStream
public java.io.InputStream parseStringToIS(String xml){
if(xml==null) return null;
xml = xml.trim();
java.io.InputStream in = null;
try{
in = new java.io.ByteArrayInputStream(xml.getBytes("UTF-8"));
}catch(Exception ex){
}
return in;
}
Thursday, September 20, 2007
Object Type - Class
What is Class and class? (Please note the second one is with a small 'c')
The one with small 'c' ie., class is a keyword used to declare Java classes.
The one with upper case 'C' is a Type inside java.lang package.
Type Class describes other objects. Class does not have a constructor.
It helps a Java program to get information about other Java objects.
The Class class provides the basis for Java Reflection and Introspection.
If it is not having a constructor, then how to obtain the object of type Class?
The method getClass() is defined in the Java Object class.
An object of type Class can be obtained by calling the getClass() method on a particular Java object.
The following code will give us the object of type Class for Object objClass objClass = obj.getClass();
The Class class offers several useful methods like below://is used to return class constructors
public Constructor[] getConstructors()
//is used to return class methods
public Method[] getMethods()
//is used to return class fields
public Field[] getFields()
//is used to return the superclass
public Class getSuperClass()
Monday, September 17, 2007
Client Interaction -- Tips
Example - I will try to organize the project artifacts and inform you of the same when it is done.
This is somewhat an Indian construct. It is better written simply as:
I will try to organize the project artifacts and inform you when that is done
2. Do not write or say, "I have some doubts on this issue"
The term "Doubt" is used in the sense of doubting someone - we use this term because in Indian languages, the word for a "doubt"
and a "question" is the same.
The correct usage (for clients) is:
I have a few questions on this issue
3. The term "regard" is not used much in American English. They usually do not say "regarding this issue" or "with regard to this".
Simply use, "about this issue".
4. Do not say "Pardon" when you want someone to repeat what they said. The word "Pardon" is unusual for them and is somewhat
formal. You can say, ‘Please come again or could y ou please repeat.’
5. Americans do not understand most of the Indian accent immediately - They only understand 75% of what we speak and then interpret the rest. Therefore try not to use shortcut terms such as "Can't" or "Don't". Use the expanded "Cannot" or "Do not".
6. Do not use the term "screwed up" liberally. If a situation is not good, it is better to say, "The situation is messed up". Do not use words such as "shucks", or "pissed off".
7. As a general matter of form, Indians interrupt each other constantly in meetings - DO NOT interrupt a client when they are speaking.
Over the phone, there could be delays - but wait for a short time before responding.
8. When explaining some complex issue, stop occasionally and ask "Does that make sense?".
This is preferrable than "Do you understand me?"
9. In email communications, use proper punctuation. To explain something, without breaking your flow, use semicolons, hyphens or
paranthesis. As an example:
You have entered a ne w bug (the popup not showing up) in the defect tracking system; we could not reproduce it - although,
a screenshot would help.
Notice that a reference to the actual bug is added in paranthesis so that the sentence flow is not broken. Break a long sentence
using such punctuation.
10. In American English, a mail is a posted letter. An email is electronic mail.
When you say "I mailed the information to you", it means you sent an actual letter or package through the postal system.
The correct usage is: "I emailed the information to you"
11. To "prepone" an appointment is an Indian usage. There is no actual word called prepone. You can "advance" an appointment.
12. In the term "N-tier Architecture" or "3-tier Architecture"
13. The usages "September End", "Month End", "Day End" are not understood we ll by Americans. They use these as "End of September",
"End of Month" or "End of Day".
14. Americans have weird conventions for time - when they say the time is "Quarter Of One", they mean the time is 1:15. Better to ask them the exact time.
15. Indians commonly use the terms "Today Evening", "Today Night". These are not correct; "Today" means "This Day" where the Day stands
for Daytime. Therefore "Today Night" is confusing. The correct usages are: "This Evening", "Tonight".
That applies for "Yesterday Night" and "Yesterday Evening". The correct usages are: "Last Night" and "Last Evening".
16. When Americans want to know the time, it is usual for them to say, "Do you have the time?". Which makes no sense to an indian.
17. There is no word called "Updation". You update somebody. You wait for updates to happen to the database. Avoid saying "Updation".
18. When you talk with someone for the first time, refer to them as they refer to you - in America, the first conversation usually starts by
using the first name. Therefore you can use the first name of a client. Do not say "Sir". Do not call women "Madam".
19. It is usual convention in initial emails (particularly technical) to expand abbreviations, this way:
We are planning to use the Java API for Registry (JAXR).
After mentioning the expanded form once, subsequently you can use the abbreviation.
20. Make sure you always have a subject in your emails and that the subject is relevant.
Do not use a subject line such as HI.
21. Avoid using "Back" instead of "Back" Use "ago". Back is the worst word for American. (for Days use "Ago", for hours use "before")
22. Avoid using "but" instead of "But" Use "However".
23. Avoid using "Yesterday" hereafter use "Last day".
24. Avoid using "Tomorrow" hereafter use "Next day".