Example usage for org.jdom2.input SAXBuilder setFeature

List of usage examples for org.jdom2.input SAXBuilder setFeature

Introduction

In this page you can find the example usage for org.jdom2.input SAXBuilder setFeature.

Prototype

public void setFeature(final String name, final boolean value) 

Source Link

Document

This sets a feature on the SAX parser.

Usage

From source file:ca.nrc.cadc.dali.tables.votable.VOTableReader.java

License:Open Source License

/**
 * Create a XML parser using the schemaMap schemas for validation.
 * @param schemaMap Map of schema namespace to location.
 * @return XML parser./*from w  w w .  j  a va 2s.com*/
 */
protected SAXBuilder createBuilder(Map<String, String> schemaMap) {
    long start = System.currentTimeMillis();
    boolean schemaVal = (schemaMap != null);
    String schemaResource;
    String space = " ";
    StringBuilder sbSchemaLocations = new StringBuilder();
    if (schemaVal) {
        log.debug("schemaMap.size(): " + schemaMap.size());
        for (String schemaNSKey : schemaMap.keySet()) {
            schemaResource = (String) schemaMap.get(schemaNSKey);
            sbSchemaLocations.append(schemaNSKey).append(space).append(schemaResource).append(space);
        }
        // enable xerces grammar caching
        System.setProperty("org.apache.xerces.xni.parser.XMLParserConfiguration", GRAMMAR_POOL);
    }

    XMLReaderSAX2Factory factory = new XMLReaderSAX2Factory(schemaVal, PARSER);
    SAXBuilder builder = new SAXBuilder(factory);
    if (schemaVal) {
        builder.setFeature("http://xml.org/sax/features/validation", true);
        builder.setFeature("http://apache.org/xml/features/validation/schema", true);
        if (schemaMap.size() > 0) {
            builder.setProperty("http://apache.org/xml/properties/schema/external-schemaLocation",
                    sbSchemaLocations.toString());
        }
    }
    long finish = System.currentTimeMillis();
    log.debug("SAXBuilder in " + (finish - start) + "ms");
    return builder;
}

From source file:ca.nrc.cadc.uws.util.XmlUtil.java

License:Open Source License

public static SAXBuilder createBuilder(Map<String, String> schemaMap) {
    long start = System.currentTimeMillis();
    boolean schemaVal = (schemaMap != null);
    String schemaResource;//  w  w w .  j av  a 2  s .c o  m
    String space = " ";
    StringBuilder sbSchemaLocations = new StringBuilder();
    if (schemaVal) {
        log.debug("schemaMap.size(): " + schemaMap.size());
        for (String schemaNSKey : schemaMap.keySet()) {
            schemaResource = (String) schemaMap.get(schemaNSKey);
            sbSchemaLocations.append(schemaNSKey).append(space).append(schemaResource).append(space);
        }
        // enable xerces grammar caching
        System.setProperty("org.apache.xerces.xni.parser.XMLParserConfiguration", GRAMMAR_POOL);
    }

    XMLReaderSAX2Factory factory = new XMLReaderSAX2Factory(schemaVal, PARSER);
    SAXBuilder builder = new SAXBuilder(factory);
    if (schemaVal) {
        builder.setFeature("http://xml.org/sax/features/validation", true);
        builder.setFeature("http://apache.org/xml/features/validation/schema", true);
        if (schemaMap.size() > 0) {
            builder.setProperty("http://apache.org/xml/properties/schema/external-schemaLocation",
                    sbSchemaLocations.toString());
        }
    }
    long finish = System.currentTimeMillis();
    log.debug("SAXBuilder in " + (finish - start) + "ms");
    return builder;
}

From source file:com.izforge.izpack.util.xmlmerge.merge.DefaultXmlMerge.java

License:Open Source License

