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   Source Code and License 10 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   Source Code and License 10 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   Source Code and License 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   Source Code and License 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: 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 6
Project: openjdk-jdk10   File: Bug8073385.java   Source Code and License 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 7
Project: adobe-air-db-connector   File: XmlEncoder.java   Source Code and License 7 votes vote down vote up
public String encode(ResultSet rs) throws Exception {
	ResultSetMetaData rsmd;
	rsmd = rs.getMetaData();
	
	DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
	
	DocumentBuilder db = dbf.newDocumentBuilder();
	
	Document doc = db.newDocument();

	Element ele = doc.createElement("result");
	Integer count = 0;
	while(rs.next()){
		count++;
		Node rowNode = doc.createElement("row"); 
		for (int i=1; i<= rsmd.getColumnCount(); i++){
			 Node colNode = doc.createElement(rsmd.getColumnName(i)) ;
			 colNode.setTextContent(rs.getObject(colNode.getNodeName()).toString());
			 rowNode.appendChild(colNode);
		}
		ele.appendChild(rowNode);
	}
	ele.setAttribute("size", count.toString());
	doc.appendChild(ele);
	return toXmlString(doc);
}
 
Example 8
Project: verify-hub   File: SoapMessageManager.java   Source Code and License 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 9
Project: openjdk-jdk10   File: TCKEncodingTest.java   Source Code and License 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 10
Project: fb2parser   File: FictionBook.java   Source Code and License 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 11
Project: javaide   File: XmlUtils.java   Source Code and License 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 12
Project: personium-core   File: DavCmpFsImpl.java   Source Code and License 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 13
Project: openjdk-jdk10   File: AbstractMethodErrorTest.java   Source Code and License 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 14
Project: FEFEditor   File: GuiData.java   Source Code and License 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 15
Project: ibench   File: AbstractCheckExpectedOutputTester.java   Source Code and License 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 16
Project: hadoop   File: TestAMWebServicesTasks.java   Source Code and License 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 17
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 18
Project: litiengine   File: EditorScreen.java   Source Code and License 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 19
Project: L2jBrasil   File: ScriptDocument.java   Source Code and License 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 20
Project: pmTrans   File: EditingPane.java   Source Code and License 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 21
Project: VISNode   File: VersionFinder.java   Source Code and License 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 22
Project: lams   File: WebdavServlet.java   Source Code and License 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 23
Project: fluentxml4j   File: TransformationChain.java   Source Code and License 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 24
Project: oscm   File: TriggerServiceBean.java   Source Code and License 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 25
Project: hadoop   File: TestHsWebServicesJobs.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("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 26
Project: Equella   File: PropBagEx.java   Source Code and License 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 27
Project: hadoop   File: TestHsWebServicesJobs.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("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 28
Project: defense-solutions-proofs-of-concept   File: CoTUtilities.java   Source Code and License 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 29
Project: hadoop   File: TestRMWebServicesApps.java   Source Code and License 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 30
Project: xmlrss   File: PSRedactableXMLSignatureTest.java   Source Code and License 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 31
Project: jmt   File: Measure.java   Source Code and License 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 32
Project: hadoop   File: TestRMWebServices.java   Source Code and License 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 33
Project: QiuQiu   File: XmlDataContext.java   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   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 39
Project: MFM   File: PersistUtils.java   Source Code and License 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   Source Code and License 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;
  }
 
Example 41
Project: OperatieBRP   File: Xml.java   Source Code and License 6 votes vote down vote up
/**
 * Decodeer een object.
 * @param configuration configuratie
 * @param clazz te decoderen object
 * @param reader reader om XML van de lezen
 * @param <T> type van het object
 * @return het gedecodeerde object
 * @throws ConfigurationException bij configuratie problemen (annoties op de klassen)
 * @throws DecodeException bij decodeer problemen
 */
public static <T> T decode(final Configuration configuration, final Class<T> clazz, final Reader reader) throws XmlException {
    final Context context = new Context();
    final Configuration theConfiguration = configuration == null ? DEFAULT_CONFIGURATION : configuration;
    ConfigurationHelper.setConfiguration(context, theConfiguration);

    final Root<T> item = theConfiguration.getModelFor(clazz);

    // Jaxp first
    final Document document;
    try {
        final DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        factory.setNamespaceAware(true);
        final DocumentBuilder builder = factory.newDocumentBuilder();
        document = builder.parse(new InputSource(reader));
    } catch (ParserConfigurationException | SAXException | IOException e) {
        throw new DecodeException(context.getElementStack(), e);
    }

    return item.decode(context, document);
}
 
Example 42
Project: apache-tomcat-7.0.73-with-comment   File: DomUtil.java   Source Code and License 6 votes vote down vote up
/** Read XML as DOM.
 */
public static Document readXml(InputStream is)
    throws SAXException, IOException, ParserConfigurationException
{
    DocumentBuilderFactory dbf =
        DocumentBuilderFactory.newInstance();

    dbf.setValidating(false);
    dbf.setIgnoringComments(false);
    dbf.setIgnoringElementContentWhitespace(true);
    //dbf.setCoalescing(true);
    //dbf.setExpandEntityReferences(true);

    DocumentBuilder db = null;
    db = dbf.newDocumentBuilder();
    db.setEntityResolver( new NullResolver() );

    // db.setErrorHandler( new MyErrorHandler());

    Document doc = db.parse(is);
    return doc;
}
 
Example 43
Project: weixin_api   File: XMLParse.java   Source Code and License 6 votes vote down vote up
/**
 * 提取出xml数据包中的加密消息Encrypt标签下的内容
 * 
 * @param xmltext
 *            待提取的xml字符串
 * @return 提取出的加密消息字符串
 * @throws AesException
 */
public static Object[] extract(String xmltext) throws AesException {
	Object[] result = new Object[3];
	try {
		DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
		DocumentBuilder db = dbf.newDocumentBuilder();
		StringReader sr = new StringReader(xmltext);
		InputSource is = new InputSource(sr);
		Document document = db.parse(is);

		Element root = document.getDocumentElement();
		NodeList nodelist1 = root.getElementsByTagName("Encrypt");
		NodeList nodelist2 = root.getElementsByTagName("AppId");
		result[0] = 0;
		result[1] = nodelist1.item(0).getTextContent();
		
		if (nodelist2 != null && nodelist2.getLength()>0) {
			result[2] = nodelist2.item(0).getTextContent();
		}
		return result;
	} catch (Exception e) {
		e.printStackTrace();
		throw new AesException(AesException.ParseXmlError);
	}
}
 
Example 44
Project: kaltura-ce-sakai-extension   File: XmlUtils.java   Source Code and License 5 votes vote down vote up
public static Element parseXml(String xml) {
	//get the factory
	DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();

	try {

		//Using factory get an instance of document builder
		DocumentBuilder db = dbf.newDocumentBuilder();

		//parse using builder to get DOM representation of the XML file
		//Document dom = db.parse(new ByteArrayInputStream(xml.getBytes()));
		Reader reader= new CharArrayReader(xml.toCharArray());
		Document dom = db.parse(new org.xml.sax.InputSource(reader)); 

		Element docEle = dom.getDocumentElement();
		
		return docEle;
		
	} catch(ParserConfigurationException pce) {
		//pce.printStackTrace();
	} catch(SAXException se) {
		//se.printStackTrace();
	} catch(IOException ioe) {
		//ioe.printStackTrace();
	}
	
	return null;
}
 
Example 45
Project: hadoop   File: TestConfServlet.java   Source Code and License 5 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 46
Project: hadoop   File: TestAMWebServicesJobs.java   Source Code and License 5 votes vote down vote up
@Test
public void testJobIdInvalidXML() throws JSONException, Exception {
  WebResource r = resource();

  try {
    r.path("ws").path("v1").path("mapreduce").path("jobs").path("job_foo")
        .accept(MediaType.APPLICATION_XML).get(JSONObject.class);
    fail("should have thrown exception on invalid uri");
  } catch (UniformInterfaceException ue) {
    ClientResponse response = ue.getResponse();
    assertEquals(Status.NOT_FOUND, response.getClientResponseStatus());
    assertEquals(MediaType.APPLICATION_XML_TYPE, response.getType());
    String msg = response.getEntity(String.class);
    System.out.println(msg);
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    DocumentBuilder db = dbf.newDocumentBuilder();
    InputSource is = new InputSource();
    is.setCharacterStream(new StringReader(msg));
    Document dom = db.parse(is);
    NodeList nodes = dom.getElementsByTagName("RemoteException");
    Element element = (Element) nodes.item(0);
    String message = WebServicesTestUtils.getXmlString(element, "message");
    String type = WebServicesTestUtils.getXmlString(element, "exception");
    String classname = WebServicesTestUtils.getXmlString(element,
        "javaClassName");
    verifyJobIdInvalid(message, type, classname);
  }
}
 
Example 47
Project: incubator-ratis   File: RaftProperties.java   Source Code and License 5 votes vote down vote up
private Document parse(DocumentBuilder builder, InputStream is,
    String systemId) throws IOException, SAXException {
  LOG.debug("parsing input stream " + is);
  if (is == null) {
    return null;
  }
  try {
    return (systemId == null) ? builder.parse(is) : builder.parse(is,
        systemId);
  } finally {
    is.close();
  }
}
 
Example 48
Project: alvisnlp   File: LibraryModel.java   Source Code and License 5 votes vote down vote up
private Document getDocumentation(DocumentBuilder docBuilder) throws IOException {
	Document result = docBuilder.newDocument();
	Element root = XMLUtils.createRootElement(result, "alvisnlp-doc");
	root.setAttribute("target", fullName);
	root.setAttribute("short-target", getName());
	Element synopsis = XMLUtils.createElement(result, root, 0, "synopsis");
	XMLUtils.createElement(result, synopsis, 1, "p");
	Element lib = XMLUtils.createElement(result, root, 1, "library-doc");
	for (List<FunctionModel> fml : functions.values())
		for (FunctionModel f : fml)
			f.fillDocumentation(result, getName(), lib);
	return result;
}
 
Example 49
Project: springbootWeb   File: XmlCodeGenerationTest.java   Source Code and License 5 votes vote down vote up
@Test
public void testXmlParse() {
    ByteArrayInputStream is = new ByteArrayInputStream(
            generatedXmlFile.getFormattedContent().getBytes());
    try {
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        factory.setValidating(true);
        DocumentBuilder builder = factory.newDocumentBuilder();
        builder.setEntityResolver(new TestEntityResolver());
        builder.setErrorHandler(new TestErrorHandler());
        builder.parse(is);
    } catch (Exception e) {
        fail("Generated XML File " + generatedXmlFile.getFileName() + " will not parse");
    }
}
 
Example 50
Project: keycloak-protocol-cas   File: ServiceResponseTest.java   Source Code and License 5 votes vote down vote up
/**
 * Parse XML document and validate against CAS schema
 */
private Document parseAndValidate(String xml) throws Exception {
    Schema schema = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI)
            .newSchema(getClass().getResource("cas-response-schema.xsd"));

    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    factory.setSchema(schema);
    factory.setNamespaceAware(true);
    DocumentBuilder builder = factory.newDocumentBuilder();
    builder.setErrorHandler(new FatalAdapter(new DefaultHandler()));
    return builder.parse(new ByteArrayInputStream(xml.getBytes(StandardCharsets.UTF_8)));
}
 
