<commit_before>package org.verapdf.model.tools;

import org.apache.log4j.Logger;
import org.apache.pdfbox.cos.*;
import org.apache.pdfbox.util.DateConverter;
import org.apache.xmpbox.XMPMetadata;
import org.apache.xmpbox.schema.AdobePDFSchema;
import org.apache.xmpbox.schema.DublinCoreSchema;
import org.apache.xmpbox.schema.XMPBasicSchema;
import org.apache.xmpbox.xml.DomXmpParser;
import org.apache.xmpbox.xml.XmpParsingException;

import java.io.IOException;
import java.util.*;

/**
 * @author <NAME>
 */
public class XMPChecker {

    private final static Logger logger = Logger.getLogger(XMPChecker.class);

    private final static List<String> URLS = new ArrayList<>(4);

    private static final String TITLE = "Title";
    private static final String SUBJECT = "Subject";
    private static final String AUTHOR = "Author";
    private static final String KEYWORDS = "Keywords";
    private static final String PRODUCER = "Producer";
    private static final String CREATOR = "Creator";
    private static final String CREATION_DATE = "CreationDate";
    private static final String MODIFICATION_DATE = "ModDate";

    static {
        URLS.add("http://purl.org/dc/elements/1.1/");
        URLS.add("http://ns.adobe.com/xap/1.0/");
        URLS.add("http://ns.adobe.com/pdf/1.3/");
        URLS.add("http://www.aiim.org/pdfa/ns/id/");
    }

    public static Boolean doesInfoMatchXMP(COSDocument document) {
        COSDictionary info = getInformationDictionary(document);
        if (info == null) {
            return Boolean.TRUE;
        }

        try {
            COSStream meta = getMetadataDictionary(document);
            if (meta != null) {
                DomXmpParser xmpParser = new DomXmpParser();
                XMPMetadata metadata = xmpParser.parse(meta.getUnfilteredStream());

                Map<String, Object> properties = new HashMap<>(8);

                getTitleAuthorSubject(metadata, properties);

                getProducerKeywords(metadata, properties);

                getCreatorAndDates(metadata, properties);

                return checkMatch(info, properties);
            }
        } catch (IOException e) {
            logger.error("Problems with document parsing or structure. " + e.getMessage());
        } catch (XmpParsingException e) {
            logger.error("Problems with XMP parsing. " + e.getMessage());
        }

        return Boolean.FALSE;
    }

    private static COSStream getMetadataDictionary(COSDocument document) throws IOException {
        final COSDictionary catalog = (COSDictionary) document.getCatalog().getObject();
        final COSObject metaObj = (COSObject) catalog.getItem(COSName.METADATA);
        if (metaObj != null && metaObj.getObject() instanceof COSStream) {
            return (COSStream) metaObj.getObject();
        } else {
            return null;
        }
    }

    private static COSDictionary getInformationDictionary(COSDocument document) {
        final COSObject info = (COSObject) document.getTrailer().getItem(COSName.INFO);
        if (info != null) {
            if (info.getObject() instanceof COSDictionary) {
                return (COSDictionary) info.getObject();
            } else if (info.getObject() instanceof COSObject) {
                return getInformationDictionary((COSObject) info.getObject());
            }
        }
        return null;
    }

    private static COSDictionary getInformationDictionary(COSObject object) {
        if (object.getObject() instanceof COSDictionary) {
            return (COSDictionary) object.getObject();
        } else if (object.getObject() instanceof COSObject) {
            return getInformationDictionary((COSObject) object.getObject());
        } else {
            return null;
        }
    }

    private static void getTitleAuthorSubject(XMPMetadata metadata, Map<String, Object> properties) {
        DublinCoreSchema dc = metadata.getDublinCoreSchema();
        if (dc != null && URLS.contains(dc.getNamespace())) {
            final List<String> buffer = dc.getCreators();
            putProperty(properties, TITLE, dc.getTitle());
            putProperty(properties, SUBJECT, dc.getDescription());
            putProperty(properties, AUTHOR, buffer.toArray(new String[buffer.size()]));
        }
    }

    private static void getProducerKeywords(XMPMetadata metadata, Map<String, Object> properties) {
        AdobePDFSchema pdf = metadata.getAdobePDFSchema();
        if (pdf != null && URLS.contains(pdf.getNamespace())) {
            putProperty(properties, KEYWORDS, pdf.getKeywords());
            putProperty(properties, PRODUCER, pdf.getProducer());
        }
    }

