org.xml.sax.InputSource Java Examples

The following examples show how to use org.xml.sax.InputSource. 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: DTDParser.java    From hottub with GNU General Public License v2.0 6 votes vote down vote up
private boolean pushReader(ExternalEntity next)
        throws IOException, SAXException {

    InputEntity r = InputEntity.getInputEntity(dtdHandler, locale);
    InputSource s;
    try {
        s = next.getInputSource(resolver);
    } catch (IOException e) {
        String msg =
                "unable to open the external entity from :" + next.systemId;
        if (next.publicId != null)
            msg += " (public id:" + next.publicId + ")";

        SAXParseException spe = new SAXParseException(msg,
                getPublicId(), getSystemId(), getLineNumber(), getColumnNumber(), e);
        dtdHandler.fatalError(spe);
        throw e;
    }

    r.init(s, next.name, in, next.isPE);
    in = r;
    return true;
}
 
Example #2
Source File: BadExceptionMessageTest.java    From jdk8u-jdk with GNU General Public License v2.0 6 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 #3
Source File: JpaJaxbUtil.java    From tomee with Apache License 2.0 6 votes vote down vote up
public static <T> Object unmarshal(final Class<T> type, final InputStream in) throws ParserConfigurationException, SAXException, JAXBException {
    final InputSource inputSource = new InputSource(in);

    final SAXParserFactory factory = SAXParserFactory.newInstance();
    factory.setNamespaceAware(true);
    factory.setValidating(false);

    final JAXBContext ctx = JAXBContextFactory.newInstance(type);
    final Unmarshaller unmarshaller = ctx.createUnmarshaller();
    unmarshaller.setEventHandler(new ValidationEventHandler() {
        public boolean handleEvent(final ValidationEvent validationEvent) {
            System.out.println(validationEvent);
            return false;
        }
    });

    return unmarshaller.unmarshal(inputSource);
}
 
Example #4
Source File: DOMHelperTest.java    From xades4j with GNU Lesser General Public License v3.0 6 votes vote down vote up
@Test
public void testGetChildElementsByTagNameNS() throws Exception
{
    String xml = "<root><a xmlns='urn:test'/><b/><n:a xmlns:n='urn:test'/><c/></root>";
    
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    dbf.setNamespaceAware(true);
    DocumentBuilder db = dbf.newDocumentBuilder();
    Document doc = db.parse(new InputSource(new StringReader(xml)));
    
    Collection<Element> elements = DOMHelper.getChildElementsByTagNameNS(doc.getDocumentElement(), "urn:test", "a");
    
    Assert.assertNotNull(elements);
    Assert.assertEquals(2, elements.size());
    for (Element element : elements)
    {
        Assert.assertEquals("a", element.getLocalName());
    }
}
 
Example #5
Source File: ApsEntityManager.java    From entando-core with GNU Lesser General Public License v3.0 6 votes vote down vote up
/**
 * Create and populate the entity as specified by its type and XML
 * definition.
 *
 * @param entityTypeCode The Entity Type code.
 * @param xml The XML of the associated entity.
 * @return The populated entity.
 * @throws ApsSystemException If errors detected while retrieving the
 * entity.
 */
protected IApsEntity createEntityFromXml(String entityTypeCode, String xml) throws ApsSystemException {
    try {
        IApsEntity entityPrototype = this.getEntityPrototype(entityTypeCode);
        SAXParserFactory parseFactory = SAXParserFactory.newInstance();
        SAXParser parser = parseFactory.newSAXParser();
        InputSource is = new InputSource(new StringReader(xml));
        EntityHandler handler = this.getEntityHandler();
        handler.initHandler(entityPrototype, this.getXmlAttributeRootElementName(), this.getCategoryManager());
        parser.parse(is, handler);
        return entityPrototype;
    } catch (ParserConfigurationException | SAXException | IOException t) {
        logger.error("Error detected while creating the entity. typecode: {} - xml: {}", entityTypeCode, xml, t);
        throw new ApsSystemException("Error detected while creating the entity", t);
    }
}
 
