Java Code Examples for javax.xml.parsers.SAXParserFactory

The following are top voted examples for showing how to use javax.xml.parsers.SAXParserFactory. 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: TrabalhoFinalEDA2   File: mxGraphViewImageReader.java   Source Code and License 7 votes vote down vote up
/**
 * Creates the image for the given display XML input source. (Note: The XML
 * is an encoded mxGraphView, not mxGraphModel.)
 * 
 * @param inputSource
 *            Input source that contains the display XML.
 * @return Returns an image representing the display XML input source.
 */
public static BufferedImage convert(InputSource inputSource,
		mxGraphViewImageReader viewReader)
		throws ParserConfigurationException, SAXException, IOException
{
	BufferedImage result = null;
	SAXParser parser = SAXParserFactory.newInstance().newSAXParser();
	XMLReader reader = parser.getXMLReader();

	reader.setContentHandler(viewReader);
	reader.parse(inputSource);

	if (viewReader.getCanvas() instanceof mxImageCanvas)
	{
		result = ((mxImageCanvas) viewReader.getCanvas()).destroy();
	}

	return result;
}
 
Example 2
Project: openjdk-jdk10   File: DefaultHandlerTest.java   Source Code and License 7 votes vote down vote up
/**
 * Test default handler that transverses XML and  print all visited node.
 *
 * @throws Exception If any errors occur.
 */
@Test
public void testDefaultHandler() throws Exception {
    String outputFile = USER_DIR + "DefaultHandler.out";
    String goldFile = GOLDEN_DIR + "DefaultHandlerGF.out";
    String xmlFile = XML_DIR + "namespace1.xml";

    SAXParserFactory spf = SAXParserFactory.newInstance();
    spf.setNamespaceAware(true);
    SAXParser saxparser = spf.newSAXParser();

    MyDefaultHandler handler = new MyDefaultHandler(outputFile);
    File file = new File(xmlFile);
    String Absolutepath = file.getAbsolutePath();
    String newAbsolutePath = Absolutepath;
    if (File.separatorChar == '\\')
            newAbsolutePath = Absolutepath.replace('\\', '/');
    saxparser.parse("file:///" + newAbsolutePath, handler);

    assertTrue(compareWithGold(goldFile, outputFile));

}
 
Example 3
Project: mobile-store   File: RepoDetails.java   Source Code and License 7 votes vote down vote up
@NonNull
public static RepoDetails getFromFile(InputStream inputStream, int pushRequests) {
    try {
        SAXParserFactory factory = SAXParserFactory.newInstance();
        factory.setNamespaceAware(true);
        SAXParser parser = factory.newSAXParser();
        XMLReader reader = parser.getXMLReader();
        RepoDetails repoDetails = new RepoDetails();
        MockRepo mockRepo = new MockRepo(100, pushRequests);
        RepoXMLHandler handler = new RepoXMLHandler(mockRepo, repoDetails);
        reader.setContentHandler(handler);
        InputSource is = new InputSource(new BufferedInputStream(inputStream));
        reader.parse(is);
        return repoDetails;
    } catch (ParserConfigurationException | SAXException | IOException e) {
        e.printStackTrace();
        fail();

        // Satisfies the compiler, but fail() will always throw a runtime exception so we never
        // reach this return statement.
        return null;
    }
}
 
Example 4
Project: tomcat7   File: GenericParser.java   Source Code and License 7 votes vote down vote up
/**
 * Create a <code>SAXParser</code> configured to support XML Schema and DTD
 * @param properties parser specific properties/features
 * @return an XML Schema/DTD enabled <code>SAXParser</code>
 */
public static SAXParser newSAXParser(Properties properties)
        throws ParserConfigurationException, 
               SAXException,
               SAXNotRecognizedException{ 

    SAXParserFactory factory = 
                    (SAXParserFactory)properties.get("SAXParserFactory");
    SAXParser parser = factory.newSAXParser();
    String schemaLocation = (String)properties.get("schemaLocation");
    String schemaLanguage = (String)properties.get("schemaLanguage");

    try{
        if (schemaLocation != null) {
            parser.setProperty(JAXP_SCHEMA_LANGUAGE, schemaLanguage);
            parser.setProperty(JAXP_SCHEMA_SOURCE, schemaLocation);
        }
    } catch (SAXNotRecognizedException e){
        log.info(parser.getClass().getName() + ": "  
                                    + e.getMessage() + " not supported."); 
    }
    return parser;
}
 
Example 5
Project: Phoenicia   File: LocaleManager.java   Source Code and License 7 votes vote down vote up
/**
 * Identify available locales
 * @param locales_directory
 * @return
 */
