Exemplo n.º 1
0
  public void initialize() {
    try {
      InputStream stream = schema.getInputStream();
      Scanner scanner = new Scanner(stream);
      StringBuilder sql = new StringBuilder();
      while (scanner.hasNext()) {
        sql.append(scanner.nextLine());
        sql.append("\n");
      }
      scanner.close();
      stream.close();
      Connection connection = null;
      Statement statement = null;
      try {
        connection = dataSource.getConnection();
        statement = connection.createStatement();
        statement.execute(sql.toString());
      } catch (SQLException ex) {
        ex.printStackTrace();
        throw new RuntimeException(ex);
      } finally {
        if (null != connection) {
          try {
            connection.close();
          } catch (SQLException ex) {
          }
        }
      }

      stream = data.getInputStream();
      scanner = new Scanner(stream);
      sql = new StringBuilder();
      while (scanner.hasNext()) {
        sql.append(scanner.nextLine());
        sql.append("\n");
      }
      scanner.close();
      stream.close();
      connection = null;
      statement = null;
      try {
        connection = dataSource.getConnection();
        statement = connection.createStatement();
        statement.executeUpdate(sql.toString());
      } catch (SQLException ex) {
        ex.printStackTrace();
        throw new RuntimeException(ex);
      } finally {
        if (null != connection) {
          try {
            connection.close();
          } catch (SQLException ex) {
          }
        }
      }

    } catch (IOException e) {
      e.printStackTrace();
    }
  }
Exemplo n.º 2
0
 public static PoolStatus getPoolStatus() {
   PoolStatus pool = new PoolStatus();
   try {
     if (dataSource.getClass().getName().indexOf("c3p0") > 0) {
       pool.total = (Integer) PropertyUtils.getProperty(dataSource, "numConnectionsDefaultUser");
       pool.busy =
           (Integer) PropertyUtils.getProperty(dataSource, "numBusyConnectionsDefaultUser");
       pool.idle =
           (Integer) PropertyUtils.getProperty(dataSource, "numIdleConnectionsDefaultUser");
     } else if (dataSource.getClass().getName().indexOf("bonecp") > 0) {
       pool.total =
           (Integer) PropertyUtils.getProperty(dataSource, "maxConnectionsPerPartition")
               * (Integer) PropertyUtils.getProperty(dataSource, "partitionCount");
       // pool.busy = (Integer)PropertyUtils.getProperty(dataSource,
       // "numBusyConnectionsDefaultUser");
       // pool.idle = (Integer)PropertyUtils.getProperty(dataSource,
       // "numIdleConnectionsDefaultUser");
     } else if (dataSource.getClass().getName().indexOf("druid") > 0) {
       pool.total = (Integer) PropertyUtils.getProperty(dataSource, "maxActive");
       pool.busy = (Integer) PropertyUtils.getProperty(dataSource, "activeCount");
       pool.idle = (Integer) PropertyUtils.getProperty(dataSource, "poolingCount");
     }
     pool.conns = connectionContext;
   } catch (Exception e) {
   }
   return pool;
 }
 public Connection getConnection() throws SQLException {
   if (user != null || pass != null) {
     return ds.getConnection(user, pass);
   } else {
     return ds.getConnection();
   }
 }
Exemplo n.º 4
0
 /**
  * 从apache提供的连接池中取连接,失败返回false
  *
  * @return boolean
  * @date:
  */
 private boolean getApachecommonDBCP() {
   try {
     Context tContext = new InitialContext();
     tContext = (Context) tContext.lookup("java:comp/env");
     Object obj = tContext.lookup(JUrl.getDBName());
     DataSource tDataSource = (DataSource) obj;
     if (tDataSource != null) {
       con = tDataSource.getConnection();
       // 如果连接的是Oracle数据库,需要稍微处理一下日期的格式,最好是在服务器哪里设置一下,而不调用下面的程序
       // 可以添加一个字段类型,来控制是否使用下面的语句
       if (con != null) {
         //                        Statement stmt = con.createStatement(ResultSet.
         //                                TYPE_SCROLL_SENSITIVE,
         //                                ResultSet.CONCUR_UPDATABLE);
         //                        stmt.execute(
         //                                "alter session set nls_date_format = 'YYYY-MM-DD
         // HH24:MI:SS'");
         //                        stmt.close();
         return true;
       }
       return false;
     } else {
       System.out.println("a error occured when geting datasource");
       return false;
     }
   } catch (Throwable e) {
     System.out.println("failure when connect apache commons dbcp ");
     e.printStackTrace();
     return false;
   }
 }
