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:edu.jhu.pha.vospace.oauth.MySQLOAuthProvider2.java

/**
 * Generate a fresh request token and secret for a consumer.
 * /*  w  w w  .  java  2 s  .  co  m*/
 * @throws OAuthException
 */
public static synchronized Token generateRequestToken(final String consumer_key, final String callback_url,
        final MultivaluedMap<String, String> attributes) {

    // generate token and secret based on consumer_key

    // for now use md5 of name + current time as token
    final String token_data = consumer_key + System.nanoTime();
    final String token = DigestUtils.md5Hex(token_data);
    // for now use md5 of name + current time + token as secret
    final String secret_data = consumer_key + System.nanoTime() + token;
    final String secret = DigestUtils.md5Hex(secret_data);

    Token tokenObj = new Token(token, secret, consumer_key, callback_url, attributes);

    if (null == attributes.getFirst("share")) {
        DbPoolServlet.goSql("Insert new request token",
                "insert into oauth_accessors (request_token, token_secret, consumer_id, created) select ?, ?, consumer_id , ? from oauth_consumers where consumer_key = ?",
                new SqlWorker<Boolean>() {
                    @Override
                    public Boolean go(Connection conn, PreparedStatement stmt) throws SQLException {
                        stmt.setString(1, token);
                        stmt.setString(2, secret);
                        stmt.setString(3,
                                dateFormat.format(Calendar.getInstance(TimeZone.getTimeZone("UTC")).getTime()));
                        stmt.setString(4, consumer_key);
                        return stmt.execute();
                    }
                });
    } else {
        DbPoolServlet.goSql("Insert new request token",
                "insert into oauth_accessors (request_token, token_secret, consumer_id, container_id, created, accessor_write_permission, share_key) "
                        + "select ?, ?, consumer_id , container_id, ?, share_write_permission, share_key "
                        + "from oauth_consumers, container_shares " + "where consumer_key = ? and share_id = ?",
                new SqlWorker<Boolean>() {
                    @Override
                    public Boolean go(Connection conn, PreparedStatement stmt) throws SQLException {
                        stmt.setString(1, token);
                        stmt.setString(2, secret);
                        stmt.setString(3,
                                dateFormat.format(Calendar.getInstance(TimeZone.getTimeZone("UTC")).getTime()));
                        stmt.setString(4, consumer_key);
                        stmt.setString(5, attributes.getFirst("share"));
                        return stmt.execute();
                    }
                });
    }

    return tokenObj;
}

From source file:com.sf.ddao.factory.param.ParameterHelper.java

public static void bind(PreparedStatement preparedStatement, int idx, Object param, Class<?> clazz,
        Context context) throws SQLException {
    if (clazz == Integer.class || clazz == Integer.TYPE) {
        preparedStatement.setInt(idx, (Integer) param);
    } else if (clazz == String.class) {
        preparedStatement.setString(idx, (String) param);
    } else if (clazz == Long.class || clazz == Long.TYPE) {
        preparedStatement.setLong(idx, (Long) param);
    } else if (clazz == Boolean.class || clazz == Boolean.TYPE) {
        preparedStatement.setBoolean(idx, (Boolean) param);
    } else if (BigInteger.class.isAssignableFrom(clazz)) {
        BigInteger bi = (BigInteger) param;
        preparedStatement.setBigDecimal(idx, new BigDecimal(bi));
    } else if (Timestamp.class.isAssignableFrom(clazz)) {
        preparedStatement.setTimestamp(idx, (Timestamp) param);
    } else if (Date.class.isAssignableFrom(clazz)) {
        if (!java.sql.Date.class.isAssignableFrom(clazz)) {
            param = new java.sql.Date(((Date) param).getTime());
        }//w ww.ja v a2  s. c  o m
        preparedStatement.setDate(idx, (java.sql.Date) param);
    } else if (BoundParameter.class.isAssignableFrom(clazz)) {
        ((BoundParameter) param).bindParam(preparedStatement, idx, context);
    } else {
        throw new SQLException("Unimplemented type mapping for " + clazz);
    }
}