public Map<String, String> scan(String locales_directory) throws IOException {
    final Map<String, String> locale_map = new HashMap<String, String>();

    String[] files = PhoeniciaContext.assetManager.list(locales_directory);
    for (String locale_dir: files) {
        if (locale_dir.equals("common")) continue;
        String locale_path = locales_directory+"/"+locale_dir+"/manifest.xml";
        LocaleHeaderScanner scanner = new LocaleHeaderScanner(locale_path, locale_map);
        try {
            InputStream locale_manifest_in = PhoeniciaContext.assetManager.open(locale_path);
            final SAXParserFactory spf = SAXParserFactory.newInstance();
            final SAXParser sp = spf.newSAXParser();
            final XMLReader xr = sp.getXMLReader();
            xr.setContentHandler(scanner);
            xr.parse(new InputSource(new BufferedInputStream(locale_manifest_in)));
        } catch (Exception e) {
            Debug.e(e);
        }
    }
    return locale_map;
}
 
Example 6
Project: SciChart.Android.Examples   File: ExampleSourceCodeParser.java   Source Code and License 7 votes vote down vote up
private static String getSearchWords(String xml) {
    try {
        SAXParserFactory spf = SAXParserFactory.newInstance();
        SAXParser sp = spf.newSAXParser();
        XMLReader xr = sp.getXMLReader();

        ItemXMLHandler myXMLHandler = new ItemXMLHandler();
        xr.setContentHandler(myXMLHandler);
        InputSource inStream = new InputSource();

        inStream.setCharacterStream(new StringReader(xml));
        xr.parse(inStream);

        return myXMLHandler.getCollectedNodes();

    } catch (ParserConfigurationException | SAXException | IOException e) {
        e.printStackTrace();
    }
    return "";
}
 
Example 7
Project: Hydrograph   File: XMLParser.java   Source Code and License 7 votes vote down vote up
/**Parses the XML to fetch parameters.
 * @param inputFile, source XML  
 * @return true, if XML is successfully parsed.
 * @throws Exception 
 */
public boolean parseXML(File inputFile,UIComponentRepo componentRepo) throws ParserConfigurationException, SAXException, IOException{
     LOGGER.debug("Parsing target XML for separating Parameters");
        SAXParserFactory factory = SAXParserFactory.newInstance();
        SAXParser saxParser;
	try {
		factory.setFeature(Constants.DISALLOW_DOCTYPE_DECLARATION,true);
		saxParser = factory.newSAXParser();
		XMLHandler xmlhandler = new XMLHandler(componentRepo);
		saxParser.parse(inputFile, xmlhandler);
		return true;
	} catch (ParserConfigurationException | SAXException | IOException exception) {
		 LOGGER.error("Parsing failed...",exception);
		throw exception; 
	}
  }
 
Example 8
Project: OpenJSharp   File: PrintTable.java   Source Code and License 7 votes vote down vote up
/**
 * @param args the command line arguments
 */
public static void main(String[] args) {
    try {
        SAXParserFactory saxParserFactory = SAXParserFactory.newInstance();
        saxParserFactory.setNamespaceAware(true);

        SAXParser saxParser = saxParserFactory.newSAXParser();

        ParserVocabulary referencedVocabulary = new ParserVocabulary();

        VocabularyGenerator vocabularyGenerator = new VocabularyGenerator(referencedVocabulary);
        File f = new File(args[0]);
        saxParser.parse(f, vocabularyGenerator);

        printVocabulary(referencedVocabulary);
    } catch (Exception e) {
        e.printStackTrace();
    }
}
 
Example 9
Project: apache-tomcat-7.0.73-with-comment   File: GenericParser.java   Source Code and License 7 votes vote down vote up
/**
 * Create a <code>SAXParser</code> configured to support XML Schema and DTD
 * @param properties parser specific properties/features
 * @return an XML Schema/DTD enabled <code>SAXParser</code>
 */
public static SAXParser newSAXParser(Properties properties)
        throws ParserConfigurationException, 
               SAXException,
               SAXNotRecognizedException{ 

    SAXParserFactory factory = 
                    (SAXParserFactory)properties.get("SAXParserFactory");
    SAXParser parser = factory.newSAXParser();
    String schemaLocation = (String)properties.get("schemaLocation");
    String schemaLanguage = (String)properties.get("schemaLanguage");

    try{
        if (schemaLocation != null) {
            parser.setProperty(JAXP_SCHEMA_LANGUAGE, schemaLanguage);
            parser.setProperty(JAXP_SCHEMA_SOURCE, schemaLocation);
        }
    } catch (SAXNotRecognizedException e){
        log.info(parser.getClass().getName() + ": "  
                                    + e.getMessage() + " not supported."); 
    }
    return parser;
}
 
Example 10
Project: openjdk-jdk10   File: DocumentBuilderFactoryTest.java   Source Code and License 7 votes vote down vote up
/**
 * Test the default functionality of schema support method. In
 * this case the schema source property is set.
 * @throws Exception If any errors occur.
 */
