Thursday 8 August 2013

Difference between Abstarct class and Interface


Interface:

An interface in the Java programming language is an abstract type that is used to specify an interface (in the generic sense of the term) that classes must implement. Interfaces are declared using the interface keyword, and may only contain method signature and constant declarations (variable declarations that are declared to be both static and final). An interface may never contain method definitions.

Interfaces cannot be instantiated, but rather are implemented. A class that implements an interface must implement all of the methods described in the interface, or be an abstract class. Object references in Java may be specified to be of an interface type; in which case, they must either benull, or be bound to an object that implements the interface.

One benefit of using interfaces is that they simulate multiple inheritance. All classes in Java must have exactly one base class, the only exception being java.lang.Object (the root class of the Java type system); multiple inheritance of classes is not allowed.

A Java class may implement, and an interface may extend, any number of interfaces; however an interface may not implement an interface.



Abstract Class:

An abstract class is a class that is declared abstract—it may or may not include abstract methods. Abstract classes cannot be instantiated, but they can be subclassed.




Difference between  Interface and Abstract Class:

Interface
Abstract Class
A Java interface are implicitly abstract and cannot have implementations
A Java abstract class can have instance methods that implements a default behavior
Variables declared in a Java interface is by default final
An  abstract class may contain non-final variables
Members of a Java interface are public by default
A Java abstract class can have the usual flavors of class members like private, protected, etc
Java interface should be implemented using keyword “implements”
A Java abstract class should be extended using keyword “extends”
An interface can extend another Java interface only
An abstract class can extend another Java class and implement multiple Java interfaces
A Java class can implement multiple interfaces
A Java class can extend only one abstract class
Interface is absolutely abstract and cannot be instantiated
A Java abstract class also cannot be instantiated, but can be invoked if a main() exists




Note: In comparison with java abstract classes, java interfaces are slow as it requires extra indirection.


Help4J - Jar Search Engine. Easiest way to find jar and its source.

profile for Ashish Aggarwal at Stack Overflow, Q&A for professional and enthusiast programmers

Wednesday 31 July 2013

Convert Powerpoint slides to Images




Aspose provides us java liberary (called Aspose slides) to work with Microsoft  worddocument to insert content, retrieve content, export document into images. So lets talk about to convert .ppt and .pptx file to images(tiff format).

Here is the link from where we can download latest Aspose slides jar.
http://www.aspose.com/java/powerpoint-component.aspx
click on download button.

Generate images of .ppt/.pptx file


 public void generateImages(final String sourcePath) {  
      try {  
           PresentationEx presentationEx = getPresentationEx(sourcePath);  
           String imageFilePath = sourcePath + "_output_.tiff";  
           presentationEx.save(imageFilePath, SaveFormat.Tiff);  
      } catch (Exception e) {  
           e.printStackTrace();  
      }  
 }  


Help4J - Jar Search Engine. Easiest way to find jar and its source.

profile for Ashish Aggarwal on Stack Exchange, a network of free, community-driven Q&A sites

Convert Excel sheet to Images


Aspose provides us java liberary (called Aspose cells) to work with Microsoft excel document to insert content, retrieve content, export worksheet into images. So lets talk about to convert .xls adn .xlsx file to images(png, jpeg format).

Here is the link from where we can download latest Aspose cells jar.
http://www.aspose.com/java/excel-component.aspx
click on download button.