Example 51
Project: geomapapp   File: XML_Layer.java   Source Code and License 5 votes vote down vote up
public static XML_Layer parse(InputStream in)
		throws ParserConfigurationException, SAXException, IOException {
	DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
	dbf.setIgnoringComments(true);
	DocumentBuilder db = dbf.newDocumentBuilder();
	Document dom = db.parse(in);

	Node root = getElement(dom, "Layers");
	XML_Layer layer = parseFolder(root);
	layer.name = "Basemaps";
	return layer;
}
 
Example 52
Project: QN-ACTR-Release   File: GuiXMLWriter.java   Source Code and License 5 votes vote down vote up
/**
 * Returns the entire Document rapresenting GUI data structure.
 * @param model data structure
 * @return complete GUI data structure in Document format
 */
public static Document getDocument(CommonModel model) {
	DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
	DocumentBuilder docBuilder = null;
	try {
		docBuilder = dbf.newDocumentBuilder();
	} catch (ParserConfigurationException e) {
		e.printStackTrace();
		return null;
	}
	Document modelDoc = docBuilder.newDocument();
	// Writes all elements on Document
	writeGuiInfos(modelDoc, model);
	return modelDoc;
}
 
Example 53
Project: TuLiPA-frames   File: RCGDOMbuilder.java   Source Code and License 5 votes vote down vote up
public static Document exportGrammar(RCG g, Map<String, TagTree> dict){
	dictionary = dict;
	try {
		DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
		DocumentBuilder constructor    = factory.newDocumentBuilder();
		Document rcggrammar            = constructor.newDocument();
		rcggrammar.setXmlVersion("1.0");
		rcggrammar.setXmlStandalone(true);
		
		Element root = rcggrammar.createElement("rcg");
		String label = "";
		PredLabel p  = g.getStartPredicateLabel();
		if (p instanceof PredStringLabel) {
			label = p.toString();
		} else if (p instanceof PredComplexLabel) {
			label = ((PredComplexLabel) p).getComplexLabel();
		}
		root.setAttribute("start", label);

		List<Clause> clauses = g.getClauses();
		for(int i = 0 ; i < clauses.size() ; i++) {
			RCGDOMbuilder.exportClause(root, clauses.get(i), null, rcggrammar);
		}

		// finally we do not forget the root
		rcggrammar.appendChild(root);
		return rcggrammar;

	} catch (ParserConfigurationException e) {
		System.err.println(e);
		//System.err.println(e.getStackTrace());
		return null;
	}
}
 
