Example usage for javax.xml.parsers SAXParserFactory newSAXParser

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

Introduction

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

Prototype


public abstract SAXParser newSAXParser() throws ParserConfigurationException, SAXException;

Source Link

Document

Creates a new instance of a SAXParser using the currently configured factory parameters.

Usage

From source file:com.sshtools.common.mru.MRUList.java

/**
 *
 *
 * @param in//  w  ww .  j ava 2s. co  m
 *
 * @throws SAXException
 * @throws ParserConfigurationException
 * @throws IOException
 */
public void reload(InputStream in) throws SAXException, ParserConfigurationException, IOException {
    try {
        SAXParserFactory saxFactory = SAXParserFactory.newInstance();
        SAXParser saxParser = saxFactory.newSAXParser();
        saxParser.parse(in, new MRUSAXHandler());
    } catch (Throwable e) {
        System.out.println("MRUList.reload: Exception loading most-recently-used list.");
        e.printStackTrace();
    }
}

From source file:com.aurel.track.plugin.PluginParser.java

private void parse(InputStream is) {
    //get a factory
    SAXParserFactory spf = SAXParserFactory.newInstance();
    try {/*  w ww  .j  av  a2  s  .  c om*/
        //get a new instance of parser
        SAXParser sp = spf.newSAXParser();

        //parse the file and also register this class for call backs
        sp.parse(is, this);
    } catch (SAXException se) {
        LOGGER.error(ExceptionUtils.getStackTrace(se));
    } catch (ParserConfigurationException pce) {
        LOGGER.error(ExceptionUtils.getStackTrace(pce));
    } catch (IOException ie) {
        LOGGER.error(ExceptionUtils.getStackTrace(ie));
    }
}

From source file:com.amytech.android.library.utils.asynchttp.SaxAsyncHttpResponseHandler.java

/**
 * Deconstructs response into given content handler
 *
 * @param entity/*from   www.jav  a  2  s.  co m*/
 *            returned HttpEntity
 * @return deconstructed response
 * @throws java.io.IOException
 *             if there is problem assembling SAX response from stream
 * @see org.apache.http.HttpEntity
 */
@Override
protected byte[] getResponseData(HttpEntity entity) throws IOException {
    if (entity != null) {
        InputStream instream = entity.getContent();
        InputStreamReader inputStreamReader = null;
        if (instream != null) {
            try {
                SAXParserFactory sfactory = SAXParserFactory.newInstance();
                SAXParser sparser = sfactory.newSAXParser();
                XMLReader rssReader = sparser.getXMLReader();
                rssReader.setContentHandler(handler);
                inputStreamReader = new InputStreamReader(instream, DEFAULT_CHARSET);
                rssReader.parse(new InputSource(inputStreamReader));
            } catch (SAXException e) {
                Log.e(LOG_TAG, "getResponseData exception", e);
            } catch (ParserConfigurationException e) {
                Log.e(LOG_TAG, "getResponseData exception", e);
            } finally {
                AsyncHttpClient.silentCloseInputStream(instream);
                if (inputStreamReader != null) {
                    try {
                        inputStreamReader.close();
                    } catch (IOException e) { /* ignore */
                    }
                }
            }
        }
    }
    return null;
}

From source file:egat.cli.neresponse.NEResponseCommandHandler.java

protected void processSymmetricGame(MutableSymmetricGame game) throws CommandProcessingException {

    InputStream inputStream = null;
    try {/*from  w w w .java2 s .  co m*/

        inputStream = new FileInputStream(profilePath);

    } catch (FileNotFoundException e) {

        throw new CommandProcessingException(e);

    }

    try {
        SAXParserFactory factory = SAXParserFactory.newInstance();

        SAXParser parser = factory.newSAXParser();

        StrategyHandler handler = new StrategyHandler();

        parser.parse(inputStream, handler);

        Strategy strategy = handler.getStrategy();

        findNEResponse(strategy, game);
    } catch (NonexistentPayoffException e) {
        System.err.println(String.format("Could not calculate regret. %s", e.getMessage()));
    } catch (ParserConfigurationException e) {
        throw new CommandProcessingException(e);
    } catch (SAXException e) {
        throw new CommandProcessingException(e);
    } catch (IOException e) {
        throw new CommandProcessingException(e);
    }
}