@Override
public InputStream merge(InputStream[] sources) throws AbstractXmlMergeException {
    SAXBuilder builder = new SAXBuilder(XMLReaders.NONVALIDATING);
    // Xerces-specific - see: http://xerces.apache.org/xerces-j/features.html
    builder.setFeature("http://apache.org/xml/features/nonvalidating/load-dtd-grammar", false);
    builder.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false);

    Document[] docs = new Document[sources.length];

    for (int i = 0; i < sources.length; i++) {
        try {/*from w w  w. j a v a 2 s  . c  o m*/
            docs[i] = builder.build(sources[i]);
        } catch (Exception e) {
            throw new ParseException(e);
        }
    }

    Document result = doMerge(docs);

    Format prettyFormatter = Format.getPrettyFormat();
    // Use system line seperator to avoid problems
    // with carriage return under linux
    prettyFormatter.setLineSeparator(System.getProperty("line.separator"));
    XMLOutputter sortie = new XMLOutputter(prettyFormatter);

    ByteArrayOutputStream buffer = new ByteArrayOutputStream();

    try {
        sortie.output(result, buffer);
    } catch (IOException ex) {
        throw new DocumentException(result, ex);
    }

    return new ByteArrayInputStream(buffer.toByteArray());
}

From source file:com.izforge.izpack.util.xmlmerge.merge.DefaultXmlMerge.java

License:Open Source License

@Override
public void merge(File[] sources, File target) throws AbstractXmlMergeException {
    SAXBuilder builder = new SAXBuilder(XMLReaders.NONVALIDATING);
    // Xerces-specific - see: http://xerces.apache.org/xerces-j/features.html
    builder.setFeature("http://apache.org/xml/features/nonvalidating/load-dtd-grammar", false);
    builder.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false);

    Document[] docs = new Document[sources.length];

    for (int i = 0; i < sources.length; i++) {
        try {/*from   ww w  .  jav  a  2s  .c  om*/
            docs[i] = builder.build(sources[i]);
        } catch (Exception e) {
            throw new ParseException(e);
        }
    }

    Document result = doMerge(docs);

    Format prettyFormatter = Format.getPrettyFormat();
    // Use system line separator to avoid problems
    // with carriage return under linux
    prettyFormatter.setLineSeparator(System.getProperty("line.separator"));
    XMLOutputter sortie = new XMLOutputter(prettyFormatter);

    try {
        sortie.output(result, new FileOutputStream(target));
    } catch (IOException ex) {
        throw new DocumentException(result, ex);
    }
}

From source file:com.rometools.rome.io.WireFeedInput.java

License:Open Source License

private void setFeature(SAXBuilder saxBuilder, XMLReader parser, String feature, boolean value) {
    try {//w w  w .j ava 2s .  co  m
        saxBuilder.setFeature(feature, true);
        parser.setFeature(feature, true);
    } catch (final SAXNotRecognizedException e) {
        // ignore
    } catch (final SAXNotSupportedException e) {
        // ignore
    }
}

From source file:com.seleniumtests.util.squashta.TaScriptGenerator.java

License:Apache License

/**
 * Search for tests in TestNG files/*from   ww w  .j  a v  a  2 s.c  o m*/
 * @param path
 * @param application
 * @return
 */
public List<SquashTaTestDef> parseTestNgXml() {

    // look for feature file into data folder
    File dir = Paths.get(srcPath, "data", application, "testng").toFile();
    if (!dir.exists()) {
        return new ArrayList<>();
    }

    File[] testngFiles = dir.listFiles((d, filename) -> filename.endsWith(".xml"));

    List<SquashTaTestDef> testDefs = new ArrayList<>();

    for (File testngFile : testngFiles) {

        Document doc;
        SAXBuilder sxb = new SAXBuilder();
        sxb.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false);
        try {

            doc = sxb.build(testngFile);
        } catch (Exception e) {
            logger.error(String.format("Fichier %s illisible: %s", testngFile, e.getMessage()));
            return testDefs;
        }

        Element suite = doc.getRootElement();
        if (!"suite".equalsIgnoreCase(suite.getName())) {
            continue;
        }

        for (Element test : suite.getChildren("test")) {
            readTestTag(test, testDefs, testngFile);

        }
    }

    return testDefs;
}

From source file:com.sun.syndication.io.WireFeedInput.java

License:Open Source License

