Example usage for javax.xml.parsers DocumentBuilderFactory setNamespaceAware

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

Introduction

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

Prototype


public void setNamespaceAware(boolean awareness) 

Source Link

Document

Specifies that the parser produced by this code will provide support for XML namespaces.

Usage

From source file:com.googlecode.jgenhtml.JGenHtmlUtils.java

public static Document loadXmlDoc(final InputStream stream) {
    Document result = null;//from  w  ww  . j  a  v  a2s. c  o m
    try {
        DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance();
        domFactory.setExpandEntityReferences(false);
        domFactory.setNamespaceAware(true);
        DocumentBuilder builder = domFactory.newDocumentBuilder();
        result = builder.parse(stream);

    } catch (SAXException ex) {
        LOGGER.log(Level.SEVERE, ex.getLocalizedMessage());
    } catch (IOException ex) {
        LOGGER.log(Level.SEVERE, ex.getLocalizedMessage());
    } catch (ParserConfigurationException ex) {
        LOGGER.log(Level.SEVERE, ex.getLocalizedMessage());
    }
    return result;
}

From source file:de.ingrid.portal.global.UtilsMapServiceManager.java

public static HashMap createKmlFromIDF(String iPlugId, int documentId)
        throws ConfigurationException, Exception {
    IBUSInterface ibus = IBUSInterfaceImpl.getInstance();
    IngridHit ingridHit = new IngridHit();
    String kmlFile = "";
    HashMap data = new HashMap();
    Record record;// w  w  w  .  j a  v a  2s . c  o  m

    ingridHit.setDocumentId(documentId);
    ingridHit.setPlugId(iPlugId);
    record = ibus.getRecord(ingridHit);

    if (record != null) {
        String idfString = record.getString("data");
        if (idfString != null) {
            DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
            dbf.setNamespaceAware(true);
            DocumentBuilder db;
            db = dbf.newDocumentBuilder();
            Document idfDoc = db.parse(new InputSource(new StringReader(idfString)));

            Node node;
            XPathUtils.getXPathInstance(new IDFNamespaceContext());

            Element rootNode = idfDoc.getDocumentElement();
            if (rootNode != null) {
                if (rootNode.hasChildNodes()) {
                    Node kmlNode = XPathUtils.getNode(rootNode, "./idf:body/kml:kml");
                    evaluateKmlNode(data, kmlNode);
                }
            }

            if (data != null) {
                try {
                    kmlFile = UtilsMapServiceManager.createTemporaryService((String) data.get("coord_class"),
                            (ArrayList) data.get("placemarks"), UtilsFileHelper.KML);
                } catch (ConfigurationException e) {
                    log.error("ConfigurationException" + e);
                } catch (Exception e) {
                    log.error("Exception" + e);
                }
            }
        }
    }

    if (kmlFile != null && kmlFile.length() > 0) {
        data.put("kml_url", "./kml/" + kmlFile);
        data.put("kml_path", getTmpDirectory(getConfig().getString("temp_service_path", null)));
    }
    return data;
}

From source file:gov.nih.nci.ncicb.tcga.dcc.dam.util.TempClinicalDataLoader.java

private static void processBiospecimenXmlFile(final String xmlFile, final String archiveName,
        final String disease, final Date dateAdded) throws ParserConfigurationException, IOException,
        SAXException, SQLException, XPathExpressionException, InstantiationException, IllegalAccessException {

    DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance();
    domFactory.setNamespaceAware(true);
    DocumentBuilder builder = domFactory.newDocumentBuilder();
    Document doc = builder.parse(xmlFile);
    XPathFactory factory = XPathFactory.newInstance();
    XPath xpath = factory.newXPath();
    Patient patient = new Patient();
    Pattern filePattern = Pattern.compile("(TCGA-[A-Z0-9]{2}-[A-Z0-9]{4})");
    Matcher matcher = filePattern.matcher(xmlFile);
    matcher.find();//from www .  j  ava 2 s . c  om
    String patientBarcode = matcher.group(1);
    if (patientBarcode == null) {
        System.out.println("Failed to get patient barcode from filename!");
        System.exit(-1);
    }
    patient.setPatientID(Patient.getPatientIdForBarcode(patientBarcode));
    if (patient.getPatientID() < 1) {
        System.out.println("Could not find PATIENT record for " + patientBarcode + " saving it now...");
        patient.setAttribute("ARCHIVE_NAME", archiveName);
        patient.setAttribute("DISEASE", disease);
        patient.setDateAdded(dateAdded);
        patient.setAttribute("BCRPATIENTBARCODE", patientBarcode);
        patient.insertSelf(0);
    }
    String patientPath = "//" + patient.getXmlElementName() + "[1]";
    processSamples(doc, xpath, patient, patientPath);
}

