private void initFromDatabase() throws SQLException, BlockStoreException {
    Statement s = conn.get().createStatement();
    ResultSet rs;

    rs = s.executeQuery("SELECT value FROM settings WHERE name = '" + CHAIN_HEAD_SETTING + "'");
    if (!rs.next()) {
      throw new BlockStoreException("corrupt Postgres block store - no chain head pointer");
    }
    Sha256Hash hash = new Sha256Hash(rs.getBytes(1));
    rs.close();
    this.chainHeadBlock = get(hash);
    this.chainHeadHash = hash;
    if (this.chainHeadBlock == null) {
      throw new BlockStoreException("corrupt Postgres block store - head block not found");
    }

    rs =
        s.executeQuery(
            "SELECT value FROM settings WHERE name = '" + VERIFIED_CHAIN_HEAD_SETTING + "'");
    if (!rs.next()) {
      throw new BlockStoreException(
          "corrupt Postgres block store - no verified chain head pointer");
    }
    hash = new Sha256Hash(rs.getBytes(1));
    rs.close();
    s.close();
    this.verifiedChainHeadBlock = get(hash);
    this.verifiedChainHeadHash = hash;
    if (this.verifiedChainHeadBlock == null) {
      throw new BlockStoreException("corrupt Postgres block store - verified head block not found");
    }
  }
  /**
   * Test importing an unsupported field e.g. datetime, the program should continue and assign null
   * value to the field.
   *
   * @throws Exception
   */
  @Test
  public void testImportUnsupportedField() throws Exception {
    ConnectionProperties p = getConnectionProperties();
    Connection cn = DatabaseConnection.getConnection(p);
    try {
      List<Field> verifiedFields = new Vector<Field>();
      String[] fields = "ListingId, Title".split(",");
      String tableName = "Listings";
      DatabaseConnection.verifyTable(p, tableName, fields, verifiedFields);

      Collection<JsonNode> importNodes = new LinkedList<JsonNode>();
      JsonNodeFactory f = JsonNodeFactory.instance;

      int listingId = 1559350;

      ObjectNode n;
      n = new ObjectNode(f);
      n.put("ListingId", listingId);
      importNodes.add(n);

      JsonArrayImporter importer = new JsonArrayImporter(p);
      importer.doImport(tableName, verifiedFields, importNodes);

      Statement st = cn.createStatement();
      ResultSet rs = st.executeQuery("SELECT ListingId, Title FROM Listings");
      assertTrue("Expected result set to contain a record", rs.next());
      assertEquals(listingId, rs.getInt("ListingId"));
      assertEquals(null, rs.getString("Title"));
    } finally {
      cn.close();
    }
  }
  /**
   * Preconditions: 1. xid is known to the RM or it's in prepared state
   *
   * <p>Implementation deficiency preconditions: 1. xid must be associated with this connection if
   * it's not in prepared state.
   *
   * <p>Postconditions: 1. Transaction is rolled back and disassociated from connection
   */
  public void rollback(Xid xid) throws XAException {
    if (logger.logDebug()) debug("rolling back xid = " + xid);

    // We don't explicitly check precondition 1.

    try {
      if (currentXid != null && xid.equals(currentXid)) {
        state = STATE_IDLE;
        currentXid = null;
        conn.rollback();
        conn.setAutoCommit(localAutoCommitMode);
      } else {
        String s = RecoveredXid.xidToString(xid);

        conn.setAutoCommit(true);
        Statement stmt = conn.createStatement();
        try {
          stmt.executeUpdate("ROLLBACK PREPARED '" + s + "'");
        } finally {
          stmt.close();
        }
      }
    } catch (SQLException ex) {
      throw new PGXAException(
          GT.tr("Error rolling back prepared transaction"), ex, XAException.XAER_RMERR);
    }
  }
  /**
   * Gets a list of courses that belongs to an instructor. Throws InvalidDBRequestException if any
   * error occured to the database connection.
   *
   * @param name the instructor's user name
   * @return a vector containing the list of courses
   * @throws InvalidDBRequestException
   */
  public Vector getCourseList(String name) throws InvalidDBRequestException {
    Vector courseList = new Vector();

    try {
      Connection db;

      Class.forName(GaigsServer.DBDRIVER);
      db =
          DriverManager.getConnection(GaigsServer.DBURL, GaigsServer.DBLOGIN, GaigsServer.DBPASSWD);

      Statement stmt = db.createStatement();
      ResultSet rs;

      // get the course list
      rs =
          stmt.executeQuery(
              "select course_num, course_name from course where instructor = '"
                  + name
                  + "' order by course_num");
      while (rs.next()) courseList.add(rs.getString(1) + " - " + rs.getString(2));

      rs.close();
      stmt.close();
      db.close();
    } catch (SQLException e) {
      System.err.println("Invalid SQL in getCourseList: " + e.getMessage());
      throw new InvalidDBRequestException("???");
    } catch (ClassNotFoundException e) {
      System.err.println("Driver Not Loaded");
      throw new InvalidDBRequestException("Server Error");
    }

    return courseList;
  }
