Example usage for java.sql PreparedStatement clearParameters

List of usage examples for java.sql PreparedStatement clearParameters

Introduction

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

Prototype

void clearParameters() throws SQLException;

Source Link

Document

Clears the current parameter values immediately.

Usage

From source file:org.sakaiproject.content.impl.DbContentService.java

public void testUTF8Transport(Connection connection) throws Exception {
    /*/*w  w w.j av  a 2s  .c om*/
     * byte[] b = new byte[102400]; byte[] b2 = new byte[102400]; byte[] b3 =
     * new byte[102400]; char[] cin = new char[102400]; Random r = new
     * Random(); r.nextBytes(b);
     */
    byte[] bin = new byte[1024];
    char[] cin = new char[1024];
    byte[] bout = new byte[1024];

    {
        int i = 0;
        for (int bx = 0; i < bin.length; bx++) {
            bin[i++] = (byte) bx;
        }
    }
    ByteStorageConversion.toChar(bin, 0, cin, 0, cin.length);
    String sin = new String(cin);

    char[] cout = sin.toCharArray();
    ByteStorageConversion.toByte(cout, 0, bout, 0, cout.length);

    for (int i = 0; i < bin.length; i++) {
        if (bin[i] != bout[i]) {
            throw new Exception(
                    "Internal Byte conversion failed at " + bin[i] + "=>" + (int) cin[i] + "=>" + bout[i]);
        }
    }

    PreparedStatement statement = null;
    PreparedStatement statement2 = null;
    PreparedStatement statement3 = null;
    ResultSet rs = null;
    try {
        statement3 = connection.prepareStatement("delete from CONTENT_RESOURCE where  RESOURCE_ID =  ?");
        statement3.clearParameters();
        statement3.setString(1, UTF8TESTID);
        statement3.executeUpdate();

        statement = connection
                .prepareStatement("insert into CONTENT_RESOURCE ( RESOURCE_ID, XML ) values ( ?, ? )");
        statement.clearParameters();
        statement.setString(1, UTF8TESTID);
        statement.setString(2, sin);
        statement.executeUpdate();

        statement2 = connection.prepareStatement("select XML from CONTENT_RESOURCE where RESOURCE_ID = ? ");
        statement2.clearParameters();
        statement2.setString(1, UTF8TESTID);
        rs = statement2.executeQuery();
        String sout = null;
        if (rs.next()) {
            sout = rs.getString(1);
        }
        rs.close();

        statement3.clearParameters();
        statement3.setString(1, UTF8TESTID);
        statement3.executeUpdate();

        if (sout != null) {
            cout = sout.toCharArray();
        }
        ByteStorageConversion.toByte(cout, 0, bout, 0, cout.length);

        if (sout != null) {
            if (sin.length() != sout.length()) {
                throw new Exception("UTF-8 Data was lost communicating with the database, please "
                        + "check connection string and default table types (Truncation/Expansion)");
            }
        }

        for (int i = 0; i < bin.length; i++) {
            if (bin[i] != bout[i]) {
                throw new Exception("UTF-8 Data was corrupted communicating with the database, "
                        + "please check connectionstring and default table types (Conversion)" + "" + bin[i]
                        + "=>" + (int) cin[i] + "=>" + bout[i]);
            }
        }

    } finally {
        try {
            rs.close();
        } catch (Exception ex) {

        }
        try {
            statement3.close();
        } catch (Exception ex) {

        }
        try {
            statement2.close();
        } catch (Exception ex) {

        }
        try {
            statement.close();
        } catch (Exception ex) {

        }
    }

}

From source file:org.apache.marmotta.kiwi.persistence.KiWiConnection.java

/**
 * Return the prepared statement with the given identifier; first looks in the statement cache and if it does
 * not exist there create a new statement. This method is used for building statements with variable argument
 * numbers (e.g. in an IN)./*from   ww w  . j ava  2  s  .  com*/
 *
 * @param key the id of the statement in statements.properties
 * @return
 * @throws SQLException
 */
