Thursday, October 8, 2009

String Util

import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.charset.Charset;

public class StringUtil {

public static String[] toUpper(String[] inStr)
{
boolean bEmpty=true;
for (int i=0; i {
if (inStr[i]!=null && !inStr[i].equals("") && bEmpty) bEmpty=false;
inStr[i] = inStr[i] != null ? inStr[i].toUpperCase():"";
}
if (bEmpty) return null;
else return inStr;
}

public static int getStringByteLength(String data) {
byte[] utf8 = null;
int byteCount = 0;
try {
utf8 = data.getBytes("UTF-8");
byteCount = utf8.length;
} catch (Exception ex) {
ex.printStackTrace();
}
return byteCount;
}

public static String[] parseCSV(String lineRead) throws Exception {

String data = "";
String tempLine = "";
boolean proceed = true;
boolean isQuotes = false;
int index = 0;
String tokens[] = new String[1000];
String tokenReturn[] ;

lineRead=lineRead+',';
for (int i = 0; i < lineRead.length() - 1; i++) {
data += lineRead.charAt(i);

if (lineRead.charAt(i) == '"' || lineRead.charAt(i) == '^') {
proceed = false;
isQuotes = true;
}

if (proceed == false && (lineRead.charAt(i) == '"' || lineRead.charAt(i) == '^')
&& lineRead.charAt(i + 1) == ',')
proceed = true;

if ((proceed == true && lineRead.charAt(i) == ',')) {
tempLine = tempLine + data;
if (isQuotes){
if(data.trim().length() > 2) {
tokens[index] = data.trim().substring(1, data.trim().length() -2);
}
else
tokens[index] = data.trim();
}
else{
if(data!=null)
tokens[index] = data.trim().substring(0, data.trim().length() - 1);
else
tokens[index]="";
}
data = "";
index++;
isQuotes = false;
}
}

if (tempLine.length() != lineRead.length()) {
if( (data.trim().startsWith("\"") || data.trim().startsWith("^")) && data.length() >= 2)
tokens[index] = data.trim().substring(1, data.trim().length() -1);
else
tokens[index] = data.trim();
index++;
}

tokenReturn = new String[index];
System.arraycopy( tokens, 0, tokenReturn, 0, index);

return tokenReturn;
}


/**
* Convert a given byte[] with charset name into UTF8 format.
*/
public static String toUTF8(String charsetname, byte[] bytes) throws Exception
{
//logger.debug("encoding input:" + new String(bytes, charsetname) + ",length:" + bytes.length);
Charset charset = Charset.forName(charsetname);
ByteBuffer bb = ByteBuffer.wrap(bytes);
CharBuffer cb = charset.decode(bb);
//logger.debug("Length:" + cb.length() + ",UTF-8 output:" + cb.toString());
return cb.toString();
}

/**
* Reverse of toUTF8. Converts UTF8 to individual charset.
*/
public static byte[] fromUTF8(String charsetname, String str) throws Exception
{
//logger.debug("encoding input:" + new String(bytes, charsetname) + ",length:" + bytes.length);
Charset charset = Charset.forName(charsetname);
ByteBuffer bb = charset.encode(str);
byte[] dst = new byte[bb.capacity()];
bb.position(0);
bb.get(dst, 0, bb.capacity());
return dst;
//return new String(dst, charsetname);
//return bb.toString();
}

public static String getErrorStackString(Exception e){
StackTraceElement[] se = e.getStackTrace();
String strse="";

for (int i=0; i {
strse += se[i].toString() + "\n";
}

return strse;
}
}

File Util

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Enumeration;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;


public class FileUtil
{
public static void zip(){}

public static void unzip(){}

public static boolean copyFile(String infile,String outfile) throws Exception {

try{
FileInputStream source = new FileInputStream(infile);
FileOutputStream copy = new FileOutputStream(outfile);

int byteCount = 0;
while (true) {
int data = source.read();
if (data < 0)
break;
copy.write(data);
byteCount++;
}
source.close();
copy.close();
return isFileExist(outfile);
}catch(Exception e){
e.printStackTrace();
return false;
}
}
/**
* Check if the file exists or not
* @param filepath
* @return boolean true if file exists false otherwise.
*/
public static boolean isFileExist(String filepath) {
boolean recfIdExist = false;
try {

File fileInput = new File(filepath);
recfIdExist = fileInput.exists();

} catch (Exception e) {


}
return recfIdExist;
}
/**
* unzip the input file
* @param filePath
* @param fileName
* @return
*/
public static String unzip(String filePath) throws Exception{
String extension = null;
ZipFile zipFile = null;
FileOutputStream fout = null;
InputStream inputStream = null;
//String fileName=filePath.substring(filePath.lastIndexOf("/")+1,filePath.length());
String fileName=extractFileName(filePath);
filePath=filePath.substring(0,filePath.lastIndexOf("/")+1);

try{

zipFile = new ZipFile(filePath+fileName);
Enumeration enumeration = zipFile.entries();
while(enumeration.hasMoreElements()){
ZipEntry zipEntry = (ZipEntry)enumeration.nextElement();
String unzipFile = zipEntry.getName();

extension = extractExtension(unzipFile);

unzipFile=unzipFile.substring(0,unzipFile.lastIndexOf("."));

String extractedFileName = filePath + unzipFile+extension ;
fout = new FileOutputStream( extractedFileName );

inputStream = zipFile.getInputStream(zipEntry);

int data = 0;
byte b[] = new byte[8092];
while ((data = inputStream.read(b)) > 0 ) {
fout.write(b,0,data);
}
}
}catch(Exception error){
throw error;
}
finally {
try {
if (inputStream != null) {
inputStream.close();
}
if (fout != null) {
fout.close();
}
if (zipFile != null) {
zipFile.close();
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

return filePath+fileName+extension;

}


// Extract the extension from file name

public static String extractExtension(String fileName) {
int indexValue = fileName.indexOf(".");
if( indexValue != -1) {
return fileName.substring(indexValue);
}else return fileName;
}

// Extract the file name

public static String extractFileName(String fileName) {

return fileName.substring(fileName.lastIndexOf("/")+1);
}

/**
* Create a directory name for current date in MMddyyyy format
* @return
*/
public static String getBaseDirNameByDate(String savePath) {

SimpleDateFormat sdf=new SimpleDateFormat("MMddyyyy");
String strDate = (sdf.format(new Date())).toString();
savePath=savePath+"/"+strDate;
boolean exists = (new File(savePath)).exists();
if (exists) {
System.out.println("Directory is Already Exists");

} else {
boolean success = (new File(savePath)).mkdirs();
System.out.println("Directory Does not Exists "+success);
}

return savePath;
}
/**
* Checks if the file is a Excel file
* @param fileName
* @return
*/
public static boolean isExcelFile(String fileName) {
if(fileName == null ) {
return false;
} else {
return fileName.endsWith(".xls");
}

}
/**
* Checks if the file is a CSV file
* @param fileName
* @return
*/
public static boolean isCSVFile(String fileName) {
if(fileName == null ) {
return false;
} else {
return fileName.endsWith(".csv");
}

}

/**
* Checks if the file is a zip file
* @param fileName
* @return
*/
public static boolean isZipFile(String fileName) {
if(fileName == null ) {
return false;
} else {
return fileName.endsWith(".zip");
}

}

public static boolean deleteFile(String fileName) {
File f = new File(fileName);
// Make sure the file or directory exists and isn't write protected
/*if (!f.exists())
throw new IllegalArgumentException(
"Delete: no such file or directory: " + fileName);

if (!f.canWrite())
throw new IllegalArgumentException("Delete: write protected: "
+ fileName);

// If it is a directory, make sure it is empty
if (f.isDirectory()) {
String[] files = f.list();
if (files.length > 0)
throw new IllegalArgumentException(
"Delete: directory not empty: " + fileName);
}*/

// Attempt to delete it
boolean success = f.delete();

if (!success)
return true;

return false;
}
}

EMailUtil using Java

This summary is not available. Please click here to view the post.

Scheduler using Java

import java.util.Timer;
import java.util.TimerTask;

public class Schedulers extends TimerTask
{

static Timer timer = null;
boolean bInit = false;
private static Schedulers scheduler = null;

protected void init() throws Exception
{
}

void schedule() throws Exception{

System.out.println("Running"+System.currentTimeMillis());

}

public void run()
{
try
{
if (!bInit) init();
schedule();
}
catch (Exception e)
{
e.printStackTrace();
}
}

public static void main(String args[])
{
try{
start(new Schedulers(),1);
}
catch(Exception e)
{
e.printStackTrace();
}
}
public static void start(Schedulers jscheduler, int min) throws Exception
{
scheduler=jscheduler;
timer = new Timer();
timer.schedule(scheduler, new java.util.Date(), min*60*1000);
}
}

Read xls data from Java using JXL jar

import java.io.File;
import java.io.*;
import jxl.*;
import java.util.*;
import jxl.Workbook;
import jxl.read.biff.*;
class readXls
{
public static void main(String[] args) throws IOException, BiffException
{
String filename = "D:/Documents and Settings/nzq4pt/Desktop/TNEWS_05/TNEWS_VRT.XLS";
readContentsFromExcel(filename);
}
private static ArrayList readContentsFromExcel(String filename)
{
ArrayList readDataShet = new ArrayList();
WorkbookSettings ws = new WorkbookSettings();
ws.setLocale(new Locale("en", "EN"));
Workbook workbook;
try
{
workbook = Workbook.getWorkbook(new File(filename),ws);
Sheet s = workbook.getSheet(0);
readDataSheet1(s);
workbook.close();
} catch (BiffException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return readDataShet;
}
private static void readDataSheet1(Sheet s)
{
// Find the labeled cell from sheet
LabelCell qname = s.findLabelCell("Email");
for(int j = 1; j{
Cell dispcell = s.getCell(0,j);
String content = dispcell.getContents();
System.out.println("'"+content+"',");
}
}
}

Friday, March 21, 2008

marker interface

Hi ,
If there is no methods in the interface that is called marker interface. But I have doubt how it will work?
for example if we will implement java.io.Serializable interface then that object is called serialized object. But we are not implement any methods regarding. How that class variables persistent.