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.jkoolcloud.tnt4j.streams.inputs.ExcelSXSSFRowStream.java

/**
 * Parses the content of one sheet using the specified styles and shared-strings tables.
 *
 * @param styles/*from   ww w.  j a  v a 2s  .  co  m*/
 *            the table of styles that may be referenced by cells in the sheet
 * @param strings
 *            the table of strings that may be referenced by cells in the sheet
 * @param sheetHandler
 *            the sheet handler
 * @param sheetInputStream
 *            the input stream to read the sheet-data from
 *
 * @throws IOException
 *             if sheet input stream read fails
 * @throws SAXException
 *             if sheet input stream provided XML can't be parsed
 */
public static void processSXSSFSheet(StylesTable styles, ReadOnlySharedStringsTable strings,
        SheetContentsHandler sheetHandler, InputStream sheetInputStream) throws IOException, SAXException {
    DataFormatter formatter = new DataFormatter();
    InputSource sheetSource = new InputSource(sheetInputStream);
    try {
        XMLReader sheetParser = SAXHelper.newXMLReader();
        ContentHandler handler = new XSSFSheetXMLHandler(styles, null, strings, sheetHandler, formatter, false);
        sheetParser.setContentHandler(handler);
        sheetParser.parse(sheetSource);
    } catch (ParserConfigurationException exc) {
        throw new RuntimeException(
                StreamsResources.getStringFormatted(MsOfficeStreamConstants.RESOURCE_BUNDLE_NAME,
                        "ExcelSXSSFRowStream.sax.cfg.error", Utils.getExceptionMessages(exc)));
    }
}

From source file:info.magnolia.importexport.DataTransporter.java

/**
 * Imports XML stream into repository./* w w w  . jav  a2 s.  c o  m*/
 * XML is filtered by <code>MagnoliaV2Filter</code>, <code>VersionFilter</code> and <code>ImportXmlRootFilter</code>
 * if <code>keepVersionHistory</code> is set to <code>false</code>
 * @param xmlStream XML stream to import
 * @param repositoryName selected repository
 * @param basepath base path in repository
 * @param name (absolute path of <code>File</code>)
 * @param keepVersionHistory if <code>false</code> version info will be stripped before importing the document
 * @param importMode a valid value for ImportUUIDBehavior
 * @param saveAfterImport
 * @param createBasepathIfNotExist
 * @throws IOException
 * @see ImportUUIDBehavior
 * @see ImportXmlRootFilter
 * @see VersionFilter
 * @see MagnoliaV2Filter
 */
