Example usage for javax.xml.stream XMLStreamReader next

List of usage examples for javax.xml.stream XMLStreamReader next

Introduction

In this page you can find the example usage for javax.xml.stream XMLStreamReader next.

Prototype

public int next() throws XMLStreamException;

Source Link

Document

Get next parsing event - a processor may return all contiguous character data in a single chunk, or it may split it into several chunks.

Usage

From source file:com.marklogic.client.functionaltest.BasicJavaClientREST.java

/**
 * Convert XMLStreamReader To String/*  w  w  w . j  a  v  a  2  s .c om*/
 * @param XMLStreamReader
 * @return String
 * @throws XMLStreamException, TransformerException, IOException, ParserConfigurationException, SAXException
 */
public String convertXMLStreamReaderToString(XMLStreamReader reader) throws XMLStreamException,
        TransformerException, IOException, ParserConfigurationException, SAXException {
    String str = null;
    while (reader.hasNext()) {
        reader.next();
        int a = reader.getEventType();
        if (reader.hasText())
            if (reader.getText() != "null")
                str = str + reader.getText().trim();
    }
    return str;
}

From source file:com.widowcrawler.exo.parse.Parser.java

public Sitemap parse(InputStream inputStream) throws XMLStreamException, SitemapParseException {

    final XMLStreamReader reader = XMLInputFactory.newInstance().createXMLStreamReader(inputStream, "utf-8");

    final Sitemap retval = new Sitemap(new HashSet<>());

    final Set<SitemapURL> sitemapURLs = new HashSet<>();
    SitemapURL.Builder urlBuilder = null;
    String urlContent;//  w w  w.jav a2  s  .  c om

    reader.getEventType();

    while (reader.hasNext()) {
        switch (state) {
        case START:
            reader.nextTag();

            if (StringUtils.equalsIgnoreCase(reader.getLocalName(), URLSET_TAG_NAME)) {
                state = State.URLSET;
            } else if (StringUtils.equalsIgnoreCase(reader.getLocalName(), SITEMAPINDEX_TAG_NAME)) {
                state = State.SITEMAPINDEX;
            } else {
                String message = "Invalid root element. Must be either urlset or sitemapindex";
                logger.error(message);
                throw new SitemapParseException(message);
            }

            break;

        case END:
            // consume all end tags
            if (reader.getEventType() != XMLStreamConstants.END_ELEMENT) {
                String message = decorate("There should be only one root element in each sitemap.xml",
                        reader.getLocation());
                logger.error(message);
                throw new SitemapParseException(message);
            }

            reader.next();
            break;

        /////////////////////
        // URLSET Hierarchy
        /////////////////////
        case URLSET:
            // If we're done with the URLs, we're done overall
            if (reader.nextTag() == XMLStreamConstants.END_ELEMENT) {
                state = State.END;
                break;
            }

            // Check that we're entering into a <url> element
            if (!StringUtils.equalsIgnoreCase(reader.getLocalName(), URL_TAG_NAME)) {
                String message = "A <urlset> element can only contain <url> elements. Found: "
                        + reader.getLocalName();
                logger.error(message);
                throw new SitemapParseException(message);
            }

            urlBuilder = new SitemapURL.Builder();
            state = State.URL;
            break;

        case URL:
            reader.nextTag();

            if (reader.getEventType() == XMLStreamConstants.START_ELEMENT) {
                //logger.info("reader.getLocalName(): " + reader.getLocalName());
                switch (StringUtils.lowerCase(reader.getLocalName())) {
                case LOC_TAG_NAME:
                    state = State.URL_PROP_LOC;
                    break;
                case LASTMOD_TAG_NAME:
                    state = State.URL_PROP_LASTMOD;
                    break;
                case CHANGEFREQ_TAG_NAME:
                    state = State.URL_PROP_CHANGEFREQ;
                    break;
                case PRIORITY_TAG_NAME:
                    state = State.URL_PROP_PRIORITY;
                    break;
                case MOBILE_TAG_NAME:
                    state = State.URL_PROP_MOBILE;
                    break;
                default:
                    String message = "Unexpected tag in url: " + reader.getLocalName();
                    logger.error(message);
                    throw new SitemapParseException(message);
                }
            } else if (reader.getEventType() == XMLStreamConstants.END_ELEMENT) {
                // we're done collecting the data for this URL
                assert urlBuilder != null;
                sitemapURLs.add(urlBuilder.build());
                urlBuilder = new SitemapURL.Builder();
                state = State.URLSET;
            }
            break;

        case URL_PROP_LOC:
            urlContent = reader.getElementText();

            try {
                assert urlBuilder != null;
                urlBuilder.withLocation(new URL(StringUtils.trimToNull(urlContent)));

            } catch (MalformedURLException ex) {
                String message = String.format("Malformed URL found: %s", urlContent);
                logger.error(message);
                throw new SitemapParseException(message);
            }
            state = State.URL;
            break;

        case URL_PROP_LASTMOD:
            assert urlBuilder != null;
            urlBuilder.withLastModified(DateTime.parse(reader.getElementText()));
            state = State.URL;
            break;

        case URL_PROP_CHANGEFREQ:
            assert urlBuilder != null;
            urlBuilder.withChangeFrequency(ChangeFreq.valueOf(StringUtils.upperCase(reader.getElementText())));
            state = State.URL;
            break;

        case URL_PROP_PRIORITY:
            assert urlBuilder != null;
            urlBuilder.withPriority(Double.valueOf(reader.getElementText()));
            state = State.URL;
            break;

        case URL_PROP_MOBILE:
            assert urlBuilder != null;
            urlBuilder.withIsMobileContent(true);
            // consume until "end tag" of self-closing tag
            // Also works if someone puts content in
            reader.getElementText();
            state = State.URL;
            break;

        ///////////////////////////
        // SITEMAPINDEX Hierarchy
        ///////////////////////////
        case SITEMAPINDEX:
            // If we're done with all the Sitemaps, we're done overall
            if (reader.nextTag() == XMLStreamConstants.END_ELEMENT) {
                state = State.END;
                break;
            }

            state = State.SITEMAP;
            break;

        case SITEMAP:
            if (!StringUtils.equalsIgnoreCase(reader.getLocalName(), SITEMAP_TAG_NAME)) {
                throw new SitemapParseException("A <sitemapindex> element can only contain <sitemap> elements");
            }

            reader.nextTag();

            if (reader.getEventType() == XMLStreamConstants.START_ELEMENT) {
                switch (StringUtils.lowerCase(reader.getLocalName())) {
                case LOC_TAG_NAME:
                    state = State.URL_PROP_LOC;
                    break;
                case LASTMOD_TAG_NAME:
                    state = State.URL_PROP_LASTMOD;
                    break;
                default:
                    throw new SitemapParseException("Unexpected tag in sitemap: " + reader.getLocalName());
                }
            } else if (reader.getEventType() == XMLStreamConstants.END_ELEMENT) {
                // we're done collecting the data for this URL
                assert urlBuilder != null;
                sitemapURLs.add(urlBuilder.build());
                urlBuilder = new SitemapURL.Builder();
                state = State.URLSET;
            }

        case SITEMAP_PROP_LOC:
            urlContent = reader.getElementText();

            try {
                URL sitemapURL = new URL(StringUtils.trimToNull(urlContent));

                Sitemap temp = Retry.retry(() -> {
                    try {
                        return Exo.parse(sitemapURL.toString());
                    } catch (Exception ex) {
                        throw new RuntimeException(ex);
                    }
                });

                retval.merge(temp);

            } catch (MalformedURLException ex) {
                String message = String.format("Malformed URL found: %s", urlContent);
                logger.error(message);
                throw new SitemapParseException(message);

            } catch (InterruptedException e) {
                logger.warn("Thread interrupted while (re)trying");
                Thread.currentThread().interrupt();

            } catch (RetryFailedException e) {
                String message = String.format("Failed to retrieve sitemap of sitemap index at %s", urlContent);
                logger.error(message);
                throw new SitemapParseException(message);
            }

            state = State.URL;
            break;

        case SITEMAP_PROP_LASTMOD:
            // Do nothing with this data for now
            reader.getElementText();
            break;
        }

        //System.out.println(state);
    }

    return retval.merge(new Sitemap(sitemapURLs));
}

