98..Etc/velocity2010. 2. 19. 18:10
반응형

import java.io.StringWriter;
import java.io.Writer;

import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.Velocity;
import org.apache.velocity.tools.generic.MathTool;

public class MathToolExample {
  public static void main(String[] args) throws Exception {
    Velocity.init();

    Template t = Velocity.getTemplate("./src/mathTool.vm");

    VelocityContext ctx = new VelocityContext();
    ctx.put("math", new MathTool());
    ctx.put("aNumber", new Double(5.5));

    Writer writer = new StringWriter();
    t.merge(ctx, writer);

    System.out.println(writer);
  }
}
-------------------------------------------------------------------------------------
$math.random is a random number
Posted by 1010
98..Etc/velocity2010. 2. 19. 18:09
반응형
-------------------------------------------------------------------------------------

import java.io.StringWriter;
import java.io.Writer;

import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.Velocity;
import org.apache.velocity.tools.generic.IteratorTool;

public class IteratorToolExample {

  public static void main(String[] args) throws Exception {
    Velocity.init();

    Template t = Velocity.getTemplate("./src/iteratorTool.vm");

    VelocityContext ctx = new VelocityContext();
    ctx.put("var", new IteratorTool());

    Writer writer = new StringWriter();
    t.merge(ctx, writer);

    System.out.println(writer);
  }
}
-------------------------------------------------------------------------------------
#set($list = ["A", "B", "C", "D", "E"])

#foreach($item in $list)
    $item
#end
Posted by 1010
98..Etc/velocity2010. 2. 19. 18:08
반응형

-------------------------------------------------------------------------------------

import java.io.StringWriter;
import java.io.Writer;

import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.Velocity;
import org.apache.velocity.tools.generic.RenderTool;

public class VMDemo {

  public static void main(String[] args) throws Exception {
    Velocity.init();
    Template t = Velocity.getTemplate("./src/VMDemo.vm");

    VelocityContext ctx = new VelocityContext();

    Writer writer = new StringWriter();
    t.merge(ctx, writer);

    System.out.println(writer);
  }
}
-------------------------------------------------------------------------------------
<html>
    <head>
        <title>Gimli's Widgetarium</title>
    </head>
    <body>
        <table>
            #set ($rowCount = 1)            
            #set ($products = ["one", "two", "three"])
            #foreach($product in $products)
                #if ($rowCount % 2 == 0)
                    #set ($bgcolor = "#FFFFFF")
                #else
                    #set ($bgcolor = "#CCCCCC")                
                #end
                <tr>
                    <td bgcolor="$bgcolor">$product</td>
                    <td bgcolor="$bgcolor">$product</td>
                </tr>                        
                #set ($rowCount = $rowCount + 1)
            #end
        </table>
    </body>
</html>

           

Posted by 1010
98..Etc/velocity2010. 2. 19. 18:07
반응형
import java.io.StringWriter;
import java.io.Writer;

import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.Velocity;
import org.apache.velocity.tools.generic.RenderTool;

public class VMDemo {

  public static void main(String[] args) throws Exception {
    Velocity.init();
    Template t = Velocity.getTemplate("./src/VMDemo.vm");

    VelocityContext ctx = new VelocityContext();

    Writer writer = new StringWriter();
    t.merge(ctx, writer);

    System.out.println(writer);
  }
}
-------------------------------------------------------------------------------------
#set ($companyName = "Name")
<html>
  <head>
    <title>$companyName Homepage</title>
  </head>
  <body>
    <h1>Welcome!!</h1>
    #if ($userType == "VIP")
      <h2>You are a VIP!</h2>
    #else
      <h2>You are not a VIP!</h2>
    #end
  </body>
</html>
Posted by 1010
98..Etc/velocity2010. 2. 19. 18:07
반응형
import java.io.StringWriter;
import java.io.Writer;

import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.Velocity;
import org.apache.velocity.tools.generic.IteratorTool;

public class IteratorToolExample {

  public static void main(String[] args) throws Exception {
    Velocity.init();

    Template t = Velocity.getTemplate("./src/iteratorTool.vm");

    VelocityContext ctx = new VelocityContext();
    ctx.put("var", new IteratorTool());

    Writer writer = new StringWriter();
    t.merge(ctx, writer);

    System.out.println(writer);
  }
}
-------------------------------------------------------------------------------------
#set($list = ["A", "B", "C", "D", "E"])

#foreach($item in $list)
    #if($velocityCount <= 3)
        $item
    #end
#end
           
Posted by 1010
98..Etc/velocity2010. 2. 19. 18:05
반응형
-------------------------------------------------------------------------------------
Today's date is:       $date
Today's date is also:  $date.long           #* using property shortcut *#
Today's date is also:  $date.get('long')    #* using full syntax *#
The date and time is:  $date.default $date.short

Another date is:       $aDate
Another date is also:  $date.format('medium', $aDate)

-------------------------------------------------------------------------------------
import java.io.StringWriter;
import java.io.Writer;
import java.util.Calendar;
import java.util.TimeZone;

import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.Velocity;
import org.apache.velocity.tools.generic.DateTool;

public class DateToolExample {

  public static void main(String[] args) throws Exception {
    Velocity.init();

    Template t = Velocity.getTemplate("./src/dateTool.vm");

    VelocityContext ctx = new VelocityContext();
    ctx.put("date", new DateTool());

    Calendar aDate = Calendar.getInstance(TimeZone.getTimeZone("PST"));
    aDate.set(200, 11, 25);

    ctx.put("aDate", aDate);

    Writer writer = new StringWriter();
    t.merge(ctx, writer);

    System.out.println(writer);
  }
}
Posted by 1010
98..Etc/velocity2010. 2. 19. 18:03
반응형
import java.io.StringWriter;

