Example usage for javax.xml.stream XMLStreamReader next

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

Introduction

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

Prototype

public int next() throws XMLStreamException;

Source Link

Document

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

Usage

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

private ImportReport importExportFile(Subject subject, InputStream exportFile,
        Map<String, Configuration> importerConfigs) throws ImportException, XMLStreamException {
    XMLStreamReader rdr = XMLInputFactory.newInstance().createXMLStreamReader(exportFile);

    ImportReport report = new ImportReport();

    while (rdr.hasNext()) {
        switch (rdr.next()) {
        case XMLStreamReader.START_ELEMENT:
            String tagName = rdr.getName().getLocalPart();
            if (SynchronizationConstants.ENTITIES_EXPORT_ELEMENT.equals(tagName)) {
                try {
                    String synchronizer = rdr.getAttributeValue(null, SynchronizationConstants.ID_ATTRIBUTE);
                    String notes = importSingle(subject, importerConfigs, rdr);
                    if (notes != null) {
                        report.getImporterNotes().put(synchronizer, notes);
                    }//  w ww  .  jav a2 s  .  c  o m
                } catch (Exception e) {
                    //fail fast on the import errors... This runs in a single transaction
                    //so all imports done so far will get rolled-back.
                    //(Even if we change our minds later and run a transaction per importer
                    //we should fail fast to prevent further damage due to possible
                    //constraint violations in the db, etc.)
                    throw new ImportException("Import failed.", e);
                }
            }
            break;
        }
    }

    return report;
}

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  w  w  .  j ava  2  s  .  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.plugins.hadoop.HadoopServerConfigurationDelegate.java

public static void parseAndAssignProps(File configFile, Map<String, PropertySimple> props)
        throws XMLStreamException, IOException {
    FileInputStream in = new FileInputStream(configFile);
    XMLStreamReader rdr = XML_INPUT_FACTORY.createXMLStreamReader(in);
    try {//ww  w .ja  v a  2  s.  co m
        boolean inProperty = false;
        String propertyName = null;
        String propertyValue = null;

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

            String tag = null;

            switch (event) {
            case XMLStreamReader.START_ELEMENT:
                tag = rdr.getName().getLocalPart();
                if (PROPERTY_TAG_NAME.equals(tag)) {
                    inProperty = true;
                } else if (inProperty && NAME_TAG_NAME.equals(tag)) {
                    propertyName = rdr.getElementText();
                } else if (inProperty && VALUE_TAG_NAME.equals(tag)) {
                    propertyValue = rdr.getElementText();
                }
                break;
            case XMLStreamReader.END_ELEMENT:
                tag = rdr.getName().getLocalPart();
                if (PROPERTY_TAG_NAME.equals(tag)) {
                    inProperty = false;

                    PropertySimple prop = props.get(propertyName);
                    if (prop != null) {
                        prop.setValue(propertyValue);
                    }

                    propertyName = null;
                    propertyValue = null;
                }
                break;
            }
        }
    } finally {
        rdr.close();
        in.close();
    }
}

From source file:org.rhq.plugins.hadoop.HadoopServerConfigurationDelegate.java

