List of usage examples for java.sql PreparedStatement setBinaryStream
void setBinaryStream(int parameterIndex, java.io.InputStream x) throws SQLException;
From source file:org.apache.kylin.common.persistence.JDBCResourceDAO.java
public void checkAndPutResource(final String resPath, final byte[] content, final long oldTS, final long newTS) throws SQLException, WriteConflictException { logger.trace(//from w w w . j av a 2 s . c o m "execute checkAndPutResource method. resPath : {} , oldTs : {} , newTs : {} , content null ? : {} ", resPath, oldTS, newTS, content == null); executeSql(new SqlOperation() { @Override public void execute(Connection connection) throws SQLException { synchronized (resPath.intern()) { String tableName = getMetaTableName(resPath); if (!existResource(resPath)) { if (oldTS != 0) { throw new IllegalStateException( "For not exist file. OldTS have to be 0. but Actual oldTS is : " + oldTS); } if (isContentOverflow(content, resPath)) { logger.debug("Overflow! resource path: {}, content size: {}", resPath, content.length); pstat = connection.prepareStatement(getInsertSqlWithoutContent(tableName)); pstat.setString(1, resPath); pstat.setLong(2, newTS); writeLargeCellToHdfs(resPath, content); try { int result = pstat.executeUpdate(); if (result != 1) throw new SQLException(); } catch (SQLException e) { rollbackLargeCellFromHdfs(resPath); throw e; } } else { pstat = connection.prepareStatement(getInsertSql(tableName)); pstat.setString(1, resPath); pstat.setLong(2, newTS); pstat.setBlob(3, new BufferedInputStream(new ByteArrayInputStream(content))); pstat.executeUpdate(); } } else { // Note the checkAndPut trick: // update {0} set {1}=? where {2}=? and {3}=? pstat = connection.prepareStatement(getUpdateSqlWithoutContent(tableName)); pstat.setLong(1, newTS); pstat.setString(2, resPath); pstat.setLong(3, oldTS); int result = pstat.executeUpdate(); if (result != 1) { long realTime = getResourceTimestamp(resPath); throw new WriteConflictException("Overwriting conflict " + resPath + ", expect old TS " + oldTS + ", but it is " + realTime); } PreparedStatement pstat2 = null; try { // "update {0} set {1}=? where {3}=?" pstat2 = connection.prepareStatement(getUpdateContentSql(tableName)); if (isContentOverflow(content, resPath)) { logger.debug("Overflow! resource path: {}, content size: {}", resPath, content.length); pstat2.setNull(1, Types.BLOB); pstat2.setString(2, resPath); writeLargeCellToHdfs(resPath, content); try { int result2 = pstat2.executeUpdate(); if (result2 != 1) throw new SQLException(); } catch (SQLException e) { rollbackLargeCellFromHdfs(resPath); throw e; } cleanOldLargeCellFromHdfs(resPath); } else { pstat2.setBinaryStream(1, new BufferedInputStream(new ByteArrayInputStream(content))); pstat2.setString(2, resPath); pstat2.executeUpdate(); } } finally { JDBCConnectionManager.closeQuietly(pstat2); } } } } }); }
From source file:org.wso2.carbon.cluster.coordinator.rdbms.RDBMSCommunicationBusContextImpl.java
@Override public void insertRemovedNodeDetails(String removedMember, String groupId, List<String> clusterNodes, Map<String, Object> removedPropertiesMap) throws ClusterCoordinationException { Connection connection = null; PreparedStatement storeRemovedMembersPreparedStatement = null; String task = "Storing removed member: " + removedMember + " in group " + groupId; try {//from ww w. ja v a 2 s . c om connection = getConnection(); storeRemovedMembersPreparedStatement = connection .prepareStatement(RDBMSConstants.PS_INSERT_REMOVED_MEMBER_DETAILS); ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); ObjectOutputStream objectOutputStream = new ObjectOutputStream(byteArrayOutputStream); objectOutputStream.writeObject(removedPropertiesMap); objectOutputStream.flush(); byteArrayOutputStream.flush(); objectOutputStream.close(); byteArrayOutputStream.close(); byte[] propertiesMapAsBytes = byteArrayOutputStream.toByteArray(); // ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(propertiesMapAsBytes); for (String clusterNode : clusterNodes) { storeRemovedMembersPreparedStatement.setString(1, clusterNode); storeRemovedMembersPreparedStatement.setString(2, groupId); storeRemovedMembersPreparedStatement.setString(3, removedMember); storeRemovedMembersPreparedStatement.setBinaryStream(4, new ByteArrayInputStream(propertiesMapAsBytes)); storeRemovedMembersPreparedStatement.addBatch(); } storeRemovedMembersPreparedStatement.executeBatch(); connection.commit(); } catch (SQLException e) { rollback(connection, task); throw new ClusterCoordinationException( "Error storing removed member: " + removedMember + " in group " + groupId, e); } catch (IOException e) { throw new ClusterCoordinationException("Error while inserting removed node data", e); } finally { close(storeRemovedMembersPreparedStatement, task); close(connection, task); } }
From source file:com.kk.dic.action.Upload.java
protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=UTF-8"); out = response.getWriter();//ww w . j av a 2s. com Connection con; PreparedStatement pstm = null; String fname = ""; String keyword = ""; String cd = ""; String a = (String) request.getSession().getAttribute("email"); System.out.println("User Name : " + a); try { boolean isMultipartContent = ServletFileUpload.isMultipartContent(request); if (!isMultipartContent) { return; } FileItemFactory factory = new DiskFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(factory); out.print("one"); try { List<FileItem> fields = upload.parseRequest(request); Iterator<FileItem> it = fields.iterator(); if (!it.hasNext()) { return; } while (it.hasNext()) { FileItem fileItem = it.next(); if (fileItem.getFieldName().equals("name")) { fname = fileItem.getString(); System.out.println("File Name" + fname); } else if (fileItem.getFieldName().equals("keyword")) { keyword = fileItem.getString(); System.out.println("File Keyword" + keyword); } else { } boolean isFormField = fileItem.isFormField(); if (isFormField) { } else { out.print("one"); try { con = Dbconnection.getConnection(); pstm = con.prepareStatement( "insert into files (file, keyword, filetype, filename, CDate, owner, size, data, frank, file_key)values(?,?,?,?,?,?,?,?,?,?)"); out.println("getD " + fileItem.getName()); String str = getStringFromInputStream(fileItem.getInputStream()); // secretkey generating KeyGenerator keyGen = KeyGenerator.getInstance("AES"); keyGen.init(128); SecretKey secretKey = keyGen.generateKey(); System.out.println("secret key:" + secretKey); //converting secretkey to String byte[] be = secretKey.getEncoded();//encoding secretkey String skey = Base64.encode(be); System.out.println("converted secretkey to string:" + skey); String cipher = new encryption().encrypt(str, secretKey); System.out.println(str); //for get extension from given file String b = fileItem.getName().substring(fileItem.getName().lastIndexOf('.')); System.out.println("File Extension" + b); pstm.setBinaryStream(1, fileItem.getInputStream()); pstm.setString(2, keyword); pstm.setString(3, b); pstm.setString(4, fname); pstm.setDate(5, getCurrentDate()); pstm.setString(6, a); pstm.setLong(7, fileItem.getSize()); pstm.setString(8, cipher); pstm.setString(9, "0"); pstm.setString(10, skey); /*Cloud Start*/ File f = new File("D:/" + fileItem.getName()); out.print("<br/>" + f.getName()); FileWriter fw = new FileWriter(f); fw.write(cipher); fw.close(); Ftpcon ftpcon = new Ftpcon(); ftpcon.upload(f, fname); /*Cloud End*/ int i = pstm.executeUpdate(); if (i == 1) { response.sendRedirect("upload.jsp?msg=success"); } else { response.sendRedirect("upload.jsp?msgg=failed"); } con.close(); } catch (Exception e) { out.println(e); } } } } catch (Exception ex) { out.print(ex); Logger.getLogger(Upload.class.getName()).log(Level.SEVERE, null, ex); } } finally { out.close(); } }
From source file:org.exoplatform.social.core.mysql.storage.ActivityMysqlStorageImpl.java
private int fillPreparedStatementFromActivity(Identity owner, ExoSocialActivity activity, PreparedStatement preparedStatement, int index) throws SQLException { preparedStatement.setString(index++, activity.getTitle()); preparedStatement.setString(index++, activity.getTitleId()); preparedStatement.setString(index++, activity.getBody()); preparedStatement.setString(index++, activity.getBodyId()); preparedStatement.setLong(index++, activity.getPostedTime()); preparedStatement.setLong(index++, activity.getUpdated().getTime()); preparedStatement.setString(index++, activity.getPosterId()); preparedStatement.setString(index++, owner.getRemoteId()); preparedStatement.setString(index++, owner.getId()); preparedStatement.setString(index++, activity.getPermaLink()); preparedStatement.setString(index++, activity.getAppId()); preparedStatement.setString(index++, activity.getExternalId()); if (activity.getPriority() == null) { preparedStatement.setNull(index++, Types.FLOAT); } else {/* ww w . j a v a 2 s . c o m*/ preparedStatement.setFloat(index++, activity.getPriority()); } preparedStatement.setBoolean(index++, activity.isHidden()); preparedStatement.setBoolean(index++, activity.isLocked()); preparedStatement.setString(index++, StringUtils.join(activity.getLikeIdentityIds(), ",")); preparedStatement.setString(index++, StringUtils.join(activity.getMentionedIds(), ",")); preparedStatement.setString(index++, StringUtils.join(activity.getCommentedIds(), ",")); preparedStatement.setString(index++, StringUtils.join(activity.getReplyToId(), ",")); preparedStatement.setString(index++, null); // if (activity.getTemplateParams() != null) { try { ByteArrayOutputStream b = new ByteArrayOutputStream(); ObjectOutputStream output = new ObjectOutputStream(b); output.writeObject(activity.getTemplateParams()); preparedStatement.setBinaryStream(index++, new ByteArrayInputStream(b.toByteArray())); } catch (IOException e) { LOG.debug("Failed to save templateParams of activity into database"); } } else { preparedStatement.setNull(index++, Types.BLOB); } preparedStatement.setString(index++, activity.getType()); return index; }
From source file:org.exoplatform.social.core.mysql.storage.ActivityMysqlStorageImpl.java
@Override public void saveComment(ExoSocialActivity activity, ExoSocialActivity comment) throws ActivityStorageException { LOG.debug("begin to create comment"); // insert to mysql comment table Connection dbConnection = null; PreparedStatement preparedStatement = null; StringBuilder insertTableSQL = new StringBuilder(); insertTableSQL.append("INSERT INTO comment").append( "(_id, activityId, title, titleId, body, bodyId, postedTime, lastUpdated, posterId, mentioners, ") .append("hidable, lockable, templateParams)").append("VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?)"); StringBuilder updateActivitySQL = new StringBuilder(); updateActivitySQL.append(/*from w ww . java 2s . c o m*/ "update activity set lastUpdated = ?, mentioners = ?, commenters = ?, commentIds = ? where _id = ?"); long currentMillis = System.currentTimeMillis(); long commentMillis = (comment.getPostedTime() != null ? comment.getPostedTime() : currentMillis); List<String> mentioners = new ArrayList<String>(); activity.setMentionedIds(processMentions(activity.getMentionedIds(), comment.getTitle(), mentioners, true)); List<String> commenters = new ArrayList<String>(Arrays.asList(activity.getCommentedIds())); if (comment.getUserId() != null && !commenters.contains(comment.getUserId())) { commenters.add(comment.getUserId()); } activity.setCommentedIds(commenters.toArray(new String[0])); comment.setMentionedIds(processMentions(comment.getTitle())); try { dbConnection = dbConnect.getDBConnection(); // insert comment preparedStatement = dbConnection.prepareStatement(insertTableSQL.toString()); comment.setId(UUID.randomUUID().toString()); preparedStatement.setString(1, comment.getId()); preparedStatement.setString(2, activity.getId()); preparedStatement.setString(3, comment.getTitle()); preparedStatement.setString(4, comment.getTitleId()); preparedStatement.setString(5, comment.getBody()); preparedStatement.setString(6, comment.getBodyId()); preparedStatement.setLong(7, commentMillis); preparedStatement.setLong(8, commentMillis); preparedStatement.setString(9, comment.getUserId()); preparedStatement.setString(10, StringUtils.join(comment.getMentionedIds(), ",")); preparedStatement.setBoolean(11, activity.isHidden()); preparedStatement.setBoolean(12, activity.isLocked()); // if (comment.getTemplateParams() != null) { try { ByteArrayOutputStream b = new ByteArrayOutputStream(); ObjectOutputStream output = new ObjectOutputStream(b); output.writeObject(comment.getTemplateParams()); preparedStatement.setBinaryStream(13, new ByteArrayInputStream(b.toByteArray())); } catch (IOException e) { LOG.debug("Failed to save templateParams of activity into database"); } } else { preparedStatement.setNull(13, Types.BLOB); } preparedStatement.executeUpdate(); LOG.debug("new comment created"); // List<String> commentIds = new ArrayList(Arrays.asList(activity.getReplyToId())); commentIds.add(comment.getId()); // update activity preparedStatement = dbConnection.prepareStatement(updateActivitySQL.toString()); preparedStatement.setLong(1, commentMillis); preparedStatement.setString(2, StringUtils.join(activity.getMentionedIds(), ",")); preparedStatement.setString(3, StringUtils.join(activity.getCommentedIds(), ",")); preparedStatement.setString(4, StringUtils.join(commentIds, ",")); preparedStatement.setString(5, activity.getId()); preparedStatement.executeUpdate(); LOG.debug("activity updated"); activity.setReplyToId(commentIds.toArray(new String[commentIds.size()])); activity.setUpdated(currentMillis); } catch (SQLException e) { LOG.error("error in comment creation:", e.getMessage()); } finally { try { if (preparedStatement != null) { preparedStatement.close(); } if (dbConnection != null) { dbConnection.close(); } } catch (SQLException e) { LOG.error("Cannot close statement or connection:", e.getMessage()); } } comment.setUpdated(commentMillis); Identity poster = new Identity(activity.getPosterId()); poster.setRemoteId(activity.getStreamOwner()); commenter(poster, activity, comment); updateMentioner(poster, activity, comment); }
From source file:org.apache.openjpa.jdbc.sql.DBDictionary.java
/** * Set the given value as a parameter to the statement. */// w w w.java 2 s . c om public void setBinaryStream(PreparedStatement stmnt, int idx, InputStream val, int length, Column col) throws SQLException { //OPENJPA-2067: If the user has set the 'useJDBC4SetBinaryStream' property //then lets use the JDBC 4.0 version of the setBinaryStream method. if (useJDBC4SetBinaryStream) { if (isJDBC4) { stmnt.setBinaryStream(idx, val); return; } else { log.trace(_loc.get("jdbc4-setbinarystream-unsupported")); } } stmnt.setBinaryStream(idx, val, length); }