Example usage for javax.xml.parsers DocumentBuilderFactory setFeature

List of usage examples for javax.xml.parsers DocumentBuilderFactory setFeature

Introduction

In this page you can find the example usage for javax.xml.parsers DocumentBuilderFactory setFeature.

Prototype

public abstract void setFeature(String name, boolean value) throws ParserConfigurationException;

Source Link

Document

Set a feature for this DocumentBuilderFactory and DocumentBuilder s created by this factory.

Usage

From source file:org.asqatasun.processor.DOMHandlerImpl.java

private void initialize() {
    if (docInitialised) {
        return;//from  ww w  .  j a v  a 2 s . c  o m
    }
    XPathFactory xPathfactory = XPathFactory.newInstance();
    xpath = xPathfactory.newXPath();

    try {

        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        factory.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false);
        //@TODO verify the namespace property is necessary in our context
        //            factory.setNamespaceAware(true);
        DocumentBuilder builder = factory.newDocumentBuilder();
        document = builder.parse(new ByteArrayInputStream(ssp.getDOM().getBytes("UTF-8")));
        docInitialised = true;
    } catch (IOException ex) {
        LOGGER.error(ssp.getURI() + "cannot be initialised due to " + ex.getMessage());
        throw new RuntimeException(ex);
    } catch (SAXException ex) {
        LOGGER.error(ssp.getURI() + "cannot be initialised due to " + ex.getMessage());
        throw new RuntimeException(ex);
    } catch (ParserConfigurationException ex) {
        LOGGER.error(ssp.getURI() + "cannot be initialised due to " + ex.getMessage());
        throw new RuntimeException(ex);
    }
    processRemarkService.initializeService(document, ssp.getDOM());
}

From source file:org.carewebframework.common.XMLUtil.java

private static void initFactory(DocumentBuilderFactory factory, boolean nsAware) {
    try {//from ww w  .  j a v  a 2 s  .c  om
        factory.setNamespaceAware(nsAware);
        factory.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false);
    } catch (ParserConfigurationException e) {
    }
}

From source file:org.codehaus.mojo.nbm.CreateWebstartAppMojo.java

/**
 *
 * @throws org.apache.maven.plugin.MojoExecutionException
 * @throws org.apache.maven.plugin.MojoFailureException
 *//*from ww  w .  ja  v a2s.  c  o m*/
