Search in sources :

Example 41 with DocumentException

use of org.dom4j.DocumentException in project maven-archetype by apache.

the class DefaultOldArchetype method createArchetype.

public void createArchetype(ArchetypeGenerationRequest request, File archetypeFile) throws ArchetypeDescriptorException, ArchetypeTemplateProcessingException {
    Map<String, String> parameters = new HashMap<String, String>();
    parameters.put("basedir", request.getOutputDirectory());
    parameters.put(Constants.PACKAGE, request.getPackage());
    parameters.put("packageName", request.getPackage());
    parameters.put(Constants.GROUP_ID, request.getGroupId());
    parameters.put(Constants.ARTIFACT_ID, request.getArtifactId());
    parameters.put(Constants.VERSION, request.getVersion());
    // ---------------------------------------------------------------------
    if (getLogger().isInfoEnabled()) {
        getLogger().info("----------------------------------------------------------------------------");
        getLogger().info("Using following parameters for creating project from Old (1.x) Archetype: " + request.getArchetypeArtifactId() + ":" + request.getArchetypeVersion());
        getLogger().info("----------------------------------------------------------------------------");
        for (Map.Entry<String, String> entry : parameters.entrySet()) {
            String parameterName = entry.getKey();
            String parameterValue = entry.getValue();
            getLogger().info("Parameter: " + parameterName + ", Value: " + parameterValue);
        }
    }
    // ----------------------------------------------------------------------
    // Load the descriptor
    // ----------------------------------------------------------------------
    ArchetypeDescriptorBuilder builder = new ArchetypeDescriptorBuilder();
    ArchetypeDescriptor descriptor;
    URLClassLoader archetypeJarLoader;
    InputStream is = null;
    try {
        URL[] urls = new URL[1];
        urls[0] = archetypeFile.toURL();
        archetypeJarLoader = new URLClassLoader(urls);
        is = getStream(ARCHETYPE_DESCRIPTOR, archetypeJarLoader);
        if (is == null) {
            is = getStream(ARCHETYPE_OLD_DESCRIPTOR, archetypeJarLoader);
        }
        if (is == null) {
            throw new ArchetypeDescriptorException("The " + ARCHETYPE_DESCRIPTOR + " descriptor cannot be found.");
        }
        descriptor = builder.build(new XmlStreamReader(is));
    } catch (IOException e) {
        throw new ArchetypeDescriptorException("Error reading the " + ARCHETYPE_DESCRIPTOR + " descriptor.", e);
    } catch (XmlPullParserException e) {
        throw new ArchetypeDescriptorException("Error reading the " + ARCHETYPE_DESCRIPTOR + " descriptor.", e);
    } finally {
        IOUtil.close(is);
    }
    // ----------------------------------------------------------------------
    // 
    // ----------------------------------------------------------------------
    String artifactId = request.getArtifactId();
    File parentPomFile = new File(request.getOutputDirectory(), ARCHETYPE_POM);
    File outputDirectoryFile;
    boolean creating;
    File pomFile;
    if (parentPomFile.exists() && descriptor.isAllowPartial() && artifactId == null) {
        outputDirectoryFile = new File(request.getOutputDirectory());
        creating = false;
        pomFile = parentPomFile;
    } else {
        if (artifactId == null) {
            throw new ArchetypeTemplateProcessingException("Artifact ID must be specified when creating a new project from an archetype.");
        }
        outputDirectoryFile = new File(request.getOutputDirectory(), artifactId);
        creating = true;
        if (outputDirectoryFile.exists()) {
            if (descriptor.isAllowPartial()) {
                creating = false;
            } else {
                throw new ArchetypeTemplateProcessingException("Directory " + outputDirectoryFile.getName() + " already exists - please run from a clean directory");
            }
        }
        pomFile = new File(outputDirectoryFile, ARCHETYPE_POM);
    }
    if (creating) {
        if (request.getGroupId() == null) {
            throw new ArchetypeTemplateProcessingException("Group ID must be specified when creating a new project from an archetype.");
        }
        if (request.getVersion() == null) {
            throw new ArchetypeTemplateProcessingException("Version must be specified when creating a new project from an archetype.");
        }
    }
    String outputDirectory = outputDirectoryFile.getAbsolutePath();
    String packageName = request.getPackage();
    // ----------------------------------------------------------------------
    // Set up the Velocity context
    // ----------------------------------------------------------------------
    Context context = new VelocityContext();
    context.put(Constants.PACKAGE, packageName);
    for (Map.Entry<String, String> entry : parameters.entrySet()) {
        context.put(entry.getKey(), entry.getValue());
    }
    // ----------------------------------------------------------------------
    // Process the templates
    // ----------------------------------------------------------------------
    ClassLoader old = Thread.currentThread().getContextClassLoader();
    Thread.currentThread().setContextClassLoader(archetypeJarLoader);
    Model parentModel = null;
    if (creating) {
        if (parentPomFile.exists()) {
            Reader fileReader = null;
            try {
                fileReader = ReaderFactory.newXmlReader(parentPomFile);
                MavenXpp3Reader reader = new MavenXpp3Reader();
                parentModel = reader.read(fileReader);
                if (!"pom".equals(parentModel.getPackaging())) {
                    throw new ArchetypeTemplateProcessingException("Unable to add module to the current project as it is not of packaging type 'pom'");
                }
            } catch (IOException e) {
                throw new ArchetypeTemplateProcessingException("Unable to read parent POM", e);
            } catch (XmlPullParserException e) {
                throw new ArchetypeTemplateProcessingException("Unable to read parent POM", e);
            } finally {
                IOUtil.close(fileReader);
            }
            parentModel.getModules().add(artifactId);
        }
    }
    try {
        processTemplates(pomFile, outputDirectory, context, descriptor, packageName, parentModel);
    } finally {
        Thread.currentThread().setContextClassLoader(old);
    }
    if (parentModel != null) {
        /*
        // TODO: would be nice to just write out with the xpp3 writer again, except that it loses a bunch of info and
        // reformats, so the module is just baked in as a string instead.
            FileWriter fileWriter = null;

            try
            {
                fileWriter = new FileWriter( parentPomFile );

                MavenXpp3Writer writer = new MavenXpp3Writer();
                writer.write( fileWriter, parentModel );
            }
            catch ( IOException e )
            {
                throw new ArchetypeTemplateProcessingException( "Unable to rewrite parent POM", e );
            }
            finally
            {
                IOUtil.close( fileWriter );
            }
*/
        Reader fileReader = null;
        boolean added;
        StringWriter w = new StringWriter();
        try {
            fileReader = ReaderFactory.newXmlReader(parentPomFile);
            added = addModuleToParentPom(artifactId, fileReader, w);
        } catch (IOException e) {
            throw new ArchetypeTemplateProcessingException("Unable to rewrite parent POM", e);
        } catch (DocumentException e) {
            throw new ArchetypeTemplateProcessingException("Unable to rewrite parent POM", e);
        } finally {
            IOUtil.close(fileReader);
        }
        if (added) {
            Writer out = null;
            try {
                out = WriterFactory.newXmlWriter(parentPomFile);
                IOUtil.copy(w.toString(), out);
            } catch (IOException e) {
                throw new ArchetypeTemplateProcessingException("Unable to rewrite parent POM", e);
            } finally {
                IOUtil.close(out);
            }
        }
    }
    // ----------------------------------------------------------------------
    if (getLogger().isInfoEnabled()) {
        getLogger().info("project created from Old (1.x) Archetype in dir: " + outputDirectory);
    }
}
Also used : HashMap(java.util.HashMap) VelocityContext(org.apache.velocity.VelocityContext) SAXReader(org.dom4j.io.SAXReader) XmlStreamReader(org.apache.commons.io.input.XmlStreamReader) Reader(java.io.Reader) MavenXpp3Reader(org.apache.maven.model.io.xpp3.MavenXpp3Reader) URL(java.net.URL) StringWriter(java.io.StringWriter) ArchetypeDescriptorBuilder(org.apache.maven.archetype.old.descriptor.ArchetypeDescriptorBuilder) DocumentException(org.dom4j.DocumentException) URLClassLoader(java.net.URLClassLoader) XmlPullParserException(org.codehaus.plexus.util.xml.pull.XmlPullParserException) Context(org.apache.velocity.context.Context) VelocityContext(org.apache.velocity.VelocityContext) InputStream(java.io.InputStream) XmlStreamReader(org.apache.commons.io.input.XmlStreamReader) MavenXpp3Reader(org.apache.maven.model.io.xpp3.MavenXpp3Reader) IOException(java.io.IOException) ArchetypeDescriptor(org.apache.maven.archetype.old.descriptor.ArchetypeDescriptor) URLClassLoader(java.net.URLClassLoader) Model(org.apache.maven.model.Model) HashMap(java.util.HashMap) Map(java.util.Map) File(java.io.File) XMLWriter(org.dom4j.io.XMLWriter) OutputStreamWriter(java.io.OutputStreamWriter) StringWriter(java.io.StringWriter) MavenXpp3Writer(org.apache.maven.model.io.xpp3.MavenXpp3Writer) Writer(java.io.Writer)