@Test(dataProvider = "schema-source")
public void testCheckSchemaSupport3(Object schemaSource) throws Exception {
    try {
        SAXParserFactory spf = SAXParserFactory.newInstance();
        spf.setValidating(true);
        spf.setNamespaceAware(true);
        SAXParser sp = spf.newSAXParser();
        sp.setProperty("http://java.sun.com/xml/jaxp/properties/schemaLanguage",
                W3C_XML_SCHEMA_NS_URI);
        sp.setProperty("http://java.sun.com/xml/jaxp/properties/schemaSource", schemaSource);
        DefaultHandler dh = new DefaultHandler();
        // Not expect any unrecoverable error here.
        sp.parse(new File(XML_DIR, "test1.xml"), dh);
    } finally {
        if (schemaSource instanceof Closeable) {
            ((Closeable) schemaSource).close();
        }
    }
}
 
Example 11
Project: openjdk-jdk10   File: FactoryFindTest.java   Source Code and License 6 votes vote down vote up
@Test
public void testFactoryFind() {
    SAXParserFactory factory = SAXParserFactory.newInstance();
    Assert.assertTrue(factory.getClass().getClassLoader() == null);

    runWithAllPerm(() -> Thread.currentThread().setContextClassLoader(null));
    factory = SAXParserFactory.newInstance();
    Assert.assertTrue(factory.getClass().getClassLoader() == null);

    runWithAllPerm(() -> Thread.currentThread().setContextClassLoader(new MyClassLoader()));
    factory = SAXParserFactory.newInstance();
    if (System.getSecurityManager() == null)
        Assert.assertTrue(myClassLoaderUsed);
    else
        Assert.assertFalse(myClassLoaderUsed);
}
 
Example 12
Project: openjdk-jdk10   File: XMLFilterTest.java   Source Code and License 6 votes vote down vote up
/**
 * Set namespaces feature to a value to XMLFilter. it's expected same when
 * obtain it again.
 *
 * @throws Exception If any errors occur.
 */
@Test
public void setFeature01() throws Exception {
    SAXParserFactory spf = SAXParserFactory.newInstance();
    spf.setNamespaceAware(true);

    XMLFilterImpl xmlFilter = new XMLFilterImpl();
    xmlFilter.setParent(spf.newSAXParser().getXMLReader());
    xmlFilter.setFeature(NAMESPACES, false);
    assertFalse(xmlFilter.getFeature(NAMESPACES));
    xmlFilter.setFeature(NAMESPACES, true);
    assertTrue(xmlFilter.getFeature(NAMESPACES));
}
 
Example 13
Project: defense-solutions-proofs-of-concept   File: DefenseInboundAdapter.java   Source Code and License 6 votes vote down vote up
public DefenseInboundAdapter(AdapterDefinition definition) throws ComponentException, ParserConfigurationException, SAXException, IOException
{
	super(definition);
	messageParser = new MessageParser(this);
	saxFactory = SAXParserFactory.newInstance();
	saxParser = saxFactory.newSAXParser();
}
 
Example 14
Project: alfresco-xml-factory   File: AppTest.java   Source Code and License 6 votes vote down vote up
/**
 * Test we have set features the way we expect as defaults.
 */
public void testSAXParserFactoryInWhiteList() throws Throwable
{
    // Using constructor rather than the service locator and then using the helper to configure it.
    SAXParserFactory spf = new SAXParserFactoryImpl();
    FactoryHelper factoryHelper = new FactoryHelper();
    List<String> whiteListClasses = Collections.singletonList(getClass().getName());
    factoryHelper.configureFactory(spf, FactoryHelper.DEFAULT_FEATURES_TO_ENABLE,
            FactoryHelper.DEFAULT_FEATURES_TO_DISABLE,
            whiteListClasses);

    assertFalse(spf.getFeature(XMLConstants.FEATURE_SECURE_PROCESSING));
    assertFalse(spf.getFeature(FactoryHelper.FEATURE_DISALLOW_DOCTYPE));

    assertTrue(spf.getFeature(FactoryHelper.FEATURE_EXTERNAL_GENERAL_ENTITIES));
    assertTrue(spf.getFeature(FactoryHelper.FEATURE_EXTERNAL_PARAMETER_ENTITIES));
    assertTrue(spf.getFeature(FactoryHelper.FEATURE_USE_ENTITY_RESOLVER2));
    assertTrue(spf.getFeature(FactoryHelper.FEATURE_LOAD_EXTERNAL_DTD));

    assertFalse(spf.isXIncludeAware()); // false is the default so is same as the non whitelist test
}
 
Example 15
Project: incubator-netbeans   File: JavaActions.java   Source Code and License 6 votes vote down vote up
/**
 * Find the line number of a target in an Ant script, or some other line in an XML file.
 * Able to find a certain element with a certain attribute matching a given value.
 * See also AntTargetNode.TargetOpenCookie.
 * @param file an Ant script or other XML file
 * @param match the attribute value to match (e.g. target name)
 * @param elementLocalName the (local) name of the element to look for
 * @param elementAttributeName the name of the attribute to match on
 * @return the line number (0-based), or -1 if not found
 */