private static void updateFile(File configFile, Map<String, PropertySimple> allProps)
        throws IOException, InterruptedException, XMLStreamException {
    InputStream in = null;/* w w w. j av a  2  s  . com*/
    XMLStreamReader rdr = null;

    OutputStream out = null;
    XMLStreamWriter outWrt = null;

    try {
        Set<String> processedPropertyNames = new HashSet<String>();

        in = new BufferedInputStream(new FileInputStream(configFile));
        rdr = XML_INPUT_FACTORY.createXMLStreamReader(in);

        File tmpFile = File.createTempFile("hadoop-plugin", null);
        out = new FileOutputStream(tmpFile);
        outWrt = XML_OUTPUT_FACTORY.createXMLStreamWriter(out);

        ByteArrayOutputStream stash = new ByteArrayOutputStream();
        XMLStreamWriter stashWrt = XML_OUTPUT_FACTORY.createXMLStreamWriter(stash);
        boolean outputActive = true;

        outWrt.writeStartDocument();

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

            XMLStreamWriter wrt = outputActive ? outWrt : stashWrt;

            switch (event) {
            case XMLStreamConstants.ATTRIBUTE:
                break;
            case XMLStreamConstants.CDATA:
                wrt.writeCData(rdr.getText());
                break;
            case XMLStreamConstants.CHARACTERS:
                wrt.writeCharacters(rdr.getText());
                break;
            case XMLStreamConstants.COMMENT:
                wrt.writeComment(rdr.getText());
                break;
            case XMLStreamConstants.DTD:
                wrt.writeDTD(rdr.getText());
                break;
            case XMLStreamConstants.END_DOCUMENT:
                wrt.writeEndDocument();
                break;
            case XMLStreamConstants.END_ELEMENT:
                if (PROPERTY_TAG_NAME.equals(rdr.getName().getLocalPart())) {
                    String encoding = rdr.getEncoding();
                    if (encoding == null) {
                        encoding = "UTF-8";
                    }

                    String propertyTagSoFar = Charset.forName(encoding)
                            .decode(ByteBuffer.wrap(stash.toByteArray())).toString();
                    DetectedPropertyNameAndUpdatedTag propAndTag = updateProperty(propertyTagSoFar, allProps);

                    //yes, we're intentionally circumventing the xml stream writer, because we already have the XML data we want to write.
                    outWrt.flush();
                    out.write(propAndTag.updatedTag.getBytes("UTF-8"));

                    processedPropertyNames.add(propAndTag.propertyName);

                    //reset stuff
                    stash.reset();
                    wrt = outWrt;
                    outputActive = true;
                } else if (CONFIGURATION_TAG_NAME.equals(rdr.getName().getLocalPart())) {
                    //now add the new props
                    for (String prop : processedPropertyNames) {
                        allProps.remove(prop);
                    }

                    for (Map.Entry<String, PropertySimple> e : allProps.entrySet()) {
                        outWrt.writeStartElement(PROPERTY_TAG_NAME);

                        outWrt.writeStartElement(NAME_TAG_NAME);
                        outWrt.writeCharacters(e.getKey());
                        outWrt.writeEndElement();

                        outWrt.writeStartElement(VALUE_TAG_NAME);
                        outWrt.writeCharacters(e.getValue().getStringValue());
                        outWrt.writeEndElement();

                        outWrt.writeEndElement();
                    }
                }
                wrt.writeEndElement();
                break;
            case XMLStreamConstants.ENTITY_DECLARATION:
                //XXX could not find what to do with this
                break;
            case XMLStreamConstants.ENTITY_REFERENCE:
                wrt.writeEntityRef(rdr.getText());
                break;
            case XMLStreamConstants.NAMESPACE:
                for (int i = 0; i < rdr.getNamespaceCount(); ++i) {
                    wrt.writeNamespace(rdr.getNamespacePrefix(i), rdr.getNamespaceURI(i));
                }
                break;
            case XMLStreamConstants.NOTATION_DECLARATION:
                //XXX could not find what to do with this
                break;
            case XMLStreamConstants.PROCESSING_INSTRUCTION:
                wrt.writeProcessingInstruction(rdr.getPITarget(), rdr.getPIData());
                break;
            case XMLStreamConstants.SPACE:
                wrt.writeCharacters(rdr.getText());
                break;
            case XMLStreamConstants.START_DOCUMENT:
                //this seems to be never called for some strange reason
                //wrt.writeStartDocument();
                break;
            case XMLStreamConstants.START_ELEMENT:
                wrt.writeStartElement(rdr.getName().getPrefix(), rdr.getName().getLocalPart(),
                        rdr.getName().getNamespaceURI());

                for (int i = 0; i < rdr.getAttributeCount(); ++i) {
                    wrt.writeAttribute(rdr.getAttributePrefix(i), rdr.getAttributeNamespace(i),
                            rdr.getAttributeLocalName(i), rdr.getAttributeValue(i));
                }

                if (PROPERTY_TAG_NAME.equals(rdr.getName().getLocalPart())) {
                    wrt.writeCharacters("");
                    outputActive = false;
                }
                break;
            }
        }

        outWrt.flush();
        out.flush();
        out.close();

        in.close();

        //now copy the temp file in the place of the original one
        FileUtil.copyFile(tmpFile, configFile);
    } finally {
        rdr.close();

        outWrt.flush();
        outWrt.close();

        try {
            in.close();
        } finally {
            out.flush();
            out.close();
        }
    }
}

From source file:org.roda.core.index.utils.SolrUtils.java

