Example usage for javax.xml.parsers DocumentBuilderFactory setValidating

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

Introduction

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

Prototype


public void setValidating(boolean validating) 

Source Link

Document

Specifies that the parser produced by this code will validate documents as they are parsed.

Usage

From source file:org.dspace.submit.lookup.CrossRefService.java

public List<Record> search(Context context, Set<String> dois, String apiKey)
        throws HttpException, IOException, JDOMException, ParserConfigurationException, SAXException {
    List<Record> results = new ArrayList<Record>();
    if (dois != null && dois.size() > 0) {
        for (String record : dois) {
            try {
                HttpGet method = null;/*w w w.j a va 2  s.c o m*/
                try {
                    HttpClient client = new DefaultHttpClient();
                    client.getParams().setIntParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, timeout);

                    try {
                        URIBuilder uriBuilder = new URIBuilder("http://www.crossref.org/openurl/");
                        uriBuilder.addParameter("pid", apiKey);
                        uriBuilder.addParameter("noredirect", "true");
                        uriBuilder.addParameter("id", record);
                        method = new HttpGet(uriBuilder.build());
                    } catch (URISyntaxException ex) {
                        throw new HttpException("Request not sent", ex);
                    }

                    // Execute the method.
                    HttpResponse response = client.execute(method);
                    StatusLine statusLine = response.getStatusLine();
                    int statusCode = statusLine.getStatusCode();

                    if (statusCode != HttpStatus.SC_OK) {
                        throw new RuntimeException("Http call failed: " + statusLine);
                    }

                    Record crossitem;
                    try {
                        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
                        factory.setValidating(false);
                        factory.setIgnoringComments(true);
                        factory.setIgnoringElementContentWhitespace(true);

                        DocumentBuilder db = factory.newDocumentBuilder();
                        Document inDoc = db.parse(response.getEntity().getContent());

                        Element xmlRoot = inDoc.getDocumentElement();
                        Element queryResult = XMLUtils.getSingleElement(xmlRoot, "query_result");
                        Element body = XMLUtils.getSingleElement(queryResult, "body");
                        Element dataRoot = XMLUtils.getSingleElement(body, "query");

                        crossitem = CrossRefUtils.convertCrossRefDomToRecord(dataRoot);
                        results.add(crossitem);
                    } catch (Exception e) {
                        log.warn(LogManager.getHeader(context, "retrieveRecordDOI",
                                record + " DOI is not valid or not exist: " + e.getMessage()));
                    }
                } finally {
                    if (method != null) {
                        method.releaseConnection();
                    }
                }
            } catch (RuntimeException rt) {
                log.error(rt.getMessage(), rt);
            }
        }
    }
    return results;
}

From source file:com.surevine.alfresco.webscript.gsa.canuserseeitems.CanUserSeeItemsCommandWebscriptImpl.java

public Map<Integer, Object> requestToNodeRefCollection(String requestXMLString)
        throws SAXException, ParserConfigurationException, IOException, GSAInvalidParameterException {
    Map<Integer, Object> responseItems = new HashMap<Integer, Object>();

    Collection<NodeRef> nodeRefs = new ArrayList<NodeRef>();

    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    factory.setValidating(false);
    DocumentBuilder parser = factory.newDocumentBuilder();
    Document document = parser.parse(new ByteArrayInputStream(requestXMLString.getBytes("UTF-8")));

    NodeList allNodeRefs = document.getElementsByTagName("nodeRef");
    Element documentElement = document.getDocumentElement();
    String runAsUser = documentElement.getAttribute("runAsUser");

    //If the runAsUser is specified but doesn't exist, throw an error
    if (runAsUser != null && (!runAsUser.equals("")) && !personService.personExists(runAsUser)) {
        throw new GSAInvalidParameterException("The specified runAsUser(" + runAsUser + ") does not exist",
                null, 140611);/*w  w  w  .j  a v  a2  s . co m*/
    }
    responseItems.put(RUN_AS_USER_KEY, runAsUser);

    int nodeRefCount = allNodeRefs.getLength();
    for (int i = 0; i < nodeRefCount; i++) {
        Node node = allNodeRefs.item(i);
        String nodeReference = node.getTextContent();

        NodeRef newNode = null;
        try {
            newNode = new NodeRef(nodeReference);
            if (_logger.isDebugEnabled()) {
                _logger.debug("Created nodeRef " + newNode + " from request");
            }
        } catch (Exception e) {
            //some problem creating the NodeRef - probably a syntactically invalid node ref.
            //ignore and continue:
            GSAProcessingException wrapped = new GSAProcessingException(
                    "Could not serialise " + nodeReference + " to a NodeRef Collection", e, 34831);
            _logger.warn(
                    "NodeRef could not be instantiated for supplied node reference [" + nodeReference + "].",
                    wrapped);
            continue;
        }

        nodeRefs.add(newNode);
    }

    responseItems.put(NODE_REFS_KEY, nodeRefs);

    return responseItems;
}