static final int findLine(FileObject file, final String match, final String elementLocalName, final String elementAttributeName) throws IOException, SAXException, ParserConfigurationException {
    InputSource in = new InputSource(file.getURL().toString());
    SAXParserFactory factory = SAXParserFactory.newInstance();
    factory.setNamespaceAware(true);
    SAXParser parser = factory.newSAXParser();
    final int[] line = new int[] {-1};
    class Handler extends DefaultHandler {
        private Locator locator;
        public void setDocumentLocator(Locator l) {
            locator = l;
        }
        public void startElement(String uri, String localname, String qname, Attributes attr) throws SAXException {
            if (line[0] == -1) {
                if (localname.equals(elementLocalName) && match.equals(attr.getValue(elementAttributeName))) { // NOI18N
                    line[0] = locator.getLineNumber() - 1;
                }
            }
        }
    }
    parser.parse(in, new Handler());
    return line[0];
}
 
Example 16
Project: OpenJSharp   File: Resolver.java   Source Code and License 6 votes vote down vote up
/**
 * Setup readers.
 */
public void setupReaders() {
  SAXParserFactory spf = catalogManager.useServicesMechanism() ?
                  SAXParserFactory.newInstance() : new SAXParserFactoryImpl();
  spf.setNamespaceAware(true);
  spf.setValidating(false);

  SAXCatalogReader saxReader = new SAXCatalogReader(spf);

  saxReader.setCatalogParser(null, "XMLCatalog",
                             "com.sun.org.apache.xml.internal.resolver.readers.XCatalogReader");

  saxReader.setCatalogParser(OASISXMLCatalogReader.namespaceName,
                             "catalog",
                             "com.sun.org.apache.xml.internal.resolver.readers.ExtendedXMLCatalogReader");

  addReader("application/xml", saxReader);

  TR9401CatalogReader textReader = new TR9401CatalogReader();
  addReader("text/plain", textReader);
}
 
Example 17
Project: incubator-netbeans   File: XMLUtil.java   Source Code and License 6 votes vote down vote up
/** Creates a SAX parser.
 *
 * <p>See {@link #parse} for hints on setting an entity resolver.
 *
 * @param validate if true, a validating parser is returned
 * @param namespaceAware if true, a namespace aware parser is returned
 *
 * @throws FactoryConfigurationError Application developers should never need to directly catch errors of this type.
 * @throws SAXException if a parser fulfilling given parameters can not be created
 *
 * @return XMLReader configured according to passed parameters
 */
public static synchronized XMLReader createXMLReader(boolean validate, boolean namespaceAware)
throws SAXException {
    SAXParserFactory factory = saxes[validate ? 0 : 1][namespaceAware ? 0 : 1];
    if (factory == null) {
        try {
            factory = SAXParserFactory.newInstance();
        } catch (FactoryConfigurationError err) {
            Exceptions.attachMessage(
                err, 
                "Info about thread context classloader: " + // NOI18N
                Thread.currentThread().getContextClassLoader()
            );
            throw err;
        }
        factory.setValidating(validate);
        factory.setNamespaceAware(namespaceAware);
        saxes[validate ? 0 : 1][namespaceAware ? 0 : 1] = factory;
    }

    try {
        return factory.newSAXParser().getXMLReader();
    } catch (ParserConfigurationException ex) {
        throw new SAXException("Cannot create parser satisfying configuration parameters", ex); //NOI18N                        
    }
}
 
Example 18
Project: testee.fi   File: BeanDeploymentArchiveImpl.java   Source Code and License 6 votes vote down vote up
private BeansXml readBeansXml(BeanArchive beanArchive, ClasspathResource resource) {
    try {
        final SAXParserFactory factory = SAXParserFactory.newInstance();
        factory.setValidating(true);
        factory.setNamespaceAware(true);
        final SAXParser parser = factory.newSAXParser();
        final InputSource source = new InputSource(new ByteArrayInputStream(resource.getBytes()));
        if (source.getByteStream().available() == 0) {
            // The file is just acting as a marker file
            return EMPTY_BEANS_XML;
        }
        final BeansXmlHandler handler = new BeansXmlHandler(beanArchive.getClasspathEntry().getURL());
        parser.setProperty("http://java.sun.com/xml/jaxp/properties/schemaLanguage", "http://www.w3.org/2001/XMLSchema");
        parser.setProperty("http://java.sun.com/xml/jaxp/properties/schemaSource", loadXsds());
        parser.parse(source, handler);
        return handler.createBeansXml();
    } catch (final SAXException | ParserConfigurationException | IOException e) {
        throw new TestEEfiException(
                "Failed to parse META-INF/beans.xml in " + beanArchive.getClasspathEntry().getURL(),
                e
        );
    }
}
 