From source file:edu.jhu.pha.vospace.oauth.MySQLOAuthProvider2.java

/**
 * Set the access token/*www . j av  a2 s.co  m*/
 * If userId != null, creates link to user's container as root matching the name in consumer. The container should exist already.
 * @param accessor The OAuth accessor object
 * @param userId the owner userId
 * @throws OAuthException
 */
public static synchronized void markAsAuthorized(final Token requestToken, final String userId) {

    try {
        if (null == requestToken.getAttributes().getFirst("root_container")) { // No predefined one (can be predefined for sharing); in this case set the default one
            final String default_root_container = ((Consumer) requestToken.getConsumer()).getAttributes()
                    .getFirst("container");
            if (!UserHelper.userExists(userId)) {
                UserHelper.addDefaultUser(userId);
            }

            //First check if the root node exists
            VospaceId identifier = new VospaceId(new NodePath(default_root_container));
            Node node = NodeFactory.createNode(identifier, userId, NodeType.CONTAINER_NODE);
            logger.debug("Marking as authorized, root node: " + identifier.toString());
            if (!node.isStoredMetadata()) {
                node.setNode(null);
                logger.debug("Creating the node " + node.getUri());
            }

            DbPoolServlet.goSql("Mark oauth token as authorized",
                    "update oauth_accessors set container_id = (select container_id from containers join user_identities on containers.user_id = user_identities.user_id where identity = ? and container_name = ?), authorized = 1 where request_token = ?;",
                    new SqlWorker<Integer>() {
                        @Override
                        public Integer go(Connection conn, PreparedStatement stmt) throws SQLException {
                            stmt.setString(1, userId);
                            stmt.setString(2, default_root_container);
                            stmt.setString(3, requestToken.getToken());
                            return stmt.executeUpdate();
                        }
                    });
        } else { // the container is already set up (sharing)
            DbPoolServlet.goSql("Mark oauth token as authorized",
                    "update oauth_accessors set authorized = 1 where request_token = ?;",
                    new SqlWorker<Integer>() {
                        @Override
                        public Integer go(Connection conn, PreparedStatement stmt) throws SQLException {
                            stmt.setString(1, requestToken.getToken());
                            return stmt.executeUpdate();
                        }
                    });
        }
    } catch (URISyntaxException ex) {
        logger.error("Error creating root (app) node for user: " + ex.getMessage());
    }

}

From source file:dataMappers.PictureDataMapper.java

