Example usage for org.xml.sax XMLReader parse

List of usage examples for org.xml.sax XMLReader parse

Introduction

In this page you can find the example usage for org.xml.sax XMLReader parse.

Prototype

public void parse(String systemId) throws IOException, SAXException;

Source Link

Document

Parse an XML document from a system identifier (URI).

Usage

From source file:be.fedict.eidviewer.lib.file.imports.Version35XMLFile.java

public void load(File file) throws CertificateException, FileNotFoundException, SAXException, IOException,
        ParseException, DataConvertorException {
    logger.fine("Loading Version 35X XML File");

    XMLReader reader = null;

    certificateFactory = CertificateFactory.getInstance("X.509");
    DateFormat dateFormat = new SimpleDateFormat("dd.MM.yyyy");
    FileInputStream fis = new FileInputStream(file);

    reader = XMLReaderFactory.createXMLReader();
    reader.setContentHandler(this);
    reader.setErrorHandler(this);
    BufferedReader in = new BufferedReader(new InputStreamReader(fis));
    reader.parse(new InputSource(in));

    Identity identity = new Identity();
    identity.cardDeliveryMunicipality = discreteValues.get("issuing_municipality");
    identity.cardNumber = discreteValues.get("logical_nr");
    GregorianCalendar validityStartCalendar = new GregorianCalendar();
    validityStartCalendar.setTime(dateFormat.parse(discreteValues.get("date_begin")));
    identity.cardValidityDateBegin = validityStartCalendar;
    GregorianCalendar validityEndCalendar = new GregorianCalendar();
    validityEndCalendar.setTime(dateFormat.parse(discreteValues.get("date_end")));
    identity.cardValidityDateEnd = validityEndCalendar;
    identity.chipNumber = discreteValues.get("chip_nr");
    identity.dateOfBirth = (new DateOfBirthDataConvertor())
            .convert(discreteValues.get("date_of_birth").getBytes());
    identity.documentType = DocumentType.toDocumentType(discreteValues.get("type").getBytes());
    identity.duplicate = discreteValues.get("duplicata");
    identity.gender = discreteValues.get("gender").equals("M") ? Gender.MALE : Gender.FEMALE;

    TextFormatHelper.setFirstNamesFromString(identity, discreteValues.get("name"));
    identity.name = discreteValues.get("surname");

    identity.nationalNumber = discreteValues.get("national_nr");
    identity.nationality = discreteValues.get("nationality");
    identity.nobleCondition = discreteValues.get("nobility");
    identity.placeOfBirth = discreteValues.get("location_of_birth");
    identity.specialStatus = SpecialStatus.toSpecialStatus(discreteValues.get("specialStatus"));
    eidData.setIdentity(identity);/*from   w ww  . j  av  a2  s  .c  o  m*/

    Address address = new Address();
    address.municipality = discreteValues.get("municipality");
    address.zip = discreteValues.get("zip");
    address.streetAndNumber = discreteValues.get("street");
    eidData.setAddress(address);

    eidData.setPhoto(pictureData);

    X509Utilities.setCertificateChainsFromCertificates(eidData, rootCert, citizenCert, authenticationCert,
            signingCert, rrnCert);
}

From source file:com.sonicle.webtop.contacts.io.input.ContactExcelFileReader.java

private void readXlsxContacts(File file, BeanHandler beanHandler) throws IOException, FileReaderException {
    OPCPackage opc = null;/* www.j av  a 2  s.  co m*/
    HashMap<String, Integer> columnIndexes = listXlsxColumnIndexes(file);
    XlsRowHandler rowHandler = new XlsRowHandler(this, columnIndexes, beanHandler);

    try {
        opc = OPCPackage.open(file, PackageAccess.READ);
        XSSFReader reader = new XSSFReader(opc);
        ReadOnlySharedStringsTable strings = new ReadOnlySharedStringsTable(opc);
        StylesTable styles = reader.getStylesTable();

        XlsxRowsHandler rowsHandler = null;
        XSSFReader.SheetIterator sit = (XSSFReader.SheetIterator) reader.getSheetsData();
        while (sit.hasNext()) {
            InputStream is = null;
            try {
                is = sit.next();
                if (StringUtils.equals(sit.getSheetName(), sheet)) {
                    XMLReader xmlReader = SAXHelper.newXMLReader();
                    rowsHandler = new XlsxRowsHandler(is, headersRow, firstDataRow, lastDataRow, rowHandler);
                    ContentHandler xhandler = new XSSFSheetXMLHandler(styles, null, strings, rowsHandler, fmt,
                            false);
                    xmlReader.setContentHandler(xhandler);
                    xmlReader.parse(new InputSource(is));
                }
            } catch (SAXException | ParserConfigurationException ex) {
                throw new FileReaderException(ex, "Error processing file content");
            } catch (NullPointerException ex) {
                // Thrown when stream is forcibly closed. Simply ignore this!
            } finally {
                IOUtils.closeQuietly(is);
            }
            if (rowsHandler != null)
                break;
        }

    } catch (OpenXML4JException | SAXException ex) {
        throw new FileReaderException(ex, "Error opening file");
    } finally {
        IOUtils.closeQuietly(opc);
    }
}

