Wednesday, October 8, 2014

Java Serialization

 java provides a mechanism, called "Object Serialization".
where an object can be represented as a sequence of byte that includes the objects data as well as all information about the objects
type and the type of data stored in the object.

After serialized object has been written into a file; with extension .ser
object can be read from the file and deserialized back to get real data of object.

for this mechanism java provides two classes
1) ObjectOutputStream
2) ObjectInputStream
both are high level streams that contain the methods for serialization and deserialization an object.
public final void writeObject(Object x) throws IOException
above method is in ObjectOutputStream class.

public final Object readObject(Object x) throws IOException,ClassNotFoundException
above method is from ObjectInputStream which returns the Object type.

Notice: while performing this serialization and Deserialization
two conditions must be met:
1. The class must be implement the java.io.Serializable interface.
2. All of the fields in the class must be serializable. if a field is not serializable it must be marked as transient keyword.
 Sample Example:

1.Student.java

public class Student implements java.io.Serializable{
public String name;
public String Address;
public transient int Rollno;
public int seatno;
public void SeatnoCheck()
{
System.out.println("Exam mail Check by "+name+" "+seatno);
}

}
//********************* Serialization*********************
2.StudentDataSer .java
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;

public class StudentDataSer {
public static void main(String[] args) {
Student s = new Student();
s.name = "Sandy";
s.Address = "Nashik";
s.Rollno = 12;
s.seatno = 3245;
try {
FileOutputStream fileout = new FileOutputStream("E://Sandeep.ser");
ObjectOutputStream out = new ObjectOutputStream(fileout);
out.writeObject(s);
out.close();
fileout.close();
System.out
.println("Student data saved in file by serializing student object ");
} catch (IOException i) {
i.getMessage();
}
}

}
//********************* Deserialization**********************
3.StudentDataDeser.java

import java.io.FileInputStream;
import java.io.IOException;
import java.io.ObjectInputStream;

public class StudentDataDeser {
public static void main(String[] args) {
Student s = null;
try {
FileInputStream filein = new FileInputStream("E://Sandeep.ser");
ObjectInputStream in = new ObjectInputStream(filein);
s = (Student) in.readObject();
in.close();
filein.close();
} catch (IOException | ClassNotFoundException i) {
System.out.println("file not found to read");
i.printStackTrace();
return;
}
System.out.println("Desrealized file output is");
System.out.println("Student Name is " + s.name);
System.out.println("Student Address is " + s.Address);
System.out.println("Student Rollno is " + s.Rollno);
System.out.println("Student Exam Seat No is " + s.seatno);
}
}

out put when Deserialized:

Desrealized file output is
Student Name is Sandy
Student Address is Nashik
Student Rollno is 0
Student Exam Seat No is 3245

 
 

Wednesday, June 18, 2014

Android print document in WiFi

The Secret ............

Android Print document in Wifi its Future post........

Java print Simple report Document on JTextArea


package reportlast;
import java.awt.Color;
import java.awt.Container;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.BorderFactory;
import javax.swing.JApplet;
import javax.swing.JButton;
import javax.swing.JTextArea;
import javax.swing.border.Border;
/**
 *  @author icebreakersandy
 *  email: sndpdevhare10@gmail.com
 */
