Example usage for javax.xml.stream XMLStreamReader getLocalName

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

Introduction

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

Prototype

public String getLocalName();

Source Link

Document

Returns the (local) name of the current event.

Usage

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

public JCoFunction transform(InputStream stream, String encoding) throws XMLStreamException {

    XMLStreamReader reader = null;
    XMLInputFactory factory = XMLInputFactory.newInstance();
    String functionName = null;// w w  w  . ja va 2  s  .com
    String tableName = null;
    String structureName = null;
    String rowId = null;
    String fieldName = null;
    String value = null;

    JCoFunction function = null;

    try {
        reader = factory.createXMLStreamReader(stream);
        String localName = null;
        while (reader.hasNext()) {
            int eventType = reader.next();

            if (eventType == XMLStreamReader.START_DOCUMENT) {
                // find START_DOCUMENT

            } else if (eventType == XMLStreamReader.START_ELEMENT) {
                // find START_ELEMENT
                localName = reader.getLocalName();

                logger.debug("START ELEMENT IS FOUND");
                logger.debug("start localName = " + localName);

                if (localName.equals(MessageConstants.JCO)) {
                    functionName = getAttributeValue(MessageConstants.JCO_ATTR_NAME, reader);

                    try {
                        function = this.connector.getAdapter().getFunction(functionName);
                    } catch (JCoException e) {
                        throw new XMLStreamException(e);
                    }
                    logger.debug("function name:" + functionName);

                } else if (functionName != null) {
                    if (localName.equals(MessageConstants.IMPORT)) {
                        //recordType = IMPORT;

                        push(function.getImportParameterList());
                    } else if (localName.equals(MessageConstants.EXPORT)) {
                        //recordType = EXPORT;

                        push(function.getExportParameterList());
                    } else if (localName.equals(MessageConstants.TABLES)) {
                        //recordType = TABLES;
                        tableName = null;
                        push(function.getTableParameterList());

                    } else if (localName.equals(MessageConstants.TABLE)) {
                        if (tableName != null) {
                            pop();
                        }
                        tableName = getAttributeValue(MessageConstants.TABLE_ATTR_NAME, reader);

                        logger.debug("tableName = " + tableName);
                        push(this.record.getTable(tableName));
                    } else if (localName.equals(MessageConstants.STRUCTURE)) {
                        structureName = getAttributeValue(MessageConstants.STRUCTURE_ATTR_NAME, reader);
                        push(this.record.getStructure(structureName));
                    } else if (localName.equals(MessageConstants.ROW)) {
                        rowId = getAttributeValue(MessageConstants.ROW_ATTR_ID, reader);
                        logger.debug("rowId = " + rowId);
                        if (this.record instanceof JCoTable) {
                            ((JCoTable) this.record).appendRow();
                        }
                    } else if (localName.equals(MessageConstants.FIELD)) {
                        fieldName = getAttributeValue(MessageConstants.STRUCTURE_ATTR_NAME, reader);
                        value = reader.getElementText().trim(); // get an element value
                        logger.debug("FieldName = " + fieldName);
                        logger.debug("value = " + value);

                        this.record.setValue(fieldName, value);

                    }
                }

            } else if (eventType == XMLStreamReader.END_DOCUMENT) {

                // find END_DOCUMENT
                logger.debug("END DOCUMENT IS FOUND");
            } else if (eventType == XMLStreamReader.END_ELEMENT) {
                logger.debug("END ELEMENT IS FOUND");
                logger.debug("end localName = " + localName);
                // find END_ELEMENT
                if (localName.equals(MessageConstants.IMPORT) || localName.equals(MessageConstants.EXPORT)
                        || localName.equals(MessageConstants.TABLES) || localName.equals(MessageConstants.TABLE)
                        || localName.equals(MessageConstants.STRUCTURE)) {
                    pop();
                }
            }
        }
    } catch (Exception e) {
        logger.fatal(e);
        throw new TransformerException(this, e);
    } finally {
        if (reader != null) {
            try {
                reader.close();
            } catch (XMLStreamException ex) {
            }
        }
        if (stream != null) {
            try {
                stream.close();
            } catch (IOException ex) {
            }
        }
        logger.debug("\n" + function.getImportParameterList().toXML());
        logger.debug("\n" + function.getExportParameterList().toXML());
        logger.debug("\n" + function.getTableParameterList().toXML());

        return function;
    }
}

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 ww  . ja va 2s  . c o  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.netbeans.jbatch.modeler.spec.core.Definitions.java

