Java Code Examples for org.xml.sax.InputSource

The following are top voted examples for showing how to use org.xml.sax.InputSource. 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: incubator-netbeans   File: XMLUtilTest.java   View source code 7 votes vote down vote up
public void testCDATA() throws Exception {
    Document doc = XMLUtil.createDocument("root", null, null, null);
    Element e = doc.createElement("sometag");
    doc.getDocumentElement().appendChild(e);

    String cdataContent = "!&<>*\n[[]]";
    CDATASection cdata = doc.createCDATASection(cdataContent);
    e.appendChild(cdata);
    
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    XMLUtil.write(doc, baos, "UTF-8");

    String data = baos.toString("UTF-8").replace("\r\n", "\n");
    assertTrue("Can't find CDATA section", data.indexOf("<![CDATA[" + cdataContent + "]]>") != -1);
    
    // parse the data back to DOM
    Document doc2 = XMLUtil.parse(new InputSource(new ByteArrayInputStream(baos.toByteArray())), false, false, null, null);
    NodeList nl = doc2.getElementsByTagName("sometag");
    assertEquals("Wrong number of <sometag/> elements", 1, nl.getLength());
    nl = nl.item(0).getChildNodes();
    assertEquals("Wrong number of <sometag/> child elements", 1, nl.getLength());
    Node child = nl.item(0);
    assertTrue("Expecting CDATASection node", child instanceof CDATASection);
    assertEquals("Wrong CDATASection content", cdataContent, ((CDATASection) child).getNodeValue());
}
 
Example 2
Project: openjdk-jdk10   File: SAXParser.java   View source code 6 votes vote down vote up
/**
 * Parse the content given {@link org.xml.sax.InputSource}
 * as XML using the specified
 * {@link org.xml.sax.helpers.DefaultHandler}.
 *
 * @param is The InputSource containing the content to be parsed.
 * @param dh The SAX DefaultHandler to use.
 *
 * @throws IllegalArgumentException If the <code>InputSource</code> object
 *   is <code>null</code>.
 * @throws IOException If any IO errors occur.
 * @throws SAXException If any SAX errors occur during processing.
 *
 * @see org.xml.sax.DocumentHandler
 */
public void parse(InputSource is, DefaultHandler dh)
    throws SAXException, IOException {
    if (is == null) {
        throw new IllegalArgumentException("InputSource cannot be null");
    }

    XMLReader reader = this.getXMLReader();
    if (dh != null) {
        reader.setContentHandler(dh);
        reader.setEntityResolver(dh);
        reader.setErrorHandler(dh);
        reader.setDTDHandler(dh);
    }
    reader.parse(is);
}
 
Example 3
Project: incubator-netbeans   File: XMLFileSystem.java   View source code 6 votes vote down vote up
@Override
public InputSource resolveEntity(String pid, String sid)
throws SAXException {
    String publicURL = (String) dtdMap.get(pid);

    if (publicURL != null) {
        if (validate) {
            publicURL = getClass().getClassLoader().getResource(publicURL).toExternalForm();

            return new InputSource(publicURL);
        } else {
            return new InputSource(new ByteArrayInputStream(new byte[0]));
        }
    }

    return new InputSource(sid);
}
 
Example 4
Project: openjdk-jdk10   File: CatalogResolverImpl.java   View source code 6 votes vote down vote up
@Override
public InputStream resolveEntity(String publicId, String systemId, String baseUri, String namespace) {
    InputSource is = resolveEntity(publicId, systemId);

    if (is != null && !is.isEmpty()) {

        try {
            return new URL(is.getSystemId()).openStream();
        } catch (IOException ex) {
            //considered as no mapping.
        }

    }

    GroupEntry.ResolveType resolveType = ((CatalogImpl) catalog).getResolve();
    switch (resolveType) {
        case IGNORE:
            return null;
        case STRICT:
            CatalogMessages.reportError(CatalogMessages.ERR_NO_MATCH,
                    new Object[]{publicId, systemId});
    }

    //no action, allow the parser to continue
    return null;
}
 
Example 5
Project: oscm   File: TechnicalProductXmlConverterTest.java   View source code 6 votes vote down vote up
/**
 * parse the XML content and verify the provisioningUsername and
 * provisioningPassword have been exported as expected
 * 
 * @param xmlString
 * @throws Exception
 */