Generate images of .xls/.xlsx file


 public void generateImages(final String sourcePath) {  
     try {  
         Workbook workbook = new Workbook(sourcePath);  
         List<Worksheet> worksheets = getAllWorksheets(workbook);  
         if (worksheets != null) {  
             int noOfImages = 0;  
             for (Worksheet worksheet : worksheets) {  
                 if (worksheet.getCells().getCount() > 0 || worksheet.getCharts().getCount() > 0 || worksheet.getPictures().getCount() > 0) {  
                     String imageFilePath = sourcePath + "_output_" + (noOfImages++) + ".jpeg";   
                     SheetRender sr = new SheetRender(worksheet, getImageOrPrintOptions());  
                     sr.toImage(0, imageFilePath);  
                 }  
             }  
         }  
     } catch (Exception e) {  
         e.printStackTrace();  
     }  
 }  
 /**  
  * Returns all worksheets present in given workbook.  
  *   
  * @param workbook  
  * @return all worksheets present in given workbook.  
  */  
 private List<Worksheet> getAllWorksheets(final Workbook workbook) {  
     List<Worksheet> worksheets = new ArrayList<Worksheet>();  
     WorksheetCollection worksheetCollection = workbook.getWorksheets();  
     for (int i = 0; i < worksheetCollection.getCount(); i++) {  
         worksheets.add(worksheetCollection.get(i));  
     }  
     return worksheets;  
 }  
 /**  
  * Returns ImageOrPrintOptions for png images  
  *   
  * @return  
  */  
 private ImageOrPrintOptions getImageOrPrintOptions() {  
     ImageOrPrintOptions imgOptions = new ImageOrPrintOptions();  
     imgOptions.setImageFormat(ImageFormat.getJpeg());  
     imgOptions.setOnePagePerSheet(true);  
     return imgOptions;  
 }  



Generate images of all charts present in .xls/.xlsx file

 public void generateChartsAsImages(final String sourcePath) {  
     try {  
         Workbook workbook = new Workbook(sourcePath);;  
         List<Chart> charts = getAllCharts(workbook);  
         if (charts != null) {  
             int noOfImages = 0;  
             for (Chart chart : charts) {  
                 String imageFilePath = sourcePath + "_output_" + (noOfImages++) + ".jpeg";   
                 chart.toImage(imageFilePath, getImageOrPrintOptions());  
             }  
         }  
     } catch (Exception e) {  
         e.printStackTrace();  
     }  
 }  
 /**  
  * Returns all charts present in given workbook.  
  *   
  * @param workbook  
  * @return all charts present in given workbook.  
  */  
 private List<Chart> getAllCharts(final Workbook workbook) {  
     List<Chart> charts = new ArrayList<Chart>();  
     List<Worksheet> worksheets = getAllWorksheets(workbook);  
     for (Worksheet worksheet : worksheets) {  
         charts.addAll(getAllCharts(worksheet));  
     }  
     return charts;  
 }  
 /**  
  * Returns all charts present in given worksheet.  
  *   
  * @param worksheet  
  * @return all charts present in given worksheet.  
  */  
 private List<Chart> getAllCharts(final Worksheet worksheet) {  
     List<Chart> charts = new ArrayList<Chart>();  
     ChartCollection chartCollection = worksheet.getCharts();  
     for (int i = 0; i < chartCollection.getCount(); i++) {  
         charts.add(chartCollection.get(i));  
     }  
     return charts;  
 }  


Generate images of all pictures present in .xls/.xlsx file


 public void generatePicturesAsImages(final String sourcePath) {  
     try {  
         Workbook workbook = new Workbook(sourcePath);;  
         List<Picture> pictures = getAllPictures(workbook);  
         if (pictures != null) {  
             int noOfImages = 0;  
             for (Picture picture : pictures) {  
                 String imageFilePath = sourcePath + "_output_" + (noOfImages++) + ".jpeg";   
                 picture.toImage(imageFilePath, getImageOrPrintOptions());  
                 filePaths.add(imageFilePath);  
             }  
         }  
     } catch (Exception e) {  
         e.printStackTrace();  
     }  
 }  
 /**  
  * Returns all pictures present in given workbook.  
  *   
  * @param workbook  
  * @return all pictures present in given workbook.  
  */  
 private List<Picture> getAllPictures(final Workbook workbook) {  
     List<Picture> pictures = new ArrayList<Picture>();  
     List<Worksheet> worksheets = getAllWorksheets(workbook);  
     for (Worksheet worksheet : worksheets) {  
         pictures.addAll(getAllPictures(worksheet));  
     }  
     return pictures;  
 }  
 /**  
  * Returns all pictures present in given worksheet.  
  *   
  * @param worksheet  
  * @return all pictures present in given worksheet.  
  */  
 private List<Picture> getAllPictures(final Worksheet worksheet) {  
     List<Picture> pictures = new ArrayList<Picture>();  
     PictureCollection pictureCollection = worksheet.getPictures();  
     for (int i = 0; i < pictureCollection.getCount(); i++) {  
         pictures.add(pictureCollection.get(i));  
     }  
     return pictures;  
 }  