public static void addPictureToReport(DBConnector dbconnector, HttpServletRequest request)
        throws FileUploadException, IOException, SQLException {

    if (!ServletFileUpload.isMultipartContent(request)) {
        System.out.println("Invalid upload request");
        return;/*from   w  ww  . jav  a2s  .c  o m*/
    }

    // Define limits for disk item
    DiskFileItemFactory factory = new DiskFileItemFactory();
    factory.setSizeThreshold(THRESHOLD_SIZE);

    // Define limit for servlet upload
    ServletFileUpload upload = new ServletFileUpload(factory);
    upload.setFileSizeMax(MAX_FILE_SIZE);
    upload.setSizeMax(MAX_REQUEST_SIZE);

    FileItem itemFile = null;
    int reportID = 0;

    // Get list of items in request (parameters, files etc.)
    List formItems = upload.parseRequest(request);
    Iterator iter = formItems.iterator();

    // Loop items
    while (iter.hasNext()) {
        FileItem item = (FileItem) iter.next();

        if (!item.isFormField()) {
            itemFile = item; // If not form field, must be item
        } else if (item.getFieldName().equalsIgnoreCase("reportID")) { // else it is a form field
            try {
                System.out.println(item.getString());
                reportID = Integer.parseInt(item.getString());
            } catch (NumberFormatException e) {
                reportID = 0;
            }
        }
    }

    // This will be null if no fields were declared as image/upload.
    // Also, reportID must be > 0
    if (itemFile != null || reportID == 0) {

        try {

            // Create credentials from final vars
            BasicAWSCredentials awsCredentials = new BasicAWSCredentials(AMAZON_ACCESS_KEY, AMAZON_SECRET_KEY);

            // Create client with credentials
            AmazonS3 s3client = new AmazonS3Client(awsCredentials);
            // Set region
            s3client.setRegion(Region.getRegion(Regions.EU_WEST_1));

            // Set content length (size) of file
            ObjectMetadata om = new ObjectMetadata();
            om.setContentLength(itemFile.getSize());

            // Get extension for file
            String ext = FilenameUtils.getExtension(itemFile.getName());
            // Generate random filename
            String keyName = UUID.randomUUID().toString() + '.' + ext;

            // This is the actual upload command
            s3client.putObject(new PutObjectRequest(S3_BUCKET_NAME, keyName, itemFile.getInputStream(), om));

            // Picture was uploaded to S3 if we made it this far. Now we insert the row into the database for the report.
            PreparedStatement stmt = dbconnector.getCon()
                    .prepareStatement("INSERT INTO reports_pictures" + "(REPORTID, PICTURE) VALUES (?,?)");

            stmt.setInt(1, reportID);
            stmt.setString(2, keyName);

            stmt.executeUpdate();

            stmt.close();

        } catch (AmazonServiceException ase) {

            System.out.println("Caught an AmazonServiceException, which " + "means your request made it "
                    + "to Amazon S3, but was rejected with an error response" + " for some reason.");
            System.out.println("Error Message:    " + ase.getMessage());
            System.out.println("HTTP Status Code: " + ase.getStatusCode());
            System.out.println("AWS Error Code:   " + ase.getErrorCode());
            System.out.println("Error Type:       " + ase.getErrorType());
            System.out.println("Request ID:       " + ase.getRequestId());

        } catch (AmazonClientException ace) {

            System.out.println("Caught an AmazonClientException, which " + "means the client encountered "
                    + "an internal error while trying to " + "communicate with S3, "
                    + "such as not being able to access the network.");
            System.out.println("Error Message: " + ace.getMessage());

        }

    }
}

From source file:com.wso2telco.util.DbUtil.java

public static String updateRegistrationStatus(String uuid, String status)
        throws SQLException, AuthenticatorException {

    Connection connection;/*from  ww  w. ja v  a 2  s  .c om*/
    PreparedStatement ps;
    String sql = "UPDATE regstatus SET status = ? WHERE uuid = ?;";
    connection = getConnectDBConnection();
    ps = connection.prepareStatement(sql);
    ps.setString(1, status);
    ps.setString(2, uuid);
    log.info(ps.toString());
    ps.execute();

    if (connection != null) {
        connection.close();
    }
    return uuid;
}

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

/**
 * Process a forgot password request. This generates a token that the
 * client is expected to return with the change password request.
 * @param requestParams// w w w.  j  a  va2s  .  c o  m
 * @throws SQLException 
 * @throws IOException 
 * @throws ClassNotFoundException 
 * @throws JSONException 
 * @throws NoSuchAlgorithmException 
 */