Example 19
Project: openjdk-jdk10   File: Bug6467808.java   Source Code and License 6 votes vote down vote up
@Test
public void test() {
    try {
        SAXParserFactory fac = SAXParserFactory.newInstance();
        fac.setNamespaceAware(true);
        SAXParser saxParser = fac.newSAXParser();

        StreamSource src = new StreamSource(new StringReader(SIMPLE_TESTXML));
        Transformer transformer = TransformerFactory.newInstance().newTransformer();
        DOMResult result = new DOMResult();
        transformer.transform(src, result);
    } catch (Throwable ex) {
        // unexpected failure
        ex.printStackTrace();
        Assert.fail(ex.toString());
    }
}
 
Example 20
Project: parabuild-ci   File: DatasetReader.java   Source Code and License 6 votes vote down vote up
/**
 * Reads a {@link PieDataset} from a stream.
 *
 * @param in  the input stream.
 *
 * @return A dataset.
 *
 * @throws IOException if there is an I/O error.
 */
public static PieDataset readPieDatasetFromXML(InputStream in) 
    throws IOException {

    PieDataset result = null;
    SAXParserFactory factory = SAXParserFactory.newInstance();
    try {
        SAXParser parser = factory.newSAXParser();
        PieDatasetHandler handler = new PieDatasetHandler();
        parser.parse(in, handler);
        result = handler.getDataset();
    }
    catch (SAXException e) {
        System.out.println(e.getMessage());
    }
    catch (ParserConfigurationException e2) {
        System.out.println(e2.getMessage());
    }
    return result;

}
 
Example 21
Project: OpenJSharp   File: ResolvingParser.java   Source Code and License 6 votes vote down vote up
/** Initialize the parser. */
private void initParser() {
  catalogResolver = new CatalogResolver(catalogManager);
  SAXParserFactory spf = catalogManager.useServicesMechanism() ?
                  SAXParserFactory.newInstance() : new SAXParserFactoryImpl();
  spf.setNamespaceAware(namespaceAware);
  spf.setValidating(validating);

  try {
    saxParser = spf.newSAXParser();
    parser = saxParser.getParser();
    documentHandler = null;
    dtdHandler = null;
  } catch (Exception ex) {
    ex.printStackTrace();
  }
}
 
Example 22
Project: alfresco-xml-factory   File: FactoryHelper.java   Source Code and License 6 votes vote down vote up
void configureFactory(SAXParserFactory factory, List<String> featuresToEnable,
                             List<String> featuresToDisable, List<String> whiteListCallers)
{
    debugStack("SAXParserFactory newInstance", 3, STACK_DEPTH);
    if (!isCallInWhiteList(whiteListCallers))
    {
        if (featuresToEnable != null)
        {
            for (String featureToEnable : featuresToEnable)
            {
                setFeature(factory, featureToEnable, true);
            }
        }
        if (featuresToDisable != null)
        {
            for (String featureToDisable : featuresToDisable)
            {
                setFeature(factory, featureToDisable, false);
            }
        }
    }
}
 
Example 23
Project: lazycat   File: Digester.java   Source Code and License 6 votes vote down vote up
/**
 * Return the SAXParserFactory we will use, creating one if necessary.
 * 
 * @throws ParserConfigurationException
 * @throws SAXNotSupportedException
 * @throws SAXNotRecognizedException
 */
public SAXParserFactory getFactory()
		throws SAXNotRecognizedException, SAXNotSupportedException, ParserConfigurationException {

	if (factory == null) {
		factory = SAXParserFactory.newInstance();

		factory.setNamespaceAware(namespaceAware);
		// Preserve xmlns attributes
		if (namespaceAware) {
			factory.setFeature("http://xml.org/sax/features/namespace-prefixes", true);
		}

		factory.setValidating(validating);
		if (validating) {
			// Enable DTD validation
			factory.setFeature("http://xml.org/sax/features/validation", true);
			// Enable schema validation
			factory.setFeature("http://apache.org/xml/features/validation/schema", true);
		}
	}
	return (factory);

}
 
Example 24
Project: openjdk-jdk10   File: ResolverTest.java   Source Code and License 6 votes vote down vote up
/**
 * Unit test for entityResolver setter.
 *
 * @throws Exception If any errors occur.
 */
