Thursday, May 19, 2005

Java sorting strings

// Sorts the input arguments

public static void main(String[] args)
{
//just sort the input command line args
Arrays.sort(args); // sorting works for many primitive data types
//sorting objects will be another section.
//Print the sorted array
for (int i=0; i .lt. args.length;i++)
{
System.out.println(args[i]);
}
}

Wednesday, May 18, 2005

Java Swing To Set custom Look and Feel to UI

if ( setcmd txt is "Windows")
{
lfName = "com.sun.java.swing.plaf.windows.WindowsLookAndFeel";
}

try
{
UIManager.setLookAndFeel(lfName);
}
catch (UnsupportedLookAndFeelException ex1)
{
System.err.println("Unsupported LookAndFeel: " + lnfName);
}

Wednesday, May 11, 2005

Eclipse SWT vs. Java Swing

Good article.

copy xml document via xslt.

Few months back, one guy stopped by office & asked me I want .xsl file to copy the incoming xml file. At first I am bit shocked why you want to do that, later he explained the scenario. Immediately I got confused how to ? but did it in 10 minutes. But a crazy scenario. here is code for that part.

.lt. xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0" .gt.
-- match the root node and copy it --
.lt. xsl:template match="/" .gt.
.lt. xsl:copy-of select="."/ .gt.
.lt./xsl:template .gt.

.lt./xsl:stylesheet.gt.

.lt. less than symbol .gt. greater than symbol

Eclipse 3.0 onwards. Using ImageRegistry & plugin your own images

The ImageRegistry is intended to be used for Images
that appear frequently in your plugnin UI.
To use ImageRegistry make sure your Plugin class a subclass of org.eclipse.ui.plugin.AbstractUIPlugin.

This class creates an ImageRegistry automatically (one per plug-in instance) and
override/implement the following methods.


public Image getImage(String id)
{
ImageRegistry ir= getImageRegistry();
return (Image)ir.get(id);
}

public ImageDescriptor getImageDescriptor(String id)
{

ImageRegistry ir= getImageRegistry();
return (ImageDescriptor)ir.getDescriptor(id);
}


protected void initializeImageRegistry(ImageRegistry image_registry)
{

ImageDescriptor desc = ImageDescriptor.createFromURL(generateURL("myOwnImage1.gif"));
image_registry.put("myOwnImage1",desc);
}

private URL generateURL(String file_name)
{
Bundle bundle = Platform.getBundle(PLUGIN_ID);
String iconPath = "icons/";
String completePath= iconPath+file_name;
IPath path = new Path(completePath);
URL url = Platform.find(bundle,path);
return url;
}

Tuesday, May 10, 2005

Java Sample code to write exception stack trace in to a file.

My previous code is too big. So I will add small code today.
Normally in the try catch block, if we have exception object, we will print exception object with printStatckTace, getErrorMessage etc. But I faced a situation in which, I need to log all the exception trace back stack in to a text file. Later admin want to view this log file for all tracebacks.
Just think how to write exception trace in to a txt file.
Here is the code block for the above problem.

StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw);
e.printStackTrace(pw);
StringBuffer error = sw.getBuffer();
String exceptionString = error. toString()
Note: StringWriter, PrintWriter classes comes from io package.

Monday, May 09, 2005

Validating XML files under a web application. ( aka a file system path.)

Following code parses xml files under a directory. (It was recursive one.)
We have a web application which is very much similar to struts framework.
So we have tons of xml preference files.
Before launching tomcat, I will invoke the following code to make sure that
all xml files were valid one.

