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.vmware.photon.controller.model.adapters.vsphere.ovf.OvfRetriever.java

private SAXParser newSaxParser() {
    SAXParserFactory saxParserFactory = SAXParserFactory.newInstance();

    try {//w  ww .j  a va2  s  .  co  m
        return saxParserFactory.newSAXParser();
    } catch (SAXException | ParserConfigurationException e) {
        throw new RuntimeException(e);
    }
}

From source file:com.pontecultural.flashcards.ReadSpreadsheet.java

public void run() {
    try {/*from  w w  w .  j a v  a2s.c o  m*/
        // This class is used to upload a zip file via 
        // the web (ie,fileData). To test it, the file is 
        // give to it directly via odsFile. One of 
        // which must be defined. 
        assertFalse(odsFile == null && fileData == null);
        XMLReader reader = null;
        final String ZIP_CONTENT = "content.xml";
        // Open office files are zipped. 
        // Walk through it and find "content.xml"

        ZipInputStream zin = null;
        try {
            if (fileData != null) {
                zin = new ZipInputStream(new BufferedInputStream(fileData.getInputStream()));
            } else {
                zin = new ZipInputStream(new BufferedInputStream(new FileInputStream(odsFile)));
            }

            ZipEntry entry;
            while ((entry = zin.getNextEntry()) != null) {
                if (entry.getName().equals(ZIP_CONTENT)) {
                    break;
                }
            }
            SAXParserFactory spf = SAXParserFactory.newInstance();
            //spf.setValidating(validate);

            SAXParser parser = spf.newSAXParser();
            reader = parser.getXMLReader();

            // reader.setErrorHandler(new MyErrorHandler());
            reader.setContentHandler(this);
            // reader.parse(new InputSource(zf.getInputStream(entry)));

            reader.parse(new InputSource(zin));

        } catch (ParserConfigurationException pce) {
            pce.printStackTrace();
        } catch (SAXParseException spe) {
            spe.printStackTrace();
        } catch (SAXException se) {
            se.printStackTrace();
        } catch (IOException ioe) {
            ioe.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (zin != null)
                zin.close();
        }
    } catch (IOException ioe) {
        ioe.printStackTrace();
    }
}

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");
    }//w  ww  .  j a va2s  . c om

    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.phonemetra.lockclock.weather.YahooWeatherProvider.java

@Override
public WeatherInfo getWeatherInfo(String id, String localizedCityName, boolean metric) {
    String url = String.format(URL_WEATHER, id, metric ? "c" : "f");
    String response = HttpRetriever.retrieve(url);

    if (response == null) {
        return null;
    }/*from w  w  w . j  av  a  2s .c o  m*/

    SAXParserFactory factory = SAXParserFactory.newInstance();
    try {
        SAXParser parser = factory.newSAXParser();
        StringReader reader = new StringReader(response);
        WeatherHandler handler = new WeatherHandler();
        parser.parse(new InputSource(reader), handler);

        if (handler.isComplete()) {
            // There are cases where the current condition is unknown, but the forecast
            // is not - using the (inaccurate) forecast is probably better than showing
            // the question mark
            if (handler.conditionCode == 3200) {
                handler.condition = handler.forecasts.get(0).condition;
                handler.conditionCode = handler.forecasts.get(0).conditionCode;
            }

            WeatherInfo w = new WeatherInfo(mContext, id,
                    localizedCityName != null ? localizedCityName : handler.city, handler.condition,
                    handler.conditionCode, handler.temperature, handler.temperatureUnit, handler.humidity,
                    handler.windSpeed, handler.windDirection, handler.speedUnit, handler.forecasts,
                    System.currentTimeMillis());
            Log.d(TAG, "Weather updated: " + w);
            return w;
        } else {
            Log.w(TAG, "Received incomplete weather XML (id=" + id + ")");
        }
    } catch (ParserConfigurationException e) {
        Log.e(TAG, "Could not create XML parser", e);
    } catch (SAXException e) {
        Log.e(TAG, "Could not parse weather XML (id=" + id + ")", e);
    } catch (IOException e) {
        Log.e(TAG, "Could not parse weather XML (id=" + id + ")", e);
    }

    return null;
}

