Java Code Examples for javax.xml.parsers.DocumentBuilder

The following are top voted examples for showing how to use javax.xml.parsers.DocumentBuilder. 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: Android_Code_Arbiter   File: DocumentBuilderSafeProperty.java   View source code 9 votes vote down vote up
public static void unsafeManualConfig3() 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 2
Project: Hydrograph   File: XMLUtil.java   View source code 9 votes vote down vote up
/**
 * 
 * Convert XML string to {@link Document}
 * 
 * @param xmlString
 * @return {@link Document}
 */
public static Document convertStringToDocument(String xmlString) {
       DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();  
       DocumentBuilder builder;  
       try 
       {  
       	factory.setFeature(Constants.DISALLOW_DOCTYPE_DECLARATION,true);
           builder = factory.newDocumentBuilder();  
           Document doc = builder.parse( new InputSource( new StringReader( xmlString ) ) );            
           
           return doc;
       } catch (ParserConfigurationException| SAXException| IOException e) {  
       	logger.debug("Unable to convert string to Document",e);  
       } 
       return null;
   }
 
Example 3
Project: FunnyCreator   File: FunnyMaven.java   View source code 8 votes vote down vote up
public void prepare() throws Exception {
    this.funnyCreator.info("Extracting maven");
    ZipUtils.unzipResource("/apache-maven-3.5.0.zip", FunnyConstants.MAVEN_DIRECTORY.getPath());

    this.invoker = new DefaultInvoker();
    this.invoker.setMavenHome(FunnyConstants.MAVEN_DIRECTORY);

    if (!FunnyConstants.BUILD_DIRECTORY.exists()) {
        FileUtils.forceMkdir(FunnyConstants.BUILD_DIRECTORY);
    }

    FunnyCreator.getLogger().info("Parse pom.xml");

    DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
    DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();

    Document doc = dBuilder.parse(new File(FunnyConstants.REPOSITORY_DIRECTORY, "pom.xml"));
    doc.getDocumentElement().normalize();

    this.projectElement = (Element) doc.getElementsByTagName("project").item(0);
}
 
Example 4
Project: trashjam2017   File: XMLPackedSheet.java   View source code 7 votes vote down vote up
/**
 * Create a new XML packed sheet from the XML output by the slick tool
 * 
 * @param imageRef The reference to the image
 * @param xmlRef The reference to the XML
 * @throws SlickException Indicates a failure to parse the XML or read the image
 */
public XMLPackedSheet(String imageRef, String xmlRef) throws SlickException
{
	image = new Image(imageRef, false, Image.FILTER_NEAREST);

	try {
		DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
		Document doc = builder.parse(ResourceLoader.getResourceAsStream(xmlRef));
		
		NodeList list = doc.getElementsByTagName("sprite");
		for (int i=0;i<list.getLength();i++) {
			Element element = (Element) list.item(i);
			
			String name = element.getAttribute("name");
			int x = Integer.parseInt(element.getAttribute("x"));
			int y = Integer.parseInt(element.getAttribute("y"));
			int width = Integer.parseInt(element.getAttribute("width"));
			int height = Integer.parseInt(element.getAttribute("height"));
			
			sprites.put(name, image.getSubImage(x,y,width,height));
		}
	} catch (Exception e) {
		throw new SlickException("Failed to parse sprite sheet XML", e);
	}
}
 
Example 5
Project: openjdk-jdk10   File: Bug8073385.java   View source code 7 votes vote down vote up
@Test(dataProvider = "illegalCharactersData")
public void test(int character) throws Exception {
    // Construct the XML document as a String
    int[] cps = new int[]{character};
    String txt = new String(cps, 0, cps.length);
    String inxml = "<topElement attTest=\'" + txt + "\'/>";
    String exceptionText = "NO EXCEPTION OBSERVED";
    String hexString = "0x" + Integer.toHexString(character);

    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    dbf.setNamespaceAware(true);
    dbf.setValidating(false);
    DocumentBuilder db = dbf.newDocumentBuilder();
    InputSource isrc = new InputSource(new StringReader(inxml));

    try {
        db.parse(isrc);
    } catch (SAXException e) {
        exceptionText = e.toString();
    }
    System.out.println("Got Exception:" + exceptionText);
    assertTrue(exceptionText.contains("attribute \"attTest\""));
    assertTrue(exceptionText.contains("element is \"topElement\""));
    assertTrue(exceptionText.contains("Unicode: " + hexString));
}
 