    private static void getCreatorAndDates(XMPMetadata metadata, Map<String, Object> properties) {
        XMPBasicSchema basic = metadata.getXMPBasicSchema();
        if (basic != null && URLS.contains(basic.getNamespace())) {
            putProperty(properties, CREATOR, basic.getCreatorTool());
            putProperty(properties, CREATION_DATE, basic.getCreateDate());
            putProperty(properties, MODIFICATION_DATE, basic.getModifyDate());
        }
    }

    private static void putProperty(Map<String, Object> properties, String key, String... values) {
        if (values != null) {
            StringBuilder builder = new StringBuilder();
            for (String value : values) {
                if (value != null) {
                    builder.append(value).append(" ");
                }
            }
            if (builder.length() > 1) {
                //need to discard last space
                properties.put(key, builder.substring(0, builder.length() - 1));
            }
        }
    }

    private static void putProperty(Map<String, Object> properties, String key, Calendar date) {
        if (date != null) {
            properties.put(key, date);
        }
    }

    private static Boolean checkMatch(COSDictionary info, Map<String, Object> properties) {
        if (!checkProperty(info, properties, TITLE)) return Boolean.FALSE;
        if (!checkProperty(info, properties, SUBJECT)) return Boolean.FALSE;
        if (!checkProperty(info, properties, AUTHOR)) return Boolean.FALSE;
        if (!checkProperty(info, properties, KEYWORDS)) return Boolean.FALSE;
        if (!checkProperty(info, properties, PRODUCER)) return Boolean.FALSE;
        if (!checkProperty(info, properties, CREATOR)) return Boolean.FALSE;
        if (!checkProperty(info, properties, CREATION_DATE)) return Boolean.FALSE;
        if (!checkProperty(info, properties, MODIFICATION_DATE)) return Boolean.FALSE;

        return Boolean.TRUE;
    }
<commit_msg>Add javadoc. Small fix<commit_after>package org.verapdf.model.tools;

import org.apache.log4j.Logger;
import org.apache.pdfbox.cos.*;
import org.apache.pdfbox.util.DateConverter;
import org.apache.xmpbox.XMPMetadata;
import org.apache.xmpbox.schema.AdobePDFSchema;
import org.apache.xmpbox.schema.DublinCoreSchema;
import org.apache.xmpbox.schema.XMPBasicSchema;
import org.apache.xmpbox.xml.DomXmpParser;
import org.apache.xmpbox.xml.XmpParsingException;

import java.io.IOException;
import java.util.*;

/**
 * Class for checking match of document information dictionary and xmp. Current class
 * compare 8 predefined fields in info with document xmp:
 * <ol>
 *     <li>Title (-> Title)</li>
 *     <li>Author (-> Creators)</li>
 *     <li>Producer (-> Producer)</li>
 *     <li>Creator (-> CreatorTool)</li>
 *     <li>Keywords (-> Keywords)</li>
 *     <li>Subject (-> Description)</li>
 *     <li>Creation Date (-> Create Date)</li>
 *     <li>Mod Date (-> Modify Date)</li>
 * </ol>
 * If document information dictionary not contain any of property, described above, than xmp
 * not required to consist it.
 *
 * @author <NAME>
 */
public class XMPChecker {

    private final static Logger logger = Logger.getLogger(XMPChecker.class);

    private final static List<String> URLS = new ArrayList<>(4);

    private static final String TITLE = "Title";
    private static final String SUBJECT = "Subject";
    private static final String AUTHOR = "Author";
    private static final String KEYWORDS = "Keywords";
    private static final String PRODUCER = "Producer";
    private static final String CREATOR = "Creator";
    private static final String CREATION_DATE = "CreationDate";
    private static final String MODIFICATION_DATE = "ModDate";

    static {
        URLS.add("http://purl.org/dc/elements/1.1/");
        URLS.add("http://ns.adobe.com/xap/1.0/");
        URLS.add("http://ns.adobe.com/pdf/1.3/");
        URLS.add("http://www.aiim.org/pdfa/ns/id/");
    }

    /**
     * Match fields of document information dictionary with fields of xmp. Check only
     * predefined fields.
     * @param document which will be tested
     * @return true if fields of xmp matches with fields of info dictionary
     */
    public static Boolean doesInfoMatchXMP(COSDocument document) {
        COSDictionary info = getInformationDictionary(document);
        if (info == null) {
            return Boolean.TRUE;
        }

        try {
            COSStream meta = getMetadataDictionary(document);
            if (meta != null) {
                DomXmpParser xmpParser = new DomXmpParser();
                XMPMetadata metadata = xmpParser.parse(meta.getUnfilteredStream());

                Map<String, Object> properties = new HashMap<>(8);

                getTitleAuthorSubject(metadata, properties);

                getProducerKeywords(metadata, properties);

                getCreatorAndDates(metadata, properties);

                return checkMatch(info, properties);
            }
        } catch (IOException e) {
            logger.error("Problems with document parsing or structure. " + e.getMessage());
        } catch (XmpParsingException e) {
            logger.error("Problems with XMP parsing. " + e.getMessage());
        }

        return Boolean.FALSE;
    }

