Java Code Examples for org.xml.sax.InputSource#setCharacterStream()

The following examples show how to use org.xml.sax.InputSource#setCharacterStream() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: TestAMWebServicesJobs.java    From big-c with Apache License 2.0 6 votes vote down vote up
@Test
public void testJobCountersXML() throws Exception {
  WebResource r = resource();
  Map<JobId, Job> jobsMap = appContext.getAllJobs();
  for (JobId id : jobsMap.keySet()) {
    String jobId = MRApps.toString(id);

    ClientResponse response = r.path("ws").path("v1").path("mapreduce")
        .path("jobs").path(jobId).path("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("jobCounters");
    verifyAMJobCountersXML(info, jobsMap.get(id));
  }
}
 
Example 2
Source File: SDKConnection.java    From BotLibre with Eclipse Public License 1.0 6 votes vote down vote up
public Element parse(String xml) {
	if (this.debug) {
		System.out.println(xml);
	}
	Document dom = null;
	DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
	try {
		DocumentBuilder builder = factory.newDocumentBuilder();
		InputSource source = new InputSource();
		source.setCharacterStream(new StringReader(xml));
		dom = builder.parse(source);
		return dom.getDocumentElement();
	} catch (Exception exception) {
		if (this.debug) {
			exception.printStackTrace();
		}
		this.exception = new SDKException(exception.getMessage(), exception);
		throw this.exception;
	}
}
 
Example 3
Source File: SAXSource.java    From Java8CN with Apache License 2.0 6 votes vote down vote up
/**
 * Attempt to obtain a SAX InputSource object from a Source
 * object.
 *
 * @param source Must be a non-null Source reference.
 *
 * @return An InputSource, or null if Source can not be converted.
 */
public static InputSource sourceToInputSource(Source source) {

    if (source instanceof SAXSource) {
        return ((SAXSource) source).getInputSource();
    } else if (source instanceof StreamSource) {
        StreamSource ss      = (StreamSource) source;
        InputSource  isource = new InputSource(ss.getSystemId());

        isource.setByteStream(ss.getInputStream());
        isource.setCharacterStream(ss.getReader());
        isource.setPublicId(ss.getPublicId());

        return isource;
    } else {
        return null;
    }
}
 
Example 4
Source File: SAXSource.java    From TencentKona-8 with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Attempt to obtain a SAX InputSource object from a Source
 * object.
 *
 * @param source Must be a non-null Source reference.
 *
 * @return An InputSource, or null if Source can not be converted.
 */
public static InputSource sourceToInputSource(Source source) {

    if (source instanceof SAXSource) {
        return ((SAXSource) source).getInputSource();
    } else if (source instanceof StreamSource) {
        StreamSource ss      = (StreamSource) source;
        InputSource  isource = new InputSource(ss.getSystemId());

        isource.setByteStream(ss.getInputStream());
        isource.setCharacterStream(ss.getReader());
        isource.setPublicId(ss.getPublicId());

        return isource;
    } else {
        return null;
    }
}
 
Example 5
Source File: TestNMWebServices.java    From hadoop with Apache License 2.0 6 votes vote down vote up
@Test
public void testSingleNodesXML() throws JSONException, Exception {
  WebResource r = resource();
  ClientResponse response = r.path("ws").path("v1").path("node")
      .path("info/").accept(MediaType.APPLICATION_XML)
      .get(ClientResponse.class);
  assertEquals(MediaType.APPLICATION_XML_TYPE, response.getType());
  String xml = response.getEntity(String.class);
  DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
  DocumentBuilder db = dbf.newDocumentBuilder();
  InputSource is = new InputSource();
  is.setCharacterStream(new StringReader(xml));
  Document dom = db.parse(is);
  NodeList nodes = dom.getElementsByTagName("nodeInfo");
  assertEquals("incorrect number of elements", 1, nodes.getLength());
  verifyNodesXML(nodes);
}
 
Example 6
Source File: TestRMWebServices.java    From hadoop with Apache License 2.0 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 7
Source File: TestRMWebServices.java    From hadoop with Apache License 2.0 5 votes vote down vote up
public void verifySchedulerFifoXML(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 nodesSched = dom.getElementsByTagName("scheduler");
  assertEquals("incorrect number of elements", 1, nodesSched.getLength());
  NodeList nodes = dom.getElementsByTagName("schedulerInfo");
  assertEquals("incorrect number of elements", 1, nodes.getLength());

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

    verifyClusterSchedulerFifoGeneric(
        WebServicesTestUtils.getXmlAttrString(element, "xsi:type"),
        WebServicesTestUtils.getXmlString(element, "qstate"),
        WebServicesTestUtils.getXmlFloat(element, "capacity"),
        WebServicesTestUtils.getXmlFloat(element, "usedCapacity"),
        WebServicesTestUtils.getXmlInt(element, "minQueueMemoryCapacity"),
        WebServicesTestUtils.getXmlInt(element, "maxQueueMemoryCapacity"),
        WebServicesTestUtils.getXmlInt(element, "numNodes"),
        WebServicesTestUtils.getXmlInt(element, "usedNodeCapacity"),
        WebServicesTestUtils.getXmlInt(element, "availNodeCapacity"),
        WebServicesTestUtils.getXmlInt(element, "totalNodeCapacity"),
        WebServicesTestUtils.getXmlInt(element, "numContainers"));
  }
}
 