public static void processRequest(JSONObject requestParams)
        throws SQLException, ClassNotFoundException, IOException, NoSuchAlgorithmException, JSONException {
    String username = requestParams.optString("username");

    /*
     * Step 1: Convert username to the userid for this
     */
    Connection c = null;
    PreparedStatement ps = null;
    ResultSet rs = null;

    int userID = 0;
    String retryID = UUID.randomUUID().toString();

    try {
        c = Database.get();
        ps = c.prepareStatement("SELECT userid " + "FROM Users " + "WHERE username = ?");
        ps.setString(1, username);
        rs = ps.executeQuery();
        if (rs.next()) {
            userID = rs.getInt(1);
        }

        if (userID == 0)
            return;
        ps.close();
        rs.close();

        /*
         * Step 2: Generate the retry token and insert into the forgot 
         * database with an expiration date 1 hour from now.
         */

        Timestamp ts = new Timestamp(System.currentTimeMillis() + 3600000);
        ps = c.prepareStatement("INSERT INTO ForgotPassword " + "    ( userid, token, expires ) " + "VALUES "
                + "    ( ?, ?, ?)");
        ps.setInt(1, userID);
        ps.setString(2, retryID);
        ps.setTimestamp(3, ts);
        ps.execute();
    } finally {
        if (rs != null)
            rs.close();
        if (ps != null)
            ps.close();
        if (c != null)
            c.close();
    }

    /*
     * Step 3: formulate a JSON string with the retry and send
     * to the user. The format of the command we send is:
     * 
     * { "cmd": "forgotpassword", "token": token }
     */

    JSONObject obj = new JSONObject();
    obj.put("cmd", "forgotpassword");
    obj.put("token", retryID);
    MessageQueue.getInstance().enqueueAdmin(userID, obj.toString(4));
}

From source file:com.app.dao.SearchQueryDAO.java

private static void _populateUpdateSearchQueryPreparedStatement(PreparedStatement preparedStatement,
        SearchQuery searchQuery, int userId) throws SQLException {

    preparedStatement.setString(1, searchQuery.getKeywords());
    preparedStatement.setString(2, searchQuery.getCategoryId());
    preparedStatement.setString(3, searchQuery.getSubcategoryId());
    preparedStatement.setBoolean(4, searchQuery.isSearchDescription());
    preparedStatement.setBoolean(5, searchQuery.isFreeShippingOnly());
    preparedStatement.setBoolean(6, searchQuery.isNewCondition());
    preparedStatement.setBoolean(7, searchQuery.isUsedCondition());
    preparedStatement.setBoolean(8, searchQuery.isUnspecifiedCondition());
    preparedStatement.setBoolean(9, searchQuery.isAuctionListing());
    preparedStatement.setBoolean(10, searchQuery.isFixedPriceListing());
    preparedStatement.setDouble(11, searchQuery.getMaxPrice());
    preparedStatement.setDouble(12, searchQuery.getMinPrice());
    preparedStatement.setString(13, searchQuery.getGlobalId());
    preparedStatement.setBoolean(14, searchQuery.isActive());
    preparedStatement.setInt(15, searchQuery.getSearchQueryId());
    preparedStatement.setInt(16, userId);
}

From source file:edu.jhu.pha.vospace.oauth.MySQLOAuthProvider2.java

public static synchronized OAuthConsumer getConsumer(final String consumer_key) {
    return DbPoolServlet.goSql("Get oauth consumer",
            "select callback_url, consumer_key, consumer_secret, consumer_description, container from oauth_consumers where consumer_key = ?",
            new SqlWorker<Consumer>() {
                @Override//w ww .  jav a  2  s  . c o  m
                public Consumer go(Connection conn, PreparedStatement stmt) throws SQLException {
                    Consumer consumer = null;

                    stmt.setString(1, consumer_key);
                    ResultSet rs = stmt.executeQuery();
                    if (rs.next()) {
                        consumer = new Consumer(rs.getString("consumer_key"), rs.getString("consumer_secret"),
                                new MultivaluedMapImpl());
                        consumer.getAttributes().add("name", rs.getString("consumer_key"));
                        consumer.getAttributes().add("description", rs.getString("consumer_description"));
                        consumer.getAttributes().add("container", rs.getString("container"));
                    }
                    return consumer;
                }
            });
}

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

/**
 * method to do order by based on the sorted set object for profiles
 * @return list of profiles//from  ww  w. j a  v a 2s.c  o  m
 */