Generate images of all tables present in .xls/.xlsx file

 public void generateTablesAsImages(final String sourcePath) {  
     try {  
         Workbook workbook = new Workbook(sourcePath);;  
         Map<Worksheet, List<ListObject>> tablesByWokeSheet = getAllTables(workbook);  
         int noOfImages = 0;  
         for (Entry<Worksheet, List<ListObject>> entry : tablesByWokeSheet.entrySet()) {  
             for (ListObject table : entry.getValue()) {  
                 String imageFilePath = sourcePath + "_output_" + (noOfImages++) + ".jpeg";   
                 tableToImage(entry.getKey(), table, imageFilePath);  
             }  
         }  
     } catch (Exception e) {  
         e.printStackTrace();  
     }  
 }  
 /**  
  * Returns all tables present in given workbook.  
  *   
  * @param workbook  
  * @return all tables present in given workbook.  
  */  
 private Map<Worksheet, List<ListObject>> getAllTables(final Workbook workbook) {  
     Map<Worksheet, List<ListObject>> tables = new HashMap<Worksheet, List<ListObject>>();  
     List<Worksheet> worksheets = getAllWorksheets(workbook);  
     for (Worksheet worksheet : worksheets) {  
         tables.put(worksheet, getAllTables(worksheet));  
     }  
     return tables;  
 }  
 /**  
  * Returns all tables present in given worksheet.  
  *   
  * @param worksheet  
  * @return all tables present in given worksheet.  
  */  
 private List<ListObject> getAllTables(final Worksheet worksheet) {  
     List<ListObject> tables = new ArrayList<ListObject>();  
     ListObjectCollection listObjectCollection = worksheet.getListObjects();  
     for (int i = 0; i < listObjectCollection.getCount(); i++) {  
         tables.add(listObjectCollection.get(i));  
     }  
     return tables;  
 }  
 /**  
  * Convert excel entity table to image.  
  *   
  * @param worksheet  
  * @param table  
  * @param outPutFilePath  
  * @throws FileNotFoundException  
  * @throws Exception  
  */  
 private void tableToImage(final Worksheet worksheet, final ListObject table, final String outPutFilePath) throws FileNotFoundException, Exception {  
     Workbook workbook = createWorkBook(worksheet, table);  
     Worksheet sheet = workbook.getWorksheets().get(0);  
     ImageOrPrintOptions imageOrPrintOptions = getImageOrPrintOptions();  
     imageOrPrintOptions.setOnlyArea(true);  
     SheetRender sr = new SheetRender(sheet, imageOrPrintOptions);  
     sr.toImage(0, outPutFilePath);  
 }  
 /**  
  * Returns a new workbook having only single worksheet with a table representing the same content as present in the given table.  
  *   
  * @param worksheet  
  *      representing the excel file having actual content.  
  * @param listObject  
  *      worksheet table whose content has to copied in new workbook  
  * @return newly created workbook containing only table content.  
  * @throws Exception  
  */  
 private Workbook createWorkBook(final Worksheet worksheet, final ListObject listObject) throws Exception {  
     Workbook workbook = new Workbook();  
     // As this workbook is blank workbook so take cells of first worksheet of this workbook  
     Cells cells = workbook.getWorksheets().get(0).getCells();  
     Cells cellsTobeCopied = worksheet.getCells();  
     int totalNoOfRows = listObject.getEndRow() - listObject.getStartRow() + 1;  
     int totalNoOfColumns = listObject.getEndColumn() - listObject.getStartColumn() + 1;  
     cells.setStandardHeight(cellsTobeCopied.getStandardHeight());  
     cells.setStandardWidth(cellsTobeCopied.getStandardWidth());  
     // Set height of each row as the height of actual rows of table  
     for (int row = 0; row < totalNoOfRows; row++) {  
         cells.setRowHeight(row, cellsTobeCopied.getRowHeight(row));  
     }  
     // Set width of each column as the width of actual columns of table  
     for (int column = 0; column < totalNoOfColumns; column++) {  
         cells.setColumnWidth(column, cellsTobeCopied.getColumnWidth(column));  
     }  
     // Copy data of table from worksheet to newly created workbook cells  
     for (int row = 0; row < totalNoOfRows; row++) {  
         for (int column = 0; column < totalNoOfColumns; column++) {  
             Cell copiedFrom = worksheet.getCells().get(listObject.getStartRow() + row, listObject.getStartColumn() + column);  
             Cell copyTo = cells.get(row, column);  
             copyTo.setHtmlString(copiedFrom.getHtmlString());  
         }  
     }  
     // Create table in newly created workbook  
     ListObjectCollection tables = workbook.getWorksheets().get(0).getListObjects();  
     tables.add(0, 0, totalNoOfRows - 1, totalNoOfColumns - 1, listObject.getShowHeaderRow());  
     return workbook;  
 }  