public static SolrInputDocument getDescriptiveMetadataFields(Binary binary, String metadataType,
        String metadataVersion) throws GenericException {
    SolrInputDocument doc;/*from   w w  w .ja  va 2  s. co  m*/

    Map<String, String> parameters = new HashMap<>();
    parameters.put("prefix", RodaConstants.INDEX_OTHER_DESCRIPTIVE_DATA_PREFIX);
    Reader transformationResult = RodaUtils.applyMetadataStylesheet(binary,
            RodaConstants.CORE_CROSSWALKS_INGEST, metadataType, metadataVersion, parameters);

    try {
        XMLLoader loader = new XMLLoader();
        XMLStreamReader parser = XMLInputFactory.newInstance().createXMLStreamReader(transformationResult);

        boolean parsing = true;
        doc = null;
        while (parsing) {
            int event = parser.next();

            if (event == XMLStreamConstants.END_DOCUMENT) {
                parser.close();
                parsing = false;
            } else if (event == XMLStreamConstants.START_ELEMENT) {
                String currTag = parser.getLocalName();
                if ("doc".equals(currTag)) {
                    doc = loader.readDoc(parser);
                }
            }
        }

    } catch (XMLStreamException | FactoryConfigurationError e) {
        throw new GenericException("Could not process descriptive metadata binary " + binary.getStoragePath(),
                e);
    } finally {
        IOUtils.closeQuietly(transformationResult);
    }

    return doc == null ? new SolrInputDocument() : validateDescriptiveMetadataFields(doc);
}

From source file:org.roda.core.index.utils.SolrUtils.java

public static SolrInputDocument premisToSolr(PreservationMetadataType preservationMetadataType, AIP aip,
        String representationUUID, String fileUUID, Binary binary) throws GenericException {
    SolrInputDocument doc;/*  ww  w  .  j a va 2 s. c  o m*/

    Map<String, String> stylesheetOpt = new HashMap<>();
    stylesheetOpt.put(RodaConstants.PRESERVATION_EVENT_OBJECT_CLASS,
            PreservationMetadataEventClass.REPOSITORY.toString());

    if (aip != null) {
        stylesheetOpt.put(RodaConstants.PRESERVATION_EVENT_OBJECT_CLASS,
                PreservationMetadataEventClass.AIP.toString());
        stylesheetOpt.put(RodaConstants.PRESERVATION_EVENT_AIP_ID, aip.getId());

        if (representationUUID != null) {
            stylesheetOpt.put(RodaConstants.PRESERVATION_EVENT_REPRESENTATION_UUID, representationUUID);
            stylesheetOpt.put(RodaConstants.PRESERVATION_EVENT_OBJECT_CLASS,
                    PreservationMetadataEventClass.REPRESENTATION.toString());
        }

        if (fileUUID != null) {
            stylesheetOpt.put(RodaConstants.PRESERVATION_EVENT_FILE_UUID, fileUUID);
            stylesheetOpt.put(RodaConstants.PRESERVATION_EVENT_OBJECT_CLASS,
                    PreservationMetadataEventClass.FILE.toString());
        }
    }

    Reader reader = null;

    try {
        reader = RodaUtils.applyMetadataStylesheet(binary, RodaConstants.CORE_CROSSWALKS_INGEST_OTHER,
                RodaConstants.PREMIS_METADATA_TYPE, RodaConstants.PREMIS_METADATA_VERSION, stylesheetOpt);

        XMLLoader loader = new XMLLoader();
        XMLStreamReader parser = XMLInputFactory.newInstance().createXMLStreamReader(reader);

        boolean parsing = true;
        doc = null;
        while (parsing) {
            int event = parser.next();

            if (event == XMLStreamConstants.END_DOCUMENT) {
                parser.close();
                parsing = false;
            } else if (event == XMLStreamConstants.START_ELEMENT && "doc".equals(parser.getLocalName())) {
                doc = loader.readDoc(parser);
            }

        }

    } catch (XMLStreamException | FactoryConfigurationError e) {
        throw new GenericException("Could not process PREMIS " + binary.getStoragePath(), e);
    } finally {
        IOUtils.closeQuietly(reader);
    }

    if (preservationMetadataType == PreservationMetadataType.EVENT && doc != null) {
        try {
            List<LinkingIdentifier> agents = PremisV3Utils.extractAgentsFromEvent(binary);
            for (LinkingIdentifier id : agents) {
                doc.addField(RodaConstants.PRESERVATION_EVENT_LINKING_AGENT_IDENTIFIER,
                        JsonUtils.getJsonFromObject(id));
            }
        } catch (org.roda.core.data.v2.validation.ValidationException e) {
            LOGGER.warn("Error setting linking agent field: {}", e.getMessage());
        }
        try {
            List<LinkingIdentifier> sources = PremisV3Utils.extractObjectFromEvent(binary);
            for (LinkingIdentifier id : sources) {
                doc.addField(RodaConstants.PRESERVATION_EVENT_LINKING_SOURCE_OBJECT_IDENTIFIER,
                        JsonUtils.getJsonFromObject(id));
            }
        } catch (org.roda.core.data.v2.validation.ValidationException e) {
            LOGGER.warn("Error setting linking source field: {}", e.getMessage());
        }
        try {
            List<LinkingIdentifier> outcomes = PremisV3Utils.extractObjectFromEvent(binary);
            for (LinkingIdentifier id : outcomes) {
                doc.addField(RodaConstants.PRESERVATION_EVENT_LINKING_OUTCOME_OBJECT_IDENTIFIER,
                        JsonUtils.getJsonFromObject(id));
            }
        } catch (org.roda.core.data.v2.validation.ValidationException e) {
            LOGGER.warn("Error setting linking outcome field: {}", e.getMessage());
        }

        // indexing active state and permissions
        if (aip != null) {
            doc.addField(RodaConstants.STATE, aip.getState().toString());
            setPermissions(aip.getPermissions(), doc);
        } else {
            doc.addField(RodaConstants.STATE, AIPState.ACTIVE);
        }
    }

    // set uuid from id defined in xslt
    if (doc != null) {
        doc.addField(RodaConstants.INDEX_UUID, doc.getFieldValue(RodaConstants.PRESERVATION_EVENT_ID));
    } else {
        doc = new SolrInputDocument();
    }

    return doc;
}

