Java Code Examples for org.xml.sax.XMLReader#setContentHandler()

The following examples show how to use org.xml.sax.XMLReader#setContentHandler() . 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: HftpFileSystem.java    From RDFS with Apache License 2.0 6 votes vote down vote up
private FileChecksum getFileChecksum(String f) throws IOException {
  final HttpURLConnection connection = openConnection(
      "/fileChecksum" + f, "ugi=" + ugi);
  try {
    final XMLReader xr = XMLReaderFactory.createXMLReader();
    xr.setContentHandler(this);

    connection.setRequestMethod("GET");
    connection.connect();

    xr.parse(new InputSource(connection.getInputStream()));
  } catch(SAXException e) {
    final Exception embedded = e.getException();
    if (embedded != null && embedded instanceof IOException) {
      throw (IOException)embedded;
    }
    throw new IOException("invalid xml directory content", e);
  } finally {
    connection.disconnect();
  }
  return filechecksum;
}
 
Example 2
Source File: SAXParser.java    From jdk1.8-source-analysis with Apache License 2.0 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
Source File: ProductImportParser.java    From development with Apache License 2.0 6 votes vote down vote up
/**
 * Parse the given XML string an create/update the corresponding entities
 * 
 * @param xml
 *            the XML string
 * @return the parse return code
 * @throws Exception
 */
public int parse(byte[] xml) throws Exception {
    SAXParserFactory spf = SAXParserFactory.newInstance();
    spf.setNamespaceAware(true);
    SchemaFactory sf = SchemaFactory
            .newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
    try (InputStream inputStream = ResourceLoader.getResourceAsStream(
            getClass(), getSchemaName())) {
        Schema schema = sf.newSchema(new StreamSource(inputStream));
        spf.setSchema(schema);
    }
    SAXParser saxParser = spf.newSAXParser();
    XMLReader reader = saxParser.getXMLReader();
    reader.setFeature(Constants.XERCES_FEATURE_PREFIX
            + Constants.DISALLOW_DOCTYPE_DECL_FEATURE, true);
    reader.setContentHandler(this);
    reader.parse(new InputSource(new ByteArrayInputStream(xml)));
    return 0;
}
 
Example 4
Source File: ColorSettingsXML.java    From tracecompass with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * Loads color settings from file and returns it in an array.
 *
 * @param pathName
 *            A file name with path
 *
 * @return the color settings array loaded from file
 */
public static ColorSetting[] load(String pathName) {
    if (!new File(pathName).canRead()) {
        return new ColorSetting[0];
    }
    SAXParserFactory parserFactory = SAXParserFactory.newInstance();
    parserFactory.setNamespaceAware(true);

    ColorSettingsContentHandler handler = new ColorSettingsContentHandler();
    try {
        XMLReader saxReader = parserFactory.newSAXParser().getXMLReader();
        saxReader.setContentHandler(handler);
        saxReader.parse(pathName);
        return handler.colorSettings.toArray(new ColorSetting[0]);
    } catch (ParserConfigurationException | SAXException | IOException e) {
        Activator.getDefault().logError("Error loading color xml file: " + pathName, e); //$NON-NLS-1$
    }
    // In case of error, dispose the partial list of color settings
    for (ColorSetting colorSetting : handler.colorSettings) {
        colorSetting.dispose();
    }
    return new ColorSetting[0];
}
 
Example 5
Source File: SAXParser.java    From openjdk-jdk9 with GNU General Public License v2.0 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 6
Source File: SAXTFactoryTest.java    From openjdk-jdk9 with GNU General Public License v2.0 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
Source File: XML_SAX_StAX_FI.java    From openjdk-8 with GNU General Public License v2.0 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 8
Source File: HftpFileSystem.java    From hadoop with Apache License 2.0 6 votes vote down vote up
private void fetchList(String path, boolean recur) throws IOException {
  try {
    XMLReader xr = XMLReaderFactory.createXMLReader();
    xr.setContentHandler(this);
    HttpURLConnection connection = openConnection(
        "/listPaths" + ServletUtil.encodePath(path),
        "ugi=" + getEncodedUgiParameter() + (recur ? "&recursive=yes" : ""));
    InputStream resp = connection.getInputStream();
    xr.parse(new InputSource(resp));
  } catch(SAXException e) {
    final Exception embedded = e.getException();
    if (embedded != null && embedded instanceof IOException) {
      throw (IOException)embedded;
    }
    throw new IOException("invalid xml directory content", e);
  }
}
 