/**
 * Creates and sets up a org.jdom2.input.SAXBuilder for parsing.
 * /*from ww  w . j  av a  2 s .  c  o  m*/
 * @return a new org.jdom2.input.SAXBuilder object
 */
protected SAXBuilder createSAXBuilder() {
    SAXBuilder saxBuilder = new SAXBuilder(_validate);
    saxBuilder.setEntityResolver(RESOLVER);

    //
    // This code is needed to fix the security problem outlined in http://www.securityfocus.com/archive/1/297714
    //
    // Unfortunately there isn't an easy way to check if an XML parser supports a particular feature, so
    // we need to set it and catch the exception if it fails. We also need to subclass the JDom SAXBuilder 
    // class in order to get access to the underlying SAX parser - otherwise the features don't get set until
    // we are already building the document, by which time it's too late to fix the problem.
    //
    // Crimson is one parser which is known not to support these features.
    try {
        XMLReader parser = saxBuilder.createParser();
        try {
            parser.setFeature("http://xml.org/sax/features/external-general-entities", false);
            saxBuilder.setFeature("http://xml.org/sax/features/external-general-entities", false);
        } catch (SAXNotRecognizedException e) {
            // ignore
        } catch (SAXNotSupportedException e) {
            // ignore
        }

        try {
            parser.setFeature("http://xml.org/sax/features/external-parameter-entities", false);
            saxBuilder.setFeature("http://xml.org/sax/features/external-parameter-entities", false);
        } catch (SAXNotRecognizedException e) {
            // ignore
        } catch (SAXNotSupportedException e) {
            // ignore
        }

        try {
            parser.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false);
            saxBuilder.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false);
        } catch (SAXNotRecognizedException e) {
            // ignore
        } catch (SAXNotSupportedException e) {
            // ignore
        }

    } catch (JDOMException e) {
        throw new IllegalStateException("JDOM could not create a SAX parser");
    }

    saxBuilder.setExpandEntities(false);
    return saxBuilder;
}

From source file:Contabilidad.javaToXML.java

public boolean creaAndValidaXML(TFactDocMX comprobante, String nombre) {
    boolean response = false;
    generaRaiz(comprobante);//from   w ww.  j  av a 2  s.  c om

    XMLOutputter outputter = new XMLOutputter();
    File folder = new File("nativos");
    folder.mkdirs();
    Format formato = Format.getPrettyFormat();
    formato.setEncoding("UTF-8");
    outputter.setFormat(formato);
    File archivoXml = new File(nombre);
    try {
        //Writer write = new FileWriter(archivoXml);
        FileOutputStream fop = new FileOutputStream(archivoXml);
        outputter.output(getXml(), fop);
    } catch (IOException e) {
        System.err.println("e1:" + e);
        return response;
    }
    //se instancia la clase que validara el XSD
    SAXBuilder builder = new SAXBuilder("org.apache.xerces.parsers.SAXParser", true);
    builder.setFeature("http://apache.org/xml/features/validation/schema", true);
    builder.setFeature("http://apache.org/xml/features/validation/schema-full-checking", true);
    builder.setProperty("http://apache.org/xml/properties/schema/external-schemaLocation",
            COMPROBANTE_SCHEMA_XSD);
    builder.setValidation(true);
    //se imprime el documento si se logro cumplir con el XSD
    try {
        Document document = builder.build(archivoXml);
        //outputter.output(document, System.out);
        response = true;
    } catch (JDOMException e) {
        System.out.println("e2:");
        error = e.toString();
        e.printStackTrace();
    } catch (IOException e) {
        System.out.println("e3");
        error = e.toString();
        e.printStackTrace();
    }
    return response;
}

From source file:cz.muni.fi.mir.mathmlcanonicalization.Settings.java

License:Apache License

/**
 * Sets properties desired for MathML normalization purpose
 *
 * @return initialized SAXBuilder instance
 *///from   ww  w  .jav  a2s  .  c  o m