Help4J - Jar Search Engine. Easiest way to find jar and its source.

profile for Ashish Aggarwal on Stack Exchange, a network of free, community-driven Q&A sites

Convert Word document to Images


Aspose provides us java liberary (called Aspose words) to work with Microsoft  worddocument to insert content, retrieve content, export document into images. So lets talk about to convert .doc and .docx file to images(png, jpeg format).

Here is the link from where we can download latest Aspose word jar.
http://www.aspose.com/java/word-component.aspx
click on download button.

Generate images of .doc/.docx file


 public void generateImages(final String sourcePath) {  
      try {  
           Document doc = new Document(sourcePath);  
           ImageSaveOptions options = new ImageSaveOptions(SaveFormat.JPEG);  
           options.setJpegQuality(100);  
           options.setResolution(100);  
           options.setUseHighQualityRendering(true);  
           for (int i = 0; i < doc.getPageCount(); i++) {  
                String imageFilePath = sourcePath + "_output_" + i + ".jpeg";  
                options.setPageIndex(i);  
                doc.save(imageFilePath, options);  
           }  
      } catch (Exception e) {  
           e.printStackTrace();  
      }  
 }  

Generate images of all pictures and charts present in .doc/.docx file

 public void generatePicturesAsImages(final String sourcePath) {  
      try {  
           Document doc = new Document(sourcePath);  
           ImageSaveOptions options = new ImageSaveOptions(SaveFormat.JPEG);  
           options.setJpegQuality(100);  
           options.setResolution(100);  
           options.setUseHighQualityRendering(true);  
           List<ShapeRenderer> pictures = getAllPictures(doc);  
           if (pictures != null) {  
                for (int i = 0; i < pictures.size(); i++) {  
                     ShapeRenderer picture = pictures.get(i);  
                     String imageFilePath = sourcePath + "_output_" + i + ".jpeg";  
                     picture.save(imageFilePath, options);  
                }  
           }  
      } catch (Exception e) {  
           e.printStackTrace();  
      }  
 }  
 private List<ShapeRenderer> getAllPictures(final Document document) throws Exception {  
      List<ShapeRenderer> images = null;  
      @SuppressWarnings("unchecked")  
      NodeCollection<DrawingML> nodeCollection = document.getChildNodes(NodeType.DRAWING_ML, Boolean.TRUE);  
      if (nodeCollection.getCount() > 0) {  
           images = new ArrayList<ShapeRenderer>();  
           for (DrawingML drawingML : nodeCollection) {  
                images.add(drawingML.getShapeRenderer());  
           }  
      }  
      return images;  
 } 