Exemplo n.º 5
0
 /** Get Connection. Support transaction if Connection in ThreadLocal */
 public final Connection getConnection() throws SQLException {
   Connection conn = threadLocal.get();
   if (conn != null) return conn;
   return showSql
       ? new SqlReporter(dataSource.getConnection()).getConnection()
       : dataSource.getConnection();
 }
Exemplo n.º 6
0
 public void initialize() {
   DataSource dataSource = getDataSource();
   try {
     Connection connection = dataSource.getConnection();
     Statement statement = connection.createStatement();
     statement.executeUpdate(
         "CREATE TABLE IF NOT EXISTS USER (ID VARCHAR(10) NOT NULL PRIMARY KEY,FULL_NAME VARCHAR(100),EMAIL VARCHAR(100), BIRTHDAY DATE)");
     statement.executeUpdate(
         "CREATE TABLE IF NOT EXISTS EVENT (NAME VARCHAR(50)NOT NULL PRIMARY KEY, BASE_PRICE VARCHAR(100) NOT NULL, RAITING VARCHAR(10) NOT NULL)");
     statement.executeUpdate(
         "CREATE TABLE IF NOT EXISTS AUDITORIUM (NAME VARCHAR(30),SEATS VARCHAR(200) , VIP_SEATS VARCHAR(200))");
     statement.executeUpdate(
         "CREATE TABLE IF NOT EXISTS COUNTER_ASPECT (EVENT_NAME VARCHAR(50) NOT NULL PRIMARY KEY, ACCESS_BY_NAME VARCHAR(20) , ACCESS_BY_PRICE VARCHAR(20), BOOKED_TICKETS VARCHAR(20))");
     statement.executeUpdate(
         "CREATE TABLE IF NOT EXISTS AUDITORIUM_BOOKING (EVENT_NAME VARCHAR(50) NOT NULL , AUDITORIUM_NAME VARCHAR(30) , BOOKED_TIME DATE NOT NULL PRIMARY KEY, BOOKED_TICKETS VARCHAR(20))");
     statement.executeUpdate(
         "CREATE TABLE IF NOT EXISTS TICKET_BOOKING (USER_ID VARCHAR(10) NOT NULL , BOOKED_TICKETS VARCHAR(20) , EVENT_NAME VARCHAR(20))");
     statement.executeUpdate(
         "CREATE TABLE IF NOT EXISTS LUCKY_WINNER (USER_ID VARCHAR(10) NOT NULL , EVENT_NAME VARCHAR(50) , DATE DATE)");
     statement.executeUpdate(
         "CREATE TABLE IF NOT EXISTS DISCOUNT_ASPECT (USER_ID VARCHAR(10) NOT NULL , EVENT_NAME VARCHAR(50) , DISCOUNT VARCHAR(3))");
     statement.close();
     connection.close();
   } catch (SQLException e) {
     e.printStackTrace();
   }
 }
