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   View source code 8 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   View source code 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: Progetto-C   File: ParticleIO.java   View source code 6 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 4
Project: hadoop   File: TestAMWebServicesJobs.java   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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: javaide   File: FormatFactory.java   View source code 6 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 34
Project: openjdk-jdk10   File: SOAPDocumentImpl.java   View source code 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 35
Project: defense-solutions-proofs-of-concept   File: CoTAdapterInbound.java   View source code 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 36
Project: trashjam2017   File: ParticleIO.java   View source code 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 37
Project: redirector   File: PathRuleWithMultipleNamespacesExpressionTest.java   View source code 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 38
Project: r2-streamer-java   File: EpubParser.java   View source code 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 39
Project: jaffa-framework   File: WSDLTrimmer.java   View source code 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 40
Project: hadoop   File: TestQueuePlacementPolicy.java   View source code 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);
}