# StoppableThread.java A template to place a thread in a RUN, WAIT, or STOP state. #Programming Code Examples #Java/J2EE/J2ME #Java Threads


/** A template to control the state of a thread through setting
 *  an internal flag.

public class StoppableThread extends Thread {

   public static final int STOP    = 0;
   public static final int RUN     = 1;
   public static final int WAIT    = 2;
   private int state = RUN;

  /** Public method to permit setting a flag to stop or
   *  suspend the thread.  The state is monitored through the
   *  corresponding checkState method.
   */

   public synchronized void setState(int state) {
      this.state = state;
      if (state==RUN) {
         notify();
      }
   }

  /** Returns the desired state of the thread (RUN, STOP, WAIT).
   *  Normally, you may want to change the state or perform some
   *  other task if an InterruptedException occurs.
   */

   private synchronized int checkState() {
      while (state==WAIT) {
        try {
          wait();
        } catch (InterruptedException e) { }
      }
      return state;
   }

  /** An example of thread that will continue to run until
   *  the creating object tells the thread to STOP.
   */

   public void run() {
      while (checkState()!=STOP) {
         ...
      }
   }
}

Note: Brought from our old site: http://www.salearningschool.com/example_codes/ on Jan 2nd, 2017 From: http://sitestree.com/?p=10297
Categories:Programming Code Examples, Java/J2EE/J2ME, Java Threads
Tags:Java/J2EE/J2MEJava Threads
Post Data:2017-01-02 16:04:31

Shop Online: https://www.ShopForSoul.com/
(Big Data, Cloud, Security, Machine Learning): Courses: http://Training.SitesTree.com
In Bengali: http://Bangla.SaLearningSchool.com
http://SitesTree.com
8112223 Canada Inc./JustEtc: http://JustEtc.net (Software/Web/Mobile/Big-Data/Machine Learning)
Shop Online: https://www.ShopForSoul.com/
Medium: https://medium.com/@SayedAhmedCanada

DOM example that represents the basic structure of an XML document as a JTree #Programming Code Examples #Java/J2EE/J2ME #JavaScript

//XMLTree.java
//Uses the following files

Uses the following files:

    * XMLFrame.java:Swing application to select an XML document and display in a JTree.

ExtensionFileFilter.java Allows you to specify which file extensions will be displayed in a JFileChooser.

test.xml Default file loaded if none selected by user. 

perennials.xml and perennials.dtd Data on daylilies and corresponding DTD.

WindowUtilities.java  

ExitListener.java. 

//XMLTree.java as follows
import java.awt.*;
import javax.swing.*;
import javax.swing.tree.*;
import java.io.*;
import org.w3c.dom.*;
import javax.xml.parsers.*;

/** Given a filename or a name and an input stream,
 *  this class generates a JTree representing the
 *  XML structure contained in the file or stream.
 *  Parses with DOM then copies the tree structure
 *  (minus text and comment nodes).
 *
 *  Taken from Core Web Programming from 
 *  Prentice Hall and Sun Microsystems Press,
 *  
 *  © 2001 Marty Hall and Larry Brown;
 *  may be freely used or adapted. 
 */

public class XMLTree extends JTree {
  public XMLTree(String filename) throws IOException {
    this(filename, new FileInputStream(new File(filename)));
  }

  public XMLTree(String filename, InputStream in) {
    super(makeRootNode(in));
  }

  // This method needs to be static so that it can be called
  // from the call to the parent constructor (super), which
  // occurs before the object is really built.
  
  private static DefaultMutableTreeNode
                                 makeRootNode(InputStream in) {
    try {
      // Use JAXP's DocumentBuilderFactory so that there
      // is no code here that is dependent on a particular
      // DOM parser. Use the system property
      // javax.xml.parsers.DocumentBuilderFactory (set either
      // from Java code or by using the -D option to "java").
      // or jre_dir/lib/jaxp.properties to specify this.
      DocumentBuilderFactory builderFactory =
        DocumentBuilderFactory.newInstance();
      DocumentBuilder builder =
        builderFactory.newDocumentBuilder();
      // Standard DOM code from hereon. The "parse"
      // method invokes the parser and returns a fully parsed
      // Document object. We'll then recursively descend the
      // tree and copy non-text nodes into JTree nodes.
      Document document = builder.parse(in);
      document.getDocumentElement().normalize();
      Element rootElement = document.getDocumentElement();
      DefaultMutableTreeNode rootTreeNode =
        buildTree(rootElement);
      return(rootTreeNode);
    } catch(Exception e) {
      String errorMessage =
        "Error making root node: " + e;
      System.err.println(errorMessage);
      e.printStackTrace();
      return(new DefaultMutableTreeNode(errorMessage));
    }
  }

  private static DefaultMutableTreeNode
                              buildTree(Element rootElement) {
    // Make a JTree node for the root, then make JTree
    // nodes for each child and add them to the root node.
    // The addChildren method is recursive.
    DefaultMutableTreeNode rootTreeNode =
      new DefaultMutableTreeNode(treeNodeLabel(rootElement));
    addChildren(rootTreeNode, rootElement);
    return(rootTreeNode);
  }