public static synchronized void importXmlStream(InputStream xmlStream, String repositoryName, String basepath,
        String name, boolean keepVersionHistory, int importMode, boolean saveAfterImport,
        boolean createBasepathIfNotExist) throws IOException {

    // TODO hopefully this will be fixed with a more useful message with the Bootstrapper refactoring
    if (xmlStream == null) {
        throw new IOException("Can't import a null stream into repository: " + repositoryName + ", basepath: "
                + basepath + ", name: " + name);
    }

    HierarchyManager hm = MgnlContext.getHierarchyManager(repositoryName);
    if (hm == null) {
        throw new IllegalStateException(
                "Can't import " + name + " since repository " + repositoryName + " does not exist.");
    }
    Workspace ws = hm.getWorkspace();

    if (log.isDebugEnabled()) {
        log.debug("Importing content into repository: [{}] from: [{}] into path: [{}]",
                new Object[] { repositoryName, name, basepath });
    }

    if (!hm.isExist(basepath) && createBasepathIfNotExist) {
        try {
            ContentUtil.createPath(hm, basepath, ItemType.CONTENT);
        } catch (RepositoryException e) {
            log.error("can't create path [{}]", basepath);
        }
    }

    Session session = ws.getSession();

    try {

        // Collects a list with all nodes at the basepath before import so we can see exactly which nodes were imported afterwards
        List<Node> nodesBeforeImport = NodeUtil
                .asList(NodeUtil.asIterable(session.getNode(basepath).getNodes()));

        if (keepVersionHistory) {
            // do not manipulate
            session.importXML(basepath, xmlStream, importMode);
        } else {
            // create readers/filters and chain
            XMLReader initialReader = XMLReaderFactory
                    .createXMLReader(org.apache.xerces.parsers.SAXParser.class.getName());
            try {
                initialReader.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true);
            } catch (SAXException e) {
                log.error("could not set parser feature");
            }

            XMLFilter magnoliaV2Filter = null;

            // if stream is from regular file, test for belonging XSL file to apply XSL transformation to XML
            if (new File(name).isFile()) {
                InputStream xslStream = getXslStreamForXmlFile(new File(name));
                if (xslStream != null) {
                    Source xslSource = new StreamSource(xslStream);
                    SAXTransformerFactory saxTransformerFactory = (SAXTransformerFactory) SAXTransformerFactory
                            .newInstance();
                    XMLFilter xslFilter = saxTransformerFactory.newXMLFilter(xslSource);
                    magnoliaV2Filter = new MagnoliaV2Filter(xslFilter);
                }
            }

            if (magnoliaV2Filter == null) {
                magnoliaV2Filter = new MagnoliaV2Filter(initialReader);
            }

            XMLFilter versionFilter = new VersionFilter(magnoliaV2Filter);

            // enable this to strip useless "name" properties from dialogs
            // versionFilter = new UselessNameFilter(versionFilter);

            // enable this to strip mix:versionable from pre 3.6 xml files
            versionFilter = new RemoveMixversionableFilter(versionFilter);

            XMLReader finalReader = new ImportXmlRootFilter(versionFilter);

            ContentHandler handler = session.getImportContentHandler(basepath, importMode);
            finalReader.setContentHandler(handler);

            // parse XML, import is done by handler from session
            try {
                finalReader.parse(new InputSource(xmlStream));
            } finally {
                IOUtils.closeQuietly(xmlStream);
            }

            if (((ImportXmlRootFilter) finalReader).rootNodeFound) {
                String path = basepath;
                if (!path.endsWith(SLASH)) {
                    path += SLASH;
                }

                Node dummyRoot = (Node) session.getItem(path + JCR_ROOT);
                for (Iterator iter = dummyRoot.getNodes(); iter.hasNext();) {
                    Node child = (Node) iter.next();
                    // move childs to real root

                    if (session.itemExists(path + child.getName())) {
                        session.getItem(path + child.getName()).remove();
                    }

                    session.move(child.getPath(), path + child.getName());
                }
                // delete the dummy node
                dummyRoot.remove();
            }

            // Post process all nodes that were imported
            NodeIterator nodesAfterImport = session.getNode(basepath).getNodes();
            while (nodesAfterImport.hasNext()) {
                Node nodeAfterImport = nodesAfterImport.nextNode();
                boolean existedBeforeImport = false;
                for (Node nodeBeforeImport : nodesBeforeImport) {
                    if (NodeUtil.isSame(nodeAfterImport, nodeBeforeImport)) {
                        existedBeforeImport = true;
                        break;
                    }
                }
                if (!existedBeforeImport) {
                    postProcessAfterImport(nodeAfterImport);
                }
            }
        }
    } catch (Exception e) {
        throw new RuntimeException("Error importing " + name + ": " + e.getMessage(), e);
    } finally {
        IOUtils.closeQuietly(xmlStream);
    }

    try {
        if (saveAfterImport) {
            session.save();
        }
    } catch (RepositoryException e) {
        log.error(MessageFormat.format(
                "Unable to save changes to the [{0}] repository due to a {1} Exception: {2}.",
                new Object[] { repositoryName, e.getClass().getName(), e.getMessage() }), e);
        throw new IOException(e.getMessage());
    }
}

From source file:com.zimbra.cs.service.FeedManager.java

@VisibleForTesting
static final String stripXML(String title) {
    if (title == null) {
        return "";
    } else if (title.indexOf('<') == -1 && title.indexOf('&') == -1) {
        return title;
    }/*from   w w  w  .j  a  v a2 s  .  com*/

    org.xml.sax.XMLReader parser = new org.cyberneko.html.parsers.SAXParser();
    org.xml.sax.ContentHandler handler = new UnescapedContent();
    parser.setContentHandler(handler);
    try {
        parser.parse(new org.xml.sax.InputSource(new StringReader(title)));
        return handler.toString();
    } catch (Exception e) {
        return title;
    }
}

From source file:nbxml.Base.java

public void parseXml(String resource, ContentHandler contentHandler) throws SAXException, IOException {
    InputStream inputStream = getResourceAsStream(resource);
    InputSource inputSource = new InputSource(inputStream);
    XMLReader xmlReader = XMLReaderFactory.createXMLReader();

    xmlReader.setContentHandler(contentHandler);
    xmlReader.parse(inputSource);/*from w w  w  .jav a 2 s .  c o  m*/
}