public void testResolver() throws Exception {
    String outputFile = USER_DIR + "EntityResolver.out";
    String goldFile = GOLDEN_DIR + "EntityResolverGF.out";
    String xmlFile = XML_DIR + "publish.xml";

    Files.copy(Paths.get(XML_DIR + "publishers.dtd"),
            Paths.get(USER_DIR + "publishers.dtd"), REPLACE_EXISTING);
    Files.copy(Paths.get(XML_DIR + "familytree.dtd"),
            Paths.get(USER_DIR + "familytree.dtd"), REPLACE_EXISTING);

    try(FileInputStream instream = new FileInputStream(xmlFile);
            MyEntityResolver eResolver = new MyEntityResolver(outputFile)) {
        SAXParser saxParser = SAXParserFactory.newInstance().newSAXParser();
        XMLReader xmlReader = saxParser.getXMLReader();
        xmlReader.setEntityResolver(eResolver);
        InputSource is = new InputSource(instream);
        xmlReader.parse(is);
    }
    assertTrue(compareWithGold(goldFile, outputFile));
}
 
Example 25
Project: openjdk-jdk10   File: Bug4848653.java   Source Code and License 6 votes vote down vote up
@Test
public void test() throws IOException, SAXException, ParserConfigurationException {
    SAXParserFactory factory = SAXParserFactory.newInstance();
    factory.setValidating(false);
    SAXParser parser = factory.newSAXParser();
    parser.setProperty("http://java.sun.com/xml/jaxp/properties/schemaLanguage", XMLConstants.W3C_XML_SCHEMA_NS_URI);

    String filename = XML_DIR + "Bug4848653.xml";
    InputSource is = new InputSource(filenameToURL(filename));
    XMLReader xmlReader = parser.getXMLReader();
    xmlReader.setErrorHandler(new MyErrorHandler());
    xmlReader.parse(is);
}
 
Example 26
Project: oxygen-dita-translation-package-builder   File: AttributesCollectorUsingSaxTest.java   Source Code and License 6 votes vote down vote up
/**
 * <p><b>Description:</b> Verify the attribute collector over DITA map.
 * Collect referred files non-recursion.</p>
 * <p><b>Bug ID:</b> #9</p>
 *
 * @author adrian_sorop
 *
 * @throws Exception
 */
public void testSaxParser() throws Exception {

  File ditaFile = new File(rootDir,"rootMap.ditamap");
  assertTrue("UNABLE TO LOAD FILE", ditaFile.exists());
  URL url = URLUtil.correct(ditaFile);
  
  SAXParserFactory factory = SAXParserFactory.newInstance();
  // Ignore the DTD declaration
  factory.setValidating(false);
  factory.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false);
  factory.setFeature("http://xml.org/sax/features/validation", false);
  
  SAXParser parser = factory.newSAXParser();
  SaxContentHandler handler= new SaxContentHandler(url);
  parser.parse(ditaFile, handler);
  List<ReferencedResource> referredFiles = new ArrayList<ReferencedResource>();
  referredFiles.addAll(handler.getDitaMapHrefs());
  
  assertEquals("Two files should have been referred.", 2, referredFiles.size());
  assertTrue("Referred topic in dita maps should be topic2.dita", 
      referredFiles.toString().contains("issue-9/topics/topic2.dita"));
  assertTrue("Referred topic in dita maps should be topic1.dita", 
      referredFiles.toString().contains("issue-9/topics/topic1.dita"));
}
 
Example 27
Project: javaps-geotools-backend   File: GML2BasicParser.java   Source Code and License 6 votes vote down vote up
private QName determineFeatureTypeSchema(File file) {
    try {
        GML2Handler handler = new GML2Handler();
        SAXParserFactory factory = SAXParserFactory.newInstance();
        factory.setNamespaceAware(true);
        factory.newSAXParser().parse(new FileInputStream(file),
                (DefaultHandler) handler);
        String schemaUrl = handler.getSchemaUrl();
        String namespaceURI = handler.getNameSpaceURI();
        return new QName(namespaceURI, schemaUrl);

    } catch (Exception e) {
        LOGGER.error(
                "Exception while trying to determining GML2 FeatureType schema.",
                e);
        throw new IllegalArgumentException(e);
    }
}
 
Example 28
Project: openjdk-jdk10   File: Bug6594813.java   Source Code and License 6 votes vote down vote up
/**
 * Test an identity transform of an XML document with NS decls using a
 * non-ns-aware parser. Output result to a StreamSource. Set ns-awareness to
 * FALSE and prefixes to FALSE.
 */
@Test
public void testXMLNoNsAwareStreamResult1() {
    try {
        // Create SAX parser *without* enabling ns
        SAXParserFactory spf = SAXParserFactory.newInstance();
        spf.setNamespaceAware(false); // Same as default
        spf.setFeature("http://xml.org/sax/features/namespace-prefixes", false);
        SAXParser sp = spf.newSAXParser();

        // Make sure that the output is well formed
        String xml = runTransform(sp);
        checkWellFormedness(xml);
    } catch (Throwable ex) {
        Assert.fail(ex.toString());
    }
}
 