private void verifyXmlForUserAndPwd(String xmlString) throws Exception {
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    DocumentBuilder builder = factory.newDocumentBuilder();
    Document document = builder.parse(new InputSource(new StringReader(
            xmlString)));
    assertEquals(1, document.getChildNodes().getLength());
    Element root = document.getDocumentElement();
    assertEquals("tns:TechnicalServices", root.getNodeName());
    List<?> productNodes = XMLConverter.getNodeList(root.getChildNodes(),
            "tns:TechnicalService");
    assertEquals(1, productNodes.size());
    Element e = (Element) productNodes.get(0);
    assertEquals(PROVISIONING_USER_NAME,
            e.getAttribute("provisioningUsername"));
    assertEquals(PROVISIONING_PASSWORD,
            e.getAttribute("provisioningPassword"));
}
 
Example 6
Project: openjdk-jdk10   File: SAXTFactoryTest.java   View source code 6 votes vote down vote up
/**
 * Unit test for TemplatesHandler setter/getter.
 *
 * @throws Exception If any errors occur.
 */
@Test
public void testcase13() throws Exception {
    String outputFile = USER_DIR + "saxtf013.out";
    String goldFile = GOLDEN_DIR + "saxtf013GF.out";
    try(FileInputStream fis = new FileInputStream(XML_FILE)) {
        // The transformer will use a SAX parser as it's reader.
        XMLReader reader = XMLReaderFactory.createXMLReader();

        SAXTransformerFactory saxTFactory
                = (SAXTransformerFactory) TransformerFactory.newInstance();
        TemplatesHandler thandler = saxTFactory.newTemplatesHandler();
        // I have put this as it was complaining about systemid
        thandler.setSystemId("file:///" + USER_DIR);

        reader.setContentHandler(thandler);
        reader.parse(XSLT_FILE);
        XMLFilter filter
                = saxTFactory.newXMLFilter(thandler.getTemplates());
        filter.setParent(reader);

        filter.setContentHandler(new MyContentHandler(outputFile));
        filter.parse(new InputSource(fis));
    }
    assertTrue(compareWithGold(goldFile, outputFile));
}
 
Example 7
Project: OpenJSharp   File: SAXSource.java   View source code 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 8
Project: openjdk-jdk10   File: XML_SAX_StAX_FI.java   View source code 6 votes vote down vote up
public void parse(InputStream xml, OutputStream finf, String workingDirectory) throws Exception {
    StAXDocumentSerializer documentSerializer = new StAXDocumentSerializer();
    documentSerializer.setOutputStream(finf);

    SAX2StAXWriter saxTostax = new SAX2StAXWriter(documentSerializer);

    SAXParserFactory saxParserFactory = SAXParserFactory.newInstance();
    saxParserFactory.setNamespaceAware(true);
    SAXParser saxParser = saxParserFactory.newSAXParser();

    XMLReader reader = saxParser.getXMLReader();
    reader.setProperty("http://xml.org/sax/properties/lexical-handler", saxTostax);
    reader.setContentHandler(saxTostax);

    if (workingDirectory != null) {
        reader.setEntityResolver(createRelativePathResolver(workingDirectory));
    }
    reader.parse(new InputSource(xml));

    xml.close();
    finf.close();
}
 
Example 9
Project: openjdk-jdk10   File: SAXDocumentParser.java   View source code 6 votes vote down vote up
public void parse(InputSource input) throws IOException, SAXException {
    try {
        InputStream s = input.getByteStream();
        if (s == null) {
            String systemId = input.getSystemId();
            if (systemId == null) {
                throw new SAXException(CommonResourceBundle.getInstance().getString("message.inputSource"));
            }
            parse(systemId);
        } else {
            parse(s);
        }
    } catch (FastInfosetException e) {
        logger.log(Level.FINE, "parsing error", e);
        throw new SAXException(e);
    }
}
 
Example 10
Project: OperatieBRP   File: Xml.java   View source code 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 11
Project: payment-wechat   File: ThlwsBeanUtil.java   View source code 6 votes vote down vote up
/**
 * Format xml string.
 *
 * @param uglyXml the ugly xml
 * @return the string
 */
