Java Code Examples for javax.xml.parsers.DocumentBuilderFactory

The following are top voted examples for showing how to use javax.xml.parsers.DocumentBuilderFactory. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: org.alloytools.alloy   File: InstanceCreator.java   Source Code and License 9 votes vote down vote up
public InstanceCreator(InputStream in) {
	try {
		this.relations = new HashMap<Relation,Set<List<String>>>();
		this.atoms = new LinkedHashSet<String>();

		DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
		DocumentBuilder builder = factory.newDocumentBuilder();
		this.document = builder.parse(in);
	} catch (SAXException sxe) {
		// Error generated during parsing
		Exception x = sxe;
		if (sxe.getException() != null)
			x = sxe.getException();
		throw new InstanceCreationException("Error generated during parsing: " + x.getMessage());

	} catch (ParserConfigurationException pce) {
		// Parser with specified options can't be built
		throw new InstanceCreationException("Parser with specified options cannot be built: " + pce.getMessage());

	} catch (IOException ioe) {
		// I/O error
		throw new InstanceCreationException("I/O error: " + ioe.getMessage());
	} finally {
		try {
			in.close();
		} catch (IOException e) {
			// ignore
		}
	}
}
 
Example 2
Project: alfresco-xml-factory   File: FactoryHelper.java   Source Code and License 8 votes vote down vote up
private void setFeature(DocumentBuilderFactory factory, String feature, boolean enable)
{
    try
    {
        if (ADDITIONAL_FEATURE_X_INCLUDE_AWARE.equals(feature))
        {
            factory.setXIncludeAware(enable);
        }
        else if (ADDITIONAL_FEATURE_EXPAND_ENTITY_REFERENCES.equals(feature))
        {
            factory.setExpandEntityReferences(enable);
        }
        else
        {
            factory.setFeature(feature, enable);
        }
        debug(debugCounter+" DocumentBuilderFactory "+feature+" "+enable);
    }
    catch (ParserConfigurationException pce)
    {
        logConfigurationFailure(factory.getClass().getName(), feature, pce);
    }
}
 
Example 3
Project: javaide   File: FormatFactory.java   Source Code and License 7 votes vote down vote up
private static String formatXml(Context context, String src) throws TransformerException,
        ParserConfigurationException, IOException, SAXException {
    DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
    Document doc = builder.parse(new InputSource(new StringReader(src)));

    AppSetting setting = new AppSetting(context);
    Transformer transformer = TransformerFactory.newInstance().newTransformer();
    transformer.setOutputProperty(OutputKeys.INDENT, "yes");
    transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", setting.getTab().length() + "");
    transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");

    //initialize StreamResult with File object to save to file
    StreamResult result = new StreamResult(new StringWriter());
    DOMSource source = new DOMSource(doc);
    transformer.transform(source, result);
    return result.getWriter().toString();
}
 
Example 4
Project: hadoop   File: TestAMWebServicesJobs.java   Source Code and License 6 votes vote down vote up
@Test
public void testJobAttemptsXML() throws Exception {
  WebResource r = resource();
  Map<JobId, Job> jobsMap = appContext.getAllJobs();
  for (JobId id : jobsMap.keySet()) {
    String jobId = MRApps.toString(id);

    ClientResponse response = r.path("ws").path("v1")
        .path("mapreduce").path("jobs").path(jobId).path("jobattempts")
        .accept(MediaType.APPLICATION_XML).get(ClientResponse.class);
    assertEquals(MediaType.APPLICATION_XML_TYPE, response.getType());
    String xml = response.getEntity(String.class);
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    DocumentBuilder db = dbf.newDocumentBuilder();
    InputSource is = new InputSource();
    is.setCharacterStream(new StringReader(xml));
    Document dom = db.parse(is);
    NodeList attempts = dom.getElementsByTagName("jobAttempts");
    assertEquals("incorrect number of elements", 1, attempts.getLength());
    NodeList info = dom.getElementsByTagName("jobAttempt");
    verifyJobAttemptsXML(info, jobsMap.get(id));
  }
}
 
Example 5
Project: doctemplate   File: DOCXMergeEngine.java   Source Code and License 6 votes vote down vote up
private int getMaxRId(ByteArrayOutputStream xmlStream) throws ParserConfigurationException, SAXException, IOException, XPathExpressionException {

		DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
		DocumentBuilder builder = factory.newDocumentBuilder();
		Document doc = builder.parse(new ByteArrayInputStream(xmlStream.toByteArray()));
		XPathFactory xPathfactory = XPathFactory.newInstance();
		XPath xpath = xPathfactory.newXPath();
		XPathExpression expr = xpath.compile("Relationships/*");
		NodeList nodeList = (NodeList) expr.evaluate(doc, XPathConstants.NODESET);
		for (int i = 0; i < nodeList.getLength(); i++) {
			String id = nodeList.item(i).getAttributes().getNamedItem("Id").getTextContent();
			int idNum = Integer.parseInt(id.substring("rId".length()));
			this.maxRId = idNum > this.maxRId ? idNum : this.maxRId;
		}
		return this.maxRId;
	}
 
Example 6
Project: cas4.0.x-server-wechat   File: SamlUtils.java   Source Code and License 6 votes vote down vote up
private static org.w3c.dom.Document toDom(final Document doc) {
    try {
        final XMLOutputter xmlOutputter = new XMLOutputter();
        final StringWriter elemStrWriter = new StringWriter();
        xmlOutputter.output(doc, elemStrWriter);
        final byte[] xmlBytes = elemStrWriter.toString().getBytes();
        final DocumentBuilderFactory dbf = DocumentBuilderFactory
                .newInstance();
        dbf.setNamespaceAware(true);
        return dbf.newDocumentBuilder().parse(
                new ByteArrayInputStream(xmlBytes));
    } catch (final Exception e) {
        return null;
    }
}
 
Example 7
Project: openjdk-jdk10   File: Bug5072946.java   Source Code and License 6 votes vote down vote up
@Test
public void test1() throws Exception {

    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    dbf.setNamespaceAware(true);
    DocumentBuilder parser = dbf.newDocumentBuilder();
    Document dom = parser.parse(Bug5072946.class.getResourceAsStream("Bug5072946.xml"));

    SchemaFactory sf = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
    Schema s = sf.newSchema(Bug5072946.class.getResource("Bug5072946.xsd"));
    Validator v = s.newValidator();

    DOMResult r = new DOMResult();
    // r.setNode(dbf.newDocumentBuilder().newDocument());
    v.validate(new DOMSource(dom), r);

    Node node = r.getNode();
    Assert.assertNotNull(node);
    Node fc = node.getFirstChild();
    Assert.assertTrue(fc instanceof Element);
    Element e = (Element) fc;

    Assert.assertEquals("value", e.getAttribute("foo"));
}
 