From source file:ee.ria.xroad.proxy.serverproxy.MetadataServiceHandlerImpl.java

/**
 * reads a WSDL from input stream, modifies it and returns input stream to the result
 * @param wsdl/*from   w  ww  . j a v a2  s  .  c  o  m*/
 * @return
 */
private InputStream modifyWsdl(InputStream wsdl) {
    try {
        TransformerHandler serializer = TRANSFORMER_FACTORY.newTransformerHandler();
        StringWriter writer = new StringWriter();
        StreamResult result = new StreamResult(writer);
        serializer.setResult(result);

        OverwriteAttributeFilter filter = getModifyWsdlFilter();
        filter.setContentHandler(serializer);

        XMLReader xmlreader = XMLReaderFactory.createXMLReader();
        xmlreader.setFeature("http://xml.org/sax/features/namespace-prefixes", true);
        xmlreader.setProperty("http://xml.org/sax/properties/lexical-handler", new CommentsHandler(serializer));
        xmlreader.setContentHandler(filter);

        // parse XML, filter it, put end result to a String
        xmlreader.parse(new InputSource(wsdl));
        String resultString = writer.toString();
        log.debug("result of WSDL cleanup: {}", resultString);

        // offer InputStream into processed String
        return new ByteArrayInputStream(resultString.getBytes(StandardCharsets.UTF_8));
    } catch (IOException | SAXException | TransformerConfigurationException e) {
        throw new RuntimeException(e);
    }
}

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

