Example usage for org.xml.sax XMLReader setContentHandler

List of usage examples for org.xml.sax XMLReader setContentHandler

Introduction

In this page you can find the example usage for org.xml.sax XMLReader setContentHandler.

Prototype

public void setContentHandler(ContentHandler handler);

Source Link

Document

Allow an application to register a content event handler.

Usage

From source file:com.edgenius.wiki.render.impl.FilterPipeImpl.java

public void load() throws FilterInitializeException {
    ClassLoader classLoader = Filter.class.getClassLoader();
    //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    //               Load filter configure XML file
    try {/*from ww  w .  j a v a2 s . c  o m*/
        SAXParser parser = SAXParserFactory.newInstance().newSAXParser();
        XMLReader reader = parser.getXMLReader();

        reader.setContentHandler(this.new FilterMetaParaser());
        reader.parse(new InputSource(classLoader.getResourceAsStream(filterResource)));
    } catch (Exception e) {
        log.error("Unable load filter configuare file " + filterResource, e);
        throw new FilterInitializeException(e);
    }

    //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    //               Load filter Pattern resource bundle file
    Properties patternResource = new Properties();
    try {
        patternResource.load(classLoader.getResourceAsStream(filterResourcePattern));
    } catch (Exception e) {
        log.error("Unable load PatternFilter pattern file " + filterResourcePattern, e);
        throw new FilterInitializeException(e);
    }

    Map<Integer, Filter> sortSet = new TreeMap<Integer, Filter>(new CompareToComparator());
    Map<Integer, RegionContentFilter> regionSortSet = new TreeMap<Integer, RegionContentFilter>(
            new CompareToComparator());
    for (FilterMetadata filterMeta : filterMetaList) {
        try {
            Object obj = classLoader.loadClass(filterMeta.getClassName().trim()).newInstance();
            if (obj instanceof Filter) {
                if (obj instanceof MacroFilter)
                    ((MacroFilter) obj).setMacroMgr(macroManager);

                //initial filter, if it is patternFilter, then do further initial
                if (obj instanceof PatternFilter) {
                    //!!! this markupPring must happen before setRegex() which may need getMarkupPrint() to build regex
                    String markupPrintVal = patternResource.getProperty(
                            ((PatternFilter) obj).getPatternKey() + PatternFilter.SUFFIX_MARKUP_PRINT);
                    if (!StringUtils.isBlank(markupPrintVal)) {
                        ((PatternFilter) obj).setMarkupPrint(markupPrintVal);
                    }
                    String matchVal = patternResource
                            .getProperty(((PatternFilter) obj).getPatternKey() + PatternFilter.SUFFIX_MATCH);
                    if (!StringUtils.isBlank(matchVal)) {
                        //special for link replacer
                        if (obj instanceof LinkFilter) {
                            linkReplacerFilter.setRegex(matchVal);
                        }
                        ((PatternFilter) obj).setRegex(matchVal);
                    }
                    String printVal = patternResource
                            .getProperty(((PatternFilter) obj).getPatternKey() + PatternFilter.SUFFIX_PRINT);
                    if (!StringUtils.isBlank(printVal)) {
                        ((PatternFilter) obj).setReplacement(printVal);
                    }
                    String htmlIDVal = patternResource.getProperty(
                            ((PatternFilter) obj).getPatternKey() + PatternFilter.SUFFIX_HTML_IDENTIFIER);
                    if (!StringUtils.isBlank(htmlIDVal)) {
                        ((PatternFilter) obj).setHTMLIdentifier(htmlIDVal);
                    }

                }
                filterNameMap.put(obj.getClass().getName(), (Filter) obj);

                ((Filter) obj).init();

                //new line filter always be last, but need special handle. see MarkupRenderEngineImpl.render()
                sortSet.put(filterMeta.getOrder(), (Filter) obj);
                if (obj instanceof RegionContentFilter) {
                    regionSortSet.put(filterMeta.getOrder(), (RegionContentFilter) obj);
                }

                log.info("Filter loaded into FilterPipe:" + obj.getClass().getName());
            } else {
                log.warn("Class " + obj.getClass().getName() + " does not implement Filter interface. "
                        + "It cannot be loaded into FilterPipe.");
            }
        } catch (InstantiationException e) {
            log.error("Filter failed on Instantiation " + filterMeta, e);
        } catch (IllegalAccessException e) {
            log.error("Filter failed on IllegalAccessException " + filterMeta, e);
        } catch (ClassNotFoundException e) {
            log.error("Filter ClassNotFoundException failed " + filterMeta, e);
        }
    }

    linkReplacerFilter.init();

    filterList.clear();
    filterList.addAll(sortSet.values());
    regionFilterList.clear();
    regionFilterList.addAll(regionSortSet.values());
}

