/**
   * 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();
    }
  }
Exemple #2
0
 public static List<WikiMessage> upgrade063(List<WikiMessage> messages) {
   TransactionStatus status = null;
   try {
     status = DatabaseConnection.startTransaction(getTransactionDefinition());
     Connection conn = DatabaseConnection.getConnection();
     // increase the size of ip address columns
     WikiBase.getDataHandler().executeUpgradeUpdate("UPGRADE_063_ALTER_USER_CREATE_IP", conn);
     WikiBase.getDataHandler().executeUpgradeUpdate("UPGRADE_063_ALTER_USER_LAST_LOGIN_IP", conn);
     messages.add(
         new WikiMessage(
             "upgrade.message.db.column.modified", "create_ip_address", "jam_wiki_user"));
     messages.add(
         new WikiMessage(
             "upgrade.message.db.column.modified", "last_login_ip_address", "jam_wiki_user"));
   } catch (SQLException e) {
     // do not throw this error and halt the upgrade process - changing the column size
     // is not required for systems that have already been successfully installed, it
     // is simply being done to keep new installs consistent with existing installs.
     messages.add(new WikiMessage("upgrade.error.nonfatal", e.getMessage()));
     logger.warning(
         "Failure while updating database for IPv6 support.  See UPGRADE.txt for instructions on how to manually complete this optional step.",
         e);
     DatabaseConnection.rollbackOnException(status, e);
     status = null; // so we do not try to commit
   }
   if (status != null) {
     DatabaseConnection.commit(status);
   }
   return messages;
 }
  @Override
  public void setConnection(final DatabaseConnection conn) {
    LogFactory.getLogger()
        .debug("Connected to " + conn.getConnectionUserName() + "@" + conn.getURL());
    this.connection = conn;
    try {
      boolean autoCommit = conn.getAutoCommit();
      if (autoCommit == getAutoCommitMode()) {
        // Don't adjust the auto-commit mode if it's already what the database wants it to be.
        LogFactory.getLogger()
            .debug("Not adjusting the auto commit mode; it is already " + autoCommit);
      } else {
        // Store the previous auto-commit mode, because the connection needs to be restored to it
        // when this
        // AbstractDatabase type is closed. This is important for systems which use connection
        // pools.
        previousAutoCommit = autoCommit;

        LogFactory.getLogger()
            .debug("Setting auto commit to " + getAutoCommitMode() + " from " + autoCommit);
        connection.setAutoCommit(getAutoCommitMode());
      }
    } catch (DatabaseException e) {
      LogFactory.getLogger()
          .warning("Cannot set auto commit to " + getAutoCommitMode() + " on connection");
    }

    this.connection.attached(this);
  }
  public void setup() {
    if (databasePool != null) {
      DatabaseConnection database = null;
      IDataSet dataSet = null;
      try {
        database = databasePool.borrowInstance(this);
        dataSet = database.getDataSet(dbQuery, true);

        int keyIdx = dataSet.getFieldIndex(keyColumn);
        int valueIdx = dataSet.getFieldIndex(valueColumn);

        while (dataSet.next()) {
          String name = dataSet.getFieldValue(keyIdx).asString();
          String value = dataSet.getFieldValue(valueIdx).asString();
          getLocalPropertyMap().put(name, value);
        }
      } catch (Exception e) {
        throw new RuntimeException(e);
      } finally {
        if (dataSet != null) {
          dataSet.close();
        }

        if (database != null) {
          databasePool.returnInstance(database, this);
        }
      }
    }
  }
Exemple #5
0
 public void closeDatabase() {
   try {
     databaseConnection.closeConnection();
     databaseConnection.closeStatement();
   } catch (SQLException e) {
     System.out.println(e);
   }
 }
 /**
  * Default implementation, just look for "local" IPs
  *
  * @throws liquibase.exception.DatabaseException
  */
 @Override
 public boolean isLocalDatabase() throws DatabaseException {
   DatabaseConnection connection = getConnection();
   if (connection == null) {
     return true;
   }
   String url = connection.getURL();
   return (url.contains("localhost")) || (url.contains("127.0.0.1"));
 }
 @Override
 public void close() throws DatabaseException {
   try {
     DatabaseConnection connection = getConnection();
     if (connection != null) {
       connection.close();
     }
   } catch (DatabaseException e) {
     throw new DatabaseException(e);
   }
 }
 @Override
 public void setConnection(DatabaseConnection conn) {
   LogFactory.getLogger()
       .debug("Connected to " + conn.getConnectionUserName() + "@" + conn.getURL());
   this.connection = conn;
   try {
     connection.setAutoCommit(getAutoCommitMode());
   } catch (DatabaseException sqle) {
     LogFactory.getLogger()
         .warning("Can not set auto commit to " + getAutoCommitMode() + " on connection");
   }
 }
  /** checks the last tweeted ID and invokes the methode getAllTweets */
  private void runHamletTweets() {

    /** the methode prepareStatements is not necessary */
    dc.prepareStatements();

    last_tweet = getLastTweet();
    /** System.out.println("LAST TWEET id: "+last_tweet); */
    last_tweet = dc.getAllTweets(last_tweet);
    System.out.println(last_tweet);
    saveLastTweet(last_tweet);

    System.out.println("end");
  }