import java.util.List;
import java.util.ArrayList;
import java.util.Map;
import java.util.HashMap;

import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.VelocityEngine;

public class EmailDemo
{
    public static void main( String[] args )
        throws Exception
    {
        /*
         *   first, get and initialize an engine
         */

        VelocityEngine ve = new VelocityEngine();
        ve.init();

        /*
         *   organize our data
         */

        ArrayList list = new ArrayList();
        Map map = new HashMap();

        map.put("name", "Cow");
        map.put("price", "$100.00");
        list.add( map );
 
        map = new HashMap();
        map.put("name", "Eagle");
        map.put("price", "$59.99");
        list.add( map );

        map = new HashMap();
        map.put("name", "Shark");
        map.put("price", "$3.99");
        list.add( map );

        /*
         *  add that list to a VelocityContext
         */

        VelocityContext context = new VelocityContext();
        context.put("petList", list);

        /*
         *   get the Template  
         */

        Template t = ve.getTemplate( "./src/email_html.vm" );

        /*
         *  now render the template into a Writer, here
         *  a StringWriter
         */

        StringWriter writer = new StringWriter();

        t.merge( context, writer );

        /*
         *  use the output in the body of your emails
         */

        System.out.println( writer.toString() );
    }
}

-------------------------------------------------------------------------------------

  <HTML>
    <HEAD>
      <TITLE>Pet Store Sale!</TITLE>
    </HEAD>


    <BODY>
      <CENTER>
      <B>$petList.size() Pets on Sale!</B>
     
      <BR/>
      This is an email generated by velocity
      <BR/>
      This month only, choose from :
   
      #set( $count = 1 )  
      <TABLE>
        #foreach( $pet in $petList )
          <TR>
            <TD>$count)</TD>
            <TD>$pet.name</TD>
            <TD>$pet.price</TD>
          </TR>
          #set( $count = $count + 1 )
        #end
      </TABLE>
     
     <I>Call Today!</I>
     Bests <br>
     www.java2s.com
      </CENTER>
 
    </BODY>
  </HTML>


Posted by 1010
98..Etc/velocity2010. 2. 19. 18:01
반응형
-------------------------------------------------------------------------------------

import java.io.StringWriter;
import java.io.Writer;

import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.Velocity;

public class ContextChaining {

  public static void main(String[] args) throws Exception {
    Velocity.init();

    Template template = Velocity.getTemplate("./src/ContextChaining.vm");

    VelocityContext context1 = new VelocityContext();
    VelocityContext context2 = new VelocityContext(context1);

    context1.put("firstName", "Joe");
    context2.put("lastName", "Wang");

    Writer writer = new StringWriter();
    template.merge(context2, writer);

    System.out.println(writer.toString());
  }
}
-------------------------------------------------------------------------------------
This is my first name $firstName
This is my last name $lastName

Full Name is $firstName $lastName

Posted by 1010
01.JAVA/Java2010. 2. 19. 17:58
반응형
public class Main {
  public static void main(String[] argv) throws Exception {

    boolean retval = false;
    String date = "12/12/1212";
    String datePattern = "\\d{1,2}-\\d{1,2}-\\d{4}";
    retval = date.matches(datePattern);

  }
}
Posted by 1010
01.JAVA/Java2010. 2. 19. 17:54
반응형
import java.io.*;
import javax.mail.*;
import javax.mail.internet.*;
import javax.activation.*;

public class SendApp {
  public static void send(String smtpHost, int smtpPort, String from, String to, String subject,
      String content) throws AddressException, MessagingException {

    java.util.Properties props = new java.util.Properties();
    props.put("mail.smtp.host", smtpHost);
    props.put("mail.smtp.port", "" + smtpPort);
    Session session = Session.getDefaultInstance(props, null);

    Message msg = new MimeMessage(session);
    msg.setFrom(new InternetAddress(from));
    msg.setRecipient(Message.RecipientType.TO, new InternetAddress(to));
    msg.setSubject(subject);
    msg.setText(content);

    Transport.send(msg);
  }

  public static void main(String[] args) throws Exception {
    send("hostname", 25, "j@s.com", "s@s.com", "re: dinner", "body");
  }
}
Posted by 1010
01.JAVA/Java2010. 2. 19. 17:46
반응형

import java.io.File;
import java.io.FileReader;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;

public class Main {
  private static String url = "jdbc:oracle:thin:@localhost:1521:xe";

  private static String username = "yourDatabase";

  private static String password = "welcome";

  public static void main(String[] args) throws Exception {

    Class.forName("oracle.jdbc.driver.OracleDriver");
    Connection conn = DriverManager.getConnection(url, username, password);
    conn.setAutoCommit(false);

    String sql = "INSERT INTO documents (name, description, data) VALUES (?, ?, ?)";
    PreparedStatement stmt = conn.prepareStatement(sql);
    stmt.setString(1, "a.txt");
    stmt.setString(2, "b");

    File data = new File("C:\\a.txt");
    FileReader reader = new FileReader(data);
    stmt.setCharacterStream(3, reader, (int) data.length());
    stmt.execute();

    conn.commit();
    reader.close();
    conn.close();

  }
}
Posted by 1010
01.JAVA/Java2010. 2. 19. 17:45
반응형
import java.io.File;
import java.io.FileWriter;
import java.io.Reader;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

public class Main {
  private static String url = "jdbc:oracle:thin:@localhost:1521:javaDemo";

  private static String username = "java";

  private static String password = "welcome";

