Example usage for javax.xml.stream XMLStreamReader getAttributeLocalName

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

Introduction

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

Prototype

public String getAttributeLocalName(int index);

Source Link

Document

Returns the localName of the attribute at the provided index

Usage

From source file:org.jbpm.designer.web.profile.impl.JbpmProfileImpl.java

private void initializeLocalPlugins(ServletContext context) {
    Map<String, IDiagramPlugin> registry = PluginServiceImpl.getLocalPluginsRegistry(context);
    FileInputStream fileStream = null;
    try {/*from  w  ww  .ja  v  a 2  s.  c o  m*/
        try {
            fileStream = new FileInputStream(new StringBuilder(context.getRealPath("/")).append("/")
                    .append(ConfigurationProvider.getInstance().getDesignerContext()).append("profiles")
                    .append("/").append("jbpm.xml").toString());
        } catch (FileNotFoundException e) {
            throw new RuntimeException(e);
        }
        XMLInputFactory factory = XMLInputFactory.newInstance();
        XMLStreamReader reader = factory.createXMLStreamReader(fileStream, "UTF-8");
        while (reader.hasNext()) {
            if (reader.next() == XMLStreamReader.START_ELEMENT) {
                if ("profile".equals(reader.getLocalName())) {
                    for (int i = 0; i < reader.getAttributeCount(); i++) {
                        if ("stencilset".equals(reader.getAttributeLocalName(i))) {
                            _stencilSet = reader.getAttributeValue(i);
                        }
                    }
                } else if ("plugin".equals(reader.getLocalName())) {
                    String name = null;
                    for (int i = 0; i < reader.getAttributeCount(); i++) {
                        if ("name".equals(reader.getAttributeLocalName(i))) {
                            name = reader.getAttributeValue(i);
                        }
                    }
                    _plugins.put(name, registry.get(name));
                } else if ("localhistory".equals(reader.getLocalName())) {
                    for (int i = 0; i < reader.getAttributeCount(); i++) {
                        if ("enabled".equals(reader.getAttributeLocalName(i))) {
                            String localhistoryenabled = reader.getAttributeValue(i);
                            if (!isEmpty(localhistoryenabled)) {
                                _localHistoryEnabled = localhistoryenabled;
                            } else {
                                _logger.info("Invalid local history enabled");
                            }
                        }
                        if ("timeout".equals(reader.getAttributeLocalName(i))) {
                            String localhistorytimeout = reader.getAttributeValue(i);
                            if (!isEmpty(localhistorytimeout)) {
                                _localHistoryTimeout = localhistorytimeout;
                            } else {
                                _logger.info("Invalid local history timeout");
                            }
                        }
                    }
                } else if ("storesvgonsave".equals(reader.getLocalName())) {
                    for (int i = 0; i < reader.getAttributeCount(); i++) {
                        if ("enabled".equals(reader.getAttributeLocalName(i))) {
                            String storesvgonsaveenabled = reader.getAttributeValue(i);
                            if (!isEmpty(storesvgonsaveenabled)) {
                                _storeSVGonSaveOption = storesvgonsaveenabled;
                            } else {
                                _logger.info("Invalid store svg on save enabled");
                            }
                        }
                    }
                }
            }
        }
    } catch (XMLStreamException e) {
        _logger.error(e.getMessage(), e);
        throw new RuntimeException(e); // stop initialization
    } finally {
        if (fileStream != null) {
            try {
                fileStream.close();
            } catch (IOException e) {
            }
        }
        ;
    }
}

From source file:org.mule.module.xml.util.XMLUtils.java