Example 8
Project: ChronoBike   File: Tag.java   Source Code and License 6 votes vote down vote up
public boolean load(InputStream s)
{
	try
	{
		Source file = new StreamSource(s) ;
		Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument() ;
		Result res = new DOMResult(doc) ;
		TransformerFactory tr = TransformerFactory.newInstance();
		Transformer xformer = tr.newTransformer();
		xformer.transform(file, res);
		m_doc = doc;
		m_elem = m_doc.getDocumentElement();			
		return true;
	}
	catch (Exception e)
	{
		LogTagError.log(e);
		return false;
	}		
}
 
Example 9
Project: TuLiPA-frames   File: DOMderivationBuilder.java   Source Code and License 6 votes vote down vote up
public static Document buildDOMderivation(ArrayList<ParseTreeCollection> all, String sentence) {
	try {
		DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
		DocumentBuilder constructor    = factory.newDocumentBuilder();
		derivDoc                       = constructor.newDocument();
		derivDoc.setXmlVersion("1.0");
		derivDoc.setXmlStandalone(false);
		
		Element root = derivDoc.createElement("parses");
		root.setAttribute("sentence", sentence);
           for (ParseTreeCollection ptc : all)
           {
           	buildOne(root, ptc.getDerivationTree().getDomNodes().get(0), ptc.getDerivedTree().getDomNodes().get(0), ptc.getSemantics(), ptc.getSpecifiedSemantics());
           }
		// finally we do not forget the root
		derivDoc.appendChild(root);
		return derivDoc;
		
	} catch (ParserConfigurationException e) {
		System.err.println(e);
		return null;
	}		
}
 
Example 10
Project: L2J-Global   File: ScriptDocument.java   Source Code and License 6 votes vote down vote up
public ScriptDocument(String name, InputStream input)
{
	_name = name;
	
	final DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
	try
	{
		final DocumentBuilder builder = factory.newDocumentBuilder();
		_document = builder.parse(input);
		
	}
	catch (SAXException sxe)
	{
		// Error generated during parsing)
		Exception x = sxe;
		if (sxe.getException() != null)
		{
			x = sxe.getException();
		}
		_log.warning(getClass().getSimpleName() + ": " + x.getMessage());
	}
	catch (ParserConfigurationException pce)
	{
		// Parser with specified options can't be built
		_log.log(Level.WARNING, "", pce);
		
	}
	catch (IOException ioe)
	{
		// I/O error
		_log.log(Level.WARNING, "", ioe);
	}
}
 
Example 11
Project: elastic-db-tools-for-java   File: SqlResults.java   Source Code and License 6 votes vote down vote up
/**
 * Constructs an instance of StoreLogEntry using parts of a row from ResultSet. Used for creating the store operation for Undo.
 *
 * @param reader
 *            ResultSet whose row has operation information.
 * @param offset
 *            Reader offset for column that begins operation information.
 */
public static StoreLogEntry readLogEntry(ResultSet reader,
        int offset) throws SQLException {
    try {
        UUID shardIdRemoves = StringUtilsLocal.isNullOrEmpty(reader.getString(offset + 4)) ? null : UUID.fromString(reader.getString(offset + 4));
        UUID shardIdAdds = StringUtilsLocal.isNullOrEmpty(reader.getString(offset + 5)) ? null : UUID.fromString(reader.getString(offset + 5));
        Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(reader.getSQLXML(offset + 2).getBinaryStream());

        return new StoreLogEntry(UUID.fromString(reader.getString(offset)), StoreOperationCode.forValue(reader.getInt(offset + 1)),
                (Element) doc.getFirstChild(), StoreOperationState.forValue(reader.getInt(offset + 3)), shardIdRemoves, shardIdAdds);
    }
    catch (SAXException | IOException | ParserConfigurationException e) {
        e.printStackTrace();
        return null;
    }
}
 
Example 12
Project: NavyCraft2-Lite   File: XMLHandler.java   Source Code and License 6 votes vote down vote up
public static void load() {
	File dir = NavyCraft.instance.getDataFolder();
	if (!dir.exists())
		dir.mkdir();
	
	File config = new File(NavyCraft.instance.getDataFolder(), NavyCraft.instance.configFile.filename);
	if (!config.exists()) {
		return;
	}
	Document doc = null;
	try {
		DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
		DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
		doc = dBuilder.parse(config.toURI().getPath());
		doc.getDocumentElement().normalize();
		
		NodeList list;
		
		for(Object configLine : NavyCraft.instance.configFile.ConfigSettings.keySet().toArray()) {
			String configKey = (String) configLine;

			list = doc.getElementsByTagName(configKey);
			
			try {
				String value = list.item(0).getChildNodes().item(0).getNodeValue();
				NavyCraft.instance.configFile.ConfigSettings.put(configKey, value);
			} catch (Exception ex){

			}
		}
	}
	catch (Exception e) {
		e.printStackTrace();
	}
}
 
Example 13
Project: EVE   File: Weather.java   Source Code and License 6 votes vote down vote up
private void generateForecast(String c) throws IOException, SAXException, TransformerException, ParserConfigurationException {
    city = c;

    // creating the URL
    String url = "http://api.openweathermap.org/data/2.5/forecast/daily?q=" + city + ",us&mode=xml&cnt=6&appid=" + APIKey;

    // printing out XML
    URL urlString = new URL(url);
    URLConnection conn = urlString.openConnection();

    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    DocumentBuilder builder = factory.newDocumentBuilder();
    Document doc = builder.parse(conn.getInputStream());

    TransformerFactory transformer = TransformerFactory.newInstance();
    Transformer xform = transformer.newTransformer();

    xform.transform(new DOMSource(doc), new StreamResult(System.out));
}
 
Example 14
Project: openjdk-jdk10   File: Bug6941169Test.java   Source Code and License 6 votes vote down vote up
private static Document getDocument(InputStream in) {

        Document document = null;

        try {
            DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
            dbf.setNamespaceAware(true);
            DocumentBuilder db = dbf.newDocumentBuilder();
            document = db.parse(in);
        } catch (Exception e) {
            e.printStackTrace();
            Assert.fail(e.toString());
        }

        return document;
    }
 
Example 15
Project: OpenJSharp   File: EPRHeader.java   Source Code and License 6 votes vote down vote up
public void writeTo(SOAPMessage saaj) throws SOAPException {
        try {
            // TODO what about in-scope namespaces
            // Not very efficient consider implementing a stream buffer
            // processor that produces a DOM node from the buffer.
            Transformer t = XmlUtil.newTransformer();
            SOAPHeader header = saaj.getSOAPHeader();
            if (header == null)
                header = saaj.getSOAPPart().getEnvelope().addHeader();
// TODO workaround for oracle xdk bug 16555545, when this bug is fixed the line below can be
// uncommented and all lines below, except the catch block, can be removed.
//            t.transform(epr.asSource(localName), new DOMResult(header));
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            XMLStreamWriter w = XMLOutputFactory.newFactory().createXMLStreamWriter(baos);
            epr.writeTo(localName, w);
            w.flush();
            ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());
            DocumentBuilderFactory fac = DocumentBuilderFactory.newInstance();
            fac.setNamespaceAware(true);
            Node eprNode = fac.newDocumentBuilder().parse(bais).getDocumentElement();
            Node eprNodeToAdd = header.getOwnerDocument().importNode(eprNode, true);
            header.appendChild(eprNodeToAdd);
        } catch (Exception e) {
            throw new SOAPException(e);
        }
    }
 