Example #6
Source File: Framework.java    From dragonwell8_jdk with GNU General Public License v2.0 6 votes vote down vote up
public Framework(final String name, final File bsFile) {
    super(name, null);
    try {
        final File pathf = bsFile.getCanonicalFile().getParentFile().getParentFile().getParentFile();
        path = pathf.getParentFile().getParentFile().getCanonicalPath();
    } catch (IOException x) {
        throw new RuntimeException(x);
    }
    binaries = findBinaries(path, name);

    pkg = ClassGenerator.JOBJC_PACKAGE + "." + name.toLowerCase();
    try {
        rootNode = (Node)XPATH.evaluate("signatures", new InputSource(bsFile.getAbsolutePath()), XPathConstants.NODE);
    } catch (final XPathExpressionException e) { throw new RuntimeException(e); }
    protocols = new ArrayList<Protocol>();
    categories = new ArrayList<Category>();
}
 
Example #7
Source File: InterceptingResolver.java    From cougar with Apache License 2.0 6 votes vote down vote up
@Override
   public InputSource resolveEntity (
   			    String name,
   			    String publicId,
   			    String baseURI,
   			    String systemId)
throws SAXException, IOException {

	try {
		if (shouldLoadAsResource(systemId)) {
			log.debug("Loading entity '" + systemId + "' as resource");
			return resourceToInputSource(publicId, systemId);
		}
		else {
			return super.resolveEntity(publicId, systemId);
		}
	}
	catch (Exception e) {
		// not in spec but too bad
		throw new PluginException("Error resolving entity: " + systemId + ": " + e, e);
	}
}
 
Example #8
Source File: XmlUtils.java    From jeecg-boot-with-activiti with MIT License 6 votes vote down vote up
public static Map<String, Object> extractCustomAttributes(final String xml) {
    final SAXParserFactory spf = SAXParserFactory.newInstance();
    spf.setNamespaceAware(true);
    spf.setValidating(false);
    try {
        final SAXParser saxParser = spf.newSAXParser();
        final XMLReader xmlReader = saxParser.getXMLReader();
        final CustomAttributeHandler handler = new CustomAttributeHandler();
        xmlReader.setContentHandler(handler);
        xmlReader.parse(new InputSource(new StringReader(xml)));
        return handler.getAttributes();
    } catch (final Exception e) {
    	log.error(e.getMessage(), e);
        return Collections.emptyMap();
    }
}
 
Example #9
Source File: DocumentCache.java    From jdk1.8-source-analysis with Apache License 2.0 6 votes vote down vote up
/**
 * Loads the document and updates build-time (latency) statistics
 */
public void loadDocument(String uri) {

    try {
        final long stamp = System.currentTimeMillis();
        _dom = (DOMEnhancedForDTM)_dtmManager.getDTM(
                         new SAXSource(_reader, new InputSource(uri)),
                         false, null, true, false);
        _dom.setDocumentURI(uri);

        // The build time can be used for statistics for a better
        // priority algorithm (currently round robin).
        final long thisTime = System.currentTimeMillis() - stamp;
        if (_buildTime > 0)
            _buildTime = (_buildTime + thisTime) >>> 1;
        else
            _buildTime = thisTime;
    }
    catch (Exception e) {
        _dom = null;
    }
}
 
Example #10
Source File: BadExceptionMessageTest.java    From TencentKona-8 with GNU General Public License v2.0 6 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 #11
Source File: AbstractStaxHandlerTestCase.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Test
public void noNamespacePrefixes() throws Exception {
	Assume.assumeTrue(wwwSpringframeworkOrgIsAccessible());

	StringWriter stringWriter = new StringWriter();
	AbstractStaxHandler handler = createStaxHandler(new StreamResult(stringWriter));
	xmlReader.setContentHandler(handler);
	xmlReader.setProperty("http://xml.org/sax/properties/lexical-handler", handler);

	xmlReader.setFeature("http://xml.org/sax/features/namespaces", true);
	xmlReader.setFeature("http://xml.org/sax/features/namespace-prefixes", false);

	xmlReader.parse(new InputSource(new StringReader(COMPLEX_XML)));

	assertThat(stringWriter.toString(), isSimilarTo(COMPLEX_XML).withNodeFilter(nodeFilter));
}
 