From source file:gpms.utils.PolicyTestUtil.java

/**
 * This creates the XACML request from a file
 *
 * @param rootDirectory//from   w  ww  . j  a va2  s .co m
 *            root directory of the request files
 * @param versionDirectory
 *            version directory of the request files
 * @param requestId
 *            request file name
 * @return String or null if any error
 */
public static String createRequest(String rootDirectory, String versionDirectory, String requestId) {

    File file = new File(".");
    StringWriter writer = null;
    try {
        String filePath = file.getCanonicalPath() + File.separator + TestConstants.RESOURCE_PATH
                + File.separator + rootDirectory + File.separator + versionDirectory + File.separator
                + TestConstants.REQUEST_DIRECTORY + File.separator + requestId;

        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        factory.setIgnoringComments(true);
        factory.setNamespaceAware(true);
        DocumentBuilder db = factory.newDocumentBuilder();
        Document doc = db.parse(new FileInputStream(filePath));
        DOMSource domSource = new DOMSource(doc);
        writer = new StringWriter();
        StreamResult result = new StreamResult(writer);
        TransformerFactory tf = TransformerFactory.newInstance();
        Transformer transformer = tf.newTransformer();
        transformer.transform(domSource, result);
        return writer.toString();
    } catch (Exception e) {
        log.error("Error while reading expected response from file ", e);
        // ignore any exception and return null
    } finally {
        if (writer != null) {
            try {
                writer.close();
            } catch (IOException e) {
                log.error("Error closing stream ", e);
                // ignore any exception and return null
            }
        }
    }
    return null;
}

From source file:gov.nih.nci.ncicb.tcga.dcc.dam.util.TempClinicalDataLoader.java

private static void processClinicalXmlFile(final String xmlFile, final String archiveName, final String disease,
        final Date dateAdded) throws ParserConfigurationException, IOException, SAXException,
        XPathExpressionException, InstantiationException, IllegalAccessException {
    Patient.setDBConnection(dbConnection);

    // get all patient barcodes
    DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance();
    domFactory.setNamespaceAware(true);
    DocumentBuilder builder = domFactory.newDocumentBuilder();
    Document doc = builder.parse(xmlFile);
    XPathFactory factory = XPathFactory.newInstance();
    XPath xpath = factory.newXPath();

    Patient p = new Patient();
    p.setAttribute("ARCHIVE_NAME", archiveName);
    p.setAttribute("DISEASE", disease);
    p.setDateAdded(dateAdded);/*w  w  w. j av a2  s  .  c o  m*/
    String basePath = "//TCGA_BCR";
    ClinicalBean[] patients = processElementGroup(basePath, doc, xpath, p, 0);
    // for each patient, process its samples
    for (int patient_i = 0; patient_i < patients.length; patient_i++) {
        Patient patient = (Patient) patients[patient_i];

        Sample s = new Sample();
        String patientPath = basePath + "/" + patient.getXmlElementName() + "[" + (patient_i + 1) + "]";

        // patients > drugs
        processElementGroup(patientPath, doc, xpath, new Drug(), patient.getPatientID());

        // patients > radiations
        processElementGroup(patientPath, doc, xpath, new Radiation(), patient.getPatientID());

        // patients > examinations
        processElementGroup(patientPath, doc, xpath, new Examination(), patient.getPatientID());

        // patients > surgeries
        processElementGroup(patientPath, doc, xpath, new Surgery(), patient.getPatientID());
    }
}

From source file:gov.nih.nci.ncicb.tcga.dcc.dam.util.TempClinicalDataLoader.java