public static String formatXml(String uglyXml) {
	try {
		String xmlHeader= "<?xml version=\"1.0\" encoding=\"UTF-8\"?>";
		DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
		DocumentBuilder db = dbf.newDocumentBuilder();
		InputSource is = new InputSource(new StringReader(uglyXml));
		final Document document = db.parse(is);
		OutputFormat format = new OutputFormat(document);
		format.setLineWidth(65);
		format.setIndenting(true);
		format.setIndent(2);
		Writer out = new StringWriter();
		XMLSerializer serializer = new XMLSerializer(out, format);
		serializer.serialize(document);
		return out.toString().replace(xmlHeader,"");
	} catch (Exception e) {
		return "";
	}
}
 
Example 12
Project: oscm   File: TriggerServiceBean.java   View source code 6 votes vote down vote up
private String retrieveValueByXpath(String xml, DocumentBuilder builder,
    XPathExpression expr) {
    try {
        Document document = builder
            .parse(new InputSource(new StringReader(xml)));
        NodeList nodes = (NodeList) expr.evaluate(document,
            XPathConstants.NODESET);
        if (nodes == null || nodes.item(0) == null
            || nodes.item(0).getFirstChild() == null) {
            return null;
        }
        return nodes.item(0).getFirstChild().getNodeValue();
    } catch (SAXException | XPathExpressionException | IOException e) {
        e.printStackTrace();
    }
    return null;
}
 
Example 13
Project: hadoop   File: TestRMWebServices.java   View source code 6 votes vote down vote up
public void verifyClusterInfoXML(String xml) throws JSONException, Exception {
  DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
  DocumentBuilder db = dbf.newDocumentBuilder();
  InputSource is = new InputSource();
  is.setCharacterStream(new StringReader(xml));
  Document dom = db.parse(is);
  NodeList nodes = dom.getElementsByTagName("clusterInfo");
  assertEquals("incorrect number of elements", 1, nodes.getLength());

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

    verifyClusterGeneric(WebServicesTestUtils.getXmlLong(element, "id"),
        WebServicesTestUtils.getXmlLong(element, "startedOn"),
        WebServicesTestUtils.getXmlString(element, "state"),
        WebServicesTestUtils.getXmlString(element, "haState"),
        WebServicesTestUtils.getXmlString(element, "hadoopVersionBuiltOn"),
        WebServicesTestUtils.getXmlString(element, "hadoopBuildVersion"),
        WebServicesTestUtils.getXmlString(element, "hadoopVersion"),
        WebServicesTestUtils.getXmlString(element,
            "resourceManagerVersionBuiltOn"),
        WebServicesTestUtils.getXmlString(element,
            "resourceManagerBuildVersion"),
        WebServicesTestUtils.getXmlString(element, "resourceManagerVersion"));
  }
}
 
Example 14
Project: incubator-netbeans   File: MakeNBM.java   View source code 6 votes vote down vote up
static void validateAgainstAUDTDs(InputSource input, final Path updaterJar, final Task task) throws IOException, SAXException {
    XMLUtil.parse(input, true, false, XMLUtil.rethrowHandler(), new EntityResolver() {
        ClassLoader loader = new AntClassLoader(task.getProject(), updaterJar);
        public InputSource resolveEntity(String publicId, String systemId) throws SAXException, IOException {
            String remote = "http://www.netbeans.org/dtds/";
            if (systemId.startsWith(remote)) {
                String rsrc = "org/netbeans/updater/resources/" + systemId.substring(remote.length());
                URL u = loader.getResource(rsrc);
                if (u != null) {
                    return new InputSource(u.toString());
                } else {
                    task.log(rsrc + " not found in " + updaterJar, Project.MSG_WARN);
                }
            }
            return null;
        }
    });
}
 
Example 15
Project: apache-tomcat-7.0.73-with-comment   File: InputSourceUtil.java   View source code 6 votes vote down vote up
public static void close(InputSource inputSource) {
    if (inputSource == null) {
        // Nothing to do
        return;
    }

    InputStream is = inputSource.getByteStream();
    if (is != null) {
        try {
            is.close();
        } catch (Throwable t) {
            ExceptionUtils.handleThrowable(t);
        }
    }

}
 
Example 16
Project: OpenJSharp   File: IncrementalSAXSource_Xerces.java   View source code 6 votes vote down vote up
/** startParse() is a simple API which tells the IncrementalSAXSource
 * to begin reading a document.
 *
 * @throws SAXException is parse thread is already in progress
 * or parsing can not be started.
 * */