Exemplo n.º 7
0
  public Account retreiveAccount(String ssn) throws RemoteException {
    Account acct = new Account();
    try {
      DataSource ds =
          (DataSource)
              javax.rmi.PortableRemoteObject.narrow(
                  jndiContext.lookup("java:comp/env/database"), DataSource.class);
      Connection con = ds.getConnection();

      try {
        PreparedStatement stmt = con.prepareStatement("select * from Account where SSN = ?");
        try {
          stmt.setString(1, ssn);
          ResultSet rs = stmt.executeQuery();
          if (!rs.next()) return null;

          acct.setSsn(rs.getString(1));
          acct.setFirstName(rs.getString(2));
          acct.setLastName(rs.getString(3));
          acct.setBalance(rs.getInt(4));
        } finally {
          stmt.close();
        }
      } finally {
        con.close();
      }
    } catch (Exception e) {
      e.printStackTrace();
      throw new RemoteException("[Bean] " + e.getClass().getName() + " : " + e.getMessage());
    }
    return acct;
  }
  // ===================================================================================
  //                                                                          DataSource
  //                                                                          ==========
  public void test_DataSource_Connection_always_close() throws SQLException {
    Connection conn = null;
    DataSource dataSource = getDataSource();

    conn = dataSource.getConnection();
    try {
      PreparedStatement ps = conn.prepareStatement("select * from MEMBER");
      ps.execute();
      ps.close();
    } finally {
      conn.close();
    }
    conn = dataSource.getConnection();
    try {
      PreparedStatement ps =
          conn.prepareStatement("update MEMBER set MEMBER_NAME = ? where MEMBER_ID = 3");
      ps.setString(1, "aaa");
      ps.execute();
      ps.close();
    } finally {
      conn.close();
    }
    conn = dataSource.getConnection();
    try {
      PreparedStatement ps = conn.prepareStatement("select * from MEMBER");
      ps.execute();
      ps.close();
    } finally {
      conn.close();
    }
  }
Exemplo n.º 9
0
 @Test
 public void moveTasksToBacklog() throws Exception {
   given()
       .header(PermanentUserData.tokenHeader)
       .post("/m/backlog/2016/04/26")
       .then()
       .statusCode(204);
   try (Connection conn = ds.getConnection();
       PreparedStatement ps =
           conn.prepareStatement(
               "select count (*) from task where appuser_id = ? and date is null")) {
     ps.setLong(1, PermanentUserData.user.getId());
     try (ResultSet rs = ps.executeQuery(); ) {
       rs.next();
       assertThat(rs.getInt(1), equalTo(2));
     }
   }
   given().filter(sessionFilter).post("/web/backlog/2016/05/16").then().statusCode(204);
   try (Connection conn = ds.getConnection();
       PreparedStatement ps =
           conn.prepareStatement(
               "select count (*) from task where appuser_id = ? and date is null")) {
     ps.setLong(1, PermanentUserData.user.getId());
     try (ResultSet rs = ps.executeQuery(); ) {
       rs.next();
       assertThat(rs.getInt(1), equalTo(3));
     }
   }
 }
Exemplo n.º 10
0
  public static boolean createTeam(Team team) throws SQLException, NamingException {
    Connection conn = null;
    PreparedStatement pstmt = null;
    int result = 0;
    DataSource ds = getDataSource();
    try {
      conn = ds.getConnection();

      pstmt = conn.prepareStatement("insert into team values(?,curdate(),curdate())");
      pstmt.setString(1, team.getT_name());
      result = pstmt.executeUpdate();

    } catch (Exception e) {
      return false;
    } finally {
      if (pstmt != null)
        try {
          pstmt.close();
        } catch (SQLException e) {
        }
      if (conn != null)
        try {
          conn.close();
        } catch (SQLException e) {
        }
    }
    return result == 1;
  }
Exemplo n.º 11
0
  public static boolean deleteTeam(String t_name) throws SQLException, NamingException {
    Connection conn = null;
    PreparedStatement pstmt = null;
    int result = 0;
    DataSource ds = getDataSource();
    try {
      conn = ds.getConnection();

      pstmt = conn.prepareStatement("delete from team where t_name =?");
      pstmt.setString(1, t_name);
      result = pstmt.executeUpdate();

    } catch (Exception e) {
      return false;
    } finally {
      if (pstmt != null)
        try {
          pstmt.close();
        } catch (SQLException e) {
        }
      if (conn != null)
        try {
          conn.close();
        } catch (SQLException e) {
        }
    }
    return result == 1;
  }