Example 6
Project: verify-hub   File: SoapMessageManager.java   View source code 7 votes vote down vote up
public Document wrapWithSoapEnvelope(Element element) {
    DocumentBuilder documentBuilder;
    try {
        documentBuilder = newDocumentBuilder();
    } catch (ParserConfigurationException e) {
        LOG.error("*** ALERT: Failed to create a document builder when trying to construct the the soap message. ***", e);
        throw propagate(e);
    }
    Document document = documentBuilder.newDocument();
    document.adoptNode(element);
    Element envelope = document.createElementNS("http://schemas.xmlsoap.org/soap/envelope/", "soapenv:Envelope");
    Element body = document.createElementNS("http://schemas.xmlsoap.org/soap/envelope/", "soapenv:Body");
    envelope.appendChild(body);
    body.appendChild(element);
    document.appendChild(envelope);

    return document;
}
 
Example 7
Project: hadoop   File: TestConfServlet.java   View source code 6 votes vote down vote up
@Test
public void testWriteXml() throws Exception {
  StringWriter sw = new StringWriter();
  ConfServlet.writeResponse(getTestConf(), sw, "xml");
  String xml = sw.toString();

  DocumentBuilderFactory docBuilderFactory 
    = DocumentBuilderFactory.newInstance();
  DocumentBuilder builder = docBuilderFactory.newDocumentBuilder();
  Document doc = builder.parse(new InputSource(new StringReader(xml)));
  NodeList nameNodes = doc.getElementsByTagName("name");
  boolean foundSetting = false;
  for (int i = 0; i < nameNodes.getLength(); i++) {
    Node nameNode = nameNodes.item(i);
    String key = nameNode.getTextContent();
    System.err.println("xml key: " + key);
    if (TEST_KEY.equals(key)) {
      foundSetting = true;
      Element propertyElem = (Element)nameNode.getParentNode();
      String val = propertyElem.getElementsByTagName("value").item(0).getTextContent();
      assertEquals(TEST_VAL, val);
    }
  }
  assertTrue(foundSetting);
}
 
Example 8
Project: openjdk-jdk10   File: TCKEncodingTest.java   View source code 6 votes vote down vote up
/**
 * Assertion testing
 * for public String getInputEncoding(),
 * Encoding is not specified. getInputEncoding returns null..
 */
@Test
public void testGetInputEncoding002() {
    Document doc = null;
    try {
        DocumentBuilder db = DocumentBuilderFactory.newInstance().newDocumentBuilder();
        doc = db.newDocument();
    } catch (ParserConfigurationException e) {
        Assert.fail(e.toString());
    }

    String encoding = doc.getInputEncoding();
    if (encoding != null) {
        Assert.fail("expected encoding: null, returned: " + encoding);
    }

    System.out.println("OK");
}
 
Example 9
Project: fb2parser   File: FictionBook.java   View source code 6 votes vote down vote up
public FictionBook(File file) throws ParserConfigurationException, IOException, SAXException, OutOfMemoryError {
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    DocumentBuilder db = dbf.newDocumentBuilder();
    InputStream inputStream = new FileInputStream(file);
    BufferedReader br = new BufferedReader(new FileReader(file));
    String encoding = "utf-8";
    try {
        String line = br.readLine();
        encoding = line.substring(line.indexOf("encoding=\"") + 10, line.indexOf("\"?>"));
    } catch (Exception e) {
        e.printStackTrace();
    }
    Document doc = db.parse(new InputSource(new InputStreamReader(inputStream, encoding)));
    initXmlns(doc);
    description = new Description(doc);
    NodeList bodyNodes = doc.getElementsByTagName("body");
    for (int item = 0; item < bodyNodes.getLength(); item++) {
        bodies.add(new Body(bodyNodes.item(item)));
    }
    NodeList binary = doc.getElementsByTagName("binary");
    for (int item = 0; item < binary.getLength(); item++) {
        Binary binary1 = new Binary(binary.item(item));
        binaries.put(binary1.getId().replace("#", ""), binary1);
    }
}
 