@Override
public void execute() throws MojoExecutionException, MojoFailureException {
    if ("none".equalsIgnoreCase(includeLocales)) {
        includeLocales = "";
    }

    if (signingThreads < 1) {
        signingThreads = Runtime.getRuntime().availableProcessors();
    }

    if ((signingMaximumThreads > 0) && (signingThreads > signingMaximumThreads)) {
        signingThreads = signingMaximumThreads;
    }

    getLog().info("Using " + signingThreads + " signing threads.");

    if (!"nbm-application".equals(project.getPackaging())) {
        throw new MojoExecutionException(
                "This goal only makes sense on project with nbm-application packaging.");
    }

    final Project antProject = antProject();

    getLog().warn(
            "WARNING: Unsigned and self-signed WebStart applications are deprecated from JDK7u21 onwards. To ensure future correct functionality please use trusted certificate.");

    if (keystore != null && keystorealias != null && keystorepassword != null) {
        File ks = new File(keystore);
        if (!ks.exists()) {
            throw new MojoFailureException("Cannot find keystore file at " + ks.getAbsolutePath());
        } else {
            //proceed..
        }
    } else if (keystore != null || keystorepassword != null || keystorealias != null) {
        throw new MojoFailureException(
                "If you want to sign the jnlp application, you need to define all three keystore related parameters.");
    } else {
        File generatedKeystore = new File(outputDirectory, "generated.keystore");
        if (!generatedKeystore.exists()) {
            getLog().warn("Keystore related parameters not set, generating a default keystore.");
            GenerateKey genTask = (GenerateKey) antProject.createTask("genkey");
            genTask.setAlias("jnlp");
            genTask.setStorepass("netbeans");
            genTask.setDname("CN=" + System.getProperty("user.name"));
            genTask.setKeystore(generatedKeystore.getAbsolutePath());
            genTask.execute();
        }
        keystore = generatedKeystore.getAbsolutePath();
        keystorepassword = "netbeans";
        keystorealias = "jnlp";
    }

    Taskdef taskdef = (Taskdef) antProject.createTask("taskdef");
    taskdef.setClassname(MakeJnlp2.class.getName());
    taskdef.setName("makejnlp");
    taskdef.execute();

    taskdef = (Taskdef) antProject.createTask("taskdef");
    taskdef.setClassname(Jar.class.getName());
    taskdef.setName("jar");
    taskdef.execute();

    taskdef = (Taskdef) antProject.createTask("taskdef");
    taskdef.setClassname(VerifyJNLP.class.getName());
    taskdef.setName("verifyjnlp");
    taskdef.execute();
    // +p

    try {
        final File webstartBuildDir = new File(
                outputDirectory + File.separator + "webstart" + File.separator + brandingToken);

        if (webstartBuildDir.exists()) {
            FileUtils.deleteDirectory(webstartBuildDir);
        }

        webstartBuildDir.mkdirs();

        // P: copy webappResources --[

        MavenResourcesExecution mavenResourcesExecution = new MavenResourcesExecution(webappResources,
                webstartBuildDir, project, encoding, Collections.EMPTY_LIST, Collections.EMPTY_LIST, session);
        mavenResourcesExecution.setEscapeWindowsPaths(true);
        mavenResourcesFiltering.filterResources(mavenResourcesExecution);

        // ]--

        final String localCodebase = codebase != null ? codebase : webstartBuildDir.toURI().toString();
        getLog().info("Generating webstartable binaries at " + webstartBuildDir.getAbsolutePath());

        final File nbmBuildDirFile = new File(outputDirectory, brandingToken);

        // +p (needs to be before make jnlp)

        //TODO is it really netbeans/
        if (masterJnlpFileName == null) {
            masterJnlpFileName = brandingToken;
        }

        Properties props = new Properties();
        props.setProperty("jnlp.codebase", localCodebase);
        props.setProperty("app.name", brandingToken);
        props.setProperty("app.title", project.getName());
        if (project.getOrganization() != null) {
            props.setProperty("app.vendor", project.getOrganization().getName());
        } else {
            props.setProperty("app.vendor", "Nobody");
        }
        String description = project.getDescription() != null ? project.getDescription()
                : "No Project Description";
        props.setProperty("app.description", description);
        props.setProperty("branding.token", brandingToken);
        props.setProperty("master.jnlp.file.name", masterJnlpFileName);
        props.setProperty("netbeans.jnlp.fixPolicy", "false");

        StringBuilder stBuilder = new StringBuilder();
        if (additionalArguments != null) {
            StringTokenizer st = new StringTokenizer(additionalArguments);
            while (st.hasMoreTokens()) {
                String arg = st.nextToken();
                if (arg.startsWith("-J")) {
                    if (stBuilder.length() > 0) {
                        stBuilder.append(' ');
                    }
                    stBuilder.append(arg.substring(2));
                }
            }
        }
        props.setProperty("netbeans.run.params", stBuilder.toString());

        final File masterJnlp = new File(webstartBuildDir, masterJnlpFileName + ".jnlp");

        filterCopy(masterJnlpFile, "master.jnlp", masterJnlp, props);

        if (generateJnlpTimestamp) //  \/\/\/\/  bad bad bad  \/\/\/\/
        {
            final File masterJnlpFileTmp = File.createTempFile(masterJnlpFileName + "_", "");

            Files.append(JnlpUtils.getCurrentJnlpTimestamp() + "\n", masterJnlpFileTmp,
                    Charset.forName("UTF-8"));

            ByteSink sink = Files.asByteSink(masterJnlpFileTmp, FileWriteMode.APPEND);

            sink.write(Files.toByteArray(masterJnlp));

            Files.copy(masterJnlpFileTmp, masterJnlp);
        }

        File startup = copyLauncher(outputDirectory, nbmBuildDirFile);

        String masterJnlpStr = FileUtils.fileRead(masterJnlp);

        // P: JNLP-INF/APPLICATION_TEMPLATE.JNLP support --[
        // this can be done better and will
        // ashamed
        if (generateJnlpApplicationTemplate) {
            File jnlpInfDir = new File(outputDirectory, "JNLP-INF");

            getLog().info("Generate JNLP application template under: " + jnlpInfDir);

            jnlpInfDir.mkdirs();

            File jnlpTemplate = new File(jnlpInfDir, "APPLICATION_TEMPLATE.JNLP");

            masterJnlpStr = masterJnlpStr.replaceAll("(<jnlp.*codebase\\ *=\\ *)\"((?!\").)*", "$1\"*")
                    .replaceAll("(<jnlp.*href\\ *=\\ *)\"((?!\").)*", "$1\"*");

            FileUtils.fileWrite(jnlpTemplate, masterJnlpStr);

            File startupMerged = new File(outputDirectory, "startup-jnlpinf.jar");

            Jar jar = (Jar) antProject.createTask("jar");
            jar.setDestFile(startupMerged);
            jar.setFilesetmanifest((FilesetManifestConfig) EnumeratedAttribute
                    .getInstance(FilesetManifestConfig.class, "merge"));

            FileSet jnlpInfDirectoryFileSet = new FileSet();
            jnlpInfDirectoryFileSet.setDir(outputDirectory);
            jnlpInfDirectoryFileSet.setIncludes("JNLP-INF/**");

            jar.addFileset(jnlpInfDirectoryFileSet);

            ZipFileSet startupJar = new ZipFileSet();
            startupJar.setSrc(startup);

            jar.addZipfileset(startupJar);

            jar.execute();

            startup = startupMerged;

            getLog().info("APPLICATION_TEMPLATE.JNLP generated - startup.jar: " + startup);
        }

        final JarsConfig startupConfig = new JarsConfig();

        ManifestEntries startupManifestEntries = new ManifestEntries();

        startupConfig.setManifestEntries(startupManifestEntries);

        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();

        if (!validateJnlpDtd) {
            factory.setValidating(false);
            factory.setNamespaceAware(true);
            factory.setFeature("http://xml.org/sax/features/namespaces", false);
            factory.setFeature("http://xml.org/sax/features/validation", false);
            factory.setFeature("http://apache.org/xml/features/nonvalidating/load-dtd-grammar", false);
            factory.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false);
        }
        DocumentBuilder builder = factory.newDocumentBuilder();

        final BufferedReader masterJnlpStrReader = new BufferedReader(new StringReader(masterJnlpStr));

        if (generateJnlpTimestamp) {
            masterJnlpStrReader.readLine();
        }

        Document doc = builder.parse(new InputSource(masterJnlpStrReader));

        Element jnlpRoot = doc.getDocumentElement();

        jarCodebase = jnlpRoot.getAttribute("codebase");

        if (jarCodebase.isEmpty()) {
            jarCodebase = "*";
        }

        startupManifestEntries.setCodebase(jarCodebase);

        XPath xpath = XPathFactory.newInstance().newXPath();

        Node jnlpSecurityPermission = (Node) xpath.evaluate(
                "(/jnlp/security/all-permissions | /jnlp/security/j2ee-application-client-permissions)[1]", doc,
                XPathConstants.NODE);

        if (jnlpSecurityPermission == null) {
            jarPermissions = "sandbox";
            jnlpSecurity = "";
        } else {
            jarPermissions = "all-permissions";
            jnlpSecurity = "<security><" + jnlpSecurityPermission.getNodeName() + "/></security>";
        }

        startupManifestEntries.setPermissions(jarPermissions);

        if (applicationName == null) {
            String jnlpApplicationTitle = (String) xpath.evaluate("/jnlp/information/title", doc,
                    XPathConstants.STRING);

            applicationName = jnlpApplicationTitle == null ? brandingToken : jnlpApplicationTitle;
        }

        startupManifestEntries.setApplicationName(applicationName);

        // +p

        if (autoManifestSecurityEntries) {
            if (jarsConfigs == null) {
                jarsConfigs = new ArrayList<JarsConfig>();
            }

            jarsConfigs.add(0, startupConfig);
        }

        final List<SignJar.JarsConfig> signJarJarsConfigs = buildSignJarJarsConfigs(jarsConfigs);

        File jnlpDestination = new File(webstartBuildDir.getAbsolutePath() + File.separator + "startup.jar");

        SignJar signTask = (SignJar) antProject.createTask("signjar");
        signTask.setKeystore(keystore);
        signTask.setStorepass(keystorepassword);
        signTask.setAlias(keystorealias);

        if (keystoretype != null) {
            signTask.setStoretype(keystoretype);
        }

        signTask.setForce(signingForce);
        signTask.setTsacert(signingTsaCert);
        signTask.setTsaurl(signingTsaUrl);
        signTask.setMaxmemory(signingMaxMemory);
        signTask.setRetryCount(signingRetryCount);

        signTask.setUnsignFirst(signingRemoveExistingSignatures);

        signTask.setJarsConfigs(buildSignJarJarsConfigs(Collections.singletonList(startupConfig)));

        signTask.setBasedir(nbmBuildDirFile);

        signTask.setSignedjar(jnlpDestination);

        signTask.setJar(startup);

        signTask.setPack200(pack200);
        signTask.setPack200Effort(pack200Effort);

        signTask.execute();
        // <-- all of this will be refactored soon ]--

        //            FileUtils.copyDirectoryStructureIfModified( nbmBuildDirFile, webstartBuildDir );

        MakeJnlp2 jnlpTask = (MakeJnlp2) antProject.createTask("makejnlp");
        jnlpTask.setOptimize(optimize);
        jnlpTask.setIncludelocales(includeLocales);
        jnlpTask.setDir(webstartBuildDir);
        jnlpTask.setCodebase(localCodebase);
        //TODO, how to figure verify excludes..
        jnlpTask.setVerify(false);
        jnlpTask.setPermissions(jnlpSecurity);
        jnlpTask.setSignJars(true);

        jnlpTask.setAlias(keystorealias);
        jnlpTask.setKeystore(keystore);
        jnlpTask.setStorePass(keystorepassword);
        if (keystoretype != null) {
            jnlpTask.setStoreType(keystoretype);
        }

        jnlpTask.setSigningForce(signingForce);
        jnlpTask.setSigningTsaCert(signingTsaCert);
        jnlpTask.setSigningTsaUrl(signingTsaUrl);
        jnlpTask.setUnsignFirst(signingRemoveExistingSignatures);
        jnlpTask.setJarsConfigs(signJarJarsConfigs);
        jnlpTask.setSigningMaxMemory(signingMaxMemory);
        jnlpTask.setSigningRetryCount(signingRetryCount);
        jnlpTask.setBasedir(nbmBuildDirFile);

        jnlpTask.setNbThreads(signingThreads);

        jnlpTask.setProcessJarVersions(processJarVersions);

        jnlpTask.setPack200(pack200);
        jnlpTask.setPack200Effort(pack200Effort);

        FileSet fs = jnlpTask.createModules();
        fs.setDir(nbmBuildDirFile);
        OrSelector or = new OrSelector();
        AndSelector and = new AndSelector();
        FilenameSelector inc = new FilenameSelector();
        inc.setName("*/modules/**/*.jar");
        or.addFilename(inc);
        inc = new FilenameSelector();
        inc.setName("*/lib/**/*.jar");
        or.addFilename(inc);
        inc = new FilenameSelector();
        inc.setName("*/core/**/*.jar");
        or.addFilename(inc);

        ModuleSelector ms = new ModuleSelector();
        Parameter included = new Parameter();
        included.setName("includeClusters");
        included.setValue("");
        Parameter excluded = new Parameter();
        excluded.setName("excludeClusters");
        excluded.setValue("");
        Parameter exModules = new Parameter();
        exModules.setName("excludeModules");
        exModules.setValue("");
        ms.setParameters(new Parameter[] { included, excluded, exModules });
        and.add(or);
        and.add(ms);
        fs.addAnd(and);
        jnlpTask.execute();

        Set<String> locales = jnlpTask.getExecutedLocales();

        String extSnippet = generateExtensions(fs, antProject, ""); // "netbeans/"

        //branding
        DirectoryScanner ds = new DirectoryScanner();
        ds.setBasedir(nbmBuildDirFile);

        final List<String> localeIncludes = new ArrayList<String>();
        final List<String> localeExcludes = new ArrayList<String>();

        localeIncludes.add("**/locale/*.jar");

        if (includeLocales != null) {
            List<String> excludes = Splitter.on(',').trimResults().omitEmptyStrings()
                    .splitToList(includeLocales);

            for (String exclude : (Collection<String>) CollectionUtils.subtract(locales, excludes)) {
                localeExcludes.add("**/locale/*_" + exclude + ".jar");
            }
        }

        ds.setIncludes(localeIncludes.toArray(new String[localeIncludes.size()]));
        ds.setExcludes(localeExcludes.toArray(new String[localeExcludes.size()]));
        ds.scan();
        String[] includes = ds.getIncludedFiles();

        StringBuilder brandRefs = new StringBuilder(
                "<property name=\"jnlp.packEnabled\" value=\"" + String.valueOf(pack200) + "\"/>\n");

        if (includes != null && includes.length > 0) {
            final File brandingDir = new File(webstartBuildDir, "branding");
            brandingDir.mkdirs();
            for (String incBran : includes) {
                File source = new File(nbmBuildDirFile, incBran);
                File dest = new File(brandingDir, source.getName());
                brandRefs.append("    <jar href=\'branding/").append(dest.getName()).append("\'/>\n");
            }

            final ExecutorService executorService = Executors.newFixedThreadPool(signingThreads);

            final List<Exception> threadException = new ArrayList<Exception>();

            for (final String toSign : includes) {
                executorService.execute(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            File toSignFile = new File(nbmBuildDirFile, toSign);

                            SignJar signTask = (SignJar) antProject.createTask("signjar");
                            if (keystoretype != null) {
                                signTask.setStoretype(keystoretype);
                            }
                            signTask.setKeystore(keystore);
                            signTask.setStorepass(keystorepassword);
                            signTask.setAlias(keystorealias);
                            signTask.setForce(signingForce);
                            signTask.setTsacert(signingTsaCert);
                            signTask.setTsaurl(signingTsaUrl);
                            signTask.setMaxmemory(signingMaxMemory);
                            signTask.setRetryCount(signingRetryCount);
                            signTask.setUnsignFirst(signingRemoveExistingSignatures);
                            signTask.setJarsConfigs(signJarJarsConfigs);
                            signTask.setJar(toSignFile);
                            signTask.setDestDir(brandingDir);
                            signTask.setBasedir(nbmBuildDirFile);
                            signTask.setDestFlatten(true);
                            signTask.setPack200(pack200);
                            signTask.setPack200Effort(pack200Effort);
                            signTask.execute();
                        } catch (Exception e) {
                            threadException.add(e);
                        }
                    }
                });
            }

            executorService.shutdown();

            executorService.awaitTermination(Long.MAX_VALUE, TimeUnit.NANOSECONDS);

            if (!threadException.isEmpty()) {
                throw threadException.get(0);
            }
        }

        File modulesJnlp = new File(webstartBuildDir.getAbsolutePath() + File.separator + "modules.jnlp");
        props.setProperty("jnlp.branding.jars", brandRefs.toString());
        props.setProperty("jnlp.resources", extSnippet);
        filterCopy(null, /* filename is historical */"branding.jnlp", modulesJnlp, props);

        if (verifyJnlp) {
            getLog().info("Verifying generated webstartable content.");
            VerifyJNLP verifyTask = (VerifyJNLP) antProject.createTask("verifyjnlp");
            FileSet verify = new FileSet();
            verify.setFile(masterJnlp);
            verifyTask.addConfiguredFileset(verify);
            verifyTask.execute();
        }

        // create zip archive
        if (destinationFile.exists()) {
            destinationFile.delete();
        }
        ZipArchiver archiver = new ZipArchiver();
        if (codebase != null) {
            getLog().warn("Defining <codebase>/${nbm.webstart.codebase} is generally unnecessary");
            archiver.addDirectory(webstartBuildDir);
        } else {
            archiver.addDirectory(webstartBuildDir, null, new String[] { "**/*.jnlp" });
            for (final File jnlp : webstartBuildDir.listFiles()) {
                if (!jnlp.getName().endsWith(".jnlp")) {
                    continue;
                }
                archiver.addResource(new PlexusIoResource() {
                    public @Override InputStream getContents() throws IOException {
                        return new ByteArrayInputStream(FileUtils.fileRead(jnlp, "UTF-8")
                                .replace(localCodebase, "$$codebase").getBytes("UTF-8"));
                    }

                    public @Override long getLastModified() {
                        return jnlp.lastModified();
                    }

                    public @Override boolean isExisting() {
                        return true;
                    }

                    public @Override long getSize() {
                        return UNKNOWN_RESOURCE_SIZE;
                    }

                    public @Override URL getURL() throws IOException {
                        return null;
                    }

                    public @Override String getName() {
                        return jnlp.getAbsolutePath();
                    }

                    public @Override boolean isFile() {
                        return true;
                    }

                    public @Override boolean isDirectory() {
                        return false;
                    }
                }, jnlp.getName(), archiver.getDefaultFileMode());
            }
        }
        File jdkhome = new File(System.getProperty("java.home"));
        File servlet = new File(jdkhome, "sample/jnlp/servlet/jnlp-servlet.jar");
        if (!servlet.exists()) {
            servlet = new File(jdkhome.getParentFile(), "sample/jnlp/servlet/jnlp-servlet.jar");

            if (!servlet.exists()) {
                servlet = File.createTempFile("nbm_", "jnlp-servlet.jar");

                FileUtils.copyURLToFile(
                        Thread.currentThread().getContextClassLoader().getResource("jnlp-servlet.jar"),
                        servlet);
            }
        }
        if (servlet.exists()) {
            File servletDir = new File(webstartBuildDir, "WEB-INF/lib");

            servletDir.mkdirs();

            signTask = (SignJar) antProject.createTask("signjar");
            signTask.setKeystore(keystore);
            signTask.setStorepass(keystorepassword);
            signTask.setAlias(keystorealias);
            signTask.setForce(signingForce);
            signTask.setTsacert(signingTsaCert);
            signTask.setTsaurl(signingTsaUrl);
            signTask.setMaxmemory(signingMaxMemory);
            signTask.setRetryCount(signingRetryCount);
            signTask.setJar(servlet);
            signTask.setSignedjar(new File(servletDir, "jnlp-servlet.jar"));
            signTask.execute();

            //archiver.addFile( servlet, "WEB-INF/lib/jnlp-servlet.jar" );
            archiver.addResource(new PlexusIoResource() {
                public @Override InputStream getContents() throws IOException {
                    return new ByteArrayInputStream(("" + "<web-app>\n" + "    <servlet>\n"
                            + "        <servlet-name>JnlpDownloadServlet</servlet-name>\n"
                            + "        <servlet-class>jnlp.sample.servlet.JnlpDownloadServlet</servlet-class>\n"
                            + "    </servlet>\n" + "    <servlet-mapping>\n"
                            + "        <servlet-name>JnlpDownloadServlet</servlet-name>\n"
                            + "        <url-pattern>*.jnlp</url-pattern>\n" + "    </servlet-mapping>\n"
                            + "    <servlet-mapping>\n"
                            + "        <servlet-name>JnlpDownloadServlet</servlet-name>\n"
                            + "        <url-pattern>*.jar</url-pattern>\n" + "    </servlet-mapping>\n"
                            + "    <mime-mapping>\n" + "        <extension>jnlp</extension>\n"
                            + "        <mime-type>application/x-java-jnlp-file</mime-type>\n"
                            + "    </mime-mapping>\n" + "</web-app>\n").getBytes());
                }

                public @Override long getLastModified() {
                    return UNKNOWN_MODIFICATION_DATE;
                }

                public @Override boolean isExisting() {
                    return true;
                }

                public @Override long getSize() {
                    return UNKNOWN_RESOURCE_SIZE;
                }

                public @Override URL getURL() throws IOException {
                    return null;
                }

                public @Override String getName() {
                    return "web.xml";
                }

                public @Override boolean isFile() {
                    return true;
                }

                public @Override boolean isDirectory() {
                    return false;
                }
            }, "WEB-INF/web.xml", archiver.getDefaultFileMode());
        }
        archiver.setDestFile(destinationFile);
        archiver.createArchive();

        if (signWar) {
            signTask = (SignJar) antProject.createTask("signjar");
            signTask.setKeystore(keystore);
            signTask.setStorepass(keystorepassword);
            signTask.setAlias(keystorealias);
            signTask.setForce(signingForce);
            signTask.setTsacert(signingTsaCert);
            signTask.setTsaurl(signingTsaUrl);
            signTask.setMaxmemory(signingMaxMemory);
            signTask.setRetryCount(signingRetryCount);
            signTask.setJar(destinationFile);
            signTask.execute();
        }

        // attach standalone so that it gets installed/deployed
        projectHelper.attachArtifact(project, "war", webstartClassifier, destinationFile);

    } catch (Exception ex) {
        throw new MojoExecutionException("Error creating webstartable binary.", ex);
    }
}