  private static void addChildren
                       (DefaultMutableTreeNode parentTreeNode,
                        Node parentXMLElement) {
    // Recursive method that finds all the child elements
    // and adds them to the parent node. We have two types
    // of nodes here: the ones corresponding to the actual
    // XML structure and the entries of the graphical JTree.
    // The convention is that nodes corresponding to the
    // graphical JTree will have the word "tree" in the
    // variable name. Thus, "childElement" is the child XML
    // element whereas "childTreeNode" is the JTree element.
    // This method just copies the non-text and non-comment
    // nodes from the XML structure to the JTree structure.
    
    NodeList childElements =
      parentXMLElement.getChildNodes();
    for(int i=0; i<childelements .getLength(); i++) {
      Node childElement = childElements.item(i);
      if (!(childElement instanceof Text ||
            childElement instanceof Comment)) {
        DefaultMutableTreeNode childTreeNode =
          new DefaultMutableTreeNode
            (treeNodeLabel(childElement));
        parentTreeNode.add(childTreeNode);
        addChildren(childTreeNode, childElement);
      }
    }
  }

  // If the XML element has no attributes, the JTree node
  // will just have the name of the XML element. If the
  // XML element has attributes, the names and values of the
  // attributes will be listed in parens after the XML
  // element name. For example:
  // XML Element: 
  // JTree Node:  blah
  // XML Element: 
  // JTree Node:  blah (foo=bar, baz=quux)

  private static String treeNodeLabel(Node childElement) {
    NamedNodeMap elementAttributes =
      childElement.getAttributes();
    String treeNodeLabel = childElement.getNodeName();
    if (elementAttributes != null &&
        elementAttributes.getLength() > 0) {
      treeNodeLabel = treeNodeLabel + " (";
      int numAttributes = elementAttributes.getLength();
      for(int i=0; i 0) {
          treeNodeLabel = treeNodeLabel + ", ";
        }
        treeNodeLabel =
          treeNodeLabel + attribute.getNodeName() +
          "=" + attribute.getNodeValue();
      }
      treeNodeLabel = treeNodeLabel + ")";
    }
    return(treeNodeLabel);
  }
}

XMLFrame.java Swing application to select an XML document and display in a JTree.

import java.awt.*;
import javax.swing.*;
import java.io.*;

/** Invokes an XML parser on an XML document and displays
 *  the document in a JTree. Both the parser and the
 *  document can be specified by the user. The parser
 *  is specified by invoking the program with
 *  java -Djavax.xml.parsers.DocumentBuilderFactory=xxx XMLFrame
 *  If no parser is specified, the Apache Xerces parser is used.
 *  The XML document can be supplied on the command
 *  line, but if it is not given, a JFileChooser is used
 *  to interactively select the file of interest.
 *
 *  Taken from Core Web Programming from 
 *  Prentice Hall and Sun Microsystems Press,
 
 *  © 2001 Marty Hall and Larry Brown;
 *  may be freely used or adapted. 
 */

public class XMLFrame extends JFrame {
  public static void main(String[] args) {
    String jaxpPropertyName =
      "javax.xml.parsers.DocumentBuilderFactory";
    // Pass the parser factory in on the command line with
    // -D to override the use of the Apache parser.
    if (System.getProperty(jaxpPropertyName) == null) {
      String apacheXercesPropertyValue =
        "org.apache.xerces.jaxp.DocumentBuilderFactoryImpl";
      System.setProperty(jaxpPropertyName,
                         apacheXercesPropertyValue);
    }
    String filename;
    if (args.length > 0) {
      filename = args[0];
    } else {
      String[] extensions = { "xml", "tld" };
      WindowUtilities.setNativeLookAndFeel();
      filename = ExtensionFileFilter.getFileName(".",
                                                 "XML Files",
                                                 extensions);
      if (filename == null) {
        filename = "test.xml";
      }
    }
    new XMLFrame(filename);
  }

  public XMLFrame(String filename) {
    try {
      WindowUtilities.setNativeLookAndFeel();
      JTree tree = new XMLTree(filename);
      JFrame frame = new JFrame(filename);
      frame.addWindowListener(new ExitListener());
      Container content = frame.getContentPane();
      content.add(new JScrollPane(tree));
      frame.pack();
      frame.setVisible(true);
    } catch(IOException ioe) {
      System.out.println("Error creating tree: " + ioe);
    }
  }
}

ExtensionFileFilter.java Allows you to specify which file extensions will be displayed in a JFileChooser.

import java.io.File;
import java.util.*;
import javax.swing.*;
import javax.swing.filechooser.FileFilter;