From source file:at.tfr.securefs.module.validation.SchemaValidationModule.java

@Override
public ModuleResult apply(InputStream input, ModuleConfiguration moduleConfiguration)
        throws ModuleException, IOException {
    SchemaResolver errorHandler = null;//w  ww  . j  a  va2s . co m
    moduleStatistics.getCalls().incrementAndGet();

    try {
        // parse an XML document into a DOM tree
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        dbf.setNamespaceAware(true);
        dbf.setValidating(true);
        dbf.setCoalescing(true);
        dbf.setCoalescing(true);

        if (schema == null) {
            loadSchema(moduleConfiguration);
        }

        DOMImplementationLS domImpl = (DOMImplementationLS) dbf.newDocumentBuilder().getDOMImplementation();
        errorHandler = new SchemaResolver(configuration.getSchemaPath(), domImpl);

        Validator validator = schema.newValidator();
        validator.setErrorHandler(errorHandler);
        validator.setResourceResolver(errorHandler);

        validator.validate(new StreamSource(input));

    } catch (SAXParseException e) {
        moduleStatistics.getFailures().incrementAndGet();
        String message = "error validating: " + getCurrent() + " err: " + e;
        log.debug(message, e);
        log.info(message);
        if (moduleConfiguration.isMandatory()) {
            throw new ModuleException(message, e);
        } else {
            return new ModuleResult(false, e);
        }
    } catch (Exception e) {
        moduleStatistics.getErrors().incrementAndGet();
        String message = "error validating: " + getCurrent() + " err: " + e;
        log.info(message, e);
        log.warn(message);
        if (moduleConfiguration.isMandatory()) {
            throw new IOException(message, e);
        } else {
            return new ModuleResult(false, e);
        }
    }

    if (errorHandler != null && errorHandler.getErrors().size() > 0) {

        moduleStatistics.getFailures().incrementAndGet();

        String message = "Validation errors for File: " + getCurrent() + " errors: " + errorHandler.getErrors();
        if (log.isDebugEnabled()) {
            log.debug(message);
            if (log.isTraceEnabled()) {
                log.trace("Validation warnings for File: " + getCurrent() + " errors: "
                        + errorHandler.getWarnings());
            }
        }
        if (moduleConfiguration.isMandatory()) {
            throw new ModuleException(message);
        } else {
            log.info("accepted errors - " + message);
        }
        return new ModuleResult(false, errorHandler.getErrors().get(0));
    }

    moduleStatistics.getSuccesses().incrementAndGet();
    return new ModuleResult(true);
}

From source file:com.idega.util.config.DefaultConfig.java

/**
 * Creates and loads a new configuration.
 * //from ww  w  .j  a v a  2  s  .  c  o  m
 * @param stream
 *            InputStream to read XML data in the default format.
 */
public DefaultConfig(InputStream stream) throws ConfigException {
    try {
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        factory.setNamespaceAware(false);
        factory.setValidating(false);

        Document document = factory.newDocumentBuilder().parse(stream);
        JXPathContext context = JXPathContext.newContext(document.getDocumentElement());

        for (Iterator iter = context.iteratePointers(properties_xpath); iter.hasNext();) {
            Pointer pointer = (Pointer) iter.next();
            Element properties_el = (Element) pointer.getNode();
            String p_name = properties_el.getAttribute(name_att);

            JXPathContext properties_context = JXPathContext.newContext(properties_el);
            Map<String, String> properties = load(properties_context, property_xpath, name_att, value_att);
            getPropertiesMap().put(p_name, properties);
        }

    } catch (Exception e) {
        throw new ConfigException(e);
    }
}

From source file:AndroidUninstallStock.java