Example 29
Project: openjdk-jdk10   File: Issue682Test.java   Source Code and License 6 votes vote down vote up
@Test
public void test() {
    try {
        Schema schema = SchemaFactory.newInstance("http://www.w3.org/2001/XMLSchema").newSchema(new StreamSource(testFile));
        SAXParserFactory saxParserFactory = SAXParserFactory.newInstance();
        saxParserFactory.setNamespaceAware(true);
        saxParserFactory.setSchema(schema);
        // saxParserFactory.setFeature("http://java.sun.com/xml/schema/features/report-ignored-element-content-whitespace",
        // true);
        SAXParser saxParser = saxParserFactory.newSAXParser();
        XMLReader xmlReader = saxParser.getXMLReader();
        xmlReader.setContentHandler(new DefaultHandler());
        // InputStream input =
        // ClassLoader.getSystemClassLoader().getResourceAsStream("test/test.xml");
        InputStream input = getClass().getResourceAsStream("Issue682.xml");
        System.out.println("Parse InputStream:");
        xmlReader.parse(new InputSource(input));
    } catch (Exception ex) {
        ex.printStackTrace();
        Assert.fail(ex.toString());
    }

}
 
Example 30
Project: powertext   File: ThemeNULL.java   Source Code and License 6 votes vote down vote up
public static void load(ThemeNULL theme, InputStream in) throws IOException {
	SAXParserFactory spf = SAXParserFactory.newInstance();
	spf.setValidating(true);
	try {
		SAXParser parser = spf.newSAXParser();
		XMLReader reader = parser.getXMLReader();
		XmlHandler handler = new XmlHandler();
		handler.theme = theme;
		reader.setEntityResolver(handler);
		reader.setContentHandler(handler);
		reader.setDTDHandler(handler);
		reader.setErrorHandler(handler);
		InputSource is = new InputSource(in);
		is.setEncoding("UTF-8");
		reader.parse(is);
	} catch (/*SAX|ParserConfiguration*/Exception se) {
		se.printStackTrace();
		throw new IOException(se.toString());
	}
}
 
Example 31
Project: openjdk-jdk10   File: TypeInfoProviderTest.java   Source Code and License 6 votes vote down vote up
@Test
public void test() throws SAXException, ParserConfigurationException, IOException {

    SchemaFactory sf = SchemaFactory.newInstance(W3C_XML_SCHEMA_NS_URI);
    Schema schema = sf.newSchema(new File(XML_DIR + "shiporder11.xsd"));
    validatorHandler = schema.newValidatorHandler();
    MyDefaultHandler myDefaultHandler = new MyDefaultHandler();
    validatorHandler.setContentHandler(myDefaultHandler);

    InputSource is = new InputSource(filenameToURL(XML_DIR + "shiporder11.xml"));

    SAXParserFactory parserFactory = SAXParserFactory.newInstance();
    parserFactory.setNamespaceAware(true);
    XMLReader xmlReader = parserFactory.newSAXParser().getXMLReader();
    xmlReader.setContentHandler(validatorHandler);
    xmlReader.parse(is);

}
 
Example 32
Project: openjdk-jdk10   File: AttributesTest.java   Source Code and License 6 votes vote down vote up
/**
 * Unit test for Attributes interface. Prints all attributes into output
 * file. Check it with golden file.
 *
 * @throws Exception If any errors occur.
 */
@Test
public void testcase01() throws Exception {
    String outputFile = USER_DIR + "Attributes.out";
    String goldFile = GOLDEN_DIR + "AttributesGF.out";
    String xmlFile = XML_DIR + "family.xml";

    SAXParserFactory spf = SAXParserFactory.newInstance();
    spf.setNamespaceAware(true);
    spf.setFeature("http://xml.org/sax/features/namespace-prefixes",
                                true);
    spf.setValidating(true);
    SAXParser saxParser = spf.newSAXParser();
    MyAttrCHandler myAttrCHandler = new MyAttrCHandler(outputFile);
    saxParser.parse(new File(xmlFile), myAttrCHandler);
    myAttrCHandler.flushAndClose();
    assertTrue(compareWithGold(goldFile, outputFile));
}
 
Example 33
Project: openjdk-jdk10   File: Parser.java   Source Code and License 6 votes vote down vote up
private XMLReader createReader() throws SAXException {
    try {
        SAXParserFactory pfactory = SAXParserFactory.newInstance();
        pfactory.setValidating(true);
        pfactory.setNamespaceAware(true);

        // Enable schema validation
        SchemaFactory sfactory = SchemaFactory.newInstance("http://www.w3.org/2001/XMLSchema");
        InputStream stream = Parser.class.getResourceAsStream("graphdocument.xsd");
        pfactory.setSchema(sfactory.newSchema(new Source[]{new StreamSource(stream)}));

        return pfactory.newSAXParser().getXMLReader();
    } catch (ParserConfigurationException ex) {
        throw new SAXException(ex);
    }
}
 
