List of usage examples for java.sql PreparedStatement getUpdateCount
int getUpdateCount() throws SQLException;
ResultSet
object or there are no more results, -1 is returned. From source file:org.wso2.carbon.appfactory.core.dao.JDBCApplicationDAO.java
/** * Helper method to add a version with given DB connection * * @param version version with version name * @param databaseConnection existing db connection * @param applicationKey application key to identify the application * @return true if it successful false if it failed * @throws AppFactoryException// ww w.ja v a2 s . c o m */ boolean addVersion(Version version, Connection databaseConnection, String applicationKey) throws AppFactoryException { PreparedStatement addVersionPreparedStatement = null; try { addVersionPreparedStatement = databaseConnection.prepareStatement(SQLConstants.ADD_VERSION); addVersionPreparedStatement.setInt(1, JDBCApplicationDAO.getInstance().getAutoIncrementAppID(applicationKey, databaseConnection)); addVersionPreparedStatement.setString(2, version.getVersion()); addVersionPreparedStatement.setString(3, version.getStage()); addVersionPreparedStatement.setInt(4, CarbonContext.getThreadLocalCarbonContext().getTenantId()); addVersionPreparedStatement.execute(); int affectedRowCount = addVersionPreparedStatement.getUpdateCount(); int tenantID = CarbonContext.getThreadLocalCarbonContext().getTenantId(); String applicationAppsBranchCountKey = JDBCApplicationCacheManager .constructApplicationBranchCountCacheKey(tenantID, applicationKey); Cache<String, Integer> applicationBranchCountCache = JDBCApplicationCacheManager .getApplicationBranchCountCache(); if (affectedRowCount > 0) { //removing the older cache while adding new version for an app. JDBCApplicationCacheManager.getAppVersionNameListCache() .remove(JDBCApplicationCacheManager.constructAppVersionNameListCacheKey(applicationKey)); applicationBranchCountCache.remove(applicationAppsBranchCountKey); JDBCApplicationCacheManager.getAppVersionListCache().remove(applicationKey); if (log.isDebugEnabled()) { String msg = "successfully added application of tenant " + CarbonContext.getThreadLocalCarbonContext().getTenantDomain() + " version : " + version.getVersion() + " of application key : " + applicationKey + " updated : " + affectedRowCount + " rows"; log.debug(msg); } int versionID = getAutoIncrementVersionID(applicationKey, version.getVersion(), databaseConnection); addRepository(versionID, false, null, databaseConnection); return true; } } catch (SQLException e) { handleException( "Adding new version : " + version.getVersion() + " for application key : " + applicationKey, e); } finally { AppFactoryDBUtil.closePreparedStatement(addVersionPreparedStatement); } return false; }
From source file:com.threecrickets.prudence.cache.SqlCache.java
public void store(String key, CacheEntry entry) { logger.fine("Store: " + key); Lock lock = lockSource.getWriteLock(key); lock.lock();//ww w .jav a 2 s . co m try { Connection connection = connect(); if (connection == null) return; try { boolean tryInsert = true; // Try updating this key String sql = "UPDATE " + cacheTableName + " SET data=?, media_type=?, language=?, character_set=?, encoding=?, modification_date=?, tag=?, headers=?, expiration_date=?, document_modification_date=? WHERE key=?"; PreparedStatement statement = connection.prepareStatement(sql); try { statement.setBytes(1, entry.getString() != null ? entry.getString().getBytes() : entry.getBytes()); statement.setString(2, entry.getMediaType() != null ? entry.getMediaType().getName() : null); statement.setString(3, entry.getLanguage() != null ? entry.getLanguage().getName() : null); statement.setString(4, entry.getCharacterSet() != null ? entry.getCharacterSet().getName() : null); statement.setString(5, entry.getEncoding() != null ? entry.getEncoding().getName() : null); statement.setTimestamp(6, entry.getModificationDate() != null ? new Timestamp(entry.getModificationDate().getTime()) : null); statement.setString(7, entry.getTag() != null ? entry.getTag().format() : null); statement.setString(8, entry.getHeaders() == null ? "" : serializeHeaders(entry.getHeaders())); statement.setTimestamp(9, entry.getExpirationDate() != null ? new Timestamp(entry.getExpirationDate().getTime()) : null); statement.setTimestamp(10, entry.getDocumentModificationDate() != null ? new Timestamp(entry.getDocumentModificationDate().getTime()) : null); statement.setString(11, key); if (!statement.execute() && statement.getUpdateCount() > 0) { logger.fine("Updated " + key); // Update worked, so no need to try insertion tryInsert = false; } } finally { statement.close(); } if (tryInsert) { // Try inserting this key // But first make sure we have room... int size = countEntries(connection); if (size >= maxSize) { prune(); size = countEntries(connection); if (size >= maxSize) { logger.fine("No room in cache (" + size + ", " + maxSize + ")"); return; } } // delete( connection, key ); sql = "INSERT INTO " + cacheTableName + " (key, data, media_type, language, character_set, encoding, modification_date, tag, headers, expiration_date, document_modification_date) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"; statement = connection.prepareStatement(sql); try { statement.setString(1, key); statement.setBytes(2, entry.getString() != null ? entry.getString().getBytes() : entry.getBytes()); statement.setString(3, getName(entry.getMediaType())); statement.setString(4, getName(entry.getLanguage())); statement.setString(5, getName(entry.getCharacterSet())); statement.setString(6, getName(entry.getEncoding())); statement.setTimestamp(7, entry.getModificationDate() != null ? new Timestamp(entry.getModificationDate().getTime()) : null); statement.setString(8, entry.getTag() != null ? entry.getTag().format() : null); statement.setString(9, entry.getHeaders() == null ? "" : serializeHeaders(entry.getHeaders())); statement.setTimestamp(10, entry.getExpirationDate() != null ? new Timestamp(entry.getExpirationDate().getTime()) : null); statement.setTimestamp(11, entry.getDocumentModificationDate() != null ? new Timestamp(entry.getDocumentModificationDate().getTime()) : null); statement.execute(); } finally { statement.close(); } } // Clean out existing tags for this key sql = "DELETE FROM " + cacheTagsTableName + " WHERE key=?"; statement = connection.prepareStatement(sql); try { statement.setString(1, key); statement.execute(); } finally { statement.close(); } // Add tags for this key String[] tags = entry.getTags(); if ((tags != null) && (tags.length > 0)) { sql = "INSERT INTO " + cacheTagsTableName + " (key, tag) VALUES (?, ?)"; statement = connection.prepareStatement(sql); statement.setString(1, key); try { for (String tag : tags) { statement.setString(2, tag); statement.execute(); } } finally { statement.close(); } } } finally { connection.close(); } } catch (SQLException x) { logger.log(Level.WARNING, "Could not store cache entry", x); } finally { lock.unlock(); } }
From source file:org.wso2.carbon.appfactory.core.dao.JDBCApplicationDAO.java
/** * Add New CartridgeCluster// ww w. j a v a 2 s .co m * * @param cartridgeCluster {@link org.wso2.carbon.appfactory.core.dto.CartridgeCluster} * @return true if it is successful, false if it is failed * @throws AppFactoryException if there is a problem in creating CartridgeCluster */ public boolean addCartridgeCluster(CartridgeCluster cartridgeCluster) throws AppFactoryException { boolean result = false; if (cartridgeCluster != null) { Connection databaseConnection = null; PreparedStatement preparedStatement = null; try { databaseConnection = AppFactoryDBUtil.getConnection(); preparedStatement = databaseConnection.prepareStatement(SQLConstants.ADD_CARTRIDGE_CLUSTER_SQL); preparedStatement.setString(1, cartridgeCluster.getClusterId()); preparedStatement.setString(2, cartridgeCluster.getLbClusterId()); preparedStatement.setString(3, cartridgeCluster.getActiveIP()); preparedStatement.setInt(4, CarbonContext.getThreadLocalCarbonContext().getTenantId()); preparedStatement.execute(); databaseConnection.commit(); int updatedRowCount = preparedStatement.getUpdateCount(); if (updatedRowCount > 0) { result = true; } } catch (SQLException e) { try { if (databaseConnection != null) { databaseConnection.rollback(); } } catch (SQLException e1) { // no need to throw since this is not related to business logic String msg = "Error while rolling back the updating cartridge for cluster Id : " + cartridgeCluster.getClusterId(); log.error(msg, e1); } handleException("Updating cartridge is failed for clusterId : " + cartridgeCluster.getClusterId(), e); } finally { AppFactoryDBUtil.closePreparedStatement(preparedStatement); AppFactoryDBUtil.closeConnection(databaseConnection); } } return result; }
From source file:org.wso2.carbon.appfactory.core.dao.JDBCApplicationDAO.java
/** * Update build status of a app version.Update will replace existing values * * @param applicationKey key of an application * @param version version name/* www . j ava 2 s .co m*/ * @param isForked true if it a forked version * @param username the user who is forked * @param buildStatus build status * @return true if it successful false if it failed * @throws AppFactoryException */ public boolean updateLastBuildStatus(String applicationKey, String version, boolean isForked, String username, BuildStatus buildStatus) throws AppFactoryException { Connection databaseConnection = null; PreparedStatement preparedStatement = null; try { databaseConnection = AppFactoryDBUtil.getConnection(); preparedStatement = databaseConnection.prepareStatement(SQLConstants.UPDATE_LAST_BUILD_STATUS_SQL); int repositoryID = getRepositoryID(applicationKey, isForked, username, version, databaseConnection); preparedStatement.setString(1, buildStatus.getLastBuildId()); preparedStatement.setString(2, buildStatus.getLastBuildStatus()); preparedStatement.setTimestamp(3, new Timestamp(buildStatus.getLastBuildTime())); preparedStatement.setInt(4, repositoryID); preparedStatement.execute(); int affectedRows = preparedStatement.getUpdateCount(); if (affectedRows > 0) { databaseConnection.commit(); // We remove the entry from the cache int tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId(); String buildStatusCacheKey = JDBCApplicationCacheManager.constructBuildStatusCacheKey(tenantId, applicationKey, version, isForked, username); Cache<String, BuildStatus> buildStatusCache = JDBCApplicationCacheManager .getApplicationBuildStatusCache(); handleDebugLog("Removing data from the build status cache for application key : " + applicationKey); buildStatusCache.remove(buildStatusCacheKey); return true; } handleException("Update latest build is failed for version " + version + " of application key : " + applicationKey); } catch (SQLException e) { try { if (databaseConnection != null) { databaseConnection.rollback(); } } catch (SQLException e1) { //Only logging this exception since this is not the main issue. The original issue is thrown. log.error("Error while rolling back Update latest build for version : " + version + " of " + "application key : " + applicationKey, e1); } handleException("Update latest build is failed for version : " + version + " of application key : " + applicationKey, e); } finally { AppFactoryDBUtil.closePreparedStatement(preparedStatement); AppFactoryDBUtil.closeConnection(databaseConnection); } return false; }
From source file:org.wso2.carbon.appfactory.core.dao.JDBCApplicationDAO.java
/** * Update method for deploy status/*from w w w . ja v a 2 s . c o m*/ * * @param applicationKey key of an application * @param version version name * @param isForked true if it a forked version * @param username the user who is forked * @param status deploy status * @return true if it successful false if it failed * @throws AppFactoryException */ public boolean updateLastDeployStatus(String applicationKey, String version, String environment, boolean isForked, String username, DeployStatus status) throws AppFactoryException { Connection databaseConnection = null; PreparedStatement preparedStatement = null; try { databaseConnection = AppFactoryDBUtil.getConnection(); preparedStatement = databaseConnection.prepareStatement(SQLConstants.UPDATE_DEPLOY_STATUS_SQL); int repositoryID = getRepositoryID(applicationKey, isForked, username, version, databaseConnection); preparedStatement.setString(1, status.getLastDeployedStatus()); if (status.getLastDeployedTime() == 0L) { preparedStatement.setTimestamp(2, null); } else { preparedStatement.setTimestamp(2, new Timestamp(status.getLastDeployedTime())); } preparedStatement.setInt(3, repositoryID); preparedStatement.setString(4, environment); preparedStatement.execute(); int affectedRows = preparedStatement.getUpdateCount(); if (affectedRows > 0) { databaseConnection.commit(); // We remove the cache entry here. int tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId(); String deployCacheKey = JDBCApplicationCacheManager.constructDeployStatusCacheKey(applicationKey, tenantId, version, environment, isForked, username); Cache<String, DeployStatus> deployCache = JDBCApplicationCacheManager .getApplicationDeployStatusCache(); handleDebugLog( "Removing data from the deployment status cache for application key : " + applicationKey); deployCache.remove(deployCacheKey); return true; } handleException("Error while updating deploy status, 0 rows affected for repository ID : " + repositoryID + "and environment : " + environment + " and version : " + version + " of application key : " + applicationKey); } catch (SQLException e) { try { if (databaseConnection != null) { databaseConnection.rollback(); } } catch (SQLException e1) { // Only logging this exception since this is not the main issue. The original issue is thrown. log.error("Error while rolling back update deploy status for version : " + version + " of application " + "key : " + applicationKey, e1); } handleException("Error while updating deploy status for version : " + version + " of application key : " + applicationKey, e); } finally { AppFactoryDBUtil.closePreparedStatement(preparedStatement); AppFactoryDBUtil.closeConnection(databaseConnection); } return false; }
From source file:org.obm.domain.dao.CalendarDaoJdbcImpl.java
@Override @AutoTruncate//from w w w . j av a 2s . c om public void modifyEventForcingSequence(Connection con, AccessToken editor, String calendar, @DatabaseEntity Event ev, boolean updateAttendees, int sequence) throws SQLException, FindException, ServerFault, EventNotFoundException { Event old = findEventById(editor, ev.getObmId()); List<Attendee> attendeetoRemove = Lists.newArrayList(old.getAttendees()); attendeetoRemove.removeAll(ev.getAttendees()); old.getRecurrence().getEventExceptions().removeAll(ev.getRecurrence().getEventExceptions()); PreparedStatement ps = null; try { ps = createEventUpdateStatement(con, editor, ev, sequence); ps.executeUpdate(); if (ps.getUpdateCount() <= 0) { throw new EventNotFoundException("Unexpected Event modification failure : " + ev.getObmId()); } ps.close(); ps = null; if (updateAttendees) { removeAttendees(con, attendeetoRemove, ev); insertDeletedEventLinks(editor, con, attendeetoRemove, ev); } if (updateAttendees) { updateAttendees(editor, con, ev); markUpdated(con, ev.getObmId()); } int ownerId = userDao.userIdFromEmail(con, calendar, editor.getDomain().getId()); updateAlerts(editor, con, ev, ownerId); removeAllException(con, ev); insertExceptions(editor, ev, con, ev.getObmId()); if (ev.isRecurrent()) { insertEventExceptions(editor, calendar, ev.getRecurrence().getEventExceptions(), con, ev.getObmId()); } } finally { obmHelper.cleanup(null, ps, null); } entityDaoListener.eventHasBeenCreated(editor, ev); }
From source file:com.xqdev.sql.MLSQL.java
protected void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { res.setContentType("text/xml"); Namespace sql = Namespace.getNamespace("sql", "http://xqdev.com/sql"); Document responseDoc = new Document(); Element root = new Element("result", sql); Element meta = new Element("meta", sql); responseDoc.setRootElement(root);/*from www. j av a 2s . com*/ root.addContent(meta); Document requestDoc = null; try { // Normally the request comes via the post body, // but we let you bookmark w/ a query string String postbody = req.getParameter("postbody"); if (postbody != null) { SAXBuilder builder = new SAXBuilder(); requestDoc = builder.build(new StringReader(postbody)); } else { InputStream in = req.getInputStream(); SAXBuilder builder = new SAXBuilder(); requestDoc = builder.build(in); } } catch (Exception e) { addExceptions(meta, e); // Now write the error and return OutputStream out = res.getOutputStream(); new XMLOutputter().output(responseDoc, out); out.flush(); return; } Connection con = null; try { Namespace[] namespaces = new Namespace[] { sql }; XPathHelper xpath = new XPathHelper(requestDoc, namespaces); String type = xpath.getString("/sql:request/sql:type"); String query = xpath.getString("/sql:request/sql:query"); int maxRows = xpath.getInt("/sql:request/sql:execute-options/sql:max-rows", -1); int queryTimeout = xpath.getInt("/sql:request/sql:execute-options/sql:query-timeout", -1); int maxFieldSize = xpath.getInt("/sql:request/sql:execute-options/sql:max-field-size", -1); List<Element> params = xpath .getElements("/sql:request/sql:execute-options/sql:parameters/sql:parameter"); con = pool.getConnection(); PreparedStatement stmt = null; if (type.equalsIgnoreCase("procedure")) { stmt = con.prepareCall(query); } else { // Note this call depends on JDBC 3.0 (accompanying Java 1.4). // The call without the 2nd argument would work on earlier JVMs, // you just won't catch any generated keys. stmt = con.prepareStatement(query, Statement.RETURN_GENERATED_KEYS); } configureStatement(stmt, maxRows, queryTimeout, maxFieldSize); parameterizeStatement(stmt, params); if (type.equalsIgnoreCase("select")) { try { ResultSet rs = stmt.executeQuery(); addWarnings(meta, stmt.getWarnings()); addResultSet(root, rs); } catch (SQLException e) { addExceptions(meta, e); Log.log(e); } } else if (type.equalsIgnoreCase("update")) { try { int count = stmt.executeUpdate(); addWarnings(meta, stmt.getWarnings()); addUpdateCount(meta, count); try { addGeneratedKeys(meta, stmt.getGeneratedKeys()); } catch (SQLException e) { // Generated keys are available on INSERT calls but not UPDATE calls // So catch and eat the exception that Oracle (and maybe others) will throw } } catch (SQLException e) { addExceptions(meta, e); } } else if (type.equalsIgnoreCase("procedure")) { boolean isResultSet = stmt.execute(); if (isResultSet) { addResultSet(root, stmt.getResultSet()); addOutParam(root, stmt, params); } else { addOutParam(root, stmt, params); } } else { try { boolean isResultSet = stmt.execute(); addWarnings(meta, stmt.getWarnings()); if (isResultSet) { addResultSet(root, stmt.getResultSet()); } else { addUpdateCount(meta, stmt.getUpdateCount()); addGeneratedKeys(meta, stmt.getGeneratedKeys()); } } catch (SQLException e) { addExceptions(meta, e); } } // Close the statement holding the connection to the JDBC Server stmt.close(); } catch (Exception e) { addExceptions(meta, e); } finally { if (con != null) pool.returnConnection(con); } OutputStream out = res.getOutputStream(); new XMLOutputter().output(responseDoc, out); out.flush(); }
From source file:org.apache.sqoop.repository.common.CommonRepositoryHandler.java
/** * Execute given query via a PreparedStatement. * A list of args can be passed to the query. * * Example: runQuery("SELECT * FROM example WHERE test = ?", "test"); * * @param query Query that should be executed * @param args Long, String, or Object arguments *///from w ww.j a va2 s .c om protected void runQuery(String query, Connection conn, Object... args) { PreparedStatement stmt = null; try { stmt = conn.prepareStatement(query); for (int i = 0; i < args.length; ++i) { if (args[i] instanceof String) { stmt.setString(i + 1, (String) args[i]); } else if (args[i] instanceof Long) { stmt.setLong(i + 1, (Long) args[i]); } else { stmt.setObject(i + 1, args[i]); } } if (stmt.execute()) { ResultSet rset = stmt.getResultSet(); int count = 0; while (rset.next()) { count++; } LOG.info("QUERY(" + query + ") produced unused resultset with " + count + " rows"); } else { int updateCount = stmt.getUpdateCount(); LOG.info("QUERY(" + query + ") Update count: " + updateCount); } } catch (SQLException ex) { throw new SqoopException(CommonRepositoryError.COMMON_0000, query, ex); } finally { closeStatements(stmt); } }
From source file:org.wso2.carbon.appfactory.core.dao.JDBCApplicationDAO.java
/** * Delete all the data related to a application. * This method will get all the versions of the application and then retrieve all the repository ids of those * versions./*from w ww. j a va 2s . co m*/ * Then delete entries related to those repository ids from other database tables. * * @param applicationKey application key * @return true if it successful false if it failed * @throws AppFactoryException */ public boolean deleteApplication(String applicationKey) throws AppFactoryException { Connection databaseConnection = null; PreparedStatement preparedStatement = null; int tenantID = CarbonContext.getThreadLocalCarbonContext().getTenantId(); try { // Get all the version IDs of the application List<Integer> allVersionIDs = getAllVersionIdsOfApplication(applicationKey); //get all repository IDs List<Integer> allRepositoryIDs = getAllRepositoryIDsOfApplication(applicationKey, allVersionIDs); // Delete from all tables using the above list of repository ids. // We use the same database connection so that we can rollback if an error happens. databaseConnection = AppFactoryDBUtil.getConnection(); deleteFromBuildStatus(databaseConnection, applicationKey, allRepositoryIDs); deleteFromDeployStatus(databaseConnection, applicationKey, allRepositoryIDs); deleteFromRepository(databaseConnection, applicationKey, allRepositoryIDs); // Delete the application Version related information deleteFromApplicationVersion(databaseConnection, applicationKey, allVersionIDs); //delete resources if any exists deleteFromApplicationResources(databaseConnection, applicationKey); // We delete the application information from the AF_APPLICATION table preparedStatement = databaseConnection.prepareStatement(SQLConstants.DELETE_APPLICATION_SQL); preparedStatement.setString(1, applicationKey); preparedStatement.setInt(2, tenantID); preparedStatement.execute(); int affectedRows = preparedStatement.getUpdateCount(); if (affectedRows > 0) { databaseConnection.commit(); handleDebugLog("Removing data from all the caches for application key : " + applicationKey); // We remove all the cache entries here. This method will remove application related data from all the caches. removeApplicationDataFromAllCaches(applicationKey); handleDebugLog("Successfully removed data from all the caches for application key : " + applicationKey + "Successfully deleted application : " + applicationKey); return true; } // If the delete application information from AF_APPLICATION tables yields no results, then we throw and error handleException("Deleting application key : " + applicationKey + " failed"); } catch (SQLException e) { try { if (databaseConnection != null) { databaseConnection.rollback(); } } catch (SQLException e1) { // Only logging this exception since this is not the main issue. The original issue is thrown. log.error("Rolling back Deleting application of application key : " + applicationKey + " is failed of " + "tenant id : " + CarbonContext.getThreadLocalCarbonContext().getTenantDomain(), e1); } handleException("Deleting application of application key : " + applicationKey + " is failed", e); } finally { AppFactoryDBUtil.closePreparedStatement(preparedStatement); AppFactoryDBUtil.closeConnection(databaseConnection); } return false; }
From source file:fr.aliacom.obm.common.calendar.CalendarDaoJdbcImpl.java
private boolean changeParticipation(Connection con, AccessToken token, EventExtId extId, ObmUser calendarOwner, Participation participation) throws SQLException { PreparedStatement ps = null; String q = "UPDATE EventLink " + "SET eventlink_state = ?, eventlink_userupdate = ?, eventlink_comment = ? " + "WHERE eventlink_event_id IN " + "( SELECT event_id FROM Event WHERE event_ext_id = ? ) AND " + "eventlink_entity_id IN " + "( SELECT userentity_entity_id FROM UserEntity WHERE userentity_user_id = ? )"; Integer loggedUserId = token.getObmId(); try {/*from w w w . j a va 2s. c o m*/ ps = con.prepareStatement(q); int idx = 1; ps.setObject(idx++, obmHelper.getDBCP().getJdbcObject(ObmHelper.VPARTSTAT, participation.getState().toString())); ps.setInt(idx++, loggedUserId); ps.setString(idx++, participation.getSerializedCommentToString()); ps.setString(idx++, extId.getExtId()); ps.setInt(idx++, calendarOwner.getUid()); ps.execute(); if (ps.getUpdateCount() > 0) { return true; } } catch (SQLException e) { logger.error(e.getMessage(), e); throw e; } finally { obmHelper.cleanup(null, ps, null); } return false; }