Example 16
Project: openjdk-jdk10   File: AuctionController.java   Source Code and License 6 votes vote down vote up
/**
 * Check usage of TypeInfo interface introduced in DOM L3.
 *
 * @throws Exception If any errors occur.
 */
@Test
public void testGetTypeInfo() throws Exception {
    String xmlFile = XML_DIR + "accountInfo.xml";

    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    dbf.setNamespaceAware(true);
    dbf.setValidating(true);
    dbf.setAttribute(JAXP_SCHEMA_LANGUAGE, W3C_XML_SCHEMA_NS_URI);

    DocumentBuilder docBuilder = dbf.newDocumentBuilder();
    docBuilder.setErrorHandler(new MyErrorHandler());

    Document document = docBuilder.parse(xmlFile);
    Element userId = (Element)document.getElementsByTagNameNS(PORTAL_ACCOUNT_NS, "UserID").item(0);
    TypeInfo typeInfo = userId.getSchemaTypeInfo();
    assertTrue(typeInfo.getTypeName().equals("nonNegativeInteger"));
    assertTrue(typeInfo.getTypeNamespace().equals(W3C_XML_SCHEMA_NS_URI));

    Element role = (Element)document.getElementsByTagNameNS(PORTAL_ACCOUNT_NS, "Role").item(0);
    TypeInfo roletypeInfo = role.getSchemaTypeInfo();
    assertTrue(roletypeInfo.getTypeName().equals("BuyOrSell"));
    assertTrue(roletypeInfo.getTypeNamespace().equals(PORTAL_ACCOUNT_NS));
}
 
Example 17
Project: HawkEngine   File: Game.java   Source Code and License 6 votes vote down vote up
public void LoadCustomBehavior(String filePath, boolean resourcesIncluded)
{
	DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
	DocumentBuilder dBuilder;
	Document doc = null;
	try
	{
		dBuilder = dbFactory.newDocumentBuilder();
		doc = dBuilder.parse(new File((resourcesIncluded ? "Resources/" : "") + filePath));
	} catch (Exception e)
	{
		e.printStackTrace();
		return;
	}

	//TODO: Load into behavior class
}
 
Example 18
Project: mobileAutomation   File: XmlDoc.java   Source Code and License 6 votes vote down vote up
/**
 * Create a new XML doc with root element. 
 *
 * @param rootName - the tagName of the root element
 */
public XmlDoc( String rootName )
{
	final DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance( );
	DocumentBuilder db = null;
	
	try
	{
		db = dbf.newDocumentBuilder( );
	}
	catch ( ParserConfigurationException e )
	{
		logger.log(""+e);
		throw new TestCaseFailure(e.getMessage());
	}
	
	Doc = db.newDocument( );
	final Element root = Doc.createElement( rootName );
	Doc.appendChild( root );
}
 
Example 19
Project: openjdk-jdk10   File: AuctionController.java   Source Code and License 6 votes vote down vote up
/**
 * Check for DOMErrorHandler handling DOMError. Before fix of bug 4896132
 * test throws DOM Level 1 node error.
 *
 * @throws Exception If any errors occur.
 */
@Test
public void testCreateNewItem2SellRetry() throws Exception  {
    String xmlFile = XML_DIR + "accountInfo.xml";

    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    dbf.setNamespaceAware(true);
    Document document = dbf.newDocumentBuilder().parse(xmlFile);

    DOMConfiguration domConfig = document.getDomConfig();
    MyDOMErrorHandler errHandler = new MyDOMErrorHandler();
    domConfig.setParameter("error-handler", errHandler);

    DOMImplementationLS impl =
         (DOMImplementationLS) DOMImplementationRegistry.newInstance()
                 .getDOMImplementation("LS");
    LSSerializer writer = impl.createLSSerializer();
    MyDOMOutput domoutput = new MyDOMOutput();

    domoutput.setByteStream(System.out);
    writer.write(document, domoutput);

    document.normalizeDocument();
    writer.write(document, domoutput);
    assertFalse(errHandler.isError());
}
 
Example 20
Project: openrouteservice   File: TrafficUtility.java   Source Code and License 6 votes vote down vote up
public static Date getMessageDateTime(String tmcMessage) throws ParserConfigurationException, SAXException,
		IOException, ParseException {
	DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
	DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();
	InputStream stream = new ByteArrayInputStream(tmcMessage.getBytes(StandardCharsets.UTF_8));
	Document doc = docBuilder.parse(stream);

	doc.getDocumentElement().normalize();
	String timeStamp = doc.getDocumentElement().getAttribute("FGT");

	// FGT="2014-05-01T15:06:00"
	SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
	formatter.setTimeZone(TimeZone.getTimeZone("UTC"));
	
	return formatter.parse(timeStamp);
}
 
Example 21
Project: hadoop   File: TestNMWebServices.java   Source Code and License 6 votes vote down vote up
@Test
public void testSingleNodesXML() throws JSONException, Exception {
  WebResource r = resource();
  ClientResponse response = r.path("ws").path("v1").path("node")
      .path("info/").accept(MediaType.APPLICATION_XML)
      .get(ClientResponse.class);
  assertEquals(MediaType.APPLICATION_XML_TYPE, response.getType());
  String xml = response.getEntity(String.class);
  DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
  DocumentBuilder db = dbf.newDocumentBuilder();
  InputSource is = new InputSource();
  is.setCharacterStream(new StringReader(xml));
  Document dom = db.parse(is);
  NodeList nodes = dom.getElementsByTagName("nodeInfo");
  assertEquals("incorrect number of elements", 1, nodes.getLength());
  verifyNodesXML(nodes);
}
 
Example 22
Project: Blockly   File: BlocklyActivityHelper.java   Source Code and License 6 votes vote down vote up
/**
 * @param fileName
 * @return
 */
public String convertXMLFileToString(String fileName) {

    try {
        DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
        InputStream inputStream = new FileInputStream(new File(fileName));
        org.w3c.dom.Document doc = documentBuilderFactory.newDocumentBuilder().parse(inputStream);
        StringWriter stw = new StringWriter();
        Transformer serializer = TransformerFactory.newInstance().newTransformer();
        serializer.transform(new DOMSource(doc), new StreamResult(stw));
        return stw.toString();
    } catch (Exception e) {
        e.printStackTrace();
    }
    return null;
}
 