Example 54
Project: ISO8583   File: Iso8583Config.java   Source Code and License 5 votes vote down vote up
public void parseXmlToConfig(PnlMain pnlMain) {
	try {
		if (!xmlText.getText().trim().equals("")) {
			configTreeNode.removeAllChildren();
			
			DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
			DocumentBuilder builder = factory.newDocumentBuilder();
		    InputSource is = new InputSource(new StringReader(xmlText.getText()));
			
			Document document = builder.parse(is);
			
			DefaultMutableTreeNode lastParseNode;
			
			setDelimiterEnum(DelimiterEnum.getDelimiter(document.getDocumentElement().getAttribute("delimiter")));
			
			NodeList nodeList = document.getDocumentElement().getChildNodes();
			Node node;
			
			for (int i = 0; i < nodeList.getLength(); i++) {
				node = nodeList.item(i);
				
				if ("message".equalsIgnoreCase(node.getNodeName())) {
					lastParseNode = addType();
					
					((MessageVO) lastParseNode.getUserObject()).setType(ISOUtils.getAttr(node, "type", "0000"));;
					((MessageVO) lastParseNode.getUserObject()).setHeaderEncoding(EncodingEnum.getEncoding(ISOUtils.getAttr(node, "header-encoding", "")));
					((MessageVO) lastParseNode.getUserObject()).setBitmatEncoding(EncodingEnum.getEncoding(ISOUtils.getAttr(node, "bitmap-encoding", "")));
					
					addFieldsToTree(pnlMain, node, lastParseNode);
				}
			}
		}
	}
	catch (Exception x) {
		x.printStackTrace();
		JOptionPane.showMessageDialog(pnlMain, "Invalid XML! See the log file.\n\n" + x.getMessage());
	}
}
 
