001package com.identityworksllc.iiq.common.task.export;
002
003import com.identityworksllc.iiq.common.query.NamedParameterStatement;
004import org.apache.commons.logging.Log;
005import sailpoint.api.SailPointContext;
006import sailpoint.server.Environment;
007import sailpoint.tools.GeneralException;
008
009import java.sql.Connection;
010import java.sql.PreparedStatement;
011import java.sql.ResultSet;
012import java.sql.SQLException;
013import java.util.HashSet;
014import java.util.Set;
015
016public class CleanupLinksPartition extends ExportPartition {
017
018    protected static final String SQL_GET_EXISTING_LINKS = "select id from spt_link";
019    protected static final String SQL_GET_MAPPED_LINKS = "select id from de_link";
020
021    @Override
022    protected void export(SailPointContext context, Connection connection, Log logger) throws GeneralException {
023        Set<String> exportIds = new HashSet<>();
024        try (PreparedStatement statement = connection.prepareStatement(SQL_GET_MAPPED_LINKS)) {
025            try (ResultSet results = statement.executeQuery()) {
026                while(results.next()) {
027                    exportIds.add(results.getString(1));
028                }
029            }
030        } catch(SQLException e) {
031            throw new GeneralException(e);
032        }
033
034        if (logger.isDebugEnabled()) {
035            logger.debug("Found " + exportIds.size() + " exported Links in the export table");
036        }
037
038        try (Connection localConnection = Environment.getEnvironment().getSpringDataSource().getConnection()) {
039            try (PreparedStatement statement = localConnection.prepareStatement(SQL_GET_EXISTING_LINKS)) {
040                try (ResultSet results = statement.executeQuery()) {
041                    while(results.next()) {
042                        exportIds.remove(results.getString(1));
043                    }
044                }
045            }
046        } catch(SQLException e) {
047            throw new GeneralException(e);
048        }
049
050        // After this, what's left should be rows in the de_link table that are not in IIQ
051
052        try (NamedParameterStatement deleteLink = new NamedParameterStatement(connection, ExportLinksPartition.DELETE_LINK); NamedParameterStatement deleteAttrs = new NamedParameterStatement(connection, ExportLinksPartition.DELETE_LINK_ATTRS)) {
053            for (String id : exportIds) {
054                deleteLink.setString("id", id);
055                deleteAttrs.setString("id", id);
056
057                deleteAttrs.executeUpdate();
058                deleteLink.executeUpdate();
059            }
060        } catch(SQLException e) {
061            throw new GeneralException(e);
062        }
063    }
064}