public static DocumentBuilderFactory getXmlDocFactory() throws SAXException {
    DocumentBuilderFactory xmlfactory = DocumentBuilderFactory.newInstance();
    xmlfactory.setIgnoringComments(true);
    xmlfactory.setCoalescing(true);/*from  www .ja va  2 s  .com*/
    // http://bugs.java.com/bugdatabase/view_bug.do?bug_id=4867706
    xmlfactory.setIgnoringElementContentWhitespace(true);
    xmlfactory.setSchema(SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI)
            .newSchema(AndroidUninstallStock.class.getResource("AndroidListSoft.xsd")));
    xmlfactory.setValidating(false); // not DTD
    return xmlfactory;
}

From source file:nl.surfnet.sab.SabResponseParser.java

private Document createDocument(InputStream documentStream)
        throws ParserConfigurationException, IOException, SAXException {
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    factory.setNamespaceAware(true);/*from  ww w.j  ava  2  s .c  om*/
    factory.setIgnoringElementContentWhitespace(true);
    factory.setValidating(false);

    DocumentBuilder builder = factory.newDocumentBuilder();
    return builder.parse(documentStream);
}

From source file:com.runwaysdk.request.ClientRequestManager.java

/**
 * Constructs a new ConnectionManager object by reading in an xml file detailing connections to servers and then populating a HashMap of Connection objects.
 *///from   w w  w. j  ava2s  .  c o  m
private ClientRequestManager() {
    // initialize the connections and proxies.
    connections = new HashMap<String, ConnectionLabel>();

    URL connectionsXmlFile;
    try {
        connectionsXmlFile = ConfigurationManager.getResource(ConfigGroup.CLIENT, "connections.xml");
    } catch (RunwayConfigurationException e) {
        log.warn("connections.xml configuration file not found.", e);
        return;
    }

    InputStream connectionsSchemaFile;
    try {
        connectionsSchemaFile = ConfigurationManager.getResource(ConfigGroup.XSD, "connectionsSchema.xsd")
                .openStream();
    } catch (IOException e) {
        throw new RunwayConfigurationException(e);
    }

    Document document = null;
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    factory.setValidating(true);
    factory.setAttribute(XMLConstants.JAXP_SCHEMA_LANGUAGE, XMLConstants.W3C_XML_SCHEMA);
    factory.setAttribute(XMLConstants.JAXP_SCHEMA_SOURCE, connectionsSchemaFile);

    DocumentBuilder builder;
    try {
        builder = factory.newDocumentBuilder();
        builder.setErrorHandler(new XMLConnectionsErrorHandler());
        document = builder.parse(connectionsXmlFile.openStream());
    } catch (ParserConfigurationException e) {
        throw new ClientRequestException(e);
    } catch (SAXException e) {
        throw new ClientRequestException(e);
    } catch (IOException e) {
        throw new ClientRequestException(e);
    }
    parseDocument(document);
}

From source file:hoot.services.controllers.osm.MapResource.java