From source file:com.openbravo.pos.printer.TicketParser.java

public void printTicket(Reader in) throws TicketPrinterException {

    try {//from   w w  w . j  a v  a2s .  c  o  m

        if (m_sp == null) {
            SAXParserFactory spf = SAXParserFactory.newInstance();
            m_sp = spf.newSAXParser();
        }
        m_sp.parse(new InputSource(in), this);

    } catch (ParserConfigurationException ePC) {
        throw new TicketPrinterException(LocalRes.getIntString("exception.parserconfig"), ePC);
    } catch (SAXException eSAX) {
        throw new TicketPrinterException(LocalRes.getIntString("exception.xmlfile"), eSAX);
    } catch (IOException eIO) {
        throw new TicketPrinterException(LocalRes.getIntString("exception.iofile"), eIO);
    }
}

From source file:com.piketec.jenkins.plugins.tpt.publisher.TPTReportPublisher.java

/**
 * Xml SAXparser// w w  w  .j  a v  a 2s  . c  o  m
 * 
 * @param xmlFile
 * @param tptFile
 * @param failedTests
 * @param reportDirOnRemote
 * @param executionConfiguration
 * @throws InterruptedException
 */
private void parse(FilePath xmlFile, TPTFile tptFile, ArrayList<TPTTestCase> failedTests,
        String reportDirOnRemote, String executionConfiguration, TptLogger logger) throws InterruptedException {
    SAXParserFactory saxParserFactory = SAXParserFactory.newInstance();

    try {
        SAXParser saxParser = saxParserFactory.newSAXParser();
        TPTReportSAXHandler handler = new TPTReportSAXHandler(tptFile, failedTests, reportDirOnRemote,
                executionConfiguration);
        InputStream inputStream = xmlFile.read();
        try {
            saxParser.parse(inputStream, handler);
        } finally {
            IOUtils.closeQuietly(inputStream);
        }
    } catch (ParserConfigurationException | SAXException | IOException e) {
        logger.error(e.getMessage());
    }

}

From source file:org.peterbaldwin.client.android.delicious.DeliciousApiRequest.java

/**
 * {@inheritDoc}/* w  w  w .  j a  va  2s .  com*/
 */
public void run() {
    Message msg = mHandler.obtainMessage();
    msg.arg1 = mRequestType;
    msg.arg2 = mRequestId;
    msg.what = HANDLE_ERROR;
    msg.obj = "unknown error";
    boolean cacheUpdated = false;
    try {
        SAXParserFactory factory = SAXParserFactory.newInstance();
        SAXParser parser = factory.newSAXParser();
        XMLReader reader = parser.getXMLReader();

        ContentHandler handler = mResponseHandler.getContentHandler();
        reader.setContentHandler(handler);

        InputStream in = null;
        if (in == null && mUseCache && mCacheFile != null) {
            in = readFromCache();
        }
        if (in == null) {
            in = readFromNetwork();

            if (mUpdateCache && mCacheFile != null) {
                in = updateCache(in);
                cacheUpdated = true;
            }
        }
        try {
            InputSource input = new InputSource(in);
            long start = now();
            try {
                reader.parse(input);
            } finally {
                logTiming("parse", start);
            }
        } finally {
            in.close();
        }
        msg.what = HANDLE_DONE;
        msg.obj = mResponseHandler;
    } catch (ConnectionException e) {
        setError(msg, e);
        int statusCode = e.getStatusCode();
        if (statusCode == HttpStatus.SC_UNAUTHORIZED) {
            msg.what = HANDLE_AUTH_ERROR;
            msg.obj = "invalid username or password";
        } else {
            msg.what = HANDLE_ERROR;
            msg.obj = "unexpected response: " + statusCode;
        }
    } catch (IOException e) {
        setError(msg, e);
    } catch (ParserConfigurationException e) {
        setError(msg, e);
    } catch (SAXException e) {
        setError(msg, e);
    } catch (RuntimeException e) {
        setError(msg, e);
    } catch (Error e) {
        setError(msg, e);
    } finally {
        mHandler.sendMessage(msg);
    }

    if (msg.what != HANDLE_AUTH_ERROR && !cacheUpdated && mAlwaysUpdateCache && mCacheFile != null) {
        // If the authentication is valid, but the cache was not updated,
        // silently update the cache in the background after dispatching the
        // result to the handler.
        try {
            InputStream in = readFromNetwork();
            in = updateCache(in);
            in.close();
            Log.i(LOG_TAG, "cache file updated: " + mCacheFile);
        } catch (IOException e) {
            Log.e(LOG_TAG, "error updating cache", e);
        } catch (RuntimeException e) {
            Log.e(LOG_TAG, "error updating cache", e);
        } catch (Error e) {
            Log.e(LOG_TAG, "error updating cache", e);
        }
    }
}