From source file:com.ibm.bi.dml.runtime.controlprogram.parfor.opt.PerfTestTool.java

/**
 * /*from ww w  . j a  v a  2  s .  c o  m*/
 * @param fname
 * @throws XMLStreamException
 * @throws IOException
 */
private static void readProfile(String fname) throws XMLStreamException, IOException {
    //init profile map
    _profile = new HashMap<Integer, HashMap<Integer, CostFunction>>();

    //read existing profile
    FileInputStream fis = new FileInputStream(fname);

    try {
        //xml parsing
        XMLInputFactory xif = XMLInputFactory.newInstance();
        XMLStreamReader xsr = xif.createXMLStreamReader(fis);

        int e = xsr.nextTag(); // profile start

        while (true) //read all instructions
        {
            e = xsr.nextTag(); // instruction start
            if (e == XMLStreamConstants.END_ELEMENT)
                break; //reached profile end tag

            //parse instruction
            int ID = Integer.parseInt(xsr.getAttributeValue(null, XML_ID));
            //String name = xsr.getAttributeValue(null, XML_NAME).trim().replaceAll(" ", Lops.OPERAND_DELIMITOR);
            HashMap<Integer, CostFunction> tmp = new HashMap<Integer, CostFunction>();
            _profile.put(ID, tmp);

            while (true) {
                e = xsr.nextTag(); // cost function start
                if (e == XMLStreamConstants.END_ELEMENT)
                    break; //reached instruction end tag

                //parse cost function
                TestMeasure m = TestMeasure.valueOf(xsr.getAttributeValue(null, XML_MEASURE));
                TestVariable lv = TestVariable.valueOf(xsr.getAttributeValue(null, XML_VARIABLE));
                InternalTestVariable[] pv = parseTestVariables(
                        xsr.getAttributeValue(null, XML_INTERNAL_VARIABLES));
                DataFormat df = DataFormat.valueOf(xsr.getAttributeValue(null, XML_DATAFORMAT));
                int tDefID = getTestDefID(m, lv, df, pv);

                xsr.next(); //read characters
                double[] params = parseParams(xsr.getText());
                boolean multidim = _regTestDef.get(tDefID).getInternalVariables().length > 1;
                CostFunction cf = new CostFunction(params, multidim);
                tmp.put(tDefID, cf);

                xsr.nextTag(); // cost function end
                //System.out.println("added cost function");
            }
        }
        xsr.close();
    } finally {
        IOUtilFunctions.closeSilently(fis);
    }

    //mark profile as successfully read
    _flagReadData = true;
}