Example 55
Project: beaker-notebook-archive   File: SVGContainer.java   Source Code and License 5 votes vote down vote up
public static MIMEContainer SVG(Object data) throws Exception {
  String code = "";
  DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
  DocumentBuilder builder = factory.newDocumentBuilder();
  Document doc = validateData(data, builder);
  TransformerFactory tf = TransformerFactory.newInstance();
  Transformer transformer = tf.newTransformer();
  transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
  StringWriter writer = new StringWriter();
  transformer.transform(new DOMSource(doc), new StreamResult(writer));
  code = writer.getBuffer().toString().replaceAll("\n|\r", "");
  return addMimeType(MIME.IMAGE_SVG, code);
}
 
Example 56
Project: Proyecto-DASI   File: ReadXMLTestSequence.java   Source Code and License 5 votes vote down vote up
public Document getDocument(String testFilePath){
	Document doc=null;		
       try {
		  DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
		  DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
		  doc = dBuilder.parse(new File(testFilePath));
		  doc.getDocumentElement().normalize();
		  return doc;
       } catch (Exception e) {
            e.printStackTrace();
       }
       return doc; //this return will be not executed
}
 
Example 57
Project: lams   File: PersistenceUnitReader.java   Source Code and License 5 votes vote down vote up
/**
 * Validate the given stream and return a valid DOM document for parsing.
 */