Example 23
Project: Android_Code_Arbiter   File: DocumentBuilderSafeProperty.java   Source Code and License 6 votes vote down vote up
/**
 * This implementation allow DTD but disable all its dangerous features.
 * Not sure it can still do something useful with DTD ...
 */
public static void safeManualConfiguration() throws ParserConfigurationException, IOException, SAXException {
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    dbf.setFeature("http://xml.org/sax/features/external-general-entities",true);
    dbf.setFeature("http://xml.org/sax/features/external-parameter-entities",true);
    dbf.setXIncludeAware(false);
    dbf.setExpandEntityReferences(false);
    DocumentBuilder db = dbf.newDocumentBuilder();

    Document doc = db.parse(getInputFile());
    print(doc);
}
 
Example 24
Project: redirector   File: ModelTranslationService.java   Source Code and License 6 votes vote down vote up
public URLRuleModel translateUrlRules(URLRules source, NamespacedListRepository namespacedLists) {
    String urlRulesXML = getUrlRulesXML(source);
    URLRuleModel model = null;
    try {
        if (StringUtils.isNotBlank(urlRulesXML)) {
            DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
            Document newDocument = builder.parse(new ByteArrayInputStream(urlRulesXML.getBytes(UTF8_CHARSET)));
            model = new URLRuleModel(newDocument, namespacedLists);
            log.info("Rules created from xml: \n{}", urlRulesXML);
        } else {
            log.error("Trying to init null model");
        }
    } catch (Exception ex) {
        log.error("Exception while creating model from xml: \n{}Root cause: {}", urlRulesXML, ex.getCause().getMessage());
    }

    return model;
}
 
Example 25
Project: Shopping-Cart-using-Web-Services   File: MyClientSOAP.java   Source Code and License 6 votes vote down vote up
private void parseUserActionResponse(String xml){
	messageList = new ArrayList<String>();
	//get the factory
	DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
	try {
		DocumentBuilder db = dbf.newDocumentBuilder();
		domARB = db.parse(new InputSource(new StringReader(xml)));
		domARB.getDocumentElement().normalize();
		NodeList nList = domARB.getElementsByTagName("messagetouser");
		messageList.clear();
		//put all message from server in a list
	    for (int temp = 0; temp < nList.getLength(); temp++) {
	        Node nNode = nList.item(temp);
	        if (nNode.getNodeType() == Node.ELEMENT_NODE) {
	        	Element eElement = (Element) nNode; 
	        	messageList.add(eElement.getTextContent());
	        }
	    }
	    //catch total items returned from server
	    totalItem=domARB.getElementsByTagName("totalitem").item(0).getTextContent();
	    
	}catch(ParserConfigurationException pce) {			pce.printStackTrace();
	}catch(SAXException se) {							se.printStackTrace();
	}catch(IOException ioe) {							ioe.printStackTrace();
	}catch (Exception e){								e.printStackTrace();
	}
}
 
Example 26
Project: openjdk-jdk10   File: Bug6531160.java   Source Code and License 6 votes vote down vote up
@Test
public void testDOMLevel1Validation() throws Exception {
    SchemaFactory fact = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
    Schema schema = fact.newSchema(new StreamSource(new StringReader(XSD)));
    DocumentBuilderFactory docfact = DocumentBuilderFactory.newInstance();
    docfact.setNamespaceAware(true);

    Document doc = docfact.newDocumentBuilder().newDocument();
    doc.appendChild(doc.createElement("root"));

    try {
        schema.newValidator().validate(new DOMSource(doc));
    } catch (SAXParseException e) {
        Assert.fail("Validation failed: " + e.getMessage());
    }
}
 
Example 27
Project: mockkid   File: XMLBodyVariableResolver.java   Source Code and License 6 votes vote down vote up
public static String extractValueFromXml(String name, HttpServletRequest request) {
    try {
        DocumentBuilderFactory builderFactory =
                DocumentBuilderFactory.newInstance();
        DocumentBuilder builder = builderFactory.newDocumentBuilder();
        Document document = builder.parse(((MockkidRequest) request).getSafeInputStream());

        XPath xPath =  XPathFactory.newInstance().newXPath();
        String expression = name.replace("body", "").replaceAll("\\.", "/");
        String result = xPath.compile(expression).evaluate(document);
        if (result.isEmpty()) return null; //empty string can mean node doesn't exist, or value is empty
        return result;
    } catch (Exception e) {
        logger.warn("Couldn't extract variable", e);
    }
    return null;
}
 
Example 28
Project: openjdk-jdk10   File: Bug6513892.java   Source Code and License 6 votes vote down vote up
@Test
public void test0() {
    try {
        TransformerFactory tf = TransformerFactory.newInstance();
        Transformer t = tf.newTransformer(new StreamSource(getClass().getResourceAsStream("redirect.xsl"), getClass().getResource("redirect.xsl")
                .toString()));

        StreamSource src1 = new StreamSource(getClass().getResourceAsStream("redirect.xml"));
        t.transform(src1, new StreamResult("redirect1.xml"));

        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        DocumentBuilder db = dbf.newDocumentBuilder();

        Document d1 = db.parse(new File("redirect1.xml"));
        Document d2 = db.parse(new File("redirect2.xml"));

        Assert.assertTrue(d1.getDocumentElement().getFirstChild().getNodeValue().equals(d2.getDocumentElement().getFirstChild().getNodeValue()));
    } catch (Exception e) {
        Assert.fail(e.getMessage());
    }
}
 
Example 29
Project: hadoop   File: TestHsWebServicesJobConf.java   Source Code and License 6 votes vote down vote up
@Test
public void testJobConfXML() throws JSONException, Exception {
  WebResource r = resource();
  Map<JobId, Job> jobsMap = appContext.getAllJobs();
  for (JobId id : jobsMap.keySet()) {
    String jobId = MRApps.toString(id);

    ClientResponse response = r.path("ws").path("v1").path("history").path("mapreduce")
        .path("jobs").path(jobId).path("conf")
        .accept(MediaType.APPLICATION_XML).get(ClientResponse.class);
    assertEquals(MediaType.APPLICATION_XML_TYPE, response.getType());
    String xml = response.getEntity(String.class);
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    DocumentBuilder db = dbf.newDocumentBuilder();
    InputSource is = new InputSource();
    is.setCharacterStream(new StringReader(xml));
    Document dom = db.parse(is);
    NodeList info = dom.getElementsByTagName("conf");
    verifyHsJobConfXML(info, jobsMap.get(id));
  }
}
 
Example 30
Project: openjdk-jdk10   File: DocumentBuilderFactoryTest.java   Source Code and License 6 votes vote down vote up
/**
 * Test the default functionality of schema support method. In
 * this case the schema source property is set.
 * @throws Exception If any errors occur.
 */