Example 9
Source File: DOMBuilder.java    From exificient with MIT License 5 votes vote down vote up
public Document parse(InputStream is, boolean exiBodyOnly)
		throws EXIException {
	try {
		// create SAX to DOM Handlers
		SaxToDomHandler s2dHandler = new SaxToDomHandler(domImplementation,
				false);

		XMLReader reader = new SAXFactory(factory).createEXIReader();
		// EXI Features
		reader.setFeature(Constants.W3C_EXI_FEATURE_BODY_ONLY, exiBodyOnly);
		// SAX Features
		reader.setFeature("http://xml.org/sax/features/namespace-prefixes",
				true);
		reader.setProperty("http://xml.org/sax/properties/lexical-handler",
				s2dHandler);
		reader.setProperty(
				"http://xml.org/sax/properties/declaration-handler",
				s2dHandler);
		reader.setContentHandler(s2dHandler);
		reader.setDTDHandler(s2dHandler);

		reader.parse(new InputSource(is));

		// return document;
		return s2dHandler.getDocument();
	} catch (Exception e) {
		throw new EXIException(e);
	}
}
 
Example 10
Source File: SAXDecoder.java    From feign with Apache License 2.0 5 votes vote down vote up
@Override
public Object decode(Response response, Type type) throws IOException, DecodeException {
  if (response.body() == null)
    return null;
  ContentHandlerWithResult.Factory<?> handlerFactory = handlerFactories.get(type);
  checkState(handlerFactory != null, "type %s not in configured handlers %s", type,
      handlerFactories.keySet());
  ContentHandlerWithResult<?> handler = handlerFactory.create();
  try {
    XMLReader xmlReader = XMLReaderFactory.createXMLReader();
    xmlReader.setFeature("http://xml.org/sax/features/namespaces", false);
    xmlReader.setFeature("http://xml.org/sax/features/validation", false);
    /* Explicitly control sax configuration to prevent XXE attacks */
    xmlReader.setFeature("http://xml.org/sax/features/external-general-entities", false);
    xmlReader.setFeature("http://xml.org/sax/features/external-parameter-entities", false);
    xmlReader.setFeature("http://apache.org/xml/features/disallow-doctype-decl", false);
    xmlReader.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false);
    xmlReader.setContentHandler(handler);
    InputStream inputStream = response.body().asInputStream();
    try {
      xmlReader.parse(new InputSource(inputStream));
    } finally {
      ensureClosed(inputStream);
    }
    return handler.result();
  } catch (SAXException e) {
    throw new DecodeException(response.status(), e.getMessage(), response.request(), e);
  }
}
 
Example 11
Source File: XML_SAX_FI.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
public void parse(InputStream xml, OutputStream finf, String workingDirectory) throws Exception {
    SAXParser saxParser = getParser();
    SAXDocumentSerializer documentSerializer = getSerializer(finf);

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

    if (workingDirectory != null) {
        reader.setEntityResolver(createRelativePathResolver(workingDirectory));
    }
    reader.parse(new InputSource(xml));
}
 
Example 12
Source File: HelpFunctions.java    From uPods-android with Apache License 2.0 5 votes vote down vote up
public static ArrayList<Episode> parseEpisodes(String url) throws Exception {
    Request episodesRequest = new Request.Builder().url(url).build();
    String response = BackendManager.getInstance().sendSimpleSynchronicRequest(episodesRequest);
    SAXParserFactory spf = SAXParserFactory.newInstance();
    SAXParser sp = spf.newSAXParser();
    XMLReader xr = sp.getXMLReader();
    EpisodesXMLHandler episodesXMLHandler = new EpisodesXMLHandler();
    xr.setContentHandler(episodesXMLHandler);
    InputSource inputSource = new InputSource(new StringReader(response));
    xr.parse(inputSource);
    return episodesXMLHandler.getParsedEpisods();
}
 
Example 13
Source File: Processor.java    From annotation-tools with MIT License 5 votes vote down vote up
private void processEntry(
    final ZipInputStream zis,
    ZipEntry ze,
    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),
                    false);

        } 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);
    }
}
 