Example 8
Source File: BPELInvokerPluginHandler.java    From container with Apache License 2.0 5 votes vote down vote up
/**
 * Loads a BPEL Assign fragment which queries the csarEntrypath from the input message into String variable.
 *
 * @param assignName          the name of the BPEL assign
 * @param csarEntryXpathQuery the csarEntryPoint XPath query
 * @param stringVarName       the variable to load the queries results into
 * @return a DOM Node representing a BPEL assign element
 * @throws IOException  is thrown when loading internal bpel fragments fails
 * @throws SAXException is thrown when parsing internal format into DOM fails
 */
public Node loadAssignXpathQueryToStringVarFragmentAsNode(final String assignName, final String xpath2Query,
                                                          final String stringVarName) throws IOException,
    SAXException {
    final String templateString =
        loadAssignXpathQueryToStringVarFragmentAsString(assignName, xpath2Query, stringVarName);
    final InputSource is = new InputSource();
    is.setCharacterStream(new StringReader(templateString));
    final Document doc = this.docBuilder.parse(is);
    return doc.getFirstChild();
}
 
Example 9
Source File: TestNMWebServicesContainers.java    From hadoop with Apache License 2.0 5 votes vote down vote up
@Test
public void testNodeSingleContainerXML() throws JSONException, Exception {
  WebResource r = resource();
  Application app = new MockApp(1);
  nmContext.getApplications().put(app.getAppId(), app);
  HashMap<String, String> hash = addAppContainers(app);
  Application app2 = new MockApp(2);
  nmContext.getApplications().put(app2.getAppId(), app2);
  addAppContainers(app2);

  for (String id : hash.keySet()) {
    ClientResponse response = r.path("ws").path("v1").path("node")
        .path("containers").path(id).accept(MediaType.APPLICATION_XML)
        .get(ClientResponse.class);
    assertEquals(MediaType.APPLICATION_XML_TYPE, response.getType());
    String xml = response.getEntity(String.class);
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    DocumentBuilder db = dbf.newDocumentBuilder();
    InputSource is = new InputSource();
    is.setCharacterStream(new StringReader(xml));
    Document dom = db.parse(is);
    NodeList nodes = dom.getElementsByTagName("container");
    assertEquals("incorrect number of elements", 1, nodes.getLength());
    verifyContainersInfoXML(nodes,
        nmContext.getContainers().get(ConverterUtils.toContainerId(id)));

  }
}
 