public PreparedStatement getPreparedStatement(String key, int numberOfArguments) throws SQLException {
    requireJDBCConnection();

    PreparedStatement statement = statementCache.get(key + numberOfArguments);
    if (statement == null || statement.isClosed()) {
        StringBuilder s = new StringBuilder();
        for (int i = 0; i < numberOfArguments; i++) {
            if (i != 0) {
                s.append(',');
            }
            s.append('?');
        }

        statement = connection.prepareStatement(
                String.format(dialect.getStatement(key), s.toString(), numberOfArguments),
                ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY);
        statementCache.put(key + numberOfArguments, statement);
    }
    statement.clearParameters();
    if (persistence.getDialect().isCursorSupported()) {
        statement.setFetchSize(persistence.getConfiguration().getCursorSize());
    }
    return statement;
}

From source file:org.LexGrid.util.sql.lgTables.SQLTableUtilities.java

/**
 * Remove the root ('@') or tail ('@@') relationship node for the given
 * coding scheme./*from w  w  w  .ja v a2s .c  o m*/
 * 
 * @param codingScheme
 *            The coding scheme to remove the root node from.
 * @param relationName
 *            The relation container for the root node. If null, the native
 *            relation for the coding scheme is used.
 * @param root
 *            - true for root ('@'), false for tail ('@@').
 * @throws SQLException
 */
public void removeRootRelationNode(String codingScheme, String relationName, boolean root) throws SQLException {
    if (!doTablesExist())
        return;

    int count = 0;
    Connection conn = getConnection();
    try {
        // Define the SQL statements to locate and delete affected entries
        // ...
        StringBuffer sb = new StringBuffer("SELECT * FROM ")
                .append(stc_.getTableName(SQLTableConstants.ENTITY_ASSOCIATION_TO_ENTITY))
                .append(" WHERE " + stc_.codingSchemeNameOrId + " = ? AND " + stc_.containerNameOrContainerDC
                        + " = ? AND ")
                .append(root ? (stc_.sourceEntityCodeOrId + " = '@'")
                        : (stc_.targetEntityCodeOrId + " = '@@'"));
        PreparedStatement getRoots = conn.prepareStatement(gsm_.modifySQL(sb.toString()));

        sb = new StringBuffer("DELETE FROM ")
                .append(stc_.getTableName(SQLTableConstants.ENTITY_ASSOCIATION_TO_ENTITY))
                .append(" WHERE " + stc_.codingSchemeNameOrId + " = ? AND " + stc_.containerNameOrContainerDC
                        + " = ? AND " + stc_.entityCodeOrAssociationId + " = ?")
                .append(" AND " + stc_.sourceCSIdOrEntityCodeNS + " = ? AND " + stc_.sourceEntityCodeOrId
                        + " = ?")
                .append(" AND " + stc_.targetCSIdOrEntityCodeNS + " = ? AND " + stc_.targetEntityCodeOrId
                        + " = ?");
        PreparedStatement deleteAssoc = conn.prepareStatement(gsm_.modifySQL(sb.toString()));

        sb = new StringBuffer("DELETE FROM ")
                .append(stc_.getTableName(SQLTableConstants.ENTITY_ASSOCIATION_TO_E_QUALS))
                .append(" WHERE " + stc_.codingSchemeNameOrId + " = ? AND "
                        + SQLTableConstants.TBLCOL_MULTIATTRIBUTESKEY + " = ?");
        PreparedStatement deleteCQual = conn.prepareStatement(gsm_.modifySQL(sb.toString()));

        // Locate matching entries and clear, along with associated
        // qualifiers ...
        try {
            getRoots.setString(1, codingScheme);
            getRoots.setString(2, relationName != null ? relationName : getNativeRelation(codingScheme));
            ResultSet rs = getRoots.executeQuery();
            while (rs.next()) {
                // Remove matching qualifiers ...
                String multiKey = rs.getString(SQLTableConstants.TBLCOL_MULTIATTRIBUTESKEY);
                if (multiKey != null && multiKey.length() > 0) {
                    deleteCQual.clearParameters();
                    deleteCQual.clearWarnings();
                    deleteCQual.setString(1, codingScheme);
                    deleteCQual.setString(2, multiKey);
                    deleteCQual.execute();
                }

                // Remove the association/source/target ...
                deleteAssoc.clearParameters();
                deleteAssoc.clearWarnings();
                deleteAssoc.setString(1, codingScheme);
                deleteAssoc.setString(2, relationName);
                deleteAssoc.setString(3, rs.getString(stc_.entityCodeOrAssociationId));
                deleteAssoc.setString(4, rs.getString(stc_.sourceCSIdOrEntityCodeNS));
                deleteAssoc.setString(5, rs.getString(stc_.sourceEntityCodeOrId));
                deleteAssoc.setString(6, rs.getString(stc_.targetCSIdOrEntityCodeNS));
                deleteAssoc.setString(7, rs.getString(stc_.targetEntityCodeOrId));
                if (!deleteAssoc.execute() && deleteAssoc.getUpdateCount() > 0)
                    count += deleteAssoc.getUpdateCount();
            }
            rs.close();
        } finally {
            getRoots.close();
            deleteAssoc.close();
            deleteCQual.close();
        }
    } finally {
        returnConnection(conn);
        log.info("Removed " + count + " root associations.");
    }
}