public void startParse(InputSource source) throws SAXException
{
  if (fIncrementalParser==null)
    throw new SAXException(XMLMessages.createXMLMessage(XMLErrorResources.ER_STARTPARSE_NEEDS_SAXPARSER, null)); //"startParse needs a non-null SAXParser.");
  if (fParseInProgress)
    throw new SAXException(XMLMessages.createXMLMessage(XMLErrorResources.ER_STARTPARSE_WHILE_PARSING, null)); //"startParse may not be called while parsing.");

  boolean ok=false;

  try
  {
    ok = parseSomeSetup(source);
  }
  catch(Exception ex)
  {
    throw new SAXException(ex);
  }

  if(!ok)
    throw new SAXException(XMLMessages.createXMLMessage(XMLErrorResources.ER_COULD_NOT_INIT_PARSER, null)); //"could not initialize parser with");
}
 
Example 17
Project: jdk8u-jdk   File: CanonicalizerSpi.java   View source code 6 votes vote down vote up
/**
 * Method canonicalize
 *
 * @param inputBytes
 * @return the c14n bytes.
 *
 * @throws CanonicalizationException
 * @throws java.io.IOException
 * @throws javax.xml.parsers.ParserConfigurationException
 * @throws org.xml.sax.SAXException
 */
public byte[] engineCanonicalize(byte[] inputBytes)
    throws javax.xml.parsers.ParserConfigurationException, java.io.IOException,
    org.xml.sax.SAXException, CanonicalizationException {

    java.io.InputStream bais = new ByteArrayInputStream(inputBytes);
    InputSource in = new InputSource(bais);
    DocumentBuilderFactory dfactory = DocumentBuilderFactory.newInstance();
    dfactory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, Boolean.TRUE);

    // needs to validate for ID attribute normalization
    dfactory.setNamespaceAware(true);

    DocumentBuilder db = dfactory.newDocumentBuilder();

    Document document = db.parse(in);
    return this.engineCanonicalizeSubTree(document);
}
 
Example 18
Project: Equella   File: BaseHandler.java   View source code 6 votes vote down vote up
/**
 * @see org.xml.sax.EntityResolver#resolveEntity(java.lang.String,
 *      java.lang.String)
 */
@Override
public InputSource resolveEntity(final String publicId, final String systemId)
	throws SAXException
{
	if( entityResolver != null )
	{
		try
		{
			return entityResolver.resolveEntity(publicId, systemId);
		}
		catch( SAXException se )
		{
			throw se;
		}
		catch( IOException ioe )
		{
			throw new SAXException("I/O error has occurred - " + ioe, ioe); //$NON-NLS-1$
		}
	}
	log.warn("ignoring publicId=" + publicId //$NON-NLS-1$
		+ " and systemId=" + systemId); //$NON-NLS-1$
	return null;
}
 
Example 19
Project: incubator-netbeans   File: Arch.java   View source code 6 votes vote down vote up
public InputSource resolveEntity(String publicId, String systemId) throws SAXException, IOException {
    log("publicId: " + publicId + " systemId: " + systemId, Project.MSG_VERBOSE);
    
    int idx = systemId.lastIndexOf('/');
    String last = systemId.substring(idx + 1);
    
    if (localDTDs.contains(last)) {
        log("Resolved to embedded DTD");
        InputSource is = new InputSource(Arch.class.getResourceAsStream(last));
        is.setSystemId(systemId);
        return is;
    } else {
        log("Not resolved");
        return null;
    }
}
 
Example 20
Project: automat   File: Excel2007Reader.java   View source code 6 votes vote down vote up
/**
 * 遍历工作簿中所有的电子表格
 * 
 * @param filename
 * @throws Exception
 */
public void process(InputStream stream) throws Exception {
	OPCPackage pkg = OPCPackage.open(stream);
	XSSFReader r = new XSSFReader(pkg);
	SharedStringsTable sst = r.getSharedStringsTable();
	XMLReader parser = fetchSheetParser(sst);
	Iterator<InputStream> sheets = r.getSheetsData();
	while (sheets.hasNext()) {
		curRow = 0;
		sheetIndex++;
		InputStream sheet = sheets.next();
		InputSource sheetSource = new InputSource(sheet);
		parser.parse(sheetSource);
		sheet.close();
	}
}
 