Exemple #5
0
  /**
   * This method queries the database to get the sequence for the BP_ID.
   *
   * @exception SQLException, if query fails
   * @author
   */
  public String getBpid() {
    String query;
    String bpid = "";
    Statement stmt = null;
    ResultSet rs = null;

    query = "select bp_id_seq.nextval from dual ";

    try {
      stmt = conn.createStatement();
      rs = stmt.executeQuery(query);
      if (rs.next()) {
        bpid = rs.getString(1);
      }
      if (rs != null) rs.close();
      if (stmt != null) stmt.close();
    } catch (SQLException ex) {
      USFEnv.getLog().writeCrit("Dinvjrnl: Sequence Value for BP_ID not Retreived ", this, ex);
      try {
        if (rs != null) rs.close();
        if (stmt != null) stmt.close();
      } catch (SQLException e) {
        USFEnv.getLog().writeCrit("Unable to close the resultset/statement", this, e);
      }
    }

    return bpid;
  }
  /**
   * Get Company ID by OrganisationID
   *
   * @param OrgID
   * @return PKCompany
   * @throws SQLException
   * @throws Exception
   */
  public int getCompanyID(int OrgID) throws SQLException, Exception {
    String query = "Select FKCompanyID from tblOrganization WHERE PKOrganization = " + OrgID;

    /*db.openDB();
    Statement stmt = db.con.createStatement();
    ResultSet rs = stmt.executeQuery(query);

    if(rs.next())
    	return rs.getInt(1);*/
    int iCompanyID = 0;
    Connection con = null;
    Statement st = null;
    ResultSet rs = null;

    try {

      con = ConnectionBean.getConnection();
      st = con.createStatement();
      rs = st.executeQuery(query);

      if (rs.next()) {
        iCompanyID = rs.getInt(1);
      }

    } catch (Exception E) {
      System.err.println("Organization.java - getCompanyID - " + E);
    } finally {

      ConnectionBean.closeRset(rs); // Close ResultSet
      ConnectionBean.closeStmt(st); // Close statement
      ConnectionBean.close(con); // Close connection
    }

    return iCompanyID;
  }
  /**
   * Get organisation's nomination rater status
   *
   * @param iOrgID
   * @return
   * @throws SQLException
   * @throws Exception
   * @author Desmond
   */
  public boolean getNomRater(int iOrgID) throws SQLException, Exception {
    String query = "SELECT NominationModule FROM tblOrganization WHERE PKOrganization =" + iOrgID;
    boolean iNomRater = true;

    Connection con = null;
    Statement st = null;
    ResultSet rs = null;

    try {
      con = ConnectionBean.getConnection();
      st = con.createStatement();
      rs = st.executeQuery(query);

      if (rs.next()) {
        iNomRater = rs.getBoolean(1);
      }

    } catch (Exception E) {
      System.err.println("Organization.java - getNomRater - " + E);
    } finally {
      ConnectionBean.closeRset(rs); // Close ResultSet
      ConnectionBean.closeStmt(st); // Close statement
      ConnectionBean.close(con); // Close connection
    }

    return iNomRater;
  } // End getNomRater()