/** A FileFilter that lets you specify which file extensions 
 *  will be displayed. Also includes a static getFileName 
 *  method that users can call to pop up a JFileChooser for 
 *  a set of file extensions.
 *  

* Adapted from Sun SwingSet demo. * * Taken from Core Web Programming from * Prentice Hall and Sun Microsystems Press, * © 2001 Marty Hall and Larry Brown; * may be freely used or adapted. */ public class ExtensionFileFilter extends FileFilter { public static final int LOAD = 0; public static final int SAVE = 1; private String description; private boolean allowDirectories; private Hashtable extensionsTable = new Hashtable(); private boolean allowAll = false; public ExtensionFileFilter(boolean allowDirectories) { this.allowDirectories = allowDirectories; } public ExtensionFileFilter() { this(true); } public static String getFileName(String initialDirectory, String description, String extension) { String[] extensions = new String[]{ extension }; return(getFileName(initialDirectory, description, extensions, LOAD)); } public static String getFileName(String initialDirectory, String description, String extension, int mode) { String[] extensions = new String[]{ extension }; return(getFileName(initialDirectory, description, extensions, mode)); } public static String getFileName(String initialDirectory, String description, String[] extensions) { return(getFileName(initialDirectory, description, extensions, LOAD)); } /** Pops up a JFileChooser that lists files with the * specified extensions. If the mode is SAVE, then the * dialog will have a Save button; otherwise, the dialog * will have an Open button. Returns a String corresponding * to the file's pathname, or null if Cancel was selected. */ public static String getFileName(String initialDirectory, String description, String[] extensions, int mode) { ExtensionFileFilter filter = new ExtensionFileFilter(); filter.setDescription(description); for(int i=0; i<extensions .length; i++) { String extension = extensions[i]; filter.addExtension(extension, true); } JFileChooser chooser = new JFileChooser(initialDirectory); chooser.setFileFilter(filter); int selectVal = (mode==SAVE) ? chooser.showSaveDialog(null) : chooser.showOpenDialog(null); if (selectVal == JFileChooser.APPROVE_OPTION) { String path = chooser.getSelectedFile().getAbsolutePath(); return(path); } else { JOptionPane.showMessageDialog(null, "No file selected."); return(null); } } public void addExtension(String extension, boolean caseInsensitive) { if (caseInsensitive) { extension = extension.toLowerCase(); } if (!extensionsTable.containsKey(extension)) { extensionsTable.put(extension, new Boolean(caseInsensitive)); if (extension.equals("*") || extension.equals("*.*") || extension.equals(".*")) { allowAll = true; } } } public boolean accept(File file) { if (file.isDirectory()) { return(allowDirectories); } if (allowAll) { return(true); } String name = file.getName(); int dotIndex = name.lastIndexOf('.'); if ((dotIndex == -1) || (dotIndex == name.length() - 1)) { return(false); } String extension = name.substring(dotIndex + 1); if (extensionsTable.containsKey(extension)) { return(true); } Enumeration keys = extensionsTable.keys(); while(keys.hasMoreElements()) { String possibleExtension = (String)keys.nextElement(); Boolean caseFlag = (Boolean)extensionsTable.get(possibleExtension); if ((caseFlag != null) && (caseFlag.equals(Boolean.FALSE)) && (possibleExtension.equalsIgnoreCase(extension))) { return(true); } } return(false); } public void setDescription(String description) { this.description = description; } public String getDescription() { return(description); } }

WindowUtilities.java

import javax.swing.*;
import java.awt.*;   // For Color and Container classes.

/** A few utilities that simplify using windows in Swing. 
 *
 *  Taken from Core Web Programming from 
 *  Prentice Hall and Sun Microsystems Press,
 * 
 *  © 2001 Marty Hall and Larry Brown;
 *  may be freely used or adapted.
 */

public class WindowUtilities {

  /** Tell system to use native look and feel, as in previous
   *  releases. Metal (Java) LAF is the default otherwise.
   */

  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 ExitListener());
    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));
  }
}

EXITListener.java

import java.awt.*;
import java.awt.event.*;

/** A listener that you attach to the top-level JFrame of
 *  your application, so that quitting the frame exits the 
 *  application.
 *
 *  Taken from Core Web Programming from 
 *  Prentice Hall and Sun Microsystems Press,
 *  
 *  © 2001 Marty Hall and Larry Brown;
 *  may be freely used or adapted. 
 */
public class ExitListener extends WindowAdapter {
  public void windowClosing(WindowEvent event) {
    System.exit(0);
  }
}

Note: Brought from our old site: http://www.salearningschool.com/example_codes/ on Jan 2nd, 2017 From: http://sitestree.com/?p=10199
Categories:Programming Code Examples, Java/J2EE/J2ME, JavaScript
Tags:Java/J2EE/J2MEJavaScript
Post Data:2017-01-02 16:04:23

Shop Online: https://www.ShopForSoul.com/
(Big Data, Cloud, Security, Machine Learning): Courses: http://Training.SitesTree.com
In Bengali: http://Bangla.SaLearningSchool.com
http://SitesTree.com
8112223 Canada Inc./JustEtc: http://JustEtc.net (Software/Web/Mobile/Big-Data/Machine Learning)
Shop Online: https://www.ShopForSoul.com/
Medium: https://medium.com/@SayedAhmedCanada

PreparedStatements.java An example to test the timing differences resulting from repeated raw queries vs. repeated calls #Programming Code Examples #Java/J2EE/J2ME #JDBC

package cwp;

import java.sql.*;

