Showing posts with label java. Show all posts
Showing posts with label java. Show all posts

Friday, October 2, 2009

Run os commands from java + print error messages

private void runProcess() throws Exception
{
try
{
Runtime rt = Runtime.getRuntime();
Process process = rt.exec("cmd /c cp C:\\work\\dev\\test.txt C:\\work\\dev\\test1.txt");
BufferedReader input = new BufferedReader(new InputStreamReader(process.getInputStream()));

String line = null;

while ((line = input.readLine()) != null)
{
System.out.println(line);
}

int exitVal = process.waitFor();
if (exitVal != 0)
{
input = new BufferedReader(new InputStreamReader(process.getErrorStream()));
line = null;

while ((line = input.readLine()) != null)
{
System.out.println(line);
}
}
}
catch (Exception e)
{
System.out.println(e.toString());
e.printStackTrace();
}
}

Monday, August 20, 2007

Create a thumbail for your image

public void generateThumbnail(String imgPath, int imgWidth, int imgHeight)
{
try
{

//Assumptions
//imgPath contains the imagefilename, BUT NOT THE EXTENSION

System.out.println("Image width : "+imgWidth+" Image Height : "+imgHeight);

String fs = System.getProperty("file.separator");

double ratio1=((double)Constants.Thumbnail_x) /Constants.Thumbnail_y;
double ratio2= ((double)imgWidth)/imgHeight ;
double ratio3 = 0;

int newImgWidth=0, newImgHeight=0;

int startX = 0, startY = 0;

if(ratio1 > ratio2)
{
ratio3 = ((double)Constants.Thumbnail_y) / imgHeight;
newImgWidth = (int)(imgWidth * ratio3);
startX = (Constants.Thumbnail_x - newImgWidth)/2;
}
else
{
ratio3 = ((double)Constants.Thumbnail_x) / imgWidth;
newImgHeight = (int)(imgHeight * ratio3);
startY = (Constants.Thumbnail_y - newImgHeight)/2;
}

System.out.println("ratio3 : "+ratio3);

BufferedImage imageBuffer = new BufferedImage(Constants.Thumbnail_x, Constants.Thumbnail_y, BufferedImage.TYPE_INT_ARGB);
Graphics2D g = imageBuffer.createGraphics();

double scaleX = ratio3, scaleY = ratio3;

//System.out.println("image file path : "+imgPath);
File file = new File(imgPath+".png");
BufferedImage bi = ImageIO.read(file);

AffineTransform at = new AffineTransform();
at.scale(scaleX, scaleY);
AffineTransformOp ato = new AffineTransformOp(at, AffineTransformOp.TYPE_BILINEAR);
g.drawImage(bi, ato, startX, startY);

String writePath=imgPath+"-tmb.png";
System.out.println("Image filepath : "+writePath);

ImageIO.write(imageBuffer, "png", new File(writePath));

char fs1 = fs.charAt(0);

String writeFile = writePath.substring(writePath.lastIndexOf(fs1)+1,writePath.length());

//writecode to write the file to disk

}
catch(Exception e)
{
System.out.println("Exception in DrawingUtils generateThumbnail() : ");e.printStackTrace();
}
}

Tuesday, July 3, 2007

Read a Matrix from a text file using Java

Rules :
Rule 1 : The matrix text file values (contents of the file) should be space/tab limited
Rule 2 : The matrix text file should contain only integers
Rule 3 : The file should start and end with the matrix values, should not have anything else.


A sample matrix file content :

3 1 -5 -3 4
4 -5 -2 -3 -3
6 -8 -2 -6 1
3 4 1 -4 -8
1 4 -2 7 -1


Here goes the code :