From source file:davmail.exchange.ews.EWSMethod.java

protected void processResponseStream(InputStream inputStream) {
    responseItems = new ArrayList<Item>();
    XMLStreamReader reader = null;
    try {/*from ww w .j  a  va 2s.  c  o  m*/
        inputStream = new FilterInputStream(inputStream) {
            int totalCount;
            int lastLogCount;

            @Override
            public int read(byte[] buffer, int offset, int length) throws IOException {
                int count = super.read(buffer, offset, length);
                totalCount += count;
                if (totalCount - lastLogCount > 1024 * 128) {
                    DavGatewayTray.debug(new BundleMessage("LOG_DOWNLOAD_PROGRESS",
                            String.valueOf(totalCount / 1024), EWSMethod.this.getURI()));
                    DavGatewayTray.switchIcon();
                    lastLogCount = totalCount;
                }
                return count;
            }
        };
        reader = XMLStreamUtil.createXMLStreamReader(inputStream);
        while (reader.hasNext()) {
            reader.next();
            handleErrors(reader);
            if (serverVersion == null && XMLStreamUtil.isStartTag(reader, "ServerVersionInfo")) {
                String majorVersion = getAttributeValue(reader, "MajorVersion");
                if ("14".equals(majorVersion)) {
                    String minorVersion = getAttributeValue(reader, "MinorVersion");
                    if ("0".equals(minorVersion)) {
                        serverVersion = "Exchange2010";
                    } else {
                        serverVersion = "Exchange2010_SP1";
                    }
                } else {
                    serverVersion = "Exchange2007_SP1";
                }
            } else if (XMLStreamUtil.isStartTag(reader, "RootFolder")) {
                includesLastItemInRange = "true"
                        .equals(reader.getAttributeValue(null, "IncludesLastItemInRange"));
            } else if (XMLStreamUtil.isStartTag(reader, responseCollectionName)) {
                handleItems(reader);
            } else {
                handleCustom(reader);
            }
        }
    } catch (XMLStreamException e) {
        LOGGER.error("Error while parsing soap response: " + e, e);
        if (reader != null) {
            try {
                LOGGER.error("Current text: " + reader.getText());
            } catch (IllegalStateException ise) {
                LOGGER.error(e + " " + e.getMessage());
            }
        }
    }
    if (errorDetail != null) {
        LOGGER.debug(errorDetail);
    }
}

