Example usage for javax.xml.parsers SAXParserFactory newInstance

List of usage examples for javax.xml.parsers SAXParserFactory newInstance

Introduction

In this page you can find the example usage for javax.xml.parsers SAXParserFactory newInstance.

Prototype


public static SAXParserFactory newInstance() 

Source Link

Document

Obtain a new instance of a SAXParserFactory .

Usage

From source file:com.zergiu.tvman.shows.search.AddShowFlowService.java

/**
 * @return/*w ww  .ja  v a  2  s .c o  m*/
 */
private void fillLanguagesTable() {
    log.debug("going to go to TVDB.com to get a list of languages");
    List<TVDBLanguage> languages = new ArrayList<TVDBLanguage>();
    URL url = null;
    try {
        url = new URL("http://www.thetvdb.com/api/CAC7D918A2D6A58F/languages.xml");
        InputStream in = url.openStream();
        SAXParserFactory factory = SAXParserFactory.newInstance();
        SAXParser parser = factory.newSAXParser();
        SearchLanguagesHandler handler = new SearchLanguagesHandler(languages);
        parser.parse(in, handler);
        in.close();
    } catch (MalformedURLException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } catch (ParserConfigurationException e) {
        e.printStackTrace();
    } catch (SAXException e) {
        e.printStackTrace();
    }
    tvdbLanguageService.addLanguages(languages);
}

From source file:joachimeichborn.geotag.io.parser.gpx.GpxParser.java

public joachimeichborn.geotag.model.Track read(final Path aGpxFile) throws IOException {
    logger.fine("Reading positions from " + aGpxFile);

    final List<PositionData> positions = new LinkedList<>();

    final SAXParserFactory factory = SAXParserFactory.newInstance();
    factory.setNamespaceAware(true);//from w w  w.ja va  2 s.  c  o m
    try {
        final SAXParser saxParser = factory.newSAXParser();
        final Handler handler = new Handler();
        saxParser.parse(aGpxFile.toFile(), handler);

        positions.addAll(handler.getPositions());

    } catch (ParserConfigurationException | SAXException e) {
        throw new IOException(e);
    }

    logger.fine("Read " + positions.size() + " coordinates from " + aGpxFile);

    return new joachimeichborn.geotag.model.Track(aGpxFile, positions);
}

From source file:com.musala.core.RssProcessorImpl.java

