List of usage examples for java.sql PreparedStatement clearParameters
void clearParameters() throws SQLException;
From source file:org.wso2.carbon.idp.mgt.dao.IdPManagementDAO.java
/** * @param identityProvider//www . j ava2 s .c o m * @param tenantId * @throws IdentityProviderManagementException */ public void addIdP(IdentityProvider identityProvider, int tenantId) throws IdentityProviderManagementException { Connection dbConnection = IdentityDatabaseUtil.getDBConnection(); ; try { if (identityProvider.isPrimary()) { // this is going to be the primary. Switch off any other primary set up in the // system. switchOffPrimary(dbConnection, tenantId); } PreparedStatement prepStmt = null; // SP_TENANT_ID, SP_IDP_NAME, SP_IDP_PRIMARY, SP_IDP_HOME_REALM_ID, SP_IDP_CERTIFICATE, // SP_IDP_TOKEN_EP_ALIAS, // SP_IDP_INBOUND_PROVISIONING_ENABLED,SP_IDP_INBOUND_PROVISIONING_USER_STORE_ID, // SP_IDP_USER_CLAIM_URI,SP_IDP_ROLE_CLAIM_URI,SP_IDP_DEFAULT_AUTHENTICATOR_NAME,SP_IDP_DEFAULT_PRO_CONNECTOR_NAME String sqlStmt = IdPManagementConstants.SQLQueries.ADD_IDP_SQL; prepStmt = dbConnection.prepareStatement(sqlStmt); prepStmt.setInt(1, tenantId); prepStmt.setString(2, CharacterEncoder.getSafeText(identityProvider.getIdentityProviderName())); if (identityProvider.isPrimary()) { prepStmt.setString(3, "1"); } else { prepStmt.setString(3, "0"); } prepStmt.setString(4, CharacterEncoder.getSafeText(identityProvider.getHomeRealmId())); if (StringUtils.isNotBlank(identityProvider.getCertificate())) { try { IdentityApplicationManagementUtil.getCertData(identityProvider.getCertificate()); } catch (CertificateException ex) { throw new IdentityProviderManagementException( "Malformed Public Certificate file has been provided.", ex); } } setBlobValue(identityProvider.getCertificate(), prepStmt, 5); prepStmt.setString(6, CharacterEncoder.getSafeText(identityProvider.getAlias())); if (identityProvider.getJustInTimeProvisioningConfig() != null && identityProvider.getJustInTimeProvisioningConfig().isProvisioningEnabled()) { // just in time provisioning enabled for this identity provider. // based on the authentication response from the identity provider - user will be // provisioned locally. prepStmt.setString(7, "1"); // user will be provisioned to the configured user store. prepStmt.setString(8, CharacterEncoder.getSafeText( identityProvider.getJustInTimeProvisioningConfig().getProvisioningUserStore())); } else { prepStmt.setString(7, "0"); prepStmt.setString(8, null); } if (identityProvider.getClaimConfig() != null) { // this is how we find the subject name from the authentication response. // this claim URI is in identity provider's own dialect. prepStmt.setString(9, CharacterEncoder.getSafeText(identityProvider.getClaimConfig().getUserClaimURI())); // this is how we find the role name from the authentication response. // this claim URI is in identity provider's own dialect. prepStmt.setString(10, CharacterEncoder.getSafeText(identityProvider.getClaimConfig().getRoleClaimURI())); } else { prepStmt.setString(9, null); prepStmt.setString(10, null); } if (identityProvider.getDefaultAuthenticatorConfig() != null) { prepStmt.setString(11, CharacterEncoder.getSafeText(identityProvider.getDefaultAuthenticatorConfig().getName())); } else { prepStmt.setString(11, null); } if (identityProvider.getDefaultProvisioningConnectorConfig() != null) { prepStmt.setString(12, CharacterEncoder .getSafeText(identityProvider.getDefaultProvisioningConnectorConfig().getName())); } else { prepStmt.setString(12, null); } prepStmt.setString(13, CharacterEncoder.getSafeText(identityProvider.getIdentityProviderDescription())); if (identityProvider.isFederationHub()) { prepStmt.setString(14, "1"); } else { prepStmt.setString(14, "0"); } if (identityProvider.getClaimConfig() != null && identityProvider.getClaimConfig().isLocalClaimDialect()) { prepStmt.setString(15, "1"); } else { prepStmt.setString(15, "0"); } prepStmt.setString(16, CharacterEncoder.getSafeText(identityProvider.getProvisioningRole())); // enabled by default prepStmt.setString(17, "1"); prepStmt.setString(18, CharacterEncoder.getSafeText(identityProvider.getDisplayName())); prepStmt.executeUpdate(); prepStmt.clearParameters(); IdentityApplicationManagementUtil.closeStatement(prepStmt); // get the id of the just added identity provider. int idPId = getIdentityProviderIdByName(dbConnection, identityProvider.getIdentityProviderName(), tenantId); if (idPId <= 0) { String msg = "Error adding Identity Provider for tenant " + tenantId; throw new IdentityProviderManagementException(msg); } // add provisioning connectors. if (identityProvider.getProvisioningConnectorConfigs() != null && identityProvider.getProvisioningConnectorConfigs().length > 0) { addProvisioningConnectorConfigs(identityProvider.getProvisioningConnectorConfigs(), dbConnection, idPId, tenantId); } // add federated authenticators. addFederatedAuthenticatorConfigs(identityProvider.getFederatedAuthenticatorConfigs(), dbConnection, idPId, tenantId); // add role configuration. if (identityProvider.getPermissionAndRoleConfig() != null) { if (identityProvider.getPermissionAndRoleConfig().getIdpRoles() != null && identityProvider.getPermissionAndRoleConfig().getIdpRoles().length > 0) { // add roles. addIdPRoles(dbConnection, idPId, tenantId, identityProvider.getPermissionAndRoleConfig().getIdpRoles()); if (identityProvider.getPermissionAndRoleConfig().getRoleMappings() != null && identityProvider.getPermissionAndRoleConfig().getRoleMappings().length > 0) { // add role mappings. addIdPRoleMappings(dbConnection, idPId, tenantId, identityProvider.getPermissionAndRoleConfig().getRoleMappings()); } } } // add claim configuration. if (identityProvider.getClaimConfig() != null && identityProvider.getClaimConfig().getClaimMappings() != null && identityProvider.getClaimConfig().getClaimMappings().length > 0) { if (identityProvider.getClaimConfig().isLocalClaimDialect()) { // identity provider is using local claim dialect - we do not need to add // claims. addDefaultClaimValuesForLocalIdP(dbConnection, idPId, tenantId, identityProvider.getClaimConfig().getClaimMappings()); } else { addIdPClaims(dbConnection, idPId, tenantId, identityProvider.getClaimConfig().getIdpClaims()); addIdPClaimMappings(dbConnection, idPId, tenantId, identityProvider.getClaimConfig().getClaimMappings()); } } dbConnection.commit(); } catch (IOException e) { throw new IdentityProviderManagementException("An error occurred while processing content stream.", e); } catch (SQLException e) { IdentityApplicationManagementUtil.rollBack(dbConnection); throw new IdentityProviderManagementException( "Error occurred while adding Identity Provider for tenant " + tenantId, e); } finally { IdentityApplicationManagementUtil.closeConnection(dbConnection); } }
From source file:org.wso2.carbon.idp.mgt.dao.IdPManagementDAO.java
/** * @param newIdentityProvider//from ww w .j a v a 2 s . c om * @param currentIdentityProvider * @param tenantId * @throws IdentityProviderManagementException */ public void updateIdP(IdentityProvider newIdentityProvider, IdentityProvider currentIdentityProvider, int tenantId) throws IdentityProviderManagementException { Connection dbConnection = IdentityDatabaseUtil.getDBConnection(); try { int idPId = getIdentityProviderIdByName(dbConnection, currentIdentityProvider.getIdentityProviderName(), tenantId); if (idPId <= 0) { String msg = "Trying to update non-existent Identity Provider for tenant " + tenantId; throw new IdentityProviderManagementException(msg); } PreparedStatement prepStmt = null; // SP_IDP_NAME=?, SP_IDP_PRIMARY=?,SP_IDP_HOME_REALM_ID=?, SP_IDP_CERTIFICATE=?, // SP_IDP_TOKEN_EP_ALIAS=?, // SP_IDP_INBOUND_PROVISIONING_ENABLED=?,SP_IDP_INBOUND_PROVISIONING_USER_STORE_ID=?,SP_IDP_USER_CLAIM_URI=?, // SP_IDP_ROLE_CLAIM_URI=?,SP_IDP_DEFAULT_AUTHENTICATOR_NAME=?,SP_IDP_DEFAULT_PRO_CONNECTOR_NAME=? String sqlStmt = IdPManagementConstants.SQLQueries.UPDATE_IDP_SQL; prepStmt = dbConnection.prepareStatement(sqlStmt); prepStmt.setString(1, CharacterEncoder.getSafeText(newIdentityProvider.getIdentityProviderName())); if (newIdentityProvider.isPrimary()) { prepStmt.setString(2, "1"); } else { prepStmt.setString(2, "0"); } prepStmt.setString(3, CharacterEncoder.getSafeText(newIdentityProvider.getHomeRealmId())); if (StringUtils.isNotBlank(newIdentityProvider.getCertificate())) { try { IdentityApplicationManagementUtil.getCertData(newIdentityProvider.getCertificate()); } catch (CertificateException ex) { throw new IdentityProviderManagementException( "Malformed Public Certificate file has been provided.", ex); } } setBlobValue(newIdentityProvider.getCertificate(), prepStmt, 4); prepStmt.setString(5, CharacterEncoder.getSafeText(newIdentityProvider.getAlias())); if (newIdentityProvider.getJustInTimeProvisioningConfig() != null && newIdentityProvider.getJustInTimeProvisioningConfig().isProvisioningEnabled()) { prepStmt.setString(6, "1"); prepStmt.setString(7, CharacterEncoder.getSafeText( newIdentityProvider.getJustInTimeProvisioningConfig().getProvisioningUserStore())); } else { prepStmt.setString(6, "0"); prepStmt.setString(7, null); } if (newIdentityProvider.getClaimConfig() != null) { prepStmt.setString(8, CharacterEncoder.getSafeText(newIdentityProvider.getClaimConfig().getUserClaimURI())); prepStmt.setString(9, CharacterEncoder.getSafeText(newIdentityProvider.getClaimConfig().getRoleClaimURI())); } else { prepStmt.setString(8, null); prepStmt.setString(9, null); } // update the default authenticator if (newIdentityProvider.getDefaultAuthenticatorConfig() != null && newIdentityProvider.getDefaultAuthenticatorConfig().getName() != null) { prepStmt.setString(10, CharacterEncoder .getSafeText(newIdentityProvider.getDefaultAuthenticatorConfig().getName())); } else { // its not a must to have a default authenticator. prepStmt.setString(10, null); } // update the default provisioning connector. if (newIdentityProvider.getDefaultProvisioningConnectorConfig() != null && newIdentityProvider.getDefaultProvisioningConnectorConfig().getName() != null) { prepStmt.setString(11, CharacterEncoder .getSafeText(newIdentityProvider.getDefaultProvisioningConnectorConfig().getName())); } else { // its not a must to have a default provisioning connector.. prepStmt.setString(11, null); } prepStmt.setString(12, CharacterEncoder.getSafeText(newIdentityProvider.getIdentityProviderDescription())); if (newIdentityProvider.isFederationHub()) { prepStmt.setString(13, "1"); } else { prepStmt.setString(13, "0"); } if (newIdentityProvider.getClaimConfig() != null && newIdentityProvider.getClaimConfig().isLocalClaimDialect()) { prepStmt.setString(14, "1"); } else { prepStmt.setString(14, "0"); } prepStmt.setString(15, CharacterEncoder.getSafeText(newIdentityProvider.getProvisioningRole())); if (newIdentityProvider.isEnable()) { prepStmt.setString(16, "1"); } else { prepStmt.setString(16, "0"); } prepStmt.setString(17, CharacterEncoder.getSafeText(newIdentityProvider.getDisplayName())); prepStmt.setInt(18, tenantId); prepStmt.setString(19, CharacterEncoder.getSafeText(currentIdentityProvider.getIdentityProviderName())); prepStmt.executeUpdate(); prepStmt.clearParameters(); IdentityApplicationManagementUtil.closeStatement(prepStmt); sqlStmt = IdPManagementConstants.SQLQueries.GET_IDP_BY_NAME_SQL; prepStmt = dbConnection.prepareStatement(sqlStmt); prepStmt.setInt(1, tenantId); prepStmt.setInt(2, MultitenantConstants.SUPER_TENANT_ID); prepStmt.setString(3, CharacterEncoder.getSafeText(newIdentityProvider.getIdentityProviderName())); ResultSet rs = prepStmt.executeQuery(); if (rs.next()) { // id of the updated identity provider. int idpId = rs.getInt("ID"); // update federated authenticators. updateFederatedAuthenticatorConfigs(newIdentityProvider.getFederatedAuthenticatorConfigs(), currentIdentityProvider.getFederatedAuthenticatorConfigs(), dbConnection, idpId, tenantId); // update claim configuration. updateClaimConfiguration(dbConnection, idpId, tenantId, newIdentityProvider.getClaimConfig()); // update role configuration. updateRoleConfiguration(dbConnection, idpId, tenantId, newIdentityProvider.getPermissionAndRoleConfig()); // // update provisioning connectors. updateProvisioningConnectorConfigs(newIdentityProvider.getProvisioningConnectorConfigs(), dbConnection, idpId, tenantId); } dbConnection.commit(); } catch (IOException e) { throw new IdentityProviderManagementException("An error occurred while processing content stream.", e); } catch (SQLException e) { IdentityApplicationManagementUtil.rollBack(dbConnection); throw new IdentityProviderManagementException( "Error occurred while updating Identity Provider " + "information for tenant " + tenantId, e); } finally { IdentityApplicationManagementUtil.closeConnection(dbConnection); } }
From source file:stg.pr.engine.CProcessRequestEngine.java
/** * Starts the service engine for the Grouped Requests. Gets the connection * from the pool and Continuously scans the PROCESS_REQUEST table for queued * grouped requests and executes them sequentially * /*from ww w.j a v a 2 s . c o m*/ * <p> * Scanning continues in a loop until the tEngine_ thread is interrupted. * </p> * <p> * The query picks up requests, from the table PROCESS_REQUEST, that have * the Req_Stat='Q' and GRP_ST_IND = 'G'. If requests are found then each * record is processed sequentially depending on the sequence given in the * group. If no records are found then the engine waits for a specified time * (picked up from property file) and then resumes scanning * </p> * */ private void startGroupServiceEngine() { if (objEngineLogger_.isInfoEnabled()) { objEngineLogger_.info("Starting Group Service Engine..."); } Connection conForGroupedRequest = null; PreparedStatement psm = null; PreparedStatement psmu = null; try { objEngineLogger_.log(Level.INFO, "Waiting for the cluster handshake."); while (!bClusterHandShakeDone_) { // wait do nothing. if (bEngineTerminated_.get() || bGroupedEngineTerminated_.get()) { tEngine_.interrupt(); break; // break the while loop. } } if (!(bEngineTerminated_.get() || bGroupedEngineTerminated_.get())) { if (objEngineLogger_.isDebugEnabled()) { objEngineLogger_.debug("Getting Connection from the pool ...."); } // conForGroupedRequest = // poolManager_.getConnection(CSettings.get("pr.dsforgroupeng")); conForGroupedRequest = dataSourceFactory_.getDataSource(CSettings.get("pr.dsforgroupeng")) .getConnection(); psmu = conForGroupedRequest.prepareStatement( "UPDATE process_request SET req_stat = ? WHERE grp_id = ? AND req_stat = ?"); psm = conForGroupedRequest.prepareStatement( "Select distinct grp_id from process_request where grp_st_ind = ? and req_stat = ? and scheduled_time <= ?"); objEngineLogger_.log(LogLevel.NOTICE, "Group Service Engine Started...."); } while (!tEngine_.isInterrupted()) { boolean bTerminate = false; // try { // LicenseVerifier.verify(readLicense()); // } catch (LicenseContentException lce) { // bTerminate = true; // objEngineLogger_.fatal(lce.getLocalizedMessage()); // } catch (Exception e) { // bTerminate = true; // objEngineLogger_.fatal(e.getLocalizedMessage()); // } if (bTerminate) { if (tEngine_ != null) { tEngine_.interrupt(); } break; } ResultSet rs = null; try { boolean bDoesRequestExists = false; if (!bGroupedEngineTerminated_.get()) { psm.clearParameters(); psm.setString(1, "G"); psm.setString(2, REQUEST_STATUS.QUEUED.getID()); psm.setTimestamp(3, getCurrentTimestamp(conForGroupedRequest)); rs = psm.executeQuery(); while (rs.next() && !tEngine_.isInterrupted()) { if (iGrpThreadCounter_.get() <= iGroupMaximumThread_) { long lGroupId = rs.getLong(1); bDoesRequestExists = true; try { if (objEngineLogger_.isInfoEnabled()) { objEngineLogger_.info("Begin Group Transaction ..."); } conForGroupedRequest.setAutoCommit(false); if (objEngineLogger_.isDebugEnabled()) { objEngineLogger_.debug( "Update Status to... " + REQUEST_STATUS.LAUNCHING.getDescription()); } psmu.setString(1, REQUEST_STATUS.LAUNCHING.getID()); psmu.setLong(2, lGroupId); psmu.setString(3, REQUEST_STATUS.QUEUED.getID()); psmu.executeUpdate(); if (objEngineLogger_.isDebugEnabled()) { objEngineLogger_.debug("Commit Transaction ..."); } conForGroupedRequest.commit(); // } catch (Exception e) { try { objEngineLogger_.error("Rollback Transaction ...", e); conForGroupedRequest.rollback(); } catch (Exception ex) { throw ex; } throw e; } finally { try { conForGroupedRequest.setAutoCommit(true); } catch (Exception ex) { if (objEngineLogger_.isEnabledFor(Level.WARN)) { objEngineLogger_.warn("Dummy Exception and can be ignored.", ex); } } } CGroupedThreadProcess cgtp = new CGroupedThreadProcess("Thread-Grp#" + lGroupId); cgtp.setGroupId(lGroupId); addGroupProcess(cgtp); cgtp.start(); // startServiceForGroupedRequests(conForGroupedRequest, // rs.getLong(1)); } if (objEngineLogger_.isEnabledFor(LogLevel.FINE)) { objEngineLogger_.log(LogLevel.FINE, "Group Engine: Maximum thread spawning capacity (#" + (iGrpThreadCounter_.get() - 1) + ") has reached. Going into Wait mode till one of the JOB gets over."); } long lCurrentTime = System.currentTimeMillis(); while (iGrpThreadCounter_.get() > iGroupMaximumThread_) { // try // { // Thread.sleep(10000); // } // catch (InterruptedException ie) // { // System.exit(1); // } } long lWaitTime = System.currentTimeMillis() - lCurrentTime; if (objEngineLogger_.isEnabledFor(LogLevel.FINE)) { objEngineLogger_.log(LogLevel.FINE, "Group Engine :Wait Over. Waited for #" + lWaitTime + " milliseconds for some JOB to get over."); } } } // If group engine is not terminated. if (!bDoesRequestExists) { lWaitInterval_ = (Math.abs(Long.parseLong(CSettings.get("pr.waitinterval")))); if (objEngineLogger_.isInfoEnabled()) { objEngineLogger_.info( mfSleepMessageForEngine_.format(new Object[] { "Group", lWaitInterval_ })); } try { Thread.yield(); TimeUnit.SECONDS.sleep(lWaitInterval_); // Thread.sleep(lWaitInterval_); } catch (InterruptedException ie) { // This is not an exception. objEngineLogger_.log(LogLevel.NOTICE, "Grouped Engine Thread Interrupted .."); break; } } // end of else } catch (IOException ioe) { // This is under the assumption that the IO Exception can // never be thrown by the object // executed by the Engine as it can only throw // CProcessRequestEngineException. This exception // means that something wrong has happened in the // Connection. try { closeSQLStatement(psmu); closeSQLStatement(psm); conForGroupedRequest = refreshJDBCConnection(4, conForGroupedRequest, CSettings.get("pr.dsforgroupeng")); // Connection gets refereshed but not the statements. // Therefore the statemetns are refreshed/recreated // here. psmu = conForGroupedRequest.prepareStatement( "UPDATE process_request SET req_stat = ? WHERE grp_id = ? AND req_stat = ?"); psm = conForGroupedRequest.prepareStatement( "Select distinct grp_id from process_request where grp_st_ind = ? and req_stat = ? and scheduled_time <= ?"); } catch (Exception e) { stopMessageForEmail_ = exceptionToString(ioe); objEngineLogger_.fatal( "Grouped Request: IOException Caught. Terminating GroupedRequest Engine", ioe); setReboot(true); break; } } catch (SQLException se) { // This is under the assumption that the SQL Exception can // never be thrown by the object // executed by the Engine as it can only throw // CProcessRequestEngineException. This exception // means that something wrong has happened in the Engine // itself and so engine should get terminated. try { closeSQLStatement(psmu); closeSQLStatement(psm); conForGroupedRequest = refreshJDBCConnection(4, conForGroupedRequest, CSettings.get("pr.dsforgroupeng")); // Connection gets refereshed but not the statements. // Therefore the statemetns are refreshed/recreated // here. psmu = conForGroupedRequest.prepareStatement( "UPDATE process_request SET req_stat = ? WHERE grp_id = ? AND req_stat = ?"); psm = conForGroupedRequest.prepareStatement( "Select distinct grp_id from process_request where grp_st_ind = ? and req_stat = ? and scheduled_time <= ?"); } catch (Exception e) { stopMessageForEmail_ = exceptionToString(se); objEngineLogger_.fatal( "Grouped Request: SQLException Caught. Terminating GroupedRequest Engine", se); setReboot(true); break; } } catch (RuntimeException ree) { objEngineLogger_.error("Grouped Request: Runtime Exception Caught", ree); // no need to throw exception. Just catch. } catch (Exception e) { objEngineLogger_.error("Grouped Request: Exception Caught", e); // no need to throw exception. Just catch. } finally { if (rs != null) { rs.close(); } } } // end of while } catch (Exception e) { objEngineLogger_.fatal("Grouped Request Main: Exception Caught", e); // no need to throw exception. Just catch. } finally { closeSQLStatement(psmu); closeSQLStatement(psm); try { if (conForGroupedRequest != null) { if (objEngineLogger_.isInfoEnabled()) { objEngineLogger_.info("Releasing Grouped Connection to the pool ...."); } conForGroupedRequest.close(); } } catch (SQLException e) { // do nothing } // objEngineLogger_.log(LogLevel.NOTICE, // "Grouped Request Engine Stopped .."); if (objEngineLogger_.isDebugEnabled()) { objEngineLogger_.debug("Interrupting Shutdown Hook from Grouped Requests..."); } // try { // poolManager_.emptyPool(CSettings.get("pr.dsforgroupeng")); // } catch (SQLException e) { // //do nothing // } if (tInterrupt_ != null) { if (tInterrupt_.isAlive()) { tInterrupt_.interrupt(); } else { if (tMain_.isAlive()) { tMain_.interrupt(); } } } else { if (tMain_.isAlive()) { tMain_.interrupt(); } } } }
From source file:com.pari.nm.utils.db.InventoryDBHelper.java
private static void insertClisOptimized(int nodeId, String[] clis, IDSPDeviceInfoProvider device, JobParameters jobParameters) {/*from w w w .ja v a 2 s. co m*/ Connection c = null; PreparedStatement ps = null; try { c = DBHelper.getConnection(); ps = c.prepareStatement("INSERT INTO show_commands_new (device_id, cli, out_put) VALUES (?,?,?)"); for (String cli : clis) { DSPCLICommandOutput output = device.getCLI(cli); if (output != null) { String outputText = output.getOutput(); if (outputText == null) { outputText = output.getErrors(); } if (outputText == null) { continue; } if (outputText.startsWith(cli)) { outputText = outputText.substring(cli.length()); } ps.clearParameters(); ps.setInt(1, nodeId); ps.setString(2, cli); ps.setObject(3, CompressionUtils.getCompressedString(outputText)); ps.executeUpdate(); CommandResult result = new CommandResult(); result.setOperation(Operation.UPDATE); result.setOperatedBy(jobParameters.getUserName()); result.setJobId(jobParameters.getParentJobId()); result.setInventoryJobId(jobParameters.getJobId()); result.setCli(cli); result.setDeviceId((long) nodeId); result.setOutput(CompressionUtils.getCompressedString(outputText)); HistoryManager.getInstance().createRecord(result); } } } catch (Exception ex) { logger.error("Exception while saving CLIs for node: " + nodeId, ex); } finally { if (ps != null) { try { ps.close(); } catch (Throwable t) { } } if (c != null) { DBHelper.releaseConnection(c); } } }