  public static void main(String[] args) throws Exception {
    Class.forName("oracle.jdbc.driver.OracleDriver");
    Connection conn = DriverManager.getConnection(url, username, password);
    PreparedStatement stmt = conn.prepareStatement("SELECT name, description, data FROM documents ");
    ResultSet resultSet = stmt.executeQuery();
    while (resultSet.next()) {
      String name = resultSet.getString(1);
      String description = resultSet.getString(2);
      File data = new File("C:\\a.txt");
      Reader reader = resultSet.getCharacterStream(3);
      FileWriter writer = new FileWriter(data);
      char[] buffer = new char[1];
      while (reader.read(buffer) > 0) {
        writer.write(buffer);
      }
      writer.close();
    }
    conn.close();
  }
}

   
   
Posted by 1010
01.JAVA/Java2010. 2. 19. 17:44
반응형
/*

MySQL and Java Developer's Guide


Mark Matthews, Jim Cole, Joseph D. Gradecki
Publisher Wiley,
Published February 2003,
ISBN 0471269239

*/


import java.awt.Container;
import java.awt.FlowLayout;
import java.awt.Graphics2D;
import java.awt.GridLayout;
import java.awt.Image;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.awt.geom.AffineTransform;
import java.awt.image.BufferedImage;
import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.sql.Blob;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.Timestamp;
import java.util.Vector;

import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;

public class IDlookGetStream extends JFrame {

  private JButton getAccountButton, updateAccountButton, insertAccountButton,
      nextButton, previousButton, lastButton, firstButton;

  private JList accountNumberList;

  private JTextField accountIDText, nailFileText, thumbIDText;

  private JTextArea errorText;

  private Connection connection;

  private Statement statement;

  private ResultSet rs;

  private ImageIcon icon = null;

  private ImageIcon iconThumbnail = null;

  JLabel photographLabel;

  public IDlookGetStream() {
    try {
      Class.forName("com.mysql.jdbc.Driver").newInstance();
    } catch (Exception e) {
      System.err.println("Unable to find and load driver");
      System.exit(1);
    }
  }

  private void loadAccounts() {
    Vector v = new Vector();
    try {
      rs = statement.executeQuery("SELECT * FROM thumbnail");

      while (rs.next()) {
        v.addElement(rs.getString("acc_id"));
      }
    } catch (SQLException e) {
      displaySQLErrors(e);
    }
    accountNumberList.setListData(v);
  }

  private void buildGUI() {
    Container c = getContentPane();
    c.setLayout(new FlowLayout());

    accountNumberList = new JList();
    loadAccounts();
    accountNumberList.setVisibleRowCount(2);
    JScrollPane accountNumberListScrollPane = new JScrollPane(
        accountNumberList);

    //Do Get Account Button
    getAccountButton = new JButton("Get Account");
    getAccountButton.addActionListener(new ActionListener() {
      public void actionPerformed(ActionEvent e) {
        try {
          rs.beforeFirst();
          while (rs.next()) {
            if (rs.getString("acc_id").equals(
                accountNumberList.getSelectedValue()))
              break;
          }
          if (!rs.isAfterLast()) {
            accountIDText.setText(rs.getString("acc_id"));
            thumbIDText.setText(rs.getString("thumb_id"));
            Blob blob = rs.getBlob("pic");

            int b;
            InputStream bis = rs.getBinaryStream("pic");
            FileOutputStream f = new FileOutputStream("pic.jpg");
            while ((b = bis.read()) >= 0) {
              f.write(b);
            }
            f.close();
            bis.close();

            icon = new ImageIcon(blob.getBytes(1L, (int) blob
                .length()));
            createThumbnail();
            photographLabel.setIcon(iconThumbnail);
          }
        } catch (Exception selectException) {
          displaySQLErrors(selectException);
        }
      }
    });

    //Do Update Account Button
    updateAccountButton = new JButton("Update Account");
    updateAccountButton.addActionListener(new ActionListener() {
      public void actionPerformed(ActionEvent e) {
        try {
          byte[] bytes = new byte[50000];
          FileInputStream fs = new FileInputStream(nailFileText
              .getText());
          BufferedInputStream bis = new BufferedInputStream(fs);
          bis.read(bytes);

          rs.updateBytes("thumbnail.pic", bytes);
          rs.updateRow();
          bis.close();

          accountNumberList.removeAll();
          loadAccounts();
        } catch (SQLException insertException) {
          displaySQLErrors(insertException);
        } catch (Exception generalE) {
          generalE.printStackTrace();
        }
      }
    });

    //Do insert Account Button
    insertAccountButton = new JButton("Insert Account");
    insertAccountButton.addActionListener(new ActionListener() {
      public void actionPerformed(ActionEvent e) {
        try {
          byte[] bytes = new byte[50000];
          FileInputStream fs = new FileInputStream(nailFileText
              .getText());
          BufferedInputStream bis = new BufferedInputStream(fs);
          bis.read(bytes);

          rs.moveToInsertRow();
          rs.updateInt("thumb_id", Integer.parseInt(thumbIDText
              .getText()));
          rs.updateInt("acc_id", Integer.parseInt(accountIDText
              .getText()));
          rs.updateBytes("pic", bytes);
          rs.updateObject("sysobject", null);
          rs.updateTimestamp("ts", new Timestamp(0));
          rs.updateTimestamp("act_ts", new Timestamp(
              new java.util.Date().getTime()));
          rs.insertRow();
          bis.close();

          accountNumberList.removeAll();
          loadAccounts();
        } catch (SQLException insertException) {
          displaySQLErrors(insertException);
        } catch (Exception generalE) {
          generalE.printStackTrace();
        }
      }
    });

    photographLabel = new JLabel();
    photographLabel.setHorizontalAlignment(JLabel.CENTER);
    photographLabel.setVerticalAlignment(JLabel.CENTER);
    photographLabel.setVerticalTextPosition(JLabel.CENTER);
    photographLabel.setHorizontalTextPosition(JLabel.CENTER);

    JPanel first = new JPanel(new GridLayout(4, 1));
    first.add(accountNumberListScrollPane);
    first.add(getAccountButton);
    first.add(updateAccountButton);
    first.add(insertAccountButton);

    accountIDText = new JTextField(15);
    thumbIDText = new JTextField(15);
    errorText = new JTextArea(5, 15);
    errorText.setEditable(false);

    JPanel second = new JPanel();
    second.setLayout(new GridLayout(2, 1));
    second.add(thumbIDText);
    second.add(accountIDText);

    JPanel third = new JPanel();
    third.add(new JScrollPane(errorText));

    nailFileText = new JTextField(25);

    c.add(first);
    c.add(second);
    c.add(third);
    c.add(nailFileText);
    c.add(photographLabel);

    setSize(500, 500);
    show();
  }