public class Testit extends JApplet implements ActionListener {
String[] colName = new String[] { "Date", "Account.No", "Description",
"Deposit", "Withdraw" };
String A[][] = {
{ "13/12/2013", "101", "AlphaSoft Infotek Ltd. Nashik", "3000", "0" },
{ "15/12/2013", "103", "Bank Ladger ", "5000", "0" } };
String[][] B = new String[3][5];
String[] K = new String[5];
Container c;
JTextArea outputArea;
JButton b;
public void init() {
c = getContentPane();
c.setLayout(new FlowLayout());
outputArea = new JTextArea(20, 80);
Border border = BorderFactory.createLineBorder(Color.RED);
outputArea.setBorder(BorderFactory.createCompoundBorder(border,BorderFactory.createEmptyBorder(10, 10, 10, 10)));
c.add(outputArea);
b = new JButton("Show Report");
b.addActionListener(this);
c.add(b);
}
public void actionPerformed(ActionEvent e) {
outputArea.setEditable(false);
outputArea.setFont(new Font("Times New Roman", Font.PLAIN, 14));
outputArea.setText(" ");
outputArea.append("ALPHASOFT -- BANK LADGER , REPORTS.\n\n");
// outputArea.append("Sr.No");
for (int j = 0; j < colName.length; j++) {
outputArea.append("\t" + colName[j]);
}
outputArea.append("\n");
for (int i = 0; i < A.length; i++) {
int colv = A[i].length;
String D = new String(" ");
// String D = "";
String Z[][] = A;
String Y[] = new String[5];
for (int ZX = 0; ZX < A[i].length; ZX++) {
Y[ZX] = A[i][ZX];
}
while (Y != null) {
System.out.println(Y[i]);
Z[i] = Y;
Y = null;
D = " ";
for (int nx = 0; nx < A[i].length; nx++) {
if (Z[i][nx].length() > 20) {
int stln = 20;
for (int zx = 20; zx > 0; zx--) {
char result = Z[i][nx].charAt(zx);
if (result == ' ') {
stln = zx + 1;
break;
}
}
D += rightpad(Z[i][nx].substring(0, stln), 20, "R");
Y[nx] = Z[i][nx].substring(stln);
} else {
D += rightpad(Z[i][nx], 20, "R");
Y[nx] = null;
}
}

outputArea.append(D + "\n");

}

}
}
public static String rightpad(String inp, int ln, String rl) {
String pd = "";
for (int nx = 0; nx < ln - inp.length(); nx++) {
pd += " ";
}
if (rl == "R") {
pd = inp + pd;
} else {

pd = pd + inp;
}

return pd;
}

}

Java Printing Simple Report Document on JTextArea.


package reportlast;

/**
 * @author icebreakersandy
 * e. sndpdevhare10@gmail.com
 */