Exemple #10
0
 public void addNewUser(User user) throws SQLException {
   try {
     String queryString =
         "INSERT INTO ratunes.user " + "(name, email, password)" + " VALUES " + "(?, ?, ?)";
     PreparedStatement statement = databaseConnection.getStatement(queryString);
     statement.setString(1, user.getName());
     statement.setString(2, user.getEmail());
     statement.setString(3, user.getPassword());
     statement.executeUpdate();
   } catch (SQLException e) {
     System.out.println(e);
   } finally {
     databaseConnection.closeDatabase();
   }
 }
Exemple #11
0
 /**
  * Special login method - it cannot be assumed that the database schema is unchanged, so do not
  * use standard methods.
  */
 public static boolean login(String username, String password) throws WikiException {
   WikiVersion oldVersion =
       new WikiVersion(Environment.getValue(Environment.PROP_BASE_WIKI_VERSION));
   if (!oldVersion.before(0, 7, 0)) {
     try {
       return (WikiBase.getDataHandler().authenticate(username, password));
     } catch (DataAccessException e) {
       logger.severe("Unable to authenticate user during upgrade", e);
       throw new WikiException(new WikiMessage("upgrade.error.fatal", e.getMessage()));
     }
   }
   try {
     Connection conn = DatabaseConnection.getConnection();
     WikiPreparedStatement stmt =
         new WikiPreparedStatement(
             "select 1 from jam_wiki_user_info where login = ? and encoded_password = ?");
     if (!StringUtils.isBlank(password)) {
       password = Encryption.encrypt(password);
     }
     stmt.setString(1, username);
     stmt.setString(2, password);
     WikiResultSet rs = stmt.executeQuery(conn);
     return (rs.size() > 0);
   } catch (SQLException e) {
     logger.severe("Database failure while authenticating user", e);
     throw new WikiException(new WikiMessage("upgrade.error.fatal", e.getMessage()));
   }
 }
Exemple #12
0
 protected static void setup(Locale locale, WikiUser user) throws Exception {
   Connection conn = null;
   try {
     try {
       conn = WikiDatabase.getConnection();
       // set up tables
       WikiDatabase.queryHandler().createTables(conn);
     } catch (Exception e) {
       logger.severe("Unable to set up database tables", e);
       // clean up anything that might have been created
       WikiDatabase.queryHandler().dropTables(conn);
       throw e;
     }
     try {
       WikiDatabase.setupDefaultVirtualWiki(conn);
       WikiDatabase.setupAdminUser(user, conn);
       WikiDatabase.setupSpecialPages(locale, user, conn);
     } catch (Exception e) {
       DatabaseConnection.handleErrors(conn);
       throw e;
     }
   } finally {
     WikiDatabase.releaseConnection(conn);
   }
 }