Example 42 with DocumentException

use of org.dom4j.DocumentException in project maven-archetype by apache.

the class DefaultFilesetArchetypeGenerator method generateArchetype.

public void generateArchetype(ArchetypeGenerationRequest request, File archetypeFile) throws UnknownArchetype, ArchetypeNotConfigured, ProjectDirectoryExists, PomFileExists, OutputFileExists, ArchetypeGenerationFailure {
    ClassLoader old = Thread.currentThread().getContextClassLoader();
    try {
        ArchetypeDescriptor archetypeDescriptor = archetypeArtifactManager.getFileSetArchetypeDescriptor(archetypeFile);
        if (!isArchetypeConfigured(archetypeDescriptor, request)) {
            if (request.isInteractiveMode()) {
                throw new ArchetypeNotConfigured("No archetype was chosen.", null);
            }
            StringBuffer exceptionMessage = new StringBuffer("Archetype " + request.getArchetypeGroupId() + ":" + request.getArchetypeArtifactId() + ":" + request.getArchetypeVersion() + " is not configured");
            List<String> missingProperties = new ArrayList<String>(0);
            for (RequiredProperty requiredProperty : archetypeDescriptor.getRequiredProperties()) {
                if (StringUtils.isEmpty(request.getProperties().getProperty(requiredProperty.getKey()))) {
                    exceptionMessage.append("\n\tProperty " + requiredProperty.getKey() + " is missing.");
                    missingProperties.add(requiredProperty.getKey());
                }
            }
            throw new ArchetypeNotConfigured(exceptionMessage.toString(), missingProperties);
        }
        Context context = prepareVelocityContext(request);
        String packageName = request.getPackage();
        String artifactId = request.getArtifactId();
        File outputDirectoryFile = new File(request.getOutputDirectory(), artifactId);
        File basedirPom = new File(request.getOutputDirectory(), Constants.ARCHETYPE_POM);
        File pom = new File(outputDirectoryFile, Constants.ARCHETYPE_POM);
        List<String> archetypeResources = archetypeArtifactManager.getFilesetArchetypeResources(archetypeFile);
        ZipFile archetypeZipFile = archetypeArtifactManager.getArchetypeZipFile(archetypeFile);
        ClassLoader archetypeJarLoader = archetypeArtifactManager.getArchetypeJarLoader(archetypeFile);
        Thread.currentThread().setContextClassLoader(archetypeJarLoader);
        if (archetypeDescriptor.isPartial()) {
            getLogger().debug("Processing partial archetype " + archetypeDescriptor.getName());
            if (outputDirectoryFile.exists()) {
                if (!pom.exists()) {
                    throw new PomFileExists("This is a partial archetype and the pom.xml file doesn't exist.");
                }
                processPomWithMerge(context, pom, "");
                processArchetypeTemplatesWithWarning(archetypeDescriptor, archetypeResources, archetypeZipFile, "", context, packageName, outputDirectoryFile);
            } else {
                if (basedirPom.exists()) {
                    processPomWithMerge(context, basedirPom, "");
                    processArchetypeTemplatesWithWarning(archetypeDescriptor, archetypeResources, archetypeZipFile, "", context, packageName, new File(request.getOutputDirectory()));
                } else {
                    processPom(context, pom, "");
                    processArchetypeTemplates(archetypeDescriptor, archetypeResources, archetypeZipFile, "", context, packageName, outputDirectoryFile);
                }
            }
            if (archetypeDescriptor.getModules().size() > 0) {
                getLogger().info("Modules ignored in partial mode");
            }
        } else {
            getLogger().debug("Processing complete archetype " + archetypeDescriptor.getName());
            if (outputDirectoryFile.exists() && pom.exists()) {
                throw new ProjectDirectoryExists("A Maven 2 project already exists in the directory " + outputDirectoryFile.getPath());
            }
            if (outputDirectoryFile.exists()) {
                getLogger().warn("The directory " + outputDirectoryFile.getPath() + " already exists.");
            }
            context.put("rootArtifactId", artifactId);
            processFilesetModule(artifactId, artifactId, archetypeResources, pom, archetypeZipFile, "", basedirPom, outputDirectoryFile, packageName, archetypeDescriptor, context);
        }
        String postGenerationScript = archetypeArtifactManager.getPostGenerationScript(archetypeFile);
        if (postGenerationScript != null) {
            getLogger().info("Executing " + Constants.ARCHETYPE_POST_GENERATION_SCRIPT + " post-generation script");
            Binding binding = new Binding();
            final Properties archetypeGeneratorProperties = new Properties();
            archetypeGeneratorProperties.putAll(System.getProperties());
            if (request.getProperties() != null) {
                archetypeGeneratorProperties.putAll(request.getProperties());
            }
            for (Map.Entry<Object, Object> entry : archetypeGeneratorProperties.entrySet()) {
                binding.setVariable(entry.getKey().toString(), entry.getValue());
            }
            binding.setVariable("request", request);
            GroovyShell shell = new GroovyShell(binding);
            shell.evaluate(postGenerationScript);
        }
        // ----------------------------------------------------------------------
        if (getLogger().isInfoEnabled()) {
            getLogger().info("Project created from Archetype in dir: " + outputDirectoryFile.getAbsolutePath());
        }
    } catch (FileNotFoundException ex) {
        throw new ArchetypeGenerationFailure(ex);
    } catch (IOException ex) {
        throw new ArchetypeGenerationFailure(ex);
    } catch (XmlPullParserException ex) {
        throw new ArchetypeGenerationFailure(ex);
    } catch (DocumentException ex) {
        throw new ArchetypeGenerationFailure(ex);
    } catch (ArchetypeGenerationFailure ex) {
        throw new ArchetypeGenerationFailure(ex);
    } catch (InvalidPackaging ex) {
        throw new ArchetypeGenerationFailure(ex);
    } finally {
        Thread.currentThread().setContextClassLoader(old);
    }
}
Also used : ArrayList(java.util.ArrayList) FileNotFoundException(java.io.FileNotFoundException) Properties(java.util.Properties) ArchetypeNotConfigured(org.apache.maven.archetype.exception.ArchetypeNotConfigured) RequiredProperty(org.apache.maven.archetype.metadata.RequiredProperty) DocumentException(org.dom4j.DocumentException) PomFileExists(org.apache.maven.archetype.exception.PomFileExists) XmlPullParserException(org.codehaus.plexus.util.xml.pull.XmlPullParserException) ProjectDirectoryExists(org.apache.maven.archetype.exception.ProjectDirectoryExists) Context(org.apache.velocity.context.Context) VelocityContext(org.apache.velocity.VelocityContext) Binding(groovy.lang.Binding) InvalidPackaging(org.apache.maven.archetype.exception.InvalidPackaging) IOException(java.io.IOException) AbstractArchetypeDescriptor(org.apache.maven.archetype.metadata.AbstractArchetypeDescriptor) ArchetypeDescriptor(org.apache.maven.archetype.metadata.ArchetypeDescriptor) GroovyShell(groovy.lang.GroovyShell) ZipFile(java.util.zip.ZipFile) ZipFile(java.util.zip.ZipFile) File(java.io.File) Map(java.util.Map) ArchetypeGenerationFailure(org.apache.maven.archetype.exception.ArchetypeGenerationFailure)