From source file:org.codelibs.robot.transformer.impl.XmlTransformer.java

@Override
public ResultData transform(final ResponseData responseData) {
    if (responseData == null || responseData.getResponseBody() == null) {
        throw new RobotCrawlAccessException("No response body.");
    }//from  w  w  w  .j  a v a2s  .  co  m

    final File tempFile = ResponseDataUtil.createResponseBodyFile(responseData);

    FileInputStream fis = null;

    try {
        fis = new FileInputStream(tempFile);
        final DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();

        for (final Map.Entry<String, Object> entry : attributeMap.entrySet()) {
            factory.setAttribute(entry.getKey(), entry.getValue());
        }

        for (final Map.Entry<String, String> entry : featureMap.entrySet()) {
            factory.setFeature(entry.getKey(), "true".equalsIgnoreCase(entry.getValue()));
        }

        factory.setCoalescing(coalescing);
        factory.setExpandEntityReferences(expandEntityRef);
        factory.setIgnoringComments(ignoringComments);
        factory.setIgnoringElementContentWhitespace(ignoringElementContentWhitespace);
        factory.setNamespaceAware(namespaceAware);
        factory.setValidating(validating);
        factory.setXIncludeAware(includeAware);

        final DocumentBuilder builder = factory.newDocumentBuilder();

        final Document doc = builder.parse(fis);

        final StringBuilder buf = new StringBuilder(1000);
        buf.append(getResultDataHeader());
        for (final Map.Entry<String, String> entry : fieldRuleMap.entrySet()) {
            final List<String> nodeStrList = new ArrayList<String>();
            try {
                final NodeList nodeList = getNodeList(doc, entry.getValue());
                for (int i = 0; i < nodeList.getLength(); i++) {
                    final Node node = nodeList.item(i);
                    nodeStrList.add(node.getTextContent());
                }
            } catch (final TransformerException e) {
                logger.warn("Could not parse a value of " + entry.getKey() + ":" + entry.getValue(), e);
            }
            if (nodeStrList.size() == 1) {
                buf.append(getResultDataBody(entry.getKey(), nodeStrList.get(0)));
            } else if (nodeStrList.size() > 1) {
                buf.append(getResultDataBody(entry.getKey(), nodeStrList));
            }
        }
        buf.append(getAdditionalData(responseData, doc));
        buf.append(getResultDataFooter());

        final ResultData resultData = new ResultData();
        resultData.setTransformerName(getName());

        try {
            resultData.setData(buf.toString().getBytes(charsetName));
        } catch (final UnsupportedEncodingException e) {
            if (logger.isInfoEnabled()) {
                logger.info("Invalid charsetName: " + charsetName + ". Changed to " + Constants.UTF_8, e);
            }
            charsetName = Constants.UTF_8_CHARSET.name();
            resultData.setData(buf.toString().getBytes(Constants.UTF_8_CHARSET));
        }
        resultData.setEncoding(charsetName);

        return resultData;
    } catch (final RobotSystemException e) {
        throw e;
    } catch (final Exception e) {
        throw new RobotSystemException("Could not store data.", e);
    } finally {
        IOUtils.closeQuietly(fis);
        // clean up
        if (!tempFile.delete()) {
            logger.warn("Could not delete a temp file: " + tempFile);
        }
    }
}