Generate images of all tables present in .doc/.docx file


 public void generateTablesAsImages(final String sourcePath) {  
      try {  
           Document doc = new Document(sourcePath);  
           ImageSaveOptions options = new ImageSaveOptions(SaveFormat.PNG);  
           options.setJpegQuality(100);  
           options.setResolution(100);  
           options.setUseHighQualityRendering(true);  
           options.setPaperColor(new Color(0, 0, 0, 0));  
           List<Table> tables = getAllTables(doc);  
           if (tables != null) {  
                int noOfImages = 0;  
                for (int i = 0; i < tables.size(); i++) {  
                     Table table = tables.get(i);  
                     String imageFilePath = sourcePath + "_output_" + i + ".png";  
                     saveTableAsImage(table, options, imageFilePath);  
                }  
           }  
      } catch (Exception e) {  
           e.printStackTrace();  
      }  
 }  
 private List<Table> getAllTables(final Document document) {  
      List<Table> tables = null;  
      @SuppressWarnings("unchecked")  
      NodeCollection<Table> nodeCollection = document.getChildNodes(NodeType.TABLE, Boolean.TRUE);  
      if (nodeCollection.getCount() > 0) {  
           tables = new ArrayList<Table>();  
           for (Table table : nodeCollection) {  
                tables.add(table);  
           }  
      }  
      return tables;  
 }  
 private void saveTableAsImage(final Table table, final ImageSaveOptions imageOptions, final String outputFile) throws Exception {  
      // There a bug which affects the cache of a cloned node. To avoid this we instead clone the entire document including all nodes,  
      // find the matching node in the cloned document and render that instead.  
      Document doc = ((Document) table.getDocument()).deepClone();  
      Node node = doc.getChild(NodeType.TABLE, table.getDocument().getChildNodes(NodeType.TABLE, true).indexOf(table), true);  
      Section parentSection = (Section) node.getAncestor(NodeType.SECTION);  
      // Create a temporary shape to store the target node in. This shape will be rendered to retrieve the rendered content of the node.  
      Shape shape = new Shape(doc, ShapeType.TEXT_BOX);  
      setShapeDefaultProperties(shape, parentSection);  
      // Add the node to the shape.  
      shape.appendChild(node.deepClone(true));  
      // We must add the shape to the document tree to have it rendered.  
      parentSection.getBody().getFirstParagraph().appendChild(shape);  
      shape.getShapeRenderer().save(outputFile, imageOptions);  
      BufferedImage renderedImage = ImageIO.read(new File(outputFile));  
      // Extract the actual content of the image by cropping transparent space around  
      // the rendered shape.  
      Rectangle cropRectangle = FindBoundingBoxAroundNode(renderedImage);  
      BufferedImage out = renderedImage.getSubimage(cropRectangle.x, cropRectangle.y, cropRectangle.width, cropRectangle.height);  
      File outputfile = new File(outputFile);  
      ImageIO.write(out, "png", outputfile);  
 }  
 private void setShapeDefaultProperties(final Shape shape, final Section section) {  
      // Assume that the node cannot be larger than the page in size.  
      shape.setWidth(section.getPageSetup().getPageWidth());  
      shape.setHeight(section.getPageSetup().getPageHeight());  
      // We must make the shape and paper color transparent.  
      shape.setFillColor(new Color(0, 0, 0, 0));  
      // Don't draw a surrounding line on the shape.  
      shape.setStroked(false);  
 }  
 private Rectangle FindBoundingBoxAroundNode(final BufferedImage originalBitmap) {  
      Point min = new Point(Integer.MAX_VALUE, Integer.MAX_VALUE);  
      Point max = new Point(Integer.MIN_VALUE, Integer.MIN_VALUE);  
      for (int x = 0; x < originalBitmap.getWidth(); ++x) {  
           for (int y = 0; y < originalBitmap.getHeight(); ++y) {  
                int argb = originalBitmap.getRGB(x, y);  
                if (argb != new Color(0, 0, 0, 0).getRGB()) {  
                     min.x = Math.min(x, min.x);  
                     min.y = Math.min(y, min.y);  
                     max.x = Math.max(x, max.x);  
                     max.y = Math.max(y, max.y);  
                }  
           }  
      }  
      return new Rectangle(min.x, min.y, max.x - min.x + 1, max.y - min.y + 1);  
 }  



Help4J - Jar Search Engine. Easiest way to find jar and its source.

profile for Ashish Aggarwal on Stack Exchange, a network of free, community-driven Q&A sites

Sunday 16 June 2013