From source file:com.ewhoxford.android.bloodpressure.ghealth.gdata.GDataHealthClient.java

@Override
public List<Result> retrieveResults()
        throws AuthenticationException, InvalidProfileException, ServiceException {

    if (authToken == null) {
        throw new IllegalStateException("authToken must not be null");
    }//from   www  .  ja  v a  2s . c  o  m

    if (profileId == null) {
        throw new IllegalStateException("profileId must not be null.");
    }

    String url = service.getBaseURL() + "/profile/ui/" + profileId + "/-/labtest";
    InputStream istream = retreiveData(url);

    HealthGDataContentHandler ccrHandler = new HealthGDataContentHandler();
    try {
        SAXParserFactory spf = SAXParserFactory.newInstance();
        SAXParser sp = spf.newSAXParser();

        XMLReader xr = sp.getXMLReader();
        xr.setContentHandler(ccrHandler);
        xr.parse(new InputSource(istream));
    } catch (ParserConfigurationException e) {
        throw new ServiceException(e);
    } catch (SAXException e) {
        throw new ServiceException(e);
    } catch (IOException e) {
        throw new ServiceException(e);
    } finally {
        if (istream != null) {
            try {
                istream.close();
            } catch (IOException e) {
                throw new ServiceException(e);
            }
        }
    }

    return ccrHandler.getResults();
}

From source file:com.box.androidlib.BoxSynchronous.java

/**
 * Executes an Http request and triggers response parsing by the specified parser.
 * /*from w  w  w  .ja  v a2  s.c  o  m*/
 * @param parser
 *            A BoxResponseParser configured to consume the response and capture data that is of interest
 * @param uri
 *            The Uri of the request
 * @throws IOException
 *             Can be thrown if there is no connection, or if some other connection problem exists.
 */
protected static void saxRequest(final DefaultResponseParser parser, final Uri uri) throws IOException {
    Uri theUri = uri;
    List<BasicNameValuePair> customQueryParams = BoxConfig.getInstance().getCustomQueryParameters();
    if (customQueryParams != null && customQueryParams.size() > 0) {
        Uri.Builder builder = theUri.buildUpon();
        for (BasicNameValuePair param : customQueryParams) {
            builder.appendQueryParameter(param.getName(), param.getValue());
        }
        theUri = builder.build();
    }

    try {
        final XMLReader xmlReader = SAXParserFactory.newInstance().newSAXParser().getXMLReader();
        xmlReader.setContentHandler(parser);
        HttpURLConnection conn = (HttpURLConnection) (new URL(theUri.toString())).openConnection();
        conn.setRequestProperty("User-Agent", BoxConfig.getInstance().getUserAgent());
        conn.setRequestProperty("Accept-Language", BoxConfig.getInstance().getAcceptLanguage());
        conn.setConnectTimeout(BoxConfig.getInstance().getConnectionTimeOut());
        if (mLoggingEnabled) {
            DevUtils.logcat("URL: " + theUri.toString());
            //                Iterator<String> keys = conn.getRequestProperties().keySet().iterator();
            //                while (keys.hasNext()) {
            //                    String key = keys.next();
            //                    DevUtils.logcat("Request Header: " + key + " => " + conn.getRequestProperties().get(key));
            //                }
        }

        int responseCode = -1;
        try {
            conn.connect();
            responseCode = conn.getResponseCode();
            if (mLoggingEnabled)
                DevUtils.logcat("Response Code: " + responseCode);
            if (responseCode == HttpURLConnection.HTTP_OK) {
                InputStream inputStream = conn.getInputStream();
                xmlReader.parse(new InputSource(inputStream));
                inputStream.close();
            } else if (responseCode == -1) {
                parser.setStatus(ResponseListener.STATUS_UNKNOWN_HTTP_RESPONSE_CODE);
            }
        } catch (IOException e) {
            try {
                responseCode = conn.getResponseCode();
            } catch (NullPointerException ee) {
                // Honeycomb devices seem to throw a null pointer exception sometimes which traces to HttpURLConnectionImpl.
            }
            // Server returned a 503 Service Unavailable. Usually means a temporary unavailability.
            if (responseCode == HttpURLConnection.HTTP_UNAVAILABLE) {
                parser.setStatus(ResponseListener.STATUS_SERVICE_UNAVAILABLE);
            } else {
                throw e;
            }
        } finally {
            conn.disconnect();
        }
    } catch (final ParserConfigurationException e) {
        e.printStackTrace();
    } catch (final SAXException e) {
        e.printStackTrace();
    } catch (final FactoryConfigurationError e) {
        e.printStackTrace();
    }
}