From source file:org.codice.alliance.catalog.transformer.mgmp.MgmpTransformer.java

private void addMetacardDataQuality(MetacardImpl metacard) {

    try (InputStream inputStream = getSourceInputStream()) {
        DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance();
        domFactory.setNamespaceAware(false);
        try {/*w  w  w .  ja  v a  2 s .co  m*/
            domFactory.setFeature("http://apache.org/xml/features/nonvalidating/load-dtd-grammar", false);
            domFactory.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false);
        } catch (ParserConfigurationException e) {
            LOGGER.debug("Unable to set features on document builder.", e);
        }
        DocumentBuilder builder = domFactory.newDocumentBuilder();
        Document document = builder.parse(inputStream);

        XPath xPath = XPathFactory.newInstance().newXPath();

        List<String> dataQualityList = new ArrayList<>();
        for (String string : MgmpConstants.DATA_QUALITY_LIST) {

            XPathExpression dataExpression = xPath.compile(string);
            NodeList dataList = (NodeList) dataExpression.evaluate(document, XPathConstants.NODESET);

            for (int i = 0; i < dataList.getLength(); i++) {
                String dataQualityName = null;
                String resultValue = null;

                NodeList children = dataList.item(i).getChildNodes();
                for (int c = 0; c < children.getLength(); c++) {
                    Node node = children.item(c);
                    String name = node.getNodeName();

                    switch (name) {
                    case MgmpConstants.RESULT:
                        NodeList childNodes = node.getChildNodes();
                        for (int x = 0; x < childNodes.getLength(); x++) {
                            Node resultNode = childNodes.item(x);
                            if (StringUtils.isEmpty(resultValue)) {
                                resultValue = getDataQualityResultValue(resultNode);
                            }
                        }
                        break;
                    case MgmpConstants.NAME_OF_MEASURE:
                        if (StringUtils.isEmpty(dataQualityName)) {
                            dataQualityName = node.getTextContent().trim();
                        }
                        break;

                    default:
                        break;
                    }
                }

                if (StringUtils.isNotEmpty(dataQualityName) && StringUtils.isNotEmpty(resultValue)) {
                    dataQualityList.add(dataQualityName + " : " + resultValue);
                }
            }
        }

        if (CollectionUtils.isNotEmpty(dataQualityList)) {
            metacard.setAttribute(Isr.DATA_QUALITY, (Serializable) dataQualityList);
        }
    } catch (ParserConfigurationException | IOException | SAXException | XPathExpressionException e) {
        LOGGER.debug("Unable to parse Data Quality elements.  Metacard Data Quality will not be set.", e);
        return;
    }
}