From source file:org.opencms.db.generic.CmsHistoryDriver.java

/**
 * @see org.opencms.db.I_CmsHistoryDriver#writeProject(org.opencms.db.CmsDbContext, int, long)
 */// www  .  ja  v a  2  s. c  o  m
public void writeProject(CmsDbContext dbc, int publishTag, long publishDate) throws CmsDataAccessException {

    CmsProject currentProject = dbc.currentProject();
    CmsUser currentUser = dbc.currentUser();

    List projectresources = m_driverManager.getProjectDriver(dbc).readProjectResources(dbc, currentProject);

    // write historical project to the database
    Connection conn = null;
    PreparedStatement stmt = null;
    try {
        conn = m_sqlManager.getConnection(dbc);

        stmt = m_sqlManager.getPreparedStatement(conn, "C_PROJECTS_HISTORY_CREATE");
        // first write the project
        stmt.setInt(1, publishTag);
        stmt.setString(2, currentProject.getUuid().toString());
        stmt.setString(3, currentProject.getSimpleName());
        stmt.setLong(4, publishDate);
        stmt.setString(5, currentUser.getId().toString());
        stmt.setString(6, currentProject.getOwnerId().toString());
        stmt.setString(7, currentProject.getGroupId().toString());
        stmt.setString(8, currentProject.getManagerGroupId().toString());
        stmt.setString(9, currentProject.getDescription());
        stmt.setLong(10, currentProject.getDateCreated());
        stmt.setInt(11, currentProject.getType().getMode());
        stmt.setString(12, CmsOrganizationalUnit.SEPARATOR + currentProject.getOuFqn());
        stmt.executeUpdate();

        m_sqlManager.closeAll(dbc, null, stmt, null);

        // now write the projectresources
        stmt = m_sqlManager.getPreparedStatement(conn, "C_PROJECTRESOURCES_HISTORY_CREATE");
        Iterator i = projectresources.iterator();
        while (i.hasNext()) {
            stmt.setInt(1, publishTag);
            stmt.setString(2, currentProject.getUuid().toString());
            stmt.setString(3, (String) i.next());
            stmt.executeUpdate();
            stmt.clearParameters();
        }
    } catch (SQLException e) {
        throw new CmsDbSqlException(
                Messages.get().container(Messages.ERR_GENERIC_SQL_1, CmsDbSqlException.getErrorQuery(stmt)), e);
    } finally {
        m_sqlManager.closeAll(dbc, conn, stmt, null);
    }
}