Exemple #8
0
  @SuppressWarnings("unchecked")
  @Test
  public void testFindCustomersWithConnection() throws Exception {
    CustomerDAO dao =
        EasyMock.createMockBuilder(CustomerDAO.class)
            .addMockedMethod("readNextCustomer")
            .addMockedMethod("getCustomerQuery")
            .createStrictMock();
    ResultSet resultSet = EasyMock.createStrictMock(ResultSet.class);
    Connection connection = EasyMock.createStrictMock(Connection.class);
    Statement statement = EasyMock.createStrictMock(Statement.class);
    List<SearchConstraint> constraints = new LinkedList<SearchConstraint>();

    EasyMock.expect(dao.getCustomerQuery(constraints)).andReturn("aQuery");
    EasyMock.expect(connection.createStatement()).andReturn(statement);
    EasyMock.expect(statement.executeQuery("aQuery")).andReturn(resultSet);

    EasyMock.expect(resultSet.next()).andReturn(true);
    EasyMock.expect(dao.readNextCustomer(EasyMock.eq(resultSet), EasyMock.isA(List.class)))
        .andReturn(true);
    EasyMock.expect(dao.readNextCustomer(EasyMock.eq(resultSet), EasyMock.isA(List.class)))
        .andReturn(true);
    EasyMock.expect(dao.readNextCustomer(EasyMock.eq(resultSet), EasyMock.isA(List.class)))
        .andReturn(false);
    resultSet.close();
    EasyMock.expectLastCall();
    statement.close();
  }
 protected Statement createStatement(Connection c) throws SQLException {
   Statement statement =
       c.createStatement(ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY);
   statement.setFetchSize(batchSize);
   statement.setMaxRows(maxRows);
   return statement;
 }
Exemple #10
0
  public static void customStartAll(Connection conn) throws SQLException {
    String method = "customStartAll";
    int location = 1000;
    try {
      Statement stmt = conn.createStatement();

      int id = 0;
      int gpfdistPort = 0;
      String strSQL = "SELECT id\n";
      strSQL += "FROM os.custom_sql";

      ResultSet rs = stmt.executeQuery(strSQL);
      while (rs.next()) {
        id = rs.getInt(1);
        gpfdistPort = GpfdistRunner.customStart(OSProperties.osHome);

        strSQL = "INSERT INTO os.ao_custom_sql\n";
        strSQL +=
            "(id, table_name, columns, column_datatypes, sql_text, source_type, source_server_name, source_instance_name, source_port, source_database_name, source_user_name, source_pass, gpfdist_port)\n";
        strSQL +=
            "SELECT id, table_name, columns, column_datatypes, sql_text, source_type, source_server_name, source_instance_name, source_port, source_database_name, source_user_name, source_pass, "
                + gpfdistPort
                + "\n";
        strSQL += "FROM os.custom_sql\n";
        strSQL += "WHERE id = " + id;

        stmt.executeUpdate(strSQL);
      }
    } catch (SQLException ex) {
      throw new SQLException(
          "(" + myclass + ":" + method + ":" + location + ":" + ex.getMessage() + ")");
    }
  }