public static Definitions load(ModelerFile file, String definitionId) {
    File savedFile = file.getFile();
    Definitions definition_Load = null;/*ww w .  j a v  a2s.co m*/
    boolean definitionExist = false;
    XMLStreamReader xsr = null;
    try {
        if (savedFile.length() != 0) {

            XMLInputFactory xif = XMLInputFactory.newFactory();
            StreamSource xml = new StreamSource(savedFile);
            xsr = xif.createXMLStreamReader(xml);
            xsr.nextTag();
            if (definitionId == null) {
                while (xsr.hasNext() && !definitionExist) {
                    if (xsr.getEventType() == XMLStreamConstants.START_ELEMENT
                            && xsr.getLocalName().equals("definitions")
                            && xsr.getAttributeValue(null, "id") == null) {
                        definitionExist = true;
                    } else {
                        xsr.next();
                    }
                }
            } else {
                while (xsr.hasNext() && !definitionExist) {
                    if (xsr.getEventType() == XMLStreamConstants.START_ELEMENT
                            && xsr.getLocalName().equals("definitions")
                            && definitionId.equals(xsr.getAttributeValue(null, "id"))) {
                        definitionExist = true;
                    } else {
                        xsr.next();
                    }
                }
            }

        }
        JAXBContext jobContext;
        Unmarshaller jobUnmarshaller;
        //            if (jobContext == null) {
        jobContext = JAXBContext.newInstance(new Class<?>[] { ShapeDesign.class, Definitions.class });
        //            }
        //            if (jobUnmarshaller == null) {
        jobUnmarshaller = jobContext.createUnmarshaller();
        jobUnmarshaller.setEventHandler(new ValidateJAXB());
        //            }
        if (definitionExist) {
            definition_Load = jobUnmarshaller.unmarshal(xsr, Definitions.class).getValue();//new StreamSource(savedFile)
        }
        if (xsr != null) {
            xsr.close();
        }

    } catch (XMLStreamException ex) {
        Exceptions.printStackTrace(ex);
    } catch (JAXBException ex) {
        //            io.getOut().println("Exception: " + ex.toString());
        ex.printStackTrace();
        System.out.println("Document XML Not Exist");
    }
    return definition_Load;
}

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