Example #12
Source File: PomTools.java    From depan with Apache License 2.0 6 votes vote down vote up
public static InputSource loadEffectivePom(
    File moduleFile, MavenContext context)
    throws IOException, InterruptedException {
  MavenExecutor exec = context.build(moduleFile);
  exec.evalEffectivePom(context);

  if (0 != exec.getExitCode()) {
    MavenLogger.LOG.warn(
        "Err {}  getting effective POM for {}\n\nMaven Console output >\n{}",
        exec.getExitCode(), moduleFile.getPath(), exec.getOut());
  }

  String effPom = exec.getEffPom();
  if (Strings.isNullOrEmpty(effPom)) {
    MavenLogger.LOG.warn(
        "Empty effective POM for {}\n\nMaven Console output >\n",
        moduleFile.getPath(), exec.getOut());
  }

  StringReader reader = new StringReader(effPom);
  return new InputSource(reader);
}
 
Example #13
Source File: XPathCondition.java    From development with Apache License 2.0 6 votes vote down vote up
public boolean eval() throws BuildException {
    if (nullOrEmpty(fileName)) {
        throw new BuildException("No file set");
    }
    File file = new File(fileName);
    if (!file.exists() || file.isDirectory()) {
        throw new BuildException(
                "The specified file does not exist or is a directory");
    }
    if (nullOrEmpty(path)) {
        throw new BuildException("No XPath expression set");
    }
    XPath xpath = XPathFactory.newInstance().newXPath();
    InputSource inputSource = new InputSource(fileName);
    Boolean result = Boolean.FALSE;
    try {
        result = (Boolean) xpath.evaluate(path, inputSource,
                XPathConstants.BOOLEAN);
    } catch (XPathExpressionException e) {
        throw new BuildException("XPath expression fails", e);
    }
    return result.booleanValue();
}
 
Example #14
Source File: test_Validator.java    From xmlunit with Apache License 2.0 6 votes vote down vote up
public void testXSchema() throws Exception{
    File xsdFile = new File(test_Constants.TEST_RESOURCE_DIR + "Book.xsd");
    assertTrue("xsdFile " + xsdFile.getAbsolutePath() + " exists",
               xsdFile.exists());
            
    InputStream xmlFile = test_Validator.class.getResourceAsStream("/BookXsdGenerated.xml");
    assertNotNull("xmlFile exists", xmlFile);
    try {
        validator = new Validator(new InputSource(xmlFile));

        validator.useXMLSchema(true);
        assertTrue("Schema " + validator.toString(), validator.isValid());
    } finally {
        xmlFile.close();
    }
}
 
Example #15
Source File: XMLSchemaLoader.java    From jdk8u60 with GNU General Public License v2.0 6 votes vote down vote up
private static XMLInputSource saxToXMLInputSource(InputSource sis) {
    String publicId = sis.getPublicId();
    String systemId = sis.getSystemId();

    Reader charStream = sis.getCharacterStream();
    if (charStream != null) {
        return new XMLInputSource(publicId, systemId, null, charStream,
                null);
    }

    InputStream byteStream = sis.getByteStream();
    if (byteStream != null) {
        return new XMLInputSource(publicId, systemId, null, byteStream,
                sis.getEncoding());
    }

    return new XMLInputSource(publicId, systemId, null);
}
 