Exemple #11
0
  public static void failJobs(Connection conn) throws SQLException {
    String method = "failJobs";
    int location = 1000;
    try {
      Statement stmt = conn.createStatement();

      String strSQL =
          "INSERT INTO os.ao_queue (queue_id, status, queue_date, start_date, end_date, "
              + "error_message, num_rows, id, refresh_type, target_schema_name, target_table_name, target_append_only, "
              + "target_compressed, target_row_orientation, source_type, source_server_name, source_instance_name, "
              + "source_port, source_database_name, source_schema_name, source_table_name, source_user_name, "
              + "source_pass, column_name, sql_text, snapshot) "
              + "SELECT queue_id, 'failed' as status, queue_date, start_date, now() as end_date, "
              + "'Outsourcer stop requested' as error_message, num_rows, id, refresh_type, target_schema_name, "
              + "target_table_name, target_append_only, target_compressed, target_row_orientation, source_type, "
              + "source_server_name, source_instance_name, source_port, source_database_name, source_schema_name, "
              + "source_table_name, source_user_name, source_pass, column_name, sql_text, snapshot "
              + "FROM os.queue WHERE status = 'queued'";

      stmt.executeUpdate(strSQL);

    } catch (SQLException ex) {
      throw new SQLException(
          "(" + myclass + ":" + method + ":" + location + ":" + ex.getMessage() + ")");
    }
  }
Exemple #12
0
  public static String getVersion(Connection conn) throws SQLException {
    String method = "getVersion";
    int location = 1000;
    try {
      location = 2000;
      String value = "";

      location = 2100;
      Statement stmt = conn.createStatement();
      String strSQL =
          "SELECT CASE "
              + "WHEN POSITION ('HAWQ 2.0.1' in version) > 0 THEN 'HAWQ_2_0_1' "
              + "WHEN POSITION ('HAWQ 2.0.0' in version) > 0 THEN 'HAWQ_2_0_0' "
              + "WHEN POSITION ('HAWQ 1' in version) > 0 THEN 'HAWQ_1' "
              + "WHEN POSITION ('HAWQ' in version) = 0 AND POSITION ('Greenplum Database' IN version) > 0 THEN 'GPDB' "
              + "ELSE 'OTHER' END "
              + "FROM version()";
      if (debug) Logger.printMsg("Getting Variable: " + strSQL);

      location = 2200;
      ResultSet rs = stmt.executeQuery(strSQL);

      while (rs.next()) {
        value = rs.getString(1);
      }

      location = 2300;
      return value;

    } catch (SQLException ex) {
      throw new SQLException(
          "(" + myclass + ":" + method + ":" + location + ":" + ex.getMessage() + ")");
    }
  }
Exemple #13
0
  public static String getVariable(Connection conn, String name) throws SQLException {
    String method = "getVariable";
    int location = 1000;
    try {
      location = 2000;
      String value = "";

      location = 2100;
      Statement stmt = conn.createStatement();
      String strSQL = "SELECT os.fn_get_variable('" + name + "')";

      if (debug) Logger.printMsg("Getting Variable: " + strSQL);

      location = 2200;
      ResultSet rs = stmt.executeQuery(strSQL);

      while (rs.next()) {
        value = rs.getString(1);
      }

      location = 2300;
      return value;

    } catch (SQLException ex) {
      throw new SQLException(
          "(" + myclass + ":" + method + ":" + location + ":" + ex.getMessage() + ")");
    }
  }
Exemple #14
0
  @Override
  public List<String> saveStatements(List<Statement> statements) throws Exception {
    List<String> statementIds = new ArrayList<String>();
    if (statements.size() == 0) {
      return statementIds;
    }

    ArrayNode rootNode = Mapper.getInstance().createArrayNode();
    for (Statement statement : statements) {
      rootNode.add(statement.toJSONNode(version));
    }

    HTTPRequest request = new HTTPRequest();
    request.setRequestContent(
        new ByteArrayBuffer(
            Mapper.getWriter(this.usePrettyJSON()).writeValueAsString(rootNode), "UTF-8"));
    request.setMethod(HttpMethods.POST);
    request.setURL(this.getEndpoint() + "statements");

    HTTPResponse response = this.sendRequest(request);
    int status = response.getStatus();

    if (status == 200) {
      String content = request.getResponseContent();
      Iterator it = Mapper.getInstance().readValue(content, ArrayNode.class).elements();
      while (it.hasNext()) {
        statementIds.add(((JsonNode) it.next()).textValue());
      }
      return statementIds;
    }

    throw new UnexpectedHTTPResponse(response);
  }