From source file:org.cytobank.acs.core.TableOfContents.java

/**
 * <p>Creates a DocumentBuilder with Cytobank's preferred security settings
 * applied to it. Specifically turning off external entities and external
 * DTDs to prevent External Entity Exploits (XXE)</p>
 *
 * @throws ParserConfigurationException// w  w  w.  j a va  2s  . c o  m
 * @return DocumentBuilder
 */
protected DocumentBuilder getDocumentBuilder() throws ParserConfigurationException {

    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();

    DocumentBuilder db = null;

    String FEATURE = null;

    // This is the PRIMARY defense. If DTDs (doctypes) are disallowed, almost all XML entity attacks are prevented
    // Xerces 2 only - http://xerces.apache.org/xerces2-j/features.html#disallow-doctype-decl
    FEATURE = "http://apache.org/xml/features/disallow-doctype-decl";
    dbf.setFeature(FEATURE, true);

    // If you can't completely disable DTDs, then at least do the following:
    // Xerces 1 - http://xerces.apache.org/xerces-j/features.html#external-general-entities
    // Xerces 2 - http://xerces.apache.org/xerces2-j/features.html#external-general-entities
    // JDK7+ - http://xml.org/sax/features/external-general-entities
    FEATURE = "http://xml.org/sax/features/external-general-entities";
    dbf.setFeature(FEATURE, false);

    // Xerces 1 - http://xerces.apache.org/xerces-j/features.html#external-parameter-entities
    // Xerces 2 - http://xerces.apache.org/xerces2-j/features.html#external-parameter-entities
    // JDK7+ - http://xml.org/sax/features/external-parameter-entities
    FEATURE = "http://xml.org/sax/features/external-parameter-entities";
    dbf.setFeature(FEATURE, false);

    // Disable external DTDs as well
    FEATURE = "http://apache.org/xml/features/nonvalidating/load-external-dtd";
    dbf.setFeature(FEATURE, false);

    // and these as well, per Timothy Morgan's 2014 paper: "XML Schema, DTD, and Entity Attacks" (see reference below)
    dbf.setXIncludeAware(false);
    dbf.setExpandEntityReferences(false);

    // And, per Timothy Morgan: "If for some reason support for inline DOCTYPEs are a requirement, then
    // ensure the entity settings are disabled (as shown above) and beware that SSRF attacks
    // (http://cwe.mitre.org/data/definitions/918.html) and denial
    // of service attacks (such as billion laughs or decompression bombs via "jar:") are a risk."

    boolean namespaceAware = true;
    boolean xsdValidate = false;
    boolean ignoreWhitespace = false;
    boolean ignoreComments = false;
    boolean putCDATAIntoText = false;
    boolean createEntityRefs = false;

    dbf.setNamespaceAware(namespaceAware);
    dbf.setValidating(xsdValidate);
    dbf.setIgnoringComments(ignoreComments);
    dbf.setIgnoringElementContentWhitespace(ignoreWhitespace);
    dbf.setCoalescing(putCDATAIntoText);
    dbf.setExpandEntityReferences(createEntityRefs);

    db = dbf.newDocumentBuilder();

    return db;

}

