public static void runTest1() throws Exception {
   boolean exceptionOccured = false;
   try {
     Context ctx = cache.getJNDIContext();
     DataSource ds1 = null;
     DataSource ds2 = null;
     ds1 = (DataSource) ctx.lookup("java:/XAPooledDataSource");
     ds2 = (DataSource) ctx.lookup("java:/SimpleDataSource");
     ds2.getConnection();
     ds1 = (DataSource) ctx.lookup("java:/XAPooledDataSource");
     UserTransaction utx = (UserTransaction) ctx.lookup("java:/UserTransaction");
     utx.begin();
     ds1.getConnection();
     Thread.sleep(8000);
     try {
       utx.commit();
     } catch (Exception e) {
       exceptionOccured = true;
     }
     if (!exceptionOccured)
       fail("Exception did not occur on commit although was supposed" + "occur");
   } catch (Exception e) {
     getLogWriter().fine("Exception caught in runTest1 due to : " + e);
     fail("failed in runTest1 due to " + e);
   }
 }
Exemple #2
0
  public static void main(String[] argv) {
    try {

      String dmds_name = null;
      String cpds_name = null;
      String pbds_name = null;

      if (argv.length == 3) {
        dmds_name = argv[0];
        cpds_name = argv[1];
        pbds_name = argv[2];
      } else usage();

      InitialContext ctx = new InitialContext();
      DataSource dmds = (DataSource) ctx.lookup(dmds_name);
      dmds.getConnection().close();
      System.out.println(
          "DriverManagerDataSource " + dmds_name + " sucessfully looked up and checked.");
      ConnectionPoolDataSource cpds = (ConnectionPoolDataSource) ctx.lookup(cpds_name);
      cpds.getPooledConnection().close();
      System.out.println(
          "ConnectionPoolDataSource " + cpds_name + " sucessfully looked up and checked.");
      DataSource pbds = (DataSource) ctx.lookup(pbds_name);
      pbds.getConnection().close();
      System.out.println(
          "PoolBackedDataSource " + pbds_name + " sucessfully looked up and checked.");
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
 public static void runTest3() throws Exception {
   boolean exceptionOccured = false;
   try {
     Context ctx = cache.getJNDIContext();
     DataSource ds1 = null;
     DataSource ds2 = null;
     ds1 = (DataSource) ctx.lookup("java:/XAPooledDataSource");
     ds2 = (DataSource) ctx.lookup("java:/SimpleDataSource");
     ds2.getConnection();
     UserTransaction utx = (UserTransaction) ctx.lookup("java:/UserTransaction");
     utx.begin();
     utx.setTransactionTimeout(2);
     ds1.getConnection();
     Thread.sleep(4000);
     try {
       utx.commit();
     } catch (Exception e) {
       exceptionOccured = true;
     }
     if (!exceptionOccured)
       fail("Exception (Transaction-Time-Out)did not occur although was supposed" + "to occur");
   } catch (Exception e) {
     fail("failed in runTest3 due to " + e);
   }
 }
Exemple #4
0
  public List<Artefato> readAll(String logado) throws SQLException {
    int i = 0;
    String loga = logado;
    ResultSet rs;
    String sql = "SELECT * FROM ARTEFATO";

    PreparedStatement stm = dataSource.getConnection().prepareStatement(sql);

    stm.setString(1, loga);

    System.out.println(stm.toString());

    rs = stm.executeQuery();
    LinkedList<Artefato> lista = new LinkedList<Artefato>();

    while (rs.next()) {
      Artefato tmp = new Artefato();
      tmp.setAprovado(rs.getBoolean("aprovado"));
      tmp.setBloqueado(rs.getBoolean("bloqueado"));
      tmp.setConteudo(rs.getString("conteudo"));
      tmp.setData_aprovacao(rs.getString("data_aprovacao"));
      tmp.setData_criacao(rs.getString("data_criacao"));
      tmp.setIdAprovador(rs.getInt("idAprovador"));
      tmp.setIdArtefato(rs.getInt("idArtefato"));
      tmp.setIdAutor(rs.getInt("idAutor"));
      tmp.setIdCategoria(rs.getInt("idCategoria"));
      tmp.setTags(rs.getString("tags"));
      tmp.setTipo(rs.getInt("tipo"));
      tmp.setTitulo(rs.getString("titulo"));
      tmp.setVersao(rs.getFloat("versao"));

      lista.add(tmp);
    }
    return lista;
  }
Exemple #5
0
  /* consulta no BD */
  @Override
  public Object read(Object key) throws SQLException {
    String nome = (String) key;

    String sql = "SELECT * FROM ARTEFATO WHERE idArtefato=?";
    PreparedStatement stm = dataSource.getConnection().prepareStatement(sql);
    stm.setString(1, nome);
    System.out.println(nome);
    ResultSet rs = stm.executeQuery();

    if (rs.next()) {
      Artefato tmp = new Artefato();
      tmp.setAprovado(rs.getBoolean("aprovado"));
      tmp.setBloqueado(rs.getBoolean("bloqueado"));
      tmp.setConteudo(rs.getString("conteudo"));
      tmp.setData_aprovacao(rs.getString("data_aprovacao"));
      tmp.setData_criacao(rs.getString("data_criacao"));
      tmp.setIdAprovador(rs.getInt("idAprovador"));
      tmp.setIdArtefato(rs.getInt("idArtefato"));
      tmp.setIdAutor(rs.getInt("idAutor"));
      tmp.setIdCategoria(rs.getInt("idCategoria"));
      tmp.setTags(rs.getString("tags"));
      tmp.setTipo(rs.getInt("tipo"));
      tmp.setTitulo(rs.getString("titulo"));
      tmp.setVersao(rs.getFloat("versao"));
      return tmp;
    }

    return null;
  }
Exemple #6
0
  /* atualizaao no BD */
  @Override
  public void update(Object object) throws SQLException {
    Artefato a = (Artefato) object;

    String sql =
        "UPDATE Artefato SET conteudo=?, data_aprovacao=?, data_criacao=?, tags=?, titulo=?, idAprovador=?, idArtefato=?, idAutor=?, idCategoria=?, tipo=?, versao=?, isAprovado=?, isBloqueado=?"
            + " where titulo=?";

    PreparedStatement stm = dataSource.getConnection().prepareStatement(sql);

    stm.setString(1, a.getConteudo());
    stm.setString(2, a.getData_aprovacao());
    stm.setString(3, a.getData_criacao());
    stm.setString(4, a.getTags());
    stm.setString(5, a.getTitulo());
    stm.setInt(6, a.getIdAprovador());
    stm.setInt(7, a.getIdArtefato());
    stm.setInt(8, a.getIdAutor());
    stm.setInt(9, a.getIdCategoria());
    stm.setInt(10, a.getTipo());
    stm.setFloat(11, a.getVersao());
    stm.setBoolean(12, a.isAprovado());
    stm.setBoolean(13, a.isBloqueado());

    stm.setString(14, a.getTitulo());

    stm.executeUpdate();
  }
  //
  // Find all the objects inside the DataSource and vet them.
  //
  private void vetDataSource(HashSet<String> unsupportedList, HashSet<String> notUnderstoodList)
      throws Exception {
    DataSource ds = JDBCDataSource.getDataSource();
    Connection conn = ds.getConnection();

    vetObject(ds, unsupportedList, notUnderstoodList);

    connectionWorkhorse(conn, unsupportedList, notUnderstoodList);
  }
Exemple #8
0
  /* exclusao no BD */
  @Override
  public void delete(Object object) throws SQLException {
    Artefato a = (Artefato) object;

    String sql = "DELETE FROM ARTEFATO WHERE titulo=?";
    PreparedStatement stm = dataSource.getConnection().prepareStatement(sql);

    stm.setString(1, a.getTitulo());

    stm.executeUpdate();
  }
Exemple #9
0
  /* exclusao no BD */
  public void delete(Object object) throws SQLException {

    Contato c = (Contato) object;
    String sql = "delete from contato where cod_contato=?";

    PreparedStatement stm = dataSource.getConnection().prepareStatement(sql);
    stm.setInt(1, c.getCod_contato());
    stm.executeUpdate();

    System.out.println("Mensagem excluida com sucesso");
  }
  public Connection getConnection() throws Exception {
    InitialContext ctx = null;
    ctx = new InitialContext();

    if (getDataSourceJndiName() == null)
      throw (new Exception("Data Source JNDI name is null. Check whether the JNDI name is null."));

    DataSource ds = (javax.sql.DataSource) ctx.lookup(getDataSourceJndiName());
    Connection conn = ds.getConnection();

    return conn;
  }
Exemple #11
0
  public ResultSet getPrefixName() throws SQLException, NamingException {

    String sql_PrefixName = "SELECT prefix_id,prefixname,abbreviation FROM hex.ref_prefixname";

    ctx = new InitialContext();
    ds = (DataSource) ctx.lookup("jdbc/HEX");
    conn = ds.getConnection();
    pstmt = conn.prepareStatement(sql_PrefixName);
    rs = pstmt.executeQuery();

    return rs;
  }
Exemple #12
0
 static void drop(DataSource ds) throws SQLException {
   Connection con = null;
   Statement stmt = null;
   try {
     con = ds.getConnection();
     stmt = con.createStatement();
     stmt.executeUpdate("DROP TABLE TRSS_TABLE");
   } finally {
     StatementUtils.attemptClose(stmt);
     ConnectionUtils.attemptClose(con);
   }
 }
Exemple #13
0
 static void create(DataSource ds) throws SQLException {
   Connection con = null;
   Statement stmt = null;
   try {
     con = ds.getConnection();
     stmt = con.createStatement();
     stmt.executeUpdate("CREATE TABLE TRSS_TABLE ( a_col VARCHAR(16) )");
   } finally {
     StatementUtils.attemptClose(stmt);
     ConnectionUtils.attemptClose(con);
   }
 }
 private Connection getConnection() throws SQLException {
   DataSource dataSource = null;
   try {
     dataSource = DataSource.getInstance();
   } catch (IOException e) {
     LOG.error("IOException : " + e);
   } catch (SQLException e) {
     LOG.error("SQLException : " + e);
   } catch (PropertyVetoException e) {
     LOG.error("PropertyVetoException : " + e);
   }
   return dataSource.getConnection();
 }
Exemple #15
0
 static void doSomething(DataSource ds) throws SQLException {
   Connection con = null;
   Statement stmt = null;
   try {
     con = ds.getConnection();
     stmt = con.createStatement();
     int i =
         stmt.executeUpdate(
             "INSERT INTO TRSS_TABLE VALUES ('" + System.currentTimeMillis() + "')");
     if (i != 1) throw new SQLException("Insert failed somehow strange!");
   } finally {
     StatementUtils.attemptClose(stmt);
     ConnectionUtils.attemptClose(con);
   }
 }
 public static void runTest2() throws Exception {
   boolean exceptionOccured1 = false;
   boolean exceptionOccured2 = false;
   try {
     Context ctx = cache.getJNDIContext();
     DataSource ds1 = null;
     DataSource ds2 = null;
     ds1 = (DataSource) ctx.lookup("java:/XAPooledDataSource");
     ds2 = (DataSource) ctx.lookup("java:/SimpleDataSource");
     ds2.getConnection();
     ds1.getConnection();
     ds1.getConnection();
     ds1.getConnection();
     ds1.getConnection();
     ds1.getConnection();
     UserTransaction utx = (UserTransaction) ctx.lookup("java:/UserTransaction");
     utx.begin();
     try {
       ds1.getConnection();
       Thread.sleep(8000);
     } catch (SQLException e) {
       exceptionOccured1 = true;
     }
     try {
       utx.commit();
     } catch (Exception e) {
       exceptionOccured2 = true;
     }
     if (!exceptionOccured1)
       fail("Exception (Login-Time-Out)did not occur although was supposed" + "to occur");
     if (exceptionOccured2)
       fail("Exception did occur on commit, although was not supposed" + "to occur");
   } catch (Exception e) {
     fail("failed in runTest2 due to " + e);
   }
 }
Exemple #17
0
  /* atualizacao no BD */
  public void update(Object object) throws SQLException {

    Contato c = (Contato) object;
    String sql = "update contato set " + "nome=?,idade=?,tel=?,mensagem=? " + "where cod_contato=?";

    PreparedStatement stm = dataSource.getConnection().prepareStatement(sql);

    stm.setString(1, c.getNome());
    stm.setInt(2, c.getIdade());
    stm.setString(3, c.getTel());
    stm.setString(4, c.getMensagem());
    stm.setInt(5, c.getCod_contato());

    stm.executeUpdate();

    System.out.println("Update realizado!");
  }
Exemple #18
0
  /** Constructor for LDAPQuery. */
  public JNDITomcat() throws Exception {
    super();

    Hashtable<String, String> env = new Hashtable<String, String>();

    env.put(Context.INITIAL_CONTEXT_FACTORY, "org.apache.naming.java.javaURLContextFactory");
    env.put(Context.PROVIDER_URL, "jndi://nadetrou2:8080/");

    // Obtain our environment naming context

    Context initCtx = new InitialContext(env);

    // Context envCtx = (Context) initCtx.lookup("comp/env");

    // Look up our data source

    // DataSource datasource = (DataSource)
    // initialContext.lookup((String)settings.get(CONNECTION_POOL_NAME));

    DataSource ds = (DataSource) initCtx.lookup("/jdbc/vrdb");

    // Allocate and use a connection from the pool

    Connection conn = ds.getConnection();

    System.out.println(conn);
    // ... use this connection to access the database ...

    conn.close();

    // Hashtable env = new Hashtable();
    // //env.put(Context.INITIAL_CONTEXT_FACTORY,"weblogic.jndi.WLInitialContextFactory");
    // //env.put(Context.PROVIDER_URL, "t3://192.168.0.55:17001/" );
    //
    // env.put(Context.INITIAL_CONTEXT_FACTORY,"weblogic.jndi.WLInitialContextFactory");
    // env.put(Context.PROVIDER_URL, "3://127.0.0.1:7001/" );
    //
    // // env.put(Context.SECURITY_PRINCIPAL, "system");
    // // env.put(Context.SECURITY_CREDENTIALS, "12345678");
    // System.out.println(env);
    // //System.out.println("--A");
    // // Create initial context
    // DirContext ctx = new InitialDirContext(env);

    // exploreNext(0, envCtx, "");
  }
Exemple #19
0
 /* consulta no BD */
 public ArrayList<Contato> readAll() throws SQLException {
   ResultSet rs;
   ArrayList<Contato> contatos = new ArrayList<Contato>();
   String sql = "select * from contato";
   PreparedStatement stm = dataSource.getConnection().prepareStatement(sql);
   rs = stm.executeQuery();
   while (rs.next()) {
     Contato c = new Contato();
     c.setNome(rs.getString(1));
     c.setIdade(rs.getInt(2));
     c.setTel(rs.getString(3));
     c.setMensagem(rs.getString(4));
     c.setCod_contato(rs.getInt(5));
     contatos.add(c);
     System.out.println("Consulta ok!");
   }
   return contatos;
 }
Exemple #20
0
  /* inserção no BD */
  @Override
  public void create(Object object) throws SQLException {

    Contato contato = (Contato) object;
    String sql =
        "insert into contato (nome, idade, tel, mensagem, cod_contato) " + "values(?,?,?,?,?)";

    PreparedStatement stm = dataSource.getConnection().prepareStatement(sql);

    stm.setString(1, contato.getNome());
    stm.setInt(2, contato.getIdade());
    stm.setString(3, contato.getTel());
    stm.setString(4, contato.getMensagem());
    stm.setInt(5, contato.getCod_contato());

    stm.executeUpdate();

    System.out.println("Mensagem enviada com sucesso");
  }
Exemple #21
0
 public void run() {
   Connection con = null;
   Statement stmt = null;
   try {
     DataSource ds = getDataSource();
     con = ds.getConnection();
     if (executeOnlyIf(con, onlyIfQuery)) {
       stmt = con.createStatement();
       if (query != null) {
         executeQuery(stmt, query);
       } else if (update != null) {
         executeUpdate(stmt, update);
       } else {
         throw new IllegalStateException("Both query and update properties are unset");
       }
     } else {
       LOG.debug("Skipped because of " + onlyIfQuery);
     }
   } catch (RuntimeException e) {
     throw e;
   } catch (Throwable t) {
     if (ignore.matcher(t.getMessage()).matches()) {
       LOG.info("Ignoring " + t.getMessage());
     } else {
       throw new RuntimeException(t.getMessage(), t);
     }
   } finally {
     try {
       if (stmt != null) {
         stmt.close();
       }
     } catch (Exception g) {
     }
     try {
       if (con != null) {
         con.close();
       }
     } catch (Exception g) {
     }
   }
 }
 public static void createConnectionPool() {
   Context context;
   try {
     context = new InitialContext();
     Class.forName("org.firebirdsql.jdbc.FBDriver");
     ds = (DataSource) context.lookup("java:comp/env/jdbc/PanelTrackDB");
     Connection c = ds.getConnection();
   } catch (NamingException e) {
     // TODO Auto-generated catch block
     errorLogger.error("An Error Occured:", e);
     e.printStackTrace();
   } catch (ClassNotFoundException e) {
     errorLogger.error("An Error Occured:", e);
     // TODO Auto-generated catch block
     e.printStackTrace();
   } catch (SQLException e) {
     errorLogger.error("An Error Occured:", e);
     // TODO Auto-generated catch block
     e.printStackTrace();
   }
 }
  /**
   * Se conecta a un servicio JDBC usando java.naming. Los parametros de configuracion se manejan
   * para el contexto de la aplicacion, permitiendo un pool de conexiónes persistentes disponibles
   * para toda la aplicacion. Tomcat proporciona este servicio configurandolo en el archivo web.xml
   * o server.xml
   *
   * @param servicio Una cadena como "java:comp/env/servicio"
   */
  protected boolean conectar(String servicio) throws Exception {

    /*
     *Para conectarse con Tomcat
     *en el archivo de coniguracion se especifican
     *los parametros de conexión.
     */
    long t = System.currentTimeMillis();
    // Context es un objeto que encapsula el contexto de la aplicacion
    Context ctx = new InitialContext();
    // DataSource es el origen de datos,
    // un servicio JDBC proporcionado mediante java naming
    // El nombre del servicio deberia ser recibido como
    // argumento
    DataSource ds = (DataSource) ctx.lookup(servicio);

    // Ahora si obtiene la conexión
    this.conexión = ds.getConnection();

    return this.conexión != null;
  } // Fin conectar
  public static Connection obtenerConexion() throws NamingException {
    Connection conexion = null;

    try {
      // Creamos un contexto jndi inicial
      // Este context no tiene nada que ver con
      // la etiqueta contexto donde esta el pool

      // Este context hace referencia un servicio de nombres
      // naming service
      Context ctx = new InitialContext();
      String nombreDelContextJNDI = "java:comp/env/";
      DataSource ds = (DataSource) ctx.lookup(nombreDelContextJNDI + "jdbc/MySqlPoolConections");

      conexion = ds.getConnection();

    } catch (SQLException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
    return conexion;
  }
Exemple #25
0
  /* consulta no BD */
  public Object read(Object key) throws SQLException {

    Integer cod_contato = (Integer) key;
    ResultSet rs;
    String sql = "select * from contato where cod_contato=?";
    PreparedStatement stm = dataSource.getConnection().prepareStatement(sql);
    stm.setLong(1, cod_contato);
    rs = stm.executeQuery();

    if (rs.next()) {

      Contato contato = new Contato();

      contato.setNome(rs.getString(1));
      contato.setIdade(rs.getInt(2));
      contato.setTel(rs.getString(3));
      contato.setMensagem(rs.getString(4));
      contato.setCod_contato(rs.getInt(5));

      return contato;
    }
    return null;
  }
Exemple #26
0
  /* inserao no BD */
  @Override
  public void create(Object object) throws SQLException {
    Artefato artefato = (Artefato) object;
    String sql =
        "INSERT INTO ARTEFATOS (aprovado,bloqueado,conteudo,data_aprovacao,data_criacao,idAprovador,idArtefato,idAutor,idCategoria,tags,tipo,titulo,versao ) "
            + "values(?,?,?,?,?,?,?,?,?,?,?,?,?)";

    PreparedStatement stm = dataSource.getConnection().prepareStatement(sql);

    stm.setInt(1, artefato.getIdAprovador());
    stm.setInt(2, artefato.getIdArtefato());
    stm.setInt(3, artefato.getIdAutor());
    stm.setInt(4, artefato.getIdCategoria());
    stm.setString(5, artefato.getConteudo());
    stm.setString(6, artefato.getData_aprovacao());
    stm.setString(3, artefato.getData_criacao());
    stm.setString(4, artefato.getTitulo());
    stm.setInt(5, artefato.getTipo());
    stm.setFloat(6, artefato.getVersao());

    System.out.println(sql);
    stm.executeUpdate();
    System.out.println("Inserção ok!");
  }
 public Customer updateCustomer(Customer customer) {
   Connection connection = null;
   CallableStatement callableStatement = null;
   ResultSet resultSet = null;
   boolean hasResults;
   String id;
   try {
     connection = dataSource.getConnection(); // get connection from dataSource
     callableStatement = connection.prepareCall(updateCustomerSql); // prepare callable statement
     id = customer.getId();
     if (id == null) {
       callableStatement.setNull(1, Types.INTEGER);
     } else {
       callableStatement.setInt(1, Integer.parseInt(id));
     }
     if (customer.isInactive()) {
       callableStatement.setNull(2, Types.VARCHAR);
       callableStatement.setNull(3, Types.VARCHAR);
       callableStatement.setNull(4, Types.VARCHAR);
       callableStatement.setNull(5, Types.VARCHAR);
       callableStatement.setNull(6, Types.VARCHAR);
       callableStatement.setNull(7, Types.VARCHAR);
       callableStatement.setNull(8, Types.VARCHAR);
       callableStatement.setNull(9, Types.VARCHAR);
       callableStatement.setNull(10, Types.VARCHAR);
       callableStatement.setNull(11, Types.VARCHAR);
       callableStatement.setByte(12, (byte) 1);
     } else {
       callableStatement.setString(2, customer.getFirstName());
       callableStatement.setString(3, customer.getLastName());
       callableStatement.setString(4, customer.getStreetAddress());
       callableStatement.setString(5, customer.getAptAddress());
       callableStatement.setString(6, customer.getCity());
       callableStatement.setString(7, customer.getState());
       callableStatement.setString(8, customer.getZip());
       callableStatement.setString(9, customer.getPhone());
       callableStatement.setString(10, customer.getEmail());
       callableStatement.setString(11, customer.getNotes());
       callableStatement.setByte(12, (byte) 0);
     }
     hasResults = callableStatement.execute();
     if (hasResults) {
       resultSet = callableStatement.getResultSet();
       if (resultSet.next()) {
         customer.setId(resultSet.getString(1));
       } else {
         throw new SQLException("Unable to update customer.");
       }
     } else {
       throw new SQLException("Unable to update customer.");
     }
   } catch (SQLException se) {
     log.error("SQL error: ", se);
     return null;
   } finally {
     try {
       resultSet.close();
     } catch (Exception se) {
       log.error("Unable to close resultSet: ", se);
     }
     try {
       callableStatement.close();
     } catch (Exception se) {
       log.error("Unable to close callableStatement: ", se);
     }
     try {
       connection.close();
     } catch (Exception se) {
       log.error("Unable to close connection: ", se);
     }
   }
   return customer;
 }
 public List<Customer> findCustomers(String id, String match, int limit) {
   Connection connection = null;
   CallableStatement callableStatement = null;
   ResultSet resultSet = null;
   boolean hasResults;
   List<Customer> customers = new ArrayList<Customer>();
   try {
     connection = dataSource.getConnection(); // get connection from dataSource
     connection.setTransactionIsolation(
         Connection.TRANSACTION_READ_COMMITTED); // prevent dirty reads
     callableStatement = connection.prepareCall(listCustomersSql); // prepare callable statement
     if (id == null) {
       callableStatement.setNull(1, Types.INTEGER);
     } else {
       callableStatement.setInt(1, Integer.parseInt(id));
     }
     if (match == null) {
       callableStatement.setNull(2, Types.VARCHAR);
     } else {
       callableStatement.setString(2, match);
     }
     callableStatement.setInt(3, limit);
     callableStatement.setNull(4, Types.INTEGER);
     hasResults = callableStatement.execute();
     if (hasResults) {
       resultSet = callableStatement.getResultSet();
       if (resultSet.isBeforeFirst()) { // customers have been returned
         while (resultSet.next()) {
           customers.add(
               new Customer(
                   resultSet.getString("id"),
                   resultSet.getString("first_name"),
                   resultSet.getString("last_name"),
                   resultSet.getString("street_address"),
                   resultSet.getString("apt_address"),
                   resultSet.getString("city"),
                   resultSet.getString("state"),
                   resultSet.getString("zip"),
                   resultSet.getString("phone"),
                   resultSet.getString("email"),
                   resultSet.getString("notes")));
         }
       } else {
         log.debug("No customers returned.");
       }
     } else {
       log.debug("No customers returned.");
     }
   } catch (SQLException se) {
     log.error("SQL error: ", se);
     return null;
   } finally {
     try {
       resultSet.close();
     } catch (Exception se) {
       log.error("Unable to close resultSet: ", se);
     }
     try {
       callableStatement.close();
     } catch (Exception se) {
       log.error("Unable to close callableStatement: ", se);
     }
     try {
       connection.close();
     } catch (Exception se) {
       log.error("Unable to close connection: ", se);
     }
   }
   return customers;
 }
Exemple #29
0
 public static Connection getConnect() throws SQLException, NamingException {
   InitialContext ic = new InitialContext();
   DataSource ds = (DataSource) ic.lookup("java:/comp/env/jdbc/chatdb");
   return ds.getConnection();
 }
  public void _jspService(HttpServletRequest request, HttpServletResponse response)
      throws java.io.IOException, ServletException {

    PageContext pageContext = null;
    HttpSession session = null;
    ServletContext application = null;
    ServletConfig config = null;
    JspWriter out = null;
    Object page = this;
    JspWriter _jspx_out = null;
    PageContext _jspx_page_context = null;

    try {
      response.setContentType("text/html");
      pageContext = _jspxFactory.getPageContext(this, request, response, null, true, 8192, true);
      _jspx_page_context = pageContext;
      application = pageContext.getServletContext();
      config = pageContext.getServletConfig();
      session = pageContext.getSession();
      out = pageContext.getOut();
      _jspx_out = out;

      out.write("\n");
      out.write("\n");
      out.write("\n");
      out.write("\n");
      out.write("\n");
      out.write("<!--%@ page errorPage=\"/error.jsp\" %-->\n");

      response.setHeader("Pragma", "no-cache"); // HTTP 1.0
      response.setDateHeader("Expires", 0);
      response.setHeader("Cache-Control", "no-cache"); // HTTP 1.1

      String _adminid = "";
      String _adminname = "";
      String _admintype = "";
      String _admingroup = "";
      String _approval = "";
      String _adminclass = "";
      String _adminmail = "";

      try {

        _adminid = (String) session.getAttribute("adminid");

        if (_adminid == null || _adminid.length() == 0 || _adminid.equals("null")) {
          response.sendRedirect("/admin/login_first.html");
          return;
        }

        _adminname = (String) session.getAttribute("adminname");
        _admintype = (String) session.getAttribute("admintype");
        _admingroup = (String) session.getAttribute("admingroup");
        _approval = (String) session.getAttribute("approval");
        _adminclass = (String) session.getAttribute("adminclass");
        _adminmail = (String) session.getAttribute("admin_email");
        // session.setMaxInactiveInterval(60*60);

      } catch (Exception e) {
        response.sendRedirect("/admin/login_first.html");
        return;
      }

      out.write('\n');
      out.write('\n');
      out.write('\n');

      String password = request.getParameter("password");
      String fromURL = request.getParameter("fromURL");
      String oldPassword = "";

      String sql = "";
      int iCnt = 0;
      boolean isSucceeded = false;
      String strMsg = "";
      Connection conn = null;
      MatrixDataSet matrix = null;
      DataProcess dataProcess = null;
      PreparedStatement pstmt = null;

      String targetUrl = "";

      try {

        if (password.equals("1111")) {
          throw new UserDefinedException(
              "The new password is not acceptable. Change your password.");
        }

        Context ic = new InitialContext();
        DataSource ds = (DataSource) ic.lookup("java:comp/env/jdbc/scm");
        conn = ds.getConnection();
        matrix = new dbconn.MatrixDataSet();
        dataProcess = new DataProcess();

        sql =
            " select  password " + " from    admin_01t " + " where   adminid = '" + _adminid + "' ";

        iCnt = dataProcess.RetrieveData(sql, matrix, conn);

        if (iCnt > 0) {
          oldPassword = matrix.getRowData(0).getData(0);
        } else {
          throw new UserDefinedException("Can't find User Information.");
        }

        if (password.equals(oldPassword)) {
          throw new UserDefinedException(
              "The new password is not acceptable. Change your password.");
        }

        // update ó¸®...
        int idx = 0;
        conn.setAutoCommit(false);

        sql =
            " update  admin_01t "
                + " set     password = ?, pw_date = sysdate() "
                + " where   adminid = ? ";

        pstmt = conn.prepareStatement(sql);
        pstmt.setString(++idx, password);
        pstmt.setString(++idx, _adminid);

        iCnt = pstmt.executeUpdate();

        if (iCnt != 1) {
          throw new UserDefinedException("Password update failed.");
        }

        conn.commit();
        isSucceeded = true;

      } catch (UserDefinedException ue) {
        try {
          conn.rollback();
        } catch (Exception ex) {
        }

        strMsg = ue.getMessage();
      } catch (Exception e) {
        try {
          conn.rollback();
        } catch (Exception ex) {
        }

        System.out.println("Exception /admin/resetAdminPasswd : " + e.getMessage());
        throw e;
      } finally {
        if (pstmt != null) {
          try {
            pstmt.close();
          } catch (Exception e) {
          }
        }

        if (conn != null) {
          try {
            conn.setAutoCommit(true);
          } catch (Exception e) {
          }
          conn.close();
        }
      }

      // °á°ú ¸Þ½ÃÁö ó¸®
      if (isSucceeded) {
        // where to go?
        if (fromURL.equals("menu")) {
          targetUrl = "";
        } else {
          targetUrl = "/admin/index2.jsp";
        }
        strMsg = "The data are successfully processed.";
      } else {
        strMsg = "The operation failed.\\n" + strMsg;
        targetUrl = "/admin/resetAdminPasswdForm.jsp";
      }

      out.write("\n");
      out.write("<html>\n");
      out.write("<head>\n");
      out.write("<title></title>\n");
      out.write("<link href=\"/common/css/style.css\" rel=\"stylesheet\" type=\"text/css\">\n");
      out.write("</head>\n");
      out.write("<body leftmargin='0' topmargin='0' marginwidth='0' marginheight='0'>\n");
      out.write("<form name=\"form1\" method=\"post\" action=\"");
      out.print(targetUrl);
      out.write("\">\n");
      out.write("<input type='hidden' name='fromURL' value='");
      out.print(fromURL);
      out.write("'>\n");
      out.write("</form>\n");
      out.write("<script language=\"javascript\">\n");
      if (targetUrl.length() > 0) {
        out.write("\n");
        out.write("  alert('");
        out.print(strMsg);
        out.write("');\n");
        out.write("  document.form1.submit();\n");
      }
      out.write("\n");
      out.write("</script>\n");
      out.write("<table width='840' border='0' cellspacing='0' cellpadding='0'><tr><td>\n");
      out.write("\n");
      out.write("<table width='99%' border='0' cellspacing='0' cellpadding='0'>\n");
      out.write("<tr>\n");
      out.write("  <td height='15' colspan='2'></td>\n");
      out.write("</tr>\n");
      out.write("<tr>\n");
      out.write("  <td width='3%'><img src='/img/title_icon.gif'></td>\n");
      out.write("  <td width='*' class='left_title'>Password Change</td>\n");
      out.write("</tr>\n");
      out.write("<tr>\n");
      out.write("  <td width='100%' height='2' colspan='2'><hr width='100%'></td>\n");
      out.write("</tr>\n");
      out.write("<tr>\n");
      out.write("  <td height='10' colspan='2'></td>\n");
      out.write("</tr>\n");
      out.write("</table>\n");
      out.write("\n");
      out.write("<table width='90%' border='0' cellspacing='0' cellpadding='0' align='center'>\n");
      out.write("<tr>\n");
      out.write("  <td width='100%' align='center'><img border=\"0\" src=\"/img/pass.jpg\">\n");
      out.write("    <br><br>\n");
      out.write("    <b>The Password has been changed successfully.</b></td>\n");
      out.write("</tr>\n");
      out.write("</table>\n");

      out.println(CopyRightLogo());

      out.write("\n");
      out.write("</tr></td></table>\n");
      out.write("</body>\n");
      out.write("</html>");
    } catch (Throwable t) {
      if (!(t instanceof SkipPageException)) {
        out = _jspx_out;
        if (out != null && out.getBufferSize() != 0)
          try {
            out.clearBuffer();
          } catch (java.io.IOException e) {
          }
        if (_jspx_page_context != null) _jspx_page_context.handlePageException(t);
      }
    } finally {
      _jspxFactory.releasePageContext(_jspx_page_context);
    }
  }