Example usage for javax.xml.stream XMLStreamConstants START_ELEMENT

List of usage examples for javax.xml.stream XMLStreamConstants START_ELEMENT

Introduction

In this page you can find the example usage for javax.xml.stream XMLStreamConstants START_ELEMENT.

Prototype

int START_ELEMENT

To view the source code for javax.xml.stream XMLStreamConstants START_ELEMENT.

Click Source Link

Document

Indicates an event is a start element

Usage

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;// ww  w  .jav  a  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

private static void updateFile(File configFile, Map<String, PropertySimple> allProps)
        throws IOException, InterruptedException, XMLStreamException {
    InputStream in = null;//from   ww  w.  j  a  v a2  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;//w  w w . j  ava2s . c om

    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;/*from  w w w.j  a v a2s  . c  om*/

    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.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");
    }//w ww.j ava2s  .  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 ww .  j  a v a2s.  co 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.slc.sli.api.resources.config.StAXMsgBodyReader.java

/**
 * Helper method for digesting XML documents
 * @param reader XML reader//from w  w  w.  ja  v a 2  s.c o m
 * @return EntityBody representation that corresponds to the xml
 * @throws XMLStreamException on malformed XML
 */
private static final EntityBody readDocument(final XMLStreamReader reader) throws XMLStreamException {
    if (XMLStreamConstants.START_DOCUMENT == reader.getEventType()) {
        EntityBody body = null;
        while (reader.hasNext()) {
            reader.next();
            switch (reader.getEventType()) {
            case XMLStreamConstants.START_ELEMENT: {
                body = readDocumentElement(reader);
                return body;
            }
            case XMLStreamConstants.END_DOCUMENT: {
                return body;
            }
            case XMLStreamConstants.CHARACTERS: {
                // Ignore
                break;
            }
            default: {
                throw new XMLStreamException();
            }
            }
        }
    } else {
        throw new XMLStreamException(reader.getLocalName());
    }
    throw new XMLStreamException();
}

From source file:org.slc.sli.api.resources.config.StAXMsgBodyReader.java

/**
 * Reads everything under the main document wrapper tag
 * @param reader Reader that we have for XML
 * @return EntityBody representation of the document
 * @throws XMLStreamException on malformed XML
 *///from w w  w  .ja  va 2s .c om
private static final EntityBody readDocumentElement(final XMLStreamReader reader) throws XMLStreamException {
    final Map<String, Object> elements = new HashMap<String, Object>();
    while (reader.hasNext()) {
        reader.next();
        switch (reader.getEventType()) {
        case XMLStreamConstants.START_ELEMENT: {
            final Pair<Object, Boolean> memberDataPair = readElement(reader);
            addToElements(reader.getLocalName(), memberDataPair, elements);
            break;
        }
        case XMLStreamConstants.END_ELEMENT: {
            return new EntityBody(elements);
        }
        case XMLStreamConstants.CHARACTERS: {
            // Ignore
            break;
        }
        default: {
            throw new XMLStreamException();
        }
        }
    }
    throw new XMLStreamException();
}

From source file:org.slc.sli.api.resources.config.StAXMsgBodyReader.java

/**
 * Reads individual elements inside of a XML Document
 * @param reader xml reader//from   w  ww . j  a  va  2 s.  c  o  m
 * @return a pair representing the Object value of the element (Left) as well as
 *         a boolean value representing either true (part of a list) or false
 *         (single value)
 * @throws XMLStreamException on malformed XML
 */
private static final Pair<Object, Boolean> readElement(final XMLStreamReader reader) throws XMLStreamException {
    final QName elementName = reader.getName();
    final StringBuilder sb = new StringBuilder();
    final Map<String, Object> data = new HashMap<String, Object>();
    final Boolean member = isMember(reader);
    while (reader.hasNext()) {
        reader.next();
        switch (reader.getEventType()) {
        case XMLStreamConstants.START_ELEMENT: {
            final QName key = reader.getName();
            final Pair<Object, Boolean> elem = readElement(reader);
            addToElements(key.getLocalPart(), elem, data);
            break;
        }
        case XMLStreamConstants.END_ELEMENT: {
            if (elementName.equals(reader.getName())) {
                if (data.size() > 0) {
                    return new ImmutablePair<Object, Boolean>(data, member);
                } else {
                    return new ImmutablePair<Object, Boolean>(sb.toString(), member);
                }
            } else {
                throw new XMLStreamException(reader.getName().getLocalPart());
            }
        }
        case XMLStreamConstants.CHARACTERS: {
            sb.append(reader.getText());
            break;
        }
        default: {
            throw new XMLStreamException();
        }
        }
    }
    throw new XMLStreamException();
}