Example 10
Project: javaide   File: XmlUtils.java   View source code 6 votes vote down vote up
/**
 * Parses the given UTF file as a DOM document, using the JDK parser. The parser does not
 * validate, and is optionally namespace aware.
 *
 * @param file           the UTF encoded file to parse
 * @param namespaceAware whether the parser is namespace aware
 * @return the DOM document
 */
@NonNull
public static Document parseUtfXmlFile(@NonNull File file, boolean namespaceAware)
        throws ParserConfigurationException, IOException, SAXException {
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    Reader reader = getUtfReader(file);
    try {
        InputSource is = new InputSource(reader);
        factory.setNamespaceAware(namespaceAware);
        factory.setValidating(false);
        DocumentBuilder builder = factory.newDocumentBuilder();
        return builder.parse(is);
    } finally {
        reader.close();
    }
}
 
Example 11
Project: personium-core   File: DavCmpFsImpl.java   View source code 6 votes vote down vote up
private Element parseProp(String value) {
    // valをDOMでElement化
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    factory.setNamespaceAware(true);
    DocumentBuilder builder = null;
    Document doc = null;
    try {
        builder = factory.newDocumentBuilder();
        ByteArrayInputStream is = new ByteArrayInputStream(value.getBytes(CharEncoding.UTF_8));
        doc = builder.parse(is);
    } catch (Exception e1) {
        throw PersoniumCoreException.Dav.DAV_INCONSISTENCY_FOUND.reason(e1);
    }
    Element e = doc.getDocumentElement();
    return e;
}
 
Example 12
Project: openjdk-jdk10   File: AbstractMethodErrorTest.java   View source code 6 votes vote down vote up
public static void main(String[] args) throws Exception {
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    DocumentBuilder builder = factory.newDocumentBuilder();
    Document document = builder.newDocument();

    DOMImplementation impl = document.getImplementation();
    DOMImplementationLS implLS = (DOMImplementationLS) impl.getFeature("LS", "3.0");
    LSSerializer dsi = implLS.createLSSerializer();

    /* We should have here incorrect document without getXmlVersion() method:
     * Such Document is generated by replacing the JDK bootclasses with it's
     * own Node,Document and DocumentImpl classes (see run.sh). According to
     * XERCESJ-1007 the AbstractMethodError should be thrown in such case.
     */
    String result = dsi.writeToString(document);
    System.out.println("Result:" + result);
}
 
Example 13
Project: FEFEditor   File: GuiData.java   View source code 6 votes vote down vote up
protected GuiData() {
    try {
        DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();

        Document doc = dBuilder.parse(FEFEditor.class.getResourceAsStream("data/xml/FileTypes.xml"));
        doc.getDocumentElement().normalize();
        NodeList nList = doc.getDocumentElement().getElementsByTagName("FatesTypes").item(0).getChildNodes();
        for (int x = 0; x < nList.getLength(); x++) {
            if (nList.item(x).getNodeType() == Node.ELEMENT_NODE)
                baseTypes.add(nList.item(x).getAttributes().getNamedItem("name").getNodeValue());
        }
        nList = doc.getDocumentElement().getElementsByTagName("DLC").item(0).getChildNodes();
        for (int x = 0; x < nList.getLength(); x++) {
            if (nList.item(x).getNodeType() == Node.ELEMENT_NODE)
                dlcTypes.add(nList.item(x).getAttributes().getNamedItem("name").getNodeValue());
        }
        nList = doc.getDocumentElement().getElementsByTagName("Awakening").item(0).getChildNodes();
        for (int x = 0; x < nList.getLength(); x++) {
            if (nList.item(x).getNodeType() == Node.ELEMENT_NODE)
                awakeningTypes.add(nList.item(x).getAttributes().getNamedItem("name").getNodeValue());
        }
    } catch (Exception ex) {
        ex.printStackTrace();
    }
}
 