Exemple #15
0
  @Override
  public UUID saveStatement(Statement statement) throws Exception {
    HTTPRequest request = new HTTPRequest();
    request.setRequestContent(
        new ByteArrayBuffer(statement.toJSON(this.getVersion(), this.usePrettyJSON()), "UTF-8"));

    String url = this.getEndpoint() + "statements";
    if (statement.getId() == null) {
      request.setMethod(HttpMethods.POST);
    } else {
      request.setMethod(HttpMethods.PUT);
      url += "?statementId=" + statement.getId().toString();
    }
    request.setURL(url);

    HTTPResponse response = this.sendRequest(request);
    int status = response.getStatus();

    // TODO: handle 409 conflict, etc.
    if (status == 204) {
      return statement.getId();
    } else if (status == 200) {
      String content = request.getResponseContent();
      return UUID.fromString(
          Mapper.getInstance().readValue(content, ArrayNode.class).get(0).textValue());
    }

    throw new UnexpectedHTTPResponse(response);
  }
  public Connection getConnection() throws SQLException {
    synchronized (pool) {
      if (!pool.isEmpty()) {
        int last = pool.size() - 1;
        Connection pooled = (Connection) pool.remove(last);

        boolean conn_ok = true;
        String test_table = prop.getProperty("test_table");
        if (test_table != null) {
          Statement stmt = null;
          try {
            stmt = pooled.createStatement();
            stmt.executeQuery("select * from " + prop.getProperty("test_table"));
          } catch (SQLException ex) {
            conn_ok = false; // 连接不可用
          } finally {
            if (stmt != null) {
              stmt.close();
            }
          }
        }
        if (conn_ok == true) {
          return pooled;
        } else {
          pooled.close();
        }
      }
    }
    Connection conn =
        DriverManager.getConnection(
            prop.getProperty("url"), prop.getProperty("username"), prop.getProperty("password"));
    return conn;
  }
  /**
   * Preconditions: 1. xid must be in prepared state in the server
   *
   * <p>Implementation deficiency preconditions: 1. Connection must be in idle state
   *
   * <p>Postconditions: 1. Transaction is committed
   */
  private void commitPrepared(Xid xid) throws XAException {
    try {
      // Check preconditions. The connection mustn't be used for another
      // other XA or local transaction, or the COMMIT PREPARED command
      // would mess it up.
      if (state != STATE_IDLE || conn.getTransactionState() != ProtocolConnection.TRANSACTION_IDLE)
        throw new PGXAException(
            GT.tr("Not implemented: 2nd phase commit must be issued using an idle connection"),
            XAException.XAER_RMERR);

      String s = RecoveredXid.xidToString(xid);

      localAutoCommitMode = conn.getAutoCommit();
      conn.setAutoCommit(true);
      Statement stmt = conn.createStatement();
      try {
        stmt.executeUpdate("COMMIT PREPARED '" + s + "'");
      } finally {
        stmt.close();
        conn.setAutoCommit(localAutoCommitMode);
      }
    } catch (SQLException ex) {
      throw new PGXAException(
          GT.tr("Error committing prepared transaction"), ex, XAException.XAER_RMERR);
    }
  }