From source file:com.mirth.connect.donkey.server.data.jdbc.JdbcDao.java

@Override
public void batchInsertMessageContent(MessageContent messageContent) {
    logger.debug(messageContent.getChannelId() + "/" + messageContent.getMessageId() + "/"
            + messageContent.getMetaDataId() + ": batch inserting message content ("
            + messageContent.getContentType().toString() + ")");

    try {/*from  ww w . j  a v  a2  s  . co m*/
        String content;
        boolean encrypted;

        // Only encrypt if the content is not already encrypted
        if (encryptData && encryptor != null && !messageContent.isEncrypted()) {
            content = encryptor.encrypt(messageContent.getContent());
            encrypted = true;
        } else {
            content = messageContent.getContent();
            encrypted = messageContent.isEncrypted();
        }

        PreparedStatement statement = prepareStatement("batchInsertMessageContent",
                messageContent.getChannelId());
        statement.setInt(1, messageContent.getMetaDataId());
        statement.setLong(2, messageContent.getMessageId());
        statement.setInt(3, messageContent.getContentType().getContentTypeCode());
        statement.setString(4, content);
        statement.setString(5, messageContent.getDataType());
        statement.setBoolean(6, encrypted);

        statement.addBatch();
        statement.clearParameters();
    } catch (SQLException e) {
        throw new DonkeyDaoException(e);
    }
}

From source file:com.mirth.connect.donkey.server.data.jdbc.JdbcDao.java

public void storeContent(String channelId, long messageId, int metaDataId, ContentType contentType,
        String content, String dataType, boolean encrypted) {
    try {/*from   w  w  w. j  a  v  a2  s  .co m*/
        // Only encrypt if the content is not already encrypted
        if (encryptData && encryptor != null && !encrypted) {
            content = encryptor.encrypt(content);
            encrypted = true;
        }

        PreparedStatement statement = prepareStatement("storeMessageContent", channelId);

        if (content == null) {
            statement.setNull(1, Types.LONGVARCHAR);
        } else {
            statement.setString(1, content);
        }

        statement.setString(2, dataType);
        statement.setBoolean(3, encrypted);
        statement.setInt(4, metaDataId);
        statement.setLong(5, messageId);
        statement.setInt(6, contentType.getContentTypeCode());

        int rowCount = statement.executeUpdate();
        statement.clearParameters();

        if (rowCount == 0) {
            // This is the same code as insertContent, without going through the encryption process again
            logger.debug(channelId + "/" + messageId + "/" + metaDataId + ": updating message content ("
                    + contentType.toString() + ")");

            statement = prepareStatement("insertMessageContent", channelId);
            statement.setInt(1, metaDataId);
            statement.setLong(2, messageId);
            statement.setInt(3, contentType.getContentTypeCode());
            statement.setString(4, content);
            statement.setString(5, dataType);
            statement.setBoolean(6, encrypted);

            statement.executeUpdate();
            statement.clearParameters();
        }
    } catch (SQLException e) {
        throw new DonkeyDaoException(e);
    }
}

From source file:org.wso2.carbon.identity.provisioning.dao.ProvisioningManagementDAO.java

/**
 * @param newIdentityProvider// w w w  .j  a  va2s. c o  m
 * @param currentIdentityProvider
 * @param tenantId
 * @throws IdentityApplicationManagementException
 */