private static void writeStartElement(XMLStreamReader reader, XMLStreamWriter writer)
        throws XMLStreamException {
    String local = reader.getLocalName();
    String uri = reader.getNamespaceURI();
    String prefix = reader.getPrefix();
    if (prefix == null) {
        prefix = "";
    }//  w w w . j a  v a2 s .c  om

    //        System.out.println("STAXUTILS:writeStartElement : node name : " + local +  " namespace URI" + uri);
    boolean writeElementNS = false;
    if (uri != null) {
        String boundPrefix = writer.getPrefix(uri);
        if (boundPrefix == null || !prefix.equals(boundPrefix)) {
            writeElementNS = true;
        }
    }

    // Write out the element name
    if (uri != null) {
        if (prefix.length() == 0 && StringUtils.isEmpty(uri)) {
            writer.writeStartElement(local);
            writer.setDefaultNamespace(uri);

        } else {
            writer.writeStartElement(prefix, local, uri);
            writer.setPrefix(prefix, uri);
        }
    } else {
        writer.writeStartElement(local);
    }

    // Write out the namespaces
    for (int i = 0; i < reader.getNamespaceCount(); i++) {
        String nsURI = reader.getNamespaceURI(i);
        String nsPrefix = reader.getNamespacePrefix(i);
        if (nsPrefix == null) {
            nsPrefix = "";
        }

        if (nsPrefix.length() == 0) {
            writer.writeDefaultNamespace(nsURI);
        } else {
            writer.writeNamespace(nsPrefix, nsURI);
        }

        if (nsURI.equals(uri) && nsPrefix.equals(prefix)) {
            writeElementNS = false;
        }
    }

    // Check if the namespace still needs to be written.
    // We need this check because namespace writing works
    // different on Woodstox and the RI.
    if (writeElementNS) {
        if (prefix.length() == 0) {
            writer.writeDefaultNamespace(uri);
        } else {
            writer.writeNamespace(prefix, uri);
        }
    }

    // Write out attributes
    for (int i = 0; i < reader.getAttributeCount(); i++) {
        String ns = reader.getAttributeNamespace(i);
        String nsPrefix = reader.getAttributePrefix(i);
        if (ns == null || ns.length() == 0) {
            writer.writeAttribute(reader.getAttributeLocalName(i), reader.getAttributeValue(i));
        } else if (nsPrefix == null || nsPrefix.length() == 0) {
            writer.writeAttribute(reader.getAttributeNamespace(i), reader.getAttributeLocalName(i),
                    reader.getAttributeValue(i));
        } else {
            writer.writeAttribute(reader.getAttributePrefix(i), reader.getAttributeNamespace(i),
                    reader.getAttributeLocalName(i), reader.getAttributeValue(i));
        }

    }
}

From source file:org.mule.transport.sap.transformer.XmlToJcoFunctionTransformer.java

private String getAttributeValue(String name, XMLStreamReader reader) {
    int count = reader.getAttributeCount();

    if (true) {//from   w w w  .j a va2 s  .  com
        return reader.getAttributeValue(0);
    }
    for (int i = 0; i < count; i++) {
        if (reader.getAttributeLocalName(i).equals(name)) {
            String value = reader.getAttributeValue(i);
            return value;
        }

    }
    return null;
}

From source file:org.neo4j.gis.spatial.osm.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 w  w  w.  j  av  a 2s . co  m
    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();
}

From source file:org.neo4j.gis.spatial.osm.OSMImporter.java

private Map<String, Object> extractProperties(String name, XMLStreamReader parser) {
    // <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"/>
    // <way id="27359054" user="spull" uid="61533" visible="true"
    // version="8" changeset="4707351" timestamp="2010-05-15T15:39:57Z">
    // <relation id="77965" user="Grillo" uid="13957" visible="true"
    // version="24" changeset="5465617" timestamp="2010-08-11T19:25:46Z">
    LinkedHashMap<String, Object> properties = new LinkedHashMap<String, Object>();
    for (int i = 0; i < parser.getAttributeCount(); i++) {
        String prop = parser.getAttributeLocalName(i);
        String value = parser.getAttributeValue(i);
        if (name != null && prop.equals("id")) {
            prop = name + "_osm_id";
            name = null;/* w  ww  .  j a  v a2s.  c o m*/
        }
        if (prop.equals("lat") || prop.equals("lon")) {
            properties.put(prop, Double.parseDouble(value));
        } else if (name != null && prop.equals("version")) {
            properties.put(prop, Integer.parseInt(value));
        } else if (prop.equals("visible")) {
            if (!value.equals("true") && !value.equals("1")) {
                properties.put(prop, false);
            }
        } else if (prop.equals("timestamp")) {
            try {
                Date timestamp = timestampFormat.parse(value);
                properties.put(prop, timestamp.getTime());
            } catch (ParseException e) {
                error("Error parsing timestamp", e);
            }
        } else {
            properties.put(prop, value);
        }
    }
    if (name != null) {
        properties.put("name", name);
    }
    return properties;
}

From source file:org.netbeans.jbatch.modeler.spec.core.Definitions.java