private static Document generateExtentOSM(String maxlon, String maxlat, String minlon, String minlat) {
    SimpleDateFormat sdfDate = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
    Date now = new Date();
    String strDate = sdfDate.format(now);

    try {/*from   w w w .  j a v  a  2 s. c  om*/
        DocumentBuilderFactory dbf = XmlDocumentBuilder.getSecureDocBuilderFactory();
        dbf.setValidating(false);
        DocumentBuilder db = dbf.newDocumentBuilder();
        Document doc = db.newDocument();

        Element osmElem = doc.createElement("osm");
        osmElem.setAttribute("version", "0.6");
        osmElem.setAttribute("generator", "hootenanny");
        doc.appendChild(osmElem);

        Element boundsElem = doc.createElement("bounds");
        boundsElem.setAttribute("minlat", minlat);
        boundsElem.setAttribute("minlon", minlon);
        boundsElem.setAttribute("maxlat", maxlat);
        boundsElem.setAttribute("maxlon", maxlon);
        osmElem.appendChild(boundsElem);

        // The ID's for these fabricated nodes were stepping on the ID's of actual nodes, so their ID's need to be
        // made negative and large, so they have no chance of stepping on anything.

        long node1Id = Long.MIN_VALUE + 3;
        long node2Id = Long.MIN_VALUE + 2;
        long node3Id = Long.MIN_VALUE + 1;
        long node4Id = Long.MIN_VALUE;

        Element nodeElem = doc.createElement("node");
        nodeElem.setAttribute("id", String.valueOf(node1Id));
        nodeElem.setAttribute("timestamp", strDate);
        nodeElem.setAttribute("user", "hootenannyuser");
        nodeElem.setAttribute("visible", "true");
        nodeElem.setAttribute("version", "1");
        nodeElem.setAttribute("lat", maxlat);
        nodeElem.setAttribute("lon", minlon);
        osmElem.appendChild(nodeElem);

        nodeElem = doc.createElement("node");
        nodeElem.setAttribute("id", String.valueOf(node2Id));
        nodeElem.setAttribute("timestamp", strDate);
        nodeElem.setAttribute("user", "hootenannyuser");
        nodeElem.setAttribute("visible", "true");
        nodeElem.setAttribute("version", "1");
        nodeElem.setAttribute("lat", maxlat);
        nodeElem.setAttribute("lon", maxlon);
        osmElem.appendChild(nodeElem);

        nodeElem = doc.createElement("node");
        nodeElem.setAttribute("id", String.valueOf(node3Id));
        nodeElem.setAttribute("timestamp", strDate);
        nodeElem.setAttribute("user", "hootenannyuser");
        nodeElem.setAttribute("visible", "true");
        nodeElem.setAttribute("version", "1");
        nodeElem.setAttribute("lat", minlat);
        nodeElem.setAttribute("lon", maxlon);
        osmElem.appendChild(nodeElem);

        nodeElem = doc.createElement("node");
        nodeElem.setAttribute("id", String.valueOf(node4Id));
        nodeElem.setAttribute("timestamp", strDate);
        nodeElem.setAttribute("user", "hootenannyuser");
        nodeElem.setAttribute("visible", "true");
        nodeElem.setAttribute("version", "1");
        nodeElem.setAttribute("lat", minlat);
        nodeElem.setAttribute("lon", minlon);
        osmElem.appendChild(nodeElem);

        Element wayElem = doc.createElement("way");
        wayElem.setAttribute("id", String.valueOf(Long.MIN_VALUE));
        wayElem.setAttribute("timestamp", strDate);
        wayElem.setAttribute("user", "hootenannyuser");
        wayElem.setAttribute("visible", "true");
        wayElem.setAttribute("version", "1");

        Element ndElem = doc.createElement("nd");
        ndElem.setAttribute("ref", String.valueOf(node1Id));
        wayElem.appendChild(ndElem);

        ndElem = doc.createElement("nd");
        ndElem.setAttribute("ref", String.valueOf(node2Id));
        wayElem.appendChild(ndElem);

        ndElem = doc.createElement("nd");
        ndElem.setAttribute("ref", String.valueOf(node3Id));
        wayElem.appendChild(ndElem);

        ndElem = doc.createElement("nd");
        ndElem.setAttribute("ref", String.valueOf(node4Id));
        wayElem.appendChild(ndElem);

        ndElem = doc.createElement("nd");
        ndElem.setAttribute("ref", String.valueOf(node1Id));
        wayElem.appendChild(ndElem);

        /*
         * ndElem = doc.createElement("tag"); ndElem.setAttribute("k", "area");
         * ndElem.setAttribute("v", "yes"); wayElem.appendChild(ndElem);
         */

        osmElem.appendChild(wayElem);

        Transformer tf = TransformerFactory.newInstance().newTransformer();

        // Fortify may require this, but it doesn't work.
        // TransformerFactory transformerFactory =
        // XmlDocumentBuilder.getSecureTransformerFactory();
        tf.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
        tf.setOutputProperty(OutputKeys.INDENT, "yes");

        try (Writer out = new StringWriter()) {
            tf.transform(new DOMSource(doc), new StreamResult(out));
            logger.debug("Layer Extent OSM: {}", out);
        }

        return doc;
    } catch (Exception e) {
        throw new RuntimeException("Error generating OSM extent", e);
    }
}

From source file:com.l2jfree.gameserver.datatables.EnchantHPBonusData.java