Exemplo n.º 12
0
 /** @param session */
 public void readMataData(Session session, ObjectNode matadataNode) {
   for (int retry = 0; ; retry++) {
     try {
       Connection conn = null;
       String shardName = matadataNode.getShardName();
       String tableName = matadataNode.getQualifiedObjectName();
       String catalog = matadataNode.getCatalog();
       String schema = matadataNode.getSchema();
       try {
         JdbcRepository dsRepository = (JdbcRepository) database.getRepository();
         DataSource dataSource = dsRepository.getDataSourceByShardName(shardName);
         conn = dataSource.getConnection();
         tableName = database.identifier(tableName);
         if (catalog != null) {
           catalog = database.identifier(catalog);
         }
         if (schema != null) {
           schema = database.identifier(schema);
         }
         tryReadMetaData(conn, catalog, schema, tableName);
         return;
       } catch (Exception e) {
         throw DbException.convert(e);
       } finally {
         JdbcUtils.closeSilently(conn);
       }
     } catch (DbException e) {
       if (retry >= MAX_RETRY) {
         throw e;
       }
     }
   }
 }
Exemplo n.º 13
0
  /**
   * Tests that we can get a connection from the DataSource bound in JNDI during test setup
   *
   * @throws Exception if an error occurs
   */
  public void testDataSource() throws Exception {
    NameParser nameParser = this.ctx.getNameParser("");
    Name datasourceName = nameParser.parse("_test");
    Object obj = this.ctx.lookup(datasourceName);
    DataSource boundDs = null;

    if (obj instanceof DataSource) {
      boundDs = (DataSource) obj;
    } else if (obj instanceof Reference) {
      //
      // For some reason, this comes back as a Reference instance under CruiseControl !?
      //
      Reference objAsRef = (Reference) obj;
      ObjectFactory factory =
          (ObjectFactory) Class.forName(objAsRef.getFactoryClassName()).newInstance();
      boundDs =
          (DataSource)
              factory.getObjectInstance(
                  objAsRef, datasourceName, this.ctx, new Hashtable<Object, Object>());
    }

    assertTrue("Datasource not bound", boundDs != null);

    Connection con = boundDs.getConnection();
    con.close();
    assertTrue("Connection can not be obtained from data source", con != null);
  }
Exemplo n.º 14
0
  @Test
  public void test() throws SQLException {

    LOGGER.info("Method test start");
    Throwable got = null;
    try {
      tf0();
    } catch (final Throwable throwable) {
      got = throwable;
    } finally {
      final DataSource dataSource = DataSource.class.cast(context.getBean("dataSource"));
      final Connection connection = dataSource.getConnection();
      final Map<String, Object> resultMap = new HashMap<String, Object>();
      try {
        JDBCHelper.executeQuery("select name from test", connection, resultMap);
      } finally {
        if (connection != null) {
          connection.close();
        }
      }
      AssertJUnit.assertTrue(resultMap.isEmpty());
    }
    AssertJUnit.assertNotNull(got);
    LOGGER.info("Method test end");
  }
Exemplo n.º 15
0
  private void doTearDown() throws Exception {
    Connection c1 = null;
    Connection c2 = null;
    Statement s1 = null;
    Statement s2 = null;
    try {
      c1 = myDS.getConnection();
      c2 = myDS2.getConnection();

      s1 = c1.createStatement();
      s2 = c2.createStatement();

      s1.execute("drop table " + TABLE1);
      c1.commit();
      s2.execute("drop table " + TABLE2);
      c2.commit();

    } catch (IllegalStateException e) {
      System.err.println("Caught expected IllegalStateException from Atomikos on doTearDown");
      doTearDown();
    } finally {
      if (s1 != null) s1.close();
      if (s2 != null) s2.close();
      if (c1 != null) c1.close();
      if (c2 != null) c2.close();
    }
  }