From source file:VSX.java

public TreeModel parse(String filename) {
    SAXParserFactory factory = SAXParserFactory.newInstance();
    XMLTreeHandler handler = new XMLTreeHandler();
    try {//  w  w w. j  a  v  a  2 s.c  o  m
        // Parse the input.
        SAXParser saxParser = factory.newSAXParser();
        saxParser.parse(new File(filename), handler);
    } catch (Exception e) {
        System.err.println("File Read Error: " + e);
        e.printStackTrace();
        return new DefaultTreeModel(new DefaultMutableTreeNode("error"));
    }
    return new DefaultTreeModel(handler.getRoot());
}

From source file:com.opengamma.financial.convention.calendar.XMLCalendarLoader.java

/**
 * Populate the specified working day calendar from the XML file.
 * @param calendar  the calendar to populate, not null
 *//*from ww  w.  j av a 2 s. c om*/
public void populateCalendar(final ExceptionCalendar calendar) {
    final SAXParserFactory factory = SAXParserFactory.newInstance();
    try {
        final SAXParser parser = factory.newSAXParser();
        parser.parse(getSourceDataURI(), new DefaultHandler() {
            private ParserState _state = ParserState.OTHER;
            private String _innerText;

            @Override
            public void startElement(final String uri, final String localName, final String qName,
                    final Attributes attributes) {
                switch (_state) {
                case OTHER:
                    if (qName.equalsIgnoreCase(TAG_WORKING_DAYS)) {
                        _state = ParserState.WORKING_DAYS;
                    } else if (qName.equalsIgnoreCase(TAG_NON_WORKING_DAYS)) {
                        _state = ParserState.NON_WORKING_DAYS;
                    }
                    break;
                }
            }

            @Override
            public void characters(final char[] ch, final int start, final int length) {
                _innerText = new String(ch, start, length);
            }

            @Override
            public void endElement(final String uri, final String localName, final String qName) {
                switch (_state) {
                case WORKING_DAYS:
                    if (qName.equalsIgnoreCase(TAG_DATE)) {
                        calendar.addWorkingDay(LocalDate.parse(_innerText));
                    } else if (qName.equalsIgnoreCase(TAG_WORKING_DAYS)) {
                        _state = ParserState.OTHER;
                    }
                    break;
                case NON_WORKING_DAYS:
                    if (qName.equalsIgnoreCase(TAG_DATE)) {
                        calendar.addNonWorkingDay(LocalDate.parse(_innerText));
                    } else if (qName.equalsIgnoreCase(TAG_NON_WORKING_DAYS)) {
                        _state = ParserState.OTHER;
                    }
                    break;
                }
            }
        });
    } catch (final ParserConfigurationException ex) {
        throw wrap(ex);
    } catch (final SAXException ex) {
        throw wrap(ex);
    } catch (final IOException ex) {
        throw wrap(ex);
    }
}

From source file:de.uzk.hki.da.model.RightsSectionURNMetsXmlReader.java

/**
 * Read urn.//from  www.ja  v  a  2 s. c  o  m
 *
 * @param file the file
 * @return The URN specified in the METS file or null if the METS file doesn't specify an URN
 * @throws IOException Signals that an I/O exception has occurred.
 * @throws ParseException the parse exception
 * @author Thomas Kleinke
 */