static void transformXMLStream(XMLStreamReader xmlStreamReader, XMLStreamWriter xmlStreamWriter) {
    try {/*w w w . j a v  a  2s  . com*/
        //            TransformerFactory tf = TransformerFactory.newInstance();
        //            Transformer t = tf.newTransformer();
        //            StAXSource source = new StAXSource(xmlStreamReader);
        //            StAXResult result = new StAXResult(xmlStreamWriter);
        //            t.transform(source, result);
        System.out.println("Defnition Id : " + xmlStreamReader.getAttributeValue(null, "id"));
        boolean finish = false;
        while (xmlStreamReader.hasNext() && !finish) {
            switch (xmlStreamReader.getEventType()) {
            case XMLEvent.START_ELEMENT:
                String prefix = xmlStreamReader.getPrefix();
                String namespaceURI = xmlStreamReader.getNamespaceURI();
                if (namespaceURI != null) {
                    if (prefix != null) {
                        xmlStreamWriter.writeStartElement(xmlStreamReader.getPrefix(),
                                xmlStreamReader.getLocalName(), xmlStreamReader.getNamespaceURI());
                    } else {
                        xmlStreamWriter.writeStartElement(xmlStreamReader.getNamespaceURI(),
                                xmlStreamReader.getLocalName());
                    }
                } else {
                    xmlStreamWriter.writeStartElement(xmlStreamReader.getLocalName());
                }

                for (int i = 0; i < xmlStreamReader.getNamespaceCount(); i++) {
                    xmlStreamWriter.writeNamespace(xmlStreamReader.getNamespacePrefix(i),
                            xmlStreamReader.getNamespaceURI(i));
                }
                int count = xmlStreamReader.getAttributeCount();
                for (int i = 0; i < count; i++) {
                    //                            xmlStreamWriter.writeAttribute(xmlStreamReader.getAttributePrefix(i),
                    //                                    xmlStreamReader.getAttributeNamespace(i),
                    //                                    xmlStreamReader.getAttributeLocalName(i),
                    //                                    xmlStreamReader.getAttributeValue(i));

                    String attrNamespaceURI = xmlStreamReader.getAttributeNamespace(i),
                            attrPrefix = xmlStreamReader.getAttributePrefix(i);
                    if (attrNamespaceURI != null) {
                        if (attrPrefix != null) {
                            xmlStreamWriter.writeAttribute(attrPrefix, attrNamespaceURI,
                                    xmlStreamReader.getAttributeLocalName(i),
                                    xmlStreamReader.getAttributeValue(i));
                        } else {
                            xmlStreamWriter.writeAttribute(attrNamespaceURI,
                                    xmlStreamReader.getAttributeLocalName(i),
                                    xmlStreamReader.getAttributeValue(i));
                        }
                    } else {
                        xmlStreamWriter.writeAttribute(xmlStreamReader.getAttributeLocalName(i),
                                xmlStreamReader.getAttributeValue(i));
                    }

                }
                break;
            case XMLEvent.END_ELEMENT:
                xmlStreamWriter.writeEndElement();
                if (xmlStreamReader.getLocalName().equals("definitions")) {
                    finish = true;
                }
                break;
            case XMLEvent.SPACE:
            case XMLEvent.CHARACTERS:
                xmlStreamWriter.writeCharacters(xmlStreamReader.getTextCharacters(),
                        xmlStreamReader.getTextStart(), xmlStreamReader.getTextLength());
                break;
            case XMLEvent.PROCESSING_INSTRUCTION:
                xmlStreamWriter.writeProcessingInstruction(xmlStreamReader.getPITarget(),
                        xmlStreamReader.getPIData());
                break;
            case XMLEvent.CDATA:
                xmlStreamWriter.writeCData(xmlStreamReader.getText());
                break;

            case XMLEvent.COMMENT:
                xmlStreamWriter.writeComment(xmlStreamReader.getText());
                break;
            case XMLEvent.ENTITY_REFERENCE:
                xmlStreamWriter.writeEntityRef(xmlStreamReader.getLocalName());
                break;
            case XMLEvent.START_DOCUMENT:
                String encoding = xmlStreamReader.getCharacterEncodingScheme();
                String version = xmlStreamReader.getVersion();

                if (encoding != null && version != null) {
                    xmlStreamWriter.writeStartDocument(encoding, version);
                } else if (version != null) {
                    xmlStreamWriter.writeStartDocument(xmlStreamReader.getVersion());
                }
                break;
            case XMLEvent.END_DOCUMENT:
                xmlStreamWriter.writeEndDocument();
                break;
            case XMLEvent.DTD:
                xmlStreamWriter.writeDTD(xmlStreamReader.getText());
                break;

            }
            if (!finish) {
                xmlStreamReader.next();
            }
        }
    } catch (XMLStreamException ex) {
        Exceptions.printStackTrace(ex);
    }
}