public void updateProvisionedIdentifier(IdentityProvider newIdentityProvider,
        IdentityProvider currentIdentityProvider, int tenantId) throws IdentityApplicationManagementException {

    Connection dbConnection = IdentityDatabaseUtil.getDBConnection();

    try {

        int idPId = getIdentityProviderIdByName(dbConnection, newIdentityProvider.getIdentityProviderName(),
                tenantId);

        if (idPId <= 0) {
            String msg = "Trying to update non-existent Identity Provider for tenant " + tenantId;
            throw new IdentityApplicationManagementException(msg);
        }

        PreparedStatement prepStmt = null;

        // SP_IDP_NAME=?, SP_IDP_PRIMARY=?,SP_IDP_HOME_REALM_ID=?,
        // SP_IDP_THUMBPRINT=?,
        // 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, newIdentityProvider.getIdentityProviderName());

        if (newIdentityProvider.isPrimary()) {
            prepStmt.setString(2, "1");
        } else {
            prepStmt.setString(2, "0");
        }

        prepStmt.setString(3, newIdentityProvider.getHomeRealmId());
        prepStmt.setBinaryStream(4, setBlobValue(newIdentityProvider.getCertificate()));
        prepStmt.setString(5, newIdentityProvider.getAlias());

        if (newIdentityProvider.getJustInTimeProvisioningConfig() != null
                && newIdentityProvider.getJustInTimeProvisioningConfig().isProvisioningEnabled()) {
            prepStmt.setString(6, "1");
            prepStmt.setString(7,
                    newIdentityProvider.getJustInTimeProvisioningConfig().getProvisioningUserStore());

        } else {
            prepStmt.setString(6, "0");
            prepStmt.setString(7, null);
        }

        if (newIdentityProvider.getClaimConfig() != null) {
            prepStmt.setString(8, newIdentityProvider.getClaimConfig().getUserClaimURI());
            prepStmt.setString(9, 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, 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, newIdentityProvider.getDefaultProvisioningConnectorConfig().getName());
        } else {
            // its not a must to have a default provisioning connector..
            prepStmt.setString(11, null);
        }

        prepStmt.setString(12, newIdentityProvider.getIdentityProviderDescription());

        prepStmt.setInt(13, tenantId);
        prepStmt.setString(14, currentIdentityProvider.getIdentityProviderName());

        prepStmt.executeUpdate();

        prepStmt.clearParameters();
        IdentityApplicationManagementUtil.closeStatement(prepStmt);

        dbConnection.commit();
    } catch (SQLException e) {
        IdentityApplicationManagementUtil.rollBack(dbConnection);
        String msg = "Error occurred while updating Identity Provider information  for tenant " + tenantId;
        throw new IdentityApplicationManagementException(msg, e);
    } finally {
        IdentityApplicationManagementUtil.closeConnection(dbConnection);
    }
}

From source file:org.sakaiproject.search.index.impl.JDBCClusterIndexStore.java

/**
 * updat this save this local segment into the db
 * /*from  w  w w  .ja  va  2 s.  c  o m*/
 * @param connection
 * @param addsi
 */