Example 43 with DocumentException

use of org.dom4j.DocumentException in project azure-tools-for-java by Microsoft.

the class AddDependencyAction method applyVersionChanges.

private static boolean applyVersionChanges(SpringCloudDependencyManager dependencyManager, File pomFile, String springBootVer, Map<String, DependencyArtifact> managerDependencyVersionsMaps, List<DependencyArtifact> versionChanges) throws IOException, DocumentException {
    versionChanges.stream().filter(change -> managerDependencyVersionsMaps.containsKey(change.getKey())).forEach(change -> {
        String managementVersion = managerDependencyVersionsMaps.get(change.getKey()).getCurrentVersion();
        if (StringUtils.equals(change.getCompatibleVersion(), managementVersion) || SpringCloudDependencyManager.isCompatibleVersion(managementVersion, springBootVer)) {
            change.setCompatibleVersion("");
            change.setManagementVersion(managementVersion);
        }
    });
    return dependencyManager.update(pomFile, versionChanges);
}
Also used : AzureExecutionException(com.microsoft.azure.toolkit.lib.common.exception.AzureExecutionException) VirtualFile(com.intellij.openapi.vfs.VirtualFile) PluginUtil(com.microsoft.intellij.util.PluginUtil) Presentation(com.intellij.openapi.actionSystem.Presentation) AzureOperationBundle(com.microsoft.azure.toolkit.lib.common.operation.AzureOperationBundle) SettableFuture(com.google.common.util.concurrent.SettableFuture) StringUtils(org.apache.commons.lang3.StringUtils) AzureTask(com.microsoft.azure.toolkit.lib.common.task.AzureTask) ArrayList(java.util.ArrayList) FileEditorManager(com.intellij.openapi.fileEditor.FileEditorManager) RefreshQueue(com.intellij.openapi.vfs.newvfs.RefreshQueue) DocumentException(org.dom4j.DocumentException) ProjectNotificationAware(com.intellij.openapi.externalSystem.autoimport.ProjectNotificationAware) MavenArtifact(org.jetbrains.idea.maven.model.MavenArtifact) Map(java.util.Map) AzureAnAction(com.microsoft.intellij.AzureAnAction) Project(com.intellij.openapi.project.Project) PsiFile(com.intellij.psi.PsiFile) AzureString(com.microsoft.azure.toolkit.lib.common.bundle.AzureString) CommonDataKeys(com.intellij.openapi.actionSystem.CommonDataKeys) Module(com.intellij.openapi.module.Module) ModuleTypeId(com.intellij.openapi.module.ModuleTypeId) ProgressManager(com.intellij.openapi.progress.ProgressManager) MavenProject(org.jetbrains.idea.maven.project.MavenProject) MavenProcessCanceledException(org.jetbrains.idea.maven.utils.MavenProcessCanceledException) Operation(com.microsoft.azuretools.telemetrywrapper.Operation) IOException(java.io.IOException) EditorKind(com.intellij.openapi.editor.EditorKind) ExternalSystemProjectTracker(com.intellij.openapi.externalSystem.autoimport.ExternalSystemProjectTracker) Editor(com.intellij.openapi.editor.Editor) LocalFileSystem(com.intellij.openapi.vfs.LocalFileSystem) File(java.io.File) MavenProjectsManager(org.jetbrains.idea.maven.project.MavenProjectsManager) ExecutionException(java.util.concurrent.ExecutionException) Nullable(org.jetbrains.annotations.Nullable) ProgressIndicator(com.intellij.openapi.progress.ProgressIndicator) List(java.util.List) MavenUtils(com.microsoft.intellij.util.MavenUtils) TelemetryConstants(com.microsoft.azuretools.telemetry.TelemetryConstants) AnActionEvent(com.intellij.openapi.actionSystem.AnActionEvent) LangDataKeys(com.intellij.openapi.actionSystem.LangDataKeys) NotNull(org.jetbrains.annotations.NotNull) Collections(java.util.Collections) AzureTaskManager(com.microsoft.azure.toolkit.lib.common.task.AzureTaskManager) AzureString(com.microsoft.azure.toolkit.lib.common.bundle.AzureString)