Exemple #18
0
  private void getIgnoreList() {
    Connection con = null;
    try {
      con = pool.getConnection(timeout);

      Statement s = con.createStatement();
      s.executeQuery("SELECT `name`, `type` FROM `ignores`");

      ResultSet rs = s.getResultSet();
      this.ignore_list.clear();
      this.soft_ignore_list.clear();
      while (rs.next()) {
        if (rs.getString("type").equals("hard")) {
          this.ignore_list.add(rs.getString("name").toLowerCase());
        } else {
          this.soft_ignore_list.add(rs.getString("name").toLowerCase());
        }
      }
      rs.close();
      s.close();
    } catch (SQLException ex) {
      Logger.getLogger(DBAccess.class.getName()).log(Level.SEVERE, null, ex);
    } finally {
      try {
        if (con != null) {
          con.close();
        }
      } catch (SQLException ex) {
        Logger.getLogger(DBAccess.class.getName()).log(Level.SEVERE, null, ex);
      }
    }
  }
 /**
  * Sets the user to run as. This is for the case where the request was generated by the user and
  * so the worker must set this value later.
  *
  * @param cq_id id of this entry in the queue
  * @param user user to run the jobs as
  */
 public void setRunAs(long cq_id, String user) throws MetaException {
   try {
     Connection dbConn = getDbConn();
     try {
       Statement stmt = dbConn.createStatement();
       String s = "update COMPACTION_QUEUE set cq_run_as = '" + user + "' where cq_id = " + cq_id;
       LOG.debug("Going to execute update <" + s + ">");
       if (stmt.executeUpdate(s) != 1) {
         LOG.error("Unable to update compaction record");
         LOG.debug("Going to rollback");
         dbConn.rollback();
       }
       LOG.debug("Going to commit");
       dbConn.commit();
     } catch (SQLException e) {
       LOG.error("Unable to update compaction queue, " + e.getMessage());
       try {
         LOG.debug("Going to rollback");
         dbConn.rollback();
       } catch (SQLException e1) {
       }
       detectDeadlock(e, "setRunAs");
     } finally {
       closeDbConn(dbConn);
     }
   } catch (DeadlockException e) {
     setRunAs(cq_id, user);
   } finally {
     deadlockCnt = 0;
   }
 }
  /* Method Name : isConsulting
   * Checks whether login organisation is a Consulting Company
   * @param sOrgName
   * @param orgCode
   * @author Mark Oei
   * @since v.1.3.12.63 (09 Mar 2010)
   */
  public boolean isConsulting(String orgName) {
    String sOrgName = "";
    orgName = "\'" + orgName + "\'";
    String querySql = "SELECT * FROM tblConsultingCompany WHERE CompanyName = " + orgName;
    // Change to disable print statement. Used for debugging only
    // Mark Oei 19 Mar 2010
    // System.out.println("testing " + orgName);
    Connection con = null;
    Statement st = null;
    ResultSet rs = null;

    try {
      con = ConnectionBean.getConnection();
      st = con.createStatement();
      rs = st.executeQuery(querySql);

      if (rs.next()) sOrgName = rs.getString("CompanyName");
    } catch (Exception E) {
      System.err.println("Organization.java - isConsulting - " + E);
    } finally {

      ConnectionBean.closeRset(rs); // Close ResultSet
      ConnectionBean.closeStmt(st); // Close statement
      ConnectionBean.close(con); // Close connection
    }
    // Change to disable print statement. Used for debugging only
    // Mark Oei 19 Mar 2010
    // System.out.println("testing " + sOrgName);
    if ((sOrgName == null) || (sOrgName == "")) return false;
    else return true;
  } // End of isConsulting
Exemple #21
0
  private void getPokemon() {
    Connection con = null;
    try {
      con = pool.getConnection(timeout);
      try (Statement s = con.createStatement()) {
        ResultSet rs;

        s.executeQuery("SELECT `name` FROM `pokemon`");
        rs = s.getResultSet();
        this.pokemon.clear();
        while (rs.next()) {
          this.pokemon.add(rs.getString("name"));
        }
        rs.close();
        s.close();
      }
    } catch (SQLException ex) {
      Logger.getLogger(DBAccess.class.getName()).log(Level.SEVERE, null, ex);
    } finally {
      try {
        if (con != null) {
          con.close();
        }
      } catch (SQLException ex) {
        Logger.getLogger(DBAccess.class.getName()).log(Level.SEVERE, null, ex);
      }
    }
  }