/** An example to test the timing differences resulting
 *  from repeated raw queries vs. repeated calls to
 *  prepared statements. These results will vary dramatically
 *  among database servers and drivers. With my setup
 *  and drivers, Oracle prepared statements took only half
 *  the time that raw queries required when using a modem
 *  connection, and took only 70% of the time that
 *  raw queries required when using a fast LAN connection.
 *  Sybase times were identical in both cases.
 *  

*/ public class PreparedStatements { public static void main(String[] args) { if (args.length 5) && (args[5].equals("print"))) { print = true; } Connection connection = getConnection(driver, url, username, password); if (connection != null) { doPreparedStatements(connection, print); doRawQueries(connection, print); } } private static void doPreparedStatements(Connection conn, boolean print) { try { String queryFormat = "SELECT lastname FROM employees WHERE salary > ?"; PreparedStatement statement = conn.prepareStatement(queryFormat); long startTime = System.currentTimeMillis(); for(int i=0; i<40; i++) { statement.setFloat(1, i*5000); ResultSet results = statement.executeQuery(); if (print) { showResults(results); } } long stopTime = System.currentTimeMillis(); double elapsedTime = (stopTime - startTime)/1000.0; System.out.println("Executing prepared statement " + "40 times took " + elapsedTime + " seconds."); } catch(SQLException sqle) { System.out.println("Error executing statement: " + sqle); } } public static void doRawQueries(Connection conn, boolean print) { try { String queryFormat = "SELECT lastname FROM employees WHERE salary > "; Statement statement = conn.createStatement(); long startTime = System.currentTimeMillis(); for(int i=0; i<40; i++) { ResultSet results = statement.executeQuery(queryFormat + (i*5000)); if (print) { showResults(results); } } long stopTime = System.currentTimeMillis(); double elapsedTime = (stopTime - startTime)/1000.0; System.out.println("Executing raw query " + "40 times took " + elapsedTime + " seconds."); } catch(SQLException sqle) { System.out.println("Error executing query: " + sqle); } } private static void showResults(ResultSet results) throws SQLException { while(results.next()) { System.out.print(results.getString(1) + " "); } System.out.println(); } private static Connection getConnection(String driver, String url, String username, String password) { try { Class.forName(driver); Connection connection = DriverManager.getConnection(url, username, password); return(connection); } catch(ClassNotFoundException cnfe) { System.err.println("Error loading driver: " + cnfe); return(null); } catch(SQLException sqle) { System.err.println("Error connecting: " + sqle); return(null); } } private static void printUsage() { System.out.println("Usage: PreparedStatements host " + "dbName username password " + "oracle|sybase [print]."); } }

Note: Brought from our old site: http://www.salearningschool.com/example_codes/ on Jan 2nd, 2017 From: http://sitestree.com/?p=10210
Categories:Programming Code Examples, Java/J2EE/J2ME, JDBC
Tags:Java/J2EE/J2MEJDBC
Post Data:2017-01-02 16:04:23

Shop Online: https://www.ShopForSoul.com/
(Big Data, Cloud, Security, Machine Learning): Courses: http://Training.SitesTree.com
In Bengali: http://Bangla.SaLearningSchool.com
http://SitesTree.com
8112223 Canada Inc./JustEtc: http://JustEtc.net (Software/Web/Mobile/Big-Data/Machine Learning)
Shop Online: https://www.ShopForSoul.com/
Medium: https://medium.com/@SayedAhmedCanada

extract relevant data from a DBResults #Programming Code Examples #Java/J2EE/J2ME #JDBC

package cwp;

import javax.swing.table.*;

/** Simple class that tells a JTable how to extract
 *  relevant data from a DBResults object (which is
 *  used to store the results from a database query).
 */

public class DBResultsTableModel extends AbstractTableModel {
  private DBResults results;

  public DBResultsTableModel(DBResults results) {
    this.results = results;
  }

  public int getRowCount() {
    return(results.getRowCount());
  }

  public int getColumnCount() {
    return(results.getColumnCount());
  }

  public String getColumnName(int column) {
    return(results.getColumnNames()[column]);
  }

  public Object getValueAt(int row, int column) {
    return(results.getRow(row)[column]);
  }
}

Note: Brought from our old site: http://www.salearningschool.com/example_codes/ on Jan 2nd, 2017 From: http://sitestree.com/?p=10209
Categories:Programming Code Examples, Java/J2EE/J2ME, JDBC
Tags:Java/J2EE/J2MEJDBC
Post Data:2017-01-02 16:04:23

Shop Online: https://www.ShopForSoul.com/
(Big Data, Cloud, Security, Machine Learning): Courses: http://Training.SitesTree.com
In Bengali: http://Bangla.SaLearningSchool.com
http://SitesTree.com
8112223 Canada Inc./JustEtc: http://JustEtc.net (Software/Web/Mobile/Big-Data/Machine Learning)
Shop Online: https://www.ShopForSoul.com/
Medium: https://medium.com/@SayedAhmedCanada

QueryViewer.java: An interactive database query viewer #Programming Code Examples #Java/J2EE/J2ME #JDBC

# QueryViewer.java  An interactive database query viewer. Connects to the specified Oracle or Sybase database, executes a query, and presents the results in a JTable. Uses the following file:

    * DBResultsTableModel.java Simple class that tells a JTable how to extract relevant data from a DBResults object (which is used to store the results from a database query). 
############################################################################

  package cwp;

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.table.*;