Example 14
Project: ibench   File: AbstractCheckExpectedOutputTester.java   View source code 6 votes vote down vote up
public void compareFile(String fileLeft, String fileRight) throws SAXException, IOException, ParserConfigurationException, TransformerException {
	DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
	dbf.setNamespaceAware(true);
	dbf.setCoalescing(true);
	dbf.setIgnoringElementContentWhitespace(true);
	dbf.setIgnoringComments(true);

	DocumentBuilder db = dbf.newDocumentBuilder();

	Document doc1 = db.parse(new File(expectedPath + "/" + fileRight + ".xml"));
	doc1.normalizeDocument();

	Document doc2 = db.parse(new File(OUT_DIR + "/" + fileLeft + ".xml"));
	doc2.normalizeDocument();

	assertEquals("Output <" + fileLeft + "> is not the same as expected output <" +
			fileRight + ">", 
			docToString(doc1), 
			docToString(doc2));
}
 
Example 15
Project: hadoop   File: TestAMWebServicesTasks.java   View source code 6 votes vote down vote up
@Test
public void testJobTaskCountersXML() throws Exception {
  WebResource r = resource();
  Map<JobId, Job> jobsMap = appContext.getAllJobs();
  for (JobId id : jobsMap.keySet()) {
    String jobId = MRApps.toString(id);
    for (Task task : jobsMap.get(id).getTasks().values()) {

      String tid = MRApps.toString(task.getID());
      ClientResponse response = r.path("ws").path("v1").path("mapreduce")
          .path("jobs").path(jobId).path("tasks").path(tid).path("counters")
          .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("jobTaskCounters");
      verifyAMTaskCountersXML(info, task);
    }
  }
}
 
Example 16
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 17
Project: litiengine   File: EditorScreen.java   View source code 6 votes vote down vote up
private void loadCustomEmitters(String projectPath) {
  for (String xmlFile : FileUtilities.findFilesByExtension(new ArrayList<>(), Paths.get(projectPath), "xml")) {
    boolean isEmitter = false;
    DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
    try {
      DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
      Document doc = dBuilder.parse(xmlFile);
      doc.getDocumentElement().normalize();
      if (doc.getDocumentElement().getNodeName().equalsIgnoreCase("emitter")) {
        isEmitter = true;
      }
    } catch (SAXException | IOException | ParserConfigurationException e) {
      log.log(Level.SEVERE, e.getLocalizedMessage(), e);
    }

    if (isEmitter) {
      CustomEmitter.load(xmlFile);
    }
  }
}
 
Example 18
Project: L2jBrasil   File: ScriptDocument.java   View source code 6 votes vote down vote up
public ScriptDocument(String name, InputStream input)
{
    _name = name;

    DocumentBuilderFactory factory =
        DocumentBuilderFactory.newInstance();
    try {
       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();
       x.printStackTrace();

    } catch (ParserConfigurationException pce) {
        // Parser with specified options can't be built
        pce.printStackTrace();

    } catch (IOException ioe) {
       // I/O error
       ioe.printStackTrace();
    }
}
 
Example 19
Project: pmTrans   File: EditingPane.java   View source code 6 votes vote down vote up
public void loadTranscription(File transcriptionFile)
		throws ParserConfigurationException, SAXException, IOException {
	text.setText("");

	DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
	DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
	Document doc = dBuilder.parse(transcriptionFile);

	// Text
	text.setText(doc.getElementsByTagName("text").item(0).getTextContent());

	// Timestamps
	NodeList nList = doc.getElementsByTagName("timeStamp");
	for (int temp = 0; temp < nList.getLength(); temp++) {
		Element timestamp = (Element) nList.item(temp);
		printTimestamp(Integer.parseInt(timestamp.getAttribute("start")),
				Integer.parseInt(timestamp.getAttribute("lenght")));
	}

	changed = false;
}
 