  public void connectToDB() {
    try {
      connection = DriverManager
          .getConnection("jdbc:mysql://192.168.1.25/identification?user=spider&password=spider");
      statement = connection.createStatement(
          ResultSet.TYPE_SCROLL_INSENSITIVE,
          ResultSet.CONCUR_UPDATABLE);

    } catch (SQLException connectException) {
      System.out.println(connectException.getMessage());
      System.out.println(connectException.getSQLState());
      System.out.println(connectException.getErrorCode());
      System.exit(1);
    }
  }

  private void displaySQLErrors(Exception e) {
    errorText.append("Exception: " + e.getMessage() + "\n");
    //    errorText.append("State: " + e.getSQLState() + "\n");
    //  errorText.append("VendorError: " + e.getErrorCode() + "\n");
  }

  private void init() {
    connectToDB();
  }

  private void createThumbnail() {
    int maxDim = 350;
    try {
      Image inImage = icon.getImage();

      double scale = (double) maxDim / (double) inImage.getHeight(null);
      if (inImage.getWidth(null) > inImage.getHeight(null)) {
        scale = (double) maxDim / (double) inImage.getWidth(null);
      }

      int scaledW = (int) (scale * inImage.getWidth(null));
      int scaledH = (int) (scale * inImage.getHeight(null));

      BufferedImage outImage = new BufferedImage(scaledW, scaledH,
          BufferedImage.TYPE_INT_RGB);

      AffineTransform tx = new AffineTransform();

      if (scale < 1.0d) {
        tx.scale(scale, scale);
      }

      Graphics2D g2d = outImage.createGraphics();
      g2d.drawImage(inImage, tx, null);
      g2d.dispose();

      iconThumbnail = new ImageIcon(outImage);
    } catch (Exception e) {
      e.printStackTrace();
    }
  }

  public static void main(String[] args) {
    IDlookGetStream id = new IDlookGetStream();

    id.addWindowListener(new WindowAdapter() {
      public void windowClosing(WindowEvent e) {
        System.exit(0);
      }
    });

    id.init();
    id.buildGUI();
  }
}

Posted by 1010
반응형
/*

Database Programming with JDBC and Java, Second Edition

By George Reese
ISBN: 1-56592-616-1

Publisher: O'Reilly

*/


import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.sql.Blob;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

/**
 * Example 4.2.
 */