From source file:org.dita.dost.util.DitaUtil.java

private static String getFileNameFromMap(String ditaMapPath) {

    StringBuffer fileName = new StringBuffer();

    try {/*from   www.  j a  v a 2 s.  com*/

        FileInputStream ditaMapStream;

        ditaMapStream = new FileInputStream(ditaMapPath);

        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();

        factory.setNamespaceAware(true);

        factory.setValidating(false);

        factory.setFeature("http://xml.org/sax/features/namespaces", false);
        factory.setFeature("http://xml.org/sax/features/validation", false);
        factory.setFeature("http://apache.org/xml/features/nonvalidating/load-dtd-grammar", false);
        factory.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false);

        DocumentBuilder builder;

        Document doc = null;

        XPathExpression expr = null;

        builder = factory.newDocumentBuilder();

        doc = builder.parse(new InputSource(ditaMapStream));

        XPathFactory xFactory = XPathFactory.newInstance();

        XPath xpath = xFactory.newXPath();

        expr = xpath.compile("//bookmap/bookmeta/prodinfo/prodname");

        Node prodNameNode = (Node) expr.evaluate(doc, XPathConstants.NODE);

        if (prodNameNode != null) {

            fileName.append(prodNameNode.getTextContent());

            expr = xpath.compile("//bookmap/bookmeta/prodinfo/vrmlist");

            Element vrmlistNode = (Element) expr.evaluate(doc, XPathConstants.NODE);

            if (vrmlistNode != null) {
                NodeList versions = vrmlistNode.getElementsByTagName("vrm");
                if (versions.getLength() > 0) {

                    NamedNodeMap versionAttributes = versions.item(0).getAttributes();
                    Attr releaseAttr = (Attr) versionAttributes.getNamedItem("release");

                    if (releaseAttr != null) {
                        fileName.append(String.format("_%s", releaseAttr.getValue()));
                    }

                    Attr versionAttr = (Attr) versionAttributes.getNamedItem("version");

                    if (versionAttr != null) {
                        fileName.append(String.format("_%s", versionAttr.getValue()));
                    }
                }
            }
        } else {
            expr = xpath.compile("/bookmap");
            prodNameNode = (Node) expr.evaluate(doc, XPathConstants.NODE);
            if (prodNameNode != null) {
                Node node = prodNameNode.getAttributes().getNamedItem("id");
                if (node != null) {
                    fileName.append(node.getTextContent());
                }
            } else {
                expr = xpath.compile("/map");
                prodNameNode = (Node) expr.evaluate(doc, XPathConstants.NODE);
                if (prodNameNode != null) {
                    Node node = prodNameNode.getAttributes().getNamedItem("title");
                    if (node != null) {
                        fileName.append(node.getTextContent());
                    }
                }
            }
        }
    } catch (FileNotFoundException e) {
    } catch (ParserConfigurationException e) {
    } catch (SAXException e) {
    } catch (IOException e) {
    } catch (XPathExpressionException e) {
    }
    return fileName.toString();
}