public static void unload(ModelerFile file, List<String> definitionIdList) {
    File savedFile = file.getFile();
    if (definitionIdList.isEmpty()) {
        return;//from www .j  a  va 2  s  .c o  m
    }
    try {
        File cloneSavedFile = File.createTempFile("TMP", "job");
        FileUtils.copyFile(savedFile, cloneSavedFile);

        BufferedReader br = new BufferedReader(new FileReader(savedFile));
        String line = null;
        while ((line = br.readLine()) != null) {
            System.out.println("pre savedFile : " + line);
        }

        XMLOutputFactory xof = XMLOutputFactory.newFactory();
        XMLStreamWriter xsw = xof.createXMLStreamWriter(new FileWriter(savedFile));
        xsw.setDefaultNamespace("http://jbatchsuite.java.net");

        xsw.writeStartDocument();
        xsw.writeStartElement("jbatchnb", "root", "http://jbatchsuite.java.net");
        xsw.writeNamespace("jbatch", "http://xmlns.jcp.org/xml/ns/javaee");
        xsw.writeNamespace("jbatchnb", "http://jbatchsuite.java.net");
        xsw.writeNamespace("xsi", "http://www.w3.org/2001/XMLSchema-instance");
        xsw.writeNamespace("java", "http://jcp.org/en/jsr/detail?id=270");
        xsw.writeNamespace("nbm", "http://nbmodeler.java.net");

        if (cloneSavedFile.length() != 0) {
            try {
                XMLInputFactory xif = XMLInputFactory.newFactory();
                StreamSource xml = new StreamSource(cloneSavedFile);
                XMLStreamReader xsr = xif.createXMLStreamReader(xml);
                xsr.nextTag();
                while (xsr.getEventType() == XMLStreamConstants.START_ELEMENT) {
                    //                        Def   Y    N
                    //                        Tag   N(D) Y(D)
                    //                        ________________
                    //                              T    T
                    //                        ----------------
                    //
                    //                        Def   Y    N
                    //                        Tag   Y(S) N(S)
                    //                        ________________
                    //                              S    S
                    //                        ----------------
                    //
                    //                        Def   Y    N
                    //                        Tag   Y(D) N(S)
                    //                        ________________
                    //                              T    S
                    //                        ----------------
                    //
                    //                       (D) => Different
                    //                       (S) => Same
                    //                        Y => Id Exist
                    //                        N => Def Id is null
                    //                        T => Transform
                    //                        S => Skip

                    if (xsr.getLocalName().equals("definitions")) {
                        //                            if (definitionId == null) {
                        //                                if (xsr.getAttributeValue(null, "id") != null) {
                        //                                    transformXMLStream(xsr, xsw);
                        //                                }
                        //                            } else {
                        if (xsr.getAttributeValue(null, "id") == null) {
                            System.out.println("transformXMLStream " + null);
                            transformXMLStream(xsr, xsw);
                        } else {
                            if (!definitionIdList.contains(xsr.getAttributeValue(null, "id"))) {
                                System.out.println("transformXMLStream " + xsr.getAttributeValue(null, "id"));
                                transformXMLStream(xsr, xsw);
                            } else {
                                System.out.println("skipXMLStream " + xsr.getAttributeValue(null, "id"));
                                skipXMLStream(xsr);
                            }
                        }
                        //                            }
                    }
                    System.out.println(
                            "pre xsr.getEventType() : " + xsr.getEventType() + "  " + xsr.getLocalName());
                    xsr.nextTag();
                    System.out.println(
                            "post xsr.getEventType() : " + xsr.getEventType() + "  " + xsr.getLocalName());
                }
            } catch (XMLStreamException ex) {
                Exceptions.printStackTrace(ex);
            }
        }
        xsw.writeEndDocument();
        xsw.close();

        br = new BufferedReader(new FileReader(savedFile));
        line = null;
        while ((line = br.readLine()) != null) {
            System.out.println("post savedFile : " + line);
        }

    } catch (IOException ex) {
        Exceptions.printStackTrace(ex);
    } catch (XMLStreamException ex) {
        Exceptions.printStackTrace(ex);
    }
}

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