import static reportlast.PrintFileToPrinter.myStyledText;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Container;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.font.LineBreakMeasurer;
import java.awt.font.TextLayout;
import java.awt.geom.Point2D;
import java.awt.print.PageFormat;
import java.awt.print.Printable;
import java.awt.print.PrinterException;
import java.text.AttributedCharacterIterator;
import java.util.Formatter;
import java.util.MissingFormatArgumentException;
import javax.swing.BorderFactory;
import javax.swing.JApplet;
import javax.swing.JButton;
import javax.swing.JPanel;
import javax.swing.JTextArea;
import javax.swing.border.Border;
public class MainReport extends JApplet implements ActionListener {
    String[] colName = new String[]{"Date", "Account.No", "Description", "Deposit", "Withdraw"};
    String a[][] = new String[][]{{"13/12/2013", "101", "AlphaSoftInfotekNashik", "3000", "0"},
    {"15/12/2013", "102", "Bank Ladger 2 xxxxxxxxxxxxx", "5000", "0"},
    {"16/12/2013", "103", "Accout Closing with Details", "800", "0"}};
    int[] pageBreaks;  // array of page break line positions.
    String[] No_of_Lines;
    StringBuilder sb = new StringBuilder();
    final String Header = "%s %85s%n%n%s %10s%n";
    final String format = "|%1$-30s|%2$-30s|%3$-30s|%4$-30s|%5$-35s";
    final String NumColF = "";
    String cformat = "%20s";
    String format1 = "%20s";
    Formatter fmt = new Formatter();
    String s1 = "%53s";//for spillover text
    String s2 = "%10s";
    int i, j, k;
    int Position = 0;
    boolean flag = false;
    boolean found;
    String a1 = "";
    String a2;
    Container c;
    JTextArea outputArea;
    public static final int LINES = 10;
    public static final int CHAR_PER_LINE = 40;
    JButton ShowRbtn;
    public void init() {
        c = getContentPane();
        c.setLayout(new FlowLayout());
        outputArea = new JTextArea(30, 60);
        outputArea.setLocation(400, 400);
        outputArea.setColumns(80);
        outputArea.setLineWrap(true);
        outputArea.setWrapStyleWord(true);
        outputArea.setEditable(false);
        Border border = BorderFactory.createLineBorder(Color.RED);
        outputArea.setBorder(BorderFactory.createCompoundBorder(border,
                BorderFactory.createEmptyBorder(10, 10, 10, 10)));
        JPanel p1 = new JPanel();
        JButton ShowRbtn = new JButton("Show Report");
        JButton printbtn = new JButton("Print");
        printbtn.addActionListener(new PrintButtonListener());
        c.add(outputArea, BorderLayout.CENTER);
        p1.add(printbtn, BorderLayout.CENTER);
        p1.add(ShowRbtn, BorderLayout.CENTER);
        ShowRbtn.addActionListener(this);
        c.add(p1, BorderLayout.SOUTH);
        this.setSize(1000, 600);//Applet Window size
    }
    public void actionPerformed(ActionEvent e) throws MissingFormatArgumentException {
        outputArea.setEditable(false);
        outputArea.setFont(new Font("Courier New", Font.PLAIN, 12));
        outputArea.append("\n\n");
        outputArea.setText(" ");
        outputArea.append(String.format("%80s %n%n", "NAME: ALPHASOFT INFOTEK LTD, Nashik."));
        outputArea.append(String.format("%67s  %n", "REPORTS  : Bank Ladger "));
        outputArea.append(String.format("%69s  %n", "ACCOUNTS : Sales Account "));
        outputArea.append(String.format("%77s  %n%n", "PERIOD   : 01/12/13  TO 30/12/13 "));
        outputArea.append("------------------------------------------------------------------------------------------------------------------");
        outputArea.append(String.format("%s %n", " "));
        outputArea.append(String.format("%-20s", "Date"));
        outputArea.append(String.format("%20s", "Account No"));
        outputArea.append(String.format("%27s", "Acount Details"));
        outputArea.append(String.format("%23s", "Deposit"));
        outputArea.append(String.format("%23s", "Withdraw"));
        outputArea.append(String.format("%s %n%n", " "));
        outputArea.append("------------------------------------------------------------------------------------------------------------------");
                for (i = 0; i < a.length; i++) {
            outputArea.append("\n");
            for (j = 0; j < a[i].length; j++) {
                int stln = 20;
                if (a[i][j].length() > 20) {
                    a1 = a[i][j].substring(0, 20);
                    flag = true;
                    Position = j;
                    outputArea.append(a1 + String.format(s2, ' '));
                    a2 = a[i][j].substring(20);
                }//end of if
                else {
                    outputArea.append(a[i][j] + String.format(cformat, ' '));
                }
            }//end of j loop
            if (flag == true) {
                outputArea.append(String.format("%n", ' '));
                flag = false;
                for (k = 0; k < a[i].length; k++) {
                    if (k == Position) {
                        outputArea.append(String.format(s1, ' ') + a2);
                    }
                }
            }
            outputArea.append("\n");
        }//end of i loop

    }//end of action performed method
//print button listener
    public class PrintButtonListener implements ActionListener {
        public void actionPerformed(ActionEvent event) {
           
            try{
                outputArea.print();
            }catch(PrinterException p)
            {
                System.out.println(p);
            }
           
       }
        class PaintCover implements Printable {

            public int print(Graphics g, PageFormat format, int pageIndex) throws PrinterException {
                Graphics2D graphics2d = (Graphics2D) g;
                graphics2d.translate(format.getImageableX(), format.getImageableY());
                /**
                 * Setting the text color*
                 */
                graphics2d.setPaint(Color.black);
                Point2D.Float pen = new Point2D.Float();
                AttributedCharacterIterator charIterator = myStyledText.getIterator();
                LineBreakMeasurer measurer = new LineBreakMeasurer(charIterator,
                        graphics2d.getFontRenderContext());
                float wrappingWidth = (float) format.getImageableWidth();
                while (measurer.getPosition() < charIterator.getEndIndex()) {
                    TextLayout layout = measurer.nextLayout(wrappingWidth);
                    pen.y += layout.getAscent();
                    float dx = layout.isLeftToRight() ? 0 : (wrappingWidth - layout
                            .getAdvance());
                    layout.draw(graphics2d, pen.x + dx, pen.y);
                    pen.y += layout.getDescent() + layout.getLeading();
                }
                return Printable.PAGE_EXISTS;
            }

        }
    }

    public static String rightpad(String inp, int ln, String rl) {
        String pd = "";
        for (int nx = 0; nx < ln - inp.length(); nx++) {
            pd += " ";
        }
        if (rl == "R") {
            pd = inp + pd;
        } else {

            pd = pd + inp;
        }

        return pd;
    }
}//end of class