From source file:org.eclipse.mdht.dita.ui.util.DitaUtil.java

public static void validate(IPath tmpFileInWorkspaceDir)
        throws IOException, ParserConfigurationException, SAXException, URISyntaxException {

    // TODO delete commented out code which was used for debugging (debug code needs to stay at least two releases after 2.5.9)
    // Get the XSD file
    Bundle bundle = Platform.getBundle("org.eclipse.mdht.dita.ui");
    // Path ditaSchemadirPath = new Path("DITA-OT/schema/technicalContent/xsd/topic.xsd");
    // URL ditaXSD = FileLocator.toFileURL(FileLocator.find(bundle, ditaSchemadirPath, null));
    Path ditaFolderPath = new Path("DITA-OT");
    URL ditaFolder = FileLocator.toFileURL(FileLocator.find(bundle, ditaFolderPath, null));
    // System.out.println(ditaFolder);

    // Create DBF and ignore DTD
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    dbf.setNamespaceAware(true);/*ww  w. j av a  2  s.  com*/
    dbf.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false);
    DocumentBuilder parser = dbf.newDocumentBuilder();
    Document document = parser.parse(tmpFileInWorkspaceDir.toFile());

    // create a SchemaFactory capable of understanding WXS schemas
    SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);

    // Use catalog
    // Path ditaCatalogPath = new Path("DITA-OT/schema/catalog.xml");
    // URL ditaCatalog = FileLocator.toFileURL(FileLocator.find(bundle, ditaCatalogPath, null));
    File ditaCatalogFile = new File(ditaFolder.getFile(), "schema/catalog.xml");
    // System.out.println(ditaCatalogFile);
    // System.out.println(ditaCatalogFile.exists());
    XMLCatalogResolver resolver = new XMLCatalogResolver(new String[] { ditaCatalogFile.getAbsolutePath() });
    schemaFactory.setResourceResolver(resolver);

    // load a WXS schema, represented by a Schema instance
    File ditaSchemaFile = new File(ditaFolder.getFile(), "schema/technicalContent/xsd/topic.xsd");

    // System.out.println(ditaSchemaFile);
    // System.out.println(ditaSchemaFile.exists());
    Source schemaFile = new StreamSource(ditaSchemaFile);
    Schema schema = schemaFactory.newSchema(schemaFile);
    Validator validator = schema.newValidator();

    DOMSource dom = new DOMSource(document);
    validator.validate(dom);
}