Java: String to Document and Document to String Transformation

 package com.quark.aspose.utils;  
 import java.io.IOException;  
 import java.io.InputStream;  
 import java.io.StringReader;  
 import java.io.StringWriter;  
 import javax.xml.parsers.DocumentBuilder;  
 import javax.xml.parsers.DocumentBuilderFactory;  
 import javax.xml.parsers.ParserConfigurationException;  
 import javax.xml.transform.Transformer;  
 import javax.xml.transform.TransformerException;  
 import javax.xml.transform.TransformerFactory;  
 import javax.xml.transform.TransformerFactoryConfigurationError;  
 import javax.xml.transform.dom.DOMSource;  
 import javax.xml.transform.stream.StreamResult;  
 import org.w3c.dom.Document;  
 import org.xml.sax.InputSource;  
 import org.xml.sax.SAXException;  
 public class StringAndDocument { 
 
     public static Document createNewDocument() throws ParserConfigurationException {  
         DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();  
         DocumentBuilder builder = dbf.newDocumentBuilder();  
         return builder.newDocument();  
     }  


     /**  
      * Create Document Object from string formatted xmlcontent.  
      *   
      * @param xmlContent  
      *      , xml content in string format  
      * @return  
      * @throws SAXException  
      * @throws IOException  
      * @throws ParserConfigurationException  
      */  
     public static Document getDocumentFromString(final String xmlContent) throws SAXException, IOException, ParserConfigurationException {  
         DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();  
         return documentBuilderFactory.newDocumentBuilder().parse(new InputSource(new StringReader(xmlContent)));  
     }  


     /**  
      * Create Document Object from input stream having xmlcontent.  
      *   
      * @param xmlContent  
      *      , xml content in input stream  
      * @return  
      * @throws SAXException  
      * @throws IOException  
      * @throws ParserConfigurationException  
      */  
     public static Document getDocumentFromInputStream(final InputStream xmlContent) throws SAXException, IOException, ParserConfigurationException {  
         DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();  
         return documentBuilderFactory.newDocumentBuilder().parse(new InputSource(xmlContent));  
     }  


     /**  
      * Returns xml content present in document object in string format  
      *   
      * @param document  
      * @return  
      * @throws TransformerFactoryConfigurationError  
      * @throws TransformerException  
      */  
     public static String getStringFromDocument(final Document document) throws TransformerFactoryConfigurationError, TransformerException {  
         StringWriter sw = new StringWriter();  
         Transformer transformer = TransformerFactory.newInstance().newTransformer();  
         transformer.setOutputProperty("omit-xml-declaration", "no");  
         transformer.setOutputProperty("indent", "no");  
         transformer.setOutputProperty("encoding", "UTF_8");  
         transformer.transform(new DOMSource(document), new StreamResult(sw));  
         return sw.toString();  
     }  
 }  


Help4J - Jar Search Engine. Easiest way to find jar and its source.

Convert InputStream To String and String to InputStream in java

 package com.iandjava;  
 import java.io.BufferedReader;  
 import java.io.ByteArrayInputStream;  
 import java.io.IOException;  
 import java.io.InputStream;  
 import java.io.InputStreamReader;  
 public class InputStreamToStringExample {  
      public static void main(final String[] args) throws IOException {  
           String content = "I and JAVA";  
           InputStream inputStream = getInputStreamFromString(content);  
           String result = getStringFromInputStream(inputStream);  
           System.out.println(result);  
      }  
      // convert String into InputStream  
      public static InputStream getInputStreamFromString(final String input) {  
           InputStream is = new ByteArrayInputStream(input.getBytes());  
           return is;  
      }  
      // convert InputStream to String  
      public static String getStringFromInputStream(final InputStream is) throws IOException {  
           BufferedReader br = null;  
           StringBuilder sb = new StringBuilder();  
           String line;  
           try {  
                br = new BufferedReader(new InputStreamReader(is));  
                while ((line = br.readLine()) != null) {  
                     sb.append(line);  
                }  
           } finally {  
                if (br != null) {  
                     br.close();  
                }  
           }  
           return sb.toString();  
      }  
 }  
profile for Ashish Aggarwal on Stack Exchange, a network of free, community-driven Q&A sites