Example #16
Source File: StandardSREInstallTest.java    From sarl with Apache License 2.0 6 votes vote down vote up
@Test
public void setFromXML() throws Exception {
	String[] expected = new String[] { "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"no\"?>",
			"<SRE name=\"Hello\" mainClass=\"io.sarl.Boot\" libraryPath=\"" + this.path.toPortableString()
					+ "\" standalone=\"true\">",
			"<libraryLocation packageRootPath=\"\" sourcePath=\"\" systemLibraryPath=\"" + this.path.toPortableString()
					+ "\"/>",
			"<libraryLocation packageRootPath=\"\" sourcePath=\"\" systemLibraryPath=\"x.jar\"/>",
			"<libraryLocation packageRootPath=\"\" sourcePath=\"\" systemLibraryPath=\"y.jar\"/>",
			"<libraryLocation packageRootPath=\"\" sourcePath=\"\" systemLibraryPath=\"z.jar\"/>", "</SRE>", };
	StringBuilder b = new StringBuilder();
	for (String s : expected) {
		b.append(s);
		// b.append("\n");
	}
	try (ByteArrayInputStream bais = new ByteArrayInputStream(b.toString().getBytes())) {
		DocumentBuilder parser = DocumentBuilderFactory.newInstance().newDocumentBuilder();
		parser.setErrorHandler(new DefaultHandler());
		Element root = parser.parse(new InputSource(bais)).getDocumentElement();
		this.sre.setFromXML(root);
		assertTrue(this.sre.isStandalone());
		assertEquals(this.path, this.sre.getJarFile());
		assertEquals("Hello", this.sre.getName());
		assertEquals("io.sarl.Boot", this.sre.getMainClass());
	}
}
 
Example #17
Source File: TestHsWebServicesTasks.java    From big-c with Apache License 2.0 6 votes vote down vote up
@Test
public void testTasksXML() throws JSONException, Exception {

  WebResource r = resource();
  Map<JobId, Job> jobsMap = appContext.getAllJobs();
  for (JobId id : jobsMap.keySet()) {
    String jobId = MRApps.toString(id);
    ClientResponse response = r.path("ws").path("v1").path("history")
        .path("mapreduce").path("jobs").path(jobId).path("tasks")
        .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 tasks = dom.getElementsByTagName("tasks");
    assertEquals("incorrect number of elements", 1, tasks.getLength());
    NodeList task = dom.getElementsByTagName("task");
    verifyHsTaskXML(task, jobsMap.get(id));
  }
}
 
Example #18
Source File: CastorMarshaller.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Override
protected Object unmarshalSaxReader(XMLReader xmlReader, InputSource inputSource)
		throws XmlMappingException, IOException {

	UnmarshalHandler unmarshalHandler = createUnmarshaller().createHandler();
	try {
		ContentHandler contentHandler = Unmarshaller.getContentHandler(unmarshalHandler);
		xmlReader.setContentHandler(contentHandler);
		xmlReader.parse(inputSource);
		return unmarshalHandler.getObject();
	}
	catch (SAXException ex) {
		throw new UnmarshallingFailureException("SAX reader exception", ex);
	}
}
 
Example #19
Source File: XmlUtil.java    From WechatTestTool with Apache License 2.0 5 votes vote down vote up
/**
 * 判断给定字符串是否符合XML格式
 */
public static boolean isValidXml(String xml) {
	try {
		StringReader reader = new StringReader(xml);
		DocumentBuilder db = DocumentBuilderFactory.newInstance()
				.newDocumentBuilder();
		db.parse(new InputSource(reader));
	} catch (Exception e) {
		return false;
	}
	return true;
}
 
Example #20
Source File: ModelLoader.java    From openjdk-jdk8u with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Parses a RELAX NG grammar into an annotated grammar.
 */