public class Blobs {
  public static void main(String args[]) {
    if (args.length != 1) {
      System.err.println("Syntax: <java Blobs [driver] [url] "
          + "[uid] [pass] [file]");
      return;
    }
    try {
      Class.forName(args[0]).newInstance();
      Connection con = DriverManager.getConnection(args[1], args[2],
          args[3]);
      File f = new File(args[4]);
      PreparedStatement stmt;

      if (!f.exists()) {
        // if the file does not exist
        // retrieve it from the database and write it to the named file
        ResultSet rs;

        stmt = con.prepareStatement("SELECT blobData "
            + "FROM BlobTest " + "WHERE fileName = ?");

        stmt.setString(1, args[0]);
        rs = stmt.executeQuery();
        if (!rs.next()) {
          System.out.println("No such file stored.");
        } else {
          Blob b = rs.getBlob(1);
          BufferedOutputStream os;

          os = new BufferedOutputStream(new FileOutputStream(f));
          os.write(b.getBytes(0, (int) b.length()), 0, (int) b
              .length());
          os.flush();
          os.close();
        }
      } else {
        // otherwise read it and save it to the database
        FileInputStream fis = new FileInputStream(f);
        byte[] tmp = new byte[1024];
        byte[] data = null;
        int sz, len = 0;

        while ((sz = fis.read(tmp)) != -1) {
          if (data == null) {
            len = sz;
            data = tmp;
          } else {
            byte[] narr;
            int nlen;

            nlen = len + sz;
            narr = new byte[nlen];
            System.arraycopy(data, 0, narr, 0, len);
            System.arraycopy(tmp, 0, narr, len, sz);
            data = narr;
            len = nlen;
          }
        }
        if (len != data.length) {
          byte[] narr = new byte[len];

          System.arraycopy(data, 0, narr, 0, len);
          data = narr;
        }
        stmt = con.prepareStatement("INSERT INTO BlobTest(fileName, "
            + "blobData) VALUES(?, ?)");
        stmt.setString(1, args[0]);
        stmt.setObject(2, data);
        stmt.executeUpdate();
        f.delete();
      }
      con.close();
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
}

           

Posted by 1010
반응형
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

public class DemoDisplayBinaryDataFromDatabase {

  public static Connection getConnection() throws Exception {
    String driver = "oracle.jdbc.driver.OracleDriver";
    String url = "jdbc:oracle:thin:@localhost:1521:databaseName";
    String username = "name";
    String password = "password";
    Class.forName(driver);
    Connection conn = DriverManager.getConnection(url, username, password);
    return conn;
  }

  public static void main(String args[]) throws Exception {
    Connection conn = null;
    ResultSet rs = null;
    PreparedStatement pstmt = null;
    String query = "SELECT raw_column, long_raw_column FROM binary_table WHERE id = ?";
    try {
      conn = getConnection();
      Object[] results = new Object[2];
      pstmt = conn.prepareStatement(query);
      pstmt.setString(1, "0001");
      rs = pstmt.executeQuery();
      rs.next();
      // materialize binary data onto client
      results[0] = rs.getBytes("RAW_COLUMN");
      results[1] = rs.getBytes("LONG_RAW_COLUMN");
    } finally {
      rs.close();
      pstmt.close();
      conn.close();
    }
  }
}

Posted by 1010
반응형

import java.io.File;
import java.io.FileInputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;

public class Main {
  static String url = "jdbc:oracle:thin:@localhost:1521:javaDemo";
  static String username = "username";
  static String password = "welcome";

  public static void main(String[] args) throws Exception {
    Class.forName("oracle.jdbc.driver.OracleDriver");
    Connection conn = DriverManager.getConnection(url, username, password);
    conn.setAutoCommit(false);

    String sql = "INSERT INTO pictures (name, description, image) VALUES (?, ?, ?)";
    PreparedStatement stmt = conn.prepareStatement(sql);
    stmt.setString(1, "java.gif");
    stmt.setString(2, "Java Official Logo");

    File image = new File("D:\\a.gif");
    FileInputStream   fis = new FileInputStream(image);
    stmt.setBinaryStream(3, fis, (int) image.length());
    stmt.execute();

    conn.commit();
    fis.close();
    conn.close();
  }
}

Posted by 1010
반응형

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

public class Main {
  static String url = "jdbc:oracle:thin:@localhost:1521:javaDemo";
  static String username = "username";
  static String password = "welcome";
  public static void main(String[] args) throws Exception {
    Class.forName("oracle.jdbc.driver.OracleDriver");
    Connection conn = DriverManager.getConnection(url, username, password);

    String sql = "SELECT name, description, image FROM pictures ";
    PreparedStatement stmt = conn.prepareStatement(sql);
    ResultSet resultSet = stmt.executeQuery();
    while (resultSet.next()) {
      String name = resultSet.getString(1);
      String description = resultSet.getString(2);
      File image = new File("D:\\java.gif");
      FileOutputStream fos = new FileOutputStream(image);

      byte[] buffer = new byte[1];
      InputStream is = resultSet.getBinaryStream(3);
      while (is.read(buffer) > 0) {
        fos.write(buffer);
      }
      fos.close();
    }
    conn.close();
  }
}

   

Posted by 1010
반응형
import org.apache.commons.dbutils.DbUtils;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanListHandler;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

import java.util.List;

public class DbUtilsUseBeanMySQL {
  public static void main(String[] args) {
    Connection conn = null;
    String jdbcURL = "jdbc:mysql://localhost/octopus";
    String jdbcDriver = "com.mysql.jdbc.Driver";
    String user = "root";
    String password = "root";

    try {
      DbUtils.loadDriver(jdbcDriver);
      conn = DriverManager.getConnection(jdbcURL, user, password);

      QueryRunner qRunner = new QueryRunner();
      List beans = (List) qRunner.query(conn, "select id, name from animals_table",
          new BeanListHandler(Employee.class));

      for (int i = 0; i < beans.size(); i++) {
        Employee bean = (Employee) beans.get(i);
        bean.print();
      }
    } catch (SQLException e) {
      // handle the exception
      e.printStackTrace();
    } finally {
      DbUtils.closeQuietly(conn);
    }
  }
}

class Employee {

  private int id;
  private String name;

  public Employee() {
  }

  public void setName(String name) {
      this.name = name;
  }

  public String getName() {
      return this.name;
  }

  public void setId(int id) {
      this.id = id;
  }

  public int getId() {
      return this.id;
  }

  public void print() {
      System.out.println("id="+id+" name="+name);
  }
}


Posted by 1010
반응형
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpVersion;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.HostConfiguration;

public class HttpClientParameter {

  public static void main(String args[]) throws Exception {

    HttpClient client = new HttpClient();
    client.getParams().setParameter("http.useragent", "My Browser");

    HostConfiguration host = client.getHostConfiguration();
    host.setHost("www.google.com");

    GetMethod method = new GetMethod("http://www.yahoo.com");

    int returnCode = client.executeMethod(host, method);

    System.err.println(method.getResponseBodyAsString());

    System.err.println("User-Agent: " + method.getHostConfiguration().getParams().getParameter("http.useragent"));

    System.err.println("User-Agent: " + method.getParams().getParameter("http.useragent"));

    method.releaseConnection();
  }
}

Posted by 1010
반응형
import org.apache.commons.httpclient.URI;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.HostConfiguration;

import org.apache.commons.httpclient.protocol.Protocol;

import java.io.File;
import java.io.IOException;
import java.io.FileOutputStream;

public class GetMethodExample {

  public static void main(String args[]) {

    HttpClient client = new HttpClient();
    client.getParams().setParameter("http.useragent", "Test Client");
    client.getParams().setParameter("http.connection.timeout",new Integer(5000));

    GetMethod method  = new GetMethod();
    FileOutputStream fos = null;

    try {

      method.setURI(new URI("http://www.google.com", true));
      int returnCode = client.executeMethod(method);

      if(returnCode != HttpStatus.SC_OK) {
        System.err.println(
          "Unable to fetch default page, status code: " + returnCode);
      }

      System.err.println(method.getResponseBodyAsString());

      method.setURI(new URI("http://www.google.com/images/logo.gif", true));
      returnCode = client.executeMethod(method);

      if(returnCode != HttpStatus.SC_OK) {
        System.err.println("Unable to fetch image, status code: " + returnCode);
      }

      byte[] imageData = method.getResponseBody();
      fos = new FileOutputStream(new File("google.gif"));
      fos.write(imageData);

      HostConfiguration hostConfig = new HostConfiguration();
      hostConfig.setHost("www.yahoo.com", null, 80, Protocol.getProtocol("http"));

      method.setURI(new URI("/", true));

      client.executeMethod(hostConfig, method);

      System.err.println(method.getResponseBodyAsString());

    } catch (HttpException he) {
      System.err.println(he);
    } catch (IOException ie) {
      System.err.println(ie);
    } finally {
      method.releaseConnection();
      if(fos != null) try { fos.close(); } catch (Exception fe) {}
    }

  }
}

Posted by 1010
반응형
import org.apache.commons.lang.exception.ExceptionUtils;
import org.apache.commons.lang.exception.NestableException;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;

public class ExceptionUtilsV1 {
  public static void main(String args[]) {
    try {
      loadFile();
    } catch(Exception e) {
      e.printStackTrace();
    }
  }

  public static void loadFile() throws Exception {
    try {
      FileInputStream fis =
       new FileInputStream(new File("nosuchfile"));
    } catch (FileNotFoundException fe) {
      throw new NestableException(fe);
    }
  }
}
Posted by 1010
반응형
import org.apache.commons.beanutils.BeanUtils;

import java.util.Map;
import java.util.Date;
import java.util.List;
import java.util.HashMap;
import java.util.ArrayList;
import java.util.GregorianCalendar;

public class BeanUtilsExampleV2 {
  public static void main(String args[]) throws Exception {
    BeanUtilsExampleV2 diff = new BeanUtilsExampleV2();
    Movie movieBean = diff.prepareData();

    // create a new Movie with the same properties
    Movie newMovieBean = new Movie();
    BeanUtils.copyProperties(newMovieBean, movieBean);
    // Movie newMovieBean = (Movie)BeanUtils.cloneBean(movieBean);

    // change its title
    BeanUtils.setProperty(newMovieBean, "title", "Quills");

    // and date
    BeanUtils.setProperty(
      newMovieBean,
      "dateOfRelease",
      new GregorianCalendar(2000, 0, 1).getTime());

    // and director name
    BeanUtils.setProperty(newMovieBean, "director.name", "Philip Kaufman");

    // and director's home number
    BeanUtils.setProperty(
      newMovieBean,
      "director.contactNumber(Home)",
      "3349084333");

    System.err.println(BeanUtils.getProperty(movieBean, "title"));
    System.err.println(BeanUtils.getProperty(movieBean, "director.name"));
    System.err.println(BeanUtils.getProperty(
      newMovieBean,
      "director.contactNumber(Home)"));
  }

  private Movie prepareData() {
    Movie movie = new Movie();
    movie.setTitle("The Italian Job");
    movie.setDateOfRelease(new GregorianCalendar(1969, 0, 1).getTime());

    // sets the genre
    Map genre_map = new HashMap();
    genre_map.put("THR", "Thriller");
    genre_map.put("ACT", "Action");

    movie.setGenre(genre_map);

    // creates the Director
    Person director = new Person();
    director.setName("Peter Collinson");
    director.setGender(1);
    Map director_contacts = new HashMap();
    director_contacts.put("Home", "99922233");
    director_contacts.put("Mobile", "0343343433");
    director.setContactNumber(director_contacts);

    movie.setDirector(director);

    // create the actors
    Actor actor1 = new Actor();
    actor1.setName("Michael Caine");
    actor1.setGender(1);
    actor1.setWorth(10000000);
    List actor1_movies = new ArrayList();

    Movie movie2 = new Movie();
    movie2.setTitle("The Fourth Protocol");

    Movie movie3 = new Movie();
    movie3.setTitle("Shiner");

    actor1_movies.add(movie2);
    actor1_movies.add(movie3);

    actor1.setMovieCredits(actor1_movies);

    Actor actor2 = new Actor();
    actor2.setName("Margaret Blye");
    actor2.setGender(2);
    actor2.setWorth(20000000);

    List actors = new ArrayList();
    actors.add(actor1);
    actors.add(actor2);

    movie.setActors(actors);

    return movie;
  }
}
----------------------------------------------------------------------------


import java.util.List;

public class Actor extends Person {
  public Actor() {
  }

  public List getMovieCredits() { return this.movieCredits; }
  public void setMovieCredits(List movieCredits) {
    this.movieCredits = movieCredits;
  }

  public long getWorth() { return this.worth; }
  public void setWorth(long worth) { this.worth = worth; }

  private List movieCredits;
  private long worth;
}
----------------------------------------------------------------------------



import java.util.Map;
import java.util.List;
import java.util.Date;

public class Movie {
  public Movie() {
  }

  public Date getDateOfRelease() { return this.dateOfRelease; }
  public void setDateOfRelease(Date dateOfRelease) {
    this.dateOfRelease = dateOfRelease;
  }

  public String getTitle() { return this.title; }
  public void setTitle(String title) {this.title = title; }

  public Person getDirector() { return this.director; }
  public void setDirector(Person director) { this.director = director; }

  public List getActors() { return this.actors; }
  public void setActors(List actors) { this.actors= actors; }

  public String[] getKeywords() { return this.keywords; }
  public void setKeyWords(String[] keywords) { this.keywords = keywords; }

  public Map getGenre() { return this.genre; }
  public void setGenre(Map genre) { this.genre = genre; }

  private Date dateOfRelease;
  private String title;
  private Person director;

  private List actors;
  private String[] keywords;

  private Map genre;
}
----------------------------------------------------------------------------


import java.util.Map;

import org.apache.commons.lang.builder.EqualsBuilder;
import org.apache.commons.lang.builder.HashCodeBuilder;
import org.apache.commons.lang.builder.ToStringBuilder;

public class Person {
  public Person() {
  }

  public String getName() {
    return this.name == null ? "NoName" : this.name; }
  public void setName(String name) { this.name = name; }

  public int getGender() { return this.gender; }
  public void setGender(int gender) {  // 0 - Indeterminate, 1 - Male, 2 - Female
    this.gender = (gender > 2 || gender < 0) ? 0 : gender; }

  public Map getContactNumber() { return this.contactNumber; }
  public void setContactNumber(Map contactNumber) {
    this.contactNumber = contactNumber;
  }

  /**public boolean equals(Object o) {
    if(o == this) return true;
    if(!(o instanceof Person)) return false;
    Person otherPerson = (Person)o;
    if(otherPerson.getName().equals(this.name) &&
       otherPerson.getGender() == this.gender) return true;

    return false;
  }*/

  public boolean equals(Object o) {
    if(!(o instanceof Person)) return false;

    Person otherPerson = (Person)o;
    return new EqualsBuilder()
               .append(name, otherPerson.getName())
               .append(gender, otherPerson.getGender())
               .isEquals();
  }

  public int hashCode() {
    return new HashCodeBuilder(7, 51)
               .append(name)
               .append(gender)
               .append(contactNumber)
               .toHashCode();
  }

  public String toString() {
    return new ToStringBuilder(this)
               .append("Name", name)
               .append("Gender", gender)
               .append("Contact Details", contactNumber)
               .toString();
  }

  private String name;
  private int gender;
  private Map contactNumber;
}
           

Posted by 1010
반응형
import org.apache.commons.dbcp.BasicDataSource;

import org.apache.commons.beanutils.DynaBean;
import org.apache.commons.beanutils.RowSetDynaClass;

import java.util.Iterator;
import java.sql.ResultSet;
import java.sql.Connection;
import java.sql.PreparedStatement;

public class DynaBeansExampleV3 {
  public static void main(String args[]) throws Exception {

    Connection conn = getConnection();
    PreparedStatement ps =
      conn.prepareStatement(
        "SELECT * from movie, person " +
        "WHERE movie.director = person.Id");
    ResultSet rs = ps.executeQuery();

    RowSetDynaClass rsdc = new RowSetDynaClass(rs);

    conn.close();

    Iterator itr = rsdc.getRows().iterator();
    while(itr.hasNext()) {
      DynaBean bean = (DynaBean)itr.next();
      System.err.println(bean.get("title"));
    }


  }

  private static Connection getConnection() throws Exception {
    BasicDataSource bds = new BasicDataSource();
    bds.setDriverClassName("com.mysql.jdbc.Driver");
    bds.setUrl("jdbc:mysql://localhost/commons");
    bds.setUsername("root");
    bds.setPassword("");

//    bds.setInitialSize(5);

    return bds.getConnection();
  }
}
           
Posted by 1010
반응형
import org.apache.commons.dbcp.BasicDataSource;

import org.apache.commons.beanutils.DynaBean;
import org.apache.commons.beanutils.ResultSetDynaClass;

import java.util.Iterator;
import java.sql.ResultSet;
import java.sql.Connection;
import java.sql.PreparedStatement;

public class DynaBeansExampleV2 {
  public static void main(String args[]) throws Exception {

    Connection conn = getConnection();
    PreparedStatement ps =  conn.prepareStatement("SELECT * from movie, person " +
                                      "WHERE movie.director = person.Id");
    ResultSet rs = ps.executeQuery();

    ResultSetDynaClass rsdc = new ResultSetDynaClass(rs);

    Iterator itr = rsdc.iterator();
    while(itr.hasNext()) {
      DynaBean bean = (DynaBean)itr.next();
      System.err.println(bean.get("title"));
    }

    conn.close();
  }

  private static Connection getConnection() throws Exception {
    BasicDataSource bds = new BasicDataSource();
    bds.setDriverClassName("com.mysql.jdbc.Driver");
    bds.setUrl("jdbc:mysql://localhost/commons");
    bds.setUsername("root");
    bds.setPassword("");

    //bds.setInitialSize(5);

    return bds.getConnection();
  }
}

Posted by 1010
반응형
import org.apache.commons.pool.impl.GenericObjectPool;
import org.apache.commons.dbcp.*;

import java.sql.*;


public class DBCPDemo{

  public static void main(String args[]) throws Exception{

    // create a generic pool
    GenericObjectPool pool = new GenericObjectPool(null);

    // use the connection factory which will wraped by
    // the PoolableConnectionFactory
    DriverManagerConnectionFactory cf =  new DriverManagerConnectionFactory(
                                            "jdbc:jtds:sqlserver://myserver:1433/tandem",
                                            "user",
                                            "pass");

    PoolableConnectionFactory pcf =  new PoolableConnectionFactory(cf, pool, null, "SELECT * FROM mysql.db", false, true);

    // register our pool and give it a name
    new PoolingDriver().registerPool("myPool", pool);

    // get a connection and test it
        Connection conn = DriverManager.getConnection("jdbc:apache:commons:dbcp:myPool");

        // now we can use this pool the way we want.
        System.err.println("Are we connected? " + !conn.isClosed());

        System.err.println("Idle Connections: " + pool.getNumIdle() + ", out of " + pool.getNumActive());

  }
}

Posted by 1010
반응형
import java.sql.Connection;

import org.apache.commons.dbcp.BasicDataSource;

public class BasicDataSourceExample {

  public static void main(String args[]) throws Exception {

    BasicDataSource bds = new BasicDataSource();
    bds.setDriverClassName("com.mysql.jdbc.Driver");
    bds.setUrl("jdbc:mysql://localhost/commons");
    bds.setUsername("root");
    bds.setPassword("");

//    bds.setInitialSize(5);

    Connection connection = bds.getConnection();

    System.err.println(connection);
    connection.close();
  }
}
Posted by 1010
반응형


package com.googelcode.jpractices.common;

import org.apache.commons.lang.builder.ToStringBuilder;

/**
 * Copyright 2009 @ jPractices v 1.0
 * @SVN URL : http://jpractices.googlecode.com
 * @author Ganesh Gowtham
 * @Homepage : http://ganesh.gowtham.googlepages.com
 */

public class Person {
  private String firstName;

  private String lastName;

  private int salary;

  public Person(String firstName, String lastName, int salary) {
    super();
    this.firstName = firstName;
    this.lastName = lastName;
    this.salary = salary;
  }

  public String getFirstName() {
    return firstName;
  }

  public void setFirstName(String firstName) {
    this.firstName = firstName;
  }

  public String getLastName() {
    return lastName;
  }

  public void setLastName(String lastName) {
    this.lastName = lastName;
  }

  public int getSalary() {
    return salary;
  }

  public void setSalary(int salary) {
    this.salary = salary;
  }

  @Override
  public String toString() {
    return ToStringBuilder.reflectionToString(this);
  }
}
-------------
package com.googelcode.jpractices;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

import org.apache.commons.beanutils.BeanComparator;

import com.googelcode.jpractices.common.Person;
/**
 * Copyright 2009 @ jPractices v 1.0
 * @SVN URL : http://jpractices.googlecode.com
 * @author Ganesh Gowtham
 * @Homepage : http://ganesh.gowtham.googlepages.com
 */
public class BeanComparatorExample {
  List<Person> personList = new ArrayList<Person>();

  /**
   * Basic method which creates the list of person object's
   *
   */
  void setUpData() {
    personList.add(new Person("jennefer", "gowtham", 35000));
    personList.add(new Person("britney", "spears", 45000));
    personList.add(new Person("tom", "gowtham", 36000));
    personList.add(new Person("joe", "dummy", 45000));
  }
  void sortPersons(String propertyName)
  {
    Comparator<Person> comp = new BeanComparator(propertyName);
    Collections.sort(personList, comp);
    for (Person person : personList) {
      System.out.println(person);
    }
  }
  public static void main(String[] args) {
    BeanComparatorExample beanComparatorExample = new BeanComparatorExample();
    beanComparatorExample.setUpData();
    beanComparatorExample.sortPersons("firstName");
  }
}

   
   

Posted by 1010
반응형
import org.apache.commons.collections.set.MapBackedSet;

import java.util.Map;
import java.util.Set;
import java.util.HashMap;
import java.util.Iterator;

public class SetExampleV1 {
  public static void main(String args[]) {
    // create a Map
    Map map = new HashMap();
    map.put("Key1", "Value1");

    // create the decoration
    Set set = MapBackedSet.decorate(map);

    map.put("Key2", "Any dummy value");
    set.add("Key3");

    Iterator itr = set.iterator();

    while(itr.hasNext()) {
      System.err.println(itr.next());
    }

  }
}
Posted by 1010
반응형
import org.apache.commons.collections.list.TreeList;
import org.apache.commons.collections.list.SetUniqueList;
import org.apache.commons.collections.list.CursorableLinkedList;

import java.util.List;
import java.util.ListIterator;

public class ListExampleV1 {
  public static void main(String args[]) {
    ListExampleV1 listExample = new ListExampleV1();
    listExample.createLists();

    uniqueList.add("Value1");
    uniqueList.add("Value1");
    System.err.println(uniqueList); // should contain only one element

    cursorList.add("Element1");
    cursorList.add("Element2");
    cursorList.add("Element3");

    ListIterator iterator = cursorList.listIterator();
    iterator.next(); // cursor now between 0th and 1st element
    iterator.add("Element2.5"); // adds this between 0th and 1st element

    System.err.println(cursorList); // modification done to the iterator are visible in the list
  }

  private void createLists() {
    uniqueList = SetUniqueList.decorate(new TreeList());
    cursorList = new CursorableLinkedList();
  }

  private static List uniqueList;
  private static List cursorList;
}
Posted by 1010
반응형
import java.util.HashMap;

public class MultiKeyExampleV1 {
  public static void main(String args[]) {
    HashMap codeToText_en = new HashMap();
    codeToText_en.put("GM", "Good Morning");
    codeToText_en.put("GN", "Good Night");
    codeToText_en.put("GE", "Good Evening");

    HashMap codeToText_de = new HashMap();
    codeToText_de.put("GM", "Guten Morgen");
    codeToText_de.put("GE", "Guten Abend");
    codeToText_de.put("GN", "Guten Nacht");

    HashMap langToMap = new HashMap();
    langToMap.put("en", codeToText_en);
    langToMap.put("de", codeToText_de);

    System.err.println("Good Evening in English: " +
      ((HashMap)langToMap.get("en")).get("GE"));
    System.err.println("Good Night in German: " +
      ((HashMap)langToMap.get("de")).get("GN"));
  }
}
Posted by 1010