public void parseDirectory(String fullpath)
{
if ( fullpath == null) return;

Path path = new Path(fullpath);
File file = path.toFile();
File[] files = file.listFiles();
if (files==null) return;
int size = files.length;

for (int i=0; i .lt. size; i=i+1)
{
if (files[i].isDirectory())
{
File[] dirFiles = files[i].listFiles();
String dirName =files[i].getName();

System.out.println("\n processing directory"+dirName);
for (int j=0; j .lt. dirFiles.length; j=j+1)
{
File subDirFile = dirFiles[j];
String subDirFileName = subDirFile.getName();
if ( subDirFileName.endsWith(".xml"))
{
parseXmlile(files[i].getName();
}
else
{
if ( subDirFile.isDirectory() ) parseDirectory(subDirFileName);
}
}
}
else
{
String fileName = files[i].getName();
if ( fileName.endsWith(".xml"))
{
parseXmlile(files[i].getName();
}
else
{
// it is not a xml file & directory.. so skip it.
}
}
}
}




public void parseXmlile(String fileName)
{

try
{
System.err.println("Parsing " + fileName + "...");
// Make the document a URL so relative DTD works.
String uri = "file:" + new File(fileName).getAbsolutePath();
XmlDocument doc = XmlDocument.createXmlDocument(uri);
System.out.println("Parsed OK...");
}
catch (SAXParseException ex)
{
System.err.println("================================");
System.err.println("| *Parse Error* |");
System.err.println("================================");
System.err.println("+ Line " + ex.getLineNumber ()
+ ", uri " + ex.getSystemId ());
System.err.println(ex.getClass());
System.err.println(ex.getMessage());
System.err.println("================================");
}
catch(SAXException ex)
{
System.err.println("================================");
System.err.println("| *SAX XML Error* |");
System.err.println("================================");
System.err.println(ex.toString());
}
catch (IOException ex)
{
System.err.println("================================");
System.err.println("| *Input/Output Error* |");
System.err.println("================================");
System.err.println(ex.toString());
}
catch (Exception ex)
{
System.err.println("================================");
System.err.println("| Unknown error |");
System.err.println("================================");
System.err.println(ex.toString());
}
}

Friday, May 06, 2005

Eclipse 3.0 onwards. A Light Weight Decorator sample.

Eclips 3.0 onwards only. for plugin developers.

Sample code to implement powerful Light Weight Decorator to
paint tree and XXX nodes.
I used it to paint tree nodes in my project to show different images on top
of standard tree folder,+,- signs.

1) plugin.xml add the following node.
point="org.eclipse.ui.decorators">
decorator
adaptable="true"
label="%plugin.my_label"
state="false"
lightweight="true"
location="BOTTOM_RIGHT"
class="com.xxx.TreeLabelProvider"
id="com.xxx.views"
enablement
objectClass
name="com.xxx.TreeObject"
objectClass
enablement
decorator
extension
stpid tool is not allowing me enter comple xml syntax.
2) open tree object class & add/ implement the following.

TreeLabelProvider extends LabelProvider
implements ILightweightLabelDecorer

implement
public Image getImage(Object element)
public String getText(Object element)
and
public void decorate(Object element, IDecoration decoration)
{
if (element instanceof TreeObject)
decoration.addOverlay(error,IDecoration.BOTTOM_RIGHT);
}
catch relation between TreeLabelProvider & TreeObject.
U are done. enjoy.

creating read-only views of collections inside a application

// create a list and add some items to it

List stringlist = new ArrayList();
stringlist.add("alpha");
stringlist.add("beta");
stringlist.add("gamma");

// create an unmodifiable view of the list

List rolist = Collections.unmodifiableList(stringlist);

// add to the original list (works OK)

stringlist.add("delta");

// add through the read-only view (gives an exception)

rolist.add("delta");

dumping system properties

Just to dump java System class properties.

try
{

////dumping system properties.

// Note1) If property is duplicated it will use the later value for key value

Properties p = System.getProperties();
Enumeration e= p.propertyNames();
for ( ; e.hasMoreElements();) {
String o =(String) e.nextElement();
System.out.println( "\n Key="+ o);
System.out.println( " Value="+ p.getProperty(o) );

}

}
catch (Exception e)
{
System.err.println("Directory " + e.getMessage() + " is invalid.");
e.printStackTrace();
}

parsing a Date string

U got date input as string. (In some MM/DD/YYYY format)
Now I want the equivalent Java date object.
(For further validity & further processing.)
Use the following segment.


public static void main(String args[])
{
String dt = "10-10-1990"; // some test data

try{

SimpleDateFormat format = new SimpleDateFormat("MM/dd/yyyy");
// input date format
format.setLenient(false);
Date date = format.parse( dt );
System.out.println("The parsed date: " + date);
} catch (ParseException e) {
System.out.println(e.getMessage());
}

About myself.

Working as software engineer.
Just want to post some useful Java, Eclipse, C/C++, XML/XSLT programming samples, tips, tools etc. Day2day programming life, I come across these things.
Just for my reference & may be useful for others too.
My sons first two letter are the blog spot name.
I will update their pictures later.