Archive for the ‘Technical’ Category

A typical File Utility class

February 23, 2009

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;

import org.apache.log4j.Logger;

public class FileUtils{
private static Logger log = Logger.getLogger(FileUtils.class);

public static void copyFile(String fileSourcePath, String fileOuputPath) throws IOException {
File inputFile = new File(fileSourcePath);
File outputFile = new File(fileOuputPath);

FileReader in;
FileWriter out;
in = new FileReader(inputFile);
out = new FileWriter(outputFile);
int c;

while((c = in.read()) != -1)
out.write(c);

in.close();
out.close();
}

public static void copyDirectory(File srcPath, File dstPath, String... extensionsToCopy) throws IOException{
if(srcPath.isDirectory()){
if(srcPath.isHidden() == false || srcPath.getName().startsWith(".") == false){
if(!dstPath.exists()){
dstPath.mkdir();
}
String files[] = srcPath.list();
for(int i = 0; i < files.length; i++){
copyDirectory(new File(srcPath, files[i]), new File(dstPath, files[i]), extensionsToCopy);
}
}
}
else{
if(!srcPath.exists()){
log.error("Cannot copy dirs");
}
else{
boolean existInList = false;
for(String tmpSt : extensionsToCopy){
if(dstPath.getPath().indexOf(tmpSt, dstPath.getPath().length() - tmpSt.length() - 1) != -1){
existInList = true;
}
}
if(srcPath.canRead() && existInList){
BufferedReader in = new BufferedReader(new FileReader(srcPath));
BufferedWriter out = new BufferedWriter(new FileWriter(dstPath));
String line = in.readLine();
while(line != null){
out.write(line);
out.newLine();
line = in.readLine();
}
in.close();
out.close();
}
}
}
}

public static void writeToFile(String filename, String content) throws IOException{

PrintWriter pw = null;
File file = null;

try{
file = new File(filename);
pw = new PrintWriter(new FileWriter(file));
pw.print(content);
pw.flush();
}
finally{
// Close the PrintWriter
if(pw != null) pw.close();
}
}

public static boolean renameFile(String oldFileName, String newFileName){
boolean isRenamed = false;
File oldFile = new File(oldFileName);
if(oldFile.exists()) isRenamed = oldFile.renameTo(new File(newFileName));
return isRenamed;
}

public static List getAllFiles(File srcPath, List paths, String... extensionsNeeded){
if(paths == null){
paths = new ArrayList();
}
if(srcPath.isDirectory()){
if(srcPath.isHidden() == false || srcPath.getName().startsWith(".") == false){
String files[] = srcPath.list();
for(int i = 0; i < files.length; i++){
getAllFiles(new File(srcPath, files[i]), paths, extensionsNeeded);
}
}
}
else{
for(String tmpSt : extensionsNeeded){
if(srcPath.getPath().indexOf(tmpSt, srcPath.getPath().length() - tmpSt.length() - 1) != -1){
paths.add(srcPath.getPath());
return paths;
}
}
}
return paths;
}

}

What is the difference between JRE and JVM

January 19, 2009

This question perplexed me for quite some time. No other site explains it as this :

Tomcat startup window disappears ?

December 31, 2008

There are times when you start tomcat and suddenly the black little window that shows the status of the server, disappears, and you are like “hey wait, where did that window disappear ?”. You do this cycle a zillion times and still the black little window just appears and disappears, more or less like my salary 🙂

You were so far probably using startup.bat or wttomcat_start to start tomcat.
Here is what you can do so you can make that window start.
at the command line, am sure you know what that means, tab into the bin of tomcats and type: catalina.bat run
this will ensure that the window stays and shows you what the error was which was causing the window to disappear, wait, what did you think, the window just like that disappeared or what ?
Only in case your catalina.bat file doesnt exist for some reason then, edit tomcat/bin/startup.bat in one of the last lines change the keyword “start” to “run”.  Then run startup.bat

hope this was of some help to you

Translation and transliteration made easy

October 10, 2008

This is freaking cool.
I stumbled on this API by google and it looks very decent.
It is just one line of code it takes to translate your text to a different language.
Proper examples on translation and transliteration are on http://code.google.com/apis/ajaxlanguage/documentation/
Its ajax obviously, and performs very well.
http://googleajaxsearchapi.blogspot.com/2008/03/introducing-ajax-language-api-tools-for.html serves as a good first step to integrate this google API into your page

Hope this helps someone

Getting a value from scriptlet to javascript

July 16, 2008