Exemplo n.º 16
0
  public Connection getConnection() throws Exception {

    // NamingException, SQLExceptionがスローされる
    try {

      if (connection == null || connection.isClosed()) {
        // JNDI参照コンテキストを取得
        InitialContext initCtx = new InitialContext();

        // Tomcatで管理されたデータベース接続をJNDI経由で取得
        // java:comp/env/を必ずつける
        DataSource ds = (DataSource) initCtx.lookup("java:comp/env/jdbc/dbtest");

        // データベース接続を取得する
        connection = ds.getConnection();

        // 自動コミットを行わず、更新系処理では常にトランザクション管理を行うように設定する。
        connection.setAutoCommit(false);
      }
    } catch (Exception e) {
      // もし接続取得で例外が出た場合はconnection=nullにし、
      // 発生した例外はそのまま送出する
      e.printStackTrace();
      connection = null;
      throw e;
    }
    return connection;
  }
Exemplo n.º 17
0
 boolean lookDataSource(JConnection jconn, JParamObject PO) throws Exception {
   boolean hasDataSource = false;
   if (jconn != null) {
     String dataSource = PO.GetValueByEnvName("DataSource");
     if (dataSource != null && !"".equals(dataSource)) {
       DataSource ds = null;
       //        try {
       //          ds = (DataSource) jconn.getDBContext().lookup("jdbc/" +
       //              dataSource);
       //        }
       //        catch (Exception e) {
       //          Context context = new InitialContext();
       //          Context envContext = (Context) context.lookup(
       //              "java:/comp/env");
       //          ds = (DataSource) envContext.lookup("jdbc/" + dataSource);
       //
       //        }
       if (ds != null) {
         jconn.getInstance(ds.getConnection());
         hasDataSource = true;
       }
     }
   }
   return hasDataSource;
 }
Exemplo n.º 18
0
 /**
  * Create connection from the data-source selected at this view
  *
  * @return
  * @throws SQLException
  */
 public static Connection getConnectionFromSelectedDatasource() throws SQLException {
   String datasourceName = CommonIDEParameters.get(SELECTED_DATASOURCE_NAME);
   DataSource dataSource = null;
   if ((datasourceName == null) || datasourceName.equals(DEFAULT_DATASOURCE_NAME)) {
     logger.debug("No selected datasource found. Make use of the default one");
     dataSource = DataSourceFacade.getInstance().getDataSource(CommonIDEParameters.getRequest());
     if (dataSource != null) {
       Connection connection = dataSource.getConnection();
       return connection;
     }
     logger.error("Trying to use the default datasource, but it is null");
   } else {
     logger.debug(String.format("Selected datasource found %s", datasourceName));
     dataSource =
         DataSourceFacade.getInstance()
             .getNamedDataSource(CommonIDEParameters.getRequest(), datasourceName);
     if (dataSource != null) {
       Connection connection = dataSource.getConnection();
       return connection;
     }
     logger.error(
         String.format(
             "Selected datasource found %s, but the datasource itself is null", datasourceName));
   }
   return null;
 }
Exemplo n.º 19
0
  /**
   * Deletes an exclusion to the database.
   *
   * @param id Exclusion ID
   * @throws StatusException Throws a status exception if the delete fails.
   */
  private void delete(String id) throws StatusException {
    InitialContext initialContext = null;
    Context context = null;
    DataSource ds = null;
    Connection conn = null;
    PreparedStatement pStmt = null;
    try {
      initialContext = new InitialContext();
      context = (Context) initialContext.lookup("java:comp/env");
      ds = (DataSource) context.lookup("jdbc/OpenSQM");
      conn = ds.getConnection();

      // Add the question
      pStmt = conn.prepareStatement(EXCLUSION_DELETE_SQL);
      pStmt.setString(1, id);
      pStmt.executeUpdate();
      pStmt.close();
    } catch (Exception e) {
      e.printStackTrace();
      throw new StatusException("800", e.toString());
    } finally {
      try {
        conn.close();
      } catch (Exception e2) {
      }
    }
  }
 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);
   }
 }