Example 10
Source File: ValidatorHandlerImpl.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Resolves the given resource and adapts the <code>LSInput</code>
 * returned into an <code>InputSource</code>.
 */
public InputSource resolveEntity(String name, String publicId,
        String baseURI, String systemId) throws SAXException, IOException {
    if (fEntityResolver != null) {
        LSInput lsInput = fEntityResolver.resolveResource(XML_TYPE, null, publicId, systemId, baseURI);
        if (lsInput != null) {
            final String pubId = lsInput.getPublicId();
            final String sysId = lsInput.getSystemId();
            final String baseSystemId = lsInput.getBaseURI();
            final Reader charStream = lsInput.getCharacterStream();
            final InputStream byteStream = lsInput.getByteStream();
            final String data = lsInput.getStringData();
            final String encoding = lsInput.getEncoding();

            /**
             * An LSParser looks at inputs specified in LSInput in
             * the following order: characterStream, byteStream,
             * stringData, systemId, publicId. For consistency
             * with the DOM Level 3 Load and Save Recommendation
             * use the same lookup order here.
             */
            InputSource inputSource = new InputSource();
            inputSource.setPublicId(pubId);
            inputSource.setSystemId((baseSystemId != null) ? resolveSystemId(systemId, baseSystemId) : systemId);

            if (charStream != null) {
                inputSource.setCharacterStream(charStream);
            }
            else if (byteStream != null) {
                inputSource.setByteStream(byteStream);
            }
            else if (data != null && data.length() != 0) {
                inputSource.setCharacterStream(new StringReader(data));
            }
            inputSource.setEncoding(encoding);
            return inputSource;
        }
    }
    return null;
}
 
Example 11
Source File: Fragments.java    From container with Apache License 2.0 5 votes vote down vote up
public Node generateBPEL4RESTLightServiceInstancePOSTAsNode(final String instanceDataAPIUrlVariableName,
                                                            final String csarId, final QName serviceTemplateId,
                                                            final String responseVariableName) throws IOException,
    SAXException {
    final String templateString =
        generateBPEL4RESTLightServiceInstancePOST(instanceDataAPIUrlVariableName, csarId, serviceTemplateId,
            responseVariableName);
    final InputSource is = new InputSource();
    is.setCharacterStream(new StringReader(templateString));
    final Document doc = this.docBuilder.parse(is);
    return doc.getFirstChild();
}
 
Example 12
Source File: TestEvalJavaScript.java    From java-client-api with Apache License 2.0 5 votes vote down vote up
@Test(expected = IllegalArgumentException.class)
 public void testJSDifferentVariableTypes() throws KeyManagementException, NoSuchAlgorithmException, Exception {
System.out.println("Running testJSDifferentVariableTypes"); 
   DocumentBuilder db = DocumentBuilderFactory.newInstance().newDocumentBuilder();
   InputSource is = new InputSource();
   is.setCharacterStream(new StringReader("<foo attr=\"attribute\"><?processing instruction?><!--comment-->test1</foo>"));
   Document doc = db.parse(is);
   System.out.println(this.convertXMLDocumentToString(doc));
   try {
     String query1 = " var results = [];"
         + "var myString;"
         + "var myBool ;"
         + "var myInteger;"
         + "var myDecimal;"
         + "var myJsonObject;"
         + "var myNull;"
         + "var myJsonArray;"
         + "var myJsonNull;"
         + "results.push(myString,myBool,myInteger,myDecimal,myJsonObject,myJsonArray,myNull,myJsonNull);"
         + "xdmp.arrayValues(results)";

     ServerEvaluationCall evl = client.newServerEval().javascript(query1);
     evl.addVariable("myString", "xml")
         .addVariable("myBool", true)
         .addVariable("myInteger", (int) 31)
         .addVariable("myDecimal", (double) 1.0471975511966)
         .addVariableAs("myJsonObject", new ObjectMapper().createObjectNode().put("foo", "v1").putNull("testNull"))
         .addVariableAs("myNull", (String) null)
         .addVariableAs("myJsonArray", new ObjectMapper().createArrayNode().add(1).add(2).add(3))
         .addVariableAs("myJsonNull", new ObjectMapper().createObjectNode().nullNode());
     System.out.println(new ObjectMapper().createObjectNode().nullNode().toString());
     EvalResultIterator evr = evl.eval();
     this.validateReturnTypes(evr);
     evr.close();
   } catch (Exception e) {
     throw e;
   }
 }
 