From source file:com.janoz.tvapilib.support.XmlParsingObject.java

protected void parse(AbstractSaxParser parser, InputStream inputStream) {
    try {/* w w  w  .  j a  v  a 2 s  .  c  o m*/
        InputSource input = new InputSource(inputStream);
        input.setPublicId("");
        input.setSystemId("");
        XMLReader reader = XMLReaderFactory.createXMLReader();
        reader.setContentHandler(parser);
        reader.parse(input);
    } catch (SAXException e) {
        LOG.info("Error parsing XML data.", e);
        throw new TvApiException(e.getMessage(), e);
    } catch (IOException e) {
        LOG.info("IO error while parsing XML data.", e);
        throw new TvApiException("IO error while parsing XML data.", e);
    }
}

From source file:com.adamrosenfield.wordswithcrosses.net.derstandard.DerStandardParser.java

private void parse(InputSource input, ContentHandler handler) throws SAXException, IOException {
    XMLReader xmlReader = XMLReaderFactory.createXMLReader("org.ccil.cowan.tagsoup.Parser");

    xmlReader.setContentHandler(handler);
    xmlReader.parse(input);//from  w w w. j  av a2  s .  com
}

From source file:org.metawatch.manager.Monitors.java

private static synchronized void updateWeatherDataGoogle(Context context) {
    try {//from   w  ww . j  av  a 2  s  .  c  o m

        if (WeatherData.updating)
            return;

        // Prevent weather updating more frequently than every 5 mins
        if (WeatherData.timeStamp != 0 && WeatherData.received) {
            long currentTime = System.currentTimeMillis();
            long diff = currentTime - WeatherData.timeStamp;

            if (diff < 5 * 60 * 1000) {
                if (Preferences.logging)
                    Log.d(MetaWatch.TAG, "Skipping weather update - updated less than 5m ago");

                //IdleScreenWidgetRenderer.sendIdleScreenWidgetUpdate(context);

                return;
            }
        }

        WeatherData.updating = true;

        if (Preferences.logging)
            Log.d(MetaWatch.TAG, "Monitors.updateWeatherDataGoogle(): start");

        String queryString;
        List<Address> addresses;
        if (Preferences.weatherGeolocation && LocationData.received) {
            Geocoder geocoder;
            String locality = "";
            String PostalCode = "";
            try {
                geocoder = new Geocoder(context, Locale.getDefault());
                addresses = geocoder.getFromLocation(LocationData.latitude, LocationData.longitude, 1);

                for (Address address : addresses) {
                    if (!address.getPostalCode().equalsIgnoreCase("")) {
                        PostalCode = address.getPostalCode();
                        locality = address.getLocality();
                        if (locality.equals("")) {
                            locality = PostalCode;
                        } else {
                            PostalCode = locality + ", " + PostalCode;
                        }

                    }
                }
            } catch (IOException e) {
                if (Preferences.logging)
                    Log.e(MetaWatch.TAG, "Exception while retreiving postalcode", e);
            }

            if (PostalCode.equals("")) {
                PostalCode = Preferences.weatherCity;
            }
            if (locality.equals("")) {
                WeatherData.locationName = PostalCode;
            } else {
                WeatherData.locationName = locality;
            }

            queryString = "http://www.google.com/ig/api?weather=" + PostalCode;
        } else {
            queryString = "http://www.google.com/ig/api?weather=" + Preferences.weatherCity;
            WeatherData.locationName = Preferences.weatherCity;
        }

        URL url = new URL(queryString.replace(" ", "%20"));

        SAXParserFactory spf = SAXParserFactory.newInstance();
        SAXParser sp = spf.newSAXParser();
        XMLReader xr = sp.getXMLReader();

        GoogleWeatherHandler gwh = new GoogleWeatherHandler();
        xr.setContentHandler(gwh);
        xr.parse(new InputSource(url.openStream()));
        WeatherSet ws = gwh.getWeatherSet();
        WeatherCurrentCondition wcc = ws.getWeatherCurrentCondition();

        ArrayList<WeatherForecastCondition> conditions = ws.getWeatherForecastConditions();

        int days = conditions.size();
        WeatherData.forecast = new Forecast[days];

        for (int i = 0; i < days; ++i) {
            WeatherForecastCondition wfc = conditions.get(i);

            WeatherData.forecast[i] = m.new Forecast();
            WeatherData.forecast[i].day = null;

            WeatherData.forecast[i].icon = getIconGoogleWeather(wfc.getCondition());
            WeatherData.forecast[i].day = wfc.getDayofWeek();

            if (Preferences.weatherCelsius) {
                WeatherData.forecast[i].tempHigh = wfc.getTempMaxCelsius().toString();
                WeatherData.forecast[i].tempLow = wfc.getTempMinCelsius().toString();
            } else {
                WeatherData.forecast[i].tempHigh = Integer
                        .toString(WeatherUtils.celsiusToFahrenheit(wfc.getTempMaxCelsius()));
                WeatherData.forecast[i].tempLow = Integer
                        .toString(WeatherUtils.celsiusToFahrenheit(wfc.getTempMinCelsius()));
            }
        }

        WeatherData.celsius = Preferences.weatherCelsius;

        String cond = wcc.getCondition();
        WeatherData.condition = cond;

        if (Preferences.weatherCelsius) {
            WeatherData.temp = Integer.toString(wcc.getTempCelcius());
        } else {
            WeatherData.temp = Integer.toString(wcc.getTempFahrenheit());
        }

        cond = cond.toLowerCase();

        WeatherData.icon = getIconGoogleWeather(cond);
        WeatherData.received = true;
        WeatherData.timeStamp = System.currentTimeMillis();

        Idle.updateIdle(context, true);
        MetaWatchService.notifyClients();

    } catch (Exception e) {
        if (Preferences.logging)
            Log.e(MetaWatch.TAG, "Exception while retreiving weather", e);
    } finally {
        if (Preferences.logging)
            Log.d(MetaWatch.TAG, "Monitors.updateWeatherData(): finish");
    }

}