private static void processFullXmlFile(final String xmlFile, final String archiveName, final String disease,
        final Date dateAdded) throws ParserConfigurationException, IOException, SAXException,
        XPathExpressionException, InstantiationException, IllegalAccessException {

    Patient.setDBConnection(dbConnection);

    // Create an XPath object from this xml file
    DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance();
    domFactory.setNamespaceAware(true);
    DocumentBuilder builder = domFactory.newDocumentBuilder();
    Document doc = builder.parse(xmlFile);
    XPathFactory factory = XPathFactory.newInstance();
    XPath xpath = factory.newXPath();

    // create the Patient bean for this file
    Patient p = new Patient();
    p.setAttribute("ARCHIVE_NAME", archiveName);
    p.setAttribute("DISEASE", disease);
    p.setDateAdded(dateAdded);/*from  w w w  . j  a v  a 2  s.  com*/
    String basePath = "//TCGA_BCR";

    // process all patients in this file (currently is only 1 but this should work even with multiples)
    ClinicalBean[] patients = processElementGroup(basePath, doc, xpath, p, 0);
    // for each patient, process its clinical elements
    for (int patient_i = 0; patient_i < patients.length; patient_i++) {
        Patient patient = (Patient) patients[patient_i];
        String patientPath = basePath + "/" + patient.getXmlElementName() + "[" + (patient_i + 1) + "]";
        processSamples(doc, xpath, patient, patientPath);
        // patients > drugs
        processElementGroup(patientPath, doc, xpath, new Drug(), patient.getPatientID());

        // patients > radiations
        processElementGroup(patientPath, doc, xpath, new Radiation(), patient.getPatientID());

        // patients > examinations
        processElementGroup(patientPath, doc, xpath, new Examination(), patient.getPatientID());

        // patients > surgeries
        processElementGroup(patientPath, doc, xpath, new Surgery(), patient.getPatientID());
    }

}

From source file:fr.cls.atoll.motu.library.misc.xml.XMLUtils.java

/**
 * Validate xml./*from  w w w  .  j av  a2s . co  m*/
 * 
 * @param inSchemas the in schemas
 * @param inXml the in xml
 * @param schemaLanguage the schema language
 * 
 * @return the xML error handler
 * 
 * @throws MotuException the motu exception
 */
public static XMLErrorHandler validateXML(String[] inSchemas, String inXml, String schemaLanguage)
        throws MotuException {

    XMLErrorHandler errorHandler = new XMLErrorHandler();
    try {

        DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
        documentBuilderFactory.setNamespaceAware(true); // Must enable namespace processing!!!!!
        try {
            documentBuilderFactory.setXIncludeAware(true);
        } catch (Exception e) {
            // Do Nothing
        }
        documentBuilderFactory.setExpandEntityReferences(true);

        documentBuilderFactory.setAttribute(XMLUtils.JAXP_SCHEMA_LANGUAGE, schemaLanguage);
        // final String[] srcSchemas =
        // {"http://schemas.opengis.net/iso/19139/20060504/srv/serviceMetadata.xsd",
        // };

        // final String[] srcSchemas =
        // {"http://opendap.aviso.oceanobs.com/data/ISO_19139/srv/serviceMetadata.xsd",
        // "http://opendap.aviso.oceanobs.com/data/ISO_19139/gco/gco.xsd", };

        // C:\Documents and Settings\dearith\Mes documents\Atoll\SchemaIso\gml
        // final String[] srcSchemas =
        // {"C:/Documents and Settings/us/userocuments/Atoll/SchemaIso/srv/serviceMetadata.xsd",
        // };
        // final String[] srcSchemas = {"schema/iso/srv/serviceMetadata.xsd",
        // };

        documentBuilderFactory.setAttribute(XMLUtils.JAXP_SCHEMA_SOURCE, inSchemas);
        // URL url = Organizer.findResource("schema/iso/srv/srv.xsd");
        // URL url = Organizer.findResource("iso/19139/20070417/srv/serviceMetadata.xsd");
        // documentBuilderFactory.setAttribute("http://java.sun.com/xml/jaxp/properties/schemaSource",
        // url.toString());
        documentBuilderFactory.setValidating(true);

        DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
        // document = documentBuilder.parse(new File(xmlUrl.toURI()));
        documentBuilder.setErrorHandler(errorHandler);
        documentBuilder.parse(inXml);

    } catch (Exception e) {
        throw new MotuException(e);
        // instance document is invalid!
    }

    return errorHandler;
}

From source file:fr.cls.atoll.motu.library.misc.xml.XMLUtils.java

/**
 * Validate xml./*  ww  w.  jav a  2 s .co  m*/
 * 
 * @param inSchemas the in schemas
 * @param inXml the in xml
 * @param schemaLanguage the schema language
 * 
 * @return the xML error handler
 * 
 * @throws MotuException the motu exception
 */