protected void updateDBPatchFilesystem(Connection connection) throws SQLException, IOException {

    PreparedStatement segmentUpdate = null;
    PreparedStatement segmentInsert = null;
    FileChannel packetStream = null;
    FileInputStream packetFIS = null;
    FileChannel sharedStream = null;
    FileOutputStream sharedFOS = null;

    File packetFile = null;
    File sharedFinalFile = null;
    File sharedTempFile = null;
    long newVersion = System.currentTimeMillis();
    try {
        sharedTempFile = new File(getSharedTempFileName(INDEX_PATCHNAME));
        sharedFinalFile = new File(getSharedFileName(INDEX_PATCHNAME, sharedStructuredStorage));
        packetFile = clusterStorage.packPatch();
        if (packetFile.exists()) {
            packetFIS = new FileInputStream(packetFile);
            packetStream = packetFIS.getChannel();
            File sharedTempFileParent = sharedTempFile.getParentFile();
            if (!sharedTempFileParent.exists() && !sharedTempFileParent.mkdirs()) {
                log.warn("couldn't create " + sharedTempFileParent.getPath());
            }
            sharedFOS = new FileOutputStream(sharedTempFile);
            sharedStream = sharedFOS.getChannel();

            doBlockedStream(packetStream, sharedStream);

            packetStream.close();
            sharedStream.close();

            segmentUpdate = connection
                    .prepareStatement("update search_segments set  version_ = ?, size_ = ? where name_ = ? ");
            segmentInsert = connection
                    .prepareStatement("insert into search_segments ( name_, version_, size_ ) values ( ?,?,?)");

            segmentUpdate.clearParameters();
            segmentUpdate.setLong(1, newVersion);
            segmentUpdate.setLong(2, packetFile.length());
            segmentUpdate.setString(3, INDEX_PATCHNAME);
            if (segmentUpdate.executeUpdate() != 1) {
                segmentInsert.clearParameters();
                segmentInsert.setString(1, INDEX_PATCHNAME);
                segmentInsert.setLong(2, newVersion);
                segmentInsert.setLong(3, packetFile.length());
                if (segmentInsert.executeUpdate() != 1) {
                    throw new SQLException(" Failed to add patch packet  ");
                }
            }

            long st = System.currentTimeMillis();
            if (!sharedTempFile.renameTo(sharedFinalFile)) {
                log.warn("Couldn't rename file " + sharedTempFile.getPath() + " to "
                        + sharedFinalFile.getPath());
            }
            if (searchService.hasDiagnostics()) {
                log.info("Renamed " + sharedTempFile.getPath() + " to " + sharedFinalFile.getPath() + " in "
                        + (System.currentTimeMillis() - st) + "ms");
            }
        } else {
            log.warn("Packet file does not exist " + packetFile.getPath());
        }

    } finally {

        try {
            if (packetStream != null) {
                packetStream.close();
                packetFIS.close();
            }
        } catch (Exception ex) {
            log.debug(ex);
        }
        try {
            packetFile.delete();
        } catch (Exception ex) {
            log.debug(ex);
        }
        try {
            if (sharedStream != null) {
                sharedStream.close();
                sharedFOS.close();
            }
        } catch (Exception ex) {
            log.debug(ex);
        }
        try {
            sharedTempFile.delete();
        } catch (Exception ex) {
            log.debug(ex);
        }
        try {
            segmentUpdate.close();
        } catch (Exception ex) {
            log.debug(ex);
        }
        try {
            segmentInsert.close();
        } catch (Exception ex) {
            log.debug(ex);
        }
    }

}

From source file:org.apereo.portal.layout.dlm.RDBMDistributedLayoutStore.java