From source file:com.liferay.portal.util.LocalizationImpl.java

public String getLocalization(String xml, String requestedLanguageId, boolean useDefault) {

    String value = _getCachedValue(xml, requestedLanguageId, useDefault);

    if (value != null) {
        return value;
    } else {//from ww  w.  j  ava  2s. c o  m
        value = StringPool.BLANK;
    }

    String systemDefaultLanguageId = LocaleUtil.toLanguageId(LocaleUtil.getDefault());

    String priorityLanguageId = null;

    Locale requestedLocale = LocaleUtil.fromLanguageId(requestedLanguageId);

    if (useDefault && LanguageUtil.isDuplicateLanguageCode(requestedLocale.getLanguage())) {

        Locale priorityLocale = LanguageUtil.getLocale(requestedLocale.getLanguage());

        if (!requestedLanguageId.equals(priorityLanguageId)) {
            priorityLanguageId = LocaleUtil.toLanguageId(priorityLocale);
        }
    }

    if (!Validator.isXml(xml)) {
        if (useDefault || requestedLanguageId.equals(systemDefaultLanguageId)) {

            value = xml;
        }

        _setCachedValue(xml, requestedLanguageId, useDefault, value);

        return value;
    }

    XMLStreamReader xmlStreamReader = null;

    ClassLoader portalClassLoader = PortalClassLoaderUtil.getClassLoader();

    Thread currentThread = Thread.currentThread();

    ClassLoader contextClassLoader = currentThread.getContextClassLoader();

    try {
        if (contextClassLoader != portalClassLoader) {
            currentThread.setContextClassLoader(portalClassLoader);
        }

        XMLInputFactory xmlInputFactory = XMLInputFactory.newInstance();

        xmlStreamReader = xmlInputFactory.createXMLStreamReader(new UnsyncStringReader(xml));

        String defaultLanguageId = StringPool.BLANK;

        // Skip root node

        if (xmlStreamReader.hasNext()) {
            xmlStreamReader.nextTag();

            defaultLanguageId = xmlStreamReader.getAttributeValue(null, _DEFAULT_LOCALE);

            if (Validator.isNull(defaultLanguageId)) {
                defaultLanguageId = systemDefaultLanguageId;
            }
        }

        // Find specified language and/or default language

        String defaultValue = StringPool.BLANK;
        String priorityValue = StringPool.BLANK;

        while (xmlStreamReader.hasNext()) {
            int event = xmlStreamReader.next();

            if (event == XMLStreamConstants.START_ELEMENT) {
                String languageId = xmlStreamReader.getAttributeValue(null, _LANGUAGE_ID);

                if (Validator.isNull(languageId)) {
                    languageId = defaultLanguageId;
                }

                if (languageId.equals(defaultLanguageId) || languageId.equals(priorityLanguageId)
                        || languageId.equals(requestedLanguageId)) {

                    String text = xmlStreamReader.getElementText();

                    if (languageId.equals(defaultLanguageId)) {
                        defaultValue = text;
                    }

                    if (languageId.equals(priorityLanguageId)) {
                        priorityValue = text;
                    }

                    if (languageId.equals(requestedLanguageId)) {
                        value = text;
                    }

                    if (Validator.isNotNull(value)) {
                        break;
                    }
                }
            } else if (event == XMLStreamConstants.END_DOCUMENT) {
                break;
            }
        }

        if (useDefault && Validator.isNotNull(priorityLanguageId) && Validator.isNull(value)
                && Validator.isNotNull(priorityValue)) {

            value = priorityValue;
        }

        if (useDefault && Validator.isNull(value)) {
            value = defaultValue;
        }
    } catch (Exception e) {
        if (_log.isWarnEnabled()) {
            _log.warn(e, e);
        }
    } finally {
        if (contextClassLoader != portalClassLoader) {
            currentThread.setContextClassLoader(contextClassLoader);
        }

        if (xmlStreamReader != null) {
            try {
                xmlStreamReader.close();
            } catch (Exception e) {
            }
        }
    }

    _setCachedValue(xml, requestedLanguageId, useDefault, value);

    return value;
}

From source file:Main.java