From source file:org.netbeans.jbatch.modeler.specification.model.job.util.JobUtil.java

void transformXMLStream(XMLStreamReader xmlStreamReader, XMLStreamWriter xmlStreamWriter) {
    try {//  w w w .j  ava 2  s.  co  m
        //            TransformerFactory tf = TransformerFactory.newInstance();
        //            Transformer t = tf.newTransformer();
        //            StAXSource source = new StAXSource(xmlStreamReader);
        //            StAXResult result = new StAXResult(xmlStreamWriter);
        //            t.transform(source, result);

        boolean finish = false;
        while (xmlStreamReader.hasNext() && !finish) {
            switch (xmlStreamReader.getEventType()) {
            case XMLEvent.START_ELEMENT:
                String prefix = xmlStreamReader.getPrefix();
                String namespaceURI = xmlStreamReader.getNamespaceURI();
                if (namespaceURI != null) {
                    if (prefix != null) {
                        xmlStreamWriter.writeStartElement(xmlStreamReader.getPrefix(),
                                xmlStreamReader.getLocalName(), xmlStreamReader.getNamespaceURI());
                    } else {
                        xmlStreamWriter.writeStartElement(xmlStreamReader.getNamespaceURI(),
                                xmlStreamReader.getLocalName());
                    }
                } else {
                    xmlStreamWriter.writeStartElement(xmlStreamReader.getLocalName());
                }

                for (int i = 0; i < xmlStreamReader.getNamespaceCount(); i++) {
                    xmlStreamWriter.writeNamespace(xmlStreamReader.getNamespacePrefix(i),
                            xmlStreamReader.getNamespaceURI(i));
                }
                int count = xmlStreamReader.getAttributeCount();
                for (int i = 0; i < count; i++) {
                    //                            xmlStreamWriter.writeAttribute(xmlStreamReader.getAttributePrefix(i),
                    //                                    xmlStreamReader.getAttributeNamespace(i),
                    //                                    xmlStreamReader.getAttributeLocalName(i),
                    //                                    xmlStreamReader.getAttributeValue(i));

                    String attrNamespaceURI = xmlStreamReader.getAttributeNamespace(i),
                            attrPrefix = xmlStreamReader.getAttributePrefix(i);
                    if (attrNamespaceURI != null) {
                        if (attrPrefix != null) {
                            xmlStreamWriter.writeAttribute(attrPrefix, attrNamespaceURI,
                                    xmlStreamReader.getAttributeLocalName(i),
                                    xmlStreamReader.getAttributeValue(i));
                        } else {
                            xmlStreamWriter.writeAttribute(attrNamespaceURI,
                                    xmlStreamReader.getAttributeLocalName(i),
                                    xmlStreamReader.getAttributeValue(i));
                        }
                    } else {
                        xmlStreamWriter.writeAttribute(xmlStreamReader.getAttributeLocalName(i),
                                xmlStreamReader.getAttributeValue(i));
                    }

                }
                break;
            case XMLEvent.END_ELEMENT:
                xmlStreamWriter.writeEndElement();
                if (xmlStreamReader.getLocalName().equals("definitions")) {
                    finish = true;
                }
                break;
            case XMLEvent.SPACE:
            case XMLEvent.CHARACTERS:
                xmlStreamWriter.writeCharacters(xmlStreamReader.getTextCharacters(),
                        xmlStreamReader.getTextStart(), xmlStreamReader.getTextLength());
                break;
            case XMLEvent.PROCESSING_INSTRUCTION:
                xmlStreamWriter.writeProcessingInstruction(xmlStreamReader.getPITarget(),
                        xmlStreamReader.getPIData());
                break;
            case XMLEvent.CDATA:
                xmlStreamWriter.writeCData(xmlStreamReader.getText());
                break;

            case XMLEvent.COMMENT:
                xmlStreamWriter.writeComment(xmlStreamReader.getText());
                break;
            case XMLEvent.ENTITY_REFERENCE:
                xmlStreamWriter.writeEntityRef(xmlStreamReader.getLocalName());
                break;
            case XMLEvent.START_DOCUMENT:
                String encoding = xmlStreamReader.getCharacterEncodingScheme();
                String version = xmlStreamReader.getVersion();

                if (encoding != null && version != null) {
                    xmlStreamWriter.writeStartDocument(encoding, version);
                } else if (version != null) {
                    xmlStreamWriter.writeStartDocument(xmlStreamReader.getVersion());
                }
                break;
            case XMLEvent.END_DOCUMENT:
                xmlStreamWriter.writeEndDocument();
                break;
            case XMLEvent.DTD:
                xmlStreamWriter.writeDTD(xmlStreamReader.getText());
                break;

            }
            if (!finish) {
                xmlStreamReader.next();
            }
        }
    } catch (XMLStreamException ex) {
        Exceptions.printStackTrace(ex);
    }
}

