001package org.fcrepo.migration.pidlist;
002
003import org.slf4j.Logger;
004
005import java.io.BufferedReader;
006import java.io.File;
007import java.io.FileReader;
008import java.io.IOException;
009import java.util.HashSet;
010import java.util.Set;
011
012import static org.slf4j.LoggerFactory.getLogger;
013
014/**
015 * This class "accepts" and PIDs that are included in the user-provided list
016 *
017 * @author awoods
018 * @since 2019-11-08
019 */
020public class UserProvidedPidListManager implements PidListManager {
021
022    private static final Logger LOGGER = getLogger(UserProvidedPidListManager.class);
023
024    private Set<String> pidList = new HashSet<>();
025
026    /**
027     * Constructor
028     *
029     * @param pidListFile provided by user
030     */
031    public UserProvidedPidListManager(final File pidListFile) {
032
033        // If arg is null, we will accept all PIDs
034        if (pidListFile != null) {
035            if (!pidListFile.exists() || !pidListFile.canRead()) {
036                throw new IllegalArgumentException("File either does not exist or is inaccessible :" +
037                        pidListFile.getAbsolutePath());
038            }
039
040            try (BufferedReader reader = new BufferedReader(new FileReader(pidListFile));) {
041                reader.lines().forEach(l -> pidList.add(l));
042            } catch (IOException e) {
043                // Should not happen based on previous check
044                throw new RuntimeException(e);
045            }
046        }
047    }
048
049
050    @Override
051    public boolean accept(final String pid) {
052        final boolean doAccept =  pidList.isEmpty() || pidList.contains(pid);
053        LOGGER.debug("PID: {}, accept? {}", pid, doAccept);
054        return doAccept;
055    }
056}