@Override
protected int saveStructure(Node node, PreparedStatement structStmt, PreparedStatement parmStmt)
        throws SQLException {
    if (node == null) { // No more
        return 0;
    }/* w  w  w  .  jav  a 2  s  .  com*/
    if (node.getNodeName().equals("parameter")) {
        //parameter, skip it and go on to the next node
        return this.saveStructure(node.getNextSibling(), structStmt, parmStmt);
    }
    if (!(node instanceof Element)) {
        return 0;
    }

    final Element structure = (Element) node;

    if (logger.isDebugEnabled()) {
        logger.debug("saveStructure XML content: {}", XmlUtilitiesImpl.toString(node));
    }

    // determine the struct_id for storing in the db. For incorporated nodes in
    // the plf their ID is a system-wide unique ID while their struct_id for
    // storing in the db is cached in a dlm:plfID attribute.
    int saveStructId = -1;
    final String plfID = structure.getAttribute(Constants.ATT_PLF_ID);

    if (!plfID.equals("")) {
        saveStructId = Integer.parseInt(plfID.substring(1));
    } else {
        final String id = structure.getAttribute("ID");
        saveStructId = Integer.parseInt(id.substring(1));
    }

    int nextStructId = 0;
    int childStructId = 0;
    int chanId = -1;
    IPortletDefinition portletDef = null;
    final boolean isChannel = node.getNodeName().equals("channel");

    if (isChannel) {
        chanId = Integer.parseInt(node.getAttributes().getNamedItem("chanID").getNodeValue());
        portletDef = this.portletDefinitionRegistry.getPortletDefinition(String.valueOf(chanId));
        if (portletDef == null) {
            //Portlet doesn't exist any more, drop the layout node
            return 0;
        }
    }

    if (node.hasChildNodes()) {
        childStructId = this.saveStructure(node.getFirstChild(), structStmt, parmStmt);
    }
    nextStructId = this.saveStructure(node.getNextSibling(), structStmt, parmStmt);
    structStmt.clearParameters();
    structStmt.setInt(1, saveStructId);
    structStmt.setInt(2, nextStructId);
    structStmt.setInt(3, childStructId);

    final String externalId = structure.getAttribute("external_id");
    if (externalId != null && externalId.trim().length() > 0) {
        final Integer eID = new Integer(externalId);
        structStmt.setInt(4, eID.intValue());
    } else {
        structStmt.setNull(4, java.sql.Types.NUMERIC);

    }
    if (isChannel) {
        structStmt.setInt(5, chanId);
        structStmt.setNull(6, java.sql.Types.VARCHAR);
    } else {
        structStmt.setNull(5, java.sql.Types.NUMERIC);
        structStmt.setString(6, structure.getAttribute("name"));
    }
    final String structType = structure.getAttribute("type");
    structStmt.setString(7, structType);
    structStmt.setString(8, RDBMServices.dbFlag(xmlBool(structure.getAttribute("hidden"))));
    structStmt.setString(9, RDBMServices.dbFlag(xmlBool(structure.getAttribute("immutable"))));
    structStmt.setString(10, RDBMServices.dbFlag(xmlBool(structure.getAttribute("unremovable"))));
    logger.debug(structStmt.toString());
    structStmt.executeUpdate();

    // code to persist extension attributes for dlm
    final NamedNodeMap attribs = node.getAttributes();
    for (int i = 0; i < attribs.getLength(); i++) {
        final Node attrib = attribs.item(i);
        final String name = attrib.getNodeName();

        if (name.startsWith(Constants.NS) && !name.equals(Constants.ATT_PLF_ID)
                && !name.equals(Constants.ATT_FRAGMENT) && !name.equals(Constants.ATT_PRECEDENCE)) {
            // a cp extension attribute. Push into param table.
            parmStmt.clearParameters();
            parmStmt.setInt(1, saveStructId);
            parmStmt.setString(2, name);
            parmStmt.setString(3, attrib.getNodeValue());
            logger.debug(parmStmt.toString());
            parmStmt.executeUpdate();
        }
    }
    final NodeList parameters = node.getChildNodes();
    if (parameters != null && isChannel) {
        for (int i = 0; i < parameters.getLength(); i++) {
            if (parameters.item(i).getNodeName().equals("parameter")) {
                final Element parmElement = (Element) parameters.item(i);
                final NamedNodeMap nm = parmElement.getAttributes();
                final String parmName = nm.getNamedItem("name").getNodeValue();
                final String parmValue = nm.getNamedItem("value").getNodeValue();
                final Node override = nm.getNamedItem("override");

                // if no override specified then default to allowed
                if (override != null && !override.getNodeValue().equals("yes")) {
                    // can't override
                } else {
                    // override only for adhoc or if diff from chan def
                    final IPortletDefinitionParameter cp = portletDef.getParameter(parmName);
                    if (cp == null || !cp.getValue().equals(parmValue)) {
                        parmStmt.clearParameters();
                        parmStmt.setInt(1, saveStructId);
                        parmStmt.setString(2, parmName);
                        parmStmt.setString(3, parmValue);
                        logger.debug(parmStmt.toString());
                        parmStmt.executeUpdate();
                    }
                }
            }
        }
    }
    return saveStructId;
}

From source file:org.sakaiproject.search.index.impl.JDBCClusterIndexStore.java

/**
 * updat this save this local segment into the db
 * /*  w  ww  .  j  av a 2s.  c  om*/
 * @param connection
 * @param addsi
 */
