Example usage for javax.xml.stream XMLStreamReader nextTag

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

Introduction

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

Prototype

public int nextTag() throws XMLStreamException;

Source Link

Document

Skips any white space (isWhiteSpace() returns true), COMMENT, or PROCESSING_INSTRUCTION, until a START_ELEMENT or END_ELEMENT is reached.

Usage

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 w ww.ja va 2 s  .  c om
    }
    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.specification.model.job.util.JobUtil.java

public void saveModelerFile(ModelerFile modelerFile) {

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

    try {// w  w  w . j a v a  2  s.  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.rhq.enterprise.server.sync.SynchronizationManagerBean.java

private <E, X> Set<ConsistencyValidatorFailureReport> validateEntities(XMLStreamReader rdr, Subject subject,
        Set<ConsistencyValidator> consistencyValidators, Map<String, Configuration> importConfigurations)
        throws Exception {
    String synchronizerClass = rdr.getAttributeValue(null, SynchronizationConstants.ID_ATTRIBUTE);
    HashSet<ConsistencyValidatorFailureReport> ret = new HashSet<ConsistencyValidatorFailureReport>();

    @SuppressWarnings("unchecked")
    Synchronizer<E, X> synchronizer = instantiate(synchronizerClass, Synchronizer.class,
            "The id attribute of entities doesn't correspond to a class implementing the Synchronizer interface.");

    synchronizer.initialize(subject, entityManager);

    Importer<E, X> importer = synchronizer.getImporter();

    Set<ConsistencyValidator> requriedConsistencyValidators = synchronizer.getRequiredValidators();

    //check that all the required consistency validators were run
    for (ConsistencyValidator v : requriedConsistencyValidators) {
        if (!consistencyValidators.contains(v)) {
            ret.add(new ConsistencyValidatorFailureReport(v.getClass().getName(),
                    "The validator '" + v.getClass().getName() + "' is required by the synchronizer '"
                            + synchronizerClass + "' but was not found in the export file."));
        }/*  www.  ja v  a  2 s . c  o m*/
    }

    //don't bother checking if there are inconsistencies in the export file
    if (!ret.isEmpty()) {
        return ret;
    }

    boolean configured = false;
    Configuration importConfiguration = importConfigurations.get(synchronizerClass);

    Set<EntityValidator<X>> validators = null;

    //the passed in configuration has precedence over the default one inlined in 
    //the config file.
    if (importConfiguration != null) {
        importer.configure(importConfiguration);
        validators = importer.getEntityValidators();
        for (EntityValidator<X> v : validators) {
            v.initialize(subject, entityManager);
        }
        configured = true;
    }

    while (rdr.hasNext()) {
        boolean bailout = false;
        switch (rdr.next()) {
        case XMLStreamConstants.START_ELEMENT:
            if (SynchronizationConstants.DEFAULT_CONFIGURATION_ELEMENT.equals(rdr.getName().getLocalPart())) {
                if (!configured) {
                    importConfiguration = getDefaultConfiguration(rdr);
                }
            } else if (SynchronizationConstants.DATA_ELEMENT.equals(rdr.getName().getLocalPart())) {

                //first check if the configure method has been called
                if (!configured) {
                    importer.configure(importConfiguration);
                    validators = importer.getEntityValidators();
                    for (EntityValidator<X> v : validators) {
                        v.initialize(subject, entityManager);
                    }
                    configured = true;
                }

                //now do the validation

                rdr.nextTag();
                X exportedEntity = importer.unmarshallExportedEntity(new ExportReader(rdr));

                for (EntityValidator<X> validator : validators) {
                    try {
                        validator.validateExportedEntity(exportedEntity);
                    } catch (Exception e) {
                        ValidationException v = new ValidationException(
                                "Failed to validate entity [" + exportedEntity + "]", e);
                        ret.add(new ConsistencyValidatorFailureReport(validator.getClass().getName(),
                                printExceptionToString(v)));
                    }
                }
            }
            break;
        case XMLStreamConstants.END_ELEMENT:
            if (SynchronizationConstants.ENTITIES_EXPORT_ELEMENT.equals(rdr.getName().getLocalPart())) {
                bailout = true;
            }
        }

        if (bailout) {
            break;
        }
    }

    return ret;
}

From source file:org.rhq.enterprise.server.sync.SynchronizationManagerBean.java

private <E, X> String importSingle(Subject subject, Map<String, Configuration> importConfigs,
        XMLStreamReader rdr) throws Exception {
    String synchronizerClassName = rdr.getAttributeValue(null, SynchronizationConstants.ID_ATTRIBUTE);

    @SuppressWarnings("unchecked")
    Synchronizer<E, X> synchronizer = instantiate(synchronizerClassName, Synchronizer.class,
            "The synchronizer denoted in the export file ('%s') does not implement the importer interface. This should not happen.");

    synchronizer.initialize(subject, entityManager);

    Importer<E, X> importer = synchronizer.getImporter();

    ExportedEntityMatcher<E, X> matcher = null; //this will be initialized once the importer is configured

    boolean configured = false;
    Configuration importConfiguration = importConfigs.get(synchronizerClassName);

    //the passed in configuration has precedence over the default one inlined in 
    //the config file.
    if (importConfiguration != null) {
        importer.configure(importConfiguration);
        matcher = importer.getExportedEntityMatcher();
        configured = true;/*from  w ww .  jav a2s .c o m*/
    }

    while (rdr.hasNext()) {
        boolean bailout = false;
        switch (rdr.next()) {
        case XMLStreamConstants.START_ELEMENT:
            if (SynchronizationConstants.DEFAULT_CONFIGURATION_ELEMENT.equals(rdr.getName().getLocalPart())) {
                if (!configured) {
                    importConfiguration = getDefaultConfiguration(rdr);
                }
            } else if (SynchronizationConstants.DATA_ELEMENT.equals(rdr.getName().getLocalPart())) {

                //first check if the configure method has been called
                if (!configured) {
                    importer.configure(importConfiguration);
                    matcher = importer.getExportedEntityMatcher();
                    configured = true;
                }

                //now do the import

                rdr.nextTag();
                X exportedEntity = importer.unmarshallExportedEntity(new ExportReader(rdr));
                E entity = matcher == null ? null : matcher.findMatch(exportedEntity);
                importer.update(entity, exportedEntity);
            }
            break;
        case XMLStreamConstants.END_ELEMENT:
            if (SynchronizationConstants.ENTITIES_EXPORT_ELEMENT.equals(rdr.getName().getLocalPart())) {
                bailout = true;
            }
        }

        if (bailout) {
            break;
        }
    }

    //we might have had no data and because we configure the importer lazily, it might
    //be left unconfigured by the above loop.
    if (!configured) {
        importer.configure(importConfiguration);
    }

    return importer.finishImport();
}

From source file:org.rhq.enterprise.server.sync.test.DeployedAgentPluginsValidatorTest.java

public void testCanExportAndImportState() throws Exception {
    final PluginManagerLocal pluginManager = context.mock(PluginManagerLocal.class);

    final DeployedAgentPluginsValidator validator = new DeployedAgentPluginsValidator(pluginManager);

    context.checking(new Expectations() {
        {//from w  w  w  . j a  v a2s  . c  o m
            oneOf(pluginManager).getInstalledPlugins();
            will(returnValue(new ArrayList<Plugin>(getDeployedPlugins())));
        }
    });

    validator.initialize(null, null);

    StringWriter output = new StringWriter();
    try {
        XMLOutputFactory ofactory = XMLOutputFactory.newInstance();

        XMLStreamWriter wrt = ofactory.createXMLStreamWriter(output);
        //wrap the exported plugins in "something" so that we produce
        //a valid xml
        wrt.writeStartDocument();
        wrt.writeStartElement("root");

        validator.exportState(new ExportWriter(wrt));

        wrt.writeEndDocument();

        wrt.close();

        StringReader input = new StringReader(output.toString());

        try {
            XMLInputFactory ifactory = XMLInputFactory.newInstance();
            XMLStreamReader rdr = ifactory.createXMLStreamReader(input);

            //push the reader to the start of the plugin elements
            //this is what is expected by the validators
            rdr.nextTag();

            validator.initializeExportedStateValidation(new ExportReader(rdr));

            rdr.close();

            assertEquals(validator.getPluginsToValidate(), getDeployedPlugins());
        } finally {
            input.close();
        }
    } catch (Exception e) {
        LOG.error("Test failed. Output generated so far:\n" + output, e);
        throw e;
    } finally {
        output.close();
    }
}

From source file:org.sakaiproject.tags.impl.job.MeshTagsSyncJob.java

public synchronized void syncAllTags() {

    long start = System.currentTimeMillis();

    if (log.isInfoEnabled()) {
        log.info("Starting MESH Tag Collection synchronization");
    }//from   w  w w.j  a  v a 2  s  .  c o  m
    try {
        XMLInputFactory factory = XMLInputFactory.newInstance();
        XMLStreamReader xsr = factory.createXMLStreamReader(getTagsXmlInputStream());
        xsr.next();
        xsr.nextTag();
        TransformerFactory tf = TransformerFactory.newInstance();
        Transformer t = tf.newTransformer();

        while (xsr.nextTag() == XMLStreamConstants.START_ELEMENT) {
            DOMResult result = new DOMResult();
            t.transform(new StAXSource(xsr), result);

            Node nNode = result.getNode();
            Element element = ((Document) nNode).getDocumentElement();
            String tagLabel = "undefined";
            counterTotal++;

            try {
                Element descriptorName = (Element) element.getElementsByTagName("DescriptorName").item(0);
                tagLabel = getString("String", descriptorName);
                String externalId = getString("DescriptorUI", element);
                String description = getString("Annotation", element);
                long externalCreationDate = xmlDateToMs(element.getElementsByTagName("DateCreated").item(0),
                        externalId);
                long lastUpdateDateInExternalSystem = xmlDateToMs(
                        element.getElementsByTagName("DateRevised").item(0), externalId);
                String externalHierarchyCode = xmlTreeToString(
                        element.getElementsByTagName("TreeNumberList").item(0), externalId);
                String externalType = element.getAttribute("DescriptorClass");
                String alternativeLabels = xmlToAlternativeLabels(
                        element.getElementsByTagName("ConceptList").item(0), externalId);
                updateOrCreateTagWithExternalSourceName(externalId, "MESH", tagLabel, description,
                        alternativeLabels, externalCreationDate, lastUpdateDateInExternalSystem, null,
                        externalHierarchyCode, externalType, null);
                counterSuccess++;
                lastSuccessfulLabel = tagLabel;
            } catch (Exception e) {
                log.warn("Mesh XML can't be processed for this Label: " + tagLabel
                        + ". If the value is undefined, then, the previous successful label was: "
                        + lastSuccessfulLabel, e);
                sendStatusMail(2, e.getMessage());
            }
            if (counterTotal % 1000 == 0) {
                log.info(counterSuccess + "/" + counterTotal
                        + " labels processed correctly... and still processing. "
                        + (counterTotal - counterSuccess) + " errors by the moment");
            }

        } // end while
        xsr.close();
        updateTagCollectionSynchronization("MESH", 0L);
        deleteTagsOlderThanDateFromCollection("MESH", start);
        sendStatusMail(1, "Imported from MESH finished. Num of labels processed successfully " + counterSuccess
                + "of" + counterTotal);
    } catch (XMLStreamException ex) {
        log.warn("Mesh XML can't be processed", ex);
    } catch (Exception e) {
        log.warn("Mesh XML can't be processed", e);
        sendStatusMail(2, e.getMessage());
    }

    if (log.isInfoEnabled()) {
        log.info("Finished Mesh Tags synchronization in " + (System.currentTimeMillis() - start) + " ms");
    }
    counterTotal = 0;
    counterSuccess = 0;
    lastSuccessfulLabel = "";
}

From source file:org.sakaiproject.tags.impl.job.TagsExportedXMLSyncJob.java

public synchronized void syncAllTags() {

    long start = System.currentTimeMillis();

    if (log.isInfoEnabled()) {
        log.info("Starting Full XML Tag Collection synchronization");
    }//from  w w  w  .java  2  s .  c  o m
    try {
        XMLInputFactory factory = XMLInputFactory.newInstance();
        XMLStreamReader xsr = factory.createXMLStreamReader(getTagsXmlInputStream());
        xsr.next();
        TransformerFactory tf = TransformerFactory.newInstance();
        Transformer t = tf.newTransformer();

        while (xsr.nextTag() == XMLStreamConstants.START_ELEMENT) {
            DOMResult result = new DOMResult();
            t.transform(new StAXSource(xsr), result);

            Node nNode = result.getNode();
            Element element = ((Document) nNode).getDocumentElement();

            String tagLabel = getString("tagLabel", element);
            String tagId = getString("tagId", element);
            String externalId = getString("externalId", element);
            String description = getString("description", element);
            long externalCreationDate = stringToLong(getString("externalCreationDate", element), 0L);
            long lastUpdateDateInExternalSystem = stringToLong(
                    getString("lastUpdateDateInExternalSystem", element), 0L);
            String externalHierarchyCode = getString("externalHierarchyCode", element);
            String externalType = getString("externalType", element);
            String alternativeLabels = getString("alternativeLabels", element);
            String tagCollectionId = getString("tagCollectionId", element);

            if (collectionToUpdate != null && !collectionToUpdateMoreThanOne) {
                if (!(collectionToUpdate.equals(tagCollectionId))) {
                    collectionToUpdateMoreThanOne = true;
                }
            } else {
                collectionToUpdate = tagCollectionId;
            }
            String data = getString("data", element);
            String parentId = getString("parentId", element);

            if (tagId != null && tagId.length() == VALID_ID_LENGTH) {
                if (tagWithIdIsPresent(tagId)) {
                    updateLabelWithId(tagId, externalId, tagCollectionId, tagLabel, description,
                            alternativeLabels, externalCreationDate, lastUpdateDateInExternalSystem, parentId,
                            externalHierarchyCode, externalType, data);
                } else {
                    updateOrCreateTagWithCollectionId(externalId, tagCollectionId, tagLabel, description,
                            alternativeLabels, externalCreationDate, lastUpdateDateInExternalSystem, parentId,
                            externalHierarchyCode, externalType, data);
                }
            } else {
                updateOrCreateTagWithCollectionId(externalId, tagCollectionId, tagLabel, description,
                        alternativeLabels, externalCreationDate, lastUpdateDateInExternalSystem, parentId,
                        externalHierarchyCode, externalType, data);
            }
        }

        updateTagCollectionSynchronizationWithCollectionId(collectionToUpdate, 0L);
        //We will delete the old ones when there is only one collectionID in the file.
        if (collectionToUpdate != null && !collectionToUpdateMoreThanOne) {
            deleteTagsOlderThanDateFromCollectionWithCollectionId(collectionToUpdate, start);
        }
        sendStatusMail(1, "");
    } catch (Exception e) {
        log.warn("Full Tags XML can't be processed", e);
        sendStatusMail(2, e.getMessage());
    }

    String collectionToUpdate = null;
    Boolean collectionToUpdateMoreThanOne = false;
    if (log.isInfoEnabled()) {
        log.info("Finished Full XML Tags synchronization in " + (System.currentTimeMillis() - start) + " ms");
    }
}

From source file:org.sakaiproject.tags.impl.job.TagsSyncJob.java

public synchronized void syncAllTags() {

    long start = System.currentTimeMillis();

    if (log.isInfoEnabled()) {
        log.info("Starting Tag Collection synchronization");
    }/*from   w  w w.j  a  v  a  2s  .c o  m*/

    try {
        XMLInputFactory factory = XMLInputFactory.newInstance();
        XMLStreamReader xsr = factory.createXMLStreamReader(getTagCollectionssXmlInputStream());
        xsr.next();
        TransformerFactory tf = TransformerFactory.newInstance();
        Transformer t = tf.newTransformer();

        while (xsr.nextTag() == XMLStreamConstants.START_ELEMENT) {
            DOMResult result = new DOMResult();
            t.transform(new StAXSource(xsr), result);

            Node nNode = result.getNode();
            Element element = ((Document) nNode).getDocumentElement();

            String name = getString("Name", element);
            log.debug("Found name: " + name);
            String description = getString("Description", element);
            log.debug("Found description : " + description);
            String externalSourceName = getString("ExternalSourceName", element);
            log.debug("externalSourceName: " + externalSourceName);
            String externalSourceDescription = getString("ExternalSourceDescription", element);
            log.debug("externalSourceDescription: " + externalSourceDescription);
            long lastUpdateDateInExternalSystem = xmlDateToMs(
                    element.getElementsByTagName("DateRevised").item(0), name);
            log.debug("lastUpdateDateInExternalSystem: " + lastUpdateDateInExternalSystem);

            updateOrCreateTagCollection(name, description, externalSourceName, externalSourceDescription,
                    lastUpdateDateInExternalSystem);
        }

        sendStatusMail(1, "");
    } catch (Exception e) {
        log.warn("Error Synchronizing the Tags from an xml file:", e);
        sendStatusMail(2, e.getMessage());
    }

    try {
        XMLInputFactory factory = XMLInputFactory.newInstance();
        XMLStreamReader xsr = factory.createXMLStreamReader(getTagsXmlInputStream());
        xsr.next();
        TransformerFactory tf = TransformerFactory.newInstance();
        Transformer t = tf.newTransformer();

        while (xsr.nextTag() == XMLStreamConstants.START_ELEMENT) {
            DOMResult result = new DOMResult();
            t.transform(new StAXSource(xsr), result);

            Node nNode = result.getNode();
            Element element = ((Document) nNode).getDocumentElement();
            String action = element.getAttribute("Action");
            String tagLabel = getString("TagLabel", element);
            log.debug("Found tagLabel: " + tagLabel);
            String externalId = getString("ExternalId", element);
            log.debug("Found externalId: " + externalId);
            String description = getString("Description", element);
            log.debug("Found description : " + description);
            long externalCreationDate = xmlDateToMs(element.getElementsByTagName("DateCreated").item(0),
                    tagLabel);
            log.debug("externalCreationDate: " + externalCreationDate);
            long lastUpdateDateInExternalSystem = xmlDateToMs(
                    element.getElementsByTagName("DateRevised").item(0), tagLabel);
            log.debug("lastUpdateDateInExternalSystem: " + lastUpdateDateInExternalSystem);
            String externalHierarchyCode = getString("HierarchyCode", element);
            log.debug("externalHierarchyCode: " + externalHierarchyCode);
            String externalType = getString("Type", element);
            log.debug("externalType: " + externalType);
            String alternativeLabels = getString("AlternativeLabels", element);
            log.debug("alternativeLabels: " + alternativeLabels);
            String externalSourceName = getString("ExternalSourceName", element);
            log.debug("externalSourceName: " + externalSourceName);
            String data = getString("Data", element);
            log.debug("data: " + data);
            String parentId = getString("ParentId", element);
            log.debug("parentId: " + parentId);

            if (Objects.equals(action, "delete")) {
                deleteTagFromExternalCollection(externalId, externalSourceName);
            } else {
                updateOrCreateTagWithExternalSourceName(externalId, externalSourceName, tagLabel, description,
                        alternativeLabels, externalCreationDate, lastUpdateDateInExternalSystem, parentId,
                        externalHierarchyCode, externalType, data);
            }

            updateTagCollectionSynchronization(externalSourceName, 0L);
        }
        sendStatusMail(1, "");
    } catch (Exception e) {
        log.warn("Error Synchronizing the Tags from an xml file:", e);
        sendStatusMail(2, e.getMessage());
    }
    if (log.isInfoEnabled()) {
        log.info("Finished Tags synchronization in " + (System.currentTimeMillis() - start) + " ms");
    }

}

From source file:org.xwiki.contrib.confluence.filter.internal.ConfluenceXMLPackage.java

private void createTree() throws XMLStreamException, FactoryConfigurationError, IOException,
        ConfigurationException, FilterException {
    if (this.temporaryDirectory) {
        this.tree = new File(this.directory, "tree");
    } else {/* w  w w .j a v  a 2s. c om*/
        this.tree = File.createTempFile("confluencexml-tree", "");
        this.tree.delete();
    }
    this.tree.mkdir();

    try (InputStream stream = new FileInputStream(getEntities())) {
        XMLStreamReader xmlReader = XML_INPUT_FACTORY.createXMLStreamReader(stream);

        xmlReader.nextTag();

        for (xmlReader.nextTag(); xmlReader.isStartElement(); xmlReader.nextTag()) {
            String elementName = xmlReader.getLocalName();

            if (elementName.equals("object")) {
                readObject(xmlReader);
            } else {
                StAXUtils.skipElement(xmlReader);
            }
        }
    }
}

From source file:org.xwiki.contrib.confluence.filter.internal.ConfluenceXMLPackage.java

private long readObjectProperties(XMLStreamReader xmlReader, PropertiesConfiguration properties)
        throws XMLStreamException, FilterException {
    long id = -1;

    for (xmlReader.nextTag(); xmlReader.isStartElement(); xmlReader.nextTag()) {
        String elementName = xmlReader.getLocalName();

        if (elementName.equals("id")) {
            String idName = xmlReader.getAttributeValue(null, "name");

            if (idName != null && idName.equals("id")) {
                id = Long.valueOf(xmlReader.getElementText());

                properties.setProperty("id", id);
            } else {
                StAXUtils.skipElement(xmlReader);
            }//w w w. j av  a  2s  . co  m
        } else if (elementName.equals("property") || elementName.equals("collection")) {
            String propertyName = xmlReader.getAttributeValue(null, "name");

            properties.setProperty(propertyName, readProperty(xmlReader));
        } else {
            StAXUtils.skipElement(xmlReader);
        }
    }

    return id;
}