Friends,
Among bevy of mails I get regularly from different persons, today I find very useful information which I think I should share with you all.
This is about taking information from clipboard (when we copy any text, it goes to clipboard) and putting the text into web page. In out internet life, we sometimes copy the passwords, usernames from the local hard drives and paste those into the webpage we are accessing. Unknowingly, those copied password are stored into the clipboard.
Now the trick is that using java script, the clipboard data can be retrieved and can be shown in the webpage. In another way, it can be retrieved by hackers and he can use it and he can access your account even without letting you know.
The java script used to get the clipboard data is:
var content = clipboardData.getData("Text");
if (content!=null) {
document.write(content);
document.write("");
}
However, there is a way to prevent it. The provision is given in the Internet Options itself. If you want to prevent copying via script then follow the steps:
Go to internet options->security ……………. Press custom level …………In the security settings, select disable under Allow paste operations via script.
So Remember the text you last copied for pasting (copy & paste) can be stolen when you visit web sites using a combination of JavaScript and ASP (or PHP, or CGI) to write your possible sensitive data to a database on another server. Hopefully you haven't copied a credit card number recently before surfing!
Have a safe surfing and have a safe internet life.
Friday, March 6, 2009
HTML Parsing in JAVA
In this article, I will take you a ride of how we can make our power of JAVA useful for parsing the HTML pages. The API I am using to parse a HTML page is available with JDK 6 documentation. The link is as follows: http://java.sun.com/javase/6/docs/api/index.html?javax/swing/text/html/parser/Parser.html
Before moving into the details of the code, I will explain how it moves into parsing.
HTMLParser class extends HTMLEditorKit class of the javax.swing.text.html package. The class (HTMLParser) returns the parser to the Main Class which parses the content of URL. The URL content can be extracted using InputStreamReader class which takes the input in terms of HTTPURLConnection.
The Main Class calls the parse method which in turn calls the parser method of the HTMLEditorKit class, which will again call handleStartTag(), handleSimpleTag() etc method.
There are three classes I am using to parse the HTML page.
------------------------------------------------------------------------
package htmlparsing;
import javax.swing.text.html.HTMLEditorKit;
public class HTMLParser extends HTMLEditorKit {
public HTMLEditorKit.Parser getParser() {
return super.getParser();
}
}
------------------------------------------------------------------------
package htmlparsing;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import javax.swing.text.MutableAttributeSet;
import javax.swing.text.html.HTML;
import javax.swing.text.html.HTMLEditorKit;
public class HTMLParserCallback extends HTMLEditorKit.ParserCallback {
boolean flag = false;
public HTMLParserCallback() {
}
public void handleStartTag(HTML.Tag tag, MutableAttributeSet attributes, int position) {
if (tag == HTML.Tag.A) {
Object attribute = attributes.getAttribute(HTML.Attribute.HREF);
if (attribute != null) {
// Do Anything
}
}
}
public void handleEndTag(HTML.Tag tag, int position) {
if (tag == HTML.Tag.A) {
// Do Anything
}
}
public void handleSimpleTag(HTML.Tag tag, MutableAttributeSet attributes, int position) {
String entireInfo = new String("");
if (tag == HTML.Tag.IMG) {
Object attribute = attributes.getAttribute(HTML.Attribute.ALT);
if (attribute != null) {
// Do Anything
}
}
}
------------------------------------------------------------------------
package htmlparsing;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.Reader;
import java.net.URL;
import java.net.HttpURLConnection;
import javax.swing.text.html.HTMLEditorKit;
public class Main {
public static void main(String[] args) {
HTMLParser kit = new HTMLParser();
HTMLEditorKit.Parser parser = kit.getParser();
try {
URL url = new URL("http://www.javaworld.com");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
Reader reader = new InputStreamReader(connection.getInputStream());
HTMLEditorKit.ParserCallback callback = new HTMLParserCallback();
parser.parse(reader, callback, true);
reader.close();
} catch (Exception e) {
System.err.println(e);
}
}
}
Hope You all will find it useful. Any suggestion/feedback would be much appreciated.
Before moving into the details of the code, I will explain how it moves into parsing.
HTMLParser class extends HTMLEditorKit class of the javax.swing.text.html package. The class (HTMLParser) returns the parser to the Main Class which parses the content of URL. The URL content can be extracted using InputStreamReader class which takes the input in terms of HTTPURLConnection.
The Main Class calls the parse method which in turn calls the parser method of the HTMLEditorKit class, which will again call handleStartTag(), handleSimpleTag() etc method.
There are three classes I am using to parse the HTML page.
------------------------------------------------------------------------
package htmlparsing;
import javax.swing.text.html.HTMLEditorKit;
public class HTMLParser extends HTMLEditorKit {
public HTMLEditorKit.Parser getParser() {
return super.getParser();
}
}
------------------------------------------------------------------------
package htmlparsing;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import javax.swing.text.MutableAttributeSet;
import javax.swing.text.html.HTML;
import javax.swing.text.html.HTMLEditorKit;
public class HTMLParserCallback extends HTMLEditorKit.ParserCallback {
boolean flag = false;
public HTMLParserCallback() {
}
public void handleStartTag(HTML.Tag tag, MutableAttributeSet attributes, int position) {
if (tag == HTML.Tag.A) {
Object attribute = attributes.getAttribute(HTML.Attribute.HREF);
if (attribute != null) {
// Do Anything
}
}
}
public void handleEndTag(HTML.Tag tag, int position) {
if (tag == HTML.Tag.A) {
// Do Anything
}
}
public void handleSimpleTag(HTML.Tag tag, MutableAttributeSet attributes, int position) {
String entireInfo = new String("");
if (tag == HTML.Tag.IMG) {
Object attribute = attributes.getAttribute(HTML.Attribute.ALT);
if (attribute != null) {
// Do Anything
}
}
}
------------------------------------------------------------------------
package htmlparsing;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.Reader;
import java.net.URL;
import java.net.HttpURLConnection;
import javax.swing.text.html.HTMLEditorKit;
public class Main {
public static void main(String[] args) {
HTMLParser kit = new HTMLParser();
HTMLEditorKit.Parser parser = kit.getParser();
try {
URL url = new URL("http://www.javaworld.com");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
Reader reader = new InputStreamReader(connection.getInputStream());
HTMLEditorKit.ParserCallback callback = new HTMLParserCallback();
parser.parse(reader, callback, true);
reader.close();
} catch (Exception e) {
System.err.println(e);
}
}
}
Hope You all will find it useful. Any suggestion/feedback would be much appreciated.
Tuesday, March 3, 2009
Print Swing Components in JAVA
Few days back, I have been asked for an assignment from my workgroup that will print a swing component. This was really new task for me, as I have never experienced it.
After digging through the internet, I could easily find out that JDK 6 itself has the provision of printing the Swing components. The package that it deals with is the java.awt.print package. The documentation link for the above package is: http://java.sun.com/javase/6/docs/api/index.html?java/awt/print/package-summary.html
The source code I found is very straight forward to explain as it first creates simple java frame. The class you will be using should extend JFrame to make it a Swing Component and it should implement Printable class to make it a pointer (Not technical terms) to printable object.
The following line of code is the backbone for printing the Swing Components:
public void print() {
PrinterJob printJob = PrinterJob.getPrinterJob();
printJob.setPrintable(this);
if (printJob.printDialog())
try {
printJob.print();
} catch(PrinterException pe) {
System.out.println("Error printing: " + pe);
}
}
public int print(Graphics g, PageFormat pageFormat, int pageIndex) {
if (pageIndex > 0) {
return(NO_SUCH_PAGE);
} else {
Graphics2D g2d = (Graphics2D)g;
g2d.translate(pageFormat.getImageableX(), pageFormat.getImageableY());
disableDoubleBuffering(this);
this.paint(g2d);
enableDoubleBuffering(this);
return(PAGE_EXISTS);
}
}
The PrinterJob class is the principal class that controls printing. An application calls methods in this class to set up a job, optionally to invoke a print dialog with the user, and then to print the pages of the job.
The setPrintable() calls painter to render the pages. The pages in the document to be printed by this PrinterJob are rendered by the Printable object, painter.
Following is the whole set of code that first creates a Swing Component and then prints it.
package printswing;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.awt.geom.AffineTransform;
import java.awt.print.PageFormat;
import java.awt.print.PrinterException;
import java.awt.print.PrinterJob;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.RepaintManager;
import java.awt.*;
import javax.swing.*;
import java.awt.print.*;
import javax.swing.UIManager;
public class Main extends JFrame implements ActionListener,Printable{
/** Creates a new instance of PrintEntire */
public Main() {
super("An example of printing swing components");
setNativeLookAndFeel();
this.addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent we){
System.exit(0);
}
});
Container content = getContentPane();
JButton printButton = new JButton("Print");
printButton.setActionCommand("Print");
printButton.addActionListener(this);
JPanel buttonPanel = new JPanel();
buttonPanel.setBackground(Color.white);
buttonPanel.add(printButton);
content.add(buttonPanel, BorderLayout.SOUTH);
DrawingPanel drawingPanel = new DrawingPanel();
content.add(drawingPanel, BorderLayout.CENTER);
pack();
setVisible(true);
}
public void actionPerformed(ActionEvent ae){
if(ae.getActionCommand().equals("Print")){
this.print();
}
}
public static void setNativeLookAndFeel() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch(Exception e) {
System.out.println("Error setting native LAF: " + e);
}
}
public static void setJavaLookAndFeel() {
try {
UIManager.setLookAndFeel(UIManager.getCrossPlatformLookAndFeelClassName());
} catch(Exception e) {
System.out.println("Error setting Java LAF: " + e);
}
}
public static void setMotifLookAndFeel() {
try {
UIManager.setLookAndFeel("com.sun.java.swing.plaf.motif.MotifLookAndFeel");
} catch(Exception e) {
System.out.println("Error setting Motif LAF: " + e);
}
}
/** A simplified way to see a JPanel or other Container.
* Pops up a JFrame with specified Container as the content pane.
*/
public static JFrame openInJFrame(Container content,
int width,
int height,
String title,
Color bgColor) {
JFrame frame = new JFrame(title);
frame.setBackground(bgColor);
content.setBackground(bgColor);
frame.setSize(width, height);
frame.setContentPane(content);
frame.addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent we){
System.exit(0);
}
});
frame.setVisible(true);
return(frame);
}
/** Uses Color.white as the background color. */
public static JFrame openInJFrame(Container content,
int width,
int height,
String title) {
return(openInJFrame(content, width, height, title, Color.white));
}
/** Uses Color.white as the background color, and the
* name of the Container's class as the JFrame title.
*/
public static JFrame openInJFrame(Container content,
int width,
int height) {
return(openInJFrame(content, width, height,
content.getClass().getName(),
Color.white));
}
public void print() {
PrinterJob printJob = PrinterJob.getPrinterJob();
printJob.setPrintable(this);
if (printJob.printDialog())
try {
printJob.print();
} catch(PrinterException pe) {
System.out.println("Error printing: " + pe);
}
}
public int print(Graphics g, PageFormat pageFormat, int pageIndex) {
if (pageIndex > 0) {
return(NO_SUCH_PAGE);
} else {
Graphics2D g2d = (Graphics2D)g;
g2d.translate(pageFormat.getImageableX(), pageFormat.getImageableY());
disableDoubleBuffering(this);
this.paint(g2d);
enableDoubleBuffering(this);
return(PAGE_EXISTS);
}
}
public static void disableDoubleBuffering(Component c) {
RepaintManager currentManager = RepaintManager.currentManager(c);
currentManager.setDoubleBufferingEnabled(false);
}
public static void enableDoubleBuffering(Component c) {
RepaintManager currentManager = RepaintManager.currentManager(c);
currentManager.setDoubleBufferingEnabled(true);
}
public static void main(String args[]){
new Main();
}
class DrawingPanel extends JPanel {
private int fontSize = 90;
private String message = "Java 2D";
private int messageWidth;
public DrawingPanel() {
setBackground(Color.white);
Font font = new Font("Serif", Font.PLAIN, fontSize);
setFont(font);
FontMetrics metrics = getFontMetrics(font);
messageWidth = metrics.stringWidth(message);
int width = messageWidth*5/3;
int height = fontSize*3;
setPreferredSize(new Dimension(width, height));
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D)g;
int x = messageWidth/10;
int y = fontSize*5/2;
g2d.translate(x, y);
g2d.setPaint(Color.lightGray);
AffineTransform origTransform = g2d.getTransform();
g2d.shear(-0.95, 0);
g2d.scale(1, 3);
g2d.drawString(message, 0, 0);
g2d.setTransform(origTransform);
g2d.setPaint(Color.black);
g2d.drawString(message, 0, 0);
}
}
}
After digging through the internet, I could easily find out that JDK 6 itself has the provision of printing the Swing components. The package that it deals with is the java.awt.print package. The documentation link for the above package is: http://java.sun.com/javase/6/docs/api/index.html?java/awt/print/package-summary.html
The source code I found is very straight forward to explain as it first creates simple java frame. The class you will be using should extend JFrame to make it a Swing Component and it should implement Printable class to make it a pointer (Not technical terms) to printable object.
The following line of code is the backbone for printing the Swing Components:
public void print() {
PrinterJob printJob = PrinterJob.getPrinterJob();
printJob.setPrintable(this);
if (printJob.printDialog())
try {
printJob.print();
} catch(PrinterException pe) {
System.out.println("Error printing: " + pe);
}
}
public int print(Graphics g, PageFormat pageFormat, int pageIndex) {
if (pageIndex > 0) {
return(NO_SUCH_PAGE);
} else {
Graphics2D g2d = (Graphics2D)g;
g2d.translate(pageFormat.getImageableX(), pageFormat.getImageableY());
disableDoubleBuffering(this);
this.paint(g2d);
enableDoubleBuffering(this);
return(PAGE_EXISTS);
}
}
The PrinterJob class is the principal class that controls printing. An application calls methods in this class to set up a job, optionally to invoke a print dialog with the user, and then to print the pages of the job.
The setPrintable() calls painter to render the pages. The pages in the document to be printed by this PrinterJob are rendered by the Printable object, painter.
Following is the whole set of code that first creates a Swing Component and then prints it.
package printswing;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.awt.geom.AffineTransform;
import java.awt.print.PageFormat;
import java.awt.print.PrinterException;
import java.awt.print.PrinterJob;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.RepaintManager;
import java.awt.*;
import javax.swing.*;
import java.awt.print.*;
import javax.swing.UIManager;
public class Main extends JFrame implements ActionListener,Printable{
/** Creates a new instance of PrintEntire */
public Main() {
super("An example of printing swing components");
setNativeLookAndFeel();
this.addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent we){
System.exit(0);
}
});
Container content = getContentPane();
JButton printButton = new JButton("Print");
printButton.setActionCommand("Print");
printButton.addActionListener(this);
JPanel buttonPanel = new JPanel();
buttonPanel.setBackground(Color.white);
buttonPanel.add(printButton);
content.add(buttonPanel, BorderLayout.SOUTH);
DrawingPanel drawingPanel = new DrawingPanel();
content.add(drawingPanel, BorderLayout.CENTER);
pack();
setVisible(true);
}
public void actionPerformed(ActionEvent ae){
if(ae.getActionCommand().equals("Print")){
this.print();
}
}
public static void setNativeLookAndFeel() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch(Exception e) {
System.out.println("Error setting native LAF: " + e);
}
}
public static void setJavaLookAndFeel() {
try {
UIManager.setLookAndFeel(UIManager.getCrossPlatformLookAndFeelClassName());
} catch(Exception e) {
System.out.println("Error setting Java LAF: " + e);
}
}
public static void setMotifLookAndFeel() {
try {
UIManager.setLookAndFeel("com.sun.java.swing.plaf.motif.MotifLookAndFeel");
} catch(Exception e) {
System.out.println("Error setting Motif LAF: " + e);
}
}
/** A simplified way to see a JPanel or other Container.
* Pops up a JFrame with specified Container as the content pane.
*/
public static JFrame openInJFrame(Container content,
int width,
int height,
String title,
Color bgColor) {
JFrame frame = new JFrame(title);
frame.setBackground(bgColor);
content.setBackground(bgColor);
frame.setSize(width, height);
frame.setContentPane(content);
frame.addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent we){
System.exit(0);
}
});
frame.setVisible(true);
return(frame);
}
/** Uses Color.white as the background color. */
public static JFrame openInJFrame(Container content,
int width,
int height,
String title) {
return(openInJFrame(content, width, height, title, Color.white));
}
/** Uses Color.white as the background color, and the
* name of the Container's class as the JFrame title.
*/
public static JFrame openInJFrame(Container content,
int width,
int height) {
return(openInJFrame(content, width, height,
content.getClass().getName(),
Color.white));
}
public void print() {
PrinterJob printJob = PrinterJob.getPrinterJob();
printJob.setPrintable(this);
if (printJob.printDialog())
try {
printJob.print();
} catch(PrinterException pe) {
System.out.println("Error printing: " + pe);
}
}
public int print(Graphics g, PageFormat pageFormat, int pageIndex) {
if (pageIndex > 0) {
return(NO_SUCH_PAGE);
} else {
Graphics2D g2d = (Graphics2D)g;
g2d.translate(pageFormat.getImageableX(), pageFormat.getImageableY());
disableDoubleBuffering(this);
this.paint(g2d);
enableDoubleBuffering(this);
return(PAGE_EXISTS);
}
}
public static void disableDoubleBuffering(Component c) {
RepaintManager currentManager = RepaintManager.currentManager(c);
currentManager.setDoubleBufferingEnabled(false);
}
public static void enableDoubleBuffering(Component c) {
RepaintManager currentManager = RepaintManager.currentManager(c);
currentManager.setDoubleBufferingEnabled(true);
}
public static void main(String args[]){
new Main();
}
class DrawingPanel extends JPanel {
private int fontSize = 90;
private String message = "Java 2D";
private int messageWidth;
public DrawingPanel() {
setBackground(Color.white);
Font font = new Font("Serif", Font.PLAIN, fontSize);
setFont(font);
FontMetrics metrics = getFontMetrics(font);
messageWidth = metrics.stringWidth(message);
int width = messageWidth*5/3;
int height = fontSize*3;
setPreferredSize(new Dimension(width, height));
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D)g;
int x = messageWidth/10;
int y = fontSize*5/2;
g2d.translate(x, y);
g2d.setPaint(Color.lightGray);
AffineTransform origTransform = g2d.getTransform();
g2d.shear(-0.95, 0);
g2d.scale(1, 3);
g2d.drawString(message, 0, 0);
g2d.setTransform(origTransform);
g2d.setPaint(Color.black);
g2d.drawString(message, 0, 0);
}
}
}
Excel Chart Types through JAVA
On our way to explore things, we have acquainted with how we can make our customized excel sheet with simple java code. We have also dealt with the chart types that can make our excel sheet presentable.
In my earlier article, we have seen how we have engraved the data with a particular format with chart showing the data. The chart we have created is of line type.
However, there are ways to change the chart types. In the code that I have mentioned in the previous article, the chart type is set using the following line of chart.setChartType(GRChart.eChartLine);
The chart type we are using here is of Line type which shows the data in a line graphics. There are plenty of chart types which can be found in the java docs of the Jxcell. The chart type includes: GRChart.ChartArea,
eChartBar,
eChartBubble,
eChartColumn,
eChartCombination,
eChartDoughnut,
eChartLine,
eChartPie,
eChartScatter,
eChartStep.
The above chart types can be used extensively after providing suitable data.
There are plenty of other things that you can explore about the Jxcell API which is useful for editing/creating the excel application.
You can download the Jxcell API Docs from http://www.jxcell.net/jxcell.zip.
Hope you all will find it useful.
In my earlier article, we have seen how we have engraved the data with a particular format with chart showing the data. The chart we have created is of line type.
However, there are ways to change the chart types. In the code that I have mentioned in the previous article, the chart type is set using the following line of chart.setChartType(GRChart.eChartLine);
The chart type we are using here is of Line type which shows the data in a line graphics. There are plenty of chart types which can be found in the java docs of the Jxcell. The chart type includes: GRChart.ChartArea,
eChartBar,
eChartBubble,
eChartColumn,
eChartCombination,
eChartDoughnut,
eChartLine,
eChartPie,
eChartScatter,
eChartStep.
The above chart types can be used extensively after providing suitable data.
There are plenty of other things that you can explore about the Jxcell API which is useful for editing/creating the excel application.
You can download the Jxcell API Docs from http://www.jxcell.net/jxcell.zip.
Hope you all will find it useful.
Subscribe to:
Posts (Atom)