private void readData() {
    SAXParserFactory factory = SAXParserFactory.newInstance();
    SAXParser parser = null;//from   ww w .  j  a v  a  2s . c o m
    try {
        parser = factory.newSAXParser();
        parser.parse(new InputSource(new URL(site.getRssLink()).openStream()), this);
    } catch (ParserConfigurationException e) {
        e.printStackTrace();
    } catch (SAXException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:org.energyos.espi.common.service.impl.ImportServiceImpl.java

@Override
public void importData(InputStream stream, Long retailCustomerId)
        throws IOException, SAXException, ParserConfigurationException {

    // setup the parser
    JAXBContext context = marshaller.getJaxbContext();

    SAXParserFactory factory = SAXParserFactory.newInstance();
    factory.setNamespaceAware(true);//  w  ww  . j a  v a2  s.  com
    XMLReader reader = factory.newSAXParser().getXMLReader();

    // EntryProcessor processor = new EntryProcessor(resourceLinker, new
    // ResourceConverter(), resourceService);
    ATOMContentHandler atomContentHandler = new ATOMContentHandler(context, entryProcessorService);
    reader.setContentHandler(atomContentHandler);

    // do the parse/import

    try {
        reader.parse(new InputSource(stream));

    } catch (SAXException e) {
        System.out.printf(
                "\nImportServiceImpl -- importData: SAXException\n     Cause = %s\n     Description = %s\n\n",
                e.getClass(), e.getMessage());
        throw new SAXException(e.getMessage(), e);

    } catch (Exception e) {
        System.out.printf("\nImportServiceImpl -- importData:\n     Cause = %s\n     Description = %s\n\n",
                e.getClass(), e.getMessage());
        e.printStackTrace();

    }
    // context of the import used for linking things up
    // and establishing notifications
    //

    entries = atomContentHandler.getEntries();
    minUpdated = atomContentHandler.getMinUpdated();
    maxUpdated = atomContentHandler.getMaxUpdated();

    // cleanup/end processing
    // 1 - associate to usage points to the right retail customer
    // 2 - make sure authorization/subscriptions have the right URIs
    // 3 - place the imported usagePoints in to the subscriptions
    //
    List<UsagePoint> usagePointList = new ArrayList<UsagePoint>();

    // now perform any associations (to RetailCustomer) and stage the
    // Notifications (if any)

    RetailCustomer retailCustomer = null;

    if (retailCustomerId != null) {
        retailCustomer = retailCustomerService.findById(retailCustomerId);
    }

    Iterator<EntryType> its = entries.iterator();

    while (its.hasNext()) {
        EntryType entry = its.next();
        UsagePoint usagePoint = entry.getContent().getUsagePoint();
        if (usagePoint != null) {

            // see if we already have a retail customer association

            RetailCustomer tempRc = usagePoint.getRetailCustomer();
            if (tempRc != null) {
                // hook it to the retailCustomer
                if (!(tempRc.equals(retailCustomer))) {
                    // we have a conflict in association meaning to Retail
                    // Customers
                    // TODO: resolve how to handle the conflict mentioned
                    // above.
                    // TODO: Only works for a single customer and not
                    // multiple customers
                    retailCustomer = tempRc;
                }
            } else {
                // associate the usagePoint with the Retail Customer
                if (retailCustomer != null) {
                    usagePointService.associateByUUID(retailCustomer, usagePoint.getUUID());
                }
            }
            usagePointList.add(usagePoint);
        }
    }

    // now if we have a retail customer, check for any subscriptions that
    // need associated
    if (retailCustomer != null) {

        Subscription subscription = null;

        // find and iterate across all relevant authorizations
        //
        List<Authorization> authorizationList = authorizationService
                .findAllByRetailCustomerId(retailCustomer.getId());
        for (Authorization authorization : authorizationList) {

            try {
                subscription = subscriptionService.findByAuthorizationId(authorization.getId());
            } catch (Exception e) {
                // an Authorization w/o an associated subscription breaks
                // the propagation chain
                System.out.printf("**** End of Notification Propagation Chain\n");
            }
            if (subscription != null) {
                String resourceUri = authorization.getResourceURI();
                // this is the first time this authorization has been in
                // effect. We must set up the appropriate resource links
                if (resourceUri == null) {
                    ApplicationInformation applicationInformation = authorization.getApplicationInformation();
                    resourceUri = applicationInformation.getDataCustodianResourceEndpoint();
                    resourceUri = resourceUri + "/Batch/Subscription/" + subscription.getId();
                    authorization.setResourceURI(resourceUri);

                    resourceService.merge(authorization);
                }

                // make sure the UsagePoint(s) we just imported are linked
                // up
                // with
                // the Subscription

                for (UsagePoint usagePoint : usagePointList) {
                    boolean addNew = false;
                    for (UsagePoint up : subscription.getUsagePoints()) {
                        if (up.equals(usagePoint))
                            addNew = true;
                    }

                    if (addNew)
                        subscriptionService.addUsagePoint(subscription, usagePoint);

                }
            }
        }
    }
}

From source file:edu.scripps.fl.pubchem.web.entrez.ELinkWebSession.java

@SuppressWarnings("unchecked")
protected Collection<ELinkResult> getELinkResultsSAX(final Collection<ELinkResult> relations) throws Exception {
    log.info("Memory in use before inputstream: " + memUsage());
    InputStream is = EUtilsWebSession.getInstance()
            .getInputStream("http://eutils.ncbi.nlm.nih.gov/entrez/eutils/elink.fcgi", getParams()).call();
    log.info("Memory in use after inputstream: " + memUsage());
    SAXParserFactory factory = SAXParserFactory.newInstance();
    SAXParser saxParser = factory.newSAXParser();
    DefaultHandler handler = new DefaultHandler() {
        private ELinkResult result;
        private List<Long> idList;
        private StringBuffer buf;
        private int depth;
        private String linkName;
        private String dbTo;

        public void characters(char ch[], int start, int length) throws SAXException {
            buf.append(ch, start, length);
        }/*from  w w  w . j  a v  a2  s  .c  o m*/

        public void endElement(String uri, String localName, String qName) throws SAXException {
            if (qName.equalsIgnoreCase("LinkSet"))
                relations.add(result);
            else if (qName.equalsIgnoreCase("LinkSetDb")) {
                if (idList.size() > 0)
                    result.setIds(dbTo, linkName, idList);
            } else if (qName.equalsIgnoreCase("LinkName"))
                linkName = buf.toString();
            else if (qName.equalsIgnoreCase("dbTo"))
                dbTo = buf.toString();
            else if (qName.equalsIgnoreCase("DbFrom"))
                result.setDbFrom(buf.toString());
            else if (qName.equalsIgnoreCase("Id")) {
                Long id = Long.parseLong(buf.toString());
                if (depth == 4)
                    result.setId(id);
                else if (depth == 5)
                    idList.add(id);
            }
            depth--;
        }

        public void startElement(String uri, String localName, String qName, Attributes attributes)
                throws SAXException {
            depth++;
            buf = new StringBuffer();
            if (qName.equalsIgnoreCase("LinkSet"))
                result = new ELinkResult();
            else if (qName.equalsIgnoreCase("LinkSetDb"))
                idList = new ArrayList();
        }
    };
    log.info("Memory in use before parsing: " + memUsage());
    log.info("Parsing elink results using SAX.");
    try {
        saxParser.parse(is, handler);
    } catch (SAXParseException ex) {
        throw new Exception("Error parsing ELink output: " + ex.getMessage());
    }
    log.info("Finished parsing elink results.");
    log.info("Memory in use after parsing: " + memUsage());
    return relations;
}

From source file:de.doering.dwca.iocwbn.ChecklistBuilder.java

private void parsePage(Eml eml) throws IOException, SAXException, ParserConfigurationException {
    // get webapge
    String url = XML_DOWNLOAD.replace("{VERSION}", VERSION);
    log.info("Downloading latest IOC world bird list from {}", url);

    DefaultHttpClient client = new DefaultHttpClient();
    HttpGet get = new HttpGet(url);

    // execute/* w  w w .ja v  a 2  s .com*/
    HttpResponse response = client.execute(get);
    HttpEntity entity = response.getEntity();
    // parse page
    SAXParserFactory factory = SAXParserFactory.newInstance();

    final SAXParser parser = factory.newSAXParser();
    IocXmlHandler handler = new IocXmlHandler(writer, eml);
    try {
        Reader reader = new InputStreamReader(entity.getContent(), ENCODING);
        parser.parse(new InputSource(reader), handler);
    } catch (Exception e) {
        log.error("Cannot process IOC XML", e);
    }
}

From source file:com.entertailion.android.slideshow.rss.RssHandler.java

public RssFeed getFeed(String data) throws Exception {
    feed = null;/*from ww  w. j a  v  a  2  s.  c o  m*/
    SAXParserFactory spf = SAXParserFactory.newInstance();
    SAXParser sp = spf.newSAXParser();
    XMLReader xr = sp.getXMLReader();

    InputSource inStream = new org.xml.sax.InputSource();
    inStream.setCharacterStream(new StringReader(data));

    xr.setContentHandler(this);
    feed = new RssFeed();
    xr.parse(inStream);

    xr = null;
    sp = null;
    spf = null;

    return feed;
}

From source file:com.entertailion.android.overlaynews.rss.RssHandler.java

public RssFeed getFeed(String data) {
    feed = null;/*from  w w w.jav a  2 s .  co  m*/
    try {
        SAXParserFactory spf = SAXParserFactory.newInstance();
        SAXParser sp = spf.newSAXParser();
        XMLReader xr = sp.getXMLReader();

        InputSource inStream = new org.xml.sax.InputSource();
        inStream.setCharacterStream(new StringReader(data));

        xr.setContentHandler(this);
        feed = new RssFeed();
        xr.parse(inStream);

        xr = null;
        sp = null;
        spf = null;
    } catch (Exception e) {
        Log.e(LOG_CAT, "getFeed", e);
    }

    return feed;
}

From source file:com.jkoolcloud.tnt4j.streams.configure.sax.ConfigParserHandlerTest.java

protected void validateConfigs(File samplesDir, String configFileWildcard, boolean checkStreams,
        List<String> skipFiles) throws Exception {
    Collection<File> sampleConfigurations = FileUtils.listFiles(samplesDir,
            FileFilterUtils.asFileFilter(
                    (FilenameFilter) new WildcardFileFilter(configFileWildcard, IOCase.INSENSITIVE)),
            TrueFileFilter.INSTANCE);//www  . j a v  a 2 s  . co  m

    Collection<File> sampleConfigurationsFiltered = new ArrayList<>(sampleConfigurations);
    if (CollectionUtils.isNotEmpty(skipFiles)) {
        for (File sampleConfiguration : sampleConfigurations) {
            for (String skipFile : skipFiles) {
                if (sampleConfiguration.getAbsolutePath().contains(skipFile))
                    sampleConfigurationsFiltered.remove(sampleConfiguration);
            }
        }
    }

    for (File sampleConfiguration : sampleConfigurationsFiltered) {
        System.out.println("Reading configuration file: " + sampleConfiguration.getAbsolutePath()); // NON-NLS
        Reader testReader = new FileReader(sampleConfiguration);
        SAXParserFactory parserFactory = SAXParserFactory.newInstance();
        SAXParser parser = parserFactory.newSAXParser();
        ConfigParserHandler hndlr = new ConfigParserHandler();
        parser.parse(new InputSource(testReader), hndlr);

        assertNotNull("Parsed streams config data is null", hndlr.getStreamsConfigData());
        boolean parseable = true;
        if (checkStreams) {
            assertTrue("No configured streams", hndlr.getStreamsConfigData().isStreamsAvailable());

            parseable = false;
            for (TNTInputStream<?, ?> s : hndlr.getStreamsConfigData().getStreams()) {
                if (s instanceof TNTParseableInputStream) {
                    parseable = true;
                    break;
                }
            }
        }
        if (parseable) {
            assertTrue("No configured parsers", hndlr.getStreamsConfigData().isParsersAvailable());
        }

        Utils.close(testReader);
    }
}

From source file:net.sf.ehcache.config.ConfigurationFactory.java

/**
 * Configures a bean from an XML input stream.
 *///ww w .java  2 s. c o m
public static Configuration parseConfiguration(final InputStream inputStream) throws CacheException {
    if (LOG.isDebugEnabled()) {
        LOG.debug("Configuring ehcache from InputStream");
    }

    Configuration configuration = new Configuration();
    try {
        InputStream translatedInputStream = translateSystemProperties(inputStream);
        final SAXParser parser = SAXParserFactory.newInstance().newSAXParser();
        final BeanHandler handler = new BeanHandler(configuration);
        parser.parse(translatedInputStream, handler);
    } catch (Exception e) {
        throw new CacheException("Error configuring from input stream. Initial cause was " + e.getMessage(), e);
    }
    return configuration;
}