private static int[][] getMatrix(String matrixFilePath) throws Exception
{
int matrix[][] = new int[1][0];

int charcount = 0;

File gf = new File(matrixFilePath);

FileInputStream fis = new FileInputStream(gf);

int ch=0, cl=0, ri=0; //char, columnlength, row index, currentcolumn


boolean negative = false;
boolean firstEntry = true;
boolean extraCharRead = false;
boolean blockEntered = false;

while(ch!=-1)
{
if(!extraCharRead)
{
ch = fis.read();
extraCharRead = false;
}

if(extraCharRead) { extraCharRead = false; System.out.println("EXTRA CHAR");}
else
//45 -, 9 tab, 32 space, 13 and 10 new line

if((ch==13)&&(charcount!=0))
if((ch = fis.read())==10) //new line
{
if(!(matrix[0].length == 0)) { ri++; }


if(firstEntry)
{
firstEntry=false;
cl = charcount;
}
else
{
if(!(cl == charcount))
{
System.out.println("MatrixFlip getMatrix() : File :"+matrixFilePath+" Line no : "+ri+" -- The number of columns doesn't match the first row. \n STOPPING PROGRAM !!!");
System.exit(0);
}
}
int tempmatrix[][] = matrix;
matrix = new int[ri+1][charcount];


for(int i=0;i<tempmatrix.length;i++)
for(int j=0;j<tempmatrix[0].length;j++)
{
matrix[i][j] = tempmatrix[i][j];
}

charcount = 0;
}

if(ch==45)
{
negative = true;
ch = fis.read();
if(!((ch > 47)&&(ch < 58))) {negative=false; extraCharRead = true;}
}

if((ch > 47)&&(ch < 58))
{
charcount ++;


int number = 0;
String numberString = "";

numberString += (char)ch;
ch = fis.read();

while((ch > 47)&&(ch < 58))
{
numberString += (char)ch;
ch = fis.read();
}
extraCharRead = true;

number = new Integer(numberString).intValue();

if (negative)
{
number = 0 - number;
negative = false;
}

if(firstEntry)
{
int tempmatrix[][] = matrix;
matrix = new int[1][charcount];


for(int j=0;j<tempmatrix[0].length;j++)
{
matrix[0][j] = tempmatrix[0][j];
}

matrix[0][charcount-1] = number;
}
else
{
matrix[ri][charcount-1] = number;
}
}
}

if(charcount == 0) // if a new line is inserted at the end of the file
{
int mh = matrix.length-1;
int tempmatrix[][] = matrix;
matrix = new int[mh][tempmatrix[0].length];


for(int i=0;i<mh;i++)
for(int j=0;j<tempmatrix[0].length;j++)
{
matrix[i][j] = tempmatrix[i][j];
}
}

System.out.println("\n PRINTING THE GRID MATRIX : ");

for(int i=0;i<matrix.length;i++)
{
System.out.println();

for(int j=0;j<matrix[0].length;j++)
{
System.out.print(matrix[i][j]+"\t");
}
}

return matrix;
}

Monday, May 21, 2007

Convert embedded images into base64 in SVG using Java

Its a nice feature that you can include images in SVG. But the embedded images still refer to an external file. So while the svg is downloaded all the relevant image files have to be downloaded as well. To avoid this you can convert your images into Base64 before embedding. All the referred images will remain in the same SVG file, SVG will not refer external image files. The functions mentioned use the Base64 utility from here : http://iharder.sourceforge.net/current/java/base64/. Pass the SVG file as a string into the method fillBase64(). This will return an SVG string with your image files Base64 embedded. What I have done here is a small text parsing to find image tag and include the corresponding Base64 code. Enjoy!

public String fillBase64(String svg) throws Exception
{
String newSvg = "";

try
{

int imageStartPos = svg.indexOf("<image",0);
int imageEndPos = 0;
int imageUrlPos = 0;
int copyStartPos = 0;
int fileNameStartPos = 0;
int fileNameEndPos = 0;

while(imageStartPos != -1)
{
imageEndPos = svg.indexOf("/>",imageStartPos);
imageUrlPos = svg.indexOf("xlink:href=",imageStartPos);

if((imageUrlPos > imageStartPos)||(imageUrlPos < imageEndPos))
{
fileNameStartPos = imageUrlPos+12 ;
fileNameEndPos = svg.indexOf("\"",fileNameStartPos);
String imageFilePath = svg.substring(fileNameStartPos, fileNameEndPos);

String base64String = getBase64(imageFilePath);

new File(imageFilePath).delete();

newSvg += svg.substring(copyStartPos, fileNameStartPos);
newSvg += "data:image/jpeg;base64,"+base64String;

copyStartPos = fileNameEndPos;
}
imageStartPos = svg.indexOf("<image",imageEndPos+2);
}

newSvg += svg.substring(copyStartPos);
}
catch(Exception e)
{
System.out.println("Exception in fillBase64() : ");e.printStackTrace();
}

return newSvg;
}