static void transformXMLStream(XMLStreamReader xmlStreamReader, XMLStreamWriter xmlStreamWriter) {
    try {//from  w  w  w .  ja v a 2s  .c om
        //            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.spec.core.Definitions.java

static void skipXMLStream(XMLStreamReader xmlStreamReader) {
    try {//from  w ww. j a  v a  2  s. c om
        boolean finish = false;
        while (xmlStreamReader.hasNext() && !finish) {
            switch (xmlStreamReader.getEventType()) {
            case XMLEvent.END_ELEMENT:
                if (xmlStreamReader.getLocalName().equals("definitions")) {
                    finish = true;
                }
                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 {/*from  w  ww .j  a  v  a 2s  .c om*/
        //            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.netbeans.jbatch.modeler.specification.model.job.util.JobUtil.java

public void saveModelerFile(ModelerFile modelerFile) {

    Definitions definitions = (Definitions) modelerFile.getDefinitionElement();

    try {//from  ww  w  .  ja  v a2s .c o m
        updateBatchDiagram(modelerFile);
        List<String> closeDefinitionIdList = closeDiagram(modelerFile, definitions.getGarbageDefinitions());
        List<String> definitionIdList = new ArrayList<String>(closeDefinitionIdList);
        //            definitionIdList.addAll(definitions.getGarbageDefinitions());
        definitionIdList.add(definitions.getId());
        File savedFile = modelerFile.getFile();

        BufferedReader br = new BufferedReader(new FileReader(savedFile));
        String line = null;
        while ((line = br.readLine()) != null) {
            System.out.println("savedFile : " + line);
        }

        File cloneSavedFile = File.createTempFile("TMP", "job");
        FileUtils.copyFile(savedFile, cloneSavedFile);
        //            br = new BufferedReader(new FileReader(cloneSavedFile));
        //            line = null;
        //            while ((line = br.readLine()) != null) {
        //                System.out.println("line2 : " + line);
        //            }

        XMLOutputFactory xof = XMLOutputFactory.newFactory();
        XMLStreamWriter xsw = xof.createXMLStreamWriter(new FileWriter(savedFile));
        xsw.setDefaultNamespace("http://jbatchsuite.java.net");

        xsw.writeStartDocument();
        xsw.writeStartElement("jbatchnb", "root", "http://jbatchsuite.java.net");
        xsw.writeNamespace("jbatch", "http://xmlns.jcp.org/xml/ns/javaee");
        xsw.writeNamespace("jbatchnb", "http://jbatchsuite.java.net");
        xsw.writeNamespace("xsi", "http://www.w3.org/2001/XMLSchema-instance");
        xsw.writeNamespace("java", "http://jcp.org/en/jsr/detail?id=270");
        xsw.writeNamespace("nbm", "http://nbmodeler.java.net");

        //            br = new BufferedReader(new FileReader(savedFile));
        //            line = null;
        //            while ((line = br.readLine()) != null) {
        //                System.out.println("line3 : " + line);
        //            }
        if (cloneSavedFile.length() != 0) {
            try {
                XMLInputFactory xif = XMLInputFactory.newFactory();
                StreamSource xml = new StreamSource(cloneSavedFile);
                XMLStreamReader xsr = xif.createXMLStreamReader(xml);
                xsr.nextTag();
                while (xsr.getEventType() == XMLStreamConstants.START_ELEMENT) {
                    //                        Def   Y    N
                    //                        Tag   N(D) Y(D)
                    //                        ________________
                    //                              T    T
                    //                        ----------------
                    //
                    //                        Def   Y    N
                    //                        Tag   Y(S) N(S)
                    //                        ________________
                    //                              S    S
                    //                        ----------------
                    //
                    //                        Def   Y    N
                    //                        Tag   Y(D) N(S)
                    //                        ________________
                    //                              T    S
                    //                        ----------------
                    //
                    //                       (D) => Different
                    //                       (S) => Same
                    //                        Y => Id Exist
                    //                        N => Id is null
                    //                        T => Transform
                    //                        S => Skip

                    if (xsr.getLocalName().equals("definitions")) {
                        //                            if (definitions.getId() == null) {
                        //                                if (xsr.getAttributeValue(null, "id") != null) {
                        //                                    transformXMLStream(xsr, xsw);
                        //                                } else {
                        //                                    skipXMLStream(xsr);
                        //                                }
                        //                            } else {
                        if (xsr.getAttributeValue(null, "id") == null) {
                            if (definitions.getId() == null) {
                                skipXMLStream(xsr);
                            } else {
                                transformXMLStream(xsr, xsw);
                            }
                        } else {
                            if (!definitionIdList.contains(xsr.getAttributeValue(null, "id"))) {
                                transformXMLStream(xsr, xsw);
                            } else {
                                skipXMLStream(xsr);
                            }
                        }
                        //                            }
                    }
                    xsr.nextTag();
                }
            } catch (XMLStreamException ex) {
                Exceptions.printStackTrace(ex);
            }
        }

        JAXBElement<Definitions> je = new JAXBElement<Definitions>(
                new QName("http://jbatchsuite.java.net", "definitions", "jbatchnb"), Definitions.class,
                definitions);
        if (jobContext == null) {
            jobContext = JAXBContext.newInstance(new Class<?>[] { ShapeDesign.class, Definitions.class });
        }
        if (jobMarshaller == null) {
            jobMarshaller = jobContext.createMarshaller();
        }

        // output pretty printed
        jobMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
        jobMarshaller.setProperty(Marshaller.JAXB_FRAGMENT, Boolean.TRUE);
        //          jobMarshaller.setProperty(Marshaller.JAXB_SCHEMA_LOCATION, "http://www.omg.org/spec/Batch/20100524/MODEL http://www.omg.org/spec/Batch/2.0/20100501/Batch20.xsd");
        jobMarshaller.setEventHandler(new ValidateJAXB());
        jobMarshaller.marshal(je, System.out);
        jobMarshaller.marshal(je, xsw);

        //            xsw.writeEndElement();
        xsw.writeEndDocument();
        xsw.close();

        //            StringWriter sw = new StringWriter();
        //            jobMarshaller.marshal(file.getDefinitionElement(), sw);
        //            FileUtils.writeStringToFile(savedFile, sw.toString().replaceFirst("xmlns:ns[A-Za-z\\d]{0,3}=\"http://www.omg.org/spec/Batch/20100524/MODEL\"",
        //                    "xmlns=\"http://www.omg.org/spec/Batch/20100524/MODEL\""));
    } catch (JAXBException ex) {
        Exceptions.printStackTrace(ex);
    } catch (IOException ex) {
        Exceptions.printStackTrace(ex);
    } catch (XMLStreamException ex) {
        Exceptions.printStackTrace(ex);
    }

}

From source file:org.openanzo.services.serialization.XMLBackupReader.java

/**
 * Parse the data within the reader, passing the results to the IRepositoryHandler
 * /*w ww .j a v a2 s.c o  m*/
 * @param reader
 *            reader containing the data
 * @param handler
 *            Handler which will handle the elements within the data
 * @throws AnzoException
 */
private void parseBackup(Reader reader, final IBackupHandler handler) throws AnzoException {
    try {
        XMLStreamReader parser = XMLFactoryFinder.getXMLInputFactory().createXMLStreamReader(reader);

        for (int event = parser.next(); event != XMLStreamConstants.END_DOCUMENT; event = parser.next()) {
            switch (event) {
            case XMLStreamConstants.START_ELEMENT:
                if (SerializationConstants.namedGraph.equals(parser.getLocalName())) {
                    graphUri = parser.getAttributeValue(null, SerializationConstants.namedGraphUri);
                    String meta = parser.getAttributeValue(null, SerializationConstants.metadataGraphUri);
                    String uuidString = parser.getAttributeValue(null, SerializationConstants.namedGraphUUID);
                    namedGraphUri = Constants.valueFactory.createURI(graphUri);
                    metaURI = Constants.valueFactory.createURI(meta);
                    uuid = Constants.valueFactory.createURI(uuidString);
                    revisioned = Boolean
                            .parseBoolean(parser.getAttributeValue(null, SerializationConstants.revisioned));
                } else if (SerializationConstants.revisions.equals(parser.getLocalName())) {
                    revisions = new ArrayList<BackupRevision>();
                } else if (SerializationConstants.revisionInfo.equals(parser.getLocalName())) {
                    long revision = Long
                            .parseLong(parser.getAttributeValue(null, SerializationConstants.revision));
                    Long start = Long.valueOf(parser.getAttributeValue(null, SerializationConstants.start));
                    String endString = parser.getAttributeValue(null, SerializationConstants.end);
                    Long end = (endString != null) ? Long.valueOf(endString) : -1;
                    lastModified = Constants.valueFactory
                            .createURI(parser.getAttributeValue(null, SerializationConstants.lastModifiedBy));
                    revisions.add(new BackupRevision(revision, start, end, lastModified));
                } else if (SerializationConstants.statement.equals(parser.getLocalName())) {
                    if (processGraph) {
                        if (revisioned) {
                            String startString = parser.getAttributeValue(null, SerializationConstants.start);
                            String endString = parser.getAttributeValue(null, SerializationConstants.end);
                            if (startString != null)
                                start = Long.valueOf(startString);
                            if (endString != null)
                                end = Long.valueOf(endString);
                        }
                    }
                } else if (SerializationConstants.statements.equals(parser.getLocalName())) {
                    if (processGraph) {
                        metadata = !parser.getAttributeValue(null, SerializationConstants.namedGraphUri)
                                .equals(graphUri);
                    }
                } else if (SerializationConstants.subject.equals(parser.getLocalName())) {
                    if (processGraph) {
                        nodeType = parser.getAttributeValue(null, SerializationConstants.subjectType);
                    }
                } else if (SerializationConstants.predicate.equals(parser.getLocalName())) {
                } else if (SerializationConstants.object.equals(parser.getLocalName())) {
                    if (processGraph) {
                        nodeType = parser.getAttributeValue(null, SerializationConstants.objectType);
                        language = parser.getAttributeValue(null, SerializationConstants.language);
                        datatype = parser.getAttributeValue(null, SerializationConstants.dataType);
                    }
                } else if (SerializationConstants.namedGraphUri.equals(parser.getLocalName())) {
                }
                break;
            case XMLStreamConstants.END_ELEMENT:
                if (SerializationConstants.namedGraph.equals(parser.getLocalName())) {
                    graphUri = null;
                    namedGraphUri = null;
                    metaURI = null;
                    uuid = null;
                    revisioned = true;
                    revisions = null;
                } else if (SerializationConstants.revisionInfo.equals(parser.getLocalName())) {
                } else if (SerializationConstants.revisions.equals(parser.getLocalName())) {
                    processGraph = handler.handleNamedGraph(revisioned, namedGraphUri, metaURI, uuid,
                            revisions);
                    revisions = null;
                } else if (SerializationConstants.statement.equals(parser.getLocalName())) {
                    if (processGraph) {
                        handler.handleStatement(metadata, revisioned,
                                Constants.valueFactory.createStatement(currentSubject, currentPredicate,
                                        currentObject, currentNamedGraphURI),
                                start, end);
                        start = null;
                        end = null;
                    }
                } else if (SerializationConstants.subject.equals(parser.getLocalName())) {
                    if (processGraph) {
                        if (NodeType.BNODE.name().equals(nodeType)) {
                            currentSubject = Constants.valueFactory.createBNode(currentValue);
                        } else {
                            currentSubject = Constants.valueFactory.createURI(currentValue);
                        }
                        currentValue = null;
                        nodeType = null;
                    }
                } else if (SerializationConstants.predicate.equals(parser.getLocalName())) {
                    if (processGraph) {
                        currentPredicate = Constants.valueFactory.createURI(currentValue);
                        currentValue = null;
                    }
                } else if (SerializationConstants.object.equals(parser.getLocalName())) {
                    if (processGraph) {
                        if (NodeType.BNODE.name().equals(nodeType)) {
                            currentObject = Constants.valueFactory.createBNode(currentValue);
                        } else if (NodeType.URI.name().equals(nodeType)) {
                            currentObject = Constants.valueFactory.createURI(currentValue);
                        } else if (NodeType.LITERAL.name().equals(nodeType)) {
                            if (currentValue == null) {
                                currentValue = "";
                            } else if (Base64
                                    .isArrayByteBase64(currentValue.getBytes(Constants.byteEncoding))) {
                                currentValue = new String(
                                        Base64.decodeBase64(currentValue.getBytes(Constants.byteEncoding)),
                                        Constants.byteEncoding);
                            }
                            if (datatype != null) {
                                currentObject = Constants.valueFactory.createLiteral(currentValue,
                                        Constants.valueFactory.createURI(datatype));
                            } else if (language != null) {
                                currentObject = Constants.valueFactory.createLiteral(currentValue, language);
                            } else {
                                currentObject = Constants.valueFactory.createLiteral(currentValue);
                            }
                        }
                        currentValue = null;
                        nodeType = null;
                        language = null;
                        datatype = null;
                    }
                } else if (SerializationConstants.namedGraphUri.equals(parser.getLocalName())) {
                    if (processGraph) {
                        currentNamedGraphURI = Constants.valueFactory.createURI(currentValue);
                        currentValue = null;
                    }
                }
                break;
            case XMLStreamConstants.CHARACTERS:
                if (parser.hasText())
                    currentValue = parser.getText();
                break;
            case XMLStreamConstants.CDATA:
                if (parser.hasText())
                    currentValue = parser.getText();
                break;
            }
        }
        parser.close();
    } catch (XMLStreamException ex) {
        throw new AnzoException(ExceptionConstants.IO.READ_ERROR, ex, ex.getMessage());
    } catch (UnsupportedEncodingException uee) {
        throw new AnzoException(ExceptionConstants.IO.ENCODING_ERROR, uee);
    }
}

From source file:org.openanzo.services.serialization.XMLNamedGraphUpdatesReader.java

/**
 * Parse the data within the reader, passing the results to the IRepositoryHandler
 * //  w ww .  java2 s . c  o  m
 * @param reader
 *            reader containing the data
 * @param handler
 *            Handler which will handle the elements within the data
 * @throws AnzoException
 */
public void parseUpdates(Reader reader, final INamedGraphUpdateHandler handler) throws AnzoException {
    try {
        XMLStreamReader parser = XMLFactoryFinder.getXMLInputFactory().createXMLStreamReader(reader);

        for (int event = parser.next(); event != XMLStreamConstants.END_DOCUMENT; event = parser.next()) {
            switch (event) {
            case XMLStreamConstants.START_ELEMENT:
                if (SerializationConstants.namedGraph.equals(parser.getLocalName())) {
                    String uri = parser.getAttributeValue(null, SerializationConstants.namedGraphUri);
                    String uuid = parser.getAttributeValue(null, SerializationConstants.namedGraphUUID);
                    currentNamedGraphUpdate = new NamedGraphUpdate(MemURI.create(uri));
                    if (uuid != null) {
                        currentNamedGraphUpdate.setUUID(MemURI.create(uuid));
                    }
                    String revision = parser.getAttributeValue(null, SerializationConstants.revision);
                    if (revision != null) {
                        currentNamedGraphUpdate.setRevision(Long.parseLong(revision));
                    }
                } else if (SerializationConstants.additions.equals(parser.getLocalName())) {
                    currentStatements = currentNamedGraphUpdate.getAdditions();
                } else if (SerializationConstants.metaAdditions.equals(parser.getLocalName())) {
                    currentStatements = currentNamedGraphUpdate.getMetaAdditions();
                } else if (SerializationConstants.removals.equals(parser.getLocalName())) {
                    currentStatements = currentNamedGraphUpdate.getRemovals();
                } else if (SerializationConstants.metaRemovals.equals(parser.getLocalName())) {
                    currentStatements = currentNamedGraphUpdate.getMetaRemovals();
                } else if (SerializationConstants.statement.equals(parser.getLocalName())) {
                } else if (SerializationConstants.subject.equals(parser.getLocalName())) {
                    nodeType = parser.getAttributeValue(null, SerializationConstants.subjectType);
                } else if (SerializationConstants.predicate.equals(parser.getLocalName())) {
                } else if (SerializationConstants.object.equals(parser.getLocalName())) {
                    nodeType = parser.getAttributeValue(null, SerializationConstants.objectType);
                    language = parser.getAttributeValue(null, SerializationConstants.language);
                    datatype = parser.getAttributeValue(null, SerializationConstants.dataType);
                } else if (SerializationConstants.namedGraphUri.equals(parser.getLocalName())) {
                }
                break;
            case XMLStreamConstants.END_ELEMENT:
                if (SerializationConstants.namedGraph.equals(parser.getLocalName())) {
                    handler.handleNamedGraphUpdate(currentNamedGraphUpdate);
                    currentNamedGraphUpdate = null;
                } else if (SerializationConstants.additions.equals(parser.getLocalName())) {
                    currentStatements = null;
                } else if (SerializationConstants.metaAdditions.equals(parser.getLocalName())) {
                    currentStatements = null;
                } else if (SerializationConstants.removals.equals(parser.getLocalName())) {
                    currentStatements = null;
                } else if (SerializationConstants.metaRemovals.equals(parser.getLocalName())) {
                    currentStatements = null;
                } else if (SerializationConstants.statement.equals(parser.getLocalName())) {
                    currentStatements.add(Constants.valueFactory.createStatement(currentSubject,
                            currentPredicate, currentObject, currentNamedGraphURI));
                } else if (SerializationConstants.subject.equals(parser.getLocalName())) {
                    if (NodeType.BNODE.name().equals(nodeType)) {
                        currentSubject = Constants.valueFactory.createBNode(currentValue);
                    } else {
                        currentSubject = Constants.valueFactory.createURI(currentValue);
                    }
                    currentValue = null;
                    nodeType = null;
                } else if (SerializationConstants.predicate.equals(parser.getLocalName())) {
                    currentPredicate = Constants.valueFactory.createURI(currentValue);
                    currentValue = null;
                } else if (SerializationConstants.object.equals(parser.getLocalName())) {
                    if (NodeType.BNODE.name().equals(nodeType)) {
                        currentObject = Constants.valueFactory.createBNode(currentValue);
                    } else if (NodeType.URI.name().equals(nodeType)) {
                        currentObject = Constants.valueFactory.createURI(currentValue);
                    } else if (NodeType.LITERAL.name().equals(nodeType)) {
                        if (Base64.isArrayByteBase64(currentValue.getBytes(Constants.byteEncoding))) {
                            currentValue = new String(
                                    Base64.decodeBase64(currentValue.getBytes(Constants.byteEncoding)),
                                    Constants.byteEncoding);
                        }
                        if (datatype != null) {
                            currentObject = Constants.valueFactory.createLiteral(currentValue,
                                    Constants.valueFactory.createURI(datatype));
                        } else if (language != null) {
                            currentObject = Constants.valueFactory.createLiteral(currentValue, language);
                        } else {
                            currentObject = Constants.valueFactory.createLiteral(currentValue);
                        }
                    }
                    currentValue = null;
                    nodeType = null;
                    language = null;
                    datatype = null;
                } else if (SerializationConstants.namedGraphUri.equals(parser.getLocalName())) {
                    currentNamedGraphURI = Constants.valueFactory.createURI(currentValue);
                    currentValue = null;
                }
                break;
            case XMLStreamConstants.CHARACTERS:
                currentValue = parser.getText();
                break;
            case XMLStreamConstants.CDATA:
                currentValue = parser.getText();
                break;
            }
        }
        parser.close();
    } catch (XMLStreamException ex) {
        throw new AnzoException(ExceptionConstants.IO.READ_ERROR, ex, ex.getMessage());
    } catch (UnsupportedEncodingException uee) {
        throw new AnzoException(ExceptionConstants.IO.ENCODING_ERROR, uee);
    }
}