You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@pdfbox.apache.org by le...@apache.org on 2012/06/29 12:25:39 UTC
svn commit: r1355309 [8/11] - in /pdfbox/trunk/preflight/src:
main/java/org/apache/pdfbox/ main/java/org/apache/pdfbox/preflight/
main/java/org/apache/pdfbox/preflight/action/
main/java/org/apache/pdfbox/preflight/annotation/
main/java/org/apache/pdfbo...
Added: pdfbox/trunk/preflight/src/main/java/org/apache/pdfbox/preflight/metadata/SynchronizedMetaDataValidation.java
URL: http://svn.apache.org/viewvc/pdfbox/trunk/preflight/src/main/java/org/apache/pdfbox/preflight/metadata/SynchronizedMetaDataValidation.java?rev=1355309&view=auto
==============================================================================
--- pdfbox/trunk/preflight/src/main/java/org/apache/pdfbox/preflight/metadata/SynchronizedMetaDataValidation.java (added)
+++ pdfbox/trunk/preflight/src/main/java/org/apache/pdfbox/preflight/metadata/SynchronizedMetaDataValidation.java Fri Jun 29 10:25:22 2012
@@ -0,0 +1,533 @@
+/*****************************************************************************
+ *
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ *
+ ****************************************************************************/
+
+package org.apache.pdfbox.preflight.metadata;
+
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.Calendar;
+import java.util.Iterator;
+import java.util.List;
+
+
+import org.apache.padaf.xmpbox.XMPMetadata;
+import org.apache.padaf.xmpbox.parser.DateConverter;
+import org.apache.padaf.xmpbox.schema.AdobePDFSchema;
+import org.apache.padaf.xmpbox.schema.DublinCoreSchema;
+import org.apache.padaf.xmpbox.schema.XMPBasicSchema;
+import org.apache.padaf.xmpbox.type.AbstractField;
+import org.apache.padaf.xmpbox.type.TextType;
+import org.apache.pdfbox.pdmodel.PDDocument;
+import org.apache.pdfbox.pdmodel.PDDocumentInformation;
+import org.apache.pdfbox.preflight.PreflightConstants;
+import org.apache.pdfbox.preflight.ValidationResult.ValidationError;
+import org.apache.pdfbox.preflight.exception.ValidationException;
+
+/**
+ * Class which check if document information available in a document are
+ * synchronized with XMP
+ *
+ * @author Germain Costenobel
+ *
+ */
+public class SynchronizedMetaDataValidation {
+
+ /**
+ * Analyze if Title embedded in Document Information dictionary and in XMP
+ * properties are synchronized
+ *
+ * @param dico
+ * Document Information Dictionary
+ * @param dc
+ * Dublin Core Schema
+ * @param ve
+ * The list of validation errors
+ */
+ protected void analyzeTitleProperty(PDDocumentInformation dico,
+ DublinCoreSchema dc, List<ValidationError> ve) {
+ String title = dico.getTitle();
+ if (title != null) {
+ if (dc != null) {
+ // Check the x-default value, if not found, check with the first value
+ // found
+ if (dc.getTitle() != null) {
+ if (dc.getTitleValue("x-default") != null) {
+ if (!dc.getTitleValue("x-default").equals(title)) {
+ ve.add(unsynchronizedMetaDataError("Title"));
+ }
+ } else {
+ // This search of first value is made just to keep compatibility
+ // with lot of PDF documents
+ // which use title without lang definition
+ // REM : MAY we have to delete this option in the future
+ Iterator<AbstractField> it = dc.getTitle().getContainer()
+ .getAllProperties().iterator();
+ if (it.hasNext()) {
+ AbstractField tmp = it.next();
+ if (tmp instanceof TextType) {
+ if (!((TextType) tmp).getStringValue().equals(title)) {
+ ve.add(unsynchronizedMetaDataError("Title"));
+ }
+ } else {
+ ve.add(AbsentXMPPropertyError("Title",
+ "Property is badly defined"));
+ }
+ } else {
+ ve
+ .add(AbsentXMPPropertyError("Title",
+ "Property is not defined"));
+ }
+ }
+
+ } else {
+ ve.add(AbsentXMPPropertyError("Title", "Property is not defined"));
+ }
+ } else {
+ ve.add(AbsentSchemaMetaDataError("Title", "Dublin Core"));
+ }
+ }
+ }
+
+ /**
+ * Analyze if Author(s) embedded in Document Information dictionary and in XMP
+ * properties are synchronized
+ *
+ * @param dico
+ * Document Information Dictionary
+ * @param dc
+ * Dublin Core Schema
+ * @param ve
+ * The list of validation errors
+ */
+ protected void analyzeAuthorProperty(PDDocumentInformation dico,
+ DublinCoreSchema dc, List<ValidationError> ve) {
+ String author = dico.getAuthor();
+ if (author != null) {
+ if (dc != null) {
+ if (dc.getCreator() != null) {
+ if (dc.getCreatorValue().size() != 1) {
+ ve
+ .add(AbsentXMPPropertyError(
+ "Author",
+ "In XMP metadata, Author(s) must be represented by a single entry in a text array (dc:creator) "));
+ } else {
+ if (dc.getCreatorValue().get(0) == null) {
+ ve.add(AbsentXMPPropertyError("Author",
+ "Property is defined as null"));
+ } else {
+ if (!dc.getCreatorValue().get(0).equals(author)) {
+ ve.add(unsynchronizedMetaDataError("Author"));
+ }
+ }
+ }
+ } else {
+ ve.add(AbsentXMPPropertyError("Author",
+ "Property is not defined in XMP Metadata"));
+ }
+ } else {
+ ve.add(AbsentSchemaMetaDataError("Author", "Dublin Core"));
+ }
+ }
+ }
+
+ /**
+ * Analyze if Subject(s) embedded in Document Information dictionary and in
+ * XMP properties are synchronized
+ *
+ * @param dico
+ * Document Information Dictionary
+ * @param dc
+ * Dublin Core Schema
+ * @param ve
+ * The list of validation errors
+ */
+ protected void analyzeSubjectProperty(PDDocumentInformation dico,
+ DublinCoreSchema dc, List<ValidationError> ve) {
+ String subject = dico.getSubject();
+ if (subject != null) {
+ if (dc != null) {
+ // PDF/A Conformance Erratum (2007) specifies XMP Subject
+ // as a Text type embedded in the dc:description["x-default"].
+ if (dc.getDescription() != null) {
+ if (dc.getDescriptionValue("x-default") == null) {
+ ve
+ .add(AbsentXMPPropertyError("Subject",
+ "Subject not found in XMP (dc:description[\"x-default\"] not found)"));
+ } else {
+ if (!dc.getDescriptionValue("x-default").equals(subject)) {
+ ve.add(unsynchronizedMetaDataError("Subject"));
+
+ }
+ }
+ } else {
+ ve.add(AbsentXMPPropertyError("Subject",
+ "Property is defined as null"));
+ }
+ } else {
+ ve.add(AbsentSchemaMetaDataError("Subject", "Dublin Core"));
+ }
+ }
+ }
+
+ /**
+ * Analyze if Keyword(s) embedded in Document Information dictionary and in
+ * XMP properties are synchronized
+ *
+ * @param dico
+ * Document Information Dictionary
+ * @param pdf
+ * PDF Schema
+ * @param ve
+ * The list of validation errors
+ */
+ protected void analyzeKeywordsProperty(PDDocumentInformation dico,
+ AdobePDFSchema pdf, List<ValidationError> ve) {
+ String keyword = dico.getKeywords();
+ if (keyword != null) {
+ if (pdf != null) {
+ if (pdf.getKeywords() == null) {
+ ve.add(AbsentXMPPropertyError("Keywords", "Property is not defined"));
+ } else {
+ if (!pdf.getKeywordsValue().equals(keyword)) {
+ ve.add(unsynchronizedMetaDataError("Keywords"));
+ }
+ }
+ } else {
+ ve.add(AbsentSchemaMetaDataError("Keywords", "PDF"));
+ }
+ }
+ }
+
+ /**
+ * Analyze if Producer embedded in Document Information dictionary and in XMP
+ * properties are synchronized
+ *
+ * @param dico
+ * Document Information Dictionary
+ * @param pdf
+ * PDF Schema
+ * @param ve
+ * The list of validation errors
+ */
+ protected void analyzeProducerProperty(PDDocumentInformation dico,
+ AdobePDFSchema pdf, List<ValidationError> ve) {
+ String producer = dico.getProducer();
+ if (producer != null) {
+ if (pdf != null) {
+ if (pdf.getProducer() == null) {
+ ve.add(AbsentXMPPropertyError("Producer", "Property is not defined"));
+ } else {
+ if (!pdf.getProducerValue().equals(producer)) {
+ ve.add(unsynchronizedMetaDataError("Producer"));
+ }
+ }
+ } else {
+ ve.add(AbsentSchemaMetaDataError("Producer", "PDF"));
+ }
+ }
+
+ }
+
+ /**
+ * Analyze if the creator tool embedded in Document Information dictionary and
+ * in XMP properties are synchronized
+ *
+ * @param dico
+ * Document Information Dictionary
+ * @param xmp
+ * XMP Basic Schema
+ * @param ve
+ * The list of validation errors
+ *
+ */
+ protected void analyzeCreatorToolProperty(PDDocumentInformation dico,
+ XMPBasicSchema xmp, List<ValidationError> ve) {
+ String creatorTool = dico.getCreator();
+ if (creatorTool != null) {
+ if (xmp != null) {
+ if (xmp.getCreatorTool() == null) {
+ ve.add(AbsentXMPPropertyError("CreatorTool",
+ "Property is not defined"));
+ } else {
+ if (!xmp.getCreatorToolValue().equals(creatorTool)) {
+ ve.add(unsynchronizedMetaDataError("CreatorTool"));
+ }
+ }
+ } else {
+ ve.add(AbsentSchemaMetaDataError("CreatorTool", "PDF"));
+ }
+ }
+
+ }
+
+ /**
+ * Analyze if the CreationDate embedded in Document Information dictionary and
+ * in XMP properties are synchronized
+ *
+ * @param dico
+ * Document Information Dictionary
+ * @param xmp
+ * XMP Basic Schema
+ * @param ve
+ * The list of validation errors
+ * @throws ValidationException
+ */
+ protected void analyzeCreationDateProperty(PDDocumentInformation dico,
+ XMPBasicSchema xmp, List<ValidationError> ve) throws ValidationException {
+ Calendar creationDate;
+ try {
+ creationDate = dico.getCreationDate();
+ } catch (IOException e) {
+ // If there is an error while converting this property to a date
+ throw formatAccessException("Document Information", "CreationDate", e);
+ }
+ if (creationDate != null) {
+ if (xmp != null) {
+ Calendar xmpCreationDate = xmp.getCreateDateValue();
+
+ if (xmpCreationDate == null) {
+ ve.add(AbsentXMPPropertyError("CreationDate",
+ "Property is not defined"));
+ } else {
+ if (!DateConverter.toISO8601(xmpCreationDate).equals(
+ DateConverter.toISO8601(creationDate))) {
+ ve.add(unsynchronizedMetaDataError("CreationDate"));
+ }
+ }
+
+ } else {
+ ve.add(AbsentSchemaMetaDataError("CreationDate", "Basic XMP"));
+ }
+ }
+ }
+
+ /**
+ * Analyze if the ModifyDate embedded in Document Information dictionary and
+ * in XMP properties are synchronized
+ *
+ * @param dico
+ * Document Information Dictionary
+ * @param xmp
+ * XMP Basic Schema
+ * @param ve
+ * The list of validation errors
+ * @throws ValidationException
+ */
+ protected void analyzeModifyDateProperty(PDDocumentInformation dico,
+ XMPBasicSchema xmp, List<ValidationError> ve) throws ValidationException {
+ Calendar modifyDate;
+ try {
+ modifyDate = dico.getModificationDate();
+ if (modifyDate != null) {
+ if (xmp != null) {
+
+ Calendar xmpModifyDate = xmp.getModifyDateValue();
+ if (xmpModifyDate == null) {
+ ve.add(AbsentXMPPropertyError("ModifyDate",
+ "Property is not defined"));
+ } else {
+ if (!DateConverter.toISO8601(xmpModifyDate).equals(
+ DateConverter.toISO8601(modifyDate))) {
+
+ ve.add(unsynchronizedMetaDataError("ModificationDate"));
+ }
+ }
+
+ } else {
+ ve.add(AbsentSchemaMetaDataError("ModifyDate", "Basic XMP"));
+ }
+ }
+ } catch (IOException e) {
+ // If there is an error while converting this property to a date
+ throw formatAccessException("Document Information", "ModifyDate", e);
+ }
+
+ }
+
+ /**
+ * Check if document information entries and XMP information are synchronized
+ *
+ * @param document
+ * the PDF Document
+ * @param metadata
+ * the XMP MetaData
+ * @return List of validation errors
+ * @throws ValidationException
+ */
+ public List<ValidationError> validateMetadataSynchronization(PDDocument document, XMPMetadata metadata)
+ throws ValidationException {
+ List<ValidationError> ve = new ArrayList<ValidationError>();
+
+ if (document == null) {
+ throw new ValidationException("Document provided is null");
+ } else {
+ PDDocumentInformation dico = document.getDocumentInformation();
+ if (metadata == null) {
+ throw new ValidationException("Metadata provided are null");
+ } else {
+ DublinCoreSchema dc = metadata.getDublinCoreSchema();
+
+ // TITLE
+ analyzeTitleProperty(dico, dc, ve);
+ // AUTHOR
+ analyzeAuthorProperty(dico, dc, ve);
+ // SUBJECT
+ analyzeSubjectProperty(dico, dc, ve);
+
+ AdobePDFSchema pdf = metadata.getAdobePDFSchema();
+
+ // KEYWORDS
+ analyzeKeywordsProperty(dico, pdf, ve);
+ // PRODUCER
+ analyzeProducerProperty(dico, pdf, ve);
+
+ XMPBasicSchema xmp = metadata.getXMPBasicSchema();
+
+ // CREATOR TOOL
+ analyzeCreatorToolProperty(dico, xmp, ve);
+
+ // CREATION DATE
+ analyzeCreationDateProperty(dico, xmp, ve);
+
+ // MODIFY DATE
+ analyzeModifyDateProperty(dico, xmp, ve);
+
+ }
+
+ }
+ return ve;
+ }
+
+ /**
+ * Return a validationError formatted when a schema has not the expected
+ * prefix
+ *
+ * @param prefFound
+ * @param prefExpected
+ * @param schema
+ * @return
+ */
+ protected ValidationError UnexpectedPrefixFoundError(String prefFound,
+ String prefExpected, String schema) {
+ StringBuilder sb = new StringBuilder(80);
+ sb.append(schema).append(" found but prefix used is '").append(prefFound)
+ .append("', prefix '").append(prefExpected).append("' is expected.");
+
+ return new ValidationError(
+ PreflightConstants.ERROR_METADATA_WRONG_NS_PREFIX, sb.toString());
+ }
+
+ /**
+ * Return an exception formatted on IOException when accessing metadata
+ *
+ * @param type
+ * type of property (Document Info or XMP)
+ * @param target
+ * the name of the metadata
+ * @param cause
+ * the raised IOException
+ * @return the generated exception
+ */
+ protected ValidationException formatAccessException(String type,
+ String target, Throwable cause) {
+ StringBuilder sb = new StringBuilder(80);
+ sb.append("Cannot treat ").append(type).append(" ").append(target).append(
+ " property");
+ return new ValidationException(sb.toString(), cause);
+ }
+
+ /**
+ * Return an exception formatted on IOException when accessing on metadata
+ * schema
+ *
+ * @param target
+ * the name of the schema
+ * @param cause
+ * the raised IOException
+ * @return the generated exception
+ */
+ protected ValidationException SchemaAccessException(String target,
+ Throwable cause) {
+ StringBuilder sb = new StringBuilder(80);
+ sb.append("Cannot access to the ").append(target).append(" schema");
+ return new ValidationException(sb.toString(), cause);
+ }
+
+ /**
+ * Return a formatted validation error when metadata are not synchronized
+ *
+ * @param target
+ * the concerned property
+ * @return the generated validation error
+ */
+ protected ValidationError unsynchronizedMetaDataError(String target) {
+ StringBuilder sb = new StringBuilder(80);
+ sb
+ .append(target)
+ .append(
+ " present in the document catalog dictionary doesn't match with XMP information");
+ return new ValidationError(PreflightConstants.ERROR_METADATA_MISMATCH, sb
+ .toString());
+ }
+
+ /**
+ * Return a formatted validation error when a specific metadata schema can't
+ * be found
+ *
+ * @param target
+ * the concerned property
+ * @param schema
+ * the XMP schema which can't be found
+ * @return the generated validation error
+ */
+ protected ValidationError AbsentSchemaMetaDataError(String target,
+ String schema) {
+ StringBuilder sb = new StringBuilder(80);
+ sb
+ .append(target)
+ .append(
+ " present in the document catalog dictionary can't be found in XMP information (")
+ .append(schema).append(" schema not declared)");
+ return new ValidationError(PreflightConstants.ERROR_METADATA_MISMATCH, sb
+ .toString());
+ }
+
+ /**
+ * Return a formatted validation error when a specific XMP property can't be
+ * found
+ *
+ * @param target
+ * the concerned property
+ * @param details
+ * comments about the XMP property
+ * @return the generated validation error
+ */
+ protected ValidationError AbsentXMPPropertyError(String target, String details) {
+ StringBuilder sb = new StringBuilder(80);
+ sb
+ .append(target)
+ .append(
+ " present in the document catalog dictionary can't be found in XMP information (")
+ .append(details).append(")");
+ return new ValidationError(PreflightConstants.ERROR_METADATA_MISMATCH, sb
+ .toString());
+ }
+}
Propchange: pdfbox/trunk/preflight/src/main/java/org/apache/pdfbox/preflight/metadata/SynchronizedMetaDataValidation.java
------------------------------------------------------------------------------
svn:eol-style = native
Added: pdfbox/trunk/preflight/src/main/java/org/apache/pdfbox/preflight/metadata/XpacketParsingException.java
URL: http://svn.apache.org/viewvc/pdfbox/trunk/preflight/src/main/java/org/apache/pdfbox/preflight/metadata/XpacketParsingException.java?rev=1355309&view=auto
==============================================================================
--- pdfbox/trunk/preflight/src/main/java/org/apache/pdfbox/preflight/metadata/XpacketParsingException.java (added)
+++ pdfbox/trunk/preflight/src/main/java/org/apache/pdfbox/preflight/metadata/XpacketParsingException.java Fri Jun 29 10:25:22 2012
@@ -0,0 +1,70 @@
+/*****************************************************************************
+ *
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ *
+ ****************************************************************************/
+
+package org.apache.pdfbox.preflight.metadata;
+
+import org.apache.pdfbox.preflight.ValidationResult.ValidationError;
+
+/**
+ * This exception is raised when the parsing of the xpacket fails
+ *
+ */
+public class XpacketParsingException extends Exception {
+
+ /**
+ *
+ */
+ private static final long serialVersionUID = 1L;
+
+ protected ValidationError error;
+
+ /**
+ * Constructor
+ *
+ * @param message
+ * the message
+ * @param cause
+ * the cause
+ */
+ public XpacketParsingException(String message, Throwable cause) {
+ super(message, cause);
+ }
+
+ /**
+ * Constructor
+ *
+ * @param message
+ * the message
+ */
+ public XpacketParsingException(String message) {
+ super(message);
+ }
+
+ public XpacketParsingException(String message, ValidationError error) {
+ super(message);
+ this.error = error;
+ }
+
+ public ValidationError getError() {
+ return error;
+ }
+
+}
Propchange: pdfbox/trunk/preflight/src/main/java/org/apache/pdfbox/preflight/metadata/XpacketParsingException.java
------------------------------------------------------------------------------
svn:eol-style = native
Added: pdfbox/trunk/preflight/src/main/java/org/apache/pdfbox/preflight/parser/PreflightParser.java
URL: http://svn.apache.org/viewvc/pdfbox/trunk/preflight/src/main/java/org/apache/pdfbox/preflight/parser/PreflightParser.java?rev=1355309&view=auto
==============================================================================
--- pdfbox/trunk/preflight/src/main/java/org/apache/pdfbox/preflight/parser/PreflightParser.java (added)
+++ pdfbox/trunk/preflight/src/main/java/org/apache/pdfbox/preflight/parser/PreflightParser.java Fri Jun 29 10:25:22 2012
@@ -0,0 +1,205 @@
+/*****************************************************************************
+ *
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ *
+ ****************************************************************************/
+
+package org.apache.pdfbox.preflight.parser;
+
+import java.io.IOException;
+import java.io.InputStreamReader;
+import java.nio.charset.Charset;
+import java.util.List;
+
+import javax.activation.DataSource;
+
+import org.apache.pdfbox.io.IOUtils;
+import org.apache.pdfbox.io.RandomAccess;
+import org.apache.pdfbox.pdfparser.PDFParser;
+import org.apache.pdfbox.pdmodel.PDDocument;
+import org.apache.pdfbox.preflight.Format;
+import org.apache.pdfbox.preflight.PreflightConfiguration;
+import org.apache.pdfbox.preflight.PreflightConstants;
+import org.apache.pdfbox.preflight.PreflightContext;
+import org.apache.pdfbox.preflight.PreflightDocument;
+import org.apache.pdfbox.preflight.ValidationResult;
+import org.apache.pdfbox.preflight.ValidationResult.ValidationError;
+import org.apache.pdfbox.preflight.exception.PdfParseException;
+import org.apache.pdfbox.preflight.exception.ValidationException;
+import org.apache.pdfbox.preflight.javacc.ParseException;
+import org.apache.pdfbox.preflight.javacc.extractor.ExtractorTokenManager;
+import org.apache.pdfbox.preflight.javacc.extractor.SimpleCharStream;
+
+public class PreflightParser extends PDFParser {
+ /**
+ * Define a one byte encoding that hasn't specific encoding in UTF-8 charset.
+ * Avoid unexpected error when the encoding is Cp5816
+ */
+ public static final Charset encoding = Charset.forName("ISO-8859-1");
+
+ protected DataSource originalDocument;
+
+ protected ValidationResult validationResult;
+
+ protected PreflightDocument document;
+
+ protected PreflightContext ctx;
+
+ public PreflightParser(DataSource input, RandomAccess rafi, boolean force) throws IOException {
+ super(input.getInputStream(), rafi, force);
+ this.originalDocument = input;
+ }
+
+ public PreflightParser(DataSource input, RandomAccess rafi) throws IOException {
+ super(input.getInputStream(), rafi);
+ this.originalDocument = input;
+ }
+
+ public PreflightParser(DataSource input) throws IOException {
+ super(input.getInputStream());
+ this.originalDocument = input;
+ }
+
+
+ /**
+ * Create an instance of ValidationResult. This object contains an instance of
+ * ValidationError. If the ParseException is an instance of PdfParseException,
+ * the embedded validation error is initialized with the error code of the
+ * exception, otherwise it is an UnknownError.
+ *
+ * @param e
+ * @return
+ */
+ protected static ValidationResult createErrorResult(ParseException e) {
+ if (e instanceof PdfParseException) {
+ if (e.getCause()==null) {
+ return new ValidationResult(new ValidationError(((PdfParseException)e).getErrorCode()));
+ } else if (e.getCause().getMessage()==null) {
+ return new ValidationResult(new ValidationError(((PdfParseException)e).getErrorCode()));
+ } else {
+ return new ValidationResult(new ValidationError(((PdfParseException)e).getErrorCode(),e.getCause().getMessage()));
+ }
+ }
+ return createUnknownErrorResult();
+ }
+
+ /**
+ * Create an instance of ValidationResult with a
+ * ValidationError(UNKNOWN_ERROR)
+ *
+ * @return
+ */
+ protected static ValidationResult createUnknownErrorResult() {
+ ValidationError error = new ValidationError(PreflightConstants.ERROR_UNKOWN_ERROR);
+ ValidationResult result = new ValidationResult(error);
+ return result;
+ }
+
+ /**
+ * Add the error to the ValidationResult.
+ * If the validationResult is null, an instance is created using the isWarning boolean of the
+ * ValidationError to know if the ValidationResult must be flagged as Valid.
+ * @param error
+ */
+ protected void addValidationError(ValidationError error) {
+ if (this.validationResult == null) {
+ this.validationResult = new ValidationResult(error.isWarning());
+ }
+ this.validationResult.addError(error);
+ }
+ protected void addValidationErrors(List<ValidationError> errors) {
+ for (ValidationError error : errors) {
+ addValidationError(error);
+ }
+ }
+
+
+ public void parse() throws IOException {
+ parse(Format.PDF_A1B);
+ }
+
+ /**
+ * Parse the given file and check if it is a confirming file according to the given format.
+ *
+ * @param format format that the document should follow (default {@link Format#PDF_A1B})
+ * @throws IOException
+ */
+ public void parse(Format format) throws IOException {
+ parse(format, null);
+ }
+
+ /**
+ * Parse the given file and check if it is a confirming file according to the given format.
+ *
+ * @param format format that the document should follow (default {@link Format#PDF_A1B})
+ * @param config Configuration bean that will be used by the PreflightDocument.
+ * If null the format is used to determine the default configuration.
+ * @throws IOException
+ */
+ public void parse(Format format, PreflightConfiguration config) throws IOException {
+ checkFileSyntax();
+ // run PDFBox Parser
+ super.parse();
+ Format formatToUse = (format == null ? Format.PDF_A1B : format);
+ createPdfADocument(formatToUse, config);
+ createContext();
+ extractTrailers();
+ }
+
+ /**
+ * Run the JavaCC parser to check the PDF syntax.
+ * @throws ValidationException
+ */
+ protected void checkFileSyntax() throws ValidationException {
+ // syntax (javacc) validation
+ try {
+ InputStreamReader reader = new InputStreamReader(this.originalDocument.getInputStream(), encoding);
+ org.apache.pdfbox.preflight.javacc.PDFParser javaCCParser = new org.apache.pdfbox.preflight.javacc.PDFParser(reader);
+ javaCCParser.PDF();
+ IOUtils.closeQuietly(reader);
+ } catch (IOException e) {
+ throw new ValidationException("Failed to parse datasource due to : " + e.getMessage(), e);
+ } catch (ParseException e) {
+ this.validationResult = createErrorResult(e);
+ }
+ }
+
+ protected void createPdfADocument(Format format, PreflightConfiguration config) throws IOException {
+ this.document = new PreflightDocument(getDocument(), format, config);
+ }
+
+ protected void createContext() {
+ this.ctx = new PreflightContext(this.originalDocument);
+ ctx.setDocument(document);
+ document.setContext(ctx);
+ }
+
+ protected void extractTrailers() throws IOException {
+ SimpleCharStream scs = new SimpleCharStream(this.originalDocument.getInputStream());
+ ExtractorTokenManager extractor = new ExtractorTokenManager(scs);
+ extractor.parse();
+ ctx.setPdfExtractor(extractor);
+ }
+
+ @Override
+ public PDDocument getPDDocument() throws IOException {
+ document.setResult(validationResult);
+ // Add XMP MetaData
+ return document;
+ }
+}
\ No newline at end of file
Propchange: pdfbox/trunk/preflight/src/main/java/org/apache/pdfbox/preflight/parser/PreflightParser.java
------------------------------------------------------------------------------
svn:eol-style = native
Added: pdfbox/trunk/preflight/src/main/java/org/apache/pdfbox/preflight/process/AbstractProcess.java
URL: http://svn.apache.org/viewvc/pdfbox/trunk/preflight/src/main/java/org/apache/pdfbox/preflight/process/AbstractProcess.java?rev=1355309&view=auto
==============================================================================
--- pdfbox/trunk/preflight/src/main/java/org/apache/pdfbox/preflight/process/AbstractProcess.java (added)
+++ pdfbox/trunk/preflight/src/main/java/org/apache/pdfbox/preflight/process/AbstractProcess.java Fri Jun 29 10:25:22 2012
@@ -0,0 +1,40 @@
+/*****************************************************************************
+ *
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ *
+ ****************************************************************************/
+
+package org.apache.pdfbox.preflight.process;
+
+import java.util.List;
+
+import org.apache.pdfbox.preflight.PreflightContext;
+import org.apache.pdfbox.preflight.ValidationResult.ValidationError;
+
+public abstract class AbstractProcess implements ValidationProcess {
+
+ protected void addValidationError(PreflightContext ctx, ValidationError error) {
+ ctx.addValidationError(error);
+ }
+
+ protected void addValidationErrors(PreflightContext ctx, List<ValidationError> errors) {
+ for (ValidationError error : errors) {
+ addValidationError(ctx, error);
+ }
+ }
+}
Propchange: pdfbox/trunk/preflight/src/main/java/org/apache/pdfbox/preflight/process/AbstractProcess.java
------------------------------------------------------------------------------
svn:eol-style = native
Added: pdfbox/trunk/preflight/src/main/java/org/apache/pdfbox/preflight/process/AcroFormValidationProcess.java
URL: http://svn.apache.org/viewvc/pdfbox/trunk/preflight/src/main/java/org/apache/pdfbox/preflight/process/AcroFormValidationProcess.java?rev=1355309&view=auto
==============================================================================
--- pdfbox/trunk/preflight/src/main/java/org/apache/pdfbox/preflight/process/AcroFormValidationProcess.java (added)
+++ pdfbox/trunk/preflight/src/main/java/org/apache/pdfbox/preflight/process/AcroFormValidationProcess.java Fri Jun 29 10:25:22 2012
@@ -0,0 +1,143 @@
+/*****************************************************************************
+ *
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ *
+ ****************************************************************************/
+
+package org.apache.pdfbox.preflight.process;
+
+import static org.apache.pdfbox.preflight.PreflightConfiguration.ANNOTATIONS_PROCESS;
+import static org.apache.pdfbox.preflight.PreflightConstants.ACROFORM_DICTIONARY_KEY_NEED_APPEARANCES;
+import static org.apache.pdfbox.preflight.PreflightConstants.ERROR_ACTION_FORBIDDEN_ADDITIONAL_ACTIONS_FIELD;
+import static org.apache.pdfbox.preflight.PreflightConstants.ERROR_ACTION_FORBIDDEN_WIDGET_ACTION_FIELD;
+import static org.apache.pdfbox.preflight.PreflightConstants.ERROR_SYNTAX_DICT_INVALID;
+
+import java.io.IOException;
+import java.util.List;
+
+import org.apache.pdfbox.cos.COSBase;
+import org.apache.pdfbox.cos.COSName;
+import org.apache.pdfbox.pdmodel.PDDocumentCatalog;
+import org.apache.pdfbox.pdmodel.interactive.action.PDFormFieldAdditionalActions;
+import org.apache.pdfbox.pdmodel.interactive.annotation.PDAnnotationWidget;
+import org.apache.pdfbox.pdmodel.interactive.form.PDAcroForm;
+import org.apache.pdfbox.pdmodel.interactive.form.PDField;
+import org.apache.pdfbox.preflight.PreflightContext;
+import org.apache.pdfbox.preflight.ValidationResult.ValidationError;
+import org.apache.pdfbox.preflight.exception.ValidationException;
+import org.apache.pdfbox.preflight.utils.ContextHelper;
+
+public class AcroFormValidationProcess extends AbstractProcess {
+
+ public void validate(PreflightContext ctx) throws ValidationException {
+ PDDocumentCatalog catalog = ctx.getDocument().getDocumentCatalog();
+ if (catalog != null) {
+ PDAcroForm acroForm = catalog.getAcroForm();
+ if (acroForm != null) {
+ checkNeedAppearences(ctx, acroForm);
+ try {
+ exploreFields(ctx, acroForm.getFields());
+ } catch (IOException e) {
+ throw new ValidationException("Unable to get the list of fields : " + e.getMessage(), e);
+ }
+ }
+ } else {
+ throw new ValidationException("There are no Catalog entry in the Document.");
+ }
+ }
+
+ /**
+ * This method checks if the NeedAppearances entry is present. If it is, the
+ * value must be false.
+ *
+ * If the entry is invalid, the ERROR_SYNTAX_DICT_INVALID (1.2.3) error is
+ * return.
+ *
+ * @param ctx
+ * @param acroForm
+ * @param result
+ */
+ protected void checkNeedAppearences(PreflightContext ctx, PDAcroForm acroForm) {
+ if (acroForm.getDictionary().getBoolean(ACROFORM_DICTIONARY_KEY_NEED_APPEARANCES, false)) {
+ addValidationError(ctx, new ValidationError(ERROR_SYNTAX_DICT_INVALID, "NeedAppearance is present with the value \"true\""));
+ }
+ }
+
+ /**
+ * This function explores all fields and their children to check if the A or
+ * AA entry is present.
+ *
+ * @param ctx
+ * @param acroForm
+ * @param result
+ * @throws IOException
+ */
+ protected boolean exploreFields(PreflightContext ctx, List<?> lFields)
+ throws IOException {
+ if (lFields != null) { // the list can be null is the Field doesn't have child
+ for (Object obj : lFields) {
+ if (!valideField(ctx, (PDField) obj)) {
+ return false;
+ }
+ }
+ }
+ return true;
+ }
+
+ /**
+ * A and AA field are forbidden, this method checks if they are present and
+ * checks all child of this field. If the an Additional Action is present the
+ * error code ERROR_ACTION_FORBIDDEN_ADDITIONAL_ACTIONS_FIELD (6.2.3) is added
+ * to the error list If the an Action is present (in the Widget Annotation)
+ * the error ERROR_ACTION_FORBIDDEN_WIDGET_ACTION_FIELD (6.2.4) is added to
+ * the error list. (Remark : The widget validation will be done by the
+ * AnnotationValidationHelper, but some actions are authorized in a standard
+ * Widget)
+ *
+ * @param ctx
+ * @param aField
+ * @return
+ * @throws IOException
+ */
+ protected boolean valideField(PreflightContext ctx, PDField aField) throws IOException {
+ boolean res = true;
+ PDFormFieldAdditionalActions aa = aField.getActions();
+ if (aa != null) {
+ addValidationError(ctx, new ValidationError(ERROR_ACTION_FORBIDDEN_ADDITIONAL_ACTIONS_FIELD, "\"AA\" must not be used in a Field dictionary"));
+ res = false;
+ }
+
+ /*
+ * The widget validation will be done by the widget annotation,
+ * a widget contained in a Field can't have action.
+ */
+ PDAnnotationWidget widget = aField.getWidget();
+ if (res && widget != null) {
+ ContextHelper.validateElement(ctx, widget.getDictionary(), ANNOTATIONS_PROCESS);
+ COSBase act = widget.getDictionary().getDictionaryObject(COSName.A);
+ if (act != null) {
+ addValidationError(ctx, new ValidationError(ERROR_ACTION_FORBIDDEN_WIDGET_ACTION_FIELD, "\"A\" must not be used in a Field dictionary"));
+ res = false;
+ }
+ }
+
+ res = res && exploreFields(ctx, aField.getKids());
+ return res;
+ }
+
+}
Propchange: pdfbox/trunk/preflight/src/main/java/org/apache/pdfbox/preflight/process/AcroFormValidationProcess.java
------------------------------------------------------------------------------
svn:eol-style = native
Added: pdfbox/trunk/preflight/src/main/java/org/apache/pdfbox/preflight/process/BookmarkValidationProcess.java
URL: http://svn.apache.org/viewvc/pdfbox/trunk/preflight/src/main/java/org/apache/pdfbox/preflight/process/BookmarkValidationProcess.java?rev=1355309&view=auto
==============================================================================
--- pdfbox/trunk/preflight/src/main/java/org/apache/pdfbox/preflight/process/BookmarkValidationProcess.java (added)
+++ pdfbox/trunk/preflight/src/main/java/org/apache/pdfbox/preflight/process/BookmarkValidationProcess.java Fri Jun 29 10:25:22 2012
@@ -0,0 +1,157 @@
+/*****************************************************************************
+ *
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ *
+ ****************************************************************************/
+
+package org.apache.pdfbox.preflight.process;
+
+import static org.apache.pdfbox.preflight.PreflightConfiguration.ACTIONS_PROCESS;
+import static org.apache.pdfbox.preflight.PreflightConstants.ERROR_SYNTAX_TRAILER_OUTLINES_INVALID;
+
+import org.apache.pdfbox.cos.COSBase;
+import org.apache.pdfbox.cos.COSDictionary;
+import org.apache.pdfbox.cos.COSDocument;
+import org.apache.pdfbox.cos.COSName;
+import org.apache.pdfbox.pdmodel.PDDocumentCatalog;
+import org.apache.pdfbox.pdmodel.interactive.documentnavigation.outline.PDDocumentOutline;
+import org.apache.pdfbox.pdmodel.interactive.documentnavigation.outline.PDOutlineItem;
+import org.apache.pdfbox.preflight.PreflightContext;
+import org.apache.pdfbox.preflight.ValidationResult.ValidationError;
+import org.apache.pdfbox.preflight.exception.ValidationException;
+import org.apache.pdfbox.preflight.utils.COSUtils;
+import org.apache.pdfbox.preflight.utils.ContextHelper;
+
+public class BookmarkValidationProcess extends AbstractProcess {
+
+ public void validate(PreflightContext ctx) throws ValidationException {
+ PDDocumentCatalog catalog = ctx.getDocument().getDocumentCatalog();
+ if (catalog != null) {
+ PDDocumentOutline outlineHierarchy = catalog.getDocumentOutline();
+ if (outlineHierarchy != null) {
+ // Count entry is mandatory if there are childrens
+ if (!isCountEntryPresent(outlineHierarchy.getCOSDictionary()) && (outlineHierarchy.getFirstChild() != null || outlineHierarchy.getLastChild() != null) ) {
+ addValidationError(ctx, new ValidationError(
+ ERROR_SYNTAX_TRAILER_OUTLINES_INVALID,
+ "Outline Hierarchy doesn't have Count entry"));
+ } else if ( isCountEntryPositive(ctx, outlineHierarchy.getCOSDictionary())
+ && (outlineHierarchy.getFirstChild() == null || outlineHierarchy.getLastChild() == null)) {
+ addValidationError(ctx, new ValidationError(ERROR_SYNTAX_TRAILER_OUTLINES_INVALID,
+ "Outline Hierarchy doesn't have First and/or Last entry(ies)"));
+ } else {
+ exploreOutlineLevel(ctx, outlineHierarchy.getFirstChild());
+ }
+ }
+ } else {
+ throw new ValidationException("There are no Catalog entry in the Document.");
+ }
+ }
+
+ /**
+ * Return true if the Count entry is present in the given dictionary.
+ *
+ * @param outline
+ * @return
+ */
+ private boolean isCountEntryPresent(COSDictionary outline) {
+ return outline.getItem(COSName.getPDFName("Count")) != null;
+ }
+ /**
+ * return true if Count entry > 0
+ * @param outline
+ * @param doc
+ * @return
+ */
+ private boolean isCountEntryPositive(PreflightContext ctx, COSDictionary outline) {
+ COSBase countBase = outline.getItem(COSName.getPDFName("Count"));
+ COSDocument cosDocument = ctx.getDocument().getDocument();
+ return COSUtils.isInteger(countBase, cosDocument) && (COSUtils.getAsInteger(countBase, cosDocument)>0);
+ }
+ /**
+ * This method explores the Outline Item Level and call a validation method on
+ * each Outline Item. If an invalid outline item is found, the result list is
+ * updated.
+ *
+ * @param inputItem
+ * The first outline item of the level
+ * @param ctx
+ * The document handler which provides useful data for the level
+ * exploration (ex : access to the PDDocument)
+ * @return true if all items are valid in this level.
+ * @throws ValidationException
+ */
+ protected boolean exploreOutlineLevel(PreflightContext ctx, PDOutlineItem inputItem)
+ throws ValidationException {
+ PDOutlineItem currentItem = inputItem;
+ while (currentItem != null) {
+ if (!validateItem(ctx, currentItem)) {
+ return false;
+ }
+ currentItem = currentItem.getNextSibling();
+ }
+ return true;
+ }
+
+ /**
+ * This method checks the inputItem dictionary and call the
+ * exploreOutlineLevel method on the first child if it is not null.
+ *
+ * @param inputItem
+ * outline item to validate
+ * @param ctx
+ * The document handler which provides useful data for the level
+ * exploration (ex : access to the PDDocument)
+ * @param result
+ * @return
+ * @throws ValidationException
+ */
+ protected boolean validateItem(PreflightContext ctx, PDOutlineItem inputItem)
+ throws ValidationException {
+ boolean isValid = true;
+ // Dest entry isn't permitted if the A entry is present
+ // A entry isn't permitted if the Dest entry is present
+ // If the A enntry is present, the referenced actions is validated
+ COSDictionary dictionary = inputItem.getCOSDictionary();
+ COSBase dest = dictionary.getItem(COSName.DEST);
+ COSBase action = dictionary.getItem(COSName.A);
+
+ if (action != null && dest != null) {
+ addValidationError(ctx, new ValidationError(ERROR_SYNTAX_TRAILER_OUTLINES_INVALID,
+ "Dest entry isn't permitted if the A entry is present"));
+ return false;
+ } else if (action != null) {
+ ContextHelper.validateElement(ctx, dictionary, ACTIONS_PROCESS);
+ } // else no specific validation
+
+ // check children
+ PDOutlineItem fChild = inputItem.getFirstChild();
+ if (fChild != null) {
+ if (!isCountEntryPresent(inputItem.getCOSDictionary())) {
+ addValidationError(ctx, new ValidationError(ERROR_SYNTAX_TRAILER_OUTLINES_INVALID,
+ "Outline item doesn't have Count entry but has at least one descendant."));
+ isValid = false;
+ } else {
+ // there are some descendants, so dictionary must have a Count entry
+ isValid = isValid && exploreOutlineLevel(ctx, fChild);
+ }
+ }
+
+ return isValid;
+ }
+
+}
Propchange: pdfbox/trunk/preflight/src/main/java/org/apache/pdfbox/preflight/process/BookmarkValidationProcess.java
------------------------------------------------------------------------------
svn:eol-style = native
Added: pdfbox/trunk/preflight/src/main/java/org/apache/pdfbox/preflight/process/CatalogValidationProcess.java
URL: http://svn.apache.org/viewvc/pdfbox/trunk/preflight/src/main/java/org/apache/pdfbox/preflight/process/CatalogValidationProcess.java?rev=1355309&view=auto
==============================================================================
--- pdfbox/trunk/preflight/src/main/java/org/apache/pdfbox/preflight/process/CatalogValidationProcess.java (added)
+++ pdfbox/trunk/preflight/src/main/java/org/apache/pdfbox/preflight/process/CatalogValidationProcess.java Fri Jun 29 10:25:22 2012
@@ -0,0 +1,426 @@
+/*****************************************************************************
+ *
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ *
+ ****************************************************************************/
+
+package org.apache.pdfbox.preflight.process;
+
+import static org.apache.pdfbox.preflight.PreflightConfiguration.ACTIONS_PROCESS;
+import static org.apache.pdfbox.preflight.PreflightConstants.DICTIONARY_KEY_ADDITIONAL_ACTION;
+import static org.apache.pdfbox.preflight.PreflightConstants.DOCUMENT_DICTIONARY_KEY_OUTPUT_INTENTS;
+import static org.apache.pdfbox.preflight.PreflightConstants.ERROR_ACTION_FORBIDDEN_ADDITIONAL_ACTION;
+import static org.apache.pdfbox.preflight.PreflightConstants.ERROR_GRAPHIC_OUTPUT_INTENT_ICC_PROFILE_INVALID;
+import static org.apache.pdfbox.preflight.PreflightConstants.ERROR_GRAPHIC_OUTPUT_INTENT_ICC_PROFILE_MULTIPLE;
+import static org.apache.pdfbox.preflight.PreflightConstants.ERROR_GRAPHIC_OUTPUT_INTENT_ICC_PROFILE_TOO_RECENT;
+import static org.apache.pdfbox.preflight.PreflightConstants.ERROR_GRAPHIC_OUTPUT_INTENT_INVALID_ENTRY;
+import static org.apache.pdfbox.preflight.PreflightConstants.ERROR_GRAPHIC_OUTPUT_INTENT_S_VALUE_INVALID;
+import static org.apache.pdfbox.preflight.PreflightConstants.ERROR_SYNTAX_LANG_NOT_RFC1766;
+import static org.apache.pdfbox.preflight.PreflightConstants.ERROR_SYNTAX_NOCATALOG;
+import static org.apache.pdfbox.preflight.PreflightConstants.ERROR_SYNTAX_TRAILER_CATALOG_EMBEDDEDFILES;
+import static org.apache.pdfbox.preflight.PreflightConstants.ERROR_SYNTAX_TRAILER_CATALOG_OCPROPERTIES;
+import static org.apache.pdfbox.preflight.PreflightConstants.ICC_Characterization_Data_Registry_Adobe;
+import static org.apache.pdfbox.preflight.PreflightConstants.ICC_Characterization_Data_Registry_CGATS_TR001;
+import static org.apache.pdfbox.preflight.PreflightConstants.ICC_Characterization_Data_Registry_CGATS_TR002;
+import static org.apache.pdfbox.preflight.PreflightConstants.ICC_Characterization_Data_Registry_CGATS_TR003;
+import static org.apache.pdfbox.preflight.PreflightConstants.ICC_Characterization_Data_Registry_CGATS_TR005;
+import static org.apache.pdfbox.preflight.PreflightConstants.ICC_Characterization_Data_Registry_CGATS_TR006;
+import static org.apache.pdfbox.preflight.PreflightConstants.ICC_Characterization_Data_Registry_CGATS_TR_001;
+import static org.apache.pdfbox.preflight.PreflightConstants.ICC_Characterization_Data_Registry_CGATS_TR_002;
+import static org.apache.pdfbox.preflight.PreflightConstants.ICC_Characterization_Data_Registry_CGATS_TR_003;
+import static org.apache.pdfbox.preflight.PreflightConstants.ICC_Characterization_Data_Registry_CGATS_TR_005;
+import static org.apache.pdfbox.preflight.PreflightConstants.ICC_Characterization_Data_Registry_CGATS_TR_006;
+import static org.apache.pdfbox.preflight.PreflightConstants.ICC_Characterization_Data_Registry_ERIMM;
+import static org.apache.pdfbox.preflight.PreflightConstants.ICC_Characterization_Data_Registry_EUROSB104;
+import static org.apache.pdfbox.preflight.PreflightConstants.ICC_Characterization_Data_Registry_EUROSB204;
+import static org.apache.pdfbox.preflight.PreflightConstants.ICC_Characterization_Data_Registry_FOGRA27;
+import static org.apache.pdfbox.preflight.PreflightConstants.ICC_Characterization_Data_Registry_FOGRA28;
+import static org.apache.pdfbox.preflight.PreflightConstants.ICC_Characterization_Data_Registry_FOGRA29;
+import static org.apache.pdfbox.preflight.PreflightConstants.ICC_Characterization_Data_Registry_FOGRA30;
+import static org.apache.pdfbox.preflight.PreflightConstants.ICC_Characterization_Data_Registry_FOGRA31;
+import static org.apache.pdfbox.preflight.PreflightConstants.ICC_Characterization_Data_Registry_FOGRA32;
+import static org.apache.pdfbox.preflight.PreflightConstants.ICC_Characterization_Data_Registry_FOGRA33;
+import static org.apache.pdfbox.preflight.PreflightConstants.ICC_Characterization_Data_Registry_FOGRA34;
+import static org.apache.pdfbox.preflight.PreflightConstants.ICC_Characterization_Data_Registry_FOGRA35;
+import static org.apache.pdfbox.preflight.PreflightConstants.ICC_Characterization_Data_Registry_FOGRA36;
+import static org.apache.pdfbox.preflight.PreflightConstants.ICC_Characterization_Data_Registry_FOGRA37;
+import static org.apache.pdfbox.preflight.PreflightConstants.ICC_Characterization_Data_Registry_FOGRA38;
+import static org.apache.pdfbox.preflight.PreflightConstants.ICC_Characterization_Data_Registry_FOGRA39;
+import static org.apache.pdfbox.preflight.PreflightConstants.ICC_Characterization_Data_Registry_FOGRA40;
+import static org.apache.pdfbox.preflight.PreflightConstants.ICC_Characterization_Data_Registry_FOGRA41;
+import static org.apache.pdfbox.preflight.PreflightConstants.ICC_Characterization_Data_Registry_FOGRA42;
+import static org.apache.pdfbox.preflight.PreflightConstants.ICC_Characterization_Data_Registry_FOGRA43;
+import static org.apache.pdfbox.preflight.PreflightConstants.ICC_Characterization_Data_Registry_FOGRA44;
+import static org.apache.pdfbox.preflight.PreflightConstants.ICC_Characterization_Data_Registry_FOGRA45;
+import static org.apache.pdfbox.preflight.PreflightConstants.ICC_Characterization_Data_Registry_FOGRA46;
+import static org.apache.pdfbox.preflight.PreflightConstants.ICC_Characterization_Data_Registry_FOGRA47;
+import static org.apache.pdfbox.preflight.PreflightConstants.ICC_Characterization_Data_Registry_IFRA26;
+import static org.apache.pdfbox.preflight.PreflightConstants.ICC_Characterization_Data_Registry_JC200103;
+import static org.apache.pdfbox.preflight.PreflightConstants.ICC_Characterization_Data_Registry_JC200104;
+import static org.apache.pdfbox.preflight.PreflightConstants.ICC_Characterization_Data_Registry_JCN2002;
+import static org.apache.pdfbox.preflight.PreflightConstants.ICC_Characterization_Data_Registry_JCW2003;
+import static org.apache.pdfbox.preflight.PreflightConstants.ICC_Characterization_Data_Registry_RIMM;
+import static org.apache.pdfbox.preflight.PreflightConstants.ICC_Characterization_Data_Registry_ROMM;
+import static org.apache.pdfbox.preflight.PreflightConstants.ICC_Characterization_Data_Registry_bg_sRGB;
+import static org.apache.pdfbox.preflight.PreflightConstants.ICC_Characterization_Data_Registry_eciRGB;
+import static org.apache.pdfbox.preflight.PreflightConstants.ICC_Characterization_Data_Registry_opRGB;
+import static org.apache.pdfbox.preflight.PreflightConstants.ICC_Characterization_Data_Registry_sRGB;
+import static org.apache.pdfbox.preflight.PreflightConstants.ICC_Characterization_Data_Registry_sRGB_IEC;
+import static org.apache.pdfbox.preflight.PreflightConstants.ICC_Characterization_Data_Registry_sYCC;
+import static org.apache.pdfbox.preflight.PreflightConstants.ICC_Characterization_Data_Registry_scRGB;
+import static org.apache.pdfbox.preflight.PreflightConstants.ICC_Characterization_Data_Registry_scRGB_nl;
+import static org.apache.pdfbox.preflight.PreflightConstants.ICC_Characterization_Data_Registry_scYCC_nl;
+import static org.apache.pdfbox.preflight.PreflightConstants.OUTPUT_INTENT_DICTIONARY_KEY_DEST_OUTPUT_PROFILE;
+import static org.apache.pdfbox.preflight.PreflightConstants.OUTPUT_INTENT_DICTIONARY_KEY_INFO;
+import static org.apache.pdfbox.preflight.PreflightConstants.OUTPUT_INTENT_DICTIONARY_KEY_OUTPUT_CONDITION_IDENTIFIER;
+import static org.apache.pdfbox.preflight.PreflightConstants.OUTPUT_INTENT_DICTIONARY_KEY_S;
+import static org.apache.pdfbox.preflight.PreflightConstants.OUTPUT_INTENT_DICTIONARY_VALUE_GTS_PDFA1;
+
+import java.awt.color.ICC_Profile;
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+import org.apache.pdfbox.cos.COSArray;
+import org.apache.pdfbox.cos.COSBase;
+import org.apache.pdfbox.cos.COSDictionary;
+import org.apache.pdfbox.cos.COSDocument;
+import org.apache.pdfbox.cos.COSName;
+import org.apache.pdfbox.cos.COSObject;
+import org.apache.pdfbox.pdmodel.PDDocument;
+import org.apache.pdfbox.pdmodel.PDDocumentCatalog;
+import org.apache.pdfbox.pdmodel.PDDocumentNameDictionary;
+import org.apache.pdfbox.pdmodel.PDEmbeddedFilesNameTreeNode;
+import org.apache.pdfbox.pdmodel.common.PDStream;
+import org.apache.pdfbox.persistence.util.COSObjectKey;
+import org.apache.pdfbox.preflight.PreflightConfiguration;
+import org.apache.pdfbox.preflight.PreflightContext;
+import org.apache.pdfbox.preflight.ValidationResult.ValidationError;
+import org.apache.pdfbox.preflight.exception.ValidationException;
+import org.apache.pdfbox.preflight.graphic.ICCProfileWrapper;
+import org.apache.pdfbox.preflight.utils.COSUtils;
+import org.apache.pdfbox.preflight.utils.ContextHelper;
+
+/**
+ * This ValidationProcess check if the Catalog entries are confirming with the PDF/A-1b specification.
+ */
+public class CatalogValidationProcess extends AbstractProcess {
+
+ protected PDDocumentCatalog catalog;
+
+ protected List<String> listICC = new ArrayList<String>();
+
+ public CatalogValidationProcess() {
+ listICC.add(ICC_Characterization_Data_Registry_FOGRA43);
+ listICC.add(ICC_Characterization_Data_Registry_CGATS_TR_006);
+ listICC.add(ICC_Characterization_Data_Registry_CGATS_TR006);
+ listICC.add(ICC_Characterization_Data_Registry_FOGRA39);
+ listICC.add(ICC_Characterization_Data_Registry_JC200103);
+ listICC.add(ICC_Characterization_Data_Registry_FOGRA27);
+ listICC.add(ICC_Characterization_Data_Registry_EUROSB104);
+ listICC.add(ICC_Characterization_Data_Registry_FOGRA45);
+ listICC.add(ICC_Characterization_Data_Registry_FOGRA46);
+ listICC.add(ICC_Characterization_Data_Registry_FOGRA41);
+ listICC.add(ICC_Characterization_Data_Registry_CGATS_TR_001);
+ listICC.add(ICC_Characterization_Data_Registry_CGATS_TR_003);
+ listICC.add(ICC_Characterization_Data_Registry_CGATS_TR_005);
+ listICC.add(ICC_Characterization_Data_Registry_CGATS_TR001);
+ listICC.add(ICC_Characterization_Data_Registry_CGATS_TR003);
+ listICC.add(ICC_Characterization_Data_Registry_CGATS_TR005);
+ listICC.add(ICC_Characterization_Data_Registry_FOGRA28);
+ listICC.add(ICC_Characterization_Data_Registry_JCW2003);
+ listICC.add(ICC_Characterization_Data_Registry_EUROSB204);
+ listICC.add(ICC_Characterization_Data_Registry_FOGRA47);
+ listICC.add(ICC_Characterization_Data_Registry_FOGRA44);
+ listICC.add(ICC_Characterization_Data_Registry_FOGRA29);
+ listICC.add(ICC_Characterization_Data_Registry_JC200104);
+ listICC.add(ICC_Characterization_Data_Registry_FOGRA40);
+ listICC.add(ICC_Characterization_Data_Registry_FOGRA30);
+ listICC.add(ICC_Characterization_Data_Registry_FOGRA42);
+ listICC.add(ICC_Characterization_Data_Registry_IFRA26);
+ listICC.add(ICC_Characterization_Data_Registry_JCN2002);
+ listICC.add(ICC_Characterization_Data_Registry_CGATS_TR_002);
+ listICC.add(ICC_Characterization_Data_Registry_CGATS_TR002);
+ listICC.add(ICC_Characterization_Data_Registry_FOGRA33);
+ listICC.add(ICC_Characterization_Data_Registry_FOGRA37);
+ listICC.add(ICC_Characterization_Data_Registry_FOGRA31);
+ listICC.add(ICC_Characterization_Data_Registry_FOGRA35);
+ listICC.add(ICC_Characterization_Data_Registry_FOGRA32);
+ listICC.add(ICC_Characterization_Data_Registry_FOGRA34);
+ listICC.add(ICC_Characterization_Data_Registry_FOGRA36);
+ listICC.add(ICC_Characterization_Data_Registry_FOGRA38);
+ listICC.add(ICC_Characterization_Data_Registry_sRGB);
+ listICC.add(ICC_Characterization_Data_Registry_sRGB_IEC);
+ listICC.add(ICC_Characterization_Data_Registry_Adobe);
+ listICC.add(ICC_Characterization_Data_Registry_bg_sRGB);
+ listICC.add(ICC_Characterization_Data_Registry_sYCC);
+ listICC.add(ICC_Characterization_Data_Registry_scRGB);
+ listICC.add(ICC_Characterization_Data_Registry_scRGB_nl);
+ listICC.add(ICC_Characterization_Data_Registry_scYCC_nl);
+ listICC.add(ICC_Characterization_Data_Registry_ROMM);
+ listICC.add(ICC_Characterization_Data_Registry_RIMM);
+ listICC.add(ICC_Characterization_Data_Registry_ERIMM);
+ listICC.add(ICC_Characterization_Data_Registry_eciRGB);
+ listICC.add(ICC_Characterization_Data_Registry_opRGB);
+ }
+
+ protected boolean isStandardICCCharacterization(String name) {
+ for (String iccStandard : listICC) {
+ if (iccStandard.contains(name)) {
+ return true;
+ }
+ }
+ return false;
+ }
+
+ public void validate(PreflightContext ctx) throws ValidationException {
+ PDDocument pdfbox = ctx.getDocument();
+ this.catalog = pdfbox.getDocumentCatalog();
+
+ if (this.catalog == null) {
+ new ValidationError(ERROR_SYNTAX_NOCATALOG, "There are no Catalog entry in the Document.");
+ throw new ValidationException("There are no Catalog entry in the Document.");
+ }
+
+ validateActions(ctx);
+ validateLang(ctx);
+ validateNames(ctx);
+ validateOCProperties(ctx);
+ validateOutputIntent(ctx);
+ }
+
+ /**
+ * This method validates if OpenAction entry contains forbidden action type.
+ * It checks too if an Additional Action is present.
+ *
+ * @param ctx
+ * @throws ValidationException Propagate the ActionManager exception
+ */
+ protected void validateActions(PreflightContext ctx) throws ValidationException {
+ ContextHelper.validateElement(ctx, catalog.getCOSDictionary(), ACTIONS_PROCESS);
+ // AA entry if forbidden in PDF/A-1
+ COSBase aa = catalog.getCOSDictionary().getItem(DICTIONARY_KEY_ADDITIONAL_ACTION);
+ if (aa != null) {
+ addValidationError(ctx, new ValidationError(ERROR_ACTION_FORBIDDEN_ADDITIONAL_ACTION, "The AA field is forbidden for the Catalog when the PDF is a PDF/A"));
+ }
+ }
+
+ /**
+ * The Lang element is optional but it is recommended. This method check the
+ * Syntax of the Lang if this entry is present.
+ *
+ * @param ctx
+ * @throws ValidationException
+ */
+ protected void validateLang(PreflightContext ctx) throws ValidationException {
+ String lang = catalog.getLanguage();
+ if (lang != null && !"".equals(lang) && !lang.matches("[A-Za-z]{1,8}(-[A-Za-z]{1,8})*")) {
+ addValidationError(ctx, new ValidationError(ERROR_SYNTAX_LANG_NOT_RFC1766));
+ }
+ }
+
+ /**
+ * A Catalog shall not contain the EmbeddedFiles entry.
+ *
+ * @param ctx
+ * @throws ValidationException
+ */
+ protected void validateNames(PreflightContext ctx) throws ValidationException {
+ PDDocumentNameDictionary names = catalog.getNames();
+ if (names != null) {
+ PDEmbeddedFilesNameTreeNode efs = names.getEmbeddedFiles();
+ if (efs != null) {
+ addValidationError(ctx,
+ new ValidationError(ERROR_SYNTAX_TRAILER_CATALOG_EMBEDDEDFILES,
+ "EmbeddedFile entry is present in the Names dictionary"));
+ }
+ }
+ }
+
+ /**
+ * A Catalog shall not contain the OCPProperties (Optional Content Properties) entry.
+ *
+ * @param ctx
+ * @throws ValidationException
+ */
+ protected void validateOCProperties(PreflightContext ctx) throws ValidationException {
+ if (catalog.getOCProperties() != null) {
+ addValidationError(ctx,
+ new ValidationError(ERROR_SYNTAX_TRAILER_CATALOG_OCPROPERTIES,
+ "A Catalog shall not contain the OCPProperties entry."));
+ }
+ }
+
+ /**
+ * This method checks the content of each OutputIntent. The S entry must
+ * contain GTS_PDFA1. The DestOuputProfile must contain a valid ICC Profile
+ * Stream.
+ *
+ * If there are more than one OutputIntent, they have to use the same ICC
+ * Profile.
+ *
+ * This method returns a list of ValidationError. It is empty if no errors
+ * have been found.
+ *
+ * @param ctx
+ * @throws ValidationException
+ */
+ public void validateOutputIntent(PreflightContext ctx) throws ValidationException {
+ COSDocument cosDocument = ctx.getDocument().getDocument();
+ COSBase cBase = catalog.getCOSDictionary().getItem(COSName.getPDFName(DOCUMENT_DICTIONARY_KEY_OUTPUT_INTENTS));
+ COSArray outputIntents = COSUtils.getAsArray(cBase, cosDocument);
+
+ Map<COSObjectKey, Boolean> tmpDestOutputProfile = new HashMap<COSObjectKey, Boolean>();
+ for (int i = 0; outputIntents != null && i < outputIntents.size(); ++i) {
+ COSDictionary outputIntentDict = COSUtils.getAsDictionary(outputIntents.get(i), cosDocument);
+
+ if (outputIntentDict == null) {
+ addValidationError(ctx,
+ new ValidationError(ERROR_GRAPHIC_OUTPUT_INTENT_INVALID_ENTRY,
+ "OutputIntent object is null or isn't a dictionary"));
+ } else {
+ // S entry is mandatory and must be equals to GTS_PDFA1
+ String sValue = outputIntentDict.getNameAsString(OUTPUT_INTENT_DICTIONARY_KEY_S);
+ if (!OUTPUT_INTENT_DICTIONARY_VALUE_GTS_PDFA1.equals(sValue)) {
+ addValidationError(ctx,
+ new ValidationError(ERROR_GRAPHIC_OUTPUT_INTENT_S_VALUE_INVALID,
+ "The S entry of the OutputIntent isn't GTS_PDFA1"));
+ continue;
+ }
+
+ // OutputConditionIdentifier is a mandatory field
+ String outputConditionIdentifier = outputIntentDict.getString(OUTPUT_INTENT_DICTIONARY_KEY_OUTPUT_CONDITION_IDENTIFIER);
+ if (outputConditionIdentifier == null) {// empty string is authorized (it may be an application specific value)
+ addValidationError(ctx,
+ new ValidationError(ERROR_GRAPHIC_OUTPUT_INTENT_INVALID_ENTRY,
+ "The OutputIntentCondition is missing"));
+ continue;
+ }
+
+
+ /* If OutputConditionIdentifier is "Custom" or a non Standard ICC Characterization :
+ * DestOutputProfile and Info are mandatory
+ * DestOutputProfile must be a ICC Profile
+ *
+ * Because of PDF/A conforming file needs to specify the color characteristics, the DestOutputProfile
+ * is checked even if the OutputConditionIdentifier isn't "Custom"
+ */
+ COSBase destOutputProfile = outputIntentDict.getItem(OUTPUT_INTENT_DICTIONARY_KEY_DEST_OUTPUT_PROFILE);
+ validateICCProfile(destOutputProfile, tmpDestOutputProfile, ctx);
+
+ PreflightConfiguration config = ctx.getConfig();
+ if (config.isLazyValidation() && !isStandardICCCharacterization(outputConditionIdentifier)) {
+ String info = outputIntentDict.getString(COSName.getPDFName(OUTPUT_INTENT_DICTIONARY_KEY_INFO));
+ if (info == null || "".equals(info)) {
+ ValidationError error = new ValidationError(ERROR_GRAPHIC_OUTPUT_INTENT_INVALID_ENTRY, "The Info entry of a OutputIntent dictionary is missing");
+ error.setWarning(true);
+ addValidationError(ctx, error);
+ continue;
+ }
+ }
+ }
+ }
+ }
+
+ /**
+ * This method checks the destOutputProfile which must be a valid ICCProfile.
+ *
+ * If an other ICCProfile exists in the mapDestOutputProfile, a
+ * ValdiationError (ERROR_GRAPHIC_OUTPUT_INTENT_ICC_PROFILE_MULTIPLE) is
+ * returned because of only one profile is authorized. If the ICCProfile
+ * already exist in the mapDestOutputProfile, the method returns null. If the
+ * destOutputProfile contains an invalid ICCProfile, a ValidationError
+ * (ERROR_GRAPHIC_OUTPUT_INTENT_ICC_PROFILE_INVALID) is returned If the
+ * destOutputProfile is an empty stream, a
+ * ValidationError(ERROR_GRAPHIC_OUTPUT_INTENT_INVALID_ENTRY) is returned.
+ *
+ * If the destOutputFile is valid, mapDestOutputProfile is updated, the
+ * ICCProfile is added to the document ctx and null is returned.
+ *
+ * @param destOutputProfile
+ * @param tmpDestOutputProfile
+ * @param ctx
+ * @return
+ * @throws ValidationException
+ */
+ protected void validateICCProfile(COSBase destOutputProfile, Map<COSObjectKey, Boolean> mapDestOutputProfile,
+ PreflightContext ctx) throws ValidationException {
+ try {
+ if (destOutputProfile == null) {
+ return ;
+ }
+
+ // destOutputProfile should be an instance of COSObject because of this is a object reference
+ if (destOutputProfile instanceof COSObject) {
+ if (mapDestOutputProfile.containsKey(new COSObjectKey((COSObject) destOutputProfile))) {
+ // the profile is already checked. continue
+ return ;
+ } else if (!mapDestOutputProfile.isEmpty()) {
+ // A DestOutputProfile exits but it isn't the same, error
+ addValidationError(ctx, new ValidationError(ERROR_GRAPHIC_OUTPUT_INTENT_ICC_PROFILE_MULTIPLE, "More than one ICCProfile is defined"));
+ return;
+ }
+ // else the profile will be kept in the tmpDestOutputProfile if it is valid
+ }
+
+ // keep reference to avoid multiple profile definition
+ mapDestOutputProfile.put(new COSObjectKey((COSObject) destOutputProfile), true);
+ COSDocument cosDocument = ctx.getDocument().getDocument();
+ PDStream stream = PDStream.createFromCOS(COSUtils.getAsStream(destOutputProfile, cosDocument));
+ if (stream == null) {
+ addValidationError(ctx, new ValidationError(ERROR_GRAPHIC_OUTPUT_INTENT_INVALID_ENTRY, "OutputIntent object uses a NULL Object"));
+ return;
+ }
+
+ ICC_Profile iccp = ICC_Profile.getInstance(stream.getByteArray());
+ PreflightConfiguration config = ctx.getConfig();
+ // check the ICC Profile version (6.2.2)
+ if (iccp.getMajorVersion() == 2) {
+ if (iccp.getMinorVersion() > 0x40) {
+ // in PDF 1.4, max version is 02h.40h (meaning V 3.5)
+ // see the ICCProfile specification (ICC.1:1998-09)page 13 - §6.1.3 :
+ // The current profile version number is "2.4.0" (encoded as 02400000h")
+ ValidationError error = new ValidationError(ERROR_GRAPHIC_OUTPUT_INTENT_ICC_PROFILE_TOO_RECENT, "Invalid version of the ICCProfile");
+ error.setWarning(config.isLazyValidation());
+ addValidationError(ctx, error);
+ return ;
+ } // else OK
+ } else if (iccp.getMajorVersion() > 2) {
+ // in PDF 1.4, max version is 02h.40h (meaning V 3.5)
+ // see the ICCProfile specification (ICC.1:1998-09)page 13 - §6.1.3 :
+ // The current profile version number is "2.4.0" (encoded as 02400000h"
+ ValidationError error = new ValidationError(ERROR_GRAPHIC_OUTPUT_INTENT_ICC_PROFILE_TOO_RECENT, "Invalid version of the ICCProfile");
+ error.setWarning(config.isLazyValidation());
+ addValidationError(ctx, error);
+ return ;
+ } // else seems less than 2, so correct
+
+ if (ctx.getIccProfileWrapper() == null) {
+ ctx.setIccProfileWrapper(new ICCProfileWrapper(iccp));
+ }
+
+ } catch (IllegalArgumentException e) {
+ // this is not a ICC_Profile
+ addValidationError(ctx, new ValidationError(ERROR_GRAPHIC_OUTPUT_INTENT_ICC_PROFILE_INVALID, "DestOutputProfile isn't a ICCProfile"));
+ } catch (IOException e) {
+ throw new ValidationException("Unable to parse the ICC Profile", e);
+ }
+ }
+}
Propchange: pdfbox/trunk/preflight/src/main/java/org/apache/pdfbox/preflight/process/CatalogValidationProcess.java
------------------------------------------------------------------------------
svn:eol-style = native
Added: pdfbox/trunk/preflight/src/main/java/org/apache/pdfbox/preflight/process/EmptyValidationProcess.java
URL: http://svn.apache.org/viewvc/pdfbox/trunk/preflight/src/main/java/org/apache/pdfbox/preflight/process/EmptyValidationProcess.java?rev=1355309&view=auto
==============================================================================
--- pdfbox/trunk/preflight/src/main/java/org/apache/pdfbox/preflight/process/EmptyValidationProcess.java (added)
+++ pdfbox/trunk/preflight/src/main/java/org/apache/pdfbox/preflight/process/EmptyValidationProcess.java Fri Jun 29 10:25:22 2012
@@ -0,0 +1,38 @@
+/*****************************************************************************
+ *
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ *
+ ****************************************************************************/
+
+package org.apache.pdfbox.preflight.process;
+
+import org.apache.pdfbox.preflight.PreflightContext;
+import org.apache.pdfbox.preflight.exception.ValidationException;
+
+/**
+ * This class is used to return a non null ValidationProcess when a missing process is asked
+ * to the ConfigurationBean only if the errorOnMissingProcess configuration attribute is set to false.
+ *
+ */
+public class EmptyValidationProcess implements ValidationProcess {
+
+ public void validate(PreflightContext context)
+ throws ValidationException {
+ // this class does nothing
+ }
+}
Propchange: pdfbox/trunk/preflight/src/main/java/org/apache/pdfbox/preflight/process/EmptyValidationProcess.java
------------------------------------------------------------------------------
svn:eol-style = native
Added: pdfbox/trunk/preflight/src/main/java/org/apache/pdfbox/preflight/process/FileSpecificationValidationProcess.java
URL: http://svn.apache.org/viewvc/pdfbox/trunk/preflight/src/main/java/org/apache/pdfbox/preflight/process/FileSpecificationValidationProcess.java?rev=1355309&view=auto
==============================================================================
--- pdfbox/trunk/preflight/src/main/java/org/apache/pdfbox/preflight/process/FileSpecificationValidationProcess.java (added)
+++ pdfbox/trunk/preflight/src/main/java/org/apache/pdfbox/preflight/process/FileSpecificationValidationProcess.java Fri Jun 29 10:25:22 2012
@@ -0,0 +1,89 @@
+/*****************************************************************************
+ *
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ *
+ ****************************************************************************/
+
+package org.apache.pdfbox.preflight.process;
+
+import static org.apache.pdfbox.preflight.PreflightConstants.ERROR_SYNTAX_EMBEDDED_FILES;
+import static org.apache.pdfbox.preflight.PreflightConstants.FILE_SPECIFICATION_KEY_EMBEDDED_FILE;
+import static org.apache.pdfbox.preflight.PreflightConstants.FILE_SPECIFICATION_VALUE_TYPE;
+
+import java.util.ArrayList;
+import java.util.List;
+
+import org.apache.pdfbox.cos.COSBase;
+import org.apache.pdfbox.cos.COSDictionary;
+import org.apache.pdfbox.cos.COSDocument;
+import org.apache.pdfbox.cos.COSName;
+import org.apache.pdfbox.cos.COSObject;
+import org.apache.pdfbox.pdmodel.PDDocument;
+import org.apache.pdfbox.preflight.PreflightContext;
+import org.apache.pdfbox.preflight.ValidationResult.ValidationError;
+import org.apache.pdfbox.preflight.exception.ValidationException;
+/**
+ *
+ * This validation process check that FileSpec dictionaries are confirming with the PDF/A-1b specification.
+ */
+public class FileSpecificationValidationProcess extends AbstractProcess {
+
+
+ public void validate(PreflightContext ctx) throws ValidationException {
+ PDDocument pdfDoc = ctx.getDocument();
+ COSDocument cDoc = pdfDoc.getDocument();
+
+ List<?> lCOSObj = cDoc.getObjects();
+ for (Object o : lCOSObj) {
+ // If this object represents a Stream
+ // The Dictionary must contain the Length key
+ COSBase cBase = ((COSObject) o).getObject();
+ if (cBase instanceof COSDictionary) {
+ COSDictionary dic = (COSDictionary) cBase;
+ String type = dic.getNameAsString(COSName.TYPE);
+ if (FILE_SPECIFICATION_VALUE_TYPE.equals(type)) {
+ // ---- It is a file specification
+ validateFileSpecification(ctx, dic);
+ }
+ }
+ }
+ }
+
+
+ /**
+ * Validate a FileSpec dictionary, a FileSpec dictionary mustn't have the EF
+ * (EmbeddedFile) entry.
+ *
+ * @param ctx
+ * The document handler
+ * @param cObj
+ * the FileSpec Dictionary
+ * @return
+ */
+ public List<ValidationError> validateFileSpecification(PreflightContext ctx, COSDictionary fileSpec) {
+ List<ValidationError> result = new ArrayList<ValidationError>(0);
+
+ // ---- Check dictionary entries
+ // ---- Only the EF entry is forbidden
+ if (fileSpec.getItem(COSName.getPDFName(FILE_SPECIFICATION_KEY_EMBEDDED_FILE)) != null) {
+ addValidationError(ctx, new ValidationError(ERROR_SYNTAX_EMBEDDED_FILES,"EmbeddedFile entry is present in a FileSpecification dictionary"));
+ }
+
+ return result;
+ }
+}
Propchange: pdfbox/trunk/preflight/src/main/java/org/apache/pdfbox/preflight/process/FileSpecificationValidationProcess.java
------------------------------------------------------------------------------
svn:eol-style = native
Added: pdfbox/trunk/preflight/src/main/java/org/apache/pdfbox/preflight/process/MetadataValidationProcess.java
URL: http://svn.apache.org/viewvc/pdfbox/trunk/preflight/src/main/java/org/apache/pdfbox/preflight/process/MetadataValidationProcess.java?rev=1355309&view=auto
==============================================================================
--- pdfbox/trunk/preflight/src/main/java/org/apache/pdfbox/preflight/process/MetadataValidationProcess.java (added)
+++ pdfbox/trunk/preflight/src/main/java/org/apache/pdfbox/preflight/process/MetadataValidationProcess.java Fri Jun 29 10:25:22 2012
@@ -0,0 +1,218 @@
+/*****************************************************************************
+ *
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ *
+ ****************************************************************************/
+
+package org.apache.pdfbox.preflight.process;
+
+import java.io.ByteArrayOutputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import java.util.ArrayList;
+import java.util.List;
+
+import org.apache.padaf.xmpbox.XMPMetadata;
+import org.apache.padaf.xmpbox.parser.PDFAExtentionSchemaPreprocessor;
+import org.apache.padaf.xmpbox.parser.XMPDocumentBuilder;
+import org.apache.padaf.xmpbox.parser.XmpExpectedRdfAboutAttribute;
+import org.apache.padaf.xmpbox.parser.XmpParsingException;
+import org.apache.padaf.xmpbox.parser.XmpPropertyFormatException;
+import org.apache.padaf.xmpbox.parser.XmpRequiredPropertyException;
+import org.apache.padaf.xmpbox.parser.XmpSchemaException;
+import org.apache.padaf.xmpbox.parser.XmpUnexpectedNamespacePrefixException;
+import org.apache.padaf.xmpbox.parser.XmpUnexpectedNamespaceURIException;
+import org.apache.padaf.xmpbox.parser.XmpUnknownPropertyException;
+import org.apache.padaf.xmpbox.parser.XmpUnknownSchemaException;
+import org.apache.padaf.xmpbox.parser.XmpUnknownValueTypeException;
+import org.apache.padaf.xmpbox.parser.XmpXpacketEndException;
+import org.apache.padaf.xmpbox.type.BadFieldValueException;
+import org.apache.pdfbox.cos.COSBase;
+import org.apache.pdfbox.cos.COSDictionary;
+import org.apache.pdfbox.cos.COSDocument;
+import org.apache.pdfbox.cos.COSName;
+import org.apache.pdfbox.cos.COSObject;
+import org.apache.pdfbox.io.IOUtils;
+import org.apache.pdfbox.pdmodel.PDDocument;
+import org.apache.pdfbox.pdmodel.common.PDStream;
+import org.apache.pdfbox.preflight.PreflightConstants;
+import org.apache.pdfbox.preflight.PreflightContext;
+import org.apache.pdfbox.preflight.ValidationResult.ValidationError;
+import org.apache.pdfbox.preflight.exception.ValidationException;
+import org.apache.pdfbox.preflight.metadata.PDFAIdentificationValidation;
+import org.apache.pdfbox.preflight.metadata.RDFAboutAttributeConcordanceValidation;
+import org.apache.pdfbox.preflight.metadata.RDFAboutAttributeConcordanceValidation.DifferentRDFAboutException;
+import org.apache.pdfbox.preflight.metadata.SynchronizedMetaDataValidation;
+import org.apache.pdfbox.preflight.metadata.XpacketParsingException;
+import org.apache.pdfbox.preflight.utils.COSUtils;
+
+
+public class MetadataValidationProcess extends AbstractProcess {
+
+
+ public void validate(PreflightContext ctx) throws ValidationException {
+ try {
+ PDDocument document = ctx.getDocument();
+
+ byte[] tmp = getXpacket(document.getDocument());
+ XMPDocumentBuilder builder;
+ try {
+ builder = new XMPDocumentBuilder();
+ builder.addPreprocessor(new PDFAExtentionSchemaPreprocessor());
+ } catch (XmpSchemaException e1) {
+ throw new ValidationException(e1.getMessage(), e1);
+ }
+ XMPMetadata metadata;
+ try {
+ metadata = builder.parse(tmp);
+ ctx.setMetadata(metadata);
+ } catch (XmpSchemaException e) {
+ throw new ValidationException(
+ "Parser: Internal Problem (failed to instanciate Schema object)", e);
+ } catch (XmpXpacketEndException e) {
+ throw new ValidationException("Unable to parse font metadata due to : "
+ + e.getMessage(), e);
+ }
+
+ // 6.7.5 no deprecated attribute in xpacket processing instruction
+ if (metadata.getXpacketBytes() != null) {
+ addValidationError(ctx, new ValidationError(
+ PreflightConstants.ERROR_METADATA_XPACKET_DEPRECATED,
+ "bytes attribute is forbidden"));
+ }
+ if (metadata.getXpacketEncoding() != null) {
+ addValidationError(ctx, new ValidationError(
+ PreflightConstants.ERROR_METADATA_XPACKET_DEPRECATED,
+ "encoding attribute is forbidden"));
+ }
+
+ // Call metadata synchronization checking
+ addValidationErrors(ctx, new SynchronizedMetaDataValidation()
+ .validateMetadataSynchronization(document, metadata));
+
+ // Call PDF/A Identifier checking
+ addValidationErrors(ctx, new PDFAIdentificationValidation()
+ .validatePDFAIdentifer(metadata));
+
+ // Call rdf:about checking
+ try {
+ new RDFAboutAttributeConcordanceValidation().validateRDFAboutAttributes(metadata);
+ } catch (DifferentRDFAboutException e) {
+ addValidationError(ctx, new ValidationError(
+ PreflightConstants.ERROR_METADATA_RDF_ABOUT_ATTRIBUTE_INEQUAL_VALUE, e
+ .getMessage()));
+ }
+
+ } catch (XpacketParsingException e) {
+ if (e.getError() != null) {
+ addValidationError(ctx, e.getError());
+ } else {
+ addValidationError(ctx, new ValidationError(PreflightConstants.ERROR_METADATA_MAIN,
+ "Unexpected error"));
+ }
+ } catch (XmpPropertyFormatException e) {
+ addValidationError(ctx, new ValidationError(
+ PreflightConstants.ERROR_METADATA_PROPERTY_FORMAT, e.getMessage()));
+ } catch (BadFieldValueException e) {
+ addValidationError(ctx, new ValidationError(PreflightConstants.ERROR_METADATA_CATEGORY_PROPERTY_INVALID ,e.getMessage()));
+ }
+ catch (XmpExpectedRdfAboutAttribute e) {
+ addValidationError(ctx, new ValidationError(PreflightConstants.ERROR_METADATA_RDF_ABOUT_ATTRIBUTE_MISSING ,e.getMessage()));
+ } catch (XmpUnknownPropertyException e) {
+ addValidationError(ctx, new ValidationError(
+ PreflightConstants.ERROR_METADATA_PROPERTY_UNKNOWN, e.getMessage()));
+ } catch (XmpUnknownSchemaException e) {
+ addValidationError(ctx, new ValidationError(
+ PreflightConstants.ERROR_METADATA_ABSENT_DESCRIPTION_SCHEMA, e
+ .getMessage()));
+ } catch (XmpUnexpectedNamespaceURIException e) {
+ addValidationError(ctx, new ValidationError(
+ PreflightConstants.ERROR_METADATA_WRONG_NS_URI, e.getMessage()));
+ } catch (XmpUnexpectedNamespacePrefixException e) {
+ addValidationError(ctx, new ValidationError(
+ PreflightConstants.ERROR_METADATA_ABSENT_DESCRIPTION_SCHEMA, e
+ .getMessage()));
+ } catch (XmpRequiredPropertyException e) {
+ addValidationError(ctx, new ValidationError(
+ PreflightConstants.ERROR_METADATA_PROPERTY_MISSING, e.getMessage()));
+ } catch (XmpUnknownValueTypeException e) {
+ addValidationError(ctx, new ValidationError(
+ PreflightConstants.ERROR_METADATA_UNKNOWN_VALUETYPE, e
+ .getMessage()));
+ } catch (XmpParsingException e) {
+
+ addValidationError(ctx, new ValidationError(PreflightConstants.ERROR_METADATA_FORMAT, e
+ .getMessage()));
+ }
+
+ catch (IOException e) {
+ throw new ValidationException("Failed while validating", e);
+ }
+ }
+
+ /**
+ * Return the xpacket from the dictionary's stream
+ */
+ public static byte[] getXpacket(COSDocument cdocument) throws IOException,
+ XpacketParsingException {
+ COSObject catalog = cdocument.getCatalog();
+ COSBase cb = catalog.getDictionaryObject(COSName.METADATA);
+ if (cb == null) {
+ // missing Metadata Key in catalog
+ ValidationError error = new ValidationError(
+ PreflightConstants.ERROR_METADATA_FORMAT,
+ "Missing Metadata Key in catalog");
+ throw new XpacketParsingException("Failed while retrieving xpacket",
+ error);
+ }
+ // no filter key
+ COSDictionary metadataDictionnary = COSUtils.getAsDictionary(cb, cdocument);
+ if (metadataDictionnary.getItem(COSName.FILTER) != null) {
+ // should not be defined
+ ValidationError error = new ValidationError(
+ PreflightConstants.ERROR_SYNTAX_STREAM_INVALID_FILTER,
+ "Filter specified in metadata dictionnary");
+ throw new XpacketParsingException("Failed while retrieving xpacket",
+ error);
+ }
+
+ PDStream stream = PDStream.createFromCOS(metadataDictionnary);
+ ByteArrayOutputStream bos = new ByteArrayOutputStream();
+ InputStream is = stream.createInputStream();
+ IOUtils.copy(is, bos);
+ is.close();
+ bos.close();
+ return bos.toByteArray();
+ }
+
+ /**
+ * Check if metadata dictionary has no stream filter
+ *
+ * @param doc
+ * @return
+ */
+ protected List<ValidationError> checkStreamFilterUsage(PDDocument doc) {
+ List<ValidationError> ve = new ArrayList<ValidationError>();
+ List<?> filters = doc.getDocumentCatalog().getMetadata().getFilters();
+ if (filters != null && !filters.isEmpty()) {
+ ve.add(new ValidationError(PreflightConstants.ERROR_METADATA_MAIN,
+ "Using stream filter on metadata dictionary is forbidden"));
+ }
+ return ve;
+ }
+}
Propchange: pdfbox/trunk/preflight/src/main/java/org/apache/pdfbox/preflight/process/MetadataValidationProcess.java
------------------------------------------------------------------------------
svn:eol-style = native
Added: pdfbox/trunk/preflight/src/main/java/org/apache/pdfbox/preflight/process/PageTreeValidationProcess.java
URL: http://svn.apache.org/viewvc/pdfbox/trunk/preflight/src/main/java/org/apache/pdfbox/preflight/process/PageTreeValidationProcess.java?rev=1355309&view=auto
==============================================================================
--- pdfbox/trunk/preflight/src/main/java/org/apache/pdfbox/preflight/process/PageTreeValidationProcess.java (added)
+++ pdfbox/trunk/preflight/src/main/java/org/apache/pdfbox/preflight/process/PageTreeValidationProcess.java Fri Jun 29 10:25:22 2012
@@ -0,0 +1,51 @@
+/*****************************************************************************
+ *
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ *
+ ****************************************************************************/
+
+package org.apache.pdfbox.preflight.process;
+
+import static org.apache.pdfbox.preflight.PreflightConfiguration.PAGE_PROCESS;
+
+import java.util.List;
+
+import org.apache.pdfbox.pdmodel.PDDocumentCatalog;
+import org.apache.pdfbox.pdmodel.PDPage;
+import org.apache.pdfbox.preflight.PreflightContext;
+import org.apache.pdfbox.preflight.exception.ValidationException;
+import org.apache.pdfbox.preflight.utils.ContextHelper;
+
+public class PageTreeValidationProcess extends AbstractProcess {
+
+ public void validate(PreflightContext context) throws ValidationException {
+ PDDocumentCatalog catalog = context.getDocument().getDocumentCatalog();
+ if (catalog != null) {
+ List<?> pages = catalog.getAllPages();
+ for (int i = 0; i < pages.size(); ++i) {
+ validatePage(context,(PDPage) pages.get(i));
+ }
+ } else {
+ throw new ValidationException("There are no Catalog entry in the Document.");
+ }
+ }
+
+ protected void validatePage(PreflightContext context, PDPage page) throws ValidationException {
+ ContextHelper.validateElement(context, page, PAGE_PROCESS);
+ }
+}
Propchange: pdfbox/trunk/preflight/src/main/java/org/apache/pdfbox/preflight/process/PageTreeValidationProcess.java
------------------------------------------------------------------------------
svn:eol-style = native