From source file:es.mityc.firmaJava.libreria.utilidades.AnalizadorFicheroFirma.java

public void analizar(File fichero) {
    SAXParserFactory factoria = SAXParserFactory.newInstance();
    factoria.setNamespaceAware(true);//from w  w w  . j  a  v a2  s  .c  o m
    factoria.setValidating(false);
    FileInputStream fis = null;
    try {
        fis = new FileInputStream(fichero);
        SAXParser parser = factoria.newSAXParser();
        parser.parse(fis, this);
    } catch (ParserConfigurationException e) {
        log.error(e);
    } catch (SAXException e) {
        log.error(e);
    } catch (FileNotFoundException e) {
        log.error(e);
    } catch (IOException e) {
        log.error(e);
    } finally {
        if (fis != null) {
            try {
                fis.close();
            } catch (IOException e) {
            }
        }
    }
}

From source file:com.aurel.track.exchange.track.importer.ImporterDataParser.java

public List<ExchangeWorkItem> parse(File xml, Map<Integer, Integer> fieldMatcher) {
    this.fieldMatcher = fieldMatcher;
    //get a factory
    SAXParserFactory saxParserFactory = SAXParserFactory.newInstance();
    try {//w  w w  . j  av  a  2s  .co  m
        SAXParser saxParser = saxParserFactory.newSAXParser();
        LOGGER.debug("Data parser started...");
        saxParser.parse(xml, this);
        LOGGER.debug("Data parser done");
        return exchangeWorkItemsList;
    } catch (SAXException se) {
        LOGGER.error(ExceptionUtils.getStackTrace(se));
    } catch (ParserConfigurationException pce) {
        LOGGER.error(ExceptionUtils.getStackTrace(pce));
    } catch (IOException ie) {
        LOGGER.error(ExceptionUtils.getStackTrace(ie));
    }
    return null;
}

From source file:com.quinsoft.zeidon.standardoe.ActivateOisFromXmlStream.java

private ViewImpl read() {
    try {/*from   w w w  .j av a2  s. c o m*/
        SAXParserFactory factory = SAXParserFactory.newInstance();
        SAXParser saxParser = factory.newSAXParser();
        DefaultHandler handler = new SaxParserHandler();
        saxParser.parse(inputStream, handler);

        // If user wanted just one root remove others if we have more than one.
        // We don't want to abort the loading of entities in the middle of
        // the stream because that could throw off XML processing.
        EntityCursorImpl rootCursor = view.getViewCursor().getEntityCursor(lodDef.getRoot());
        if (control.contains(ActivateFlags.fSINGLE) && rootCursor.getEntityCount() > 1) {
            rootCursor.setFirst();
            while (rootCursor.setNext().isSet())
                rootCursor.dropEntity();
            rootCursor.setFirst();
        }

        if (selectedInstances.size() > 0)
            setCursors();
        else
            view.reset();

        return view;
    } catch (Exception e) {
        ZeidonException ze = ZeidonException.wrapException(e);
        if (locator != null)
            ze.appendMessage("Line/col = %d/%d", locator.getLineNumber(), locator.getColumnNumber());

        throw ze;
    }
}