Example 20
Project: VISNode   File: VersionFinder.java   View source code 6 votes vote down vote up
/**
 * Returns the version
 * 
 * @return String
 */
public static String getVersion() {
    String jarImplementation = VISNode.class.getPackage().getImplementationVersion();
    if (jarImplementation != null) {
        return jarImplementation;
    }
    String file = VISNode.class.getResource(".").getFile();
    String pack = VISNode.class.getPackage().getName().replace(".", "/") + '/';
    File pomXml = new File(file.replace("target/classes/" + pack, "pom.xml"));
    if (pomXml.exists()) {
        try {
            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            DocumentBuilder builder = factory.newDocumentBuilder();
            Document document = builder.parse(new InputSource(new FileReader(pomXml)));
            XPath xPath = XPathFactory.newInstance().newXPath();
            return (String) xPath.evaluate("/project/version", document, XPathConstants.STRING);
        } catch (IOException | ParserConfigurationException | XPathExpressionException | SAXException e) { }
    }
    return "Unknown version";
}
 
Example 21
Project: lams   File: WebdavServlet.java   View source code 6 votes vote down vote up
/**
 * Return JAXP document builder instance.
 */
protected DocumentBuilder getDocumentBuilder()
    throws ServletException {
    DocumentBuilder documentBuilder = null;
    DocumentBuilderFactory documentBuilderFactory = null;
    try {
        documentBuilderFactory = DocumentBuilderFactory.newInstance();
        documentBuilderFactory.setNamespaceAware(true);
        documentBuilderFactory.setExpandEntityReferences(false);
        documentBuilder = documentBuilderFactory.newDocumentBuilder();
        documentBuilder.setEntityResolver(
                new WebdavResolver(this.getServletContext()));
    } catch(ParserConfigurationException e) {
        throw new ServletException
            (sm.getString("webdavservlet.jaxpfailed"));
    }
    return documentBuilder;
}
 
Example 22
Project: fluentxml4j   File: TransformationChain.java   View source code 6 votes vote down vote up
public Document transformToDocument()
{
	try
	{
		DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
		documentBuilderFactory.setNamespaceAware(true);
		DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
		Document document = documentBuilder.newDocument();

		transformTo(new DOMResult(document));
		return document;
	}
	catch (ParserConfigurationException ex)
	{
		throw new FluentXmlConfigurationException(ex);
	}

}
 
Example 23
Project: oscm   File: TriggerServiceBean.java   View source code 6 votes vote down vote up
private VOService getVOServiceFromTrigger(TriggerProcess triggerProcess,
    DocumentBuilder builder, XPathExpression serviceIdXpath) {
    TriggerProcessParameter triggerProcessParameter = triggerProcess
        .getParamValueForName(TriggerProcessParameterName.PRODUCT);
    String product;
    try {
        product = AESEncrypter
            .decrypt(triggerProcessParameter.getSerializedValue());
    } catch (GeneralSecurityException e) {
        product = triggerProcessParameter.getSerializedValue();
    }
    String serviceId = retrieveValueByXpath(product, builder,
        serviceIdXpath);
    if (serviceId == null) {
        return null;
    }
    VOService voService = new VOService();
    voService.setServiceId(serviceId);
    return voService;
}
 
Example 24
Project: hadoop   File: TestHsWebServicesJobs.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("history")
        .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");
    verifyHsJobAttemptsXML(info, appContext.getJob(id));
  }
}
 
Example 25
Project: Equella   File: PropBagEx.java   View source code 6 votes vote down vote up
public void setXML(final Reader reader)
{
	final BufferedReader filterer = new BufferedReader(new BadCharacterFilterReader(reader));
	DocumentBuilder builder = null;
	try
	{
		builder = getBuilder();
		Document doc = builder.parse(new InputSource(filterer));

		// Get the root element
		m_elRoot = doc.getDocumentElement();
	}
	catch( Exception ex )
	{
		throw new RuntimeException("Error parsing XML", ex);
	}
	finally
	{
		releaseBuilder(builder);
	}
}
 