Example 21
Project: openjdk-jdk10   File: CatalogTest.java   View source code 6 votes vote down vote up
@DataProvider(name = "supportLSResourceResolver1")
public Object[][] supportLSResourceResolver1() throws Exception {
    URI catalogFile = getClass().getResource("CatalogSupport.xml").toURI();
    URI catalogFileUri = getClass().getResource("CatalogSupport_uri.xml").toURI();

    /*
     * val_test.xml has a reference to system.dtd and val_test.xsd
    */
    SAXSource ss = new SAXSource(new InputSource(xml_val_test));
    ss.setSystemId(xml_val_test_id);

    return new Object[][]{
        {catalogFile, ss},
        {catalogFileUri, ss},
     };
}
 
Example 22
Project: MybatisGeneatorUtil   File: XmlFileMergerTest.java   View source code 6 votes vote down vote up
@Test
public void testThatFilesAreTheSameAfterMerge() throws Exception {
    DefaultXmlFormatter xmlFormatter = new DefaultXmlFormatter();
    Properties p = new Properties();
    p.setProperty(PropertyRegistry.COMMENT_GENERATOR_SUPPRESS_DATE, "true");
    CommentGenerator commentGenerator = new DefaultCommentGenerator();
    commentGenerator.addConfigurationProperties(p);

    Document document = new Document(XmlConstants.MYBATIS3_MAPPER_PUBLIC_ID,
            XmlConstants.MYBATIS3_MAPPER_SYSTEM_ID);
    document.setRootElement(getSqlMapElement(commentGenerator));

    GeneratedXmlFile generatedFile1 = new GeneratedXmlFile(document, "TestMapper.xml", "org.mybatis.test", "src",
            true, xmlFormatter);
    InputSource is1 = new InputSource(new StringReader(generatedFile1.getFormattedContent()));

    GeneratedXmlFile generatedFile2 = new GeneratedXmlFile(document, "TestMapper.xml", "org.mybatis.test", "src",
            true, xmlFormatter);
    InputSource is2 = new InputSource(new StringReader(generatedFile2.getFormattedContent()));

    String mergedSource = XmlFileMergerJaxp.getMergedSource(is1, is2, "TestMapper.xml");

    assertEquals(generatedFile1.getFormattedContent(), mergedSource);
}
 
Example 23
Project: incubator-netbeans   File: CatalogTest.java   View source code 6 votes vote down vote up
public void testSpaceInPath() throws Exception {
    Catalog catalog = new Catalog();
    URL locationURL = getClass().getResource("data/catalog.xml");
    String location = locationURL.toExternalForm();
    catalog.setLocation(location);
    catalog.refresh();
    String s0 = catalog.resolvePublic("-//NetBeans//IZ53710//EN");
    new URL(s0).openStream();
    String s1 = catalog.resolvePublic("-//NetBeans//IZ53710 1//EN");
    new URL(s1).openStream();
    String s2 = catalog.resolvePublic("-//NetBeans//IZ53710 2//EN");
    // new URL(s2).openStream();
    String s3 = catalog.resolvePublic("-//NetBeans//IZ53710 3//EN");
    new URL(s3).openStream();

    InputSource in1 = catalog.resolveEntity("-//NetBeans//IZ53710 1//EN", null);
    InputSource in2 = catalog.resolveEntity("-//NetBeans//IZ53710 2//EN", null);
    InputSource in3 = catalog.resolveEntity("-//NetBeans//IZ53710 3//EN", null);

    System.err.println("Done");
}
 
Example 24
Project: openjdk-jdk10   File: Bug6690015.java   View source code 5 votes vote down vote up
@Test
public void test() {
    try {
        FileInputStream fis = new FileInputStream(getClass().getResource("bug6690015.xml").getFile());

        Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(new InputSource(fis));
        Element root = doc.getDocumentElement();
        NodeList textnodes = root.getElementsByTagName("text");
        int len = textnodes.getLength();
        int index = 0;
        int attindex = 0;
        int attrlen = 0;
        NamedNodeMap attrs = null;

        while (index < len) {
            Element te = (Element) textnodes.item(index);
            attrs = te.getAttributes();
            attrlen = attrs.getLength();
            attindex = 0;
            Node node = null;

            while (attindex < attrlen) {
                node = attrs.item(attindex);
                System.out.println("attr: " + node.getNodeName() + " is shown holding value: " + node.getNodeValue());
                attindex++;
            }
            index++;
            System.out.println("-------------");
        }
        fis.close();
    } catch (Exception e) {
        Assert.fail("Exception: " + e.getMessage());
    }
}
 
