Example usage for java.sql PreparedStatement setString

List of usage examples for java.sql PreparedStatement setString

Introduction

In this page you can find the example usage for java.sql PreparedStatement setString.

Prototype

void setString(int parameterIndex, String x) throws SQLException;

Source Link

Document

Sets the designated parameter to the given Java String value.

Usage

From source file:com.keybox.manage.db.SessionAuditDB.java

/**
 * insert new terminal history for user/*  ww w  . j  a  v  a  2  s. c  o  m*/
 *
 * @param con           DB connection
 * @param sessionOutput output from session terminals
 * @return session id
 */
public static void insertTerminalLog(Connection con, SessionOutput sessionOutput) {

    try {

        if (sessionOutput != null && sessionOutput.getSessionId() != null
                && sessionOutput.getInstanceId() != null && sessionOutput.getOutput() != null
                && !sessionOutput.getOutput().toString().equals("")) {
            //insert
            PreparedStatement stmt = con.prepareStatement(
                    "insert into terminal_log (session_id, instance_id, system_id, output) values(?,?,?,?)");
            stmt.setLong(1, sessionOutput.getSessionId());
            stmt.setLong(2, sessionOutput.getInstanceId());
            stmt.setLong(3, sessionOutput.getId());
            stmt.setString(4, sessionOutput.getOutput().toString());
            stmt.execute();
            DBUtils.closeStmt(stmt);
        }

    } catch (Exception e) {
        log.error(e.toString(), e);
    }

}

From source file:com.keybox.manage.db.PublicKeyDB.java

/**
 * checks fingerprint to determine if key is disabled
 * /*from  www . java2 s  .  c o  m*/
 * @param fingerprint public key fingerprint
 * @return true if disabled
 */
public static boolean isKeyDisabled(String fingerprint) {
    boolean isDisabled = false;

    Connection con = null;
    try {
        con = DBUtils.getConn();
        PreparedStatement stmt = con
                .prepareStatement("select * from  public_keys where fingerprint like ? and enabled=false");
        stmt.setString(1, fingerprint);
        ResultSet rs = stmt.executeQuery();

        if (rs.next()) {
            isDisabled = true;
        }

        DBUtils.closeRs(rs);
        DBUtils.closeStmt(stmt);
    } catch (Exception e) {
        log.error(e.toString(), e);
    }
    DBUtils.closeConn(con);

    return isDisabled;

}

From source file:com.act.lcms.db.model.ScanFile.java

protected static void bindInsertOrUpdateParameters(PreparedStatement stmt, String filename, SCAN_MODE mode,
        SCAN_FILE_TYPE fileType, Integer plateId, Integer plateRow, Integer plateColumn) throws SQLException {
    stmt.setString(DB_FIELD.FILENAME.getInsertUpdateOffset(), filename);
    stmt.setString(DB_FIELD.MODE.getInsertUpdateOffset(), mode.name());
    stmt.setString(DB_FIELD.FILE_TYPE.getInsertUpdateOffset(), fileType.name());
    if (plateId != null) {
        stmt.setInt(DB_FIELD.PLATE_ID.getInsertUpdateOffset(), plateId);
    } else {/* w w  w  .ja v  a  2 s. co  m*/
        stmt.setNull(DB_FIELD.PLATE_ID.getInsertUpdateOffset(), Types.INTEGER);
    }
    if (plateRow != null) {
        stmt.setInt(DB_FIELD.PLATE_ROW.getInsertUpdateOffset(), plateRow);
    } else {
        stmt.setNull(DB_FIELD.PLATE_ROW.getInsertUpdateOffset(), Types.INTEGER);
    }
    if (plateColumn != null) {
        stmt.setInt(DB_FIELD.PLATE_COLUMN.getInsertUpdateOffset(), plateColumn);
    } else {
        stmt.setNull(DB_FIELD.PLATE_COLUMN.getInsertUpdateOffset(), Types.INTEGER);
    }
}

From source file:com.trackplus.ddl.DataWriter.java