Example 26
Project: hadoop   File: TestHsWebServicesJobs.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("history")
        .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");
    verifyHsJobXML(job, appContext);
  }

}
 
Example 27
Project: defense-solutions-proofs-of-concept   File: CoTUtilities.java   View source code 6 votes vote down vote up
public static ArrayList<CoTTypeDef> getCoTTypeMap(InputStream mapInputStream) throws ParserConfigurationException, SAXException, IOException
{

	ArrayList<CoTTypeDef> types = null;

	String content = getStringFromFile(mapInputStream);


	DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
	DocumentBuilder db = dbf.newDocumentBuilder();
	InputSource source = new InputSource();
	source.setCharacterStream(new StringReader(content));
	Document doc = db.parse(source);
	NodeList nodeList = doc.getElementsByTagName("types");
	types = typeBreakdown(nodeList.item(0));
	return types;
}
 
Example 28
Project: hadoop   File: TestRMWebServicesApps.java   View source code 6 votes vote down vote up
@Test
public void testAppsXML() throws JSONException, Exception {
  rm.start();
  MockNM amNodeManager = rm.registerNode("127.0.0.1:1234", 2048);
  RMApp app1 = rm.submitApp(CONTAINER_MB, "testwordcount", "user1");
  amNodeManager.nodeHeartbeat(true);
  WebResource r = resource();
  ClientResponse response = r.path("ws").path("v1").path("cluster")
      .path("apps").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 nodesApps = dom.getElementsByTagName("apps");
  assertEquals("incorrect number of elements", 1, nodesApps.getLength());
  NodeList nodes = dom.getElementsByTagName("app");
  assertEquals("incorrect number of elements", 1, nodes.getLength());
  verifyAppsXML(nodes, app1);
  rm.stop();
}
 
Example 29
Project: xmlrss   File: PSRedactableXMLSignatureTest.java   View source code 6 votes vote down vote up
@Test
public void engineVerifyFail() throws Exception {
    RedactableXMLSignature sig = RedactableXMLSignature.getInstance(algorithm);

    DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
    documentBuilderFactory.setNamespaceAware(true);
    DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
    Document document = documentBuilder.parse(new File("testdata/vehicles.sig.xml"));

    NodeList nodeList = document.getElementsByTagNameNS(RedactableXMLSignature.XML_NAMESPACE, "Signature");
    assertEquals(1, nodeList.getLength());

    sig.initVerify(keyPair.getPublic());
    sig.setDocument(document);
    assertFalse(sig.verify());
    validateXSD(document);
}
 
Example 30
Project: jmt   File: Measure.java   View source code 6 votes vote down vote up
/**
 * Creates a DOM (Document Object Model) <code>Document<code>.
 */
private void createDOM() {
	try {
		DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
		DocumentBuilder builder = factory.newDocumentBuilder();

		//data is a Document
		Document data = builder.newDocument();
		Element root = data.createElement("measure");
		root.setAttribute("name", name);
		root.setAttribute("meanValue", "null");
		root.setAttribute("upperBound", "null");
		root.setAttribute("lowerBound", "null");
		root.setAttribute("progress", Double.toString(getSamplesAnalyzedPercentage()));
		root.setAttribute("data", "null");
		root.setAttribute("finished", "false");
		root.setAttribute("discarded", "0");
		root.setAttribute("precision", Double.toString(analyzer.getPrecision()));
		root.setAttribute("maxSamples", Double.toString(getMaxSamples()));
		data.appendChild(root);
	} catch (FactoryConfigurationError factoryConfigurationError) {
		factoryConfigurationError.printStackTrace();
	} catch (ParserConfigurationException e) {
		e.printStackTrace();
	}
}
 