From source file:net.ontopia.persistence.proxy.ObjectRelationalMapping.java

/**
 * INTERNAL: Read a mapping description from the specified file.
 *///  w  w w.ja  va2 s  .com
protected void loadMapping(InputSource isource) {

    // Read mapping file.
    ContentHandler handler = new MappingHandler(this);

    try {
        XMLReader parser = DefaultXMLReaderFactory.createXMLReader();
        parser.setContentHandler(handler);
        parser.setErrorHandler(new Slf4jSaxErrorHandler(log));
        parser.parse(isource);
    } catch (IOException e) {
        throw new OntopiaRuntimeException(e);
    } catch (SAXException e) {
        throw new OntopiaRuntimeException(e);
    }
}

From source file:com.zazuko.wikidata.municipalities.SparqlClient.java

List<Map<String, RDFTerm>> queryResultSet(final String query) throws IOException, URISyntaxException {
    CloseableHttpClient httpclient = HttpClients.createDefault();
    URIBuilder builder = new URIBuilder(endpoint);
    builder.addParameter("query", query);
    HttpGet httpGet = new HttpGet(builder.build());
    /*List<NameValuePair> nvps = new ArrayList<NameValuePair>();
    nvps.add(new BasicNameValuePair("query", query));
    httpGet.setEntity(new UrlEncodedFormEntity(nvps));*/
    CloseableHttpResponse response2 = httpclient.execute(httpGet);

    try {//from w w w  . j  a  va2 s  . co  m
        HttpEntity entity2 = response2.getEntity();
        InputStream in = entity2.getContent();
        if (debug) {
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            for (int ch = in.read(); ch != -1; ch = in.read()) {
                System.out.print((char) ch);
                baos.write(ch);
            }
            in = new ByteArrayInputStream(baos.toByteArray());
        }
        SAXParserFactory spf = SAXParserFactory.newInstance();
        spf.setNamespaceAware(true);
        SAXParser saxParser = spf.newSAXParser();
        XMLReader xmlReader = saxParser.getXMLReader();
        final SparqlsResultsHandler sparqlsResultsHandler = new SparqlsResultsHandler();
        xmlReader.setContentHandler(sparqlsResultsHandler);
        xmlReader.parse(new InputSource(in));
        /*
         for (int ch = in.read(); ch != -1; ch = in.read()) {
         System.out.print((char)ch);
         }
         */
        // do something useful with the response body
        // and ensure it is fully consumed
        EntityUtils.consume(entity2);
        return sparqlsResultsHandler.getResults();
    } catch (ParserConfigurationException ex) {
        throw new RuntimeException(ex);
    } catch (SAXException ex) {
        throw new RuntimeException(ex);
    } finally {
        response2.close();
    }

}