private static void insertClobData(Connection con, String line) throws DDLException {
    /*/*w  w  w .  j  ava2  s.  c o  m*/
    "OBJECTID",//Integer not null
    "EXCHANGEDIRECTION",//Integer not null
    "ENTITYID",//Integer not null
    "ENTITYTYPE",//Integer not null
    "FILENAME",//Varchar(255)
    "CHANGEDBY",//Integer
    "LASTEDIT",//Timestamp
    "TPUUID",//Varchar(36)
    "FILECONTENT"//Blob sub_type 1
     */

    String sql = "INSERT INTO TMSPROJECTEXCHANGE(OBJECTID, EXCHANGEDIRECTION, ENTITYID,ENTITYTYPE,FILENAME,CHANGEDBY,LASTEDIT,TPUUID,FILECONTENT) "
            + "VALUES(?,?,?,?,?,?,?,?,?)";
    StringTokenizer st = new StringTokenizer(line, ",");
    Integer objectID = Integer.valueOf(st.nextToken());
    Integer exchangeDirection = Integer.valueOf(st.nextToken());
    Integer entityID = Integer.valueOf(st.nextToken());
    Integer entityType = Integer.valueOf(st.nextToken());
    String fileName = st.nextToken();
    if ("null".equalsIgnoreCase(fileName)) {
        fileName = null;
    }
    Integer changedBy = null;
    try {
        changedBy = Integer.valueOf(st.nextToken());
    } catch (Exception ex) {
        LOGGER.debug(ex);
    }

    Timestamp lastEdit = null;
    String lastEditStr = st.nextToken();
    if (lastEditStr != null) {
        try {
            lastEdit = Timestamp.valueOf(lastEditStr);
        } catch (Exception ex) {
            LOGGER.debug(ex);
        }
    }
    String tpuid = st.nextToken();
    String base64Str = st.nextToken();
    if (base64Str.length() == 1 && " ".equals(base64Str)) {
        base64Str = "";
    }
    byte[] bytes = Base64.decodeBase64(base64Str);
    String fileContent = new String(bytes);

    try {
        PreparedStatement preparedStatement = con.prepareStatement(sql);

        preparedStatement.setInt(1, objectID);
        preparedStatement.setInt(2, exchangeDirection);
        preparedStatement.setInt(3, entityID);
        preparedStatement.setInt(4, entityType);
        preparedStatement.setString(5, fileName);
        preparedStatement.setInt(6, changedBy);
        preparedStatement.setTimestamp(7, lastEdit);
        preparedStatement.setString(8, tpuid);
        preparedStatement.setString(9, fileContent);

        preparedStatement.executeUpdate();
    } catch (SQLException e) {
        throw new DDLException(e.getMessage(), e);
    }

}

From source file:com.chaosinmotion.securechat.server.commands.UpdateForgottenPassword.java

public static boolean processRequest(Login.UserInfo userinfo, JSONObject requestParams)
        throws ClassNotFoundException, SQLException, IOException {
    String newPassword = requestParams.getString("password");
    String requestToken = requestParams.getString("token");

    /*/*from   ww w  .jav a2s .com*/
     * Determine if the token matches for this user record. We are in the
     * unique situation of having a logged in user, but he doesn't know
     * his password. We also ignore any requests with an expired
     * token.
     */

    Connection c = null;
    PreparedStatement ps = null;
    ResultSet rs = null;

    try {
        /*
         * Delete old requests
         */
        c = Database.get();
        ps = c.prepareStatement("DELETE FROM forgotpassword WHERE expires < LOCALTIMESTAMP");
        ps.execute();

        ps.close();
        ps = null;

        /*
         * Verify the token we passed back was correct
         */
        ps = c.prepareStatement(
                "SELECT token " + "FROM forgotpassword " + "WHERE userid = ? " + "AND token = ?");
        ps.setInt(1, userinfo.getUserID());
        ps.setString(2, requestToken);
        rs = ps.executeQuery();
        if (!rs.next())
            return false; // token does not exist or expired.

        rs.close();
        rs = null;
        ps.close();
        ps = null;

        /*
         * Step 2: Modify the password.
         */

        ps = c.prepareStatement("UPDATE Users SET password = ? WHERE userid = ?");
        ps.setString(1, newPassword);
        ps.setInt(2, userinfo.getUserID());
        ps.execute();

        return true;
    } finally {
        if (rs != null)
            rs.close();
        if (ps != null)
            ps.close();
        if (c != null)
            c.close();
    }
}

From source file:com.mirth.connect.server.controllers.tests.TestUtils.java

public static boolean channelExists(String channelId) throws Exception {
    boolean exists = false;
    Connection connection = getConnection();
    PreparedStatement statement = connection.prepareStatement("SELECT 1 FROM channels WHERE channel_id = ?");
    statement.setString(1, channelId);
    ResultSet result = statement.executeQuery();

    if (result.next()) {
        exists = true;//from  w w w  . j  a va2 s.co  m
    }

    result.close();
    connection.close();
    return exists;
}

From source file:edu.jhu.pha.vospace.storage.SwiftStorageManager.java

public static String generateRandomCredentials(final String username) {
    return DbPoolServlet.goSql("Generate random credentials",
            "select username, apikey from storage_users_pool where user_id IS NULL limit 1;",
            new SqlWorker<String>() {
                @Override//from   w  ww .  j  av  a2s .co m
                public String go(Connection conn, PreparedStatement stmt) throws SQLException {
                    ResultSet rs = stmt.executeQuery();
                    if (rs.next()) {
                        String user = rs.getString("username");
                        String password = rs.getString("apikey");
                        PreparedStatement prep = conn.prepareStatement(
                                "update storage_users_pool SET user_id = (select user_id from user_identities where identity = ?) where username = ?");
                        prep.setString(1, username);
                        prep.setString(2, user);
                        prep.execute();

                        logger.debug(username + " " + user);

                        StringWriter writer = new StringWriter();
                        JsonFactory f = new JsonFactory();
                        try {
                            JsonGenerator g = f.createJsonGenerator(writer);

                            g.writeStartObject();
                            g.writeStringField("username", user);
                            g.writeStringField("apikey", password);
                            g.writeEndObject();

                            g.close(); // important: will force flushing of output, close underlying output stream

                            return writer.getBuffer().toString();
                        } catch (JsonGenerationException ex) {
                            throw new InternalServerErrorException(
                                    "Error generating user storage credentials. " + ex.getMessage());
                        } catch (IOException e) {
                            throw new InternalServerErrorException(
                                    "Error generating user storage credentials. " + e.getMessage());
                        }

                    } else
                        throw new PermissionDeniedException("The user does not exist.");
                }
            });

}