Example 44 with DocumentException

use of org.dom4j.DocumentException in project mustangproject by ZUGFeRD.

the class ZUGFeRDValidator method validate.

/**
 * performs a validation on the file filename
 *
 * @param filename the complete absolute filename of a PDF or XML
 * @return a xml string with the validation result
 */
public String validate(String filename) {
    boolean xmlValidity;
    context.clear();
    StringBuffer finalStringResult = new StringBuffer();
    SimpleDateFormat isoDF = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    Date date = new Date();
    startTime = Calendar.getInstance().getTimeInMillis();
    try {
        Path path = Paths.get(filename);
        // set filename without path
        context.setFilename(path.getFileName().toString());
    } catch (NullPointerException ex) {
    // ignore
    }
    finalStringResult.append("<validation filename='" + context.getFilename() + "' datetime='" + isoDF.format(date) + "'>");
    boolean isPDF = false;
    try {
        if (filename == null) {
            optionsRecognized = false;
            context.addResultItem(new ValidationResultItem(ESeverity.fatal, "Filename not specified").setSection(10).setPart(EPart.pdf));
        }
        PDFValidator pdfv = new PDFValidator(context);
        File file = new File(filename);
        if (!file.exists()) {
            context.addResultItem(new ValidationResultItem(ESeverity.fatal, "File not found").setSection(1).setPart(EPart.pdf));
        } else if (file.length() < 32) {
            // with less then 32 bytes it can not even be a proper XML file
            context.addResultItem(new ValidationResultItem(ESeverity.fatal, "File too small").setSection(5).setPart(EPart.pdf));
        } else {
            BigFileSearcher searcher = new BigFileSearcher();
            XMLValidator xv = new XMLValidator(context);
            if (disableNotices) {
                xv.disableNotices();
            }
            byte[] pdfSignature = { '%', 'P', 'D', 'F' };
            isPDF = searcher.indexOf(file, pdfSignature) == 0;
            if (isPDF) {
                pdfv.setFilename(filename);
                optionsRecognized = true;
                try {
                    if (!file.exists()) {
                        context.addResultItem(new ValidationResultItem(ESeverity.exception, "File " + filename + " not found").setSection(1));
                    }
                } catch (IrrecoverableValidationError irx) {
                // @todo log
                }
                finalStringResult.append("<pdf>");
                optionsRecognized = true;
                try {
                    pdfv.validate();
                    sha1Checksum = calcSHA1(file);
                    // Validate PDF
                    finalStringResult.append(pdfv.getXMLResult());
                    pdfValidity = context.isValid();
                    Signature = context.getSignature();
                    // clear sets valid to true again
                    context.clear();
                    if (pdfv.getRawXML() != null) {
                        xv.setStringContent(pdfv.getRawXML());
                        displayXMLValidationOutput = true;
                    } else {
                        context.addResultItem(new ValidationResultItem(ESeverity.exception, "XML could not be extracted").setSection(17));
                    }
                } catch (IrrecoverableValidationError irx) {
                // @todo log
                }
                finalStringResult.append("</pdf>\n");
                context.clearCustomXML();
            } else {
                boolean isXML = false;
                try {
                    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
                    DocumentBuilder db = dbf.newDocumentBuilder();
                    byte[] content = Files.readAllBytes(file.toPath());
                    content = XMLTools.removeBOM(content);
                    String s = new String(content, StandardCharsets.UTF_8);
                    InputSource is = new InputSource(new StringReader(s));
                    Document doc = db.parse(is);
                    Element root = doc.getDocumentElement();
                    // no exception so far
                    isXML = true;
                } catch (Exception ex) {
                // probably no xml file, sth like SAXParseException content not allowed in prolog
                // ignore isXML is already false
                // in the tests, this may error-out anyway
                // ex.printStackTrace();
                }
                if (isXML) {
                    pdfValidity = true;
                    optionsRecognized = true;
                    xv.setFilename(filename);
                    if (file.exists()) {
                        sha1Checksum = calcSHA1(file);
                    }
                    displayXMLValidationOutput = true;
                } else {
                    optionsRecognized = false;
                    context.addResultItem(new ValidationResultItem(ESeverity.exception, "File does not look like PDF nor XML (contains neither %PDF nor <?xml)").setSection(8));
                }
            }
            if ((optionsRecognized) && (displayXMLValidationOutput)) {
                finalStringResult.append("<xml>");
                try {
                    xv.validate();
                } catch (IrrecoverableValidationError irx) {
                // @todo log
                }
                finalStringResult.append(xv.getXMLResult());
                finalStringResult.append("</xml>");
                context.clearCustomXML();
            }
            if ((isPDF) && (!pdfValidity)) {
                context.setInvalid();
            }
        }
    } catch (IrrecoverableValidationError irx) {
    // @todo log
    } finally {
        finalStringResult.append(context.getXMLResult());
        finalStringResult.append("</validation>");
    }
    OutputFormat format = OutputFormat.createPrettyPrint();
    StringWriter sw = new StringWriter();
    org.dom4j.Document document = null;
    try {
        document = DocumentHelper.parseText(new String(finalStringResult));
    } catch (DocumentException e1) {
        LOGGER.error(e1.getMessage());
    }
    XMLWriter writer = new XMLWriter(sw, format);
    try {
        writer.write(document);
    } catch (Exception e) {
        LOGGER.error(e.getMessage());
    }
    xmlValidity = context.isValid();
    long duration = Calendar.getInstance().getTimeInMillis() - startTime;
    String toBeAppended = "";
    if (logAppend != null) {
        toBeAppended = logAppend;
    }
    String pdfResult = "invalid";
    if (!isPDF) {
        pdfResult = "absent";
    } else if (pdfValidity) {
        pdfResult = "valid";
    }
    LOGGER.info("Parsed PDF:" + pdfResult + " XML:" + (xmlValidity ? "valid" : "invalid") + " Signature:" + Signature + " Checksum:" + sha1Checksum + " Profile:" + context.getProfile() + " Version:" + context.getGeneration() + " Took:" + duration + "ms Errors:[" + context.getCSVResult() + "] " + toBeAppended);
    wasCompletelyValid = ((pdfValidity) && (xmlValidity));
    return sw.toString();
}
Also used : InputSource(org.xml.sax.InputSource) DocumentBuilderFactory(javax.xml.parsers.DocumentBuilderFactory) Element(org.w3c.dom.Element) Document(org.w3c.dom.Document) XMLWriter(org.dom4j.io.XMLWriter) DocumentException(org.dom4j.DocumentException) BigFileSearcher(org.riversun.bigdoc.bin.BigFileSearcher) Path(java.nio.file.Path) OutputFormat(org.dom4j.io.OutputFormat) Date(java.util.Date) DocumentException(org.dom4j.DocumentException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) DocumentBuilder(javax.xml.parsers.DocumentBuilder) SimpleDateFormat(java.text.SimpleDateFormat)