Java Print file to Printer


package reportlast;
/**
 * @author icebreakersandy
 * e. sndpdevhare10@gmail.com
 */
import java.awt.*;
import java.awt.font.*;
import java.awt.geom.*;
import java.awt.print.*;
import java.io.BufferedReader;
import java.io.FileReader;
import java.text.*;
import static javax.management.Query.lt;
/**
 * Using JAVA to print simple text file to a printer
 */
public class PrintFileToPrinter implements Printable {
    static AttributedString myStyledText = null;
    public static void main(String args[]) {
        /**Location of a file to print**/
        String fileName = "D://Icebreakersandy//26-12-13//Header.txt";
      //  String fileName = "C:/Temp/abc.txt";
        /**Read the text content from this location **/
        String mText = readContentFromFileToPrint(fileName);
        /**Create an AttributedString object from the text read*/
        myStyledText = new AttributedString(mText);
        printToPrinter();
    }
    /**
     * This method reads the content of a text file.
     * The location of the file is provided in the parameter
     */
    private static String readContentFromFileToPrint(String fileName) {
        String dataToPrint = "";
        try {
            BufferedReader input = new BufferedReader(new FileReader(fileName));
            String line = "";
            /**Read the file and populate the data**/
            while ((line = input.readLine()) != null) {
                dataToPrint += line + "\n";
            }
        } catch (Exception e) {
            return dataToPrint;
        }
        return dataToPrint;
    }

    /**
     * Printing the data to a printer.
     * Initialization done in this method.
     */
    public static void printToPrinter() {
        /**
         * Get a Printer Job
         */
        PrinterJob printerJob = PrinterJob.getPrinterJob();

        /**
         * Create a book. A book contains a pair of page painters
         * called <span id="IL_AD4" class="IL_AD">printables</span>. Also you have different pageformats.
         */
        Book book = new Book();
        /**
         * Append the Printable Object (this one itself, as it
         * implements a printable interface) and the page format.
         */
        book.append(new PrintFileToPrinter(), new PageFormat());
        /**
         * Set the object to be printed (the Book) into the PrinterJob. Doing this
         * before bringing up the print dialog allows the print dialog to correctly
         * display the page range to be printed and to dissallow any print settings not
         * appropriate for the pages to be printed.
         */
        printerJob.setPageable(book);

        /**
         * Calling the printDialog will pop up <span id="IL_AD11" class="IL_AD">the Printing</span> Dialog.
         * If you want to print without user <span id="IL_AD10" class="IL_AD">confirmation</span>, you can directly call printerJob.print()
         *
         * doPrint will be false, if the user cancels the print operation.
         */
        boolean doPrint = printerJob.printDialog();

        if (doPrint) {
            try {
                printerJob.print();
            } catch (PrinterException ex) {
                System.err.println("Error occurred while trying to Print: "
                        + ex);
            }
        }
    }

    /**
     * This method comes from the Printable interface.
     * The method implementation in this class
     * prints a page of text.
     */
    public int print(Graphics g, PageFormat format, int pageIndex) {

        Graphics2D graphics2d = (Graphics2D) g;
        /**
         * Move the origin from the corner of the Paper to the corner of the imageable
         * area.
         */
        graphics2d.translate(format.getImageableX(), format.getImageableY());

        /** Setting the text color**/
        graphics2d.setPaint(Color.black);
        /**
         * Use a LineBreakMeasurer instance to break our text into lines that fit the
         * imageable area of the page.
         */
        Point2D.Float pen = new Point2D.Float();
        AttributedCharacterIterator charIterator = myStyledText.getIterator();
        LineBreakMeasurer measurer = new LineBreakMeasurer(charIterator,
                graphics2d.getFontRenderContext());
        float wrappingWidth = (float) format.getImageableWidth();
        while (measurer.getPosition()< charIterator.getEndIndex()) {
            TextLayout layout = measurer.nextLayout(wrappingWidth);
            pen.y += layout.getAscent();
            float dx = layout.isLeftToRight() ? 0 : (wrappingWidth - layout
                    .getAdvance());
            layout.draw(graphics2d, pen.x + dx, pen.y);
            pen.y += layout.getDescent() + layout.getLeading();
        }
        return Printable.PAGE_EXISTS;
    }

}