Example 13
Source File: AbstractUnmarshallerImpl.java    From openjdk-8 with GNU General Public License v2.0 5 votes vote down vote up
private static InputSource streamSourceToInputSource( StreamSource ss ) {
    InputSource is = new InputSource();
    is.setSystemId( ss.getSystemId() );
    is.setByteStream( ss.getInputStream() );
    is.setCharacterStream( ss.getReader() );

    return is;
}
 
Example 14
Source File: BPELConnectsToPluginHandler.java    From container with Apache License 2.0 5 votes vote down vote up
/**
 * Loads a BPEL Assign fragment which queries the csarEntrypath from the input message into String variable.
 *
 * @param assignName    the name of the BPEL assign
 * @param stringVarName the variable to load the queries results into
 * @return a DOM Node representing a BPEL assign element
 * @throws IOException  is thrown when loading internal bpel fragments fails
 * @throws SAXException is thrown when parsing internal format into DOM fails
 */
public Node loadAssignXpathQueryToStringVarFragmentAsNode(final String assignName, final String xpath2Query,
                                                          final String stringVarName) throws IOException,
    SAXException {
    final String templateString =
        loadAssignXpathQueryToStringVarFragmentAsString(assignName, xpath2Query, stringVarName);
    final InputSource is = new InputSource();
    is.setCharacterStream(new StringReader(templateString));
    final Document doc = this.docBuilder.parse(is);
    return doc.getFirstChild();
}
 
Example 15
Source File: TestEvalJavaScript.java    From java-client-api with Apache License 2.0 5 votes vote down vote up
@Test
 public void testJSDifferentVariableTypesWithNulls() throws KeyManagementException, NoSuchAlgorithmException, Exception {
System.out.println("Running testJSDifferentVariableTypesWithNulls");
   DocumentBuilder db = DocumentBuilderFactory.newInstance().newDocumentBuilder();
   InputSource is = new InputSource();
   is.setCharacterStream(new StringReader("<foo attr=\"attribute\"><?processing instruction?><!--comment-->test1</foo>"));
   Document doc = db.parse(is);
   System.out.println(this.convertXMLDocumentToString(doc));
   try {
     String query1 = " var results = [];"
         + "var myString;"
         + "var myBool ;"
         + "var myInteger;"
         + "var myDecimal;"
         + "var myJsonObject;"
         + "var myNull;"
         + "var myJsonArray;"
         + "var myJsonNull;"
         + "results.push(myString,myBool,myInteger,myDecimal,myJsonObject,myJsonArray,myNull,myJsonNull);"
         + "xdmp.arrayValues(results)";

     ServerEvaluationCall evl = client.newServerEval().javascript(query1);
     evl.addVariable("myString", "xml")
         .addVariable("myBool", true)
         .addVariable("myInteger", (int) 31)
         .addVariable("myDecimal", (double) 1.0471975511966)
         .addVariableAs("myJsonObject", new ObjectMapper().createObjectNode().put("foo", "v1").putNull("testNull"))
         .addVariableAs("myNull", (String) null)
         .addVariableAs("myJsonArray", new ObjectMapper().createArrayNode().add(1).add(2).add(3))
         .addVariableAs("myJsonNull", null);
     System.out.println(new ObjectMapper().createObjectNode().nullNode().toString());
     EvalResultIterator evr = evl.eval();
     this.validateReturnTypes(evr);
     evr.close();
   } catch (Exception e) {
     throw e;
   }
 }
 