Exemplo n.º 21
0
  public static void main(final String[] args) throws Exception {
    // Create a database connection
    final DataSource dataSource =
        new DatabaseConnectionOptions(
            "org.hsqldb.jdbcDriver", "jdbc:hsqldb:hsql://localhost:9001/schemacrawler");
    final Connection connection = dataSource.getConnection("sa", "");

    // Create the options
    final SchemaCrawlerOptions options = new SchemaCrawlerOptions();
    // Set what details are required in the schema - this affects the
    // time taken to crawl the schema
    options.setSchemaInfoLevel(SchemaInfoLevel.standard());
    options.setRoutineInclusionRule(new InclusionRule(InclusionRule.NONE, InclusionRule.ALL));
    options.setSchemaInclusionRule(new InclusionRule("PUBLIC.BOOKS", InclusionRule.NONE));

    // Get the schema definition
    final Database database = SchemaCrawlerUtility.getDatabase(connection, options);

    for (final Schema schema : database.getSchemas()) {
      System.out.println(schema);
      for (final Table table : database.getTables(schema)) {
        System.out.print("o--> " + table);
        if (table instanceof View) {
          System.out.println(" (VIEW)");
        } else {
          System.out.println();
        }

        for (final Column column : table.getColumns()) {
          System.out.println("     o--> " + column + " (" + column.getColumnDataType() + ")");
        }
      }
    }
  }
 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);
   }
 }
Exemplo n.º 23
0
  public static Connection getConnection()
      throws IOException, ClassNotFoundException, SQLException, NamingException {
    if (connection == null || connection.isClosed()) {

      InputStream in =
          JDBCConnection.class.getClassLoader().getResourceAsStream("jdbc.dev.properties");
      //			InputStream in =
      // JDBCConnection.class.getClassLoader().getResourceAsStream("/MavenWebAppSample2/webapp/jdbc.dev.properties");

      //			InputStream in = null;

      if (in != null) {
        logger.info("Using jdbc.dev.properties");
        Properties prop = new Properties();
        prop.load(in);
        in.close();

        String url = prop.getProperty("url");
        String user = prop.getProperty("user");
        String pass = prop.getProperty("pass");
        String driver = prop.getProperty("driver");

        // Dev mode
        Class.forName(driver);
        connection = java.sql.DriverManager.getConnection(url, user, pass);
      } else {
        logger.info("Using data source");
        // Cloud mode
        InitialContext ctx = new InitialContext();
        DataSource ds = (DataSource) ctx.lookup("java:comp/env/jdbc/DefaultDB");
        connection = ds.getConnection();
      }
    }
    return connection;
  }
Exemplo n.º 24
0
  @Test
  public void testTopLevelJdbcDataSource() throws Exception {
    final CollectingDataSink dataSink = new CollectingDataSink();
    NSysMonConfigurer.addDataSink(NSysMon.get(), dataSink);

    final DataSource dataSource =
        new NSysMonDataSource(
            JdbcConnectionPool.create("jdbc:h2:mem:demo", "sa", ""), null, NSysMon.get());

    try (Connection conn = dataSource.getConnection()) {
      final Statement stmt = conn.createStatement();
      stmt.execute("create table A (oid number primary key)");
      stmt.execute("insert into A (oid) values (1)");
      final ResultSet rs = conn.createStatement().executeQuery("select * from A");
      while (rs.next()) {
        // Just ignore the result, goal is only to generat the sql
      }
    }

    assertEquals(1, dataSink.data.size());
    final AHierarchicalData root = dataSink.data.get(0).getRootNode();
    assertEquals("jdbc:connection from pool", root.getIdentifier());

    assertEquals(3, root.getChildren().size());

    assertEquals(
        "jdbc: create table A (oid number primary key)", root.getChildren().get(0).getIdentifier());
    assertEquals("jdbc: insert into A (oid) values (1)", root.getChildren().get(1).getIdentifier());

    assertEquals("jdbc: select * from A", root.getChildren().get(2).getIdentifier());
  }