public static XMLErrorHandler validateXML(String[] inSchemas, InputStream inXml, String schemaLanguage)
        throws MotuException {

    XMLErrorHandler errorHandler = new XMLErrorHandler();

    try {

        DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
        documentBuilderFactory.setNamespaceAware(true); // Must enable namespace processing!!!!!
        try {
            documentBuilderFactory.setXIncludeAware(true);
        } catch (Exception e) {
            // Do Nothing
        }
        // documentBuilderFactory.setExpandEntityReferences(true);

        documentBuilderFactory.setAttribute(XMLUtils.JAXP_SCHEMA_LANGUAGE, schemaLanguage);
        // final String[] srcSchemas =
        // {"http://schemas.opengis.net/iso/19139/20060504/srv/serviceMetadata.xsd",
        // };

        // final String[] srcSchemas =
        // {"http://opendap.aviso.oceanobs.com/data/ISO_19139/srv/serviceMetadata.xsd",
        // "http://opendap.aviso.oceanobs.com/data/ISO_19139/gco/gco.xsd", };

        // C:\Documents and Settings\dearith\Mes documents\Atoll\SchemaIso\gml
        // final String[] srcSchemas =
        // {"C:/Documents and Settings/users documents/Atoll/SchemaIso/srv/serviceMetadata.xsd",
        // };
        // final String[] srcSchemas = {"schema/iso/srv/serviceMetadata.xsd",
        // };

        documentBuilderFactory.setAttribute(XMLUtils.JAXP_SCHEMA_SOURCE, inSchemas);
        // URL url = Organizer.findResource("schema/iso/srv/srv.xsd");
        // URL url = Organizer.findResource("iso/19139/20070417/srv/serviceMetadata.xsd");
        // documentBuilderFactory.setAttribute("http://java.sun.com/xml/jaxp/properties/schemaSource",
        // url.toString());
        documentBuilderFactory.setValidating(true);

        DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
        // document = documentBuilder.parse(new File(xmlUrl.toURI()));
        documentBuilder.setErrorHandler(errorHandler);
        documentBuilder.parse(inXml);

    } catch (Exception e) {
        throw new MotuException(e);
        // instance document is invalid!
    }

    return errorHandler;
}

From source file:fr.cls.atoll.motu.library.misc.xml.XMLUtils.java

/**
 * Validate xml./*from   w w w. jav a  2 s .co  m*/
 * 
 * @param inSchemas the in schemas
 * @param inXml the in xml
 * @param schemaLanguage the schema language
 * 
 * @return the xML error handler
 * 
 * @throws MotuException the motu exception
 */
public static XMLErrorHandler validateXML(InputStream[] inSchemas, InputStream inXml, String schemaLanguage)
        throws MotuException {
    // parse an XML document into a DOM tree
    Document document;
    // create a Validator instance, which can be used to validate an instance document
    Validator validator;
    XMLErrorHandler errorHandler = new XMLErrorHandler();

    try {

        DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
        documentBuilderFactory.setNamespaceAware(true); // Must enable namespace processing!!!!!
        try {
            documentBuilderFactory.setXIncludeAware(true);
        } catch (Exception e) {
            // Do Nothing
        }
        // documentBuilderFactory.setExpandEntityReferences(true);

        DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
        // document = documentBuilder.parse(new File(xmlUrl.toURI()));
        documentBuilder.setErrorHandler(errorHandler);
        document = documentBuilder.parse(inXml);

        // create a SchemaFactory capable of understanding WXS schemas
        SchemaFactory schemaFactory = SchemaFactory.newInstance(schemaLanguage);
        schemaFactory.setErrorHandler(errorHandler);

        // load a WXS schema, represented by a Schema instance

        Source[] schemaFiles = new Source[inSchemas.length];

        // InputStream inShema = null;
        int i = 0;
        for (InputStream inSchema : inSchemas) {
            schemaFiles[i] = new StreamSource(inSchema);
            i++;
        }

        Schema schema = schemaFactory.newSchema(schemaFiles);

        validator = schema.newValidator();
        validator.setErrorHandler(errorHandler);
        validator.validate(new DOMSource(document));

    } catch (Exception e) {
        throw new MotuException(e);
        // instance document is invalid!
    }

    return errorHandler;
}

From source file:Main.java

private static synchronized DocumentBuilderFactory getFactory(boolean validate, boolean namespaceAware) {
    DocumentBuilderFactory factory = doms[validate ? 0 : 1][namespaceAware ? 0 : 1];
    if (factory == null) {
        factory = DocumentBuilderFactory.newInstance();
        factory.setValidating(validate);
        factory.setNamespaceAware(namespaceAware);
        doms[validate ? 0 : 1][namespaceAware ? 0 : 1] = factory;
    }//from w w w  .j a  v  a 2  s  .co m
    return factory;
}