private String getBase64(String filePath) throws Exception
{
String h = "";
try
{
System.out.println("PRINTING THE FILEPATH \""+filePath+"\"");
File f = new File(filePath);

byte[] b = new byte[(int)f.length()];
System.out.println("FILELENGTH : "+(int)f.length());
FileInputStream fis = new FileInputStream(f);
fis.read(b);
h = Base64.encodeBytes(b);
}
catch(Exception e)
{
System.out.println("Exception in getBase64() : ");e.printStackTrace();
}

return h;
}

Tuesday, May 15, 2007

runtime file upload using java

CLIENT (HttpMultiPartFileUpload.java):

import java.io.File;
import java.io.IOException;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.methods.MultipartPostMethod;

public class HttpMultiPartFileUpload {
private static String url =
"http://aruljose:9090/ProcessFileUpload.jsp";

public static void main(String[] args) throws IOException {
HttpClient client = new HttpClient();
MultipartPostMethod mPost = new MultipartPostMethod(url);
client.setConnectionTimeout(8000);

// Send any XML file as the body of the POST request
File f1 = new File("C:\\Documents and Settings\\aruljose\\Desktop\\downloaded.jpg");
//File f2 = new File("academy.xml");
//File f3 = new File("academyRules.xml");

System.out.println("File1 Length = " + f1.length());
//System.out.println("File2 Length = " + f2.length());
//System.out.println("File3 Length = " + f3.length());

mPost.addParameter(f1.getName(), f1);
//mPost.addParameter(f2.getName(), f2);
//mPost.addParameter(f3.getName(), f3);

int statusCode1 = client.executeMethod(mPost);

System.out.println("statusLine>>>" + mPost.getStatusLine());
mPost.releaseConnection();
}
}


SERVER (ProcessFileUpload.jsp) :

<%@ page contentType="text/html;charset=windows-1252"%>
<%@ page import="org.apache.commons.fileupload.DiskFileUpload"%>
<%@ page import="org.apache.commons.fileupload.FileItem"%>
<%@ page import="java.util.List"%>
<%@ page import="java.util.Iterator"%>
<%@ page import="java.io.File"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=windows-1252">
<title>Process File Upload</title>
</head>
<%
System.out.println("Content Type ="+request.getContentType());

DiskFileUpload fu = new DiskFileUpload();
// If file size exceeds, a FileUploadException will be thrown
fu.setSizeMax(1000000);

List fileItems = fu.parseRequest(request);
Iterator itr = fileItems.iterator();

while(itr.hasNext()) {
FileItem fi = (FileItem)itr.next();

//Check if not form field so as to only handle the file inputs
//else condition handles the submit button input
if(!fi.isFormField()) {
System.out.println("\nNAME: "+fi.getName());
System.out.println("SIZE: "+fi.getSize());
//System.out.println(fi.getOutputStream().toString());
File fNew= new File("C:\\Documents and Settings\\aruljose\\Desktop\\downloaded1.jpg");

System.out.println(fNew.getAbsolutePath());
fi.write(fNew);
}
else {
System.out.println("Field ="+fi.getFieldName());
}
}
%>
<body>
Upload Successful!!
</body>
</html>

Monday, May 14, 2007

read image from url, write to your disk using java

URL url = new URL("http://host/urlseg1/urlseg2");//image url
BufferedImage bi = ImageIO.read(url);
ImageIO.write(bi,"jpg",new File("your file path - c:\\folder1\folder2\file.jpg"));

Tuesday, March 20, 2007

tag completion for xhtml conversion using java

This java class completes the incomplete tags in your html [you need to pass the html as a string to the function convertHtml(String)]. The code is free for use.

First make sure your html is browser compatible, then use this code for tag completion.

import java.util.Stack;

public class HtmlToXHtml
{
public String convertHtml(String fs)
{
StringBuffer nfs = new StringBuffer();
boolean parsingOver = false;
StringBuffer startTag = new StringBuffer();
StringBuffer endTag = new StringBuffer();
StringBuffer currentEndTag = new StringBuffer();

Stack stack = new Stack();

int sl = fs.length();
sl--;

int i=0;

while(!parsingOver)
{
if(i>sl) {parsingOver = true;break;}

if(fs.charAt(i)=='<')
{
//END TAG PART
if(fs.charAt(i+1)=='/')
{
endTag = new StringBuffer(""+fs.charAt(i));
i++;
//System.out.println(i);
while(fs.charAt(i)!= '>')
{
if(fs.charAt(i)=='<')
{
nfs.append(endTag);
break;
}
else if (i>sl)
{
nfs.append(endTag);
parsingOver = true;
break;
}
endTag.append(fs.charAt(i));
//System.out.println("\n CHARACTER : "+fs.charAt(i));
i++;
//System.out.println(i);
if(i>sl){i--; parsingOver=true; break;}
}

if(fs.charAt(i)== '>')
{
endTag.append(fs.charAt(i));
//System.out.println("\n CHARACTER : "+fs.charAt(i));


if(endTag.indexOf(" ")== -1)
{
//System.out.println("\nA END TAG COMING IN : "+endTag);

startTag = new StringBuffer(); //essential for the condition in the next while

try
{
//System.out.println(stack);
startTag = (StringBuffer)stack.pop();
//System.out.println("POPPING START TAG : "+startTag);

while(!(startTag.toString()).equals(getStartTagForEndTag(endTag).toString()))
{
if(i>sl) {parsingOver = true;break;}
//System.out.println("START TAG : "+startTag+" END TAG : "+getStartTagForEndTag(endTag));
currentEndTag = getEndTagForStartTag(startTag);
nfs.append(currentEndTag);
try
{
startTag = (StringBuffer)stack.pop();
//System.out.println("POPPING START TAG : "+startTag);
}
catch(Exception e)
{
nfs.append(getStartTagForEndTag(endTag));
break;
}

}
}
catch(Exception e)
{
nfs.append(getStartTagForEndTag(endTag));
//System.out.println(e);
}

nfs.append(endTag);
i++;
//System.out.println(i);
}
else
{
nfs.append(endTag);
}
}
else
{
nfs.append(endTag);
}
}


//STARTING TAG PART
else if (fs.charAt(i+1)!=' ')
{
startTag = new StringBuffer(""+fs.charAt(i));
i++;
System.out.println(i+" : "+nfs );
while(fs.charAt(i)!= '>')
{
if(i>sl) {parsingOver = true;break;}
if(fs.charAt(i)=='<')
{
break;
}
startTag.append(fs.charAt(i));
i++;
if(i>sl){i--; parsingOver=true; break;}
}
if(fs.charAt(i)== '>')
{
startTag.append(fs.charAt(i));
nfs.append(startTag);

if((startTag.indexOf(" ")== -1)||(startTag.indexOf(" ")>1))
{
StringBuffer startTagPart = new StringBuffer();
if(startTag.indexOf(" ")>1)
{
startTagPart = new StringBuffer(startTag.substring(0,startTag.indexOf(" "))).append(""+'>');
}
else startTagPart = new StringBuffer(startTag);
stack.push(startTagPart);
}

i++;
}
else
{
nfs.append(startTag);
}
}
}
else
{
nfs.append(fs.charAt(i));
//System.out.println("\n CHARACTER1 : "+fs.charAt(i));
i++;
//System.out.println(i);
}
}

while(!stack.empty())
{
try
{
startTag = (StringBuffer)stack.pop();
//System.out.println("POPPING START TAG : "+startTag);
currentEndTag = getEndTagForStartTag(startTag);
nfs.append(currentEndTag);
}
catch(Exception e)
{
break;
}
}

return nfs.toString();
}


private StringBuffer getEndTagForStartTag(StringBuffer startTag)
{
StringBuffer startTag1 = new StringBuffer(startTag);
return startTag1.insert(1, '/');
}

private StringBuffer getStartTagForEndTag(StringBuffer endTag)
{
StringBuffer endTag1 = new StringBuffer(endTag);
endTag1.replace(1,2,"");
return endTag1;
}

}