public static String parse(XMLStreamReader reader) {
    StringBuffer result = new StringBuffer();
    if (reader != null) {
        try {/* w ww . j av a  2 s. c  o m*/
            while (reader.hasNext()) {
                switch (reader.getEventType()) {

                case XMLStreamConstants.START_ELEMENT:
                    result.append("<");
                    printName(reader, result);
                    printNamespaces(reader, result);
                    printAttributes(reader, result);
                    result.append(">");
                    break;

                case XMLStreamConstants.END_ELEMENT:
                    result.append("</");
                    printName(reader, result);
                    result.append(">");
                    break;

                case XMLStreamConstants.SPACE:

                case XMLStreamConstants.CHARACTERS:
                    int start = reader.getTextStart();
                    int length = reader.getTextLength();
                    result.append(new String(reader.getTextCharacters(), start, length));
                    break;

                case XMLStreamConstants.PROCESSING_INSTRUCTION:
                    result.append("<?");
                    if (reader.hasText())
                        result.append(reader.getText());
                    result.append("?>");
                    break;

                case XMLStreamConstants.CDATA:
                    result.append("<![CDATA[");
                    start = reader.getTextStart();
                    length = reader.getTextLength();
                    result.append(new String(reader.getTextCharacters(), start, length));
                    result.append("]]>");
                    break;

                case XMLStreamConstants.COMMENT:
                    result.append("<!--");
                    if (reader.hasText())
                        result.append(reader.getText());
                    result.append("-->");
                    break;

                case XMLStreamConstants.ENTITY_REFERENCE:
                    result.append(reader.getLocalName()).append("=");
                    if (reader.hasText())
                        result.append("[").append(reader.getText()).append("]");
                    break;

                case XMLStreamConstants.START_DOCUMENT:
                    result.append("<?xml");
                    result.append(" version='").append(reader.getVersion()).append("'");
                    result.append(" encoding='").append(reader.getCharacterEncodingScheme()).append("'");
                    if (reader.isStandalone())
                        result.append(" standalone='yes'");
                    else
                        result.append(" standalone='no'");
                    result.append("?>");
                    break;
                }
                reader.next();
            } // end while
        } catch (XMLStreamException e) {
            throw new RuntimeException(e);
        } finally {
            try {
                reader.close();
            } catch (XMLStreamException e) {
            }
        }
    }
    return result.toString();
}

From source file:net.cloudkit.enterprises.ws.SuperPassQueryTest.java

public static String parsingReceiptData(String responseData) throws XMLStreamException {
    StringBuilder dataBuilder = new StringBuilder("");
    XMLStreamReader reader = factory.createXMLStreamReader(new StringReader(responseData));
    try {/*  w  w  w .j  a va 2s  . co m*/
        int event = reader.getEventType();
        while (true) {
            switch (event) {
            case XMLStreamConstants.START_ELEMENT:

                if (reader.getName().toString().equals("TradeName")) {
                    // System.out.println(reader.getElementText());
                    dataBuilder.append(reader.getElementText());
                    dataBuilder.append("\t");
                }
                // System.out.println(reader.getName());
                if (reader.getName().toString().equals("SeqNo")) {
                    // System.out.println(reader.getElementText());
                    dataBuilder.append(reader.getElementText());
                    dataBuilder.append("\t");
                }
                // BillNo
                if (reader.getName().toString().equals("EntryId")) {
                    // System.out.println(reader.getElementText());
                    dataBuilder.append(reader.getElementText());
                    dataBuilder.append("\t");
                }
                if (reader.getName().toString().equals("IEFlag")) {
                    // System.out.println(reader.getElementText());
                    dataBuilder.append(reader.getElementText());
                    dataBuilder.append("\t");
                }
                // ??
                if (reader.getName().toString().equals("IEDate")) {
                    // System.out.println(reader.getElementText());
                    dataBuilder.append(reader.getElementText());
                    dataBuilder.append("\t");
                }
                if (reader.getName().toString().equals("TradeMode")) {
                    // System.out.println(reader.getElementText());
                    dataBuilder.append(reader.getElementText());
                    dataBuilder.append("\t");
                }
                if (reader.getName().toString().equals("Status")) {
                    // System.out.println(reader.getElementText());
                    dataBuilder.append(reader.getElementText());
                    dataBuilder.append("\t");
                }
                if (reader.getName().toString().equals("RetExplain")) {
                    // System.out.println(reader.getElementText());
                    dataBuilder.append(reader.getElementText());
                    dataBuilder.append("\t");
                }
                // NoticeDate
                // CustomsCode
                break;
            case XMLStreamConstants.END_ELEMENT:
                // System.out.println("End Element:" + r.getName());
                break;
            }
            if (!reader.hasNext())
                break;
            event = reader.next();
        }
    } finally {
        reader.close();
    }
    dataBuilder.append("\n");
    return dataBuilder.toString();
}