From source file:com.mirth.connect.model.converters.NCPDPSerializer.java

@Override
public String fromXML(String source) throws SerializerException {
    /*//from   w ww .  j a v a 2s .  c om
     * Need to determine the version by looking at the raw message.
     * The transaction header will contain the version ("51" for 5.1 and
     * "D0" for D.0)
     */
    String version = "D0";

    if (source.indexOf("D0") == -1) {
        version = "51";
    } else if (source.indexOf("51") == -1) {
        version = "D0";
    } else if (source.indexOf("51") < source.indexOf("D0")) {
        version = "51";
    }

    try {
        XMLReader reader = XMLReaderFactory.createXMLReader();
        NCPDPXMLHandler handler = new NCPDPXMLHandler(segmentDelimeter, groupDelimeter, fieldDelimeter,
                version);
        reader.setContentHandler(handler);

        if (useStrictValidation) {
            reader.setFeature("http://xml.org/sax/features/validation", true);
            reader.setFeature("http://apache.org/xml/features/validation/schema", true);
            reader.setFeature("http://apache.org/xml/features/validation/schema-full-checking", true);
            reader.setProperty("http://java.sun.com/xml/jaxp/properties/schemaLanguage",
                    "http://www.w3.org/2001/XMLSchema");
            reader.setProperty("http://apache.org/xml/properties/schema/external-noNamespaceSchemaLocation",
                    "ncpdp" + version + ".xsd");
            reader.setProperty("http://java.sun.com/xml/jaxp/properties/schemaSource",
                    "/ncpdp" + version + ".xsd");
        }

        /*
         * Parse, but first replace all spaces between brackets. This fixes
         * pretty-printed XML we might receive
         */
        reader.parse(new InputSource(new StringReader(source.replaceAll(">\\s+<", "><"))));
        return handler.getOutput().toString();
    } catch (Exception e) {
        throw new SerializerException("Error converting XML to NCPDP message.", e);
    }
}

From source file:com.webcohesion.ofx4j.client.impl.OFXHomeFIDataStore.java

private void initializeFIData() throws IOException, SAXException {
    URL url = new URL(getUrl());
    XMLReader xmlReader = new Parser();
    xmlReader.setFeature("http://xml.org/sax/features/namespaces", false);
    xmlReader.setFeature("http://xml.org/sax/features/validation", false);
    xmlReader.setContentHandler(new DirectoryContentHandler());
    xmlReader.parse(new InputSource(url.openStream()));
}

From source file:no.uis.service.studinfo.commons.StudinfoValidator.java

protected List<String> validate(String studieinfoXml, StudinfoType infoType, int year, FsSemester semester,
        String language) throws Exception {

    // save xml/*w  w  w  . j a v  a  2  s. c  om*/
    File outFile = new File("target/out", infoType.toString() + year + semester + language + ".xml");
    if (outFile.exists()) {
        outFile.delete();
    } else {
        outFile.getParentFile().mkdirs();
    }
    File outBackup = new File("target/out", infoType.toString() + year + semester + language + "_orig.xml");
    Writer backupWriter = new OutputStreamWriter(new FileOutputStream(outBackup), IOUtils.UTF8_CHARSET);
    backupWriter.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n");
    IOUtils.copy(new StringReader(studieinfoXml), backupWriter, IOBUFFER_SIZE);
    backupWriter.flush();
    backupWriter.close();

    TransformerFactory trFactory = TransformerFactory.newInstance();
    Source schemaSource = new StreamSource(getClass().getResourceAsStream("/fspreprocess.xsl"));
    Transformer stylesheet = trFactory.newTransformer(schemaSource);

    Source input = new StreamSource(new StringReader(studieinfoXml));

    Result result = new StreamResult(outFile);
    stylesheet.transform(input, result);

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

    SchemaFactory schemaFactory = SchemaFactory.newInstance("http://www.w3.org/2001/XMLSchema");
    Schema schema = schemaFactory
            .newSchema(new Source[] { new StreamSource(new File("src/main/xsd/studinfo.xsd")) });

    factory.setSchema(schema);

    SAXParser parser = factory.newSAXParser();

    XMLReader reader = parser.getXMLReader();
    ValidationErrorHandler errorHandler = new ValidationErrorHandler(infoType, year, semester, language);
    reader.setErrorHandler(errorHandler);
    reader.setContentHandler(errorHandler);
    try {
        reader.parse(
                new InputSource(new InputStreamReader(new FileInputStream(outFile), IOUtils.UTF8_CHARSET)));
    } catch (SAXException ex) {
        // do nothing. The error is handled in the error handler
    }
    return errorHandler.getMessages();
}