Exemple #22
0
 protected void executeQuery(Statement stmt, String q) throws SQLException {
   q = q.replace("$PREFIX", getPrefix());
   LOG.info(" Executing " + q);
   ResultSet rs = stmt.executeQuery(q);
   StringBuilder header = new StringBuilder();
   for (int i = 1; i <= rs.getMetaData().getColumnCount(); i++) {
     if (i > 1) {
       header.append("|");
     }
     header.append(rs.getMetaData().getColumnName(i));
   }
   LOG.info(header);
   int seq = 0;
   while (true) {
     boolean valid = rs.next();
     if (!valid) break;
     seq++;
     StringBuilder line = new StringBuilder();
     for (int i = 1; i <= rs.getMetaData().getColumnCount(); i++) {
       if (i > 1) {
         line.append("|");
       }
       line.append(rs.getString(i));
     }
     LOG.info(seq + ":" + line);
   }
 }
  public String getOrganisationName(int iFKOrg) {
    String sOrgName = "";
    String querySql = "SELECT * FROM tblOrganization WHERE PKOrganization = " + iFKOrg;

    Connection con = null;
    Statement st = null;
    ResultSet rs = null;

    try {
      con = ConnectionBean.getConnection();
      st = con.createStatement();
      rs = st.executeQuery(querySql);

      if (rs.next()) sOrgName = rs.getString("OrganizationName");

    } catch (Exception E) {
      System.err.println("Organization.java - getOrganizationName - " + E);
    } finally {

      ConnectionBean.closeRset(rs); // Close ResultSet
      ConnectionBean.closeStmt(st); // Close statement
      ConnectionBean.close(con); // Close connection
    }

    return sOrgName;
  }
  public void upgradeBaseSchema(Connection conn, int currentVersion) {
    if (!isLoaded()) {
      throw new TajoInternalError("Database schema files are not loaded.");
    }

    final List<SchemaPatch> candidatePatches = new ArrayList<>();
    Statement stmt;

    for (SchemaPatch patch : this.catalogStore.getPatches()) {
      if (currentVersion >= patch.getPriorVersion()) {
        candidatePatches.add(patch);
      }
    }

    Collections.sort(candidatePatches);
    try {
      stmt = conn.createStatement();
    } catch (SQLException e) {
      throw new TajoInternalError(e);
    }

    for (SchemaPatch patch : candidatePatches) {
      for (DatabaseObject object : patch.getObjects()) {
        try {
          stmt.executeUpdate(object.getSql());
          LOG.info(object.getName() + " " + object.getType() + " was created or altered.");
        } catch (SQLException e) {
          throw new TajoInternalError(e);
        }
      }
    }

    CatalogUtil.closeQuietly(stmt);
  }
  /** Get Organisation ID by User email */
  public int getOrgIDbyEmail(String UserEmail) throws SQLException, Exception {
    String query = "Select COUNT(*) as TotRecord from tblEmail";
    int count = 0;
    Connection con = null;
    Statement st = null;
    ResultSet rs = null;

    try {
      con = ConnectionBean.getConnection();
      st = con.createStatement();
      rs = st.executeQuery(query);

      if (rs.next()) {
        count = rs.getInt(1);
      }

    } catch (Exception E) {
      System.err.println("Organization.java - editRecord - " + E);
    } finally {
      ConnectionBean.closeRset(rs); // Close ResultSet
      ConnectionBean.closeStmt(st); // Close statement
      ConnectionBean.close(con); // Close connection
    }

    return count;
  }