private Model loadRELAXNG() throws SAXException {

    // build DOM forest
    final DOMForest forest = buildDOMForest( new RELAXNGInternalizationLogic() );

    // use JAXP masquerading to validate the input document.
    // DOMForest -> ExtensionBindingChecker -> RNGOM

    XMLReaderCreator xrc = new XMLReaderCreator() {
        public XMLReader createXMLReader() {

            // foreset parser cannot change the receivers while it's working,
            // so we need to have one XMLFilter that works as a buffer
            XMLFilter buffer = new XMLFilterImpl() {
                @Override
                public void parse(InputSource source) throws IOException, SAXException {
                    forest.createParser().parse( source, this, this, this );
                }
            };

            XMLFilter f = new ExtensionBindingChecker(Const.RELAXNG_URI,opt,errorReceiver);
            f.setParent(buffer);

            f.setEntityResolver(opt.entityResolver);

            return f;
        }
    };

    Parseable p = new SAXParseable( opt.getGrammars()[0], errorReceiver, xrc );

    return loadRELAXNG(p);

}
 
Example #21
Source File: UPnPGatewayDevice.java    From open-ig with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * Retrieves the properties and description of the GatewayDevice.
 * <p/>
 * Connects to the device's {@link #location} and parses the response
 * using a {@link UPnPGatewayDeviceHandler} to populate the fields of this
 * class
 *
 * @throws SAXException if an error occurs while parsing the request
 * @throws IOException  on communication errors
 * @see hu.openig.net.UPnPGatewayDeviceHandler
 */
public void loadDescription() throws SAXException, IOException {

    URLConnection urlConn = new URL(getLocation()).openConnection();
    urlConn.setReadTimeout(HTTP_RECEIVE_TIMEOUT);

    XMLReader parser = XMLReaderFactory.createXMLReader();
    parser.setContentHandler(new UPnPGatewayDeviceHandler(this));
    parser.parse(new InputSource(urlConn.getInputStream()));


    /* fix urls */
    String ipConDescURL;
    if (urlBase != null && urlBase.trim().length() > 0) {
        ipConDescURL = urlBase;
    } else {
        ipConDescURL = location;
    }

    int lastSlashIndex = ipConDescURL.indexOf('/', 7);
    if (lastSlashIndex > 0) {
        ipConDescURL = ipConDescURL.substring(0, lastSlashIndex);
    }


    sCPDURL = copyOrCatUrl(ipConDescURL, sCPDURL);
    controlURL = copyOrCatUrl(ipConDescURL, controlURL);
    controlURLCIF = copyOrCatUrl(ipConDescURL, controlURLCIF);
    presentationURL = copyOrCatUrl(ipConDescURL, presentationURL);
}
 
Example #22
Source File: TestUtil.java    From netbeans with Apache License 2.0 5 votes vote down vote up
/**
 * Get a particular element in a test XML document.
 * Pass in a well-formed XML document and an element name to search for.
 * Must be exactly one such.
 */
public static Element createElementInDocument(String xml, String elementName, String elementNamespace) throws Exception {
    Document doc = XMLUtil.parse(new InputSource(new StringReader(xml)), false, true, null, null);
    NodeList nl = doc.getElementsByTagNameNS(elementNamespace, elementName);
    if (nl.getLength() != 1) {
        throw new IllegalArgumentException("Zero or more than one <" + elementName + ">s in \"" + xml + "\"");
    }
    return (Element)nl.item(0);
}
 
Example #23
Source File: UnmarshallerImpl.java    From jdk8u60 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 #24
Source File: WsimportOptions.java    From TencentKona-8 with GNU General Public License v2.0 5 votes vote down vote up
private InputSource absolutize(InputSource is) {
    // absolutize all the system IDs in the input,
    // so that we can map system IDs to DOM trees.
    try {
        URL baseURL = new File(".").getCanonicalFile().toURL();
        is.setSystemId(new URL(baseURL, is.getSystemId()).toExternalForm());
    } catch (IOException e) {
        // ignore
    }
    return is;
}
 
Example #25
Source File: SourceHttpMessageConverterTests.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Test
public void readSAXSource() throws Exception {
	MockHttpInputMessage inputMessage = new MockHttpInputMessage(BODY.getBytes("UTF-8"));
	inputMessage.getHeaders().setContentType(new MediaType("application", "xml"));
	SAXSource result = (SAXSource) converter.read(SAXSource.class, inputMessage);
	InputSource inputSource = result.getInputSource();
	String s = FileCopyUtils.copyToString(new InputStreamReader(inputSource.getByteStream()));
	assertThat("Invalid result", s, isSimilarTo(BODY));
}
 