@Test(dataProvider = "schema-source")
public void testCheckSchemaSupport2(Object schemaSource) throws Exception {
    try {
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        dbf.setValidating(true);
        dbf.setNamespaceAware(true);
        dbf.setAttribute("http://java.sun.com/xml/jaxp/properties/schemaLanguage",
                W3C_XML_SCHEMA_NS_URI);
        dbf.setAttribute("http://java.sun.com/xml/jaxp/properties/schemaSource", schemaSource);
        MyErrorHandler eh = MyErrorHandler.newInstance();
        DocumentBuilder db = dbf.newDocumentBuilder();
        db.setErrorHandler(eh);
        db.parse(new File(XML_DIR, "test1.xml"));
        assertFalse(eh.isErrorOccured());
    } finally {
        if (schemaSource instanceof Closeable) {
            ((Closeable) schemaSource).close();
        }
    }

}
 
Example 31
Project: springboot-shiro-cas-mybatis   File: AbstractSamlObjectBuilder.java   Source Code and License 6 votes vote down vote up
/**
 * Convert the received jdom doc to a Document element.
 *
 * @param doc the doc
 * @return the org.w3c.dom. document
 */
private org.w3c.dom.Document toDom(final Document doc) {
    try {
        final XMLOutputter xmlOutputter = new XMLOutputter();
        final StringWriter elemStrWriter = new StringWriter();
        xmlOutputter.output(doc, elemStrWriter);
        final byte[] xmlBytes = elemStrWriter.toString().getBytes(Charset.defaultCharset());
        final DocumentBuilderFactory dbf = DocumentBuilderFactory
                .newInstance();
        dbf.setNamespaceAware(true);
        return dbf.newDocumentBuilder().parse(
                new ByteArrayInputStream(xmlBytes));
    } catch (final Exception e) {
        logger.trace(e.getMessage(), e);
        return null;
    }
}
 
Example 32
Project: hadoop   File: TestAMWebServicesJobs.java   Source Code and License 6 votes vote down vote up
@Test
public void testJobIdXML() throws Exception {
  WebResource r = resource();
  Map<JobId, Job> jobsMap = appContext.getAllJobs();
  for (JobId id : jobsMap.keySet()) {
    String jobId = MRApps.toString(id);

    ClientResponse response = r.path("ws").path("v1").path("mapreduce")
        .path("jobs").path(jobId).accept(MediaType.APPLICATION_XML)
        .get(ClientResponse.class);
    assertEquals(MediaType.APPLICATION_XML_TYPE, response.getType());
    String xml = response.getEntity(String.class);
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    DocumentBuilder db = dbf.newDocumentBuilder();
    InputSource is = new InputSource();
    is.setCharacterStream(new StringReader(xml));
    Document dom = db.parse(is);
    NodeList job = dom.getElementsByTagName("job");
    verifyAMJobXML(job, appContext);
  }

}
 
Example 33
Project: openjdk-jdk10   File: SOAPDocumentImpl.java   Source Code and License 5 votes vote down vote up
private Document createDocument() {
    DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance("com.sun.org.apache.xerces.internal.jaxp.DocumentBuilderFactoryImpl", SAAJUtil.getSystemClassLoader());
    try {
        final DocumentBuilder documentBuilder = docFactory.newDocumentBuilder();
        return documentBuilder.newDocument();
    } catch (ParserConfigurationException e) {
        throw new RuntimeException("Error creating xml document", e);
    }
}
 
Example 34
Project: defense-solutions-proofs-of-concept   File: CoTAdapterInbound.java   Source Code and License 5 votes vote down vote up
private NodeList unpackXML(String xml, String targetTag) throws Exception {
	try {
		DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
		DocumentBuilder db = dbf.newDocumentBuilder();
		InputSource source = new InputSource();
		source.setCharacterStream(new StringReader(xml));
		Document doc = db.parse(source);
		NodeList nodeList = doc.getElementsByTagName(targetTag);
		return nodeList;
	} catch (Exception e) {
		log.error(e);
		log.error(e.getStackTrace());
		throw (e);
	}
}
 
Example 35
Project: trashjam2017   File: ParticleIO.java   Source Code and License 5 votes vote down vote up
/**
 * Save a single emitter to the XML file
 * 
 * @param out
 *            The location to which we should save
 * @param emitter
 *            The emitter to store to the XML file
 * @throws IOException
 *             Indicates a failure to write or encode the XML
 */
public static void saveEmitter(OutputStream out, ConfigurableEmitter emitter)
		throws IOException {
	try {
		DocumentBuilder builder = DocumentBuilderFactory.newInstance()
				.newDocumentBuilder();
		Document document = builder.newDocument();

		document.appendChild(emitterToElement(document, emitter));
		Result result = new StreamResult(new OutputStreamWriter(out,
				"utf-8"));
		DOMSource source = new DOMSource(document);

		TransformerFactory factory = TransformerFactory.newInstance();
		Transformer xformer = factory.newTransformer();
		xformer.setOutputProperty(OutputKeys.INDENT, "yes");

		xformer.transform(source, result);
	} catch (Exception e) {
		Log.error(e);
		throw new IOException("Failed to save emitter");
	}
}
 
Example 36
Project: redirector   File: PathRuleWithMultipleNamespacesExpressionTest.java   Source Code and License 5 votes vote down vote up
private static Document fromString(String xmlString) {
    try {
        return DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(new ByteArrayInputStream(xmlString.getBytes()));
    } catch (Exception ex) {
        throw new RuntimeException(ex);
    }
}
 
Example 37
Project: r2-streamer-java   File: EpubParser.java   Source Code and License 5 votes vote down vote up
private String containerXmlParser(String containerData) throws EpubParserException {           //parsing container.xml
    try {
        String xml = containerData.replaceAll("[^\\x20-\\x7e]", "").trim();         //in case encoding problem

        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        DocumentBuilder builder = factory.newDocumentBuilder();
        Document document = builder.parse(new InputSource(new StringReader(xml)));
        document.getDocumentElement().normalize();
        if (document == null) {
            throw new EpubParserException("Error while parsing container.xml");
        }

        Element rootElement = (Element) ((Element) document.getDocumentElement().getElementsByTagName("rootfiles").item(0)).getElementsByTagName("rootfile").item(0);
        if (rootElement != null) {
            String opfFile = rootElement.getAttribute("full-path");
            if (opfFile == null) {
                throw new EpubParserException("Missing root file element in container.xml");
            }

            //Log.d(TAG, "Root file: " + opfFile);
            return opfFile;                    //returns opf file
        }
    } catch (ParserConfigurationException | SAXException | IOException e) {
        e.printStackTrace();
    }
    return null;
}
 
