반응형
/*

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
반응형
import org.apache.commons.collections.BidiMap;
import org.apache.commons.collections.bidimap.DualHashBidiMap;

public class HashMapExampleV1 {
  public static void main(String args[]) {
    BidiMap agentToCode = new DualHashBidiMap();
    agentToCode.put("007", "Bond");
    agentToCode.put("006", "Trevelyan");
    agentToCode.put("002", "Fairbanks");

    System.err.println("Agent name from code: " + agentToCode.get("007"));
    System.err.println("Code from Agent name: " + agentToCode.getKey("Bond"));
  }
}
Posted by 1010
반응형
import org.apache.commons.collections.Factory;
import org.apache.commons.collections.FactoryUtils;

public class FactoryExampleV1 {
  public static void main(String args[]) {
    Factory bufferFactory = FactoryUtils.instantiateFactory(StringBuffer.class,
                          new Class[] {String.class},
                          new Object[] {"a string"});
    System.err.println(bufferFactory.create());
  }
}
Posted by 1010
반응형
import org.apache.commons.collections.ComparatorUtils;
import org.apache.commons.collections.comparators.BooleanComparator;
import org.apache.commons.collections.comparators.FixedOrderComparator;

import java.util.Arrays;
import java.util.Comparator;

public class ComparatorExampleForBuildInDataType {

  private static Comparator boolComp;
  private static Comparator fixedComp;

  private static Boolean boolParams[] = {new Boolean(true), new Boolean(true),
                                         new Boolean(false), new Boolean(false)};
  private static String  stringParams[] = {"Russia", "Canada", "USA", "Australia", "India"};
 
  public static void main(String args[]) {
    ComparatorExampleForBuildInDataType example = new ComparatorExampleForBuildInDataType();
    example.createComparators();

    Arrays.sort(boolParams, boolComp);

    example.printArray(boolParams);

    Arrays.sort(stringParams);

    example.printArray(stringParams);

    Arrays.sort(stringParams, fixedComp);

    example.printArray(stringParams);
  }

  private void createComparators() {
    boolComp = ComparatorUtils.booleanComparator(true);
    fixedComp = new FixedOrderComparator(stringParams);
  }

  private void printArray(Object[] array) {
    for(int i = 0; i < array.length; i++)
      System.err.println(array[i]);
  }

}
           

Posted by 1010
반응형
import org.apache.commons.collections.BidiMap;
import org.apache.commons.collections.bidimap.DualHashBidiMap;
import org.apache.commons.collections.bidimap.UnmodifiableBidiMap;

public class BidiMapExample {
  public static void main(String args[]) {

    BidiMap agentToCode = new DualHashBidiMap();
    agentToCode.put("007", "Bond");
    agentToCode.put("006", "Joe");

    agentToCode = UnmodifiableBidiMap.decorate(agentToCode);
    agentToCode.put("002", "Fairbanks"); // throws Exception
    agentToCode.remove("007"); // throws Exception
    agentToCode.removeValue("Bond"); // throws Exception
  }
}

Posted by 1010
반응형
import org.apache.commons.collections.Buffer;
import org.apache.commons.collections.buffer.BlockingBuffer;
import org.apache.commons.collections.buffer.PriorityBuffer;

public class BufferExample {
  public static void main(String args[]) {
    Buffer buffer = new PriorityBuffer();

    buffer.add("2");
    buffer.add("1");

    buffer = BlockingBuffer.decorate(buffer);

    buffer.remove();

    System.err.println(buffer);
    buffer.clear();

    AddElementThread runner = new AddElementThread(buffer);
    runner.start();

    buffer.remove();
    System.err.println(buffer);
  }
}

class AddElementThread extends Thread {
  private Buffer buffer;

  public AddElementThread(Buffer buffer) {

    this.buffer = buffer;
  }

  public void run() {
    try {
      sleep(2000);
    } catch (InterruptedException ie) {}

    buffer.add("3");
  }
}

Posted by 1010
반응형
import org.apache.commons.collections.Bag;
import org.apache.commons.collections.bag.HashBag;
import org.apache.commons.collections.bag.TreeBag;

import java.util.Arrays;

public class CookieBagV1 {

  private Bag cookieBag;
  private Bag sortedCookieBag;

  public static void main(String args[]) {
    CookieBagV1 app = new CookieBagV1();
    app.prepareBags();
    app.printBagContents();
    app.addRandomCookies();
    app.printBagContents();
  }

  private void printBagContents() {
    System.err.println("Cookie Bag Contents: " + cookieBag);
    System.err.println("Sorted Cookie Bag Contents: " + sortedCookieBag);
  }

  private void addRandomCookies() {
    int count = (int)(Math.random() * 10);
    int pick  = (int)(Math.random() * 10);
    pick = pick > 6 ? 6 : pick;
    if (count > 5) cookieBag.add(cookieJar[pick], count);
    else sortedCookieBag.add(cookieJar[pick], count);
  }

  private void prepareBags() {
    prepareCookieBag();
    prepareSortedCookieBag();
  }

  private void prepareCookieBag() {
    cookieBag = new HashBag(Arrays.asList(cookieJar));
  }

  private void prepareSortedCookieBag() {
    sortedCookieBag = new TreeBag(Arrays.asList(cookieJar));
  }

  private String[] cookieJar =
    {"Bar", "Drop", "Brownies", "Cut Out", "Molded", "Sliced", "No Bake"};

}
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 BeanUtilsExampleV1 {
  public static void main(String args[]) throws Exception {
    BeanUtilsExampleV1 diff = new BeanUtilsExampleV1();
    Movie movieBean = diff.prepareData();

    System.err.println("Movie Title: " +
      BeanUtils.getProperty(movieBean, "title"));
    System.err.println("Movie Year: " +
      BeanUtils.getProperty(movieBean, "dateOfRelease"));
    System.err.println("Movie Director: " +
      BeanUtils.getProperty(movieBean, "director.name"));
    System.err.println("Movie Director Home Contact: " +
      BeanUtils.getProperty(movieBean, "director.contactNumber(Home)"));
    System.err.println("Movie Genre (Thriller): " +
      BeanUtils.getProperty(movieBean, "genre(THR)"));
    System.err.println("Movie Actor 1 name: " +
      BeanUtils.getProperty(movieBean, "actors[0].name"));
    System.err.println("Movie Actor 1 worth: " +
      BeanUtils.getProperty(movieBean, "actors[0].worth"));
    System.err.println("Movie Actor 1 other movie 1: " +
      BeanUtils.getProperty(movieBean, "actors[0].movieCredits[0].title"));

  }

  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.beanutils.DynaBean;
import org.apache.commons.beanutils.DynaClass;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.beanutils.LazyDynaBean;
import org.apache.commons.beanutils.DynaProperty;
import org.apache.commons.beanutils.BasicDynaClass;

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

public class DynaBeansExampleV1 {
  public static void main(String args[]) throws Exception {
    Object movie = createMovieBean();
    System.err.println(BeanUtils.getProperty(movie, "title"));
    System.err.println(BeanUtils.getProperty(movie, "director.name"));
  }

  private static Object createMovieBean() throws Exception {

    // first create the properties
    DynaProperty properties[] = new DynaProperty[] {
      new DynaProperty("title", String.class),
      new DynaProperty("dateOfRelease", Date.class),
      new DynaProperty("keywords", String[].class),
      new DynaProperty("genre", Map.class),
      new DynaProperty("actors", List.class),
      new DynaProperty("director", DynaBean.class)
    };

    // next using the properties define the class
    DynaClass movieClass = new BasicDynaClass("movie", null, properties);

    // now, with the class, create a new instance
    DynaBean movieBean = movieClass.newInstance();

    // set its properties
    movieBean.set("title", "The Italian Job");
    movieBean.set("dateOfRelease",
      new GregorianCalendar(1969, 0, 1).getTime());
    movieBean.set("keywords", new String[] {"Italy", "Bank Robbery"});

    Map genre = new HashMap();
    genre.put("THR", "Thriller");

    movieBean.set("genre", genre);
    movieBean.set("genre", "ACT", "Action");

    DynaBean director = createPersonBean();
    director.set("name", "Peter Collinson");
    director.set("gender", new Integer(1));

    movieBean.set("director", director);

    return movieBean;
  }

  private static DynaBean createPersonBean() {
    DynaBean person = new LazyDynaBean();
    return person;
  }
}

Posted by 1010
반응형
import org.apache.commons.lang.time.DateUtils;

import java.util.Date;
import java.util.Calendar;
import java.util.Iterator;
import java.util.GregorianCalendar;

public class DateUtilsV1 {
  public static void main(String args[]) {
    GregorianCalendar calendar = new GregorianCalendar(1974, 5, 25, 6, 30, 30);
    Date date = calendar.getTime();

    System.err.println("Original Date: " + date);
    System.err.println("Rounded Date: " + DateUtils.round(date, Calendar.HOUR));
    System.err.println("Truncated Date: " +  DateUtils.truncate(date, Calendar.MONTH));

    Iterator itr = DateUtils.iterator(date, DateUtils.RANGE_WEEK_MONDAY);

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

}
----------------------------------------------------------------------------


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;
}
----------------------------------------------------------------------------


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;
}

Posted by 1010
반응형
import org.apache.commons.beanutils.BeanPredicate;
import org.apache.commons.collections.PredicateUtils;

public class BeanUtilsCollectionsV2 {
  public static void main(String args[]) {
    BeanPredicate predicate =
      new BeanPredicate("title", PredicateUtils.uniquePredicate());

    Movie movie = new Movie();
    movie.setTitle("The Italian Job");

    Movie movie1 = new Movie();
    movie1.setTitle("The Italian Job");

    System.err.println(predicate.evaluate(movie)); // evaluates true
    System.err.println(predicate.evaluate(movie1)); // evaluates false

  }
}

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


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.lang.ArrayUtils;

public class ArrayUtilsExampleV1 {

  public static void main(String args[]) {

    long[] longArray = new long[] {10000, 30, 99};
    String[] stringArray = new String[] {"abc", "def", "fgh"};

    long[] clonedArray = ArrayUtils.clone(longArray);
    System.err.println(
      ArrayUtils.toString((ArrayUtils.toObject(clonedArray))));

    System.err.println(ArrayUtils.indexOf(stringArray, "def"));

    ArrayUtils.reverse(stringArray);
    System.err.println(ArrayUtils.toString(stringArray));
  }
}

Posted by 1010
반응형
import java.util.Map;
import java.util.HashMap;
import java.util.Iterator;
import java.lang.reflect.Method;

import org.apache.commons.collections.Bag;
import org.apache.commons.collections.bag.HashBag;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.beanutils.PropertyUtils;

import org.apache.commons.lang.StringUtils;

public class TasteOfThingsV1 {

  private static Map testMap;
  private static TestBean testBean;

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

    HashBag myBag = new HashBag(testMap.values());

    System.err.println("How many Boxes? " + myBag.getCount("Boxes"));
    myBag.add("Boxes", 5);
    System.err.println("How many Boxes now? " + myBag.getCount("Boxes"));

    Method method =
      testBean.getClass().getDeclaredMethod("getTestMap", new Class[0]);
    HashMap reflectionMap =
      (HashMap)method.invoke(testBean, new Object[0]);
    System.err.println("The value of the 'squ' key using reflection: " +
      reflectionMap.get("squ"));

    String squ = BeanUtils.getMappedProperty(testBean, "testMap", "squ");
    squ = StringUtils.capitalize(squ);

    PropertyUtils.setMappedProperty(testBean, "testMap", "squ", squ);

    System.err.println("The value of the 'squ' key is: " +
      BeanUtils.getMappedProperty(testBean, "testMap", "squ"));

    String box = (String)testMap.get("box");
    String caps =
      Character.toTitleCase(box.charAt(0)) +
      box.substring(1, box.length());
    System.err.println("Capitalizing boxes by Java: " + caps);
  }

  private static void prepareData() {
    testMap = new HashMap();
    testMap.put("box", "boxes");
    testMap.put("squ", "squares");
    testMap.put("rect", "rectangles");
    testMap.put("cir", "circles");

    testBean = new TestBean();
    testBean.setTestMap(testMap);
  }
}

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

import java.util.Map;
import java.util.HashMap;

public class TestBean {
  private Map testMap;

  public Map getTestMap() {
    return this.testMap;
  }
  public void setTestMap(Map testMap) {
    this.testMap = testMap;
  }
}
       
Posted by 1010
반응형

데이터 Validator 체크를 위해서 공통클래스를 만들곤 하는데 이미 만들어진걸

씀으로서 수고를 덜 수 있다.  그게 apache 에서 제공하는 common-validator jar 이다.

이것을 잘 활용한다면 많은 수고를 덜수 있다. 무식하게 만든다고 장땡이는 아니다.

있는걸 활용해서 시간을 업무에 집중할수 있는것도 중요하다.

http://commons.apache.org/validator/index.html

현재 1.3.1 까지 나와있는 상태이다. 그대로 활용해도 되지만

jar 내부에 제공하는 클래스들을 상속받아 좀더 구체적인 로직을 구현해서 사용하는것도

확장성 면에서 고려해볼만하다. 1.3. 에선 xml 검증 엔진도 추가되어있다.


routines 패키지 내에 보면 구체적으로 Validator 체크를 할수 있도록 클래스가 제공된다.

클래스 이름만 봐도 어떤 종류의 데이터를 체크할수 있을지 감이 올것이다.

그리고 제일 위 3개는 Abstract 라는 이름이 붙어있다. 이것은 추상클래스를 나타내며

3개를 제외한 클래스들에서 상속받아 구체적으로 구현한것이다. 그러므로 3개를 제외한

클래스들을 쓰면된다.

 

common-validator API 를 보면 http://commons.apache.org/validator/api-1.3.1/

설명에도 나와있지만 어떤 특정데이타를 다룰때 그 데이타에 해당하는 validator

체크할수 있도록 클래스가 분류 되어있는 것을 볼수있다. 


데이타에 대한 validator 가 아닌 일반적인 체크는 아래 클래스들을 사용하면되는데

보통 Genericvalidator 를 많이 사용한다.


함수예제를 몇가지 추려보면 다음과 같다.

public static boolean isBlankOrNull(String value) : blank or null 체크

public static boolean isByte(String value) : Byte 변환가능한지 여부

public static boolean isShort(String value) : Short 변환가능한지 여부

public static boolean isInRange(byte value, byte min, byte max)

범위지정한 곳에 속하는지에 대한 여부 등등이 있다.

 

함수들을 사용해서 구현한 예제이다.

private static final int ID_CHECK_ID = 2;

   public void validateId(String id){

   if (!GenericValidator.minLength(id, ID_CHECK_ID)){

       throw new IllegalArgumentException("ID 길이가 너무 작습니다");

   }

}


출처 : http://mainia.tistory.com/336?srchid=BR1http%3A%2F%2Fmainia.tistory.com%2F336

Posted by 1010