Example 25
Project: openjdk-jdk10   File: ValidationWarningsTest.java   View source code 5 votes vote down vote up
void doOneTestIteration() throws Exception {
    Source src = new StreamSource(new StringReader(xml));
    SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
    SAXSource xsdSource = new SAXSource(new InputSource(new ByteArrayInputStream(xsd.getBytes())));
    Schema schema = schemaFactory.newSchema(xsdSource);
    Validator v = schema.newValidator();
    v.validate(src);
}
 
Example 26
Project: openjdk-jdk10   File: XPathExpressionTest.java   View source code 5 votes vote down vote up
/**
 * Test for evaluate(InputSource source,QName returnType) return a node list
 * if returnType is NodeList.
 *
 * @throws Exception If any errors occur.
 */
@Test
public void testCheckXPathExpression31() throws Exception {
    try (InputStream is = Files.newInputStream(XML_PATH)) {
        NodeList nodeList = (NodeList) xpath.compile(EXPRESSION_NAME_A).
            evaluate(new InputSource(is), NODESET);
        assertEquals(((Attr) nodeList.item(0)).getValue(), "6");
    }
}
 
Example 27
Project: kaltura-ce-sakai-extension   File: KalturaAPIService.java   View source code 5 votes vote down vote up
/**
 * Method to process the KalturaMetadata object (and the XML it contains) into a list of field strings
 * @param metadata kaltura metadata object
 * @return List of field strings
 */
private List<String> convertKalturaMetadataToFieldsList(KalturaMetadata metadata) {
    List<String> fields = new ArrayList<String>();
    // if metadata exists for object
    if (metadata != null && StringUtils.isNotEmpty(metadata.xml)) {
        // check for malformed beginning of XML
        String metadataXml = metadata.xml;
        if (StringUtils.startsWithIgnoreCase(metadataXml, "xml=")){ 
            metadataXml = metadataXml.replaceAll("xml=", ""); 
        }

        // ensure XML begins with the <?xml tag
        int lastIndex = StringUtils.lastIndexOf(metadataXml, "<?xml");
        if(lastIndex > 0){
            metadataXml = StringUtils.substring(metadataXml, lastIndex);
        }

        // set the metadata's XML to the updated string
        metadata.xml = metadataXml;

        try {
            Document metadataDoc = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(new InputSource(new StringReader(metadata.xml)));
            org.w3c.dom.Element root = metadataDoc.getDocumentElement();
            NodeList childNodes = root.getChildNodes();
            for (int i = 0; i < childNodes.getLength(); i++) {
                Node node = childNodes.item(i);
                if (node instanceof org.w3c.dom.Element) {
                    fields.add(node.getTextContent());
                }
            }
        } catch (Exception e) {
            throw new RuntimeException("Error processing metadata fields for kaltura metadata object (" + metadata.objectId + ") :: " + e + ", xml="+metadata.xml, e);
        }
    }
    return fields;
}
 
Example 28
Project: OpenJSharp   File: ValidatorHandlerImpl.java   View source code 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 29
Project: QiuQiu   File: UrlDtdPathResolver.java   View source code 5 votes vote down vote up
@Override
public InputSource resolveEntity(String publicId, String systemId) throws SAXException, IOException {
    if (systemId != null) {
        return new InputSource(Thread.currentThread().getContextClassLoader().getResourceAsStream("config/config.dtd"));
    }
    return null;
}
 
Example 30
Project: incubator-netbeans   File: Convertors.java   View source code 5 votes vote down vote up
/**
 * @return InputSource, a callie SHOULD set systemId if available
 */
public static InputSource documentToInputSource (Document doc) {
    String text = documentToString (doc);
    Reader reader = new StringReader (text);
    InputSource in = new InputSource ("StringReader"); // NOI18N
    in.setCharacterStream (reader);
    return in;
}
 
Example 31
Project: tomcat7   File: Digester.java   View source code 5 votes vote down vote up
/**
 * Parse the content of the specified file using this Digester.  Returns
 * the root element from the object stack (if any).
 *
 * @param file File containing the XML data to be parsed
 *
 * @exception IOException if an input/output error occurs
 * @exception SAXException if a parsing exception occurs
 */
public Object parse(File file) throws IOException, SAXException {

    configure();
    InputSource input = new InputSource(new FileInputStream(file));
    input.setSystemId("file://" + file.getAbsolutePath());
    getXMLReader().parse(input);
    return (root);

}
 