public static SortedSet getProfileSet(SortedSet sortedSet) {

    ArrayList<Profile> profileList = new ArrayList<>();

    String orderBy = "";
    if (sortedSet.getOrderByField() != null && !sortedSet.getOrderByField().trim().equals("")) {
        orderBy = " order by " + sortedSet.getOrderByField() + " " + sortedSet.getOrderByDirection();
    }
    String sql = "select distinct p.* from  profiles p ";
    if (StringUtils.isNotEmpty(sortedSet.getFilterMap().get(FILTER_BY_SYSTEM))) {
        sql = sql + ", system_map m, system s where m.profile_id = p.id and m.system_id = s.id"
                + " and (lower(s.display_nm) like ? or lower(s.host) like ?)";
    } else if (StringUtils.isNotEmpty(sortedSet.getFilterMap().get(FILTER_BY_USER))) {
        sql = sql + ", user_map m, users u where m.profile_id = p.id and m.user_id = u.id"
                + " and (lower(u.first_nm) like ? or lower(u.last_nm) like ?"
                + " or lower(u.email) like ? or lower(u.username) like ?)";
    }
    sql = sql + orderBy;

    Connection con = null;
    try {
        con = DBUtils.getConn();
        PreparedStatement stmt = con.prepareStatement(sql);
        if (StringUtils.isNotEmpty(sortedSet.getFilterMap().get(FILTER_BY_SYSTEM))) {
            stmt.setString(1, "%" + sortedSet.getFilterMap().get(FILTER_BY_SYSTEM).toLowerCase() + "%");
            stmt.setString(2, "%" + sortedSet.getFilterMap().get(FILTER_BY_SYSTEM).toLowerCase() + "%");
        } else if (StringUtils.isNotEmpty(sortedSet.getFilterMap().get(FILTER_BY_USER))) {
            stmt.setString(1, "%" + sortedSet.getFilterMap().get(FILTER_BY_USER).toLowerCase() + "%");
            stmt.setString(2, "%" + sortedSet.getFilterMap().get(FILTER_BY_USER).toLowerCase() + "%");
            stmt.setString(3, "%" + sortedSet.getFilterMap().get(FILTER_BY_USER).toLowerCase() + "%");
            stmt.setString(4, "%" + sortedSet.getFilterMap().get(FILTER_BY_USER).toLowerCase() + "%");
        }
        ResultSet rs = stmt.executeQuery();

        while (rs.next()) {
            Profile profile = new Profile();
            profile.setId(rs.getLong("id"));
            profile.setNm(rs.getString("nm"));
            profile.setDesc(rs.getString("desc"));
            profileList.add(profile);

        }
        DBUtils.closeRs(rs);
        DBUtils.closeStmt(stmt);

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

    sortedSet.setItemList(profileList);
    return sortedSet;
}

From source file:edu.jhu.pha.vospace.oauth.MySQLOAuthProvider2.java

public static synchronized Token getRequestToken(final String tokenStr) {

    Token tokenObj = DbPoolServlet.goSql("Get oauth token",
            "select request_token, token_secret, consumer_key, callback_url, identity, container_name, accessor_write_permission "
                    + "from oauth_accessors "
                    + "join oauth_consumers on oauth_consumers.consumer_id = oauth_accessors.consumer_id "
                    + "left outer join containers on containers.container_id = oauth_accessors.container_id "
                    + "left outer join users on users.user_id = containers.user_id "
                    + "left outer join user_identities on users.user_id = user_identities.user_id "
                    + "where request_token = ? limit 1",
            new SqlWorker<Token>() {
                @Override/*www  .j  a  v a 2  s .c om*/
                public Token go(Connection conn, PreparedStatement stmt) throws SQLException {
                    Token token = null;

                    stmt.setString(1, tokenStr);
                    ResultSet rs = stmt.executeQuery();
                    if (rs.next()) {
                        token = new Token(rs.getString("request_token"), rs.getString("token_secret"),
                                rs.getString("consumer_key"), rs.getString("callback_url"),
                                new MultivaluedMapImpl());

                        if (null != rs.getString("container_name"))
                            token.getAttributes().add("root_container", rs.getString("container_name"));
                    }

                    return token;
                }
            });

    return tokenObj;
}