Example #26
Source File: LogParser.java    From TencentKona-8 with GNU General Public License v2.0 5 votes vote down vote up
public static ArrayList<LogEvent> parse(Reader reader, boolean cleanup) throws Exception {
    // Create the XML input factory
    SAXParserFactory factory = SAXParserFactory.newInstance();

    // Create the XML LogEvent reader
    SAXParser p = factory.newSAXParser();

    if (cleanup) {
        // some versions of the log have slightly malformed XML, so clean it
        // up before passing it to SAX
        reader = new LogCleanupReader(reader);
    }

    LogParser log = new LogParser();
    try {
        p.parse(new InputSource(reader), log);
    } catch (Throwable th) {
        th.printStackTrace();
        // Carry on with what we've got...
    }

    // Associate compilations with their NMethods
    for (NMethod nm : log.nmethods.values()) {
        Compilation c = log.compiles.get(nm.getId());
        nm.setCompilation(c);
        // Native wrappers for methods don't have a compilation
        if (c != null) {
            c.setNMethod(nm);
        }
    }

    // Initially we want the LogEvent log sorted by timestamp
    Collections.sort(log.events, sortByStart);

    return log.events;
}
 
Example #27
Source File: ExternalEntity.java    From openjdk-8-source with GNU General Public License v2.0 5 votes vote down vote up
public InputSource getInputSource(EntityResolver r)
        throws IOException, SAXException {

    InputSource retval;

    retval = r.resolveEntity(publicId, systemId);
    // SAX sez if null is returned, use the URI directly
    if (retval == null)
        retval = Resolver.createInputSource(new URL(systemId), false);
    return retval;
}
 
Example #28
Source File: SocketCommandParser.java    From OpenAs2App with BSD 2-Clause "Simplified" License 5 votes vote down vote up
public void parse(String inLine) throws SAXException, IOException {
    userid = "";
    password = "";
    commandText = "";
    contents.reset();

    StringReader sr = new StringReader(inLine);
    parser.parse(new InputSource(sr), this);
}
 
Example #29
Source File: RemotePlatformProvider.java    From netbeans with Apache License 2.0 5 votes vote down vote up
@Override
@NonNull
public synchronized RemotePlatform instanceCreate() throws IOException, ClassNotFoundException {
    RemotePlatform remotePlatform = platformRef == null ? null : platformRef.get();
    if (remotePlatform == null) {
        final SAXHandler handler = new SAXHandler();
        try (InputStream in = store.getPrimaryFile().getInputStream()) {
            final XMLReader reader = XMLUtil.createXMLReader();
            InputSource is = new InputSource(in);
            is.setSystemId(store.getPrimaryFile().toURL().toExternalForm());
            reader.setContentHandler(handler);
            reader.setErrorHandler(handler);
            reader.setEntityResolver(handler);
            reader.parse(is);
        } catch (SAXException ex) {
            final Exception x = ex.getException();
            if (x instanceof java.io.IOException) {
                throw (IOException)x;
            } else {
                throw new java.io.IOException(ex);
            }
        }
        remotePlatform = RemotePlatform.create(
                handler.name,
                handler.properties,
                handler.sysProperties);
        remotePlatform.addPropertyChangeListener(this);
        platformRef = new WeakReference<>(remotePlatform);
    }
    return remotePlatform;
}
 
Example #30
Source File: UserConfigBuilderTest.java    From vespa with Apache License 2.0 5 votes vote down vote up
private Element getDocument(String xml) {
    Reader xmlReader = new StringReader("<model>" + xml + "</model>");
    Document doc;
    try {
        doc = XmlHelper.getDocumentBuilder().parse(new InputSource(xmlReader));
    } catch (Exception e) {
        throw new RuntimeException();
    }
    return doc.getDocumentElement();
}