Example 32
Project: jdk8u-jdk   File: XOMParserTest.java   View source code 5 votes vote down vote up
public void canonicalize(String inName, String outName) {
    try (//FileOutputStream outStream = new FileOutputStream(outName);
            FileInputStream inputStream = new FileInputStream(inName);) {
        JDK15XML1_0Parser parser = new JDK15XML1_0Parser();
        parser.parse(new InputSource(inputStream));
        success("test passed");
    } catch (Exception e) {
        fail(e.getMessage());
    }

}
 
Example 33
Project: myfaces-trinidad   File: TreeBuilder.java   View source code 5 votes vote down vote up
/**
 * Parses the document.
 * @param provider an implementation of the XMLProvider interface
 * @param source a SAX input source
 * @param context a parsing context
 * @param rootParser the root parser to start with;  if null,
 *         a root parser will be derived based on the rootClass
 *         requested in the constructor.
 * @return an object that is the result of parsing.
 */
public Object parse(
  XMLProvider      provider,
  InputSource      source,
  ParseContext     context,
  NodeParser       rootParser) throws IOException, SAXException
{
  if ((_rootClass == null) && (rootParser == null))
    throw new NullPointerException(_LOG.getMessage(
      "NULL_ROOTCLASS_ROOTPARSER"));

  if (provider == null)
    provider = new JaxpXMLProvider();

  ParseContextWrapper wrappedContext = new ParseContextWrapper(context,
                                                               _manager,
                                                               provider);
  Handler handler = new Handler(wrappedContext, rootParser);
  XMLReader reader = provider.getXMLReader();

  // Force these two features to be set the way we want.
  // These are the default values, but we'd crash and burn
  // if they're wrong.
  reader.setFeature("http://xml.org/sax/features/namespaces", true);
  reader.setFeature("http://xml.org/sax/features/namespace-prefixes", false);

  reader.setContentHandler(handler);
  reader.setErrorHandler(handler);
  if (getEntityResolver() != null)
    reader.setEntityResolver(getEntityResolver());

  reader.parse(source);

  return handler.getRoot();
}
 
Example 34
Project: incubator-netbeans   File: PersistenceManager.java   View source code 5 votes vote down vote up
/** Returns a XML parser. The same parser can be returned assuming that config files
 * are parser sequentially.
 *
 * @return XML parser with set content handler, errror handler
 * and entity resolver.
 */
public XMLReader getXMLParser (DefaultHandler h) throws SAXException {
    if (parser == null) {
        // get non validating, not namespace aware parser
        parser = XMLUtil.createXMLReader();
        parser.setEntityResolver(new EntityResolver () {
            /** Implementation of entity resolver. Points to the local DTD
             * for our public ID */
            public InputSource resolveEntity (String publicId, String systemId)
            throws SAXException {
                if (ModeParser.INSTANCE_DTD_ID_1_0.equals(publicId)
                || ModeParser.INSTANCE_DTD_ID_1_1.equals(publicId)
                || ModeParser.INSTANCE_DTD_ID_1_2.equals(publicId)
                || ModeParser.INSTANCE_DTD_ID_2_0.equals(publicId)
                || ModeParser.INSTANCE_DTD_ID_2_1.equals(publicId)
                || ModeParser.INSTANCE_DTD_ID_2_2.equals(publicId)
                || ModeParser.INSTANCE_DTD_ID_2_3.equals(publicId)
                || GroupParser.INSTANCE_DTD_ID_2_0.equals(publicId)
                || TCGroupParser.INSTANCE_DTD_ID_2_0.equals(publicId)
                || TCRefParser.INSTANCE_DTD_ID_1_0.equals(publicId)
                || TCRefParser.INSTANCE_DTD_ID_2_0.equals(publicId)
                || TCRefParser.INSTANCE_DTD_ID_2_1.equals(publicId)
                || TCRefParser.INSTANCE_DTD_ID_2_2.equals(publicId)
                || WindowManagerParser.INSTANCE_DTD_ID_1_0.equals(publicId)
                || WindowManagerParser.INSTANCE_DTD_ID_1_1.equals(publicId)
                || WindowManagerParser.INSTANCE_DTD_ID_2_0.equals(publicId)
                || WindowManagerParser.INSTANCE_DTD_ID_2_1.equals(publicId)) {
                    InputStream is = new ByteArrayInputStream(new byte[0]);
                    return new InputSource(is);
                }
                return null; // i.e. follow advice of systemID
            }
        });
    }
    parser.setContentHandler(h);
    parser.setErrorHandler(h);
    return parser;
}
 