From source file:at.lame.hellonzb.parser.NzbParser.java

/**
 * This is the constructor of the class.
 * It parses the given XML file.// w  w  w  .  j a v  a  2s.com
 *
 * @param mainApp The main application object
 * @param file The file name of the nzb file to parse
 * @throws XMLStreamException 
 * @throws IOException 
 */
public NzbParser(HelloNzbCradle mainApp, String file) throws XMLStreamException, IOException, ParseException {
    this.mainApp = mainApp;

    DownloadFile currentFile = null;
    DownloadFileSegment currentSegment = null;
    boolean groupFlag = false;
    boolean segmentFlag = false;

    this.name = file.trim();
    this.name = file.substring(0, file.length() - 4);
    this.downloadFiles = new Vector<DownloadFile>();

    this.origTotalSize = 0;
    this.downloadedBytes = 0;

    // create XML parser
    String string = reformatInputStream(file);
    InputStream in = new ByteArrayInputStream(string.getBytes());
    XMLInputFactory factory = XMLInputFactory.newInstance();
    XMLStreamReader parser = factory.createXMLStreamReader(in);

    // parse nzb file with a Java XML parser
    while (parser.hasNext()) {
        switch (parser.getEventType()) {
        // parser has reached the end of the xml file
        case XMLStreamConstants.END_DOCUMENT:
            parser.close();
            break;

        // parser has found a new element
        case XMLStreamConstants.START_ELEMENT:
            String elemName = parser.getLocalName().toLowerCase();
            if (elemName.equals("file")) {
                currentFile = newDownloadFile(parser);
                boolean found = false;
                for (DownloadFile dlf : downloadFiles)
                    if (dlf.getFilename().equals(currentFile.getFilename())) {
                        found = true;
                        break;
                    }

                if (!found)
                    downloadFiles.add(currentFile);
            } else if (elemName.equals("group"))
                groupFlag = true;
            else if (elemName.equals("segment")) {
                currentSegment = newDownloadFileSegment(parser, currentFile);
                currentFile.addSegment(currentSegment);
                segmentFlag = true;
            }
            break;

        // end of element
        case XMLStreamConstants.END_ELEMENT:
            groupFlag = false;
            segmentFlag = false;
            break;

        // get the elements value(s)
        case XMLStreamConstants.CHARACTERS:
            if (!parser.isWhiteSpace()) {
                if (groupFlag && (currentFile != null))
                    currentFile.addGroup(parser.getText());
                else if (segmentFlag && (currentSegment != null))
                    currentSegment.setArticleId(parser.getText());
            }
            break;

        // any other parser event?
        default:
            break;
        }

        parser.next();
    }

    checkFileSegments();
    this.origTotalSize = getCurrTotalSize();
}

From source file:gima.neo4j.testsuite.osmcheck.OSMImporter.java