From source file:codeswarm.XMLQueueLoader.java

public void run() {
    XMLReader reader = null;
    try {/*from   w  w w . j a va2s.c o m*/
        reader = XMLReaderFactory.createXMLReader();
    } catch (SAXException e) {
        logger.error("Couldn't find/create an XML SAX Reader", e);
        System.exit(1);
    }

    reader.setContentHandler(new DefaultHandler() {
        public void startElement(String uri, String localName, String name, Attributes atts)
                throws SAXException {
            if (name.equals("event")) {
                String eventFilename = atts.getValue("filename");
                String eventDatestr = atts.getValue("date");
                long eventDate = Long.parseLong(eventDatestr);
                String eventWeightStr = atts.getValue("weight");
                int eventWeight = 1;
                if (eventWeightStr != null) {
                    eventWeight = Integer.parseInt(eventWeightStr);
                }

                //It's difficult for the user to tell that they're missing events,
                //so we should crash in this case
                if (isXMLSorted) {
                    if (eventDate < maximumDateSeenSoFar) {
                        logger.error(
                                "Input not sorted, you must set IsInputSorted to false in your config file");
                        System.exit(1);
                    } else
                        maximumDateSeenSoFar = eventDate;
                }

                String eventAuthor = atts.getValue("author");
                // int eventLinesAdded = atts.getValue( "linesadded" );
                // int eventLinesRemoved = atts.getValue( "linesremoved" );

                FileEvent evt = new FileEvent(eventDate, eventAuthor, "", eventFilename, eventWeight);
                try {
                    queue.put(evt);
                    fireEventAddedEvent();
                } catch (InterruptedException e) {
                    // TODO Auto-generated catch block
                    logger.error("Interrupted while trying to put into eventsQueue", e);
                    System.exit(1);
                }
            }
        }

        /*
         * (non-Javadoc)
         * @see org.xml.sax.helpers.DefaultHandler#endDocument()
         * 
         * Notify any listeners that the Document has finished parsing.
         */
        public void endDocument() {
            fireTaskDoneEvent();
        }

    });

    try {
        reader.parse(fullFilename);
    } catch (Exception e) {
        logger.error("Error parsing xml:", e);
        System.exit(1);
    }
}

From source file:com.myjeeva.poi.ExcelReader.java

/**
 * Parses the content of one sheet using the specified styles and shared-strings tables.
 * //from w ww . j a v  a2  s.c  o m
 * @param styles a {@link StylesTable} object
 * @param sharedStringsTable a {@link ReadOnlySharedStringsTable} object
 * @param sheetInputStream a {@link InputStream} object
 * @throws IOException
 * @throws ParserConfigurationException
 * @throws SAXException
 */
private void readSheet(StylesTable styles, ReadOnlySharedStringsTable sharedStringsTable,
        InputStream sheetInputStream) throws IOException, ParserConfigurationException, SAXException {

    SAXParserFactory saxFactory = SAXParserFactory.newInstance();
    XMLReader sheetParser = saxFactory.newSAXParser().getXMLReader();

    ContentHandler handler = new XSSFSheetXMLHandler(styles, sharedStringsTable, sheetContentsHandler, true);

    sheetParser.setContentHandler(handler);
    sheetParser.parse(new InputSource(sheetInputStream));
}