Getting value from a scriptlet into javascript is pretty simple. However the otherway round which means getting a value from a scriptlets into javascript may not be too simple.
You could probably have a hidden parameter, have its

value = <%=request.getParameter(“value”) %>

and how this request parameter is going to get populated is, when you have the jsp submit the request to itself, i.e., have the action = to the same jsp page. For submitting the page to another action, you will have to write a submitForm() method and have it populated with this.form.action=youraction and then submit it.
Now on to the main topic, to get a value from scriptlet into javascript you could :

String a = “abc”;

Then make a hidden element in our good old HTML

<input type=”hidden” name=”testa” id=”testa” value=<%= a%> >

In the javascript where you want to fetch the value, you can do a

document.getElementById(“testa”).value;

thats all.

Date Validity Check

July 9, 2008

This logic can be used to check validty of date in date month year format :

boolean checkDate(int mm, int dd, int yy){
boolean validDate = false;
if((mm == 1 || mm == 3 || mm == 5 || mm == 7 || mm == 8 || mm == 10 || mm == 12) && yy > 2000 ){ //this means the month has 31 days fro sure
if(dd>0 && dd 0 && dd 2000)){
validDate = true;
}else if(mm == 2)
validDate = ((yy%4 ==0)&& (dd>0 && dd0 && dd<29))? true: false; //figuring out leap year
else
validDate = false;

return validDate;
}

Adding || subtracting dates in java

June 24, 2008

I see so many posts around so many forums where people want help on adding or subtracting days from a specific date. So I thought Id leave on the wild world of the net some help which might come handy to someone, someday. Here it is.. you can either follow the logic and add some jazz to it and become the hero of your project or do what most of us happily do, copy paste !

import java.util.Calendar;
import java.util.Date;
public class DateAdder {
public Date addOrSubstractDaysFromDate(Date aDate,int noOfDays) {
Calendar calendar = Calendar.getInstance(); //get teh calendar instance
calendar.setTime(aDate);//set it to today
calendar.add(Calendar.DATE, noOfDays);// this is where the adding || subtracting happens
return calendar.getTime();
}

public static void main(String[] args){
Date today = new Date();
DateAdder dateAdd = new DateAdder();
System.out.println(“Date today : “+today);
System.out.println(“Date after 10 days : “+ dateAdd.addOrSubstractDaysFromDate(today, 10));
System.out.println(“Date before 10 days : “+dateAdd.addOrSubstractDaysFromDate(today, -10));
}
}

enjoy madi

P.S: the formatting is as usual screwy, or may be I dont know how to do it. This is the best I can do to help. If you need further assistance leave a message and Ill see what I can do for ya !!

^ M Command Not found, shell script execution

June 2, 2008

^M Command Not found, shell script execution

if you get an error, in unix duh-uh, which says “^M Command not found”, that means, you just got a freaking extra useless “space” somewhere in your script (while running the script generally the exception comes immediately after execution/interpretation of the line, where you left the space in the file).
you can also run unix2dos which will help you in this.

Code to read an Xml file in DOM and SAX, respectively.

May 27, 2008

The Simple API for XML (SAX)is available with the Java API for XML Processing (JAXP). Along with the Document Object Model, SAX is one of two common ways to write software that accesses XML data
DOM and SAX can either be a validating or a non validating parser.
    A validating parser checks the XML file against the rules imposed by DTD or XML Schema.
    A non validating parser doesn’t validate the XML file against a DTD or XML Schema.
Both Validating and non validating parser checks for the well formedness of the xml document
DOM: DOM will read the entire XML file and keep it in the memory as a tree. I wouldnt recomend DOM to be used where you are parsing realy huge XML files or XML Streams. The API is easier than SAX.. but what the heck. Generally as a rule of thumb use DOM when you want to manipulate the document, traverse the document back and forth and when they are small XML files