protected void updateDBSegmentFilesystem(Connection connection, SegmentInfo addsi)
        throws SQLException, IOException {

    PreparedStatement segmentUpdate = null;
    PreparedStatement segmentInsert = null;
    FileChannel packetStream = null;
    FileInputStream packetFIS = null;
    FileChannel sharedStream = null;
    FileOutputStream sharedFOS = null;
    File packetFile = null;
    File sharedFinalFile = null;
    File sharedTempFile = null;
    long newVersion = System.currentTimeMillis();
    try {
        sharedTempFile = new File(getSharedTempFileName(addsi.getName()));
        sharedFinalFile = new File(getSharedFileName(addsi.getName(), sharedStructuredStorage));
        packetFile = clusterStorage.packSegment(addsi, newVersion);
        if (packetFile.exists()) {
            packetFIS = new FileInputStream(packetFile);
            packetStream = packetFIS.getChannel();
            File parentFile = sharedTempFile.getParentFile();
            if (!parentFile.exists() && !parentFile.mkdirs()) {
                log.warn("Unable to create directory " + sharedTempFile.getParentFile().getPath());
            }
            sharedFOS = new FileOutputStream(sharedTempFile);
            sharedStream = sharedFOS.getChannel();

            // Copy file contents from source to destination
            doBlockedStream(packetStream, sharedStream);

            packetStream.close();
            sharedStream.close();

            segmentUpdate = connection.prepareStatement(
                    "update search_segments set  version_ = ?, size_ = ? where name_ = ? and version_ = ?");
            segmentInsert = connection
                    .prepareStatement("insert into search_segments ( name_, version_, size_ ) values ( ?,?,?)");
            if (addsi.isInDb()) {
                segmentUpdate.clearParameters();
                segmentUpdate.setLong(1, newVersion);
                segmentUpdate.setLong(2, packetFile.length());
                segmentUpdate.setString(3, addsi.getName());
                segmentUpdate.setLong(4, addsi.getVersion());
                if (segmentUpdate.executeUpdate() != 1) {
                    throw new SQLException(" ant Find packet to update " + addsi);
                }
            } else {
                segmentInsert.clearParameters();
                segmentInsert.setString(1, addsi.getName());
                segmentInsert.setLong(2, newVersion);
                segmentInsert.setLong(3, packetFile.length());
                if (segmentInsert.executeUpdate() != 1) {
                    throw new SQLException(" Failed to insert packet  " + addsi);
                }
            }
            addsi.setVersion(newVersion);
            File sharedParentFile = sharedFinalFile.getParentFile();
            if (!sharedParentFile.exists() && !sharedParentFile.mkdirs()) {
                log.warn("Couln't create directory " + sharedParentFile.getPath());
            }
            long st = System.currentTimeMillis();
            if (!sharedTempFile.renameTo(sharedFinalFile)) {
                log.warn("Couldn't rename " + sharedTempFile.getPath() + " to " + sharedFinalFile.getPath());

            }
            if (searchService.hasDiagnostics()) {
                log.info("Renamed " + sharedTempFile.getPath() + " to " + sharedFinalFile.getPath() + " in "
                        + (System.currentTimeMillis() - st) + "ms");
            }

            log.info("DB Updated " + addsi);
        } else {
            log.warn("Packet file does not exist " + packetFile.getPath());
        }

    } finally {
        try {
            packetStream.close();
            packetFIS.close();
        } catch (Exception ex) {
            log.debug(ex);
        }
        try {
            packetFile.delete();
        } catch (Exception ex) {
            log.debug(ex);
        }
        try {
            sharedStream.close();
            sharedFOS.close();
        } catch (Exception ex) {
            log.debug(ex);
        }
        try {
            sharedTempFile.delete();
        } catch (Exception ex) {
            log.debug(ex);
        }
        try {
            segmentUpdate.close();
        } catch (Exception ex) {
            log.debug(ex);
        }
        try {
            segmentInsert.close();
        } catch (Exception ex) {
            log.debug(ex);
        }
    }

}