Example 35
Project: openjdk-jdk10   File: SAXParserTest.java   View source code 5 votes vote down vote up
/**
 * Test with an invalid XML file, parser should throw SAXException.
 *
 * @param saxparser a SAXParser instance.
 * @throws Exception If any errors occur.
 */
@Test(expectedExceptions = SAXException.class,
        dataProvider = "parser-provider")
public void testParse29(SAXParser saxparser) throws Exception {
    try (FileInputStream instream = new FileInputStream(
            new File(XML_DIR, "invalid.xml"))) {
        saxparser.parse(new InputSource(instream), new DefaultHandler());
    }
}
 
Example 36
Project: qpp-conversion-tool   File: QrdaGenerator.java   View source code 5 votes vote down vote up
private void prettyPrint(StringWriter writer) throws TransformerException, IOException,
		SAXException, ParserConfigurationException, XPathExpressionException {
	DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
	DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
	InputSource is = new InputSource(new InputStreamReader(
			new ByteArrayInputStream(writer.toString().getBytes())));

	Document original = dBuilder.parse(is);
	removeWhitespace(original);
	moreThanMeetsTheEye().transform(new DOMSource(original), getDestination());
}
 
Example 37
Project: convertigo-eclipse   File: ProjectExplorerView.java   View source code 5 votes vote down vote up
/**
 * Parses as a DOM the IFile passed in argument ..
 * 
 * @param 	file to parse
 * @return 	parsed Document
 */
private Document parseXslFile(IFile file) throws Exception
{
	Document doc;
	doc = XMLUtils.getDefaultDocumentBuilder().parse(new InputSource(file.getContents()));
	return doc;
}
 
Example 38
Project: openjdk-jdk10   File: SupplementDataParseHandler.java   View source code 5 votes vote down vote up
@Override
public InputSource resolveEntity(String publicID, String systemID) throws IOException, SAXException {
    // avoid HTTP traffic to unicode.org
    if (systemID.startsWith(CLDRConverter.SPPL_LDML_DTD_SYSTEM_ID)) {
        return new InputSource((new File(CLDRConverter.LOCAL_SPPL_LDML_DTD)).toURI().toString());
    }
    return null;
}
 
Example 39
Project: defense-solutions-proofs-of-concept   File: CoTAdapterInbound.java   View source code 5 votes vote down vote up
private NodeList unpackXML(String xml, String targetTag) throws Exception {
	try {
		DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
		DocumentBuilder db = dbf.newDocumentBuilder();
		InputSource source = new InputSource();
		source.setCharacterStream(new StringReader(xml));
		Document doc = db.parse(source);
		NodeList nodeList = doc.getElementsByTagName(targetTag);
		return nodeList;
	} catch (Exception e) {
		log.error(e);
		log.error(e.getStackTrace());
		throw (e);
	}
}
 
Example 40
Project: fastAOP   File: Processor.java   View source code 5 votes vote down vote up
private void processEntry(final ZipInputStream zis, final ZipEntry ze,
        final ContentHandlerFactory handlerFactory) {
    ContentHandler handler = handlerFactory.createContentHandler();
    try {

        // if (CODE2ASM.equals(command)) { // read bytecode and process it
        // // with TraceClassVisitor
        // ClassReader cr = new ClassReader(readEntry(zis, ze));
        // cr.accept(new TraceClassVisitor(null, new PrintWriter(os)),
        // false);
        // }

        boolean singleInputDocument = inRepresentation == SINGLE_XML;
        if (inRepresentation == BYTECODE) { // read bytecode and process it
            // with handler
            ClassReader cr = new ClassReader(readEntry(zis, ze));
            cr.accept(new SAXClassAdapter(handler, singleInputDocument), 0);

        } else { // read XML and process it with handler
            XMLReader reader = XMLReaderFactory.createXMLReader();
            reader.setContentHandler(handler);
            reader.parse(new InputSource(
                    singleInputDocument ? (InputStream) new ProtectedInputStream(
                            zis) : new ByteArrayInputStream(readEntry(zis,
                            ze))));

        }
    } catch (Exception ex) {
        update(ze.getName(), 0);
        update(ex, 0);
    }
}