import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
//////////////////////////////////////////////////////////////// CombineName
public class CombineName extends JFrame {
//=================================================== instance variables
private JTextField _fNameTf = new JTextField(8);
private JTextField _lNameTf = new JTextField(8);
private JTextField _combinedNameTf = new JTextField(14);
//================================================================= main
public static void main(String[] args) {
JFrame window = new CombineName(); // Create window.
}
//========================================================== constructor
public CombineName() {
//... 1. Create or set attributes of components.
_combinedNameTf.setEditable(false); // Don't let user change output.
JButton combineBtn = new JButton("Combine");
//... 2. Add listener(s).
combineBtn.addActionListener(new CombineAction());
//... 3. Create a panel, set layout, and add components to it.
JPanel content = new JPanel();
content.setLayout(new FlowLayout());
content.add(new JLabel("First"));
content.add(_fNameTf);
content.add(new JLabel("Last"));
content.add(_lNameTf);
content.add(combineBtn);
content.add(new JLabel("Combined Name"));
content.add(_combinedNameTf);
//... 4. Set the content panel of window and perform layout.
this.setContentPane(content);
this.setTitle("CombineName Example");
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.pack(); // Do layout.
this.setLocationRelativeTo(null); // Center window.
this.setVisible(true);
}
///////////////////////////////////// inner listener class CombineAction
class CombineAction implements ActionListener {
public void actionPerformed(ActionEvent e) {
//... Get text from the text fields, combine, set text.
// Please make this program do something interesting.
String first = _fNameTf.getText();
String last = _lNameTf.getText();
String combined = last + ", " + first; // Trivial logic!!!
_combinedNameTf.setText(combined);
}
}
}Tuesday, 31 May 2011
combining two strings using java
Lower case to Upper case conversion in java
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
//////////////////////////////////////////////////////////////// ToUpperCase
public class ToUpperCase extends JApplet {
//=================================================== instance variables
private JTextField _inField = new JTextField(20);
private JTextField _outField = new JTextField(20);
//================================================================= main
public static void main(String[] args) {
JFrame window = new JFrame();
window.setTitle("ToUpperCase Example");
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//... JApplet works fine as content pane in a window!
window.setContentPane(new ToUpperCase());
window.pack(); // Layout components.
window.setLocationRelativeTo(null); // Center window.
window.setVisible(true);
}
//================================================== applet constructor
public ToUpperCase() {
//... Create or set attributes of components.
_outField.setEditable(false); // Don't let user change output.
JButton toUpperButton = new JButton("To Uppercase");
//... Add listener to button.
toUpperButton.addActionListener(new UpperCaseAction());
//... Add components directly to applet. Don't need content pane.
setLayout(new FlowLayout());
add(_inField);
add(toUpperButton);
add(_outField);
}
/////////////////////////////////// inner listener class UpperCaseAction
class UpperCaseAction implements ActionListener {
public void actionPerformed(ActionEvent e) {
//... Convert text in one textfield to uppercase in another.
String data = _inField.getText(); // Get the text
String out = data.toUpperCase(); // Create uppercase version.
_outField.setText(out); // Set output field
}
}
}Detecting Extension Filename in JAVA
import javax.swing.*;
public class FileExt {
public static void main(String[] args) {
//... Declare local variables.
String fileName; // The file name the user entered.
String extension; // The extension.
//... Input a file name and remove whitespace.
fileName = JOptionPane.showInputDialog(null, "Enter file name.");
fileName = fileName.trim();
//... Find the position of the last dot. Get extension.
int dotPos = fileName.lastIndexOf(".");
extension = fileName.substring(dotPos);
//... Output extension.
JOptionPane.showMessageDialog(null, "Extension is " + extension);
}
}Capitalizae charecters using java
import javax.swing.*;
public class Capitalize2 {
public static void main(String[] args) {
//.. Input a word
String inputWord = JOptionPane.showInputDialog(null, "Enter a word");
//.. Process - Separate word into parts, change case, put together.
String firstLetter = inputWord.substring(0,1); // Get first letter
String remainder = inputWord.substring(1); // Get remainder of word.
String capitalized = firstLetter.toUpperCase() + remainder.toLowerCase();
//.. Output the result.
JOptionPane.showMessageDialog(null, capitalized);
}
}Km to Miles conversion using swing
import javax.swing.*;
public class KmToMiles {
//============================================================ constants
private static final double MILES_PER_KILOMETER = 0.621;
//================================================================= main
public static void main(String[] args) { //Note 1
//... Local variables
String kmStr; // String km before conversion to double.
double km; // Number of kilometers.
double mi; // Number of miles.
//... Input
kmStr = JOptionPane.showInputDialog(null, "Enter kilometers.");
km = Double.parseDouble(kmStr);
//... Computation
mi = km * MILES_PER_KILOMETER;
//... Output
JOptionPane.showMessageDialog(null, km + " kilometers is " + mi + " miles.");
}
}
public class KmToMiles {
//============================================================ constants
private static final double MILES_PER_KILOMETER = 0.621;
//================================================================= main
public static void main(String[] args) { //Note 1
//... Local variables
String kmStr; // String km before conversion to double.
double km; // Number of kilometers.
double mi; // Number of miles.
//... Input
kmStr = JOptionPane.showInputDialog(null, "Enter kilometers.");
km = Double.parseDouble(kmStr);
//... Computation
mi = km * MILES_PER_KILOMETER;
//... Output
JOptionPane.showMessageDialog(null, km + " kilometers is " + mi + " miles.");
}
}
Sunday, 29 May 2011
Slide puzzle game in java
// SlidePuzzle.java - Puzzle to slide pieces to correct position.
// Fred Swartz, 2003-May, 2004-May
// The SlidePuzzle program consists of three files:
// SlidePuzzle.java - this file with main to create window.
// SlidePuzzleGUI.java - implements the GUI interface.
// SlidePuzzleModel.java - the logical functioning.
import javax.swing.JFrame;
///////////////////////////////////////////// class SlidePuzzle
class SlidePuzzle {
//============================================= method main
public static void main(String[] args) {
JFrame window = new JFrame("Slide Puzzle");
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
window.setContentPane(new SlidePuzzleGUI());
window.pack(); // finalize layout
window.show(); // make window visible
window.setResizable(false);
}//end main
}//endclass SlidePuzzle-------------------------------------------------
// SlidePuzzleGUI.java - GUI for SlidePuzzle
// Fred Swartz, 2003-May-10, 2004-May-3
//
// The SlidePuzzleGUI class creates a panel which
// contains two subpanels.
// 1. In the north is a subpanel for controls (just a button now).
// 2. In the center a graphics
// This needs a few improvements.
// Both the GUI and Model define the number or rows and columns.
// How would you set both from one place?
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
/////////////////////////////////////////////////// class SlidePuzzleGUI
// This class contains all the parts of the GUI interface
class SlidePuzzleGUI extends JPanel {
//=============================================== instance variables
private GraphicsPanel _puzzleGraphics;
private SlidePuzzleModel _puzzleModel = new SlidePuzzleModel();
//end instance variables
//====================================================== constructor
public SlidePuzzleGUI() {
//--- Create a button. Add a listener to it.
JButton newGameButton = new JButton("New Game");
newGameButton.addActionListener(new NewGameAction());
//--- Create control panel
JPanel controlPanel = new JPanel();
controlPanel.setLayout(new FlowLayout());
controlPanel.add(newGameButton);
//--- Create graphics panel
_puzzleGraphics = new GraphicsPanel();
//--- Set the layout and add the components
this.setLayout(new BorderLayout());
this.add(controlPanel, BorderLayout.NORTH);
this.add(_puzzleGraphics, BorderLayout.CENTER);
}//end constructor
//////////////////////////////////////////////// class GraphicsPanel
// This is defined inside the outer class so that
// it can use the outer class instance variables.
class GraphicsPanel extends JPanel implements MouseListener {
private static final int ROWS = 3;
private static final int COLS = 3;
private static final int CELL_SIZE = 80; // Pixels
private Font _biggerFont;
//================================================== constructor
public GraphicsPanel() {
_biggerFont = new Font("SansSerif", Font.BOLD, CELL_SIZE/2);
this.setPreferredSize(
new Dimension(CELL_SIZE * COLS, CELL_SIZE*ROWS));
this.setBackground(Color.black);
this.addMouseListener(this); // Listen own mouse events.
}//end constructor
//=======================================x method paintComponent
public void paintComponent(Graphics g) {
super.paintComponent(g);
for (int r=0; r<ROWS; r++) {
for (int c=0; c<COLS; c++) {
int x = c * CELL_SIZE;
int y = r * CELL_SIZE;
String text = _puzzleModel.getFace(r, c);
if (text != null) {
g.setColor(Color.gray);
g.fillRect(x+2, y+2, CELL_SIZE-4, CELL_SIZE-4);
g.setColor(Color.black);
g.setFont(_biggerFont);
g.drawString(text, x+20, y+(3*CELL_SIZE)/4);
}
}
}
}//end paintComponent
//======================================== listener mousePressed
public void mousePressed(MouseEvent e) {
//--- map x,y coordinates into a row and col.
int col = e.getX()/CELL_SIZE;
int row = e.getY()/CELL_SIZE;
if (!_puzzleModel.moveTile(row, col)) {
// moveTile moves tile if legal, else returns false.
Toolkit.getDefaultToolkit().beep();
}
this.repaint(); // Show any updates to model.
}//end mousePressed
//========================================== ignore these events
public void mouseClicked (MouseEvent e) {}
public void mouseReleased(MouseEvent e) {}
public void mouseEntered (MouseEvent e) {}
public void mouseExited (MouseEvent e) {}
}//end class GraphicsPanel
////////////////////////////////////////// inner class NewGameAction
public class NewGameAction implements ActionListener {
public void actionPerformed(ActionEvent e) {
_puzzleModel.reset();
_puzzleGraphics.repaint();
}
}//end inner class NewGameAction}//end class SlidePuzzleGUI
--------------------------------------------------------
// SlidePuzzleModel.java - Slide pieces to correct position.
// Fred Swartz, 2003-May-10
/////////////////////////////////////////// class SlidePuzzleModel
class SlidePuzzleModel {
private static final int ROWS = 3;
private static final int COLS = 3;
private Tile[][] _contents; // All tiles.
private Tile _emptyTile; // The empty space.
//================================================= constructor
public SlidePuzzleModel() {
_contents = new Tile[ROWS][COLS];
reset(); // Initialize and shuffle tiles.
}//end constructor
//===================================================== getFace
// Return the string to display at given row, col.
String getFace(int row, int col) {
return _contents[row][col].getFace();
}//end getFace
//======================================================= reset
// Initialize and shuffle the tiles.
public void reset() {
for (int r=0; r<ROWS; r++) {
for (int c=0; c<COLS; c++) {
_contents[r][c] = new Tile(r, c, "" + (r*COLS+c+1));
}
}
//--- Set last tile face to null to mark empty space
_emptyTile = _contents[ROWS-1][COLS-1];
_emptyTile.setFace(null);
//-- Shuffle - Exchange each tile with random tile.
for (int r=0; r<ROWS; r++) {
for (int c=0; c<COLS; c++) {
exchangeTiles(r, c, (int)(Math.random()*ROWS)
, (int)(Math.random()*COLS));
}
}
}//end reset
//==================================================== moveTile
// Move a tile to empty position beside it, if possible.
// Return true if it was moved, false if not legal.
public boolean moveTile(int r, int c) {
//--- It's a legal move if the empty cell is next to it.
return checkEmpty(r, c, -1, 0) || checkEmpty(r, c, 1, 0)
|| checkEmpty(r, c, 0, -1) || checkEmpty(r, c, 0, 1);
}//end moveTile
//================================================== checkEmpty
// Check to see if there is an empty position beside tile.
// Return true and exchange if possible, else return false.
private boolean checkEmpty(int r, int c, int rdelta, int cdelta) {
int rNeighbor = r + rdelta;
int cNeighbor = c + cdelta;
//--- Check to see if this neighbor is on board and is empty.
if (isLegalRowCol(rNeighbor, cNeighbor)
&& _contents[rNeighbor][cNeighbor] == _emptyTile) {
exchangeTiles(r, c, rNeighbor, cNeighbor);
return true;
}
return false;
}//end checkEmpty
//=============================================== isLegalRowCol
// Check for legal row, col
public boolean isLegalRowCol(int r, int c) {
return r>=0 && r<ROWS && c>=0 && c<COLS;
}//end isLegalRowCol
//=============================================== exchangeTiles
// Exchange two tiles.
private void exchangeTiles(int r1, int c1, int r2, int c2) {
Tile temp = _contents[r1][c1];
_contents[r1][c1] = _contents[r2][c2];
_contents[r2][c2] = temp;
}//end exchangeTiles
//=================================================== isGameOver
public boolean isGameOver() {
for (int r=0; r<ROWS; r++) {
for (int c=0; c<ROWS; c++) {
Tile trc = _contents[r][c];
return trc.isInFinalPosition(r, c);
}
}
//--- Falling thru loop means nothing out of place.
return true;
}//end isGameOver
}//end class SlidePuzzleModel
////////////////////////////////////////////////////////// class Tile
// Represents the individual "tiles" that slide in puzzle.
class Tile {
//============================================ instance variables
private int _row; // row of final position
private int _col; // col of final position
private String _face; // string to display
//end instance variables
//==================================================== constructor
public Tile(int row, int col, String face) {
_row = row;
_col = col;
_face = face;
}//end constructor
//======================================================== setFace
public void setFace(String newFace) {
_face = newFace;
}//end getFace
//======================================================== getFace
public String getFace() {
return _face;
}//end getFace
//=============================================== isInFinalPosition
public boolean isInFinalPosition(int r, int c) {
return r==_row && c==_col;
}//end isInFinalPosition
}//end class Tile
URL Searching using java
import java.awt.BorderLayout;
import java.awt.Cursor;
import java.awt.Font;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.BufferedReader;
import java.io.FileWriter;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JProgressBar;
import javax.swing.JScrollPane;
import javax.swing.JSeparator;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.table.DefaultTableModel;
// The Search Web Crawler
public class SearchCrawler extends JFrame {
// Max URLs drop-down values.
private static final String[] MAX_URLS = { "50", "100", "500", "1000" };
// Cache of robot disallow lists.
private HashMap disallowListCache = new HashMap();
// Search GUI controls.
private JTextField startTextField;
private JComboBox maxComboBox;
private JCheckBox limitCheckBox;
private JTextField logTextField;
private JTextField searchTextField;
private JCheckBox caseCheckBox;
private JButton searchButton;
// Search stats GUI controls.
private JLabel crawlingLabel2;
private JLabel crawledLabel2;
private JLabel toCrawlLabel2;
private JProgressBar progressBar;
private JLabel matchesLabel2;
// Table listing search matches.
private JTable table;
// Flag for whether or not crawling is underway.
private boolean crawling;
// Matches log file print writer.
private PrintWriter logFileWriter;
// Constructor for Search Web Crawler.
public SearchCrawler() {
// Set application title.
setTitle("Search Crawler");
// Set window size.
setSize(600, 600);
// Handle window closing events.
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
actionExit();
}
});
// Set up File menu.
JMenuBar menuBar = new JMenuBar();
JMenu fileMenu = new JMenu("File");
fileMenu.setMnemonic(KeyEvent.VK_F);
JMenuItem fileExitMenuItem = new JMenuItem("Exit", KeyEvent.VK_X);
fileExitMenuItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
actionExit();
}
});
fileMenu.add(fileExitMenuItem);
menuBar.add(fileMenu);
setJMenuBar(menuBar);
// Set up search panel.
JPanel searchPanel = new JPanel();
GridBagConstraints constraints;
GridBagLayout layout = new GridBagLayout();
searchPanel.setLayout(layout);
JLabel startLabel = new JLabel("Start URL:");
constraints = new GridBagConstraints();
constraints.anchor = GridBagConstraints.EAST;
constraints.insets = new Insets(5, 5, 0, 0);
layout.setConstraints(startLabel, constraints);
searchPanel.add(startLabel);
startTextField = new JTextField();
constraints = new GridBagConstraints();
constraints.fill = GridBagConstraints.HORIZONTAL;
constraints.gridwidth = GridBagConstraints.REMAINDER;
constraints.insets = new Insets(5, 5, 0, 5);
layout.setConstraints(startTextField, constraints);
searchPanel.add(startTextField);
JLabel maxLabel = new JLabel("Max URLs to Crawl:");
constraints = new GridBagConstraints();
constraints.anchor = GridBagConstraints.EAST;
constraints.insets = new Insets(5, 5, 0, 0);
layout.setConstraints(maxLabel, constraints);
searchPanel.add(maxLabel);
maxComboBox = new JComboBox(MAX_URLS);
maxComboBox.setEditable(true);
constraints = new GridBagConstraints();
constraints.insets = new Insets(5, 5, 0, 0);
layout.setConstraints(maxComboBox, constraints);
searchPanel.add(maxComboBox);
limitCheckBox = new JCheckBox("Limit crawling to Start URL site");
constraints = new GridBagConstraints();
constraints.anchor = GridBagConstraints.WEST;
constraints.insets = new Insets(0, 10, 0, 0);
layout.setConstraints(limitCheckBox, constraints);
searchPanel.add(limitCheckBox);
JLabel blankLabel = new JLabel();
constraints = new GridBagConstraints();
constraints.gridwidth = GridBagConstraints.REMAINDER;
layout.setConstraints(blankLabel, constraints);
searchPanel.add(blankLabel);
JLabel logLabel = new JLabel("Matches Log File:");
constraints = new GridBagConstraints();
constraints.anchor = GridBagConstraints.EAST;
constraints.insets = new Insets(5, 5, 0, 0);
layout.setConstraints(logLabel, constraints);
searchPanel.add(logLabel);
String file = System.getProperty("user.dir")
+ System.getProperty("file.separator") + "crawler.log";
logTextField = new JTextField(file);
constraints = new GridBagConstraints();
constraints.fill = GridBagConstraints.HORIZONTAL;
constraints.gridwidth = GridBagConstraints.REMAINDER;
constraints.insets = new Insets(5, 5, 0, 5);
layout.setConstraints(logTextField, constraints);
searchPanel.add(logTextField);
JLabel searchLabel = new JLabel("Search String:");
constraints = new GridBagConstraints();
constraints.anchor = GridBagConstraints.EAST;
constraints.insets = new Insets(5, 5, 0, 0);
layout.setConstraints(searchLabel, constraints);
searchPanel.add(searchLabel);
searchTextField = new JTextField();
constraints = new GridBagConstraints();
constraints.fill = GridBagConstraints.HORIZONTAL;
constraints.insets = new Insets(5, 5, 0, 0);
constraints.gridwidth = 2;
constraints.weightx = 1.0d;
layout.setConstraints(searchTextField, constraints);
searchPanel.add(searchTextField);
caseCheckBox = new JCheckBox("Case Sensitive");
constraints = new GridBagConstraints();
constraints.insets = new Insets(5, 5, 0, 5);
constraints.gridwidth = GridBagConstraints.REMAINDER;
layout.setConstraints(caseCheckBox, constraints);
searchPanel.add(caseCheckBox);
searchButton = new JButton("Search");
searchButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
actionSearch();
}
});
constraints = new GridBagConstraints();
constraints.gridwidth = GridBagConstraints.REMAINDER;
constraints.insets = new Insets(5, 5, 5, 5);
layout.setConstraints(searchButton, constraints);
searchPanel.add(searchButton);
JSeparator separator = new JSeparator();
constraints = new GridBagConstraints();
constraints.fill = GridBagConstraints.HORIZONTAL;
constraints.gridwidth = GridBagConstraints.REMAINDER;
constraints.insets = new Insets(5, 5, 5, 5);
layout.setConstraints(separator, constraints);
searchPanel.add(separator);
JLabel crawlingLabel1 = new JLabel("Crawling:");
constraints = new GridBagConstraints();
constraints.anchor = GridBagConstraints.EAST;
constraints.insets = new Insets(5, 5, 0, 0);
layout.setConstraints(crawlingLabel1, constraints);
searchPanel.add(crawlingLabel1);
crawlingLabel2 = new JLabel();
crawlingLabel2.setFont(crawlingLabel2.getFont().deriveFont(Font.PLAIN));
constraints = new GridBagConstraints();
constraints.fill = GridBagConstraints.HORIZONTAL;
constraints.gridwidth = GridBagConstraints.REMAINDER;
constraints.insets = new Insets(5, 5, 0, 5);
layout.setConstraints(crawlingLabel2, constraints);
searchPanel.add(crawlingLabel2);
JLabel crawledLabel1 = new JLabel("Crawled URLs:");
constraints = new GridBagConstraints();
constraints.anchor = GridBagConstraints.EAST;
constraints.insets = new Insets(5, 5, 0, 0);
layout.setConstraints(crawledLabel1, constraints);
searchPanel.add(crawledLabel1);
crawledLabel2 = new JLabel();
crawledLabel2.setFont(crawledLabel2.getFont().deriveFont(Font.PLAIN));
constraints = new GridBagConstraints();
constraints.fill = GridBagConstraints.HORIZONTAL;
constraints.gridwidth = GridBagConstraints.REMAINDER;
constraints.insets = new Insets(5, 5, 0, 5);
layout.setConstraints(crawledLabel2, constraints);
searchPanel.add(crawledLabel2);
JLabel toCrawlLabel1 = new JLabel("URLs to Crawl:");
constraints = new GridBagConstraints();
constraints.anchor = GridBagConstraints.EAST;
constraints.insets = new Insets(5, 5, 0, 0);
layout.setConstraints(toCrawlLabel1, constraints);
searchPanel.add(toCrawlLabel1);
toCrawlLabel2 = new JLabel();
toCrawlLabel2.setFont(toCrawlLabel2.getFont().deriveFont(Font.PLAIN));
constraints = new GridBagConstraints();
constraints.fill = GridBagConstraints.HORIZONTAL;
constraints.gridwidth = GridBagConstraints.REMAINDER;
constraints.insets = new Insets(5, 5, 0, 5);
layout.setConstraints(toCrawlLabel2, constraints);
searchPanel.add(toCrawlLabel2);
JLabel progressLabel = new JLabel("Crawling Progress:");
constraints = new GridBagConstraints();
constraints.anchor = GridBagConstraints.EAST;
constraints.insets = new Insets(5, 5, 0, 0);
layout.setConstraints(progressLabel, constraints);
searchPanel.add(progressLabel);
progressBar = new JProgressBar();
progressBar.setMinimum(0);
progressBar.setStringPainted(true);
constraints = new GridBagConstraints();
constraints.fill = GridBagConstraints.HORIZONTAL;
constraints.gridwidth = GridBagConstraints.REMAINDER;
constraints.insets = new Insets(5, 5, 0, 5);
layout.setConstraints(progressBar, constraints);
searchPanel.add(progressBar);
JLabel matchesLabel1 = new JLabel("Search Matches:");
constraints = new GridBagConstraints();
constraints.anchor = GridBagConstraints.EAST;
constraints.insets = new Insets(5, 5, 10, 0);
layout.setConstraints(matchesLabel1, constraints);
searchPanel.add(matchesLabel1);
matchesLabel2 = new JLabel();
matchesLabel2.setFont(matchesLabel2.getFont().deriveFont(Font.PLAIN));
constraints = new GridBagConstraints();
constraints.fill = GridBagConstraints.HORIZONTAL;
constraints.gridwidth = GridBagConstraints.REMAINDER;
constraints.insets = new Insets(5, 5, 10, 5);
layout.setConstraints(matchesLabel2, constraints);
searchPanel.add(matchesLabel2);
// Set up matches table.
table = new JTable(new DefaultTableModel(new Object[][] {},
new String[] { "URL" }) {
public boolean isCellEditable(int row, int column) {
return false;
}
});
// Set up Matches panel.
JPanel matchesPanel = new JPanel();
matchesPanel.setBorder(BorderFactory.createTitledBorder("Matches"));
matchesPanel.setLayout(new BorderLayout());
matchesPanel.add(new JScrollPane(table), BorderLayout.CENTER);
// Add panels to display.
getContentPane().setLayout(new BorderLayout());
getContentPane().add(searchPanel, BorderLayout.NORTH);
getContentPane().add(matchesPanel, BorderLayout.CENTER);
}
// Exit this program.
private void actionExit() {
System.exit(0);
}
// Handle Search/Stop button being clicked.
private void actionSearch() {
// If stop button clicked, turn crawling flag off.
if (crawling) {
crawling = false;
return;
}
ArrayList errorList = new ArrayList();
// Validate that start URL has been entered.
String startUrl = startTextField.getText().trim();
if (startUrl.length() < 1) {
errorList.add("Missing Start URL.");
}
// Verify start URL.
else if (verifyUrl(startUrl) == null) {
errorList.add("Invalid Start URL.");
}
// Validate that Max URLs is either empty or is a number.
int maxUrls = 0;
String max = ((String) maxComboBox.getSelectedItem()).trim();
if (max.length() > 0) {
try {
maxUrls = Integer.parseInt(max);
} catch (NumberFormatException e) {
}
if (maxUrls < 1) {
errorList.add("Invalid Max URLs value.");
}
}
// Validate that matches log file has been entered.
String logFile = logTextField.getText().trim();
if (logFile.length() < 1) {
errorList.add("Missing Matches Log File.");
}
// Validate that search string has been entered.
String searchString = searchTextField.getText().trim();
if (searchString.length() < 1) {
errorList.add("Missing Search String.");
}
// Show errors, if any, and return.
if (errorList.size() > 0) {
StringBuffer message = new StringBuffer();
// Concatenate errors into single message.
for (int i = 0; i < errorList.size(); i++) {
message.append(errorList.get(i));
if (i + 1 < errorList.size()) {
message.append("\n");
}
}
showError(message.toString());
return;
}
// Remove "www" from start URL if present.
startUrl = removeWwwFromUrl(startUrl);
// Start the Search Crawler.
search(logFile, startUrl, maxUrls, searchString);
}
private void search(final String logFile, final String startUrl,
final int maxUrls, final String searchString) {
// Start the search in a new thread.
Thread thread = new Thread(new Runnable() {
public void run() {
// Show hour glass cursor while crawling is under way.
setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
// Disable search controls.
startTextField.setEnabled(false);
maxComboBox.setEnabled(false);
limitCheckBox.setEnabled(false);
logTextField.setEnabled(false);
searchTextField.setEnabled(false);
caseCheckBox.setEnabled(false);
// Switch Search button to "Stop."
searchButton.setText("Stop");
// Reset stats.
table.setModel(new DefaultTableModel(new Object[][] {},
new String[] { "URL" }) {
public boolean isCellEditable(int row, int column) {
return false;
}
});
updateStats(startUrl, 0, 0, maxUrls);
// Open matches log file.
try {
logFileWriter = new PrintWriter(new FileWriter(logFile));
} catch (Exception e) {
showError("Unable to open matches log file.");
return;
}
// Turn crawling flag on.
crawling = true;
// Perform the actual crawling.
crawl(startUrl, maxUrls, limitCheckBox.isSelected(),
searchString, caseCheckBox.isSelected());
// Turn crawling flag off.
crawling = false;
// Close matches log file.
try {
logFileWriter.close();
} catch (Exception e) {
showError("Unable to close matches log file.");
}
// Mark search as done.
crawlingLabel2.setText("Done");
// Enable search controls.
startTextField.setEnabled(true);
maxComboBox.setEnabled(true);
limitCheckBox.setEnabled(true);
logTextField.setEnabled(true);
searchTextField.setEnabled(true);
caseCheckBox.setEnabled(true);
// Switch search button back to "Search."
searchButton.setText("Search");
// Return to default cursor.
setCursor(Cursor.getDefaultCursor());
// Show message if search string not found.
if (table.getRowCount() == 0) {
JOptionPane
.showMessageDialog(
SearchCrawler.this,
"Your Search String was not found. Please try another.",
"Search String Not Found",
JOptionPane.WARNING_MESSAGE);
}
}
});
thread.start();
}
// Show dialog box with error message.
private void showError(String message) {
JOptionPane.showMessageDialog(this, message, "Error",
JOptionPane.ERROR_MESSAGE);
}
// Update crawling stats.
private void updateStats(String crawling, int crawled, int toCrawl,
int maxUrls) {
crawlingLabel2.setText(crawling);
crawledLabel2.setText("" + crawled);
toCrawlLabel2.setText("" + toCrawl);
// Update progress bar.
if (maxUrls == -1) {
progressBar.setMaximum(crawled + toCrawl);
} else {
progressBar.setMaximum(maxUrls);
}
progressBar.setValue(crawled);
matchesLabel2.setText("" + table.getRowCount());
}
// Add match to matches table and log file.
private void addMatch(String url) {
// Add URL to matches table.
DefaultTableModel model = (DefaultTableModel) table.getModel();
model.addRow(new Object[] { url });
// Add URL to matches log file.
try {
logFileWriter.println(url);
} catch (Exception e) {
showError("Unable to log match.");
}
}
// Verify URL format.
private URL verifyUrl(String url) {
// Only allow HTTP URLs.
if (!url.toLowerCase().startsWith("http://"))
return null;
// Verify format of URL.
URL verifiedUrl = null;
try {
verifiedUrl = new URL(url);
} catch (Exception e) {
return null;
}
return verifiedUrl;
}
// Check if robot is allowed to access the given URL.
private boolean isRobotAllowed(URL urlToCheck) {
String host = urlToCheck.getHost().toLowerCase();
// Retrieve host's disallow list from cache.
ArrayList disallowList = (ArrayList) disallowListCache.get(host);
// If list is not in the cache, download and cache it.
if (disallowList == null) {
disallowList = new ArrayList();
try {
URL robotsFileUrl = new URL("http://" + host + "/robots.txt");
// Open connection to robot file URL for reading.
BufferedReader reader = new BufferedReader(
new InputStreamReader(robotsFileUrl.openStream()));
// Read robot file, creating list of disallowed paths.
String line;
while ((line = reader.readLine()) != null) {
if (line.indexOf("Disallow:") == 0) {
String disallowPath = line.substring("Disallow:"
.length());
// Check disallow path for comments and remove if
// present.
int commentIndex = disallowPath.indexOf("#");
if (commentIndex != -1) {
disallowPath = disallowPath.substring(0,
commentIndex);
}
// Remove leading or trailing spaces from disallow path.
disallowPath = disallowPath.trim();
// Add disallow path to list.
disallowList.add(disallowPath);
}
}
// Add new disallow list to cache.
disallowListCache.put(host, disallowList);
} catch (Exception e) {
/*
* Assume robot is allowed since an exception is thrown if the
* robot file doesn't exist.
*/
return true;
}
}
/*
* Loop through disallow list to see if crawling is allowed for the
* given URL.
*/
String file = urlToCheck.getFile();
for (int i = 0; i < disallowList.size(); i++) {
String disallow = (String) disallowList.get(i);
if (file.startsWith(disallow)) {
return false;
}
}
return true;
}
// Download page at given URL.
private String downloadPage(URL pageUrl) {
try {
// Open connection to URL for reading.
BufferedReader reader = new BufferedReader(new InputStreamReader(
pageUrl.openStream()));
// Read page into buffer.
String line;
StringBuffer pageBuffer = new StringBuffer();
while ((line = reader.readLine()) != null) {
pageBuffer.append(line);
}
return pageBuffer.toString();
} catch (Exception e) {
}
return null;
}
// Remove leading "www" from a URL's host if present.
private String removeWwwFromUrl(String url) {
int index = url.indexOf("://www.");
if (index != -1) {
return url.substring(0, index + 3) + url.substring(index + 7);
}
return (url);
}
// Parse through page contents and retrieve links.
private ArrayList retrieveLinks(URL pageUrl, String pageContents,
HashSet crawledList, boolean limitHost) {
// Compile link matching pattern.
Pattern p = Pattern.compile("<a\\s+href\\s*=\\s*\"?(.*?)[\" |>]",
Pattern.CASE_INSENSITIVE);
Matcher m = p.matcher(pageContents);
// Create list of link matches.
ArrayList linkList = new ArrayList();
while (m.find()) {
String link = m.group(1).trim();
// Skip empty links.
if (link.length() < 1) {
continue;
}
// Skip links that are just page anchors.
if (link.charAt(0) == '#') {
continue;
}
// Skip mailto links.
if (link.indexOf("mailto:") != -1) {
continue;
}
// Skip JavaScript links.
if (link.toLowerCase().indexOf("javascript") != -1) {
continue;
}
// Prefix absolute and relative URLs if necessary.
if (link.indexOf("://") == -1) {
// Handle absolute URLs.
if (link.charAt(0) == '/') {
link = "http://" + pageUrl.getHost() + link;
// Handle relative URLs.
} else {
String file = pageUrl.getFile();
if (file.indexOf('/') == -1) {
link = "http://" + pageUrl.getHost() + "/" + link;
} else {
String path = file.substring(0,
file.lastIndexOf('/') + 1);
link = "http://" + pageUrl.getHost() + path + link;
}
}
}
// Remove anchors from link.
int index = link.indexOf('#');
if (index != -1) {
link = link.substring(0, index);
}
// Remove leading "www" from URL's host if present.
link = removeWwwFromUrl(link);
// Verify link and skip if invalid.
URL verifiedLink = verifyUrl(link);
if (verifiedLink == null) {
continue;
}
/*
* If specified, limit links to those having the same host as the
* start URL.
*/
if (limitHost
&& !pageUrl.getHost().toLowerCase().equals(
verifiedLink.getHost().toLowerCase())) {
continue;
}
// Skip link if it has already been crawled.
if (crawledList.contains(link)) {
continue;
}
// Add link to list.
linkList.add(link);
}
return (linkList);
}
/*
* Determine whether or not search string is matched in the given page
* contents.
*/
private boolean searchStringMatches(String pageContents,
String searchString, boolean caseSensitive) {
String searchContents = pageContents;
/*
* If case-sensitive search, lowercase page contents for comparison.
*/
if (!caseSensitive) {
searchContents = pageContents.toLowerCase();
}
// Split search string into individual terms.
Pattern p = Pattern.compile("[\\s]+");
String[] terms = p.split(searchString);
// Check to see if each term matches.
for (int i = 0; i < terms.length; i++) {
if (caseSensitive) {
if (searchContents.indexOf(terms[i]) == -1) {
return false;
}
} else {
if (searchContents.indexOf(terms[i].toLowerCase()) == -1) {
return false;
}
}
}
return true;
}
// Perform the actual crawling, searching for the search string.
public void crawl(String startUrl, int maxUrls, boolean limitHost,
String searchString, boolean caseSensitive) {
// Set up crawl lists.
HashSet crawledList = new HashSet();
LinkedHashSet toCrawlList = new LinkedHashSet();
// Add start URL to the to crawl list.
toCrawlList.add(startUrl);
/*
* Perform actual crawling by looping through the To Crawl list.
*/
while (crawling && toCrawlList.size() > 0) {
/*
* Check to see if the max URL count has been reached, if it was
* specified.
*/
if (maxUrls != -1) {
if (crawledList.size() == maxUrls) {
break;
}
}
// Get URL at bottom of the list.
String url = (String) toCrawlList.iterator().next();
// Remove URL from the To Crawl list.
toCrawlList.remove(url);
// Convert string url to URL object.
URL verifiedUrl = verifyUrl(url);
// Skip URL if robots are not allowed to access it.
if (!isRobotAllowed(verifiedUrl)) {
continue;
}
// Update crawling stats.
updateStats(url, crawledList.size(), toCrawlList.size(), maxUrls);
// Add page to the crawled list.
crawledList.add(url);
// Download the page at the given URL.
String pageContents = downloadPage(verifiedUrl);
/*
* If the page was downloaded successfully, retrieve all its links
* and then see if it contains the search string.
*/
if (pageContents != null && pageContents.length() > 0) {
// Retrieve list of valid links from page.
ArrayList links = retrieveLinks(verifiedUrl, pageContents,
crawledList, limitHost);
// Add links to the To Crawl list.
toCrawlList.addAll(links);
/*
* Check if search string is present in page, and if so, record
* a match.
*/
if (searchStringMatches(pageContents, searchString,
caseSensitive)) {
addMatch(url);
}
}
// Update crawling stats.
updateStats(url, crawledList.size(), toCrawlList.size(), maxUrls);
}
}
// Run the Search Crawler.
public static void main(String[] args) {
SearchCrawler crawler = new SearchCrawler();
crawler.show();
}
}
/**
A quantifier determines how many times an expression is matched. The quantifiers are shown here:
+ Match one or more.
* Match zero or more.
? Match zero or one.
*/
/*
Character Sequence Explanation
<a Look for the characters "<a".
\\s+ Look for one or more space characters.
href Look for the characters "href".
\\s* Look for zero or more space characters.
= Look for the character "--".
\\s* Look for zero or more space characters.
\"? Look for zero or one quote character.
(.*?)Look for zero or more of any character until the next part of the pattern is matched, and place the results in a group.
[\">]Look for quote character or greater than (">") character.
*/
import java.awt.Cursor;
import java.awt.Font;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.BufferedReader;
import java.io.FileWriter;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JProgressBar;
import javax.swing.JScrollPane;
import javax.swing.JSeparator;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.table.DefaultTableModel;
// The Search Web Crawler
public class SearchCrawler extends JFrame {
// Max URLs drop-down values.
private static final String[] MAX_URLS = { "50", "100", "500", "1000" };
// Cache of robot disallow lists.
private HashMap disallowListCache = new HashMap();
// Search GUI controls.
private JTextField startTextField;
private JComboBox maxComboBox;
private JCheckBox limitCheckBox;
private JTextField logTextField;
private JTextField searchTextField;
private JCheckBox caseCheckBox;
private JButton searchButton;
// Search stats GUI controls.
private JLabel crawlingLabel2;
private JLabel crawledLabel2;
private JLabel toCrawlLabel2;
private JProgressBar progressBar;
private JLabel matchesLabel2;
// Table listing search matches.
private JTable table;
// Flag for whether or not crawling is underway.
private boolean crawling;
// Matches log file print writer.
private PrintWriter logFileWriter;
// Constructor for Search Web Crawler.
public SearchCrawler() {
// Set application title.
setTitle("Search Crawler");
// Set window size.
setSize(600, 600);
// Handle window closing events.
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
actionExit();
}
});
// Set up File menu.
JMenuBar menuBar = new JMenuBar();
JMenu fileMenu = new JMenu("File");
fileMenu.setMnemonic(KeyEvent.VK_F);
JMenuItem fileExitMenuItem = new JMenuItem("Exit", KeyEvent.VK_X);
fileExitMenuItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
actionExit();
}
});
fileMenu.add(fileExitMenuItem);
menuBar.add(fileMenu);
setJMenuBar(menuBar);
// Set up search panel.
JPanel searchPanel = new JPanel();
GridBagConstraints constraints;
GridBagLayout layout = new GridBagLayout();
searchPanel.setLayout(layout);
JLabel startLabel = new JLabel("Start URL:");
constraints = new GridBagConstraints();
constraints.anchor = GridBagConstraints.EAST;
constraints.insets = new Insets(5, 5, 0, 0);
layout.setConstraints(startLabel, constraints);
searchPanel.add(startLabel);
startTextField = new JTextField();
constraints = new GridBagConstraints();
constraints.fill = GridBagConstraints.HORIZONTAL;
constraints.gridwidth = GridBagConstraints.REMAINDER;
constraints.insets = new Insets(5, 5, 0, 5);
layout.setConstraints(startTextField, constraints);
searchPanel.add(startTextField);
JLabel maxLabel = new JLabel("Max URLs to Crawl:");
constraints = new GridBagConstraints();
constraints.anchor = GridBagConstraints.EAST;
constraints.insets = new Insets(5, 5, 0, 0);
layout.setConstraints(maxLabel, constraints);
searchPanel.add(maxLabel);
maxComboBox = new JComboBox(MAX_URLS);
maxComboBox.setEditable(true);
constraints = new GridBagConstraints();
constraints.insets = new Insets(5, 5, 0, 0);
layout.setConstraints(maxComboBox, constraints);
searchPanel.add(maxComboBox);
limitCheckBox = new JCheckBox("Limit crawling to Start URL site");
constraints = new GridBagConstraints();
constraints.anchor = GridBagConstraints.WEST;
constraints.insets = new Insets(0, 10, 0, 0);
layout.setConstraints(limitCheckBox, constraints);
searchPanel.add(limitCheckBox);
JLabel blankLabel = new JLabel();
constraints = new GridBagConstraints();
constraints.gridwidth = GridBagConstraints.REMAINDER;
layout.setConstraints(blankLabel, constraints);
searchPanel.add(blankLabel);
JLabel logLabel = new JLabel("Matches Log File:");
constraints = new GridBagConstraints();
constraints.anchor = GridBagConstraints.EAST;
constraints.insets = new Insets(5, 5, 0, 0);
layout.setConstraints(logLabel, constraints);
searchPanel.add(logLabel);
String file = System.getProperty("user.dir")
+ System.getProperty("file.separator") + "crawler.log";
logTextField = new JTextField(file);
constraints = new GridBagConstraints();
constraints.fill = GridBagConstraints.HORIZONTAL;
constraints.gridwidth = GridBagConstraints.REMAINDER;
constraints.insets = new Insets(5, 5, 0, 5);
layout.setConstraints(logTextField, constraints);
searchPanel.add(logTextField);
JLabel searchLabel = new JLabel("Search String:");
constraints = new GridBagConstraints();
constraints.anchor = GridBagConstraints.EAST;
constraints.insets = new Insets(5, 5, 0, 0);
layout.setConstraints(searchLabel, constraints);
searchPanel.add(searchLabel);
searchTextField = new JTextField();
constraints = new GridBagConstraints();
constraints.fill = GridBagConstraints.HORIZONTAL;
constraints.insets = new Insets(5, 5, 0, 0);
constraints.gridwidth = 2;
constraints.weightx = 1.0d;
layout.setConstraints(searchTextField, constraints);
searchPanel.add(searchTextField);
caseCheckBox = new JCheckBox("Case Sensitive");
constraints = new GridBagConstraints();
constraints.insets = new Insets(5, 5, 0, 5);
constraints.gridwidth = GridBagConstraints.REMAINDER;
layout.setConstraints(caseCheckBox, constraints);
searchPanel.add(caseCheckBox);
searchButton = new JButton("Search");
searchButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
actionSearch();
}
});
constraints = new GridBagConstraints();
constraints.gridwidth = GridBagConstraints.REMAINDER;
constraints.insets = new Insets(5, 5, 5, 5);
layout.setConstraints(searchButton, constraints);
searchPanel.add(searchButton);
JSeparator separator = new JSeparator();
constraints = new GridBagConstraints();
constraints.fill = GridBagConstraints.HORIZONTAL;
constraints.gridwidth = GridBagConstraints.REMAINDER;
constraints.insets = new Insets(5, 5, 5, 5);
layout.setConstraints(separator, constraints);
searchPanel.add(separator);
JLabel crawlingLabel1 = new JLabel("Crawling:");
constraints = new GridBagConstraints();
constraints.anchor = GridBagConstraints.EAST;
constraints.insets = new Insets(5, 5, 0, 0);
layout.setConstraints(crawlingLabel1, constraints);
searchPanel.add(crawlingLabel1);
crawlingLabel2 = new JLabel();
crawlingLabel2.setFont(crawlingLabel2.getFont().deriveFont(Font.PLAIN));
constraints = new GridBagConstraints();
constraints.fill = GridBagConstraints.HORIZONTAL;
constraints.gridwidth = GridBagConstraints.REMAINDER;
constraints.insets = new Insets(5, 5, 0, 5);
layout.setConstraints(crawlingLabel2, constraints);
searchPanel.add(crawlingLabel2);
JLabel crawledLabel1 = new JLabel("Crawled URLs:");
constraints = new GridBagConstraints();
constraints.anchor = GridBagConstraints.EAST;
constraints.insets = new Insets(5, 5, 0, 0);
layout.setConstraints(crawledLabel1, constraints);
searchPanel.add(crawledLabel1);
crawledLabel2 = new JLabel();
crawledLabel2.setFont(crawledLabel2.getFont().deriveFont(Font.PLAIN));
constraints = new GridBagConstraints();
constraints.fill = GridBagConstraints.HORIZONTAL;
constraints.gridwidth = GridBagConstraints.REMAINDER;
constraints.insets = new Insets(5, 5, 0, 5);
layout.setConstraints(crawledLabel2, constraints);
searchPanel.add(crawledLabel2);
JLabel toCrawlLabel1 = new JLabel("URLs to Crawl:");
constraints = new GridBagConstraints();
constraints.anchor = GridBagConstraints.EAST;
constraints.insets = new Insets(5, 5, 0, 0);
layout.setConstraints(toCrawlLabel1, constraints);
searchPanel.add(toCrawlLabel1);
toCrawlLabel2 = new JLabel();
toCrawlLabel2.setFont(toCrawlLabel2.getFont().deriveFont(Font.PLAIN));
constraints = new GridBagConstraints();
constraints.fill = GridBagConstraints.HORIZONTAL;
constraints.gridwidth = GridBagConstraints.REMAINDER;
constraints.insets = new Insets(5, 5, 0, 5);
layout.setConstraints(toCrawlLabel2, constraints);
searchPanel.add(toCrawlLabel2);
JLabel progressLabel = new JLabel("Crawling Progress:");
constraints = new GridBagConstraints();
constraints.anchor = GridBagConstraints.EAST;
constraints.insets = new Insets(5, 5, 0, 0);
layout.setConstraints(progressLabel, constraints);
searchPanel.add(progressLabel);
progressBar = new JProgressBar();
progressBar.setMinimum(0);
progressBar.setStringPainted(true);
constraints = new GridBagConstraints();
constraints.fill = GridBagConstraints.HORIZONTAL;
constraints.gridwidth = GridBagConstraints.REMAINDER;
constraints.insets = new Insets(5, 5, 0, 5);
layout.setConstraints(progressBar, constraints);
searchPanel.add(progressBar);
JLabel matchesLabel1 = new JLabel("Search Matches:");
constraints = new GridBagConstraints();
constraints.anchor = GridBagConstraints.EAST;
constraints.insets = new Insets(5, 5, 10, 0);
layout.setConstraints(matchesLabel1, constraints);
searchPanel.add(matchesLabel1);
matchesLabel2 = new JLabel();
matchesLabel2.setFont(matchesLabel2.getFont().deriveFont(Font.PLAIN));
constraints = new GridBagConstraints();
constraints.fill = GridBagConstraints.HORIZONTAL;
constraints.gridwidth = GridBagConstraints.REMAINDER;
constraints.insets = new Insets(5, 5, 10, 5);
layout.setConstraints(matchesLabel2, constraints);
searchPanel.add(matchesLabel2);
// Set up matches table.
table = new JTable(new DefaultTableModel(new Object[][] {},
new String[] { "URL" }) {
public boolean isCellEditable(int row, int column) {
return false;
}
});
// Set up Matches panel.
JPanel matchesPanel = new JPanel();
matchesPanel.setBorder(BorderFactory.createTitledBorder("Matches"));
matchesPanel.setLayout(new BorderLayout());
matchesPanel.add(new JScrollPane(table), BorderLayout.CENTER);
// Add panels to display.
getContentPane().setLayout(new BorderLayout());
getContentPane().add(searchPanel, BorderLayout.NORTH);
getContentPane().add(matchesPanel, BorderLayout.CENTER);
}
// Exit this program.
private void actionExit() {
System.exit(0);
}
// Handle Search/Stop button being clicked.
private void actionSearch() {
// If stop button clicked, turn crawling flag off.
if (crawling) {
crawling = false;
return;
}
ArrayList errorList = new ArrayList();
// Validate that start URL has been entered.
String startUrl = startTextField.getText().trim();
if (startUrl.length() < 1) {
errorList.add("Missing Start URL.");
}
// Verify start URL.
else if (verifyUrl(startUrl) == null) {
errorList.add("Invalid Start URL.");
}
// Validate that Max URLs is either empty or is a number.
int maxUrls = 0;
String max = ((String) maxComboBox.getSelectedItem()).trim();
if (max.length() > 0) {
try {
maxUrls = Integer.parseInt(max);
} catch (NumberFormatException e) {
}
if (maxUrls < 1) {
errorList.add("Invalid Max URLs value.");
}
}
// Validate that matches log file has been entered.
String logFile = logTextField.getText().trim();
if (logFile.length() < 1) {
errorList.add("Missing Matches Log File.");
}
// Validate that search string has been entered.
String searchString = searchTextField.getText().trim();
if (searchString.length() < 1) {
errorList.add("Missing Search String.");
}
// Show errors, if any, and return.
if (errorList.size() > 0) {
StringBuffer message = new StringBuffer();
// Concatenate errors into single message.
for (int i = 0; i < errorList.size(); i++) {
message.append(errorList.get(i));
if (i + 1 < errorList.size()) {
message.append("\n");
}
}
showError(message.toString());
return;
}
// Remove "www" from start URL if present.
startUrl = removeWwwFromUrl(startUrl);
// Start the Search Crawler.
search(logFile, startUrl, maxUrls, searchString);
}
private void search(final String logFile, final String startUrl,
final int maxUrls, final String searchString) {
// Start the search in a new thread.
Thread thread = new Thread(new Runnable() {
public void run() {
// Show hour glass cursor while crawling is under way.
setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
// Disable search controls.
startTextField.setEnabled(false);
maxComboBox.setEnabled(false);
limitCheckBox.setEnabled(false);
logTextField.setEnabled(false);
searchTextField.setEnabled(false);
caseCheckBox.setEnabled(false);
// Switch Search button to "Stop."
searchButton.setText("Stop");
// Reset stats.
table.setModel(new DefaultTableModel(new Object[][] {},
new String[] { "URL" }) {
public boolean isCellEditable(int row, int column) {
return false;
}
});
updateStats(startUrl, 0, 0, maxUrls);
// Open matches log file.
try {
logFileWriter = new PrintWriter(new FileWriter(logFile));
} catch (Exception e) {
showError("Unable to open matches log file.");
return;
}
// Turn crawling flag on.
crawling = true;
// Perform the actual crawling.
crawl(startUrl, maxUrls, limitCheckBox.isSelected(),
searchString, caseCheckBox.isSelected());
// Turn crawling flag off.
crawling = false;
// Close matches log file.
try {
logFileWriter.close();
} catch (Exception e) {
showError("Unable to close matches log file.");
}
// Mark search as done.
crawlingLabel2.setText("Done");
// Enable search controls.
startTextField.setEnabled(true);
maxComboBox.setEnabled(true);
limitCheckBox.setEnabled(true);
logTextField.setEnabled(true);
searchTextField.setEnabled(true);
caseCheckBox.setEnabled(true);
// Switch search button back to "Search."
searchButton.setText("Search");
// Return to default cursor.
setCursor(Cursor.getDefaultCursor());
// Show message if search string not found.
if (table.getRowCount() == 0) {
JOptionPane
.showMessageDialog(
SearchCrawler.this,
"Your Search String was not found. Please try another.",
"Search String Not Found",
JOptionPane.WARNING_MESSAGE);
}
}
});
thread.start();
}
// Show dialog box with error message.
private void showError(String message) {
JOptionPane.showMessageDialog(this, message, "Error",
JOptionPane.ERROR_MESSAGE);
}
// Update crawling stats.
private void updateStats(String crawling, int crawled, int toCrawl,
int maxUrls) {
crawlingLabel2.setText(crawling);
crawledLabel2.setText("" + crawled);
toCrawlLabel2.setText("" + toCrawl);
// Update progress bar.
if (maxUrls == -1) {
progressBar.setMaximum(crawled + toCrawl);
} else {
progressBar.setMaximum(maxUrls);
}
progressBar.setValue(crawled);
matchesLabel2.setText("" + table.getRowCount());
}
// Add match to matches table and log file.
private void addMatch(String url) {
// Add URL to matches table.
DefaultTableModel model = (DefaultTableModel) table.getModel();
model.addRow(new Object[] { url });
// Add URL to matches log file.
try {
logFileWriter.println(url);
} catch (Exception e) {
showError("Unable to log match.");
}
}
// Verify URL format.
private URL verifyUrl(String url) {
// Only allow HTTP URLs.
if (!url.toLowerCase().startsWith("http://"))
return null;
// Verify format of URL.
URL verifiedUrl = null;
try {
verifiedUrl = new URL(url);
} catch (Exception e) {
return null;
}
return verifiedUrl;
}
// Check if robot is allowed to access the given URL.
private boolean isRobotAllowed(URL urlToCheck) {
String host = urlToCheck.getHost().toLowerCase();
// Retrieve host's disallow list from cache.
ArrayList disallowList = (ArrayList) disallowListCache.get(host);
// If list is not in the cache, download and cache it.
if (disallowList == null) {
disallowList = new ArrayList();
try {
URL robotsFileUrl = new URL("http://" + host + "/robots.txt");
// Open connection to robot file URL for reading.
BufferedReader reader = new BufferedReader(
new InputStreamReader(robotsFileUrl.openStream()));
// Read robot file, creating list of disallowed paths.
String line;
while ((line = reader.readLine()) != null) {
if (line.indexOf("Disallow:") == 0) {
String disallowPath = line.substring("Disallow:"
.length());
// Check disallow path for comments and remove if
// present.
int commentIndex = disallowPath.indexOf("#");
if (commentIndex != -1) {
disallowPath = disallowPath.substring(0,
commentIndex);
}
// Remove leading or trailing spaces from disallow path.
disallowPath = disallowPath.trim();
// Add disallow path to list.
disallowList.add(disallowPath);
}
}
// Add new disallow list to cache.
disallowListCache.put(host, disallowList);
} catch (Exception e) {
/*
* Assume robot is allowed since an exception is thrown if the
* robot file doesn't exist.
*/
return true;
}
}
/*
* Loop through disallow list to see if crawling is allowed for the
* given URL.
*/
String file = urlToCheck.getFile();
for (int i = 0; i < disallowList.size(); i++) {
String disallow = (String) disallowList.get(i);
if (file.startsWith(disallow)) {
return false;
}
}
return true;
}
// Download page at given URL.
private String downloadPage(URL pageUrl) {
try {
// Open connection to URL for reading.
BufferedReader reader = new BufferedReader(new InputStreamReader(
pageUrl.openStream()));
// Read page into buffer.
String line;
StringBuffer pageBuffer = new StringBuffer();
while ((line = reader.readLine()) != null) {
pageBuffer.append(line);
}
return pageBuffer.toString();
} catch (Exception e) {
}
return null;
}
// Remove leading "www" from a URL's host if present.
private String removeWwwFromUrl(String url) {
int index = url.indexOf("://www.");
if (index != -1) {
return url.substring(0, index + 3) + url.substring(index + 7);
}
return (url);
}
// Parse through page contents and retrieve links.
private ArrayList retrieveLinks(URL pageUrl, String pageContents,
HashSet crawledList, boolean limitHost) {
// Compile link matching pattern.
Pattern p = Pattern.compile("<a\\s+href\\s*=\\s*\"?(.*?)[\" |>]",
Pattern.CASE_INSENSITIVE);
Matcher m = p.matcher(pageContents);
// Create list of link matches.
ArrayList linkList = new ArrayList();
while (m.find()) {
String link = m.group(1).trim();
// Skip empty links.
if (link.length() < 1) {
continue;
}
// Skip links that are just page anchors.
if (link.charAt(0) == '#') {
continue;
}
// Skip mailto links.
if (link.indexOf("mailto:") != -1) {
continue;
}
// Skip JavaScript links.
if (link.toLowerCase().indexOf("javascript") != -1) {
continue;
}
// Prefix absolute and relative URLs if necessary.
if (link.indexOf("://") == -1) {
// Handle absolute URLs.
if (link.charAt(0) == '/') {
link = "http://" + pageUrl.getHost() + link;
// Handle relative URLs.
} else {
String file = pageUrl.getFile();
if (file.indexOf('/') == -1) {
link = "http://" + pageUrl.getHost() + "/" + link;
} else {
String path = file.substring(0,
file.lastIndexOf('/') + 1);
link = "http://" + pageUrl.getHost() + path + link;
}
}
}
// Remove anchors from link.
int index = link.indexOf('#');
if (index != -1) {
link = link.substring(0, index);
}
// Remove leading "www" from URL's host if present.
link = removeWwwFromUrl(link);
// Verify link and skip if invalid.
URL verifiedLink = verifyUrl(link);
if (verifiedLink == null) {
continue;
}
/*
* If specified, limit links to those having the same host as the
* start URL.
*/
if (limitHost
&& !pageUrl.getHost().toLowerCase().equals(
verifiedLink.getHost().toLowerCase())) {
continue;
}
// Skip link if it has already been crawled.
if (crawledList.contains(link)) {
continue;
}
// Add link to list.
linkList.add(link);
}
return (linkList);
}
/*
* Determine whether or not search string is matched in the given page
* contents.
*/
private boolean searchStringMatches(String pageContents,
String searchString, boolean caseSensitive) {
String searchContents = pageContents;
/*
* If case-sensitive search, lowercase page contents for comparison.
*/
if (!caseSensitive) {
searchContents = pageContents.toLowerCase();
}
// Split search string into individual terms.
Pattern p = Pattern.compile("[\\s]+");
String[] terms = p.split(searchString);
// Check to see if each term matches.
for (int i = 0; i < terms.length; i++) {
if (caseSensitive) {
if (searchContents.indexOf(terms[i]) == -1) {
return false;
}
} else {
if (searchContents.indexOf(terms[i].toLowerCase()) == -1) {
return false;
}
}
}
return true;
}
// Perform the actual crawling, searching for the search string.
public void crawl(String startUrl, int maxUrls, boolean limitHost,
String searchString, boolean caseSensitive) {
// Set up crawl lists.
HashSet crawledList = new HashSet();
LinkedHashSet toCrawlList = new LinkedHashSet();
// Add start URL to the to crawl list.
toCrawlList.add(startUrl);
/*
* Perform actual crawling by looping through the To Crawl list.
*/
while (crawling && toCrawlList.size() > 0) {
/*
* Check to see if the max URL count has been reached, if it was
* specified.
*/
if (maxUrls != -1) {
if (crawledList.size() == maxUrls) {
break;
}
}
// Get URL at bottom of the list.
String url = (String) toCrawlList.iterator().next();
// Remove URL from the To Crawl list.
toCrawlList.remove(url);
// Convert string url to URL object.
URL verifiedUrl = verifyUrl(url);
// Skip URL if robots are not allowed to access it.
if (!isRobotAllowed(verifiedUrl)) {
continue;
}
// Update crawling stats.
updateStats(url, crawledList.size(), toCrawlList.size(), maxUrls);
// Add page to the crawled list.
crawledList.add(url);
// Download the page at the given URL.
String pageContents = downloadPage(verifiedUrl);
/*
* If the page was downloaded successfully, retrieve all its links
* and then see if it contains the search string.
*/
if (pageContents != null && pageContents.length() > 0) {
// Retrieve list of valid links from page.
ArrayList links = retrieveLinks(verifiedUrl, pageContents,
crawledList, limitHost);
// Add links to the To Crawl list.
toCrawlList.addAll(links);
/*
* Check if search string is present in page, and if so, record
* a match.
*/
if (searchStringMatches(pageContents, searchString,
caseSensitive)) {
addMatch(url);
}
}
// Update crawling stats.
updateStats(url, crawledList.size(), toCrawlList.size(), maxUrls);
}
}
// Run the Search Crawler.
public static void main(String[] args) {
SearchCrawler crawler = new SearchCrawler();
crawler.show();
}
}
/**
A quantifier determines how many times an expression is matched. The quantifiers are shown here:
+ Match one or more.
* Match zero or more.
? Match zero or one.
*/
/*
Character Sequence Explanation
<a Look for the characters "<a".
\\s+ Look for one or more space characters.
href Look for the characters "href".
\\s* Look for zero or more space characters.
= Look for the character "--".
\\s* Look for zero or more space characters.
\"? Look for zero or one quote character.
(.*?)Look for zero or more of any character until the next part of the pattern is matched, and place the results in a group.
[\">]Look for quote character or greater than (">") character.
*/
Message Digest SHA-1 and MD5 in JAVA
import java.awt.Container;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import javax.swing.ButtonGroup;
import javax.swing.JCheckBox;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
public class MessageDigestTest {
public static void main(String[] args) {
JFrame f = new MessageDigestFrame();
f.show();
}
}
class MessageDigestFrame extends JFrame {
public MessageDigestFrame() {
setTitle("MessageDigestTest");
setSize(400, 200);
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
JPanel panel = new JPanel();
ButtonGroup group = new ButtonGroup();
ActionListener listener = new ActionListener() {
public void actionPerformed(ActionEvent event) {
JCheckBox b = (JCheckBox) event.getSource();
setAlgorithm(b.getText());
}
};
addCheckBox(panel, "SHA-1", group, true, listener);
addCheckBox(panel, "MD5", group, false, listener);
Container contentPane = getContentPane();
contentPane.add(panel, "North");
contentPane.add(new JScrollPane(message), "Center");
contentPane.add(digest, "South");
digest.setFont(new Font("Monospaced", Font.PLAIN, 12));
setAlgorithm("SHA-1");
JMenuBar menuBar = new JMenuBar();
JMenu menu = new JMenu("File");
JMenuItem fileDigestItem = new JMenuItem("File digest");
fileDigestItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
loadFile();
}
});
menu.add(fileDigestItem);
JMenuItem textDigestItem = new JMenuItem("Text area digest");
textDigestItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
String m = message.getText();
computeDigest(m.getBytes());
}
});
menu.add(textDigestItem);
menuBar.add(menu);
setJMenuBar(menuBar);
}
public void addCheckBox(Container c, String name, ButtonGroup g,
boolean selected, ActionListener listener) {
JCheckBox b = new JCheckBox(name, selected);
c.add(b);
g.add(b);
b.addActionListener(listener);
}
public void setAlgorithm(String alg) {
try {
currentAlgorithm = MessageDigest.getInstance(alg);
digest.setText("");
} catch (NoSuchAlgorithmException e) {
digest.setText("" + e);
}
}
public void loadFile() {
JFileChooser chooser = new JFileChooser();
chooser.setCurrentDirectory(new File("."));
int r = chooser.showOpenDialog(this);
if (r == JFileChooser.APPROVE_OPTION) {
String name = chooser.getSelectedFile().getAbsolutePath();
computeDigest(loadBytes(name));
}
}
public byte[] loadBytes(String name) {
FileInputStream in = null;
try {
in = new FileInputStream(name);
ByteArrayOutputStream buffer = new ByteArrayOutputStream();
int ch;
while ((ch = in.read()) != -1)
buffer.write(ch);
return buffer.toByteArray();
} catch (IOException e) {
if (in != null) {
try {
in.close();
} catch (IOException e2) {
}
}
return null;
}
}
public void computeDigest(byte[] b) {
currentAlgorithm.reset();
currentAlgorithm.update(b);
byte[] hash = currentAlgorithm.digest();
String d = "";
for (int i = 0; i < hash.length; i++) {
int v = hash[i] & 0xFF;
if (v < 16)
d += "0";
d += Integer.toString(v, 16).toUpperCase() + " ";
}
digest.setText(d);
}
private JTextArea message = new JTextArea();
private JTextField digest = new JTextField();
private MessageDigest currentAlgorithm;
}
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import javax.swing.ButtonGroup;
import javax.swing.JCheckBox;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
public class MessageDigestTest {
public static void main(String[] args) {
JFrame f = new MessageDigestFrame();
f.show();
}
}
class MessageDigestFrame extends JFrame {
public MessageDigestFrame() {
setTitle("MessageDigestTest");
setSize(400, 200);
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
JPanel panel = new JPanel();
ButtonGroup group = new ButtonGroup();
ActionListener listener = new ActionListener() {
public void actionPerformed(ActionEvent event) {
JCheckBox b = (JCheckBox) event.getSource();
setAlgorithm(b.getText());
}
};
addCheckBox(panel, "SHA-1", group, true, listener);
addCheckBox(panel, "MD5", group, false, listener);
Container contentPane = getContentPane();
contentPane.add(panel, "North");
contentPane.add(new JScrollPane(message), "Center");
contentPane.add(digest, "South");
digest.setFont(new Font("Monospaced", Font.PLAIN, 12));
setAlgorithm("SHA-1");
JMenuBar menuBar = new JMenuBar();
JMenu menu = new JMenu("File");
JMenuItem fileDigestItem = new JMenuItem("File digest");
fileDigestItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
loadFile();
}
});
menu.add(fileDigestItem);
JMenuItem textDigestItem = new JMenuItem("Text area digest");
textDigestItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
String m = message.getText();
computeDigest(m.getBytes());
}
});
menu.add(textDigestItem);
menuBar.add(menu);
setJMenuBar(menuBar);
}
public void addCheckBox(Container c, String name, ButtonGroup g,
boolean selected, ActionListener listener) {
JCheckBox b = new JCheckBox(name, selected);
c.add(b);
g.add(b);
b.addActionListener(listener);
}
public void setAlgorithm(String alg) {
try {
currentAlgorithm = MessageDigest.getInstance(alg);
digest.setText("");
} catch (NoSuchAlgorithmException e) {
digest.setText("" + e);
}
}
public void loadFile() {
JFileChooser chooser = new JFileChooser();
chooser.setCurrentDirectory(new File("."));
int r = chooser.showOpenDialog(this);
if (r == JFileChooser.APPROVE_OPTION) {
String name = chooser.getSelectedFile().getAbsolutePath();
computeDigest(loadBytes(name));
}
}
public byte[] loadBytes(String name) {
FileInputStream in = null;
try {
in = new FileInputStream(name);
ByteArrayOutputStream buffer = new ByteArrayOutputStream();
int ch;
while ((ch = in.read()) != -1)
buffer.write(ch);
return buffer.toByteArray();
} catch (IOException e) {
if (in != null) {
try {
in.close();
} catch (IOException e2) {
}
}
return null;
}
}
public void computeDigest(byte[] b) {
currentAlgorithm.reset();
currentAlgorithm.update(b);
byte[] hash = currentAlgorithm.digest();
String d = "";
for (int i = 0; i < hash.length; i++) {
int v = hash[i] & 0xFF;
if (v < 16)
d += "0";
d += Integer.toString(v, 16).toUpperCase() + " ";
}
digest.setText(d);
}
private JTextArea message = new JTextArea();
private JTextField digest = new JTextField();
private MessageDigest currentAlgorithm;
}
Bitwise Operators in Java
public class BitwiseOperators {
public BitwiseOperators( ) {
int a = 11; //1 0 1 1
int b = 12; //1 1 0 0
System.out.println("a & b : "+(a & b));
System.out.println("a | b : "+(a | b));
System.out.println("a ^ b : "+(a ^ b));
System.out.println("~a : "+(~a));
System.out.println("a << b : "+(a << b));
System.out.println("a >> b : "+(a >> b));
System.out.println("a >>> b : "+(a >>> b));
}
public static void main(String args[]){
new BitwiseOperators();
}
}
public BitwiseOperators( ) {
int a = 11; //1 0 1 1
int b = 12; //1 1 0 0
System.out.println("a & b : "+(a & b));
System.out.println("a | b : "+(a | b));
System.out.println("a ^ b : "+(a ^ b));
System.out.println("~a : "+(~a));
System.out.println("a << b : "+(a << b));
System.out.println("a >> b : "+(a >> b));
System.out.println("a >>> b : "+(a >>> b));
}
public static void main(String args[]){
new BitwiseOperators();
}
}
Runtime Polymorphism or method overriding
class A{
public void fun1(int x){
System.out.println(""int in Class A is : " + x : " + x);
}
}
class B extends A{
public void fun1(int x){
System.out.println("int in Class B is : " + x);
}
}
public class polytwo{
public static void main(String[] args){
A obj;
obj=new A(); // line 1
obj.fun1(2); // line 2 (prints ""int in Class A is : 2")
obj=new B(); // line 3
obj.fun1(5); // line 4 (prints "int in Class A is : 5")
}
}
int in class A is: 2
int in class B is:5
public void fun1(int x){
System.out.println(""int in Class A is : " + x : " + x);
}
}
class B extends A{
public void fun1(int x){
System.out.println("int in Class B is : " + x);
}
}
public class polytwo{
public static void main(String[] args){
A obj;
obj=new A(); // line 1
obj.fun1(2); // line 2 (prints ""int in Class A is : 2")
obj=new B(); // line 3
obj.fun1(5); // line 4 (prints "int in Class A is : 5")
}
}
int in class A is: 2
int in class B is:5
Compline time Polymorpism or method overloading
class A{
public void fun1(int x){
System.out.println("The value of class A is : " + x);
}
public void fun1(int x,int y){
System.out.println("The value of class B is : "+x +" and "+ y);
}
}
public class polyone{
public static void main(String[] args){
A obj=new A();
// Here compiler decides that fun1(int) is to be called and "int" will be printed.
obj.fun1(2);
// Here compiler decides that fun1(int,int) is to be called and "int and int" will be printed.
obj.fun1(2,3);
}
}
output
The value of class A is: 2
The value of class B is: 2 and 3
public void fun1(int x){
System.out.println("The value of class A is : " + x);
}
public void fun1(int x,int y){
System.out.println("The value of class B is : "+x +" and "+ y);
}
}
public class polyone{
public static void main(String[] args){
A obj=new A();
// Here compiler decides that fun1(int) is to be called and "int" will be printed.
obj.fun1(2);
// Here compiler decides that fun1(int,int) is to be called and "int and int" will be printed.
obj.fun1(2,3);
}
}
output
The value of class A is: 2
The value of class B is: 2 and 3
inheritance in java
class A{
public void fun1(int x){
System.out.println("Int in A is :" + x);
}
}
class B extends A{
public void fun2(int x,int y){
fun1(6); // prints "int in A"
System.out.println("Int in B is :" + x + " and " + y);
}
}
public class inherit{
public static void main(String[] args){
B obj=new B();
obj.fun2(2, 5);
}
}
output
Int in A is: 6
Int in B is: 2 and 5
public void fun1(int x){
System.out.println("Int in A is :" + x);
}
}
class B extends A{
public void fun2(int x,int y){
fun1(6); // prints "int in A"
System.out.println("Int in B is :" + x + " and " + y);
}
}
public class inherit{
public static void main(String[] args){
B obj=new B();
obj.fun2(2, 5);
}
}
output
Int in A is: 6
Int in B is: 2 and 5
Encapsulation Example in java
class Check{
private int amount=0;
public int getAmount(){
return amount;
}
public void setAmount(int amt){
amount=amt;
}
}
public class Mainclass{
public static void main(String[] args){
int amt=0;
Check obj=new Check();
obj.setAmount(200);
amt=obj.getAmount();
System.out.println("Your current amount is :"+amt);
}
}
output
Your current amount is: 200
private int amount=0;
public int getAmount(){
return amount;
}
public void setAmount(int amt){
amount=amt;
}
}
public class Mainclass{
public static void main(String[] args){
int amt=0;
Check obj=new Check();
obj.setAmount(200);
amt=obj.getAmount();
System.out.println("Your current amount is :"+amt);
}
}
output
Your current amount is: 200
Calculate Circle Area using Java
/* Calculate Circle Area using Java Example This Calculate Circle Area using Java Example shows how to calculate area of circle using it's radius. */ import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; public class CalculateCircleAreaExample { public static void main(String[] args) { int radius = 0; System.out.println("Please enter radius of a circle"); try { //get the radius from console BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); radius = Integer.parseInt(br.readLine()); } //if invalid value was entered catch(NumberFormatException ne) { System.out.println("Invalid radius value" + ne); System.exit(0); } catch(IOException ioe) { System.out.println("IO Error :" + ioe); System.exit(0); } /* * Area of a circle is * pi * r * r * where r is a radius of a circle. */ //NOTE : use Math.PI constant to get value of pi double area = Math.PI * radius * radius; System.out.println("Area of a circle is " + area); } } /* Output of Calculate Circle Area using Java Example would be Please enter radius of a circle 19 Area of a circle is 1134.1149479459152 */
Saturday, 28 May 2011
combo box example in java
import java.applet.*;
import java.awt.*;
import java.awt.event.*;
import java.lang.*;
/*<applet code = choice.java width=200 height=200></applet> */
public class choice extends Applet implements ItemListener
{
Choice lang,db;
String msg=" ";
public void init()
{
lang=new Choice();
db=new Choice();
/*adding items to language*/
lang.add("c");
lang.add("c++");
lang.add("vb");
lang.add("vc++");
lang.add("java");
/*adding to database*/
db.add("oracle 8i");
db.add("oracle 9i");
db.add("ms-Access");
add(lang);
add(db);
lang.addItemListener(this);
db.addItemListener(this);
}
public void itemStateChanged (ItemEvent e)
{
repaint();
}
public void paint(Graphics g)
{
msg="CURRENT SELECTED LANGUAGE: ";
msg+=lang.getSelectedItem();
g.drawString(msg,6,40);
msg="CURRENT SELECTED DATABASE: ";
msg+=db.getSelectedItem();
g.drawString(msg,16,160);
}
}
java simple calculator
import java.applet.*;
import java.awt.*;
import java.awt.event.*;
public class Cal extends Applet implements ItemListener,ActionListener
{
Button b1;
Label l1,l2,l3;
TextField t1,t2,t3;
Checkbox c1,c2,c3,c4;
CheckboxGroup cbg; String msg="";
long a,b;
public void init()
{
l1=new Label("First Number:");
l2=new Label("Second Number:");
l3=new Label("The Result Is:");
t1=new TextField(6);
t2=new TextField(6);
t3=new TextField(12);
b1=new Button("Calculate");
cbg=new CheckboxGroup();
c1=new Checkbox("Add",cbg,true);
c2=new Checkbox("Sub",cbg,false);
c3=new Checkbox("Mul",cbg,false);
c4=new Checkbox("Div",cbg,false);
setLayout(new GridLayout(6,6));
add(l1); add(t1); add(l2); add(t2);
add(l3); add(t3);
add(c1); add(c2); add(c3); add(c4);
add(b1);
b1.addActionListener(this);
c1.addItemListener(this);
c2.addItemListener(this);
c3.addItemListener(this);
c4.addItemListener(this);
}
public void actionPerformed(ActionEvent e)
{
msg=e.getActionCommand();
a=Integer.parseInt(t1.getText());
b=Integer.parseInt(t2.getText());
if(msg.equals("Calculate"))
{
if("Add".equals(cbg.getSelectedCheckbox().getLabel()))
t3.setText(String.valueOf(a+b));
else if("Sub".equals(cbg.getSelectedCheckbox().getLabel()))
t3.setText(String.valueOf(a-b));
else if("Mul".equals(cbg.getSelectedCheckbox().getLabel()))
t3.setText(String.valueOf(a*b));
else if("Div".equals(cbg.getSelectedCheckbox().getLabel()))
t3.setText(String.valueOf(a/b));
}
repaint();
}
public void itemStateChanged(ItemEvent e)
{
repaint();
}
}
/*<applet code="Cal.java" width=300 height=250>
</applet> */
Subscribe to:
Comments (Atom)









