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.sparsity.dex.etl.config.impl.XMLConfigurationProvider.java

public void load() throws DexUtilsException {
    SAXParserFactory factory = SAXParserFactory.newInstance();
    factory.setValidating(true);/* w w w .j  ava 2 s.  co m*/
    factory.setNamespaceAware(true);

    try {
        SAXParser parser = factory.newSAXParser();
        DexUtilsHandler handler = new DexUtilsHandler(config);
        parser.parse(xml.getAbsolutePath(), handler);
    } catch (Exception e) {
        String msg = new String("Parsing error.");
        log.error(msg, e);
        throw new DexUtilsException(msg, e);
    }
    log.info("Loaded configuration from " + xml.getAbsolutePath());
}

From source file:captureplugin.drivers.dreambox.connector.DreamboxConnector.java

/**
 * @param service/*from w ww  .  j a v a  2s .co m*/
 *          Service-ID
 * @return Data of specific service
 */
private TreeMap<String, String> getServiceData(String service) {
    if (!mConfig.hasValidAddress()) {
        return null;
    }
    try {
        InputStream stream = openStreamForLocalUrl("/web/getservices?sRef=" + service);
        SAXParser saxParser = SAXParserFactory.newInstance().newSAXParser();
        DreamboxHandler handler = new DreamboxHandler();
        saxParser.parse(stream, handler);
        return handler.getData();
    } catch (ParserConfigurationException e) {
        e.printStackTrace();
    } catch (SAXException e) {
        e.printStackTrace();
    } catch (MalformedURLException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

    return null;
}

From source file:it.openyoureyes.test.OpenCellId.java

private String parseImage(HttpEntity entity, DefaultHandler dd) throws IOException {
    String result = "";
    String line;// ww  w .  ja v  a  2s . com

    try {

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

        /* Parse the xml-data from our URL. */
        xr.parse(new InputSource(entity.getContent()));

    } catch (ParserConfigurationException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (SAXException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } finally {
        entity.consumeContent();
    }
    return result;
}

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

public void run() {
    try {/*from   www .  j av a  2s . 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:io.lightlink.excel.StreamingExcelTransformer.java

private void processSheet(byte[] bytes, OutputStream out, ExcelStreamVisitor visitor)
        throws ParserConfigurationException, SAXException, IOException {

    SAXParserFactory factory = SAXParserFactory.newInstance();
    SAXParser saxParser = factory.newSAXParser();
    Writer printWriter = new OutputStreamWriter(out, "UTF-8");

    saxParser.parse(new ByteArrayInputStream(bytes),
            new SheetTemplateHandler(printWriter, sharedStrings, visitor));

    printWriter.flush();/*w w  w. j a v  a  2s  .  co m*/

}

From source file:fr.lemet.application.keolis.Keolis.java

/**
 * @param <ObjetKeolis> type d'objet Keolis.
 * @param url           url./*from   w  w w  . jav a  2 s .com*/
 * @param handler       handler.
 * @return liste d'objets Keolis.
 * @throws fr.lemet.transportscommun.util.ErreurReseau    en cas d'erreur rseau.
 * @throws KeolisException en cas d'erreur lors de l'appel aux API Keolis.
 */
@SuppressWarnings("unchecked")
private <ObjetKeolis> List<ObjetKeolis> appelKeolis(String url, KeolisHandler<ObjetKeolis> handler)
        throws ErreurReseau {
    LOG_YBO.debug("Appel d'une API Keolis sur l'url '" + url + '\'');
    long startTime = System.nanoTime() / 1000;
    HttpClient httpClient = HttpUtils.getHttpClient();
    HttpUriRequest httpPost = new HttpPost(url);
    Answer<?> answer;
    try {
        HttpResponse reponse = httpClient.execute(httpPost);
        ByteArrayOutputStream ostream = new ByteArrayOutputStream();
        reponse.getEntity().writeTo(ostream);
        SAXParserFactory factory = SAXParserFactory.newInstance();
        SAXParser parser = factory.newSAXParser();
        parser.parse(new ByteArrayInputStream(ostream.toByteArray()), handler);
        answer = handler.getAnswer();
    } catch (IOException socketException) {
        throw new ErreurReseau(socketException);
    } catch (SAXException saxException) {
        throw new ErreurReseau(saxException);
    } catch (ParserConfigurationException exception) {
        throw new KeolisException("Erreur lors de l'appel  l'API keolis", exception);
    }
    if (answer == null || answer.getStatus() == null || !"0".equals(answer.getStatus().getCode())) {
        throw new ErreurReseau();
    }
    long elapsedTime = System.nanoTime() / 1000 - startTime;
    LOG_YBO.debug("Rponse de Keolis en " + elapsedTime + "s");
    return (List<ObjetKeolis>) answer.getData();
}

From source file:org.transdroid.search.RssFeedSearch.PretomeAdapter.java

@Override
protected RssParser getRssParser(final String url) {
    return new RssParser(url) {
        @Override//from  w  ww .jav a  2 s  .  c  o  m
        public void parse() throws ParserConfigurationException, SAXException, IOException {
            HttpClient httpclient = initialise();
            HttpResponse result = httpclient.execute(new HttpGet(url));
            //FileInputStream urlInputStream = new FileInputStream("/sdcard/rsstest2.txt");
            SAXParserFactory spf = SAXParserFactory.newInstance();
            SAXParser sp = spf.newSAXParser();
            InputSource is = new InputSource();
            // Pretome supplies UTF-8 compatible character data yet incorrectly defined a windows-1251 encode: override
            is.setEncoding("UTF-8");
            is.setCharacterStream(new InputStreamReader(result.getEntity().getContent()));
            sp.parse(is, this);
        }
    };
}

From source file:es.prodevelop.gvsig.mini.tasks.weather.WeatherFunctionality.java

@Override
public boolean execute() {
    URL url;/*from   ww w  . j  a  v a  2  s .c o m*/
    try {
        String queryString = "http://ws.geonames.org/findNearbyPlaceName?lat=" + lat + "&lng=" + lon;
        InputStream is = Utils.openConnection(queryString);
        BufferedInputStream bis = new BufferedInputStream(is);

        /* Read bytes to the Buffer until there is nothing more to read(-1). */
        ByteArrayBuffer baf = new ByteArrayBuffer(50);
        int current = 0;
        while ((current = bis.read()) != -1) {
            if (isCanceled()) {
                res = TaskHandler.CANCELED;
                return true;
            }
            baf.append((byte) current);

        }

        place = this.parseGeoNames(baf.toByteArray());

        queryString = "http://www.google.com/ig/api?weather=" + place;
        /* Replace blanks with HTML-Equivalent. */
        url = new URL(queryString.replace(" ", "%20"));

        /* Get a SAXParser from the SAXPArserFactory. */
        SAXParserFactory spf = SAXParserFactory.newInstance();
        SAXParser sp = spf.newSAXParser();

        /* Get the XMLReader of the SAXParser we created. */
        XMLReader xr = sp.getXMLReader();

        /*
         * Create a new ContentHandler and apply it to the XML-Reader
         */
        GoogleWeatherHandler gwh = new GoogleWeatherHandler();
        xr.setContentHandler(gwh);

        if (isCanceled()) {
            res = TaskHandler.CANCELED;
            return true;
        }
        /* Parse the xml-data our URL-call returned. */
        xr.parse(new InputSource(url.openStream()));

        if (isCanceled()) {
            res = TaskHandler.CANCELED;
            return true;
        }
        /* Our Handler now provides the parsed weather-data to us. */
        ws = gwh.getWeatherSet();

        ws.place = place;
        res = TaskHandler.FINISHED;
        // map.showWeather(ws);
    } catch (IOException e) {
        if (e instanceof UnknownHostException) {
            res = TaskHandler.NO_RESPONSE;
        }
    } catch (Exception e) {
        log.log(Level.SEVERE, "", e);
        res = TaskHandler.ERROR;
    } finally {
        //         super.stop();
        return true;
    }
}

From source file:architecture.common.util.L10NUtils.java

private void loadProps(String resource, boolean breakOnError) throws IOException {

    HashSet<URL> hashset = new HashSet<URL>();
    if (log.isDebugEnabled()) {
        log.debug((new StringBuilder()).append("Searching ").append(resource).toString());
    }/*from   w w  w. jav  a  2 s.c  om*/
    Enumeration<URL> urls = Thread.currentThread().getContextClassLoader().getResources(resource);
    if (urls != null) {
        URL url;
        for (; urls.hasMoreElements(); hashset.add(url)) {
            url = urls.nextElement();
            if (log.isDebugEnabled())
                log.debug((new StringBuilder()).append("Adding ").append(url).toString());
        }
    }

    for (URL url : hashset) {
        if (log.isDebugEnabled())
            log.debug((new StringBuilder()).append("Loading from ").append(url).toString());
        InputStream is = null;
        try {
            is = url.openStream();
            InputSource input = new InputSource(is);
            SAXParserFactory factory = SAXParserFactory.newInstance();
            factory.setNamespaceAware(true);
            XMLReader xmlreader = factory.newSAXParser().getXMLReader();
            I18nParsingHandler handler = new I18nParsingHandler();
            xmlreader.setContentHandler(handler);
            xmlreader.setDTDHandler(handler);
            xmlreader.setEntityResolver(handler);
            xmlreader.setErrorHandler(handler);
            xmlreader.parse(input);
            localizers.addAll(handler.localizers);
        } catch (IOException e) {
            if (log.isDebugEnabled())
                log.debug((new StringBuilder()).append("Skipping ").append(url).toString());
            if (breakOnError)
                throw e;
        } catch (Exception e) {
            log.error(e);
        } finally {
            if (is != null)
                IOUtils.closeQuietly(is);
        }
    }

}

From source file:com.esri.geoevent.solutions.adapter.cot.CoTAdapterInbound.java

public CoTAdapterInbound(AdapterDefinition adapterDefinition, String guid)
        throws ConfigurationException, ComponentException {
    super(adapterDefinition);

    this.guid = guid;

    messageParser = new MessageParser(this);
    saxFactory = SAXParserFactory.newInstance();
    try {/*from   w ww  . j a  v a 2  s  . c om*/
        saxParser = saxFactory.newSAXParser();
    } catch (ParserConfigurationException e) {
        e.printStackTrace();
        saxParser = null;
        log.error(e);
        log.error(e.getStackTrace());

    } catch (SAXException e) {
        e.printStackTrace();
        saxParser = null;
        log.error(e);
        log.error(e.getStackTrace());
    }

}