From source file:org.eclipse.mdht.dita.ui.util.DitaUtil.java

private static String getFileNameFromMap(String ditaMapPath) {

    StringBuffer fileName = new StringBuffer();

    try {/*from   w  w w.  ja va  2 s .c  om*/

        FileInputStream ditaMapStream;

        ditaMapStream = new FileInputStream(ditaMapPath);

        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();

        factory.setNamespaceAware(true);

        factory.setValidating(false);

        factory.setFeature("http://xml.org/sax/features/namespaces", false);
        factory.setFeature("http://xml.org/sax/features/validation", false);
        factory.setFeature("http://apache.org/xml/features/nonvalidating/load-dtd-grammar", false);
        factory.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false);

        DocumentBuilder builder;

        Document doc = null;

        XPathExpression expr = null;

        builder = factory.newDocumentBuilder();

        doc = builder.parse(new InputSource(ditaMapStream));

        XPathFactory xFactory = XPathFactory.newInstance();

        XPath xpath = xFactory.newXPath();

        expr = xpath.compile("//bookmap/bookmeta/prodinfo/prodname");

        Node prodNameNode = (Node) expr.evaluate(doc, XPathConstants.NODE);

        if (prodNameNode != null) {

            fileName.append(prodNameNode.getTextContent());

            expr = xpath.compile("//bookmap/bookmeta/prodinfo/vrmlist");

            Element vrmlistNode = (Element) expr.evaluate(doc, XPathConstants.NODE);

            if (vrmlistNode != null) {
                NodeList versions = vrmlistNode.getElementsByTagName("vrm");
                if (versions.getLength() > 0) {

                    NamedNodeMap versionAttributes = versions.item(0).getAttributes();
                    Attr releaseAttr = (Attr) versionAttributes.getNamedItem("release");

                    if (releaseAttr != null) {
                        fileName.append(String.format("_%s", releaseAttr.getValue()));
                    }

                    Attr versionAttr = (Attr) versionAttributes.getNamedItem("version");

                    if (versionAttr != null) {
                        fileName.append(String.format("_%s", versionAttr.getValue()));
                    }
                }
            }
        } else {
            expr = xpath.compile("/bookmap");
            prodNameNode = (Node) expr.evaluate(doc, XPathConstants.NODE);
            if (prodNameNode != null) {
                Node node = prodNameNode.getAttributes().getNamedItem("id");
                if (node != null) {
                    fileName.append(node.getTextContent());
                }
            } else {
                expr = xpath.compile("/map");
                prodNameNode = (Node) expr.evaluate(doc, XPathConstants.NODE);
                if (prodNameNode != null) {
                    Node node = prodNameNode.getAttributes().getNamedItem("title");
                    if (node != null) {
                        fileName.append(node.getTextContent());
                    }
                }
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
        System.out.println();
    }
    return fileName.toString();
}

From source file:org.gluu.saml.Response.java

public void loadXml(String xml) throws ParserConfigurationException, SAXException, IOException {
    DocumentBuilderFactory fty = DocumentBuilderFactory.newInstance();

    fty.setNamespaceAware(true);//from w ww.j  ava 2s.c  o  m

    // Fix XXE vulnerability
    fty.setXIncludeAware(false);
    fty.setExpandEntityReferences(false);
    fty.setFeature("http://xml.org/sax/features/external-parameter-entities", false);
    fty.setFeature("http://xml.org/sax/features/external-general-entities", false);
    fty.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false);

    DocumentBuilder builder = fty.newDocumentBuilder();
    ByteArrayInputStream bais = new ByteArrayInputStream(xml.getBytes());
    xmlDoc = builder.parse(bais);
}