Example 31
Project: hadoop   File: TestRMWebServices.java   View source code 6 votes vote down vote up
public void verifyClusterInfoXML(String xml) throws JSONException, Exception {
  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("clusterInfo");
  assertEquals("incorrect number of elements", 1, nodes.getLength());

  for (int i = 0; i < nodes.getLength(); i++) {
    Element element = (Element) nodes.item(i);

    verifyClusterGeneric(WebServicesTestUtils.getXmlLong(element, "id"),
        WebServicesTestUtils.getXmlLong(element, "startedOn"),
        WebServicesTestUtils.getXmlString(element, "state"),
        WebServicesTestUtils.getXmlString(element, "haState"),
        WebServicesTestUtils.getXmlString(element, "hadoopVersionBuiltOn"),
        WebServicesTestUtils.getXmlString(element, "hadoopBuildVersion"),
        WebServicesTestUtils.getXmlString(element, "hadoopVersion"),
        WebServicesTestUtils.getXmlString(element,
            "resourceManagerVersionBuiltOn"),
        WebServicesTestUtils.getXmlString(element,
            "resourceManagerBuildVersion"),
        WebServicesTestUtils.getXmlString(element, "resourceManagerVersion"));
  }
}
 
Example 32
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 33
Project: QiuQiu   File: XmlDataContext.java   View source code 6 votes vote down vote up
private List<RuleNode> loadXml(String path) throws Exception{
    DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
    DocumentBuilder builder = documentBuilderFactory.newDocumentBuilder();
    builder.setEntityResolver(new UrlDtdPathResolver());
    Document document = builder.parse(Thread.currentThread().getContextClassLoader().getResourceAsStream(path));

    List<RuleNode> results = new ArrayList<>();

    NodeList rootChildren = document.getDocumentElement().getChildNodes();
    for (int i = 0; i < rootChildren.getLength(); i++) {

        Optional.ofNullable(parseNode(rootChildren.item(i))).ifPresent(node -> results.add(node));

    }

    return results.stream().filter(Objects::nonNull).collect(Collectors.toList());
}
 
Example 34
Project: redirector   File: ModelTranslationService.java   View source code 6 votes vote down vote up
public Model translateFlavorRules(SelectServer source, NamespacedListRepository namespacedLists) {
    String flavorRulesXML = getFlavorRulesXML(source);

    Model model = null;
    try {
        if (StringUtils.isNotBlank(flavorRulesXML)) {
            DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
            Document newDocument = builder.parse(new ByteArrayInputStream(flavorRulesXML.getBytes(UTF8_CHARSET)));
            model = new Model(newDocument, namespacedLists);
            log.info("Creating model from xml: \n{}", flavorRulesXML);
        } else {
            log.error("Trying to init null model");
        }
    } catch (Exception ex) {
        log.error("Exception while creating model from xml: \n{} \n{}", flavorRulesXML, ex);
    }

    return model;
}
 
Example 35
Project: oscm   File: PaymentServiceProviderBean.java   View source code 6 votes vote down vote up
private Document createDeregistrationRequestDocument(RequestData data)
        throws ParserConfigurationException,
        PSPIdentifierForSellerException {

    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    DocumentBuilder db = dbf.newDocumentBuilder();
    Document doc = db.newDocument();

    Element headerElement = setHeaderXMLParameters(doc);
    setSecurityHeaderXMLParameters(doc, headerElement, data);

    Element transactionElement = setTransactionXMLAttributes(doc,
            headerElement, true, data);

    setIdentificationXMLParameters(doc, transactionElement, data
            .getPaymentInfoKey().longValue(), data.getExternalIdentifier());

    // set the payment code to indicate deregistration
    Element paymentElement = doc
            .createElement(HeidelpayXMLTags.XML_ELEMENT_PAYMENT);
    paymentElement.setAttribute(HeidelpayXMLTags.XML_ATTRIBUTE_CODE,
            getHeidelPayPaymentType(data.getPaymentTypeId()) + ".DR");
    transactionElement.appendChild(paymentElement);
    return doc;
}
 