From source file:org.opendatakit.briefcase.export.SubmissionParser.java

private static Optional<String> parseAttribute(Path submission, Reader ioReader, String attributeName,
        SubmissionExportErrorCallback onParsingError) {
    try {/* w w w  .  j  av a 2  s . co m*/
        XMLStreamReader reader = xmlInputFactory.createXMLStreamReader(ioReader);
        while (reader.hasNext())
            if (reader.next() == START_ELEMENT)
                for (int i = 0, c = reader.getAttributeCount(); i < c; ++i)
                    if (reader.getAttributeLocalName(i).equals(attributeName))
                        return Optional.of(reader.getAttributeValue(i));
    } catch (XMLStreamException e) {
        log.error("Can't parse submission", e);
        onParsingError.accept(submission, "parsing error");
    }
    return Optional.empty();
}

From source file:org.openo.nfvo.emsdriver.collector.TaskThread.java

private boolean processCMXml(File tempfile, String nename, String type) {

    String csvpath = localPath + nename + "/" + type + "/";
    File csvpathfile = new File(csvpath);
    if (!csvpathfile.exists()) {
        csvpathfile.mkdirs();/*from  w  ww.j  av  a2s . c o m*/
    }
    String csvFileName = nename + dateFormat.format(new Date()) + System.nanoTime();
    String csvpathAndFileName = csvpath + csvFileName + ".csv";
    BufferedOutputStream bos = null;
    FileOutputStream fos = null;
    try {
        fos = new FileOutputStream(csvpathAndFileName, false);
        bos = new BufferedOutputStream(fos, 10240);
    } catch (FileNotFoundException e1) {
        log.error("FileNotFoundException " + StringUtil.getStackTrace(e1));
    }

    boolean FieldNameFlag = false;
    boolean FieldValueFlag = false;
    //line num
    int countNum = 0;
    String xmlPathAndFileName = null;
    String localName = null;
    String endLocalName = null;
    String rmUID = null;
    int index = -1;
    ArrayList<String> names = new ArrayList<String>();// colname
    LinkedHashMap<String, String> nameAndValue = new LinkedHashMap<String, String>();

    FileInputStream fis = null;
    InputStreamReader isr = null;
    XMLStreamReader reader = null;
    try {
        fis = new FileInputStream(tempfile);
        isr = new InputStreamReader(fis, Constant.ENCODING_UTF8);
        XMLInputFactory fac = XMLInputFactory.newInstance();
        reader = fac.createXMLStreamReader(isr);
        int event = -1;
        boolean setcolum = true;
        while (reader.hasNext()) {
            try {
                event = reader.next();
                switch (event) {
                case XMLStreamConstants.START_ELEMENT:
                    localName = reader.getLocalName();
                    if ("FieldName".equalsIgnoreCase(localName)) {
                        FieldNameFlag = true;
                    }
                    if (FieldNameFlag) {
                        if ("N".equalsIgnoreCase(localName)) {
                            String colName = reader.getElementText().trim();
                            names.add(colName);
                        }
                    }
                    if ("FieldValue".equalsIgnoreCase(localName)) {
                        FieldValueFlag = true;

                    }
                    if (FieldValueFlag) {
                        if (setcolum) {
                            xmlPathAndFileName = this.setColumnNames(nename, names, type);
                            setcolum = false;
                        }

                        if ("Object".equalsIgnoreCase(localName)) {
                            int ac = reader.getAttributeCount();
                            for (int i = 0; i < ac; i++) {
                                if ("rmUID".equalsIgnoreCase(reader.getAttributeLocalName(i))) {
                                    rmUID = reader.getAttributeValue(i).trim();
                                }
                            }
                            nameAndValue.put("rmUID", rmUID);
                        }
                        if ("V".equalsIgnoreCase(localName)) {
                            index = Integer.parseInt(reader.getAttributeValue(0)) - 1;
                            String currentName = names.get(index);
                            String v = reader.getElementText().trim();
                            nameAndValue.put(currentName, v);
                        }
                    }
                    break;
                case XMLStreamConstants.CHARACTERS:
                    break;
                case XMLStreamConstants.END_ELEMENT:
                    endLocalName = reader.getLocalName();

                    if ("FieldName".equalsIgnoreCase(endLocalName)) {
                        FieldNameFlag = false;
                    }
                    if ("FieldValue".equalsIgnoreCase(endLocalName)) {
                        FieldValueFlag = false;
                    }
                    if ("Object".equalsIgnoreCase(endLocalName)) {
                        countNum++;
                        this.appendLine(nameAndValue, bos);
                        nameAndValue.clear();
                    }
                    break;
                }
            } catch (Exception e) {
                log.error("" + StringUtil.getStackTrace(e));
                event = reader.next();
            }
        }

        if (bos != null) {
            bos.close();
            bos = null;
        }
        if (fos != null) {
            fos.close();
            fos = null;
        }

        String[] fileKeys = this.createZipFile(csvpathAndFileName, xmlPathAndFileName, nename);
        //ftp store
        Properties ftpPro = configurationInterface.getProperties();
        String ip = ftpPro.getProperty("ftp_ip");
        String port = ftpPro.getProperty("ftp_port");
        String ftp_user = ftpPro.getProperty("ftp_user");
        String ftp_password = ftpPro.getProperty("ftp_password");

        String ftp_passive = ftpPro.getProperty("ftp_passive");
        String ftp_type = ftpPro.getProperty("ftp_type");
        String remoteFile = ftpPro.getProperty("ftp_remote_path");
        this.ftpStore(fileKeys, ip, port, ftp_user, ftp_password, ftp_passive, ftp_type, remoteFile);
        //create Message
        String message = this.createMessage(fileKeys[1], ftp_user, ftp_password, ip, port, countNum, nename);

        //set message
        this.setMessage(message);
    } catch (Exception e) {
        log.error("" + StringUtil.getStackTrace(e));
        return false;
    } finally {
        try {
            if (reader != null) {
                reader.close();
            }
            if (isr != null) {
                isr.close();
            }
            if (fis != null) {
                fis.close();
            }
            if (bos != null) {
                bos.close();
            }

            if (fos != null) {
                fos.close();
            }
        } catch (Exception e) {
            log.error(e);
        }
    }
    return true;
}

From source file:org.openvpms.tools.data.loader.Data.java

/**
 * Creates a new <tt>Data</tt>.
 *
 * @param reader the stream to read from
 *//*w  w w  . j  a v  a  2  s .c  o  m*/
public Data(XMLStreamReader reader) {
    shortName = reader.getAttributeValue(null, "archetype");
    location = reader.getLocation();
    if (StringUtils.isEmpty(shortName)) {
        throw new ArchetypeDataLoaderException(InvalidArchetype, location.getLineNumber(),
                location.getColumnNumber(), "<null>");
    }

    if (!"data".equals(reader.getLocalName())) {
        throw new ArchetypeDataLoaderException(UnexpectedElement, reader.getLocalName(),
                location.getLineNumber(), location.getColumnNumber());
    }
    id = reader.getAttributeValue(null, "id");
    collection = reader.getAttributeValue(null, "collection");

    for (int i = 0; i < reader.getAttributeCount(); i++) {
        String name = reader.getAttributeLocalName(i);
        String value = reader.getAttributeValue(i);
        if (!"archetype".equals(name) && !"id".equals(name) && !"collection".equals(name)
                && !StringUtils.isEmpty(value)) {
            attributes.put(name, value);
        }
    }
}