public static SAXBuilder setupSAXBuilder() {
    final SAXBuilder builder = new SAXBuilder();
    builder.setXMLReaderFactory(XMLReaders.NONVALIDATING);
    builder.setFeature("http://xml.org/sax/features/validation", false);
    //builder.setFeature("http://xml.org/sax/features/external-general-entities", true);
    builder.setFeature("http://apache.org/xml/features/nonvalidating/load-dtd-grammar", true);
    builder.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", true);
    builder.setEntityResolver(new EntityResolver() {
        @Override
        public InputSource resolveEntity(String publicId, String systemId) {
            if (systemId.endsWith("dtd")) {
                String dtdLocation = Settings.getProperty(Settings.MATHMLDTD);
                return new InputSource(Settings.class.getResourceAsStream(dtdLocation));
            }
            return null;
        }
    });

    return builder;
}

From source file:de.intranda.goobi.plugins.sru.SRUHelper.java

License:Open Source License

public static Node parseHaabResult(GbvMarcSruImport opac, String catalogue, String schema, String searchField,
        String searchValue, String resultString, String packing, String version, boolean ignoreAnchor)
        throws IOException, JDOMException, ParserConfigurationException {
    SAXBuilder builder = new SAXBuilder(XMLReaders.NONVALIDATING);
    builder.setFeature("http://xml.org/sax/features/validation", false);
    builder.setFeature("http://apache.org/xml/features/nonvalidating/load-dtd-grammar", false);
    builder.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false);
    Document doc = builder.build(new StringReader(resultString), "utf-8");
    Element record = getRecordWithoutSruHeader(doc);
    if (record == null) {
        opac.setHitcount(0);/*  w  w w  .ja  v  a 2 s .  c om*/
        return null;
    }
    opac.setHitcount(1);
    boolean isPeriodical = false;
    boolean isManuscript = false;
    boolean isCartographic = false;
    boolean isMultiVolume = false;
    boolean isFSet = false;

    String anchorPpn = null;
    String otherAnchorPpn = null;
    String otherAnchorEpn = null;

    String otherPpn = null;
    String currentEpn = null;
    String otherEpn = null;
    boolean foundMultipleEpns = false;

    // generate an answer document
    DocumentBuilderFactory dbfac = DocumentBuilderFactory.newInstance();
    DocumentBuilder docBuilder = dbfac.newDocumentBuilder();
    org.w3c.dom.Document answer = docBuilder.newDocument();
    org.w3c.dom.Element collection = answer.createElement("collection");
    answer.appendChild(collection);

    boolean shelfmarkFound = false;
    List<Element> data = record.getChildren();
    for (Element el : data) {
        if (el.getName().equalsIgnoreCase("leader")) {
            String value = el.getText();
            if (value.length() < 24) {
                value = "00000" + value;
            }
            char c6 = value.toCharArray()[6];
            char c7 = value.toCharArray()[7];
            char c19 = value.toCharArray()[19];
            if (c6 == 'a' && (c7 == 's' || c7 == 'd')) {
                isPeriodical = true;
            } else if (c6 == 't') {
                isManuscript = true;
            } else if (c6 == 'e') {
                isCartographic = true;
            }
            if (c19 == 'b' || c19 == 'c') {
                isFSet = true;
            }

        }
        if (el.getName().equalsIgnoreCase("datafield")) {
            String tag = el.getAttributeValue("tag");
            List<Element> subfields = el.getChildren();
            boolean isCurrentEpn = false;
            for (Element sub : subfields) {
                String code = sub.getAttributeValue("code");
                // anchor identifier
                if (tag.equals("773") && code.equals("w")) {
                    if (ignoreAnchor) {
                        sub.setText("");
                    } else if (isFSet || isPeriodical) {
                        isMultiVolume = true;
                        anchorPpn = sub.getText().replaceAll("\\(.+\\)", "").replace("KXP", "");

                    }
                } else if (tag.equals("800") && code.equals("w")) {
                    isMultiVolume = true;
                    anchorPpn = sub.getText().replaceAll("\\(.+\\)", "").replace("KXP", "");
                } else if (isManuscript && tag.equals("810") && code.equals("w")) {
                    isMultiVolume = true;
                    anchorPpn = sub.getText().replaceAll("\\(.+\\)", "").replace("KXP", "");

                } else if (tag.equals("830") && code.equals("w")) {
                    if (isCartographic || (isFSet && anchorPpn == null)) {
                        isMultiVolume = true;
                        anchorPpn = sub.getText().replaceAll("\\(.+\\)", "").replace("KXP", "");

                    }
                } else if (tag.equals("776") && code.equals("w")) {
                    if (otherPpn == null) {
                        // found first/only occurrence
                        otherPpn = sub.getText().replaceAll("\\(.+\\)", "").replace("KXP", "");

                    } else {
                        otherPpn = null;
                        foundMultipleEpns = true;
                    }

                } else if (tag.equals("954")) {
                    if (code.equals("b")) {
                        if (searchField.equals("pica.epn")) {
                            // remove wrong epns
                            currentEpn = sub.getText().replaceAll("\\(.+\\)", "").replace("KXP", "");
                            isCurrentEpn = true;
                            if (!searchValue.trim().equals(currentEpn)) {
                                sub.setAttribute("code", "invalid");
                                for (Element exemplarData : subfields) {
                                    if (exemplarData.getAttributeValue("code").equals("d")) {
                                        exemplarData.setAttribute("code", "invalid");
                                    }
                                }
                            }
                        } else {
                            if (currentEpn == null) {
                                isCurrentEpn = true;
                                currentEpn = sub.getText().replaceAll("\\(.+\\)", "").replace("KXP", "");

                            } else {
                                foundMultipleEpns = true;
                            }
                        }
                    } else if (code.equals("d")) {
                        if (!shelfmarkFound && isCurrentEpn) {
                            shelfmarkFound = true;
                        } else {
                            sub.setAttribute("code", "invalid");
                        }
                    }
                }
            }
        }
    }

    //  search for pica.zdb for periodca
    // get digital epn from digital ppn record
    if (otherPpn != null) {
        String otherResult = SRUHelper.search(catalogue, schema, isPeriodical ? "pica.zdb" : "pica.ppn",
                otherPpn, packing, version);
        Document otherDocument = new SAXBuilder().build(new StringReader(otherResult), "utf-8");
        if (otherDocument != null) {
            Element otherRecord = getRecordWithoutSruHeader(otherDocument);
            if (otherRecord == null) {
                Helper.setFehlerMeldung("import_OtherEPNNotFound");
            } else {

                List<Element> controlList = otherRecord.getChildren("controlfield", MARC);
                for (Element field : controlList) {
                    if (field.getAttributeValue("tag").equals("001")) {
                        otherPpn = field.getText();
                    }
                }

                List<Element> fieldList = otherRecord.getChildren("datafield", MARC);
                for (Element field : fieldList) {
                    String tag = field.getAttributeValue("tag");

                    List<Element> subfields = field.getChildren();
                    for (Element sub : subfields) {
                        String code = sub.getAttributeValue("code");
                        // anchor identifier
                        if (tag.equals("773") && code.equals("w")) {
                            otherAnchorPpn = sub.getText().replaceAll("\\(.+\\)", "").replace("KXP", "");
                        } else if (tag.equals("800") && code.equals("w")) {
                            otherAnchorPpn = sub.getText().replaceAll("\\(.+\\)", "").replace("KXP", "");
                        } else if (isManuscript && tag.equals("810") && code.equals("w")) {
                            otherAnchorPpn = sub.getText().replaceAll("\\(.+\\)", "");
                        } else if (isCartographic && tag.equals("830") && code.equals("w")) {
                            otherAnchorPpn = sub.getText().replaceAll("\\(.+\\)", "").replace("KXP", "");
                        } else if (tag.equals("954") && code.equals("b")) {
                            if (otherEpn == null) {
                                otherEpn = sub.getText().replaceAll("\\(.+\\)", "").replace("KXP", "");
                            } else {
                                foundMultipleEpns = true;
                                otherEpn = null;
                            }
                        }

                    }
                }
            }
            if (otherPpn != null) {
                Element datafield = new Element("datafield", MARC);
                datafield.setAttribute("tag", "ppnDigital");
                datafield.setAttribute("ind1", "");
                datafield.setAttribute("ind2", "");

                Element subfield = new Element("subfield", MARC);
                subfield.setAttribute("code", "a");
                subfield.setText(otherPpn);
                datafield.addContent(subfield);
                data.add(datafield);
            }
            if (otherEpn != null && !foundMultipleEpns) {
                Element datafield = new Element("datafield", MARC);
                datafield.setAttribute("tag", "epnDigital");
                datafield.setAttribute("ind1", "");
                datafield.setAttribute("ind2", "");

                Element subfield = new Element("subfield", MARC);
                subfield.setAttribute("code", "a");
                subfield.setText(otherEpn);
                datafield.addContent(subfield);
                data.add(datafield);
            }
        }
    }
    org.w3c.dom.Element marcRecord = getRecord(answer, data, opac);

    if (isMultiVolume) {
        // get anchor record
        String anchorResult = SRUHelper.search(catalogue, schema, "pica.ppn", anchorPpn, packing, version);
        Document anchorDoc = new SAXBuilder().build(new StringReader(anchorResult), "utf-8");

        Element anchorRecord = getRecordWithoutSruHeader(anchorDoc);

        if (anchorRecord != null) {
            List<Element> anchorData = anchorRecord.getChildren();

            // get EPN/PPN digital for anchor
            String otherAnchorResult = SRUHelper.search(catalogue, schema,
                    isPeriodical ? "pica.zdb" : "pica.ppn", otherAnchorPpn, packing, version);
            Document otherAnchorDoc = new SAXBuilder().build(new StringReader(otherAnchorResult), "utf-8");
            Element otherAnchorRecord = getRecordWithoutSruHeader(otherAnchorDoc);

            if (otherAnchorRecord == null) {
                Helper.setFehlerMeldung("import_OtherEPNNotFound");
            } else {

                List<Element> controlList = otherAnchorRecord.getChildren("controlfield", MARC);
                for (Element field : controlList) {
                    if (field.getAttributeValue("tag").equals("001")) {
                        otherAnchorPpn = field.getText();
                    }
                }

                List<Element> fieldList = otherAnchorRecord.getChildren("datafield", MARC);
                for (Element field : fieldList) {
                    if (field.getAttributeValue("tag").equals("954")) {
                        List<Element> subfields = field.getChildren();
                        for (Element sub : subfields) {
                            String code = sub.getAttributeValue("code");
                            if (code.equals("b")) {
                                if (otherAnchorEpn == null) {
                                    otherAnchorEpn = sub.getText().replaceAll("\\(.+\\)", "").replace("KXP",
                                            "");
                                    ;
                                } else {
                                    foundMultipleEpns = true;
                                }
                            }
                        }
                    }
                }

                if (otherAnchorPpn != null) {
                    Element datafield = new Element("datafield", MARC);
                    datafield.setAttribute("tag", "ppnDigital");
                    datafield.setAttribute("ind1", "");
                    datafield.setAttribute("ind2", "");

                    Element subfield = new Element("subfield", MARC);
                    subfield.setAttribute("code", "a");
                    subfield.setText(otherAnchorPpn);
                    datafield.addContent(subfield);
                    anchorData.add(datafield);
                }

                if (otherAnchorEpn != null && !foundMultipleEpns) {
                    Element datafield = new Element("datafield", MARC);
                    datafield.setAttribute("tag", "epnDigital");
                    datafield.setAttribute("ind1", "");
                    datafield.setAttribute("ind2", "");

                    Element subfield = new Element("subfield", MARC);
                    subfield.setAttribute("code", "a");
                    subfield.setText(otherAnchorEpn);
                    datafield.addContent(subfield);
                    anchorData.add(datafield);
                }
            }
            org.w3c.dom.Element anchorMarcRecord = getRecord(answer, anchorData, opac);

            collection.appendChild(anchorMarcRecord);
        }

    }

    if (foundMultipleEpns) {
        Helper.setFehlerMeldung("import_foundMultipleEPNs");
    }

    collection.appendChild(marcRecord);
    return answer.getDocumentElement();
}