Example 16
Source File: CoTInboundAdapterDefinition.java    From defense-solutions-proofs-of-concept with Apache License 2.0 5 votes vote down vote up
private void getAdditionalSchemasFromXSDFolder( FieldDefinition detailsDef )
{
	String directory = "src/main/resources/XSD-Add-on/";
	File dir = new File( directory );
	if( ! dir.exists() )
		return;
	if( ! dir.isDirectory() )
		return;

	System.out.println("Scanning directory " + dir.getAbsolutePath());
	// String directory="XSD Add-on/";
	try {
		// get a list of all xsd files in a directory.

		ArrayList<String> fileList = getXSDFiles(directory);


		for (String fileName : fileList)
		{
			String xsdContent = readXSD(directory + fileName);
			InputSource source = new InputSource();
			source.setCharacterStream(new StringReader(xsdContent));

			CoTDetailsDeff.parseXSD( source, detailsDef);
		}


	} catch (Exception e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	}
}
 
Example 17
Source File: Fragments.java    From container with Apache License 2.0 5 votes vote down vote up
public Node generateBPEL4RESTLightGETAsNode(final String serviceInstanceUrlVarName,
                                            final String responseVarName) throws IOException, SAXException {
    final String templateString = generateBPEL4RESTLightGET(serviceInstanceUrlVarName, responseVarName);
    final InputSource is = new InputSource();
    is.setCharacterStream(new StringReader(templateString));
    final Document doc = this.docBuilder.parse(is);
    return doc.getFirstChild();
}
 
Example 18
Source File: SOAPCommunicatorTest.java    From Java-OCA-OCPP with MIT License 5 votes vote down vote up
public static Document stringToDocument(String xml) throws Exception {
  DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
  factory.setNamespaceAware(true);
  DocumentBuilder db = factory.newDocumentBuilder();

  InputSource is = new InputSource();
  is.setCharacterStream(new StringReader(xml));
  return db.parse(is);
}
 
Example 19
Source File: AbstractUnmarshallerImpl.java    From openjdk-8-source with GNU General Public License v2.0 5 votes vote down vote up
private static InputSource streamSourceToInputSource( StreamSource ss ) {
    InputSource is = new InputSource();
    is.setSystemId( ss.getSystemId() );
    is.setByteStream( ss.getInputStream() );
    is.setCharacterStream( ss.getReader() );

    return is;
}
 
Example 20
Source File: CoTAdapterService.java    From defense-solutions-proofs-of-concept with Apache License 2.0 5 votes vote down vote up
private void getAdditionalSchemasFromXSDFolder( FieldDefinition detailsDef )
{
	String directory = "src/main/resources/XSD-Add-on/";
	File dir = new File( directory );
	if( ! dir.exists() )
		return;
	if( ! dir.isDirectory() )
		return;

	System.out.println("Scanning directory " + dir.getAbsolutePath());
	// String directory="XSD Add-on/";
	try {
		// get a list of all xsd files in a directory.

		ArrayList<String> fileList = getXSDFiles(directory);
		// attempt to load each of them in an array of strings. 1 xsd file =
		// 1 string

		// System.out.println(System.getProperty("user.dir"));
		// EDIT: select a folder dialog box?
		// include these xsd anyway?
		// String
		// sampleTagsFile=readXSD("src/main/resources/XSD Add-on/CoT_spatial.xsd");


		for (String fileName : fileList)
		{
			String xsdContent = readXSD(directory + fileName);
			InputSource source = new InputSource();
			source.setCharacterStream(new StringReader(xsdContent));

			CoTDetailsDeff.parseXSD( source, detailsDef);
		}


	} catch (Exception e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	}
}