public void importFile(OSMWriter<?> osmWriter, String dataset, boolean allPoints, Charset charset)
        throws IOException, XMLStreamException {
    System.out.println("Importing with osm-writer: " + osmWriter);
    osmWriter.getOrCreateOSMDataset(layerName);
    osm_dataset = osmWriter.getDatasetId();

    long startTime = System.currentTimeMillis();
    long[] times = new long[] { 0L, 0L, 0L, 0L };
    javax.xml.stream.XMLInputFactory factory = javax.xml.stream.XMLInputFactory.newInstance();
    CountedFileReader reader = new CountedFileReader(dataset, charset);
    javax.xml.stream.XMLStreamReader parser = factory.createXMLStreamReader(reader);
    int countXMLTags = 0;
    beginProgressMonitor(100);/*from  www  .  j av a2  s  .c om*/
    setLogContext(dataset);
    boolean startedWays = false;
    boolean startedRelations = false;
    try {
        ArrayList<String> currentXMLTags = new ArrayList<String>();
        int depth = 0;
        Map<String, Object> wayProperties = null;
        ArrayList<Long> wayNodes = new ArrayList<Long>();
        Map<String, Object> relationProperties = null;
        ArrayList<Map<String, Object>> relationMembers = new ArrayList<Map<String, Object>>();
        LinkedHashMap<String, Object> currentNodeTags = new LinkedHashMap<String, Object>();
        while (true) {
            updateProgressMonitor(reader.getPercentRead());
            incrLogContext();
            int event = parser.next();
            if (event == javax.xml.stream.XMLStreamConstants.END_DOCUMENT) {
                break;
            }
            switch (event) {
            case javax.xml.stream.XMLStreamConstants.START_ELEMENT:
                currentXMLTags.add(depth, parser.getLocalName());
                String tagPath = currentXMLTags.toString();
                if (tagPath.equals("[osm]")) {
                    osmWriter.setDatasetProperties(extractProperties(parser));
                } else if (tagPath.equals("[osm, bounds]")) {
                    osmWriter.addOSMBBox(extractProperties("bbox", parser));
                } else if (tagPath.equals("[osm, node]")) {
                    // <node id="269682538" lat="56.0420950" lon="12.9693483" user="sanna" uid="31450" visible="true" version="1" changeset="133823" timestamp="2008-06-11T12:36:28Z"/>
                    osmWriter.createOSMNode(extractProperties("node", parser));
                } else if (tagPath.equals("[osm, way]")) {
                    // <way id="27359054" user="spull" uid="61533" visible="true" version="8" changeset="4707351" timestamp="2010-05-15T15:39:57Z">
                    if (!startedWays) {
                        startedWays = true;
                        times[0] = System.currentTimeMillis();
                        osmWriter.optimize();
                        times[1] = System.currentTimeMillis();
                    }
                    wayProperties = extractProperties("way", parser);
                    wayNodes.clear();
                } else if (tagPath.equals("[osm, way, nd]")) {
                    Map<String, Object> properties = extractProperties(parser);
                    wayNodes.add(Long.parseLong(properties.get("ref").toString()));
                } else if (tagPath.endsWith("tag]")) {
                    Map<String, Object> properties = extractProperties(parser);
                    currentNodeTags.put(properties.get("k").toString(), properties.get("v").toString());
                } else if (tagPath.equals("[osm, relation]")) {
                    // <relation id="77965" user="Grillo" uid="13957" visible="true" version="24" changeset="5465617" timestamp="2010-08-11T19:25:46Z">
                    if (!startedRelations) {
                        startedRelations = true;
                        times[2] = System.currentTimeMillis();
                        osmWriter.optimize();
                        times[3] = System.currentTimeMillis();
                    }
                    relationProperties = extractProperties("relation", parser);
                    relationMembers.clear();
                } else if (tagPath.equals("[osm, relation, member]")) {
                    relationMembers.add(extractProperties(parser));
                }
                if (startedRelations) {
                    if (countXMLTags < 10) {
                        log("Starting tag at depth " + depth + ": " + currentXMLTags.get(depth) + " - "
                                + currentXMLTags.toString());
                        for (int i = 0; i < parser.getAttributeCount(); i++) {
                            log("\t" + currentXMLTags.toString() + ": " + parser.getAttributeLocalName(i) + "["
                                    + parser.getAttributeNamespace(i) + "," + parser.getAttributePrefix(i) + ","
                                    + parser.getAttributeType(i) + "," + "] = " + parser.getAttributeValue(i));
                        }
                    }
                    countXMLTags++;
                }
                depth++;
                break;
            case javax.xml.stream.XMLStreamConstants.END_ELEMENT:
                if (currentXMLTags.toString().equals("[osm, node]")) {
                    osmWriter.addOSMNodeTags(allPoints, currentNodeTags);
                } else if (currentXMLTags.toString().equals("[osm, way]")) {
                    osmWriter.createOSMWay(wayProperties, wayNodes, currentNodeTags);
                } else if (currentXMLTags.toString().equals("[osm, relation]")) {
                    osmWriter.createOSMRelation(relationProperties, relationMembers, currentNodeTags);
                }
                depth--;
                currentXMLTags.remove(depth);
                // log("Ending tag at depth "+depth+": "+currentTags.get(depth));
                break;
            default:
                break;
            }
        }
    } finally {
        endProgressMonitor();
        parser.close();
        osmWriter.finish();
        this.osm_dataset = osmWriter.getDatasetId();
    }
    describeTimes(startTime, times);
    osmWriter.describeMissing();
    osmWriter.describeLoaded();

    long stopTime = System.currentTimeMillis();
    log("info | Elapsed time in seconds: " + (1.0 * (stopTime - startTime) / 1000.0));
    stats.dumpGeomStats();
    stats.printTagStats();
}