@Override
public boolean execute() {
    URL url;//from w w w.j a v  a  2s  .  com
    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 . j a  v a2 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.commonsware.android.EMusicDownloader.SingleAlbum.java

private void getInfoFromXML() {

    //Show a progress dialog while reading XML
    final ProgressDialog dialog = ProgressDialog.show(this, "", getString(R.string.loading), true, true);
    setProgressBarIndeterminateVisibility(true);

    Thread t3 = new Thread() {
        public void run() {

            waiting(200);// ww w.  j  ava 2 s.  c o  m

            try {

                //Log.d("EMD - ","About to parse");

                URL url = new URL(urlAddress);
                SAXParserFactory spf = SAXParserFactory.newInstance();
                SAXParser sp = spf.newSAXParser();
                XMLReader xr = sp.getXMLReader();
                XMLHandlerSingleAlbum myXMLHandler = new XMLHandlerSingleAlbum();
                xr.setContentHandler(myXMLHandler);
                xr.parse(new InputSource(url.openStream()));

                //Log.d("EMD - ","Done Parsing");

                statuscode = myXMLHandler.statuscode;
                if (statuscode != 200 && statuscode != 206) {
                    throw new Exception();
                }

                genre = myXMLHandler.genre;
                genreId = myXMLHandler.genreId;
                labelId = myXMLHandler.labelId;
                label = myXMLHandler.label;
                date = myXMLHandler.releaseDate;
                rating = myXMLHandler.rating;
                imageURL = myXMLHandler.imageURL;
                artist = myXMLHandler.artist;
                artistId = myXMLHandler.artistId;

                //Log.d("EMD - ","Set genre etc..");

                numberOfTracks = myXMLHandler.nItems;
                trackNames = myXMLHandler.tracks;
                //sampleAddresses = myXMLHandler.sampleAddress;
                //sampleExists = myXMLHandler.sampleExists;
                //vSamplesExist = myXMLHandler.samplesExist;

                handlerSetContent.sendEmptyMessage(0);
                dialog.dismiss();
                updateImage();

            } catch (Exception e) {
                final Exception ef = e;
                nameTextView.post(new Runnable() {
                    public void run() {
                        nameTextView.setText(R.string.couldnt_get_album_info);
                    }
                });

            }

            //Remove Progress Dialog
            if (dialog.isShowing()) {
                dialog.dismiss();
            }
            handlerDoneLoading.sendEmptyMessage(0);
        }
    };
    t3.start();
}

From source file:com.thruzero.common.core.infonode.builder.SaxInfoNodeBuilder.java

/** construct complete {@code InfoNodeElement} from dom. */
protected InfoNodeElement doBuildInfoNode(final String xml, final InfoNodeElement targetNode,
        final InfoNodeFilterChain infoNodeFilterChain) throws Exception {
    handlePrimaryKey(targetNode);/* w  w w  . j  av  a 2s.  c o  m*/
    if (StringUtils.isNotEmpty(xml)) {
        XMLReader parser = XMLReaderFactory.createXMLReader();
        InfoNodeSaxHandler dnHandler = new InfoNodeSaxHandler(targetNode, infoNodeFilterChain); // state for this build is kept in this InfoNode Handler instance

        parser.setContentHandler(dnHandler);
        parser.setErrorHandler(dnHandler);
        parser.setFeature("http://xml.org/sax/features/validation", false);

        InputSource input = new InputSource(new StringReader(xml));
        parser.parse(input);
    }
    handleRootNode(targetNode);

    return targetNode;
}

From source file:com.mirth.connect.model.converters.ER7Serializer.java

/**
 * Returns an ER7-encoded HL7 message given an XML-encoded HL7 message.
 * //  www  . j  a v  a  2  s  . com
 * @param source
 *            a XML-encoded HL7 message.
 * @return
 */
public String fromXML(String source) throws SerializerException {
    try {
        if (useStrictParser) {
            return pipeParser.encode(xmlParser.parse(source));
        } else {
            /*
             * The delimiters below need to come from the XML somehow. The
             * ER7 handler should take care of it TODO: Ensure you get these
             * elements from the XML
             */

            String segmentSeparator = "\r";
            String fieldSeparator = getNodeValue(source, "<MSH.1>", "</MSH.1>");

            if (StringUtils.isEmpty(fieldSeparator)) {
                fieldSeparator = "|";
            }

            String componentSeparator = "^";
            String repetitionSeparator = "~";
            String subcomponentSeparator = "&";
            String escapeCharacter = "\\";

            /*
             * Our delimiters usually look like this:
             * <MSH.2>^~\&amp;</MSH.2> We need to decode XML entities
             */
            String separators = getNodeValue(source, "<MSH.2>", "</MSH.2>").replaceAll("&amp;", "&");

            if (separators.length() == 4) {
                // usually ^
                componentSeparator = separators.substring(0, 1);
                // usually ~
                repetitionSeparator = separators.substring(1, 2);
                // usually \
                escapeCharacter = separators.substring(2, 3);
                // usually &
                subcomponentSeparator = separators.substring(3, 4);
            }

            XMLEncodedHL7Handler handler = new XMLEncodedHL7Handler(segmentSeparator, fieldSeparator,
                    componentSeparator, repetitionSeparator, escapeCharacter, subcomponentSeparator, true);
            XMLReader reader = XMLReaderFactory.createXMLReader();
            reader.setContentHandler(handler);
            reader.setErrorHandler(handler);

            /*
             * Parse, but first replace all spaces between brackets. This
             * fixes pretty-printed XML we might receive.
             */
            reader.parse(new InputSource(new StringReader(
                    source.replaceAll("\\s*<([^/][^>]*)>", "<$1>").replaceAll("<(/[^>]*)>\\s*", "<$1>"))));
            return handler.getOutput().toString();
        }
    } catch (Exception e) {
        throw new SerializerException(e);
    }
}

From source file:edu.harvard.iq.dataverse.ingest.tabulardata.impl.plugins.xlsx.XLSXFileReader.java

public void processSheet(InputStream inputStream, DataTable dataTable, PrintWriter tempOut) throws Exception {
    dbglog.info("entering processSheet");
    OPCPackage pkg = OPCPackage.open(inputStream);
    XSSFReader r = new XSSFReader(pkg);
    SharedStringsTable sst = r.getSharedStringsTable();

    XMLReader parser = fetchSheetParser(sst, dataTable, tempOut);

    // rId2 found by processing the Workbook
    // Seems to either be rId# or rSheet#
    InputStream sheet1 = r.getSheet("rId1");
    InputSource sheetSource = new InputSource(sheet1);
    parser.parse(sheetSource);
    sheet1.close();/*from  ww w  .j a  v  a  2s.com*/
}

From source file:cm.aptoide.pt.ManageRepo.java

private Vector<String> getRemoteServLst(String file) {
    SAXParserFactory spf = SAXParserFactory.newInstance();
    Vector<String> out = new Vector<String>();
    try {//from   w  w w.  j av  a2s  .  co m
        SAXParser sp = spf.newSAXParser();
        XMLReader xr = sp.getXMLReader();
        NewServerRssHandler handler = new NewServerRssHandler(this);
        xr.setContentHandler(handler);

        InputStreamReader isr = new FileReader(new File(file));
        InputSource is = new InputSource(isr);
        xr.parse(is);
        File xml_file = new File(file);
        xml_file.delete();
        out = handler.getNewSrvs();
    } catch (IOException e) {
        e.printStackTrace();
    } catch (SAXException e) {
        e.printStackTrace();
    } catch (ParserConfigurationException e) {
        e.printStackTrace();
    }
    return out;
}