/** An interactive database query viewer. Connects to
 *  the specified Oracle or Sybase database, executes a query,
 *  and presents the results in a JTable.
 *  

*/ public class QueryViewer extends JFrame implements ActionListener{ public static void main(String[] args) { new QueryViewer(); } private JTextField hostField, dbNameField, queryField, usernameField; private JRadioButton oracleButton, sybaseButton; private JPasswordField passwordField; private JButton showResultsButton; Container contentPane; private JPanel tablePanel; public QueryViewer () { super("Database Query Viewer"); WindowUtilities.setNativeLookAndFeel(); addWindowListener(new ExitListener()); contentPane = getContentPane(); contentPane.add(makeControlPanel(), BorderLayout.NORTH); pack(); setVisible(true); } /** When the "Show Results" button is pressed or * RETURN is hit while the query textfield has the * keyboard focus, a database lookup is performed, * the results are placed in a JTable, and the window * is resized to accommodate the table. */ public void actionPerformed(ActionEvent event) { String host = hostField.getText(); String dbName = dbNameField.getText(); String username = usernameField.getText(); String password = String.valueOf(passwordField.getPassword()); String query = queryField.getText(); int vendor; if (oracleButton.isSelected()) { vendor = DriverUtilities.ORACLE; } else { vendor = DriverUtilities.SYBASE; } if (tablePanel != null) { contentPane.remove(tablePanel); } tablePanel = makeTablePanel(host, dbName, vendor, username, password, query); contentPane.add(tablePanel, BorderLayout.CENTER); pack(); } // Executes a query and places the result in a // JTable that is, in turn, inside a JPanel. private JPanel makeTablePanel(String host, String dbName, int vendor, String username, String password, String query) { String driver = DriverUtilities.getDriver(vendor); String url = DriverUtilities.makeURL(host, dbName, vendor); DBResults results = DatabaseUtilities.getQueryResults(driver, url, username, password, query, true); JPanel panel = new JPanel(new BorderLayout()); if (results == null) { panel.add(makeErrorLabel()); return(panel); } DBResultsTableModel model = new DBResultsTableModel(results); JTable table = new JTable(model); table.setFont(new Font("Serif", Font.PLAIN, 17)); table.setRowHeight(28); JTableHeader header = table.getTableHeader(); header.setFont(new Font("SansSerif", Font.BOLD, 13)); panel.add(table, BorderLayout.CENTER); panel.add(header, BorderLayout.NORTH); panel.setBorder (BorderFactory.createTitledBorder("Query Results")); return(panel); } // The panel that contains the textfields, checkboxes, // and button. private JPanel makeControlPanel() { JPanel panel = new JPanel(new GridLayout(0, 1)); panel.add(makeHostPanel()); panel.add(makeUsernamePanel()); panel.add(makeQueryPanel()); panel.add(makeButtonPanel()); panel.setBorder (BorderFactory.createTitledBorder("Query Data")); return(panel); } // The panel that has the host and db name textfield and // the driver radio buttons. Placed in control panel. private JPanel makeHostPanel() { JPanel panel = new JPanel(); panel.add(new JLabel("Host:")); hostField = new JTextField(15); panel.add(hostField); panel.add(new JLabel(" DB Name:")); dbNameField = new JTextField(15); panel.add(dbNameField); panel.add(new JLabel(" Driver:")); ButtonGroup vendorGroup = new ButtonGroup(); oracleButton = new JRadioButton("Oracle", true); vendorGroup.add(oracleButton); panel.add(oracleButton); sybaseButton = new JRadioButton("Sybase"); vendorGroup.add(sybaseButton); panel.add(sybaseButton); return(panel); } // The panel that has the username and password textfields. // Placed in control panel. private JPanel makeUsernamePanel() { JPanel panel = new JPanel(); usernameField = new JTextField(10); passwordField = new JPasswordField(10); panel.add(new JLabel("Username: ")); panel.add(usernameField); panel.add(new JLabel(" Password:")); panel.add(passwordField); return(panel); } // The panel that has textfield for entering queries. // Placed in control panel. private JPanel makeQueryPanel() { JPanel panel = new JPanel(); queryField = new JTextField(40); queryField.addActionListener(this); panel.add(new JLabel("Query:")); panel.add(queryField); return(panel); } // The panel that has the "Show Results" button. // Placed in control panel. private JPanel makeButtonPanel() { JPanel panel = new JPanel(); showResultsButton = new JButton("Show Results"); showResultsButton.addActionListener(this); panel.add(showResultsButton); return(panel); } // Shows warning when bad query sent. private JLabel makeErrorLabel() { JLabel label = new JLabel("No Results", JLabel.CENTER); label.setFont(new Font("Serif", Font.BOLD, 36)); return(label); } }

Note: Brought from our old site: http://www.salearningschool.com/example_codes/ on Jan 2nd, 2017 From: http://sitestree.com/?p=10208
Categories:Programming Code Examples, Java/J2EE/J2ME, JDBC
Tags:Java/J2EE/J2MEJDBC
Post Data:2017-01-02 16:04:23

Shop Online: https://www.ShopForSoul.com/
(Big Data, Cloud, Security, Machine Learning): Courses: http://Training.SitesTree.com
In Bengali: http://Bangla.SaLearningSchool.com
http://SitesTree.com
8112223 Canada Inc./JustEtc: http://JustEtc.net (Software/Web/Mobile/Big-Data/Machine Learning)
Shop Online: https://www.ShopForSoul.com/
Medium: https://medium.com/@SayedAhmedCanada

EmployeeCreation.java: Make a simple "employees" table using the database utilities #Programming Code Examples #Java/J2EE/J2ME #JDBC

package cwp;

import java.sql.*;

/** Make a simple "employees" table using DatabaseUtilities.
 */

public class EmployeeCreation {
  public static Connection createEmployees(String driver,
                                           String url,
                                           String username,
                                           String password,
                                           boolean close) {
    String format =
      "(id int, firstname varchar(32), lastname varchar(32), " +
      "language varchar(16), salary float)";
    String[] employees =
      {"(1, 'Wye', 'Tukay', 'COBOL', 42500)",
       "(2, 'Britt', 'Tell',   'C++',   62000)",
       "(3, 'Max',  'Manager', 'none',  15500)",
       "(4, 'Polly', 'Morphic', 'Smalltalk', 51500)",
       "(5, 'Frank', 'Function', 'Common Lisp', 51500)",
       "(6, 'Justin', 'Timecompiler', 'Java', 98000)",
       "(7, 'Sir', 'Vlet', 'Java', 114750)",
       "(8, 'Jay', 'Espy', 'Java', 128500)" };
    return(DatabaseUtilities.createTable(driver, url,
                                         username, password,
                                         "employees",
                                         format, employees,
                                         close));    
  }

  public static void main(String[] args) {
    if (args.length < 5) {
      printUsage();
      return;
    }
    String vendorName = args[4];
    int vendor = DriverUtilities.getVendor(vendorName);
    if (vendor == DriverUtilities.UNKNOWN) {
      printUsage();
      return;
    }
    String driver = DriverUtilities.getDriver(vendor);
    String host = args[0];
    String dbName = args[1];
    String url =
      DriverUtilities.makeURL(host, dbName, vendor);
    String username = args[2];
    String password = args[3];
    createEmployees(driver, url, username, password, true);
  }

  private static void printUsage() {
    System.out.println("Usage: EmployeeCreation host dbName " +
                       "username password oracle|sybase.");
  }
}

Note: Brought from our old site: http://www.salearningschool.com/example_codes/ on Jan 2nd, 2017 From: http://sitestree.com/?p=10207
Categories:Programming Code Examples, Java/J2EE/J2ME, JDBC
Tags:Java/J2EE/J2MEJDBC
Post Data:2017-01-02 16:04:23

Shop Online: https://www.ShopForSoul.com/
(Big Data, Cloud, Security, Machine Learning): Courses: http://Training.SitesTree.com
In Bengali: http://Bangla.SaLearningSchool.com
http://SitesTree.com
8112223 Canada Inc./JustEtc: http://JustEtc.net (Software/Web/Mobile/Big-Data/Machine Learning)
Shop Online: https://www.ShopForSoul.com/
Medium: https://medium.com/@SayedAhmedCanada

EmployeeTest2.java: A test case for the database utilities. Prints results formatted as an HTML table. #Programming Code Examples #Java/J2EE/J2ME #JDBC

package cwp;

import java.sql.*;

/** Connect to Oracle or Sybase and print "employees" table
 *  as an HTML table.
 *  

*/ public class EmployeeTest2 { public static void main(String[] args) { if (args.length < 5) { printUsage(); return; } String vendorName = args[4]; int vendor = DriverUtilities.getVendor(vendorName); if (vendor == DriverUtilities.UNKNOWN) { printUsage(); return; } String driver = DriverUtilities.getDriver(vendor); String host = args[0]; String dbName = args[1]; String url = DriverUtilities.makeURL(host, dbName, vendor); String username = args[2]; String password = args[3]; String query = "SELECT * FROM employees"; DBResults results = DatabaseUtilities.getQueryResults(driver, url, username, password, query, true); System.out.println(results.toHTMLTable("CYAN")); } private static void printUsage() { System.out.println("Usage: EmployeeTest2 host dbName " + "username password oracle|sybase."); } }

Note: Brought from our old site: http://www.salearningschool.com/example_codes/ on Jan 2nd, 2017 From: http://sitestree.com/?p=10206
Categories:Programming Code Examples, Java/J2EE/J2ME, JDBC
Tags:Java/J2EE/J2MEJDBC
Post Data:2017-01-02 16:04:23

Shop Online: https://www.ShopForSoul.com/
(Big Data, Cloud, Security, Machine Learning): Courses: http://Training.SitesTree.com
In Bengali: http://Bangla.SaLearningSchool.com
http://SitesTree.com
8112223 Canada Inc./JustEtc: http://JustEtc.net (Software/Web/Mobile/Big-Data/Machine Learning)
Shop Online: https://www.ShopForSoul.com/
Medium: https://medium.com/@SayedAhmedCanada

EmployeeTest.java: A test case for the database utilities. Prints results in plain text. #Programming Code Examples #Java/J2EE/J2ME #JDBC


package cwp;

import java.sql.*;

/** Connect to Oracle or Sybase and print "employees" table.
 *  

*/ public class EmployeeTest { public static void main(String[] args) { if (args.length < 5) { printUsage(); return; } String vendorName = args[4]; int vendor = DriverUtilities.getVendor(vendorName); if (vendor == DriverUtilities.UNKNOWN) { printUsage(); return; } String driver = DriverUtilities.getDriver(vendor); String host = args[0]; String dbName = args[1]; String url = DriverUtilities.makeURL(host, dbName, vendor); String username = args[2]; String password = args[3]; DatabaseUtilities.printTable(driver, url, username, password, "employees", 12, true); } private static void printUsage() { System.out.println("Usage: EmployeeTest host dbName " + "username password oracle|sybase."); } }

Note: Brought from our old site: http://www.salearningschool.com/example_codes/ on Jan 2nd, 2017 From: http://sitestree.com/?p=10205
Categories:Programming Code Examples, Java/J2EE/J2ME, JDBC
Tags:Java/J2EE/J2MEJDBC
Post Data:2017-01-02 16:04:23

Shop Online: https://www.ShopForSoul.com/
(Big Data, Cloud, Security, Machine Learning): Courses: http://Training.SitesTree.com
In Bengali: http://Bangla.SaLearningSchool.com
http://SitesTree.com
8112223 Canada Inc./JustEtc: http://JustEtc.net (Software/Web/Mobile/Big-Data/Machine Learning)
Shop Online: https://www.ShopForSoul.com/
Medium: https://medium.com/@SayedAhmedCanada

DBResults.java: Class to store completed results of a JDBC Query. Differs from a ResultSet in several ways #Programming Code Examples #Java/J2EE/J2ME #JDBC


# DBResults.java  Class to store completed results of a JDBC Query. Differs from a ResultSet in several ways:

    * ResultSet doesn?t necessarily have all the data; reconnection to database occurs as you ask for later rows.
    * This class stores results as strings, in arrays.
    * This class includes DatabaseMetaData (database product name and version) and ResultSetMetaData (the column names).
    * This class has a toHTMLTable method that turns the results into a long string corresponding to an HTML table. 




package cwp;

import java.sql.*;
import java.util.*;

/** Class to store completed results of a JDBC Query.
 *  Differs from a ResultSet in several ways:
 *  
    *
  • ResultSet doesn't necessarily have all the data; * reconnection to database occurs as you ask for * later rows. *
  • This class stores results as strings, in arrays. *
  • This class includes DatabaseMetaData (database product * name and version) and ResultSetMetaData * (the column names). *
  • This class has a toHTMLTable method that turns * the results into a long string corresponding to * an HTML table. *
*

*/ public class DBResults { private Connection connection; private String productName; private String productVersion; private int columnCount; private String[] columnNames; private Vector queryResults; String[] rowData; public DBResults(Connection connection, String productName, String productVersion, int columnCount, String[] columnNames) { this.connection = connection; this.productName = productName; this.productVersion = productVersion; this.columnCount = columnCount; this.columnNames = columnNames; rowData = new String[columnCount]; queryResults = new Vector(); } public Connection getConnection() { return(connection); } public String getProductName() { return(productName); } public String getProductVersion() { return(productVersion); } public int getColumnCount() { return(columnCount); } public String[] getColumnNames() { return(columnNames); } public int getRowCount() { return(queryResults.size()); } public String[] getRow(int index) { return((String[])queryResults.elementAt(index)); } public void addRow(String[] row) { queryResults.addElement(row); } /** Output the results as an HTML table, with * the column names as headings and the rest of * the results filling regular data cells. */ public String toHTMLTable(String headingColor) { StringBuffer buffer = new StringBuffer("

n"); if (headingColor != null) { buffer.append(" n "); } else { buffer.append(" n "); } for(int col=0; col<getcolumncount (); col++) { buffer.append("n "); String[] rowData = getRow(row); for(int col=0; col<getcolumncount (); col++) { buffer.append("
" + columnNames[col]); } for(int row=0; row<getrowcount (); row++) { buffer.append("n
" + rowData[col]); } } buffer.append("n
"); return(buffer.toString()); } }

Note: Brought from our old site: http://www.salearningschool.com/example_codes/ on Jan 2nd, 2017 From: http://sitestree.com/?p=10204
Categories:Programming Code Examples, Java/J2EE/J2ME, JDBC
Tags:Java/J2EE/J2MEJDBC
Post Data:2017-01-02 16:04:23

Shop Online: https://www.ShopForSoul.com/
(Big Data, Cloud, Security, Machine Learning): Courses: http://Training.SitesTree.com
In Bengali: http://Bangla.SaLearningSchool.com
http://SitesTree.com
8112223 Canada Inc./JustEtc: http://JustEtc.net (Software/Web/Mobile/Big-Data/Machine Learning)
Shop Online: https://www.ShopForSoul.com/
Medium: https://medium.com/@SayedAhmedCanada

DatabaseUtilities.java: Several general-purpose utilities discussed and used in the chapter. #Programming Code Examples #Java/J2EE/J2ME #JDBC

package cwp;

import java.sql.*;

/** Three database utilities:
* 1) getQueryResults. Connects to a database, executes * a query, retrieves all the rows as arrays * of strings, and puts them inside a DBResults * object. Also places the database product name, * database version, and the names of all the columns * into the DBResults object. This has two versions: * one that makes a new connection and another that * uses an existing connection.

* 2) createTable. Given a table name, a string denoting * the column formats, and an array of strings denoting * the row values, this method connects to a database, * removes any existing versions of the designated * table, issues a CREATE TABLE command with the * designated format, then sends a series of INSERT INTO * commands for each of the rows. Again, there are * two versions: one that makes a new connection and * another that uses an existing connection.

* 3) printTable. Given a table name, this connects to * the specified database, retrieves all the rows, * and prints them on the standard output. */ public class DatabaseUtilities { /** Connect to database, execute specified query, * and accumulate results into DBRresults object. * If the database connection is left open (use the * close argument to specify), you can retrieve the * connection via DBResults.getConnection. */ public static DBResults getQueryResults(String driver, String url, String username, String password, String query, boolean close) { try { Class.forName(driver); Connection connection = DriverManager.getConnection(url, username, password); return(getQueryResults(connection, query, close)); } catch(ClassNotFoundException cnfe) { System.err.println("Error loading driver: " + cnfe); return(null); } catch(SQLException sqle) { System.err.println("Error connecting: " + sqle); return(null); } } /** Retrieves results as in previous method, but uses * an existing connection instead of opening a new one. */ public static DBResults getQueryResults(Connection connection, String query, boolean close) { try { DatabaseMetaData dbMetaData = connection.getMetaData(); String productName = dbMetaData.getDatabaseProductName(); String productVersion = dbMetaData.getDatabaseProductVersion(); Statement statement = connection.createStatement(); ResultSet resultSet = statement.executeQuery(query); ResultSetMetaData resultsMetaData = resultSet.getMetaData(); int columnCount = resultsMetaData.getColumnCount(); String[] columnNames = new String[columnCount]; // Column index starts at 1 (ala SQL) not 0 (ala Java). for(int i=1; i<columncount +1; i++) { columnNames[i-1] = resultsMetaData.getColumnName(i).trim(); } DBResults dbResults = new DBResults(connection, productName, productVersion, columnCount, columnNames); while(resultSet.next()) { String[] row = new String[columnCount]; // Again, ResultSet index starts at 1, not 0. for(int i=1; i<columnCount+1; i++) { String entry = resultSet.getString(i); if (entry != null) { entry = entry.trim(); } row[i-1] = entry; } dbResults.addRow(row); } if (close) { connection.close(); } return(dbResults); } catch(SQLException sqle) { System.err.println("Error connecting: " + sqle); return(null); } } /** Build a table with the specified format and rows. */ public static Connection createTable(String driver, String url, String username, String password, String tableName, String tableFormat, String[] tableRows, boolean close) { try { Class.forName(driver); Connection connection = DriverManager.getConnection(url, username, password); return(createTable(connection, username, password, tableName, tableFormat, tableRows, close)); } catch(ClassNotFoundException cnfe) { System.err.println("Error loading driver: " + cnfe); return(null); } catch(SQLException sqle) { System.err.println("Error connecting: " + sqle); return(null); } } /** Like the previous method, but uses existing connection. */ public static Connection createTable(Connection connection, String username, String password, String tableName, String tableFormat, String[] tableRows, boolean close) { try { Statement statement = connection.createStatement(); // Drop previous table if it exists, but don't get // error if it doesn't. Thus the separate try/catch here. try { statement.execute("DROP TABLE " + tableName); } catch(SQLException sqle) {} String createCommand = "CREATE TABLE " + tableName + " " + tableFormat; statement.execute(createCommand); String insertPrefix = "INSERT INTO " + tableName + " VALUES"; for(int i=0; i<tableRows.length; i++) { statement.execute(insertPrefix + tableRows[i]); } if (close) { connection.close(); return(null); } else { return(connection); } } catch(SQLException sqle) { System.err.println("Error creating table: " + sqle); return(null); } } public static void printTable(String driver, String url, String username, String password, String tableName, int entryWidth, boolean close) { String query = "SELECT * FROM " + tableName; DBResults results = getQueryResults(driver, url, username, password, query, close); printTableData(tableName, results, entryWidth, true); } /** Prints out all entries in a table. Each entry will * be printed in a column that is entryWidth characters * wide, so be sure to provide a value at least as big * as the widest result. */ public static void printTable(Connection connection, String tableName, int entryWidth, boolean close) { String query = "SELECT * FROM " + tableName; DBResults results = getQueryResults(connection, query, close); printTableData(tableName, results,entryWidth, true); } public static void printTableData(String tableName, DBResults results, int entryWidth, boolean printMetaData) { if (results == null) { return; } if (printMetaData) { System.out.println("Database: " + results.getProductName()); System.out.println("Version: " + results.getProductVersion()); System.out.println(); } System.out.println(tableName + ":"); String underline = padString("", tableName.length()+1, "="); System.out.println(underline); int columnCount = results.getColumnCount(); String separator = makeSeparator(entryWidth, columnCount); System.out.println(separator); String row = makeRow(results.getColumnNames(), entryWidth); System.out.println(row); System.out.println(separator); int rowCount = results.getRowCount(); for(int i=0; i<rowCount; i++) { row = makeRow(results.getRow(i), entryWidth); System.out.println(row); } System.out.println(separator); } // A String of the form "| xxx | xxx | xxx |" private static String makeRow(String[] entries, int entryWidth) { String row = "|"; for(int i=0; i<entries.length; i++) { row = row + padString(entries[i], entryWidth, " "); row = row + " |"; } return(row); } // A String of the form "+------+------+------+" private static String makeSeparator(int entryWidth, int columnCount) { String entry = padString("", entryWidth+1, "-"); String separator = "+"; for(int i=0; i<columnCount; i++) { separator = separator + entry + "+"; } return(separator); } private static String padString(String orig, int size, String padChar) { if (orig == null) { orig = ""; } // Use StringBuffer, not just repeated String concatenation // to avoid creating too many temporary Strings. StringBuffer buffer = new StringBuffer(""); int extraChars = size - orig.length(); for(int i=0; i<extrachars ; i++) { buffer.append(padChar); } buffer.append(orig); return(buffer.toString()); } }

Note: Brought from our old site: http://www.salearningschool.com/example_codes/ on Jan 2nd, 2017 From: http://sitestree.com/?p=10203
Categories:Programming Code Examples, Java/J2EE/J2ME, JDBC
Tags:Java/J2EE/J2MEJDBC
Post Data:2017-01-02 16:04:23

Shop Online: https://www.ShopForSoul.com/
(Big Data, Cloud, Security, Machine Learning): Courses: http://Training.SitesTree.com
In Bengali: http://Bangla.SaLearningSchool.com
http://SitesTree.com
8112223 Canada Inc./JustEtc: http://JustEtc.net (Software/Web/Mobile/Big-Data/Machine Learning)
Shop Online: https://www.ShopForSoul.com/
Medium: https://medium.com/@SayedAhmedCanada