Example 14
Source File: TMRAPTestCaseContentHandler.java    From ontopia with Apache License 2.0 5 votes vote down vote up
public void register(XMLReader parser) {
  parser.setContentHandler(this);
  ErrorHandler _ehandler = parser.getErrorHandler();
  if (_ehandler == null || (_ehandler instanceof DefaultHandler))
    parser.setErrorHandler(getDefaultErrorHandler());
  ehandler = parser.getErrorHandler();
}
 
Example 15
Source File: TestCaseContentHandler.java    From ontopia with Apache License 2.0 5 votes vote down vote up
public void register(XMLReader parser) {
  parser.setContentHandler(this);
  ErrorHandler _ehandler = parser.getErrorHandler();
  if (_ehandler == null || (_ehandler instanceof DefaultHandler))
    parser.setErrorHandler(getDefaultErrorHandler());
  ehandler = parser.getErrorHandler();
}
 
Example 16
Source File: PositionalXmlScanner.java    From google-cloud-eclipse with Apache License 2.0 5 votes vote down vote up
static Document parse(byte[] bytes) throws SAXException, IOException {
  if (bytes.length == 0) { //file is empty
    return null;
  }
  ByteArrayInputStream bais = new ByteArrayInputStream(bytes);
  InputSource is = new InputSource(bais);
  XMLReader reader = XMLReaderFactory.createXMLReader();     
  PositionalXmlHandler handler = new PositionalXmlHandler();
  reader.setContentHandler(handler);
  reader.setErrorHandler(handler);
  reader.parse(is);
  return handler.getDocument();
}
 
Example 17
Source File: GeoTiffReaderExample.java    From GeoTriples with Apache License 2.0 5 votes vote down vote up
public void read() throws IOException, SAXException {
	XMLReader xr;
	xr = new org.apache.xerces.parsers.SAXParser();
	KMLHandler kmlHandler = new KMLHandler();
	xr.setContentHandler(kmlHandler);
	xr.setErrorHandler(kmlHandler);

	Reader r = new BufferedReader(new FileReader(filename));
	LineNumberReader myReader = new LineNumberReader(r);
	xr.parse(new InputSource(myReader));

	// List geoms = kmlHandler.getGeometries();
}
 
Example 18
Source File: ConvertExcelToCSVProcessor.java    From nifi with Apache License 2.0 4 votes vote down vote up
/**
 * Handles an individual Excel sheet from the entire Excel document. Each sheet will result in an individual flowfile.
 *
 * @param session
 *  The NiFi ProcessSession instance for the current invocation.
 */
private void handleExcelSheet(ProcessSession session, FlowFile originalParentFF, final InputStream sheetInputStream, ExcelSheetReadConfig readConfig,
                              CSVFormat csvFormat) throws IOException {

    FlowFile ff = session.create(originalParentFF);
    try {
        final DataFormatter formatter = new DataFormatter();
        final InputSource sheetSource = new InputSource(sheetInputStream);

        final SheetToCSV sheetHandler = new SheetToCSV(readConfig, csvFormat);

        final XMLReader parser = SAXHelper.newXMLReader();

        //If Value Formatting is set to false then don't pass in the styles table.
        // This will cause the XSSF Handler to return the raw value instead of the formatted one.
        final StylesTable sst = readConfig.getFormatValues()?readConfig.getStyles():null;

        final XSSFSheetXMLHandler handler = new XSSFSheetXMLHandler(
                sst, null, readConfig.getSharedStringsTable(), sheetHandler, formatter, false);

        parser.setContentHandler(handler);

        ff = session.write(ff, new OutputStreamCallback() {
            @Override
            public void process(OutputStream out) throws IOException {
                PrintStream outPrint = new PrintStream(out);
                sheetHandler.setOutput(outPrint);

                try {
                    parser.parse(sheetSource);

                    sheetInputStream.close();

                    sheetHandler.close();
                    outPrint.close();
                } catch (SAXException se) {
                    getLogger().error("Error occurred while processing Excel sheet {}", new Object[]{readConfig.getSheetName()}, se);
                }
            }
        });

        ff = session.putAttribute(ff, SHEET_NAME, readConfig.getSheetName());
        ff = session.putAttribute(ff, ROW_NUM, new Long(sheetHandler.getRowCount()).toString());

        if (StringUtils.isNotEmpty(originalParentFF.getAttribute(CoreAttributes.FILENAME.key()))) {
            ff = session.putAttribute(ff, SOURCE_FILE_NAME, originalParentFF.getAttribute(CoreAttributes.FILENAME.key()));
        } else {
            ff = session.putAttribute(ff, SOURCE_FILE_NAME, UNKNOWN_SHEET_NAME);
        }

        //Update the CoreAttributes.FILENAME to have the .csv extension now. Also update MIME.TYPE
        ff = session.putAttribute(ff, CoreAttributes.FILENAME.key(), updateFilenameToCSVExtension(ff.getAttribute(CoreAttributes.UUID.key()),
                ff.getAttribute(CoreAttributes.FILENAME.key()), readConfig.getSheetName()));
        ff = session.putAttribute(ff, CoreAttributes.MIME_TYPE.key(), CSV_MIME_TYPE);

        session.transfer(ff, SUCCESS);

    } catch (SAXException | ParserConfigurationException saxE) {
        getLogger().error("Failed to create instance of Parser.", saxE);
        ff = session.putAttribute(ff,
                ConvertExcelToCSVProcessor.class.getName() + ".error", saxE.getMessage());
        session.transfer(ff, FAILURE);
    } finally {
        sheetInputStream.close();
    }
}
 