From source file:org.sakaiproject.nakamura.importer.ImportSiteArchiveServlet.java

private void processContentXml(InputStream in, String sitePath, Session session, ZipFile zip)
        throws XMLStreamException {
    Map<String, Resource> resources = new HashMap<String, Resource>();
    String currentResourceId = null;
    XMLStreamReader reader = xmlInputFactory.createXMLStreamReader(in);
    for (int event = reader.next(); event != XMLStreamReader.END_DOCUMENT; event = reader.next()) {
        String localName = null;//from   www.  ja v a2 s  .  c  o  m
        switch (event) {
        case XMLStreamReader.START_ELEMENT:
            localName = reader.getLocalName();
            if ("archive".equalsIgnoreCase(localName)) {
                final String system = reader.getAttributeValue(null, "system");
                boolean supportedVersion = false;
                for (String version : supportedVersions) {
                    if (version.equalsIgnoreCase(system)) {
                        supportedVersion = true;
                    }
                }
                if (!supportedVersion) {
                    throw new Error("Not a supported version: " + system);
                }
                break;
            }
            if ("collection".equalsIgnoreCase(localName) || "resource".equalsIgnoreCase(localName)) {
                // grab the resource's attributes
                Resource resource = new Resource();
                for (int i = 0; i < reader.getAttributeCount(); i++) {
                    resource.attributes.put(reader.getAttributeLocalName(i).toLowerCase(),
                            reader.getAttributeValue(i));
                }
                currentResourceId = resource.getId();
                resources.put(currentResourceId, resource);
                break;
            }
            if ("property".equalsIgnoreCase(localName)) {
                Resource resource = resources.get(currentResourceId);
                final String name = reader.getAttributeValue(null, "name");
                String value = reader.getAttributeValue(null, "value");
                if (value != null && !"".equals(value)) {
                    if (reader.getAttributeValue(null, "enc").equalsIgnoreCase("BASE64")) {
                        value = new String(base64.decode(value));
                    }
                    resource.properties.put(name, value);
                }
                break;
            }
            break;
        case XMLStreamReader.END_ELEMENT:
            localName = reader.getLocalName();
            if ("collection".equalsIgnoreCase(localName) || "resource".equalsIgnoreCase(localName)) {
                makeResource(resources.get(currentResourceId), sitePath, session, zip);
            }
            break;
        } // end switch
    } // end for
    reader.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 ww  .jav a  2s  .co  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");
    }//w w  w.jav  a 2  s  .  co 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 ww w  .j av 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");
    }

}