Exemplo n.º 25
0
  protected void testQuery() {
    try {
      // ClassArrayShell whether model is null
      if (sqlPredicate == null) {
        MessageDialog.openWarning(top.getShell(), "Warning!", "The predicate is null");
        //		return;
      }
      // ClassArrayShell whether there is a name
      if (textName.getText() == null || textName.getText().trim().length() == 0) {
        MessageDialog.openWarning(top.getShell(), "Warning!", "The predicate should have a name");
        //		return;
      }
      // ClassArrayShell whether there is a data source
      if (sqlPredicate.getDataSource() == null) {
        MessageDialog.openWarning(top.getShell(), "Warning!", "There is no datasource set");
        //		return;
      }

      // ClassArrayShell SQL
      DataSource ds = sqlPredicate.getDataSource();
      Connection con = ds.getConnection();
      java.sql.Statement stmt = con.createStatement();
      final ResultSet rs = stmt.executeQuery(sqlPredicate.getQuery());

      QueryResultsDialog dialog = new QueryResultsDialog(getSite().getShell(), sqlPredicate, rs);
      dialog.create();
      if (dialog.open() != InputDialog.OK) return;
    } catch (Exception x) {
      MessageDialog.openError(top.getShell(), "Error!", "Test has failed");
    }
  }
Exemplo n.º 26
0
  private Connection getConnection() throws Exception {
    Context initCtx = new InitialContext();
    Context envCtx = (Context) initCtx.lookup("java:comp/env");
    DataSource ds = (DataSource) envCtx.lookup("jdbc/itis");

    return ds.getConnection();
  }
Exemplo n.º 27
0
  /**
   * Получение соединения внутри сервлета
   *
   * @param servletContext
   * @return
   * @throws SQLException
   */
  public static Connection getConnection(ServletContext servletContext) throws SQLException {

    Connection connection = null;

    //
    String connectionUrl = servletContext.getInitParameter("webdicom.connection.url");
    if (connectionUrl != null) {
      Properties props = new Properties(); // connection properties
      props.put("user", "user1"); // FIXME взять из конфига
      props.put("password", "user1"); // FIXME взять из конфига

      connection = DriverManager.getConnection(connectionUrl + ";create=true", props);
    } else {
      // for Tomcat
      try {
        Context initCtx = new InitialContext();
        Context envCtx = (Context) initCtx.lookup("java:comp/env");
        DataSource ds = (DataSource) envCtx.lookup("jdbc/webdicom");
        connection = ds.getConnection();
      } catch (NamingException e) {
        throw new SQLException("JNDI error " + e);
      }
    }

    return connection;
  }
Exemplo n.º 28
0
  private void doSetup() throws Exception {

    if (setupDone) return;

    Connection c1 = null;
    Connection c2 = null;
    Statement s1 = null;
    Statement s2 = null;
    try {
      c1 = myDS.getConnection();
      c2 = myDS2.getConnection();

      s1 = c1.createStatement();
      s2 = c2.createStatement();

      s1.execute("create table " + TABLE1 + " ( id INTEGER, foo INTEGER )");
      s1.executeUpdate("insert into " + TABLE1 + " (id, foo) values (1, 1)");
      c1.commit();
      s2.execute("create table " + TABLE2 + " ( id INTEGER, foo INTEGER )");
      s2.executeUpdate("insert into " + TABLE2 + " (id, foo) values (1, 1)");
      c2.commit();

      setupDone = true;
    } finally {
      if (s1 != null) s1.close();
      if (s2 != null) s2.close();
      if (c1 != null) c1.close();
      if (c2 != null) c2.close();
    }
  }
Exemplo n.º 29
0
 @Override
 public Connection getConnection() throws Exception {
   Context initCtx = new InitialContext();
   Context envCtx = (Context) initCtx.lookup("java:/comp/env");
   DataSource ds = (DataSource) envCtx.lookup("jdbc/orcl");
   return ds.getConnection();
 }
Exemplo n.º 30
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();
    }
  }