Exemple #13
0
  @Before
  public void populate() throws Exception {
    queryTemplate.run(
        new UpdateQuery() {
          @Override
          public Integer perform(DatabaseConnection connection) throws Exception {
            int affectedRows = 0;

            affectedRows +=
                connection.executeUpdate(
                    "INSERT INTO Person (id, name, birthday, employed) VALUES (?, ?, ?, ?)",
                    1,
                    "John",
                    johnBirthday,
                    true);
            affectedRows +=
                connection.executeUpdate(
                    "INSERT INTO Person (id, name, birthday, employed) VALUES (?, ?, ?, ?)",
                    2,
                    "Doe",
                    doeBirthday,
                    false);

            return affectedRows;
          }
        },
        true);

    DatabaseConnection.clearCache();
  }
Exemple #14
0
  /** 扩展基类的preDelete方法,对实际业务做删除前的检验 */
  public int preDelete(
      SessionContext ctx,
      DatabaseConnection conn,
      FormInstance instance,
      ErrorMessages msgs,
      EventManager manager,
      SqlAssistor assistor) {

    String cltNo = ctx.getParameter("CLIENTNO");

    String bmStr = "select * from bmtable where clientno='" + cltNo + "'";
    RecordSet bmRs = conn.executeQuery(bmStr);
    if (bmRs.next()) {
      msgs.add("还有业务没有删除");
      return -1;
    }

    RecordSet rs = conn.executeQuery("select id from CMINDVCLIENT where clientno='" + cltNo + "'");

    if (!rs.next()) {
      msgs.add("取得id失败!");
      return -1;
    } else {
      String id = rs.getString("ID");
      String tempStr = "select * from bmguarantor where id='" + id + "'";
      // System.out.println(tempStr);
      RecordSet tempRs = conn.executeQuery(tempStr);
      if (tempRs.next()) {
        msgs.add("还有担保的贷款,不能删除!");
        return -1;
      }
    }

    String sql1[] = new String[4];
    sql1[0] = "delete from CMINDVRELA where clientno='" + cltNo + "'";
    sql1[1] = "delete from CMINDVASSET where clientno='" + cltNo + "'"; //
    sql1[2] = "delete from CMINDVDEBT where clientno='" + cltNo + "'"; //
    sql1[3] = "delete from CMINDVDEBTPAYMENT where clientno='" + cltNo + "'"; //
    String sql2 = "";
    for (int i = 0; i < sql1.length; i++) {
      sql2 += sql1[i] + ";";
    }
    sql2 = sql2.substring(0, sql2.length() - 1);
    // System.out.println(sql2);
    int ret = conn.executeUpdate(sql2);
    return ret;
  }
  public static boolean registerUser(String username, String password, String passwordConfirm) {

    // check required limits on lengths of username and password
    // if those are good, call database register user
    // check to see if that user is already registered
    if (db.checkEmail(username)) return false;
    // if everything is good, register the user, set the current user information
    else {
      db.registerUser(username, password);
      loggedIn = true;
      currUserEmail = username;
      currUserPassword = password;
    }

    // to make the compiler happy until we finish implementation
    return true;
  }
  @Override
  public void close() throws DatabaseException {
    DatabaseConnection connection = getConnection();
    if (connection != null) {
      if (previousAutoCommit != null) {
        try {
          connection.setAutoCommit(previousAutoCommit);
        } catch (DatabaseException e) {
          LogFactory.getLogger()
              .warning("Failed to restore the auto commit to " + previousAutoCommit);

          throw e;
        }
      }
      connection.close();
    }
    ExecutorService.getInstance().clearExecutor(this);
  }
 public static boolean checkLogin(String username, String password) {
   loggedIn = db.checkLogin(username, password);
   // if the login was successful, set the current user information
   if (loggedIn) {
     currUserEmail = username;
     currUserPassword = password;
   }
   return loggedIn;
 }