Example 38
Project: jaffa-framework   File: WSDLTrimmer.java   Source Code and License 5 votes vote down vote up
/**
 * Trims the sourceWSDL based on the excludedFields that are declared for the graphClass associated with the input WebService implementation class.
 * The targetWSDL will be generated as a result.
 * @param sourceWSDL a source WSDL.
 * @param targetWSDLToGenerate the WSDL to generate.
 * @param webServiceImplementationClassName the WebService implementation class that may have an annotation declaring the need for WSDL trimming.
 */
public static void trim(File sourceWSDL, File targetWSDLToGenerate, String webServiceImplementationClassName) throws ParserConfigurationException, SAXException, IOException, TransformerConfigurationException, TransformerException, ClassNotFoundException {
    Map<Class, Collection<String>> excludedFields = getExcludedFields(webServiceImplementationClassName);
    if (excludedFields != null && excludedFields.size() > 0) {
        if (log.isDebugEnabled())
            log.debug("Trimming '" + sourceWSDL + "' by excluding " + excludedFields);

        //Parse the source WSDL
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        factory.setNamespaceAware(true);
        DocumentBuilder parser = factory.newDocumentBuilder();
        Document document = parser.parse(sourceWSDL);

        //Trim the source WSDL
        trim(document.getDocumentElement(), excludedFields);

        //Generate the target WSDL
        if (log.isDebugEnabled())
            log.debug("Generating: " + targetWSDLToGenerate);
        Source source = new DOMSource(document);
        Result result = new StreamResult(targetWSDLToGenerate);
        TransformerFactory transformerFactory = TransformerFactory.newInstance();
        //transformerFactory.setAttribute("indent-number", 2);
        Transformer transformer = transformerFactory.newTransformer();
        transformer.setOutputProperty(OutputKeys.INDENT, "yes");
        transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
        transformer.transform(source, result);
    } else if (!sourceWSDL.equals(targetWSDLToGenerate)) {
        if (log.isDebugEnabled())
            log.debug("None of the fields are excluded. '" + targetWSDLToGenerate + "'  will be created as a copy of '" + sourceWSDL + '\'');
        copy(sourceWSDL, targetWSDLToGenerate);
    }
}
 
Example 39
Project: Progetto-C   File: ParticleIO.java   Source Code and License 5 votes vote down vote up
/**
 * Save a single emitter to the XML file
 * 
 * @param out
 *            The location to which we should save
 * @param emitter
 *            The emitter to store to the XML file
 * @throws IOException
 *             Indicates a failure to write or encode the XML
 */
public static void saveEmitter(OutputStream out, ConfigurableEmitter emitter)
		throws IOException {
	try {
		DocumentBuilder builder = DocumentBuilderFactory.newInstance()
				.newDocumentBuilder();
		Document document = builder.newDocument();

		document.appendChild(emitterToElement(document, emitter));
		Result result = new StreamResult(new OutputStreamWriter(out,
				"utf-8"));
		DOMSource source = new DOMSource(document);

		TransformerFactory factory = TransformerFactory.newInstance();
		Transformer xformer = factory.newTransformer();
		xformer.setOutputProperty(OutputKeys.INDENT, "yes");

		xformer.transform(source, result);
	} catch (Exception e) {
		Log.error(e);
		throw new IOException("Failed to save emitter");
	}
}
 
Example 40
Project: hadoop   File: TestQueuePlacementPolicy.java   Source Code and License 5 votes vote down vote up
private QueuePlacementPolicy parse(String str) throws Exception {
  // Read and parse the allocations file.
  DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory
      .newInstance();
  docBuilderFactory.setIgnoringComments(true);
  DocumentBuilder builder = docBuilderFactory.newDocumentBuilder();
  Document doc = builder.parse(IOUtils.toInputStream(str));
  Element root = doc.getDocumentElement();
  return QueuePlacementPolicy.fromXml(root, configuredQueues, conf);
}
 
Example 41
Project: Android_Code_Arbiter   File: DocumentBuilderSafeProperty.java   Source Code and License 5 votes vote down vote up
public static void unsafeNoSpecialSettings() throws ParserConfigurationException, IOException, SAXException {
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    DocumentBuilder db = dbf.newDocumentBuilder();

    Document doc = db.parse(getInputFile());
    print(doc);
}
 
Example 42
Project: OpenJSharp   File: DOMForest.java   Source Code and License 5 votes vote down vote up
public DOMForest( InternalizationLogic logic, Options opt ) {

        if (opt == null) throw new AssertionError("Options object null");
        this.options = opt;

        try {
            DocumentBuilderFactory dbf = XmlFactory.createDocumentBuilderFactory(opt.disableXmlSecurity);
            this.documentBuilder = dbf.newDocumentBuilder();
            this.parserFactory = XmlFactory.createParserFactory(opt.disableXmlSecurity);
        } catch( ParserConfigurationException e ) {
            throw new AssertionError(e);
        }

        this.logic = logic;
    }
 
Example 43
Project: lams   File: LineitemUtil.java   Source Code and License 5 votes vote down vote up
private static boolean hasLessonScoreOutputs(Content bbContent, String username) throws IOException, ParserConfigurationException, SAXException {

//at this moment bbContent contains already updated lessonId
String lessonId = bbContent.getLinkRef();

String serviceURL = LamsPluginUtil.getServerUrl() + "/services/xml/LessonManager?"
	+ LamsSecurityUtil.generateAuthenticateParameters(username)
	+ "&method=checkLessonForNumericToolOutputs&lsId=" + lessonId;

URL url = new URL(serviceURL);
URLConnection conn = url.openConnection();
if (!(conn instanceof HttpURLConnection)) {
    throw new RuntimeException("Unable to open connection to: " + serviceURL);
}

HttpURLConnection httpConn = (HttpURLConnection) conn;

if (httpConn.getResponseCode() != HttpURLConnection.HTTP_OK) {
    throw new RuntimeException("HTTP Response Code: " + httpConn.getResponseCode() + ", HTTP Response Message: "
	    + httpConn.getResponseMessage());
}

InputStream is = conn.getInputStream();

// parse xml response
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document document = db.parse(is);
Element lesson = document.getDocumentElement();
boolean hasNumericToolOutput = Boolean
	.parseBoolean(lesson.getAttributes().getNamedItem("hasNumericToolOutput").getNodeValue());

return hasNumericToolOutput;
   }
 
Example 44
Project: k-framework   File: XMLParser.java   Source Code and License 5 votes vote down vote up
public static Map<String,Object> getMapFromXML(String xmlString) throws ParserConfigurationException, IOException, SAXException {

        //这里用Dom的方式解析回包的最主要目的是防止API新增回包字段
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        DocumentBuilder builder = factory.newDocumentBuilder();
        InputStream is =  Util.getStringStream(xmlString);
        Document document = builder.parse(is);

        //获取到document里面的全部结点
        NodeList allNodes = document.getFirstChild().getChildNodes();
        Node node;
        Map<String, Object> map = new HashMap<String, Object>();
        int i=0;
        while (i < allNodes.getLength()) {
            node = allNodes.item(i);
            if(node instanceof Element){
                map.put(node.getNodeName(),node.getTextContent());
            }
            i++;
        }
        return map;

    }
 