Example 34
Project: openjdk-jdk10   File: EHFatalTest.java   Source Code and License 6 votes vote down vote up
/**
 * Error Handler to capture all error events to output file. Verifies the
 * output file is same as golden file.
 *
 * @throws Exception If any errors occur.
 */
@Test
public void testEHFatal() throws Exception {
    String outputFile = USER_DIR + "EHFatal.out";
    String goldFile = GOLDEN_DIR + "EHFatalGF.out";
    String xmlFile = XML_DIR + "invalid.xml";

    try(MyErrorHandler eHandler = new MyErrorHandler(outputFile);
            FileInputStream instream = new FileInputStream(xmlFile)) {
        SAXParser saxParser = SAXParserFactory.newInstance().newSAXParser();
        XMLReader xmlReader = saxParser.getXMLReader();
        xmlReader.setErrorHandler(eHandler);
        InputSource is = new InputSource(instream);
        xmlReader.parse(is);
        fail("Parse should throw SAXException");
    } catch (SAXException expected) {
        // This is expected.
    }
    // Need close the output file before we compare it with golden file.
    assertTrue(compareWithGold(goldFile, outputFile));
}
 
Example 35
Project: openjdk-jdk10   File: Bug6509668.java   Source Code and License 5 votes vote down vote up
private XMLReader createXMLReader() throws ParserConfigurationException, SAXException {
    SAXParserFactory parserFactory = SAXParserFactory.newInstance();
    if (!parserFactory.isNamespaceAware()) {
        parserFactory.setNamespaceAware(true);
    }

    return parserFactory.newSAXParser().getXMLReader();
}
 
Example 36
Project: UIAutomatorAdapter   File: SaxActionParser.java   Source Code and License 5 votes vote down vote up
@Override
public List<App> parse(InputStream is) throws Exception {
    // get SAXParserFactory instance
    SAXParserFactory factory = SAXParserFactory.newInstance();
    // get SAXParser instance from SAXParserFactory instance
    SAXParser parser = factory.newSAXParser();
    // new appHandler
    appHandler handler = new appHandler();
    // parse is with handler
    parser.parse(is, handler);
    return handler.getApps();
}
 
Example 37
Project: DELDroid   File: SAXHandlerAndroidManifest.java   Source Code and License 5 votes vote down vote up
public static void main(String[] args) {
//        System.out.println("SAXHandlerAndroidManifest ...");
        try {
            SAXParserFactory saxParserFactory = SAXParserFactory.newInstance();
            SAXParser saxParser = saxParserFactory.newSAXParser();
            File xmlFile = new File(ANDROID_FRAMEWORK_MANIFEST_PATH);
            SimpleSAXHandler handler = new SAXHandlerAndroidManifest();
            InputStream is = new FileInputStream(xmlFile);
            saxParser.parse(is, handler);
            System.out.println(componentsMap.size());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
 
Example 38
Project: incubator-netbeans   File: CheckHelpSets.java   Source Code and License 5 votes vote down vote up
@Override
public void processMapRef(HelpSet hs, @SuppressWarnings("rawtypes") Hashtable attrs) {
    try {
        URL map = new URL(hs.getHelpSetURL(), (String)attrs.get("location"));
        SAXParserFactory factory = SAXParserFactory.newInstance();
        factory.setValidating(false);
        factory.setNamespaceAware(false);
        SAXParser parser = factory.newSAXParser();
        parser.parse(new InputSource(map.toExternalForm()), new Handler(map.getFile()));
    } catch (Exception e) {
        e.printStackTrace();
    }
}
 
Example 39
Project: openjdk-jdk10   File: SAXParserTest03.java   Source Code and License 5 votes vote down vote up
/**
 * invalidns.xml holds an invalid document with XML namespaces in it. This
 * method tests the validating parser with namespace processing on. It
 * should throw validation error.
 *
 * @param spf a Parser factory.
 * @param handler an error handler for capturing events.
 * @throws Exception If any errors occur.
 */
@Test(dataProvider = "input-provider")
public void testParseValidate03(SAXParserFactory spf, MyErrorHandler handler)
        throws Exception {
    try {
        spf.setNamespaceAware(true);
        SAXParser saxparser = spf.newSAXParser();
        saxparser.parse(new File(XML_DIR, "invalidns.xml"), handler);
        fail("Expecting SAXException here");
    } catch (SAXException e) {
        assertTrue(handler.isErrorOccured());
    }
}
 
Example 40
Project: oma-riista-android   File: XmlSaxTask.java   Source Code and License 5 votes vote down vote up
@Override
protected final void onAsyncStream(InputStream stream) throws Exception 
{
    TaskXMLHandler handler = new TaskXMLHandler();

    SAXParserFactory factory = SAXParserFactory.newInstance();
    SAXParser parser = factory.newSAXParser();
    InputSource is = new InputSource(stream);
    if (mEncoding != null) {
        is.setEncoding(mEncoding);
    }
    parser.parse(is, handler);
}