protected Document buildDocument(ErrorHandler handler, InputStream stream)
		throws ParserConfigurationException, SAXException, IOException {

	DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
	dbf.setNamespaceAware(true);
	DocumentBuilder parser = dbf.newDocumentBuilder();
	parser.setErrorHandler(handler);
	return parser.parse(stream);
}
 
Example 58
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 59
Project: incubator-netbeans   File: BaseTest.java   Source Code and License 5 votes vote down vote up
void readDocument(String name)
{
	/*
	 *	The other way to create the object graph:
	 *
	 *	DDFactory.register("book", "book.Book");
	 *	book = DDFactory.create(in, "book");
	 *
	 */
       if (documentDir != null)
           name = documentDir + name;
	try
	{
		FileInputStream in = new FileInputStream(name);
		
		out("creating the DOM document");
		DocumentBuilderFactory dbf = 
				DocumentBuilderFactory.newInstance();
		DocumentBuilder db = dbf.newDocumentBuilder();
		this.doc = db.parse(in);
		in.close();
	}
	catch (Throwable t)
	{
           t.printStackTrace();
		throw new RuntimeException("DD creation failed: " +
								   t.getMessage());
	}

	if (doc == null)
	{
		err("doc is null");
		return;
	}
}
 
Example 60
Project: Compiler   File: GParser.java   Source Code and License 5 votes vote down vote up
private void readXMLFile(String iXMLFile) {
    try {
        File fXMLFile = new File(iXMLFile);
        DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
        Document document = documentBuilder.parse(fXMLFile);

        //  http://stackoverflow.com/questions/13786607/normalization-in-dom-parsing-with-java-how-does-it-work
        document.getDocumentElement().normalize();

        System.out.println("Root element: " + document.getDocumentElement().getNodeName());

        NodeList nodeList = document.getElementsByTagName("token");

        for (int i = 0; i < nodeList.getLength(); i++) {
            Node node = nodeList.item(i);

            if (node.getNodeType() == Node.ELEMENT_NODE) {
                Element element = (Element) node;
                int tokenNumber = Integer.parseInt(element.getElementsByTagName("number").item(0).getTextContent());
                System.out.println("Word #"+tokenNumber);
                String isValidStr = element.getElementsByTagName("valid").item(0).getTextContent();
                boolean isValid = Boolean.parseBoolean(isValidStr);
                String typeStr = element.getElementsByTagName("type").item(0).getTextContent();
                int type = parseTypeStringToInt(typeStr);
                String value = element.getElementsByTagName("value").item(0).getTextContent();
                if (isValid) {
                    GWordInfo wordInfo = new GWordInfo(type, value);
                    addWordToLab(wordInfo);
                }
            }
        }


    } catch (Exception error) {
        error.printStackTrace();
    }

}