public String readURN(File file) throws IOException, ParseException {

    FileInputStream fileInputStream = new FileInputStream(file);
    BOMInputStream bomInputStream = new BOMInputStream(fileInputStream);

    XMLReader xmlReader = null;
    SAXParserFactory spf = SAXParserFactory.newInstance();
    try {
        xmlReader = spf.newSAXParser().getXMLReader();
    } catch (Exception e) {
        fileInputStream.close();
        bomInputStream.close();
        throw new IOException("Error creating SAX parser", e);
    }
    xmlReader.setErrorHandler(err);
    NodeFactory nodeFactory = new PremisXmlReaderNodeFactory();
    Builder parser = new Builder(xmlReader, false, nodeFactory);
    logger.trace("Successfully built builder and XML reader");

    try {
        String urn = null;

        Document doc = parser.build(bomInputStream);
        Element root = doc.getRootElement();

        Element dmdSecEl = root.getFirstChildElement("dmdSec", METS_NS);
        if (dmdSecEl == null)
            return null;

        Element mdWrapEl = dmdSecEl.getFirstChildElement("mdWrap", METS_NS);
        if (mdWrapEl == null)
            return null;

        Element xmlDataEl = mdWrapEl.getFirstChildElement("xmlData", METS_NS);
        if (xmlDataEl == null)
            return null;

        Element modsEl = xmlDataEl.getFirstChildElement("mods", MODS_NS);
        if (modsEl == null)
            return null;

        Elements identifierEls = modsEl.getChildElements("identifier", MODS_NS);
        for (int i = 0; i < identifierEls.size(); i++) {
            Element element = identifierEls.get(i);
            Attribute attribute = element.getAttribute("type");
            if (attribute.getValue().toLowerCase().equals("urn"))
                urn = element.getValue();
        }

        if (urn != null && urn.equals(""))
            urn = null;

        return urn;
    } catch (ValidityException ve) {
        throw new IOException(ve);
    } catch (ParsingException pe) {
        throw new IOException(pe);
    } catch (IOException ie) {
        throw new IOException(ie);
    } finally {
        fileInputStream.close();
        bomInputStream.close();
    }
}

From source file:com.inferiorhumanorgans.WayToGo.Agency.BART.Station.StationTask.java

@Override
protected Void doInBackground(BARTAgency... someAgencies) {
    Assert.assertEquals(1, someAgencies.length);
    super.doInBackground(someAgencies);

    Log.i(LOG_NAME, "Trying to get BART station list.");

    InputStream content = null;//w  w  w. j av a 2 s  .c o m
    ClientConnectionManager connman = new ThreadSafeClientConnManager(params, registry);
    DefaultHttpClient hc = new DefaultHttpClient(connman, params);

    Log.i(LOG_NAME, "Fetching basic station info 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!!!!!");
        return null; // Pass on some exception to the caller?
    } 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");

    final DetailXMLHandler detailDataHandler = new DetailXMLHandler(this);

    for (String aStationTag : theStations.keySet()) {
        getRequest = new HttpGet(BART_DETAIL_URL + BARTAgency.API_KEY + "&orig=" + aStationTag);
        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 detail for " + aStationTag + " in the background.");

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

            XMLReader xr = sp.getXMLReader();

            xr.setContentHandler(detailDataHandler);

            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;
}

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 .j  a  va2 s . c  om
    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.epam.wilma.test.client.HttpRequestSender.java

private InputStream compress(final InputStream source) {
    try {// w  ww.ja  v a2 s  .  c om
        OutputStream fis = new ByteArrayOutputStream();
        SAXDocumentSerializer saxDocumentSerializer = new SAXDocumentSerializer();
        saxDocumentSerializer.setOutputStream(fis);
        SAXParserFactory saxParserFactory = SAXParserFactory.newInstance();
        saxParserFactory.setNamespaceAware(true);
        SAXParser saxParser = saxParserFactory.newSAXParser();
        saxParser.parse(source, saxDocumentSerializer);
        return new ByteArrayInputStream(((ByteArrayOutputStream) fis).toByteArray());
    } catch (ParserConfigurationException e) {
        throw new SystemException("error", e);
    } catch (SAXException e) {
        throw new SystemException("error", e);
    } catch (IOException e) {
        throw new SystemException("error", e);
    }
}