From source file:SAXLister.java

public SAXLister(String[] args) throws SAXException, IOException {
    XMLReader parser = XMLReaderFactory.createXMLReader();
    // should load properties rather than hardcoding class name
    parser.setContentHandler(new PeopleHandler());
    parser.parse(args.length == 1 ? args[0] : "people.xml");
}

From source file:org.npr.api.Client.java

public void sax(ContentHandler handler) {
    try {//from  w ww  . ja  v  a  2s. c o m
        XMLReader xr = SAXParserFactory.newInstance().newSAXParser().getXMLReader();
        xr.setContentHandler(handler);
        xr.parse(new InputSource(download()));
    } catch (SAXException e) {
        Log.e(LOG_TAG, "error creating parser", e);
    } catch (ParserConfigurationException e) {
        Log.e(LOG_TAG, "error creating parser", e);
    } catch (FactoryConfigurationError e) {
        Log.e(LOG_TAG, "error creating parser", e);
    } catch (IOException e) {
        Log.e(LOG_TAG, "error parsing", e);
    }
}

From source file:com.inferiorhumanorgans.WayToGo.Agency.BART.Route.RouteTask.java

@Override
protected Void doInBackground(BARTAgency... someAgencies) {
    super.doInBackground(someAgencies);
    Log.i(LOG_NAME, "Trying to get BART route list.");

    InputStream content = null;/*from  ww  w.  j a  va 2s  .c  om*/
    ClientConnectionManager connman = new ThreadSafeClientConnManager(params, registry);
    DefaultHttpClient hc = new DefaultHttpClient(connman, params);

    Log.i(LOG_NAME, "Fetching from: " + BART_URL + BARTAgency.API_KEY);
    HttpGet getRequest = new HttpGet(BART_URL + BARTAgency.API_KEY);
    try {
        content = hc.execute(getRequest).getEntity().getContent();
    } catch (ClientProtocolException ex) {
        Logger.getLogger(LOG_NAME).log(Level.SEVERE, null, ex);
    } catch (IOException ex) {
        Logger.getLogger(LOG_NAME).log(Level.SEVERE, null, ex);
    }
    Log.i(LOG_NAME, "Put the station list in the background.");

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

        XMLReader xr = sp.getXMLReader();

        xr.setContentHandler(dataHandler);

        xr.parse(new InputSource(content));

    } catch (ParserConfigurationException pce) {
        Log.e(LOG_NAME + " SAX XML", "sax parse error", pce);
    } catch (AbortXMLParsingException abrt) {
        Log.i(LOG_NAME + " AsyncXML", "Cancelled!!!!!");
    } catch (SAXException se) {
        Log.e(LOG_NAME + " SAX XML", "sax error", se);
    } catch (IOException ioe) {
        Log.e(LOG_NAME + " SAX XML", "sax parse io error", ioe);
    }
    Log.i(LOG_NAME + " SAX XML", "Done parsing BART station XML");
    return null;
}