Exemple #26
0
  public void saveSentMessage(COutgoingMessage message) throws Exception {
    Statement sqlCmd;

    if (connection != null) {
      sqlCmd =
          connection.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
      sqlCmd.executeUpdate(
          "insert into sms_out (recipient, text, dispatch_date, flash_sms, status_report, src_port, dst_port, validity_period) values ('"
              + message.getRecipient()
              + "', '"
              + message.getText().replaceAll("'", "''")
              + "', "
              + escapeDate(message.getDate(), true)
              + ", "
              + (message.getFlashSms() ? 1 : 0)
              + ", "
              + (message.getStatusReport() ? 1 : 0)
              + ", "
              + message.getSourcePort()
              + ", "
              + message.getDestinationPort()
              + ", "
              + message.getValidityPeriod()
              + ")");
      connection.commit();
      sqlCmd.close();
    }
  }
  /**
   * Get organisation's name sequence
   *
   * @param iOrgID
   * @return
   * @throws SQLException
   * @throws Exception
   * @author Maruli
   */
  public int getNameSeq(int iOrgID) throws SQLException, Exception {
    String query = "SELECT NameSequence FROM tblOrganization WHERE PKOrganization =" + iOrgID;
    int iNameSeqe = 0;

    Connection con = null;
    Statement st = null;
    ResultSet rs = null;

    try {
      con = ConnectionBean.getConnection();
      st = con.createStatement();
      rs = st.executeQuery(query);

      if (rs.next()) {
        iNameSeqe = rs.getInt(1);
      }

    } catch (Exception E) {
      System.err.println("Organization.java - getNameSeq - " + E);
    } finally {
      ConnectionBean.closeRset(rs); // Close ResultSet
      ConnectionBean.closeStmt(st); // Close statement
      ConnectionBean.close(con); // Close connection
    }

    return iNameSeqe;
  }
 private static void truncateTables(Collection<String> tables, Connection connection) {
   try (Statement statement = connection.createStatement()) {
     statement.executeUpdate("TRUNCATE " + Joiner.on(", ").join(tables) + " CASCADE");
   } catch (SQLException e) {
     throw new RuntimeException(e);
   }
 }
  protected List<List<Statement>> buildContext(
      InputContext inputContext, List<Statement> stmts, int targetIndex) {
    VarCartesianProduct varCartesianProduct = new VarCartesianProduct();
    Statement statement = stmts.get(targetIndex);

    for (CtVariableReference var : statement.getInputContext().getVar()) {

      varCartesianProduct.addReplaceVar(var, valueCreator.createNull(var.getType()));

      List<CtVariableReference> candidates = inputContext.allCandidate(var.getType(), true, false);
      if (!candidates.isEmpty()) {
        varCartesianProduct.addReplaceVar(
            var, candidates.get(AmplificationHelper.getRandom().nextInt(candidates.size())));
      }

      Statement cfLocalVar = getLocalVar(var.getType(), inputContext);
      if (cfLocalVar != null) {
        varCartesianProduct.addReplaceVar(var, cfLocalVar);
      }

      CtLocalVariable localVariable =
          createLocalVarFromMethodLiterals(currentMethod, var.getType());
      if (localVariable != null) {
        varCartesianProduct.addReplaceVar(var, localVariable);
      }

      CtLocalVariable randomVar = valueCreator.createRandomLocalVar(var.getType());
      if (randomVar != null) {
        varCartesianProduct.addReplaceVar(var, randomVar);
      }
    }

    return varCartesianProduct.apply(stmts, targetIndex);
  }
  /**
   * Deletes an instructor from the database. Deletes the instructor's courses by invoking the
   * deleteCourse method. Throws InvalidDBRequestException if instructor not in the database or
   * other database connection problems.
   *
   * @see deleteCourse
   * @param instructor instructor's user name
   * @throws InvalidDBRequestException
   */
  public void deleteInstructor(String instructor) throws InvalidDBRequestException {
    try {
      Class.forName(GaigsServer.DBDRIVER);
      db =
          DriverManager.getConnection(GaigsServer.DBURL, GaigsServer.DBLOGIN, GaigsServer.DBPASSWD);

      Statement stmt = db.createStatement();
      int count;

      // delete the instructor's courses
      ResultSet rs =
          stmt.executeQuery(
              "select course_num from course where instructor = '" + instructor + "'");
      while (rs.next()) deleteCourse(rs.getString(1).trim(), instructor);

      // delete the instructor's record
      count = stmt.executeUpdate("delete from instructor where login ='******'");

      rs.close();
      stmt.close();
      db.close();
    } catch (SQLException e) {
      System.err.println("Invalid SQL in addCourse: " + e.getMessage());
      throw new InvalidDBRequestException("??? ");
    } catch (ClassNotFoundException e) {
      System.err.println("Driver Not Loaded");
      throw new InvalidDBRequestException("Internal Server Error");
    }
  }