From source file:ca.qc.adinfo.rouge.variable.db.PersistentVariableDb.java

public static boolean updatePersitentVariable(DBManager dbManager, User user, Variable variable) {

    Connection connection = null;
    PreparedStatement stmt = null;
    ResultSet rs = null;/*from ww w . ja va 2s  .c  o m*/
    String sql = null;

    if (variable.getVersion() == 0) {
        sql = "INSERT INTO rouge_persistant_variable (`key`, `value`, `version`, `creator_user_id`) "
                + " VALUES (?, ?, ?, ?);";
    } else {
        sql = "UPDATE rouge_persistant_variable SET `value` = ?, `version` = ? "
                + " WHERE `key` = ? AND `version` = ?";
    }

    try {
        connection = dbManager.getConnection();
        stmt = connection.prepareStatement(sql);

        if (variable.getVersion() == 0) {
            stmt.setString(1, variable.getKey());
            stmt.setString(2, variable.getValue().toJSON().toString());
            stmt.setLong(3, 1);
            stmt.setLong(4, user.getId());

            variable.setVersion(1);
        } else {
            stmt.setString(1, variable.getValue().toJSON().toString());
            stmt.setLong(2, variable.getVersion() + 1);
            stmt.setString(3, variable.getKey());
            stmt.setLong(4, variable.getVersion());

            variable.setVersion(variable.getVersion() + 1);
        }

        int ret = stmt.executeUpdate();

        return (ret > 0);

    } catch (SQLException e) {
        log.error(stmt);
        log.error(e);
        return false;

    } finally {

        DbUtils.closeQuietly(rs);
        DbUtils.closeQuietly(stmt);
        DbUtils.closeQuietly(connection);
    }
}

From source file:com.keybox.manage.db.UserThemeDB.java

/**
 * saves user theme/*  www  .j  av a  2s  .c  o  m*/
 * 
 * @param userId object
 */
public static void saveTheme(Long userId, UserSettings theme) {

    Connection con = null;
    try {
        con = DBUtils.getConn();
        PreparedStatement stmt = con.prepareStatement("delete from user_theme where user_id=?");
        stmt.setLong(1, userId);
        stmt.execute();
        DBUtils.closeStmt(stmt);

        if (org.apache.commons.lang.StringUtils.isNotEmpty(theme.getPlane())
                || org.apache.commons.lang.StringUtils.isNotEmpty(theme.getTheme())) {

            stmt = con.prepareStatement(
                    "insert into user_theme(user_id, bg, fg, d1, d2, d3, d4, d5, d6, d7, d8, b1, b2, b3, b4, b5, b6, b7, b8) values (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)");
            stmt.setLong(1, userId);
            stmt.setString(2, theme.getBg());
            stmt.setString(3, theme.getFg());
            //if contains all 16 theme colors insert
            if (theme.getColors() != null && theme.getColors().length == 16) {
                for (int i = 0; i < 16; i++) {
                    stmt.setString(i + 4, theme.getColors()[i]);
                }
                //else set to null
            } else {
                for (int i = 0; i < 16; i++) {
                    stmt.setString(i + 4, null);
                }
            }
            stmt.execute();
            DBUtils.closeStmt(stmt);
        }

    } catch (Exception e) {
        log.error(e.toString(), e);
    }
    DBUtils.closeConn(con);

}

From source file:com.keybox.manage.db.PublicKeyDB.java

/**
 * inserts new public key//from  w  w  w.  j a  v  a 2 s . c  o m
 *
 * @param publicKey key object
 */
public static void insertPublicKey(PublicKey publicKey) {

    Connection con = null;
    try {
        con = DBUtils.getConn();
        PreparedStatement stmt = con.prepareStatement(
                "insert into public_keys(key_nm, type, fingerprint, public_key, profile_id, user_id) values (?,?,?,?,?,?)");
        stmt.setString(1, publicKey.getKeyNm());
        stmt.setString(2, SSHUtil.getKeyType(publicKey.getPublicKey()));
        stmt.setString(3, SSHUtil.getFingerprint(publicKey.getPublicKey()));
        stmt.setString(4, publicKey.getPublicKey().trim());
        if (publicKey.getProfile() == null || publicKey.getProfile().getId() == null) {
            stmt.setNull(5, Types.NULL);
        } else {
            stmt.setLong(5, publicKey.getProfile().getId());
        }
        stmt.setLong(6, publicKey.getUserId());
        stmt.execute();

        DBUtils.closeStmt(stmt);

    } catch (Exception e) {
        log.error(e.toString(), e);
    }
    DBUtils.closeConn(con);

}