Example 45 with DocumentException

use of org.dom4j.DocumentException in project mustangproject by ZUGFeRD.

the class ZUGFeRD1PullProvider method getXML.

@Override
public byte[] getXML() {
    byte[] res = zugferdData;
    final StringWriter sw = new StringWriter();
    Document document = null;
    try {
        document = DocumentHelper.parseText(new String(zugferdData));
    } catch (final DocumentException e1) {
        Logger.getLogger(ZUGFeRD1PullProvider.class.getName()).log(Level.SEVERE, null, e1);
    }
    try {
        final OutputFormat format = OutputFormat.createPrettyPrint();
        format.setTrimText(false);
        final XMLWriter writer = new XMLWriter(sw, format);
        writer.write(document);
        res = sw.toString().getBytes("UTF-8");
    } catch (final IOException e) {
        Logger.getLogger(ZUGFeRD1PullProvider.class.getName()).log(Level.SEVERE, null, e);
    }
    return res;
}
Also used : StringWriter(java.io.StringWriter) DocumentException(org.dom4j.DocumentException) OutputFormat(org.dom4j.io.OutputFormat) IOException(java.io.IOException) Document(org.dom4j.Document) XMLWriter(org.dom4j.io.XMLWriter)

Aggregations

DocumentException (org.dom4j.DocumentException)123 Document (org.dom4j.Document)80 SAXReader (org.dom4j.io.SAXReader)73 Element (org.dom4j.Element)51 IOException (java.io.IOException)45 File (java.io.File)27 InputStream (java.io.InputStream)21 StringReader (java.io.StringReader)15 InputStreamReader (java.io.InputStreamReader)11 ArrayList (java.util.ArrayList)10 XMLWriter (org.dom4j.io.XMLWriter)9 InputSource (org.xml.sax.InputSource)9 FileInputStream (java.io.FileInputStream)7 URL (java.net.URL)7 List (java.util.List)7 Node (org.dom4j.Node)7 ByteArrayInputStream (java.io.ByteArrayInputStream)6 UnsupportedEncodingException (java.io.UnsupportedEncodingException)6 FileNotFoundException (java.io.FileNotFoundException)5 Reader (java.io.Reader)5