Example 36
Project: openjdk-jdk10   File: Bug4971605.java   View source code 6 votes vote down vote up
@Test
public void test1() throws Exception {
    String xsd = "<?xml version='1.0'?>\n" + "<schema xmlns='http://www.w3.org/2001/XMLSchema'\n" + "        xmlns:test='jaxp13_test1'\n"
            + "        targetNamespace='jaxp13_test1'\n" + "        elementFormDefault='qualified'>\n" + "    <element name='test'/>\n" + "</schema>\n";

    DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
    docBuilderFactory.setNamespaceAware(true);
    DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();

    Node document = docBuilder.parse(new InputSource(new StringReader(xsd)));
    Assert.assertNotNull(document);

    SchemaFactory schemaFactory = SchemaFactory.newInstance("http://www.w3.org/2001/XMLSchema");
    Schema schema = schemaFactory.newSchema(new Source[] { new DOMSource(document) });
    Assert.assertNotNull(schema, "Failed: newSchema returned null.");
}
 
Example 37
Project: lams   File: BasicParserPool.java   View source code 6 votes vote down vote up
/** Constructor. */
public BasicParserPool() {
    maxPoolSize = 5;
    builderPool = new Stack<SoftReference<DocumentBuilder>>();
    builderAttributes = new LazyMap<String, Object>();
    coalescing = true;
    expandEntityReferences = true;
    builderFeatures = new LazyMap<String, Boolean>();
    ignoreComments = true;
    ignoreElementContentWhitespace = true;
    namespaceAware = true;
    schema = null;
    dtdValidating = false;
    xincludeAware = false;
    errorHandler = new LoggingErrorHandler(log);

    try {
        dirtyBuilderConfiguration = true;
        initializePool();
    } catch (XMLParserException e) {
        // default settings, no parsing exception
    }
}
 
Example 38
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 39
Project: MFM   File: PersistUtils.java   View source code 6 votes vote down vote up
public static void saveDATtoFile(Datafile datafile, String path)
            throws ParserConfigurationException, JAXBException, TransformerException, FileNotFoundException {

        JAXBContext jc = JAXBContext.newInstance(Datafile.class);

        // Create the Document
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        DocumentBuilder db = dbf.newDocumentBuilder();
        Document document = db.newDocument();
        DocumentType docType = getDocumentType(document);

        // Marshal the Object to a Document formatted so human readable
        Marshaller marshaller = jc.createMarshaller();
/*
        marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
        marshaller.setProperty(Marshaller.JAXB_SCHEMA_LOCATION, docType.getSystemId());
*/

        marshaller.marshal(datafile, document);
        document.setXmlStandalone(true);
        // NOTE could output with marshaller but cannot set DTD document type
/*
        OutputStream os = new FileOutputStream(path);
        marshaller.marshal(datafile, os);
*/

        // Output the Document
        TransformerFactory transformerFactory = TransformerFactory.newInstance();
        //    transformerFactory.setAttribute("indent-number", "4");
        Transformer transformer = transformerFactory.newTransformer();
        transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
        //   transformer.setOutputProperty(OutputKeys.STANDALONE, "yes");
        transformer.setOutputProperty(OutputKeys.INDENT, "yes");
        transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "8");
        transformer.setOutputProperty(OutputKeys.DOCTYPE_PUBLIC, docType.getPublicId());
        transformer.setOutputProperty(OutputKeys.DOCTYPE_SYSTEM, docType.getSystemId());
        DOMSource source = new DOMSource(document);
        StreamResult result = new StreamResult(new File(path));
        transformer.transform(source, result);
    }
 
Example 40
Project: emr-nlp-server   File: XMLUtil.java   View source code 6 votes vote down vote up
public static List<String> getModelFnFromXMLList(String fn_xmlList)
  		throws Exception {
  	List<String> modelNameList = new ArrayList<>();
  	
if (fn_xmlList != null && Util.fileExists(fn_xmlList)) {
	org.w3c.dom.Document dom = null;
	DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
	DocumentBuilder db = dbf.newDocumentBuilder();
	dom = db.parse(fn_xmlList);
	Element modellistRoot = dom.getDocumentElement();
	NodeList attributeNodes = modellistRoot
			.getElementsByTagName("Attr");

	for (int n = 0; n < attributeNodes.getLength(); n++) {
		Element attributeNode = (Element) attributeNodes.item(n);
		modelNameList.add(attributeNode.getAttribute("fileName").trim());
	}
}
      
  	return modelNameList;
  }