Example 45
Project: onvifjava   File: SoapClient.java   Source Code and License 5 votes vote down vote up
public SoapClient(OnvifDevice device) throws Exception {
	if (device == null)
		throw new IllegalArgumentException("Device can't be null");
	this.onvifDevice = device;
	soapConnectionFactory = SOAPConnectionFactory.newInstance();
	messageFactory = MessageFactory.newInstance(SOAPConstants.SOAP_1_2_PROTOCOL);
	documentBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
}
 
Example 46
Project: javaide   File: MergedResourceWriter.java   Source Code and License 5 votes vote down vote up
@Override
public void start(@NonNull DocumentBuilderFactory factory) throws ConsumerException {
    super.start(factory);
    mValuesResMap = ArrayListMultimap.create();
    mQualifierWithDeletedValues = Sets.newHashSet();
    mFactory = factory;
}
 
Example 47
Project: jmt   File: XMLMeasureOutput.java   Source Code and License 5 votes vote down vote up
/**
 * Creates a DOM (Document Object Model) <code>Document<code> for XMLMeasureOutput.
 */
private void createDOM() {
	try {
		DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
		DocumentBuilder builder = factory.newDocumentBuilder();

		//data is a Document
		document = builder.newDocument();

		root = document.createElement("measureOutput");

		root.setAttribute("name", name);
		root.setAttribute("precision", Double.toString(measure.getAnalyzer().getPrecision()));
		root.setAttribute("alfa", Double.toString(measure.getAnalyzer().getAlfa()));
		root.setAttribute("maxSamples", Integer.toString(measure.getMaxSamples()));

		report = document.createElement("report");
		report.setAttribute("meanValue", "null");
		report.setAttribute("upperBound", "null");
		report.setAttribute("lowerBound", "null");
		report.setAttribute("finished", "false");
		report.setAttribute("successful", "false");
		report.setAttribute("isZero", "false");
		report.setAttribute("analyzedSamples", "0");
		report.setAttribute("discardedSamples", "0");

		root.appendChild(report);

		samples = document.createElement("samples");
	} catch (FactoryConfigurationError factoryConfigurationError) {
		factoryConfigurationError.printStackTrace();
	} catch (ParserConfigurationException e) {
		e.printStackTrace();
	}
}
 
Example 48
Project: openjdk-jdk10   File: AuctionController.java   Source Code and License 5 votes vote down vote up
/**
 * Check validation API features. A schema which is including in Bug 4909119
 * used to be testing for the functionalities.
 *
 * @throws Exception If any errors occur.
 * @see <a href="content/userDetails.xsd">userDetails.xsd</a>
 */
@Test
public void testGetOwnerInfo() throws Exception {
    String schemaFile = XML_DIR + "userDetails.xsd";
    String xmlFile = XML_DIR + "userDetails.xml";

    try(FileInputStream fis = new FileInputStream(xmlFile)) {
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        dbf.setNamespaceAware(true);
        dbf.setAttribute(JAXP_SCHEMA_LANGUAGE, W3C_XML_SCHEMA_NS_URI);

        SchemaFactory schemaFactory = SchemaFactory.newInstance(W3C_XML_SCHEMA_NS_URI);
        Schema schema = schemaFactory.newSchema(Paths.get(schemaFile).toFile());

        Validator validator = schema.newValidator();
        MyErrorHandler eh = new MyErrorHandler();
        validator.setErrorHandler(eh);

        DocumentBuilder docBuilder = dbf.newDocumentBuilder();
        docBuilder.setErrorHandler(eh);

        Document document = docBuilder.parse(fis);
        DOMResult dResult = new DOMResult();
        DOMSource domSource = new DOMSource(document);
        validator.validate(domSource, dResult);
        assertFalse(eh.isAnyError());
    }
}
 
Example 49
Project: ISO8583   File: PayloadMessageConfig.java   Source Code and License 5 votes vote down vote up
public ISOTestVO getISOTestVOFromXML(String xmlToParse) throws ParseException {
	ISOTestVO testVO = new ISOTestVO();
	
	try {
		String xml = new Parser().parseText(xmlToParse);
		
		DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
		DocumentBuilder builder = factory.newDocumentBuilder();
	    InputSource is = new InputSource(new StringReader(xml));
	    
		Document document = builder.parse(is);
		NodeList nodeList = document.getDocumentElement().getChildNodes();
		Node node;
		
		for (int i = 0; i < nodeList.getLength(); i++) {
			node = nodeList.item(i);
			
			if ("test-iso".equalsIgnoreCase(node.getNodeName())) {
				testVO.setConfigFile(ISOUtils.getAttr(node, "config-file", ""));
				testVO.setRequestSync(ISOUtils.getAttr(node, "request-sync", "false").equals("true"));
				testVO.setResponseSync(ISOUtils.getAttr(node, "response-sync", "false").equals("true"));
			}
		}
	}
	catch (Exception x) {
		throw new ParseException("Error parsing the XML.\n\n" + x.getMessage());
	}
	
	return testVO;
}
 
Example 50
Project: ShotgunWSD   File: SemEval2007Parser.java   Source Code and License 5 votes vote down vote up
private void loadDocumentBuilder(DocumentBuilderFactory dbFactory) {
    try {
        this.dBuilder = dbFactory.newDocumentBuilder();
    } catch (ParserConfigurationException e) {
        e.printStackTrace();
    }
}
 
Example 51
Project: bohemia   File: XmlUtils.java   Source Code and License 5 votes vote down vote up
/** 
 * Creates a new document instance. 
 * 
 * @return a new document instance 
 * @throws XmlException problem creating a new document 
 */  
public static Document newDocument() throws XmlException {  
    Document doc = null;  
  
    try {  
        doc = DocumentBuilderFactory.newInstance().newDocumentBuilder()  
                .newDocument();  
    } catch (ParserConfigurationException e) {  
        throw new XmlException(e);  
    }  
  
    return doc;  
}
 
Example 52
Project: pretty-android-lint   File: Parser.java   Source Code and License 5 votes vote down vote up
/**
 * Parse lint-results.xml file and returns list of {@link Issue}s.
 */