Example 19
Source File: XmiCasDeserializerTest.java    From uima-uimaj with Apache License 2.0 4 votes vote down vote up
private void doTestMultiThreadedSerialize(File typeSystemDescriptor) throws Exception {
  // deserialize a complex CAS from XCAS
  CAS cas = CasCreationUtils.createCas(typeSystem, new TypePriorities_impl(), indexes);

  InputStream serCasStream = new FileInputStream(JUnitExtension.getFile("ExampleCas/cas.xml"));
  XCASDeserializer deser = new XCASDeserializer(cas.getTypeSystem());
  ContentHandler deserHandler = deser.getXCASHandler(cas);
  SAXParserFactory fact = SAXParserFactory.newInstance();
  SAXParser parser = fact.newSAXParser();
  XMLReader xmlReader = parser.getXMLReader();
  xmlReader.setContentHandler(deserHandler);
  xmlReader.parse(new InputSource(serCasStream));
  serCasStream.close();

  // make n copies of the cas, so they all share
  // the same type system
  
  final CAS [] cases = new CAS[MAX_THREADS];
  
  for (int i = 0; i < MAX_THREADS; i++) {
  	cases[i] = CasCreationUtils.createCas(cas.getTypeSystem(), new TypePriorities_impl(),	indexes, null);
  	CasCopier.copyCas(cas, cases[i], true);
  }
  
  // start n threads, serializing as XMI
  MultiThreadUtils.ThreadM [] threads = new MultiThreadUtils.ThreadM[MAX_THREADS];
  for (int i = 0; i < MAX_THREADS; i++) {
    threads[i] = new MultiThreadUtils.ThreadM(new DoSerialize(cases[i]));
    threads[i].start();
  }
  MultiThreadUtils.waitForAllReady(threads);
  
  for (int i = 0; i < threadsToUse.length; i++) {
    MultiThreadUtils.ThreadM[] sliceOfThreads = new MultiThreadUtils.ThreadM[threadsToUse[i]];
    System.arraycopy(threads, 0, sliceOfThreads, 0, threadsToUse[i]);
    
  	long startTime = System.currentTimeMillis();
  	
  	MultiThreadUtils.kickOffThreads(sliceOfThreads);
  	
  	MultiThreadUtils.waitForAllReady(sliceOfThreads);
  	
  	System.out.println("\nNumber of threads serializing: " + threadsToUse[i] + 
  			               "  Normalized millisecs (should be close to the same): " + (System.currentTimeMillis() - startTime) / threadsToUse[i]);
  }
  
  MultiThreadUtils.terminateThreads(threads);
}
 
Example 20
Source File: XMLResponseProcessor.java    From smarthome with Eclipse Public License 2.0 4 votes vote down vote up
public void handleMessage(String msg) throws SAXException, IOException {
    XMLReader reader = XMLReaderFactory.createXMLReader();
    reader.setContentHandler(new XMLResponseHandler(handler, stateSwitchingMap));
    reader.parse(new InputSource(new StringReader(msg)));
}