Exemple #18
0
 public static List<WikiMessage> upgrade061(List<WikiMessage> messages) throws WikiException {
   TransactionStatus status = null;
   try {
     status = DatabaseConnection.startTransaction(getTransactionDefinition());
     Connection conn = DatabaseConnection.getConnection();
     // delete ROLE_DELETE
     WikiBase.getDataHandler()
         .executeUpgradeUpdate("UPGRADE_061_DELETE_ROLE_MAP_ROLE_DELETE", conn);
     WikiBase.getDataHandler().executeUpgradeUpdate("UPGRADE_061_DELETE_ROLE_ROLE_DELETE", conn);
     messages.add(new WikiMessage("upgrade.message.db.data.deleted", "jam_role_map"));
     messages.add(new WikiMessage("upgrade.message.db.data.deleted", "jam_role"));
   } catch (SQLException e) {
     DatabaseConnection.rollbackOnException(status, e);
     logger.severe("Database failure during upgrade", e);
     throw new WikiException(new WikiMessage("upgrade.error.fatal", e.getMessage()));
   }
   DatabaseConnection.commit(status);
   return messages;
 }
Exemple #19
0
  public boolean checkLogin(User user) throws SQLException {
    boolean result = false;
    try {
      String queryString = "SELECT id FROM user WHERE name=? and password=?";
      PreparedStatement statement = databaseConnection.getStatement(queryString);
      statement.setString(1, user.getName());
      statement.setString(2, user.getPassword());

      ResultSet resultSet = statement.executeQuery();
      if (resultSet.next()) {
        result = true;
        user.setId(resultSet.getInt("id"));
      }
    } catch (SQLException e) {
      System.out.println(e);
    } finally {
      databaseConnection.closeDatabase();
    }
    return result;
  }
 static void addNewLanguage() {
   if (dbIsOpen()) {
     System.out.println("New language name: ");
     String newLanguage = scanner.next();
     try {
       DatabaseConnection.updateListOfLanguages(flags.getConnection(), newLanguage);
     } catch (SQLException ex) {
       printSQLException(ex);
     }
   }
 }
 @Override
 public int getDatabaseMinorVersion() throws DatabaseException {
   if (connection == null) {
     return -1;
   }
   try {
     return connection.getDatabaseMinorVersion();
   } catch (DatabaseException e) {
     throw new DatabaseException(e);
   }
 }
  /**
   * Добавляет в БД время отправки сообщения.
   *
   * @param date время,добавляемое в базу данных
   * @param messageId id сообщения для которого добавляется время
   */
  public void setSendTime(Date date, Integer messageId) {

    try (SqlSession session = DatabaseConnection.getDatabase().openSession()) {
      try {
        MessageMapper mapp = session.getMapper(MessageMapper.class);
        mapp.addSendTime(date, messageId);
        session.commit();
      } catch (Exception e) {
        log.severe(e, "Ошибка добавления в базу времени отправления сообщения!");
      }
    }
  }
Exemple #23
0
 private static void releaseConnection(Connection conn) throws Exception {
   if (conn == null) {
     return;
   }
   try {
     conn.commit();
   } finally {
     if (conn != null) {
       DatabaseConnection.closeConnection(conn);
     }
   }
 }
  /**
   * Меняет в Бд статус отправки конкретного сообщения по его id.
   *
   * @param messageId id сообщения для которого меняется статус
   * @param statusString новый статус
   */
  public void setSendStatus(Integer messageId, String statusString) {

    try (SqlSession session = DatabaseConnection.getDatabase().openSession()) {
      try {
        MessageMapper mapp = session.getMapper(MessageMapper.class);
        mapp.changeMessageStatus(messageId, statusString);
        session.commit();
      } catch (Exception e) {
        log.severe(e, "Ошибка изменения статуса отправки сообщения!");
      }
    }
  }
  /** Returns the name of the database product according to the underlying database. */
  @Override
  public String getDatabaseProductName() {
    if (connection == null) {
      return getDefaultDatabaseProductName();
    }

    try {
      return connection.getDatabaseProductName();
    } catch (DatabaseException e) {
      throw new RuntimeException("Cannot get database name");
    }
  }
  @Override
  public String getDatabaseProductVersion() throws DatabaseException {
    if (connection == null) {
      return null;
    }

    try {
      return connection.getDatabaseProductVersion();
    } catch (DatabaseException e) {
      throw new DatabaseException(e);
    }
  }