    private static COSStream getMetadataDictionary(COSDocument document) throws IOException {
        final COSDictionary catalog = (COSDictionary) document.getCatalog().getObject();
        final COSObject metaObj = (COSObject) catalog.getItem(COSName.METADATA);
        if (metaObj != null && metaObj.getObject() instanceof COSStream) {
            return (COSStream) metaObj.getObject();
        } else {
            return null;
        }
    }

    private static COSDictionary getInformationDictionary(COSDocument document) {
        final COSObject info = (COSObject) document.getTrailer().getItem(COSName.INFO);
        if (info != null) {
            if (info.getObject() instanceof COSDictionary) {
                return (COSDictionary) info.getObject();
            } else if (info.getObject() instanceof COSObject) {
                return getInformationDictionary((COSObject) info.getObject());
            }
        }
        return null;
    }

    private static COSDictionary getInformationDictionary(COSObject object) {
        if (object.getObject() instanceof COSDictionary) {
            return (COSDictionary) object.getObject();
        } else if (object.getObject() instanceof COSObject) {
            return getInformationDictionary((COSObject) object.getObject());
        } else {
            return null;
        }
    }

    private static void getTitleAuthorSubject(XMPMetadata metadata, Map<String, Object> properties) {
        DublinCoreSchema dc = metadata.getDublinCoreSchema();
        if (dc != null && URLS.contains(dc.getNamespace())) {
            final List<String> buffer = dc.getCreators();
            putProperty(properties, TITLE, dc.getTitle());
            putProperty(properties, SUBJECT, dc.getDescription());
            putProperty(properties, AUTHOR, buffer.toArray(new String[buffer.size()]));
        }
    }

    private static void getProducerKeywords(XMPMetadata metadata, Map<String, Object> properties) {
        AdobePDFSchema pdf = metadata.getAdobePDFSchema();
        if (pdf != null && URLS.contains(pdf.getNamespace())) {
            putProperty(properties, KEYWORDS, pdf.getKeywords());
            putProperty(properties, PRODUCER, pdf.getProducer());
        }
    }

    private static void getCreatorAndDates(XMPMetadata metadata, Map<String, Object> properties) {
        XMPBasicSchema basic = metadata.getXMPBasicSchema();
        if (basic != null && URLS.contains(basic.getNamespace())) {
            putProperty(properties, CREATOR, basic.getCreatorTool());
            putProperty(properties, CREATION_DATE, basic.getCreateDate());
            putProperty(properties, MODIFICATION_DATE, basic.getModifyDate());
        }
    }

    private static void putProperty(Map<String, Object> properties, String key, String... values) {
        if (values != null) {
            StringBuilder builder = new StringBuilder();
            for (String value : values) {
                if (value != null && !value.isEmpty()) {
                    builder.append(value).append(" ");
                }
            }
            if (builder.length() > 1) {
                //need to discard last space
                properties.put(key, builder.substring(0, builder.length() - 1));
            }
        }
    }

    private static void putProperty(Map<String, Object> properties, String key, Calendar date) {
        if (date != null) {
            properties.put(key, date);
        }
    }

    private static Boolean checkMatch(COSDictionary info, Map<String, Object> properties) {
        if (!checkProperty(info, properties, TITLE)) return Boolean.FALSE;
        if (!checkProperty(info, properties, SUBJECT)) return Boolean.FALSE;
        if (!checkProperty(info, properties, AUTHOR)) return Boolean.FALSE;
        if (!checkProperty(info, properties, KEYWORDS)) return Boolean.FALSE;
        if (!checkProperty(info, properties, PRODUCER)) return Boolean.FALSE;
        if (!checkProperty(info, properties, CREATOR)) return Boolean.FALSE;
        if (!checkProperty(info, properties, CREATION_DATE)) return Boolean.FALSE;
        if (!checkProperty(info, properties, MODIFICATION_DATE)) return Boolean.FALSE;

        return Boolean.TRUE;
    }

{'fraction_non_alphanumeric': 0.11071024335031127, 'fraction_numerical': 0.0017685342388228636, 'mean_word_length': 2.7095250590396223, 'pattern_counts': {'":': 0, '<': 45, '<?xml version=': 0, '>': 55, 'https://': 0, 'lorem ipsum': 0, 'www.': 2, 'xml': 4}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '6722382', 'n_tokens_mistral': 3864, 'n_tokens_neox': 3751, 'n_words': 941}