File file = new File(“C://TestXml.xml”);
//hook up your file here… this is a bad way to do it. Specify the path in a properties file and then  read it from there. Can you make sure your code runs the same on Unix and Windows ?

   try {
    DocumentBuilder builder =
   DocumentBuilderFactory.newInstance().newDocumentBuilder();
//rings bells ? Factory design pattern…
    Document doc = builder.parse(file); // this is what will hold a handle to
all the elements in the tree.

     NodeList nodes = doc.getElementsByTagName(“person”); //the tag whose
subtags you want to read

      for (int i = 0; i < nodes.getLength(); i++) {
        Element element = (Element) nodes.item(i);
        NodeList title = element.getElementsByTagName(“firstname”);
//the sub tag
        Element line = (Element) title.item(0);
     }

You can loop in this manner and walk throught the nodes available
SAX
Generally (yeah, am taking my arse to a safer stand :D), use SAX where there are no structural modification and they are huge XML files

Pretty obvious :

  XMLReader parser =
XMLReaderFactory.createXMLReader(“org.apache.xerces.parsers.SAXParser”);
 org.xml.sax.ContentHandler handler = new SaxParserClassName();
//your class name
  parser.setContentHandler(handler);   
  InputStream in = connection.getInputStream();
  InputSource source = new InputSource(in);
  parser.parse(source);
  //parser.parse(new InputSource(“C://TestXml.xml”)); either ways !!

The comments that appear below a line, are meant for that line, below which the comments appear. The Formatting is screwing up my effort. Aiway, I think the one who is looking for help will be able to figure out what I am trying to say.

JSP Exception handling

May 15, 2008

I keep forgetting this, so I thought Id make it easier for myself and other schizophrenics like me. Huh 🙂
To demonstrate the run-time exception handling feature of JSP pages, we will build three pages.

Form.html – Display a Form to the user to enter his or her age.
FormHandler.jsp – A JSP Page which receives this value and prints it on the user screen.
ExceptionHandler.jsp – An exception handler JSP page which is actually an error page to which control will be passed when an exception is thrown.
i. Form.html
Create a new Form.html page.

<html>
<body>

<!– HTML Form –>
<form action=”FormHandler.jsp” method=”post”>
Enter your age ( in years ) :
<input type=”text” name=”age” />
<input type=”submit” value=”Submit” />
</form>

</body>
</html>

Explanation
Form.html page simply displays a single input field Form to the user to enter his age in months (Yes, I calculate it in months.. innovative ha). The name of input field where user will enter his/her age is “age”. We will use this input field name “age” in the FormHandler.jsp page to receive it’s value.

ii. FormHandler.jsp
Create new FormHandler.jsp page. :

<%@ page errorPage=”ExceptionHandler.jsp” %> <html> <body> <%– Form Handler Code –%> <% int age; age = Integer.parseInt(request.getParameter(“age”)); %> <%– Displaying User Age –%> <p>Your age is : <%= age %> months.</p> </body> </html>

Explanation
Code above is rather simple. Notice the first line, the page directive. It specifies an errorPage ExceptionHandler.jsp, our exception handler JSP page.

<%@ page errorPage=”ExceptionHandler.jsp” %>

Then we declare an int variable “age”. Then using the static method of Integer class we parse the entered value using Integer.parseInt() method. The value is retrieved using request.getParameter() method. The argument to request.getParameter() is the name of Form field whose value we want to retrieve.

<%
int age;

age = Integer.parseInt(request.getParameter(“age”));
%>

If all goes well and user entered an int ( e.g. 666 ) value in the input field then we display that value back to the user.

<p>Your age is : <%= age %> months.</p

Now things can go wrong and exceptional events can occur. For example, if user didn’t enter a value and what if user entered his name ( e.g. “Marshall Mathers”), of String type instead of an integer ?.

These things will be handled by the ExceptionHandler.jsp JSP page.

iii. ExceptionHandler.jsp
Create a new ExceptionHandler.jsp page.

<%@ page isErrorPage=”true” import=”java.io.*” %>
<html>
<head>
<title>Exceptional Even Occurred!</title>
 </head>
<body>

<%– Exception Handler –%>
<font color=”red”>
<%= exception.toString() %><br>
</font>

<%
out.println(“<!–“);
StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw);
exception.printStackTrace(pw);
out.print(sw);
sw.close();
pw.close();
out.println(“–>”);
%>

</body>
</html>

Explanation
To make a JSP page exception handler ( i.e. errorPage ), you have to specify isErrorPage attribute in the page directive at the top and set it’s value to true.

<%@ page isErrorPage=”true” %>

When a JSP page has been declared an errorPage, it is made available an object with name of “exception” of type java.lang.Throwable. We use different methods of this exception object to display useful information to the user.

<font color=”red”>
<%= exception.toString() %><br>
</font>

 

 We can put the stack trace information for debugging inside HTML comment tags. So that user only sees a useful message and the sysadmin, developers can see the entire story.

<%
out.println(“<!–“);
StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw);
exception.printStackTrace(pw);
out.print(sw);
sw.close();
pw.close();
out.println(“–>”);
%>

To use the PrintWriter and StringWriter classes you’ll have to import java.io.* package in your JSP page by changing the page directive at the top to :

<%@ page isErrorPage=”true” import=”java.io.*” %>