public List<Issue> parseFile(File file) {
  DocumentBuilder builder;
  Document doc;
  try {
    builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
    doc = builder.parse(file);
  } catch (Exception e) {
    // TODO: handle exception
    throw new IllegalStateException("problem while parsing", e);
  }
  doc.getDocumentElement().normalize();

  List<Issue> issues = new ArrayList<>();
  NodeList nodes = doc.getElementsByTagName("issues").item(0).getChildNodes();
  for (int i = 0; i < nodes.getLength(); i++) {
    Node node = nodes.item(i);
    if (node.getNodeType() == Node.ELEMENT_NODE) {
      Element element = (Element) node;
      Severity severity = Severity.valueOf(element.getAttribute("severity").toUpperCase());
      if (Severity.WARNING.equals(severity)) {
        // Ignore warning for now
        continue;
      }
      String type = element.getAttribute("id");
      String message = element.getAttribute("message");
      Location location = parseLocation(
          (Element) element.getElementsByTagName("location").item(0));
      // TODO: validate input
      issues.add(
          new Issue(type, severity, message, location));
    }
  }
  return issues;
}
 
Example 53
Project: encdroidMC   File: SardineUtil.java   Source Code and License 5 votes vote down vote up
/**
 * @return New XML document from the default document builder factory.
 */
private static Document createDocument()
{
	DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
	DocumentBuilder builder;
	try
	{
		builder = factory.newDocumentBuilder();
	}
	catch (ParserConfigurationException e)
	{
		throw new RuntimeException(e.getMessage(), e);
	}
	return builder.newDocument();
}
 
Example 54
Project: octane-cucumber-jvm   File: HPEAlmOctaneGherkinFormatter.java   Source Code and License 5 votes vote down vote up
public HPEAlmOctaneGherkinFormatter(ResourceLoader resourceLoader, List<String> features, OutputFile outputFile) {
    cucumberFeatures = features;
    cucumberResourceLoader = resourceLoader;
    this.outputFile = outputFile;
    try {
        _doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();
        _rootElement = _doc.createElement(GherkinSerializer.ROOT_TAG_NAME);
        _rootElement.setAttribute("version",Constants.XML_VERSION);
        _doc.appendChild(_rootElement);
    } catch (ParserConfigurationException e) {
        throw new CucumberException(Constants.errorPrefix + "Failed to create xml document",e);
    }
}
 
Example 55
Project: openjdk-jdk10   File: TransformerTest.java   Source Code and License 5 votes vote down vote up
/**
 * This tests getOutputProperty() method of Transformer.
 *
 * @throws Exception If any errors occur.
 */
@Test
public void transformer06() throws Exception {
    TransformerFactory tfactory = TransformerFactory.newInstance();

    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    dbf.setNamespaceAware(true);
    DocumentBuilder db = dbf.newDocumentBuilder();
    Document document = db.parse(new File(TEST_XSL));
    DOMSource domSource = new DOMSource(document);

    Transformer transformer = tfactory.newTransformer(domSource);
    assertEquals(transformer.getOutputProperty("method"), "xml");
}
 
Example 56
Project: karate   File: KarateJunitFormatter.java   Source Code and License 5 votes vote down vote up
public KarateJunitFormatter(String featurePath, String reportPath) throws IOException {
    this.featurePath = featurePath;
    this.reportPath = reportPath;
    logger.trace(">> {}", reportPath);
    URL url = FileUtils.toFileUrl(reportPath);
    this.out = new UTF8OutputStreamWriter(new URLOutputStream(url));
    try {
        doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();
        rootElement = doc.createElement("testsuite");
        doc.appendChild(rootElement);
    } catch (ParserConfigurationException e) {
        throw new CucumberException("Error while processing unit report", e);
    }
}
 
Example 57
Project: Cognizant-Intelligent-Test-Scripter   File: XMLOperation.java   Source Code and License 5 votes vote down vote up
public static Document initTreeOpFromString(String xml) {
    try {
        DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
        return docBuilder.parse(new InputSource(new StringReader(xml)));
    } catch (ParserConfigurationException | SAXException | IOException ex) {
        Logger.getLogger(XMLOperation.class.getName()).log(Level.SEVERE, null, ex);
    }
    return null;
}
 
Example 58
Project: BookyMcBookface   File: EpubBook.java   Source Code and License 5 votes vote down vote up
private static Map<String,?> processToc(BufferedReader tocReader) {
    Map<String,Object> bookdat = new LinkedHashMap<>();

    DocumentBuilderFactory dfactory = DocumentBuilderFactory.newInstance();
    XPathFactory factory = XPathFactory.newInstance();
    DocumentBuilder builder = null;
    try {
        builder = dfactory.newDocumentBuilder();

        tocReader.mark(4);
        if ('\ufeff' != tocReader.read()) tocReader.reset(); // not the BOM marker

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

        XPath tocPath = factory.newXPath();
        tocPath.setNamespaceContext(tocnsc);

        Node nav = (Node)tocPath.evaluate("/ncx/navMap", doc, XPathConstants.NODE);

        int total = readNavPoint(nav, tocPath, bookdat, 0);
        bookdat.put(TOCCOUNT, total);

    } catch (ParserConfigurationException | IOException | SAXException | XPathExpressionException e) {
        Log.e("BMBF", "Error parsing xml " + e.getMessage(), e);
    }
    return bookdat;
}
 
Example 59
Project: ascii_generate   File: GetEmoticons.java   Source Code and License 5 votes vote down vote up
private void writeFile(String title, ArrayList<String> list) throws IOException, ParserConfigurationException, TransformerException {
    System.out.println("GetEmoticons.writeFile");
    System.out.println("title = " + title);
    System.out.println("list = " + list);
    if (title == null || list == null || list.isEmpty()) return;
    String fileName = title.replaceAll("\\W", "") + ".xml";
    File file = new File("C:\\github\\AsciiGenerator\\app\\src\\main\\assets\\emoticons\\" + fileName);
    if (!file.getParentFile().exists()) file.getParentFile().mkdirs();
    DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
    DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
    org.w3c.dom.Document document = documentBuilder.newDocument();
    org.w3c.dom.Element root = document.createElement("root");
    document.appendChild(root);

    org.w3c.dom.Element name = document.createElement("name");
    name.appendChild(document.createTextNode(title));
    root.appendChild(name);

    org.w3c.dom.Element data = document.createElement("data");

    for (String s : list) {
        org.w3c.dom.Element item = document.createElement("item");
        item.appendChild(document.createTextNode(s));
        data.appendChild(item);
    }
    root.appendChild(data);

    TransformerFactory transformerFactory = TransformerFactory.newInstance();
    Transformer transformer = transformerFactory.newTransformer();
    DOMSource domSource = new DOMSource(document);
    StreamResult streamResult = new StreamResult(file);
    transformer.transform(domSource, streamResult);
}
 
Example 60
Project: swallow-core   File: DocumentParser.java   Source Code and License 5 votes vote down vote up
public DocumentParser() {
    try {
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        builder = factory.newDocumentBuilder();
    } catch (ParserConfigurationException e) {
        e.printStackTrace();
    }
}