Exemple #27
0
  public int buttonEvent(
      SessionContext ctx,
      DatabaseConnection conn,
      FormInstance instance,
      String button,
      ErrorMessages msgs,
      EventManager manager) {
    // String CLIENTNO = instance.getStringValue("CLIENTNO");
    String CLIENTNO = strClientNo;
    // String CLIENTNO = ctx.getParameter("CLIENTNO");
    if (CLIENTNO == null || CLIENTNO.length() < 1 || CLIENTNO.equals("自动生成")) {
      System.out.println(CLIENTNO);
      msgs.add("请确定个人客户资料信息已经存在!");
      return -1;
    }
    // setRequestAtrribute
    ctx.setRequestAtrribute("flag", flag);
    ctx.setRequestAtrribute("CLIENTNO", CLIENTNO);

    if (button.equals("CMINDVRELA")) {
      trigger(manager, "100012", null);
    } else if (button.equals("BMRQL")) {
      trigger(manager, "BMRQL1", null);
    } else if (button.equals("BMCREDITLMAINTPAGE")) {
      trigger(manager, "BMCREDITLMAINTPAGE", null);
    } else if (button.equals("PHOTO")) {
      // ctx.setRequestAtrribute("PHOTONO",ctx.getParameter("PHOTONO"));
      ctx.setRequestAtrribute("TABLENAME", "CMINDVCLIENT");
      ctx.setRequestAtrribute("WHERECONDITION", "clientno='" + CLIENTNO + "'");
      ctx.setRequestAtrribute("title", "个人客户图片");
      ctx.setRequestAtrribute("flag", this.flag);
      ctx.setTarget("/photo/photo.jsp");
    } else if (button.equals("CREDIT")) {
      RecordSet rs =
          conn.executeQuery("select id from CMINDVCLIENT where clientno='" + CLIENTNO + "'");
      if (!rs.next()) {
        msgs.add("取得id失败!");
        return -1;
      }
      String id = rs.getString("ID");
      ctx.setRequestAtrribute("ID", id);
      trigger(manager, "GUARANTORCREDITLIST", null);
      return 0;
    }

    /**
     * else if (button.equals("CMINDVASSET")) { trigger(manager, "100013", null); } else if
     * (button.equals("CMINDVDEBT")) { trigger(manager, "100014", null); } else if
     * (button.equals("CMINDVDEBTPAYMENT")) { trigger(manager, "100015", null); }
     */
    return 0;
  }
Exemple #28
0
 protected static void initialize() {
   try {
     WikiDatabase.CONNECTION_VALIDATION_QUERY =
         WikiDatabase.queryHandler().connectionValidationQuery();
     WikiDatabase.EXISTENCE_VALIDATION_QUERY =
         WikiDatabase.queryHandler().existenceValidationQuery();
     // initialize connection pool in its own try-catch to avoid an error
     // causing property values not to be saved.
     DatabaseConnection.setPoolInitialized(false);
   } catch (Exception e) {
     logger.severe("Unable to initialize database", e);
   }
 }
 static void showLanguages() {
   if (dbIsOpen()) {
     try {
       ArrayList<String> listOfLanguages =
           DatabaseConnection.getListOfLanguages(flags.getConnection());
       for (String language : listOfLanguages) {
         System.out.println(language);
       }
     } catch (SQLException ex) {
       printSQLException(ex);
     }
   }
 }
 public static void toStdOut(
     final GetMetricStatisticsResult result, final String instanceId, final String metricOption) {
   for (final Datapoint dataPoint : result.getDatapoints()) {
     DateFormat timeStampvalue = new SimpleDateFormat("dd/MM/yy HH:mm:ss");
     Calendar calobj = Calendar.getInstance();
     String timeStamp = timeStampvalue.format(calobj.getTime());
     DatabaseConnection.insertData(instanceId, metricOption, dataPoint.getAverage());
     // System.out.printf("%s %s : %s %s %n", instanceId,metricOption,
     // dataPoint.getAverage(),timeStamp,dataPoint);
     // System.out.printf("***TimeStamp***", instanceId,metricOption,
     // dataPoint.getAverage(),timeStamp,dataPoint);
   }
 }