private EnchantHPBonusData() {
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    factory.setValidating(true);
    factory.setIgnoringComments(true);/* ww w . j  a  va  2  s .com*/
    File file = new File(Config.DATAPACK_ROOT, "data/enchantHPBonus.xml");
    Document doc = null;

    try {
        doc = factory.newDocumentBuilder().parse(file);
    } catch (Exception e) {
        _log.warn("", e);
        return;
    }

    for (Node n = doc.getFirstChild(); n != null; n = n.getNextSibling()) {
        if ("list".equalsIgnoreCase(n.getNodeName())) {
            for (Node d = n.getFirstChild(); d != null; d = d.getNextSibling()) {
                if ("enchantHP".equalsIgnoreCase(d.getNodeName())) {
                    NamedNodeMap attrs = d.getAttributes();
                    Node att;
                    boolean fullArmor;

                    att = attrs.getNamedItem("grade");
                    if (att == null) {
                        _log.warn("[EnchantHPBonusData] Missing grade, skipping");
                        continue;
                    }

                    int grade = Integer.parseInt(att.getNodeValue());

                    att = attrs.getNamedItem("fullArmor");
                    if (att == null) {
                        _log.warn("[EnchantHPBonusData] Missing fullArmor, skipping");
                        continue;
                    }
                    fullArmor = Boolean.valueOf(att.getNodeValue());

                    att = attrs.getNamedItem("values");
                    if (att == null) {
                        _log.warn("[EnchantHPBonusData] Missing bonus id: " + grade + ", skipping");
                        continue;
                    }
                    StringTokenizer st = new StringTokenizer(att.getNodeValue(), ",");
                    int tokenCount = st.countTokens();
                    Integer[] bonus = new Integer[tokenCount];
                    for (int i = 0; i < tokenCount; i++) {
                        Integer value = Integer.decode(st.nextToken().trim());
                        if (value == null) {
                            _log.warn("[EnchantHPBonusData] Bad Hp value!! grade: " + grade + " FullArmor? "
                                    + fullArmor + " token: " + i);
                            value = 0;
                        }
                        bonus[i] = value;
                    }
                    if (fullArmor)
                        _fullArmorHPBonus.set(grade, bonus);
                    else
                        _singleArmorHPBonus.set(grade, bonus);
                }
            }
        }
    }

    if (_fullArmorHPBonus.isEmpty() && _singleArmorHPBonus.isEmpty())
        return;

    int count = 0;

    for (L2Item item0 : ItemTable.getInstance().getAllTemplates()) {
        if (!(item0 instanceof L2Equip))
            continue;

        final L2Equip item = (L2Equip) item0;

        if (item.getCrystalType() == L2Item.CRYSTAL_NONE)
            continue;

        boolean shouldAdd = false;

        // normally for armors
        if (item instanceof L2Armor) {
            switch (item.getBodyPart()) {
            case L2Item.SLOT_CHEST:
            case L2Item.SLOT_FEET:
            case L2Item.SLOT_GLOVES:
            case L2Item.SLOT_HEAD:
            case L2Item.SLOT_LEGS:
            case L2Item.SLOT_BACK:
            case L2Item.SLOT_FULL_ARMOR:
            case L2Item.SLOT_UNDERWEAR:
            case L2Item.SLOT_L_HAND:
                shouldAdd = true;
                break;
            }
        }
        // shields in the weapons table
        else if (item instanceof L2Weapon) {
            switch (item.getBodyPart()) {
            case L2Item.SLOT_L_HAND:
                shouldAdd = true;
                break;
            }
        }

        if (shouldAdd) {
            count++;
            item.attach(new FuncTemplate(null, "EnchantHp", Stats.MAX_HP, 0x60, 0));
        }
    }

    _log.info("Enchant HP Bonus registered for " + count + " items!");
}

From source file:com.l2jfree.gameserver.datatables.MerchantPriceConfigTable.java

public void loadXML() throws SAXException, IOException, ParserConfigurationException {
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    factory.setValidating(true);
    factory.setIgnoringComments(true);//  w w  w. j a va  2s  .co m
    File file = new File(Config.DATAPACK_ROOT, "data/" + MPCS_FILE);
    if (file.exists()) {
        int defaultPriceConfigId;
        Document doc = factory.newDocumentBuilder().parse(file);

        Node n = doc.getDocumentElement();
        Node dpcNode = n.getAttributes().getNamedItem("defaultPriceConfig");
        if (dpcNode == null) {
            throw new IllegalStateException("merchantPriceConfig must define an 'defaultPriceConfig'");
        }

        defaultPriceConfigId = Integer.parseInt(dpcNode.getNodeValue());

        MerchantPriceConfig mpc;
        for (n = n.getFirstChild(); n != null; n = n.getNextSibling()) {
            mpc = parseMerchantPriceConfig(n);
            if (mpc != null) {
                _mpcs.put(mpc.getId(), mpc);
            }
        }

        MerchantPriceConfig defaultMpc = this.getMerchantPriceConfig(defaultPriceConfigId);
        if (defaultMpc == null) {
            throw new IllegalStateException("'defaultPriceConfig' points to an non-loaded priceConfig");
        }
        _defaultMpc = defaultMpc;
    }
}