Wednesday, February 15, 2012

HTML TO JPEG IN JAVA

Hi,
   Today i will explain you how to convert html page to jpeg in java.

     public class HTML2JPEG{
          public static void main(String args[]){
              //for reading the input file data
              DataInputStream dis = new DataInputStream(new FileInputStream(new File("file.html")));
              //for writing the output file data
              FileOutputStream fos = new FielOutputStream(new File("testfile.jpeg"));
              bytes[]  bytes = new byte[1024];
              StringBuffer sb = new StringBuffer();
              while(dis.available() >0){
                      sb.append(new String(bytes, 0, dis. read(bytes)));
             }
              String str = sb.toString();
              //using awt package for creating the image
              JLabel label = new JLabel(str);
              label.setSize(800,800);
            
               BufferedImage image = new BufferedImage(label.getWidth(),label.getHeight(),BufferedImage.TYPE_BYTE_RGB);
               Graphics g = image.getGraphics();//or else can use createGraphics()              
               g.setColor(Color.BLACK);            
               label.paint(g);
               g.dispose();
            
              ByteArrayOutputStream baos = new ByteArrayOutputStream();
              ImageIO.write(image, "jpeg",baos);
              //read the data from baos to byte[]
              byte[] bytesData = baos.toByteArray();  
               //Or Else you can use FileOutputStream
              ImageIO.write(image, "jpeg",fos);
              System.out.println("Completed");
         }
}

Please correct me if at all there is any changes need to be done in the above program.Or else if there is a better way than this, post it immediately.Any help appreciated.

Wednesday, January 25, 2012

LOG4J Configuration in Simple Project

Hi,
     Here i'll be explaining you the Log4j configuration in Sturts1.x with a sample Java Program.
     import org.apache.log4j.*;
     public class Log4jClass {
         //In order to generate the logger file at the time of starting the server.
         static{
                   //create a logger instance
                   Logger log = Logger.getLogger(Log4jClass.class);
                    //Domconfigurator to setting the properties of logger file using xml or properties file.
                    DomConfigurator.configure("log4jpath/log4j.xml"); //or log4j.properties file
          }
      
          public static void main(String args[]) {
              //Different logging levels available in Log4j
              Log4jClass.trace(Log4jClass.class,"This is the trace method usage in log4j file");
              Log4jClass.debug(Log4jClass.class,"This is the debug method usage in log4j file");
              Log4jClass.info(Log4jClass.class,"This is the info method usage in log4j file");
              Log4jClass.warn(Log4jClass.class,"This is the warn method usage in log4j file");
              Log4jClass.error(Log4jClass.class,"This is the error method usage in log4j file");
              Log4jClass.fatal(Log4jClass.class,"This is the fatal method usage in log4j file");
       }
 }

You can set the System Out console to logger also using the System.setOut() method
Where,
            PrintStream ps = new PrintStream(new FileOutputStream("pathtofile");
            System.setOut(ps);
Now,
          System.out.println("Text");
                                                  will be moved to the logger file only but not to system console. Any line before the System.setOut() will be to System Console but not to logger file.

Any modifications or corrections will be appreciated......
          

        

Wednesday, September 14, 2011

XPath Tutorial


Hi All,
Please i have small description of the XPath Parser usage in Java instead of the DOM or SAX parsers. The XPath language provides a simple, concise syntax for selecting nodes from an XML document. XPath also provides rules for converting a node in an XML document object model (DOM) tree to a boolean, double, or string value.



Below i have written  a Simple XPath Tutorial program in java
import javax.xml.xpath.*;

public static void main(String args[]){
          String xmlString = "<employees>"+
                                         "<employee> "+
"<name>"+
"Johny"+
"</name>"+
"<name>"+
"Williams"+
"</name>"+
"</employee>"+
"</employees>" ;
try{
//To get an instance of the XPathFactory object itself.

XPathFactory xPathFactory = XPathFactory.newInstance();
// Create an instance of XPath from the factory class

XPath xPath = xPathFactory.newXPath();
String expression = "/employees/employee/name";
// Compile the expression to get a XPathExpression object.
XPathExpression xpathExpression = xPath.compile(expression);
//Evaluate the expression against the XML Document to get the result.
Object result = xpathExpression.evaluate(new InputSource(new StringReader(xmlString)));


}catch(XPathExpressionException e){
e.printStackTrace();
}
}


The above program will give the name of all the employees in the xml Document.

  • If at all you need only the first employee name pass the expression value as :-

                  String expression = "/employees/employee[1]/name"; 
                  will return only the first employee name.

  • If you need to pass a document instead of an xmlString then follow the below process for reading the xml document.
       String  xmlFile = "TestFile.xml";
        Document xmlDocument = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(xmlFile);
At the lat pass the only xmlDocument to evaluate() method instead of 
xmlString See Below:-
xPathExpression.evaluate(xmlDocument, returnType);
//returnType can be any of the QNames available in XPath Package:-
//XPathConstants.STRING, XPathConstants.NUMBER, XPathConstants.BOOLEAN, 
//XPathConstants.NODE and XPathConstants.NODESET. 

                              OR
      XPathReader reader = new XPathReader("src\\com\\javabeat\\tips\\xpath\\projects.xml"); 
reader.read(expression, XPathConstants.STRING)

// To get a xml attribute.
String expression = "/projects/project[1]/@id";
System.out.println(reader.read(expression, 
XPathConstants.STRING) + "\n");

// To get a child element's value.
expression = "/projects/project[2]/name";
System.out.println(reader.read(expression, 
XPathConstants.STRING) + "\n");

// To get an entire node
expression = "/projects/project[3]";
NodeList thirdProject = (NodeList)reader.read(expression,
XPathConstants.NODESET);
traverse(thirdProject);

public static void traverse(NodeList rootNode){
for(int index = 0; index < rootNode.getLength();index ++){
Node aNode = rootNode.item(index);
if (aNode.getNodeType() == Node.ELEMENT_NODE){
NodeList childNodes = aNode.getChildNodes();
if (childNodes.getLength() > 0){
System.out.println("Node Name-->" + aNode.getNodeName() +" , Node Value-->" + aNode.getTextContent());
}
traverse(aNode.getChildNodes());
}
}
}



Tuesday, September 6, 2011

Creation Of PDF Document in JAVA

Here i'm giving a simple program for creating a pdf document using java.
Prerequsite jars are :-
iText.jar


Remark:
  1. Once a document is created you can add some meta information.
  2. You can also set the headers/footers.
  3. You have to open the document before you can write content.
  4. You can only write content (no more meta-formation!) once a document is opened.
  5. When you change the header/footer on a certain page, this will be effective starting on the next page.
  6. After closing the document, every listener (as well as its OutputStream) is closed too.
Below is the main program:-
import com.itextpdf.text.*;

public class DataIntoPDF{


public static void main(String args[]){
//create a document
Document PDFDocument = new Document(PageSize.A4,50,50,50,50);
try{
//pdfwriter instance for writing the data to a file.FileOutput writes the data using output stream to the file specified.If the file doesn't exists throws file not found exception.
PdfWriter pdfWriter  = PdfWriter.getInstance(PDFDocument, new FileOutputStream("E:/pdfData.pdf"));
//add meta information to document
pDFDocument.addAuthor("Anand Kumar");
pDFDocument.addCreator("Anand Kumar");
pDFDocument.addSubject("PDF Creation");
pDFDocument.addCreationDate();
pDFDocument.addTitle("PDf Creation");
PDFDocument.open();
                        String dataToPDF  = 
                                        "Anand Kumar,
                                            " +
 Information only
                                           " +
"Nothing Confidential," +
"
                                                   Just Follow,
                                                  " +
"
                                     Address– " +
"Not Mine Write your Own 
                                      ";

Paragraph p = new Paragraph(dataToPDF);
PDFDocument.add(p);
//Adds a new page to the existing document
PDFDocument.newPage();
Image image = getImageFromResource("/PathtoImage/ImageFile");
Chunk imageChunk = new Chunk(image,-5,0);
PDFDocument.add(imageChunk);
}catch(DocumentException de){
de.printStackTrace();
}catch(Exception e){
e.printStackTrace();
}
PDFDocument.close();

}


//For Image resource
private static Image getImageFromResource(String URI){
Image image = null;
try{
image = Image.getInstance(URI);
}catch(IOException ioe){
de.printStackTrace();
}catch(Exception e){
e.printStackTrace();
}
return image;
}


}

If any modifications are appreciated.
Thankyou.......................!!!!!!!!!!!!!!!!:-)

Wednesday, July 27, 2011

Excel Creation Using JAVA

Creating the Excel using JAVA


POI terminology

The key terms associated with Jakarta POI are as follows:

  • POIFS (Poor Obfuscation Implementation File System): Java APIs for reading and writing OLE (Object Linking and Embedding) 2 compound document formats
  • HSSF (Horrible Spreadsheet Format): Java API to read Microsoft Excel
  • HDF (Horrible Document Format): Java API to read and write Microsoft Word 97
  • HPSF (Horrible Property Set Format): Java API for reading property sets using (only) Java

Create an Excel document

The Jakarta POI API can be used to create an Excel document programmatically. The important steps involved are:

  • Create a workbook: HSSFWorkbook workbook = new HSSFWorkbook();
  • Create a new worksheet in the workbook and name the worksheet "Java Excels": HSSFSheet sheet = workbook.createSheet("Java Excels");
  • Create a new row in the sheet: HSSFRow row = sheet.createRow((short)0);
  • Create a cell in the row: HSSFCell cell = row.createCell((short) 0);
  • Put some content in the cell: cell.setCellValue("Have a Cup of XL");
  • Write the workbook into the filesystem: workbook.write(fileOutputStream);

The key steps in reading the Excel sheet are as follows:

  • Create a new Excel document reference: HSFWorkbook workbook = new HSSFWorkbook(new FileInputStream(fileToBeRead));.
  • Refer to the sheet: By default, the first sheet in the Excel document is at reference 0: HSSFSheet sheet = workbook.getSheetAt(0);. A sheet can also be referred to by name. Let's assume that the Excel sheet has the default name "Sheet1". It can be referred to as follows:HSSFSheet sheet = workbook.getSheet("Sheet1");.
  • Refer to a row: HSSFRow row = sheet.getRow(0);.
  • Refer to a cell in the row: HSSFCell cell = row.getCell((short)0);.
  • Get the values in that cell: cell.getStringCellValue();.

A Practical Example

Let's concentrate on just the interesting steps of Jakarta POI usage:

  • Create a new Excel document: workbook = new HSSFWorkbook();
  • Make a worksheet in that document and give the worksheet a name:sheet = workbook.createSheet("Java Class Info");
  • Set the first three columns' widths:sheet.setColumnWidth((short)0,(short)10000 );
  • Create the header line: HSSFRow row = sheet.createRow((short)0);
  • Create and set font and cell style:
       HSSFFont font = workbook.createFont();    font.setColor(HSSFFont.COLOR_RED);    font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);    // Create the style       HSSFCellStyle cellStyle= workbook.createCellStyle();       cellStyle.setFont(font); 
  • Use the cell style:
          HSSFCell cell = row.createCell((short) 0);       cell.setCellStyle(cellStyle);       cell.setCellType(HSSFCell.CELL_TYPE_STRING);       cell.setCellValue("Class Name "); 
  • Write the output file:
          FileOutputStream fOut = new FileOutputStream(outputFile);       // Write the Excel sheet       workbook.write(fOut);       fOut.flush();       // Done deal. Close it.       fOut.close(); 

A Good Reference for the HSSFWorkBook is provided below:- http://poi.apache.org/spreadsheet/quick-guide.html

Friday, June 17, 2011

JAVA DLL BRIDGE

Hi All,
I made a small research in the java program , on how to call windows DLL files using Java program.
Actually this is task provided for me by the project Manager. In our project, there has been a requirement that, when the client clicks on a link.It must call the scanner machine, scan the Image selected by the client and paste it in some location in the system after scanning.

Dlls considered as a native application, not like any applications.
Using the dll libraries within the .Net framework is such an easy operation, just we need to load the library within the environment, initiate an object from it, then use it like any other object in the program.

Such an immediate operation does not exist for the java environment, so that there are some interfaces and frameworks has been built that allow java programmers to interact with dll libraries and use their functionality within java applications.
So, almost this has taken 3 days for me to get the solution. Might be more but have some reasons behind it. Coming directly to the solution.

Firstly, i have googled for loading the DLL files using JAVA program. They are providing the solution using the System.loadLibrary() or System.load(). But they din't worked out for me.In the middle got frustated might not be possible. Latter, thought that how come this will not come for me. After coming from office to home sat for 2 or 3 hours on the system googled it out. Came across JACOB . Thought this might work out for me for bringing the solution for my problem.
As the enviroment is not available at my home thought to implement it at the office.

Nex day went to the office, opened the same link.

The JACOB project is a generic COM bridge. It is licensed as open-source on sourceforge.net.
it is an ancronym for JAva COm Bridge. It only implements a generic bridge to call COM components from Java.
It is not the Java interface of Microsoft Office nor it supports directly its COM components
The way jacob is implemented is using JNI
and a c++ DLL designed for the windows platform. COM is a binary standard
defined by Microsoft as it hasn’t been ported over (as far as I know) to any
other platforms yet. Jacob is only a java bridge for COM which defines how
components talk to each other when they are on the same machine.

JACOB is a JAva-COm Bridge that allows you to call COM automation components from Java. It uses JNI internally to make native calls into COM and Win32 libraries. In simple words, you can now call any of the .dll file functions from Java and use the result in your Java program (provided you know which function to call)”, JNI is the Java Native Interface.
Written a program to invoke the DLL file using Jacob – JAva COm Bridge.

Made a Sample Project in Eclipse having a standalone java program. This program makes use of methods available in Jacob jar files. These methods make the java program to invoke the methods available in the dll file.

Pre-requisite before running the program are:-

Put Jacob.dll in the directory that Windows searches for the libraries(in my computer – “Windows/system32”).

Put Jacob.jar in my CLASSPATH or BuildPath.

Registered the user-defined DLL or my.DLL using the .net framework – located in my system at :- “C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727” through command prompt - C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727> RegAsm/codebase "E:/JARS/ImageAssembly/ImageAssembly.dll".

If the registration has been successfully done. There will not be any errors related to the

dll file. If the library is not registered, or not registered properly, an exception will be

thrown (ComFailException: Can't get object clsid from progid) .

Now write the java program to access the methods available in dll file.

> First load library using ActiveXComponent class available in Jacob.jar as below:-
Ex: ActiveXComponent comp = new

ActiveXComponent("ImageAssembly.CallScanner");
//Where ImageAssembly - Name of the dll file
CallScanner - Class name

Then call the Dispatch.call method of the Jacob.jar file. This returns a variant.Depending

on the return type of the method you are calling in the Dispatch.call - append respective

return type to Dispatch.call().
Ex:- Dispatch.call().toString();
Dispatch.call().toInt();

Now I’m able to access the methods available in the dll using the dispatch class methods available from Jacob jar.

Thanks a lot to JACOB for providing such a simple, efficient app.

If anybody wants the link here it is:-

Saturday, November 7, 2009

Main Shayaar Tho nahiiiiii...................

Dil Ki Baath Shayaari sey shuruu hothi hain......
Tho yeeh thi hamarey gazal.............

Tairna hai to samundar mein tairo,
Nadi naalo mein kya rakha hai,
Mohabbat karni hai to apne watan se karo,
In bewafa hasino mein kya rakha hai……

Dil-e-nadan tha jo tumse pyaar kar baitha,
Khuli aankhon se tera khwab dekha,
Chand ko apni takdeer samaj,
Ae bewafa, aasman ko choone chala….


Kaante hi na hote rahon mein kabhi,
Un nazook ko phool kaun kehta,
Mushkile na hoti zindagi mein kabhi,
Us insaan ko sikandar kaun kehta….


Pyaar karne wale darte nahi,
Darnewale pyaar karte nahi,
Hote nahi hausle buland jinke,
Maidan-e-jung ladaa karte nahi….


Tum haseen ho to hum bhi kuch kam nahi,
Tum mahlo ki ho to hum bhi sadko ke nahi,
Pyaar kar ke kehti ho ke shaadi shuda ho,
Kaan khol kar sunlo Kuvare hum bhi nahi.

Boss: Arz kiya hai………
Office may Kaam hote hain…
Galtiyon ka sama hota hai….
Aise mausam mein hi to PERFORMANCE jawan hote hai….
Dil ki khunnas BOSS Zabaan se nahi kehte…
Ye fasana to appraisal mein bayan hota hai….


Employee’s reply… Arz kiya hai………
Appraisal hote hain…
Disappointment ka sama hota hai…
Aise mausam mein hi to Attrition jawan hote hai….
Dil ki khunnas HUM jabaan se nahi kehte…
Ye fasana to resignation se bayan hota hai….

Sangeet Ka Taraana Hua,
Shamaa Ka Parwana Hua,
Masti Ka mastaana Hua,
Jaise Hi Gunghat Uthaya
Is Duniya Se Ravana Hua!

Kisi ne hume aashiq kaha,Kisi ne hume diwana kaha.... In aankhon me aansu tab aaye,Jab apno ne hume begana kaha....

Mere Dil, Jiger, Kidney, Liver ho tum
waqt-bewaqt aaye vo fever ho tum
Doob kar jisme marr jaoo vo River ho tum
Mere jeevan mein ab to forever ho tum…

Shaam hote hi ye Dil udaas hota hai
Toote khwaboo ke siwa kuch na pass hota hai
Tumahri yaad aise waqt bohat aati hai
Bandar jab koi aas-paas hota hai..

Bolaa dukaan-daar, ke kyaa chahiye tumhain
Jo bhii kaho ge merii dukaan per wo paoge
Maine kahaa ke kutte ke khaane kaa cake hai
Bolaa yahiin pe khaaoge yaa leke jaaoge

Shraab dard ki dawa hai
Peene se koi khraabi nahi
Dil ke dard se peete hain
Waise hum Shraabi nahi…

Shraab dard ki dawa hai
Peene se koi khraabi nahi
Dil ke dard se peete hain
Waise hum Shraabi nahi…

Bhuto sa chehra tera
Chudeel si muskan hai
Rang tera dekh ke… rup tera dekh ke
kutte bhi hairan hai

Chandni raat thi, main so rahi thi
Phir kisi ne darwaza khutkhataya
Maine soncha mera dil aaya
Darwaza khol ker dekha to bijli ka bill aaaya

Juice peene ka maza cup mein nahin, glass mein hota hai
Greeting card dene ka maza gharwali ko nahin, saali ko hota hai

Tu mere dil mein aise samaayi hai
Jaise baajre ke khet mein bhains ghus aayi hai

Tumsa koi dusara zamin par ho to rab se shikayat hogi,
tumsa koi dusara zamin par ho to rabse shikayat hogi,
Ek to jhela nahi jata dusara aa gaya ye kam baat hogi.

Remaining will be updated soon.............