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.unitedinternet.cosmo.model.text.XhtmlPreferenceFormat.java

public Preference parse(String source, EntityFactory entityFactory) throws ParseException {
    Preference pref = entityFactory.createPreference();

    try {// w  w  w. j av  a  2 s . c  o m
        if (source == null) {
            throw new ParseException("Source has no XML data", -1);
        }
        StringReader sr = new StringReader(source);
        XMLStreamReader reader = createXmlReader(sr);

        boolean inPreference = false;
        while (reader.hasNext()) {
            reader.next();
            if (!reader.isStartElement()) {
                continue;
            }

            if (hasClass(reader, "preference")) {
                if (LOG.isDebugEnabled()) {
                    LOG.debug("found preference element");
                }
                inPreference = true;
                continue;
            }

            if (inPreference && hasClass(reader, "key")) {
                if (LOG.isDebugEnabled()) {
                    LOG.debug("found key element");
                }

                String key = reader.getElementText();
                if (StringUtils.isBlank(key)) {
                    handleParseException("Key element must not be empty", reader);
                }
                pref.setKey(key);

                continue;
            }

            if (inPreference && hasClass(reader, "value")) {
                if (LOG.isDebugEnabled()) {
                    LOG.debug("found value element");
                }

                String value = reader.getElementText();
                if (StringUtils.isBlank(value)) {
                    value = "";
                }
                pref.setValue(value);

                continue;
            }
        }

        reader.close();
    } catch (XMLStreamException e) {
        handleXmlException("Error reading XML", e);
    }

    return pref;
}

From source file:org.unitedinternet.cosmo.model.text.XhtmlSubscriptionFormat.java

public CollectionSubscription parse(String source, EntityFactory entityFactory) throws ParseException {
    CollectionSubscription sub = entityFactory.createCollectionSubscription();

    try {// w  w w  . ja va 2 s  .  com
        if (source == null) {
            throw new ParseException("Source has no XML data", -1);
        }
        StringReader sr = new StringReader(source);
        XMLStreamReader reader = createXmlReader(sr);

        boolean inLocalSub = false;
        boolean inCollection = false;
        boolean inTicket = false;
        while (reader.hasNext()) {
            reader.next();
            if (!reader.isStartElement()) {
                continue;
            }

            if (hasClass(reader, "local-subscription")) {
                if (LOG.isDebugEnabled()) {
                    LOG.debug("found local-subscription element");
                }
                inLocalSub = true;
                continue;
            }

            if (inLocalSub && hasClass(reader, "name")) {
                if (LOG.isDebugEnabled()) {
                    LOG.debug("found name element");
                }

                String name = reader.getElementText();
                if (StringUtils.isBlank(name)) {
                    handleParseException("Name element must not be empty", reader);
                }
                sub.setDisplayName(name);

                continue;
            }

            if (inLocalSub && hasClass(reader, "collection")) {
                if (LOG.isDebugEnabled()) {
                    LOG.debug("found collection element");
                }
                inCollection = true;
                inTicket = false;
                continue;
            }

            if (inCollection && hasClass(reader, "uuid")) {
                if (LOG.isDebugEnabled()) {
                    LOG.debug("found uuid element");
                }

                String uuid = reader.getElementText();
                if (StringUtils.isBlank(uuid)) {
                    handleParseException("Uuid element must not be empty", reader);
                }
                sub.setCollectionUid(uuid);

                continue;
            }

            if (inLocalSub && hasClass(reader, "ticket")) {
                if (LOG.isDebugEnabled()) {
                    LOG.debug("found ticket element");
                }
                inCollection = false;
                inTicket = true;
                continue;
            }

            if (inTicket && hasClass(reader, "key")) {
                if (LOG.isDebugEnabled()) {
                    LOG.debug("found key element");
                }

                String key = reader.getElementText();
                if (StringUtils.isBlank(key)) {
                    handleParseException("Key element must not be empty", reader);
                }
                sub.setTicketKey(key);

                continue;
            }
        }

        reader.close();
    } catch (XMLStreamException e) {
        handleXmlException("Error reading XML", e);
    }

    return sub;
}

From source file:org.unitedinternet.cosmo.model.text.XhtmlTicketFormat.java

public Ticket parse(String source, EntityFactory entityFactory) throws ParseException {

    String key = null;// w  w  w  . ja  va2  s  .  co m
    TicketType type = null;
    Integer timeout = null;
    try {
        if (source == null) {
            throw new ParseException("Source has no XML data", -1);
        }
        StringReader sr = new StringReader(source);
        XMLStreamReader reader = createXmlReader(sr);

        boolean inTicket = false;
        while (reader.hasNext()) {
            reader.next();
            if (!reader.isStartElement()) {
                continue;
            }

            if (hasClass(reader, "ticket")) {
                if (LOG.isDebugEnabled()) {
                    LOG.debug("found ticket element");
                }
                inTicket = true;
                continue;
            }

            if (inTicket && hasClass(reader, "key")) {
                if (LOG.isDebugEnabled()) {
                    LOG.debug("found key element");
                }

                key = reader.getElementText();
                if (StringUtils.isBlank(key)) {
                    handleParseException("Key element must not be empty", reader);
                }

                continue;
            }

            if (inTicket && hasClass(reader, "type")) {
                if (LOG.isDebugEnabled()) {
                    LOG.debug("found type element");
                }

                String typeId = reader.getAttributeValue(null, "title");
                if (StringUtils.isBlank(typeId)) {
                    handleParseException("Ticket type title must not be empty", reader);
                }
                type = TicketType.createInstance(typeId);

                continue;
            }
            if (inTicket && hasClass(reader, "timeout")) {
                if (LOG.isDebugEnabled()) {
                    LOG.debug("found timeout element");
                }

                String timeoutString = reader.getAttributeValue(null, "title");
                if (StringUtils.isBlank(timeoutString)) {
                    timeout = null;
                } else {
                    timeout = Integer.getInteger(timeoutString);
                }

                continue;
            }
        }
        if (type == null || key == null) {
            handleParseException("Ticket must have type and key", reader);
        }
        reader.close();
    } catch (XMLStreamException e) {
        handleXmlException("Error reading XML", e);
    }

    Ticket ticket = entityFactory.createTicket(type);
    ticket.setKey(key);
    if (timeout == null) {
        ticket.setTimeout(Ticket.TIMEOUT_INFINITE);
    } else {
        ticket.setTimeout(timeout);
    }

    return ticket;
}

From source file:org.unitedinternet.cosmo.util.DomReader.java

private static Node readNode(Document d, XMLStreamReader reader) throws XMLStreamException {
    Node root = null;/* w w  w. j  a  v a2 s .co  m*/
    Node current = null;

    while (reader.hasNext()) {
        reader.next();

        if (reader.isEndElement()) {
            //log.debug("Finished reading " + current.getNodeName());

            if (current.getParentNode() == null) {
                break;
            }

            //log.debug("Setting current to " +
            //current.getParentNode().getNodeName());
            current = current.getParentNode();
        }

        if (reader.isStartElement()) {
            Element e = readElement(d, reader);
            if (root == null) {
                //log.debug("Setting root to " + e.getNodeName());
                root = e;
            }

            if (current != null) {
                //log.debug("Appending child " + e.getNodeName() + " to " +
                //current.getNodeName());
                current.appendChild(e);
            }

            //log.debug("Setting current to " + e.getNodeName());
            current = e;

            continue;
        }

        if (reader.isCharacters()) {
            CharacterData cd = d.createTextNode(reader.getText());
            if (root == null) {
                return cd;
            }
            if (current == null) {
                return cd;
            }

            //log.debug("Appending text '" + cd.getData() + "' to " +
            //current.getNodeName());
            current.appendChild(cd);

            continue;
        }
    }

    return root;
}

From source file:org.ut.biolab.medsavant.client.plugin.AppController.java

public AppDescriptor getDescriptorFromFile(File f) throws PluginVersionException {
    XMLStreamReader reader;

    try {/*from  w  w  w  .j  ava 2 s  .co m*/
        JarFile jar = new JarFile(f);
        ZipEntry entry = jar.getEntry("plugin.xml");
        if (entry != null) {
            InputStream entryStream = jar.getInputStream(entry);
            reader = XMLInputFactory.newInstance().createXMLStreamReader(entryStream);
            String className = null;
            String id = null;
            String version = null;
            String sdkVersion = null;
            String name = null;
            String category = AppDescriptor.Category.UTILITY.toString();
            String currentElement = null;
            String currentText = "";
            do {
                switch (reader.next()) {
                case XMLStreamConstants.START_ELEMENT:
                    switch (readElement(reader)) {
                    case PLUGIN:
                        className = readAttribute(reader, AppDescriptor.PluginXMLAttribute.CLASS);

                        //category can be specified as an attribute or <property>.
                        category = readAttribute(reader, AppDescriptor.PluginXMLAttribute.CATEGORY);
                        break;

                    case ATTRIBUTE:
                        if ("sdk-version".equals(readAttribute(reader, AppDescriptor.PluginXMLAttribute.ID))) {
                            sdkVersion = readAttribute(reader, AppDescriptor.PluginXMLAttribute.VALUE);
                        }
                        break;

                    case PARAMETER:
                        if ("name".equals(readAttribute(reader, AppDescriptor.PluginXMLAttribute.ID))) {
                            name = readAttribute(reader, AppDescriptor.PluginXMLAttribute.VALUE);
                        }
                        break;

                    case PROPERTY:
                        if ("name".equals(readAttribute(reader, AppDescriptor.PluginXMLAttribute.NAME))) {
                            name = readAttribute(reader, AppDescriptor.PluginXMLAttribute.VALUE);
                            if (name == null) {
                                currentElement = "name";
                            }
                        }

                        if ("version".equals(readAttribute(reader, AppDescriptor.PluginXMLAttribute.NAME))) {
                            version = readAttribute(reader, AppDescriptor.PluginXMLAttribute.VALUE);
                            if (version == null) {
                                currentElement = "version";
                            }
                        }

                        if ("sdk-version"
                                .equals(readAttribute(reader, AppDescriptor.PluginXMLAttribute.NAME))) {
                            sdkVersion = readAttribute(reader, AppDescriptor.PluginXMLAttribute.VALUE);
                            if (sdkVersion == null) {
                                currentElement = "sdk-version";
                            }
                        }

                        if ("category".equals(readAttribute(reader, AppDescriptor.PluginXMLAttribute.NAME))) {
                            category = readAttribute(reader, AppDescriptor.PluginXMLAttribute.VALUE);
                            if (category == null) {
                                currentElement = "category";
                            }
                        }

                        break;
                    }
                    break;

                case XMLStreamConstants.CHARACTERS:
                    if (reader.isWhiteSpace()) {
                        break;
                    } else if (currentElement != null) {
                        currentText += reader.getText().trim().replace("\t", "");
                    }
                    break;

                case XMLStreamConstants.END_ELEMENT:
                    if (readElement(reader) == AppDescriptor.PluginXMLElement.PROPERTY) {
                        if (currentElement != null && currentText.length() > 0) {
                            if (currentElement.equals("name")) {
                                name = currentText;
                            } else if (currentElement.equals("sdk-version")) {
                                sdkVersion = currentText;
                            } else if (currentElement.equals("category")) {
                                category = currentText;
                            } else if (currentElement.equals("version")) {
                                version = currentText;
                            }
                        }
                        currentText = "";
                        currentElement = null;
                    }
                    break;

                case XMLStreamConstants.END_DOCUMENT:
                    reader.close();
                    reader = null;
                    break;
                }
            } while (reader != null);

            System.out.println(className + " " + name + " " + version);

            if (className != null && name != null && version != null) {
                return new AppDescriptor(className, version, name, sdkVersion, category, f);
            }
        }
    } catch (Exception x) {
        LOG.error("Error parsing plugin.xml from " + f.getAbsolutePath() + ": " + x);
    }
    throw new PluginVersionException(f.getName() + " did not contain a valid plugin");
}

From source file:org.ut.biolab.medsavant.client.plugin.PluginIndex.java

public PluginIndex(URL url) throws IOException {
    urls = new HashMap<String, URL>();
    try {// w  ww.j  a v  a2s  .  co m

        XMLStreamReader reader = XMLInputFactory.newInstance().createXMLStreamReader(
                ClientNetworkUtils.openStream(url, ClientNetworkUtils.NONCRITICAL_CONNECT_TIMEOUT,
                        ClientNetworkUtils.NONCRITICAL_READ_TIMEOUT));
        if (reader.getVersion() == null) {
            throw new XMLStreamException("Invalid XML at URL " + url);
        }
        boolean done = false;
        String id = null;
        do {
            if (reader.hasNext()) {
                int t = reader.next();
                switch (t) {
                case XMLStreamConstants.START_ELEMENT:
                    String elemName = reader.getLocalName();
                    if (elemName.equals("leaf")) {
                        id = reader.getAttributeValue(null, "id");
                    } else if (elemName.equals("url")) {
                        if (id != null) {
                            try {
                                urls.put(id, new URL(reader.getElementText()));
                            } catch (MalformedURLException x) {
                                LOG.warn(String.format("Unable to parse \"%s\" as a plugin URL.",
                                        reader.getElementText()));
                            }
                            id = null;
                        }
                    }
                    break;
                case XMLStreamConstants.END_DOCUMENT:
                    reader.close();
                    done = true;
                    break;
                }
            } else {
                throw new XMLStreamException("Malformed XML at " + url);
            }
        } while (!done);
    } catch (XMLStreamException x) {
        throw new IOException("Unable to get version number from web-site.", x);
    }
}

From source file:org.wso2.carbon.registry.core.jdbc.Repository.java

@SuppressWarnings("deprecation")
private void restoreRecursively(String path, XMLStreamReader xmlReader, DumpReader dumpReader,
        long currentVersion, boolean resourceExists) throws RegistryException, XMLStreamException {
    // we need to check the authorization with the current resource path at this point
    if (!AuthorizationUtils.authorize(path, ActionConstants.PUT)) {
        String msg = "Failed to check-in resource " + path + ". User " + CurrentSession.getUser()
                + " is not authorized to update " + "the current collection path " + path + ".";
        log.warn(msg);//from  ww w  . ja v  a2s.co m
        throw new AuthorizationFailedException(msg);
    }

    while (!xmlReader.isStartElement() && xmlReader.hasNext()) {
        xmlReader.next();
    }

    if (!xmlReader.hasNext()) {
        // nothing to parse
        return;
    }

    if (!xmlReader.getLocalName().equals(DumpConstants.RESOURCE)) {
        String msg = "Invalid dump to restore at " + path;
        log.error(msg);
        throw new RegistryException(msg);
    }

    String incomingParentPath = xmlReader.getAttributeValue(null, DumpConstants.RESOURCE_PATH);
    // the name of the resource is used instead of the path
    String resourceName = xmlReader.getAttributeValue(null, DumpConstants.RESOURCE_NAME);
    String ignoreConflictsStrValue = xmlReader.getAttributeValue(null, DumpConstants.IGNORE_CONFLICTS);

    boolean ignoreConflicts = true;
    if (ignoreConflictsStrValue != null && Boolean.toString(false).equals(ignoreConflictsStrValue)) {
        ignoreConflicts = false;
    }

    String isCollectionString = xmlReader.getAttributeValue(null, DumpConstants.RESOURCE_IS_COLLECTION);
    boolean isCollection = isCollectionString.equals(DumpConstants.RESOURCE_IS_COLLECTION_TRUE);

    if (path.equals(RegistryConstants.ROOT_PATH) && !isCollection) {
        // you can not put non collection to the root path
        String msg = "Illegal to restore a non-collection in place of root collection.";
        log.error(msg);
        throw new RegistryException(msg);
    }

    String status = xmlReader.getAttributeValue(null, DumpConstants.RESOURCE_STATUS);

    //if the status is deleted we delete that resource/collection
    if (DumpConstants.RESOURCE_DELETED.equals(status) && resourceExists) {
        delete(path);
        return;
    }

    ResourceImpl resourceImpl;
    byte[] contentBytes = new byte[0];
    if (isCollection) {
        resourceImpl = new CollectionImpl();
    } else {
        resourceImpl = new ResourceImpl();
    }

    List<CommentDO> commentDOList = new ArrayList<CommentDO>();
    List<TaggingDO> taggingDOList = new ArrayList<TaggingDO>();
    List<RatingDO> ratingDOList = new ArrayList<RatingDO>();
    List<Association> associationList = new ArrayList<Association>();

    boolean isCreatorExisting = false;
    boolean isCreatedTimeExisting = false;
    boolean isUpdaterExisting = false;
    boolean isUpdatedTimeExisting = false;
    long dumpingResourceVersion = -1;

    // traversing to the next element
    do {
        xmlReader.next();
    } while (!xmlReader.isStartElement() && xmlReader.hasNext());

    while (xmlReader.hasNext()) {
        String localName = xmlReader.getLocalName();

        // setMediaType
        if (localName.equals(DumpConstants.MEDIA_TYPE)) {
            String text = xmlReader.getElementText();
            if (text.indexOf('/') < 0) {
                text = MediaTypesUtils.getMediaType("dummy." + text);
            }
            if (text != null) {
                resourceImpl.setMediaType(text);
            }
            // now go to the next element
            do {
                xmlReader.next();
            } while (!xmlReader.isStartElement() && xmlReader.hasNext());
        }
        // creator
        else if (localName.equals(DumpConstants.CREATOR)) {
            String text = xmlReader.getElementText();
            if (text != null) {
                resourceImpl.setAuthorUserName(text);
                isCreatorExisting = true;
            }
            // now go to the next element
            do {
                xmlReader.next();
            } while (!xmlReader.isStartElement() && xmlReader.hasNext());
        }
        // version: just to keep track of the server changes
        else if (localName.equals(DumpConstants.VERSION)) {
            String text = xmlReader.getElementText();
            if (text != null) {
                dumpingResourceVersion = Long.parseLong(text);
            }
            // now go to the next element
            do {
                xmlReader.next();
            } while (!xmlReader.isStartElement() && xmlReader.hasNext());
        }
        // uuid: just to keep track of the server changes
        else if (localName.equals(DumpConstants.UUID)) {
            String text = xmlReader.getElementText();
            if (text != null) {
                resourceImpl.setUUID(text);
            }
            // now go to the next element
            do {
                xmlReader.next();
            } while (!xmlReader.isStartElement() && xmlReader.hasNext());
        }
        // createdTime
        else if (localName.equals(DumpConstants.CREATED_TIME)) {
            String text = xmlReader.getElementText();
            if (text != null) {
                long date = Long.parseLong(text);
                resourceImpl.setCreatedTime(new Date(date));
                isCreatedTimeExisting = true;
            }
            // now go to the next element
            do {
                xmlReader.next();
            } while (!xmlReader.isStartElement() && xmlReader.hasNext());
        }
        // setLastUpdater
        else if (localName.equals(DumpConstants.LAST_UPDATER)) {
            String text = xmlReader.getElementText();
            if (text != null) {
                resourceImpl.setLastUpdaterUserName(text);
                isUpdaterExisting = true;
            }
            // now go to the next element
            do {
                xmlReader.next();
            } while (!xmlReader.isStartElement() && xmlReader.hasNext());
        }
        // LastModified
        else if (localName.equals(DumpConstants.LAST_MODIFIED)) {
            String text = xmlReader.getElementText();
            if (text != null) {
                long date = Long.parseLong(text);
                resourceImpl.setLastModified(new Date(date));
                isUpdatedTimeExisting = true;
            }
            // now go to the next element
            do {
                xmlReader.next();
            } while (!xmlReader.isStartElement() && xmlReader.hasNext());
        }
        // get description
        else if (localName.equals(DumpConstants.DESCRIPTION)) {
            String text = xmlReader.getElementText();
            if (text != null) {
                resourceImpl.setDescription(text);
            }
            // now go to the next element
            do {
                xmlReader.next();
            } while (!xmlReader.isStartElement() && xmlReader.hasNext());
        }
        // get properties
        else if (localName.equals(DumpConstants.PROPERTIES)) {
            // iterating trying to find the children..
            do {
                xmlReader.next();
            } while (!xmlReader.isStartElement() && xmlReader.hasNext());
            while (xmlReader.hasNext() && xmlReader.getLocalName().equals(DumpConstants.PROPERTY_ENTRY)) {
                String key = xmlReader.getAttributeValue(null, DumpConstants.PROPERTY_ENTRY_KEY);
                String text = xmlReader.getElementText();
                if (text.equals("")) {
                    text = null;
                }
                if (text != null) {
                    resourceImpl.addPropertyWithNoUpdate(key, text);
                }
                do {
                    xmlReader.next();
                } while (!xmlReader.isStartElement() && xmlReader.hasNext());
            }
        }
        // get content
        else if (localName.equals(DumpConstants.CONTENT)) {
            String text = xmlReader.getElementText();
            // we keep content as base64 encoded
            if (text != null) {
                contentBytes = Base64.decode(text);
            }
            do {
                xmlReader.next();
            } while ((!xmlReader.isStartElement() && xmlReader.hasNext())
                    && !(xmlReader.isEndElement() && xmlReader.getLocalName().equals(DumpConstants.RESOURCE)));
        }
        // getting comment information
        else if (localName.equals(DumpConstants.COMMENTS)) {
            // iterating trying to find the children..
            do {
                xmlReader.next();
            } while (!xmlReader.isStartElement() && xmlReader.hasNext());
            while (xmlReader.hasNext() && xmlReader.getLocalName().equals(DumpConstants.COMMENT_ENTRY)) {
                CommentDO commentDO = new CommentDO();

                do {
                    xmlReader.next();
                } while (!xmlReader.isStartElement() && xmlReader.hasNext());

                localName = xmlReader.getLocalName();
                while (xmlReader.hasNext() && (localName.equals(DumpConstants.COMMENT_ENTRY_USER)
                        || localName.equals(DumpConstants.COMMENT_ENTRY_TEXT))) {
                    if (localName.equals(DumpConstants.COMMENT_ENTRY_USER)) {
                        String text = xmlReader.getElementText();
                        if (text != null) {
                            commentDO.setCommentedUser(text);
                        }
                    } else if (localName.equals(DumpConstants.COMMENT_ENTRY_TEXT)) {
                        String text = xmlReader.getElementText();
                        if (text != null) {
                            commentDO.setCommentText(text);
                        }
                    }

                    do {
                        xmlReader.next();
                    } while (!xmlReader.isStartElement() && xmlReader.hasNext());
                    if (xmlReader.hasNext()) {
                        localName = xmlReader.getLocalName();
                    }
                }
                commentDOList.add(commentDO);
            }
        }
        // getting tagging information
        else if (localName.equals(DumpConstants.TAGGINGS)) {
            // iterating trying to find the children..
            do {
                xmlReader.next();
            } while (!xmlReader.isStartElement() && xmlReader.hasNext());
            while (xmlReader.hasNext() && xmlReader.getLocalName().equals(DumpConstants.TAGGING_ENTRY)) {

                TaggingDO taggingDO = new TaggingDO();

                do {
                    xmlReader.next();
                } while (!xmlReader.isStartElement() && xmlReader.hasNext());

                localName = xmlReader.getLocalName();
                while (xmlReader.hasNext() && (localName.equals(DumpConstants.TAGGING_ENTRY_USER)
                        || localName.equals(DumpConstants.TAGGING_ENTRY_DATE)
                        || localName.equals(DumpConstants.TAGGING_ENTRY_TAG_NAME))) {
                    if (localName.equals(DumpConstants.TAGGING_ENTRY_USER)) {
                        String text = xmlReader.getElementText();
                        if (text != null) {
                            taggingDO.setTaggedUserName(text);
                        }
                    } else if (localName.equals(DumpConstants.TAGGING_ENTRY_DATE)) {
                        String text = xmlReader.getElementText();
                        if (text != null) {
                            long date = Long.parseLong(text);
                            taggingDO.setTaggedTime(new Date(date));
                        }
                    } else if (localName.equals(DumpConstants.TAGGING_ENTRY_TAG_NAME)) {
                        String text = xmlReader.getElementText();
                        if (text != null) {
                            taggingDO.setTagName(text);
                        }
                    }
                    do {
                        xmlReader.next();
                    } while (!xmlReader.isStartElement() && xmlReader.hasNext());
                    if (xmlReader.hasNext()) {
                        localName = xmlReader.getLocalName();
                    }
                }
                taggingDOList.add(taggingDO);
            }
        }
        // getting rating information
        else if (localName.equals(DumpConstants.RATINGS)) {
            // iterating trying to find the children..
            do {
                xmlReader.next();
            } while (!xmlReader.isStartElement() && xmlReader.hasNext());
            while (xmlReader.hasNext() && xmlReader.getLocalName().equals(DumpConstants.RATING_ENTRY)) {
                RatingDO ratingDO = new RatingDO();

                do {
                    xmlReader.next();
                } while (!xmlReader.isStartElement() && xmlReader.hasNext());

                localName = xmlReader.getLocalName();
                while (xmlReader.hasNext() && (localName.equals(DumpConstants.RATING_ENTRY_USER)
                        || localName.equals(DumpConstants.RATING_ENTRY_DATE)
                        || localName.equals(DumpConstants.RATING_ENTRY_RATE))) {
                    if (localName.equals(DumpConstants.RATING_ENTRY_USER)) {
                        String text = xmlReader.getElementText();
                        if (text != null) {
                            ratingDO.setRatedUserName(text);
                        }
                    } else if (localName.equals(DumpConstants.RATING_ENTRY_DATE)) {
                        String text = xmlReader.getElementText();
                        if (text != null) {
                            long date = Long.parseLong(text);
                            ratingDO.setRatedTime(new Date(date));
                        }
                    } else if (localName.equals(DumpConstants.RATING_ENTRY_RATE)) {
                        String text = xmlReader.getElementText();
                        if (text != null) {
                            int ratingValue = Integer.parseInt(text);
                            ratingDO.setRating(ratingValue);
                        }
                    }
                    do {
                        xmlReader.next();
                    } while (!xmlReader.isStartElement() && xmlReader.hasNext());
                    if (xmlReader.hasNext()) {
                        localName = xmlReader.getLocalName();
                    }
                }
                ratingDOList.add(ratingDO);
            }
        }

        // getting rating information
        else if (localName.equals(DumpConstants.ASSOCIATIONS)) {
            // iterating trying to find the children..
            do {
                xmlReader.next();
            } while (!xmlReader.isStartElement() && xmlReader.hasNext());
            while (xmlReader.hasNext() && xmlReader.getLocalName().equals(DumpConstants.ASSOCIATION_ENTRY)) {
                String source = null;
                String destination = null;
                String type = null;

                do {
                    xmlReader.next();
                } while (!xmlReader.isStartElement() && xmlReader.hasNext());

                localName = xmlReader.getLocalName();
                while (xmlReader.hasNext() && (localName.equals(DumpConstants.ASSOCIATION_ENTRY_SOURCE)
                        || localName.equals(DumpConstants.ASSOCIATION_ENTRY_DESTINATION)
                        || localName.equals(DumpConstants.ASSOCIATION_ENTRY_TYPE))) {
                    if (localName.equals(DumpConstants.ASSOCIATION_ENTRY_SOURCE)) {
                        String text = xmlReader.getElementText();
                        if (text != null) {
                            source = text;
                        }
                    } else if (localName.equals(DumpConstants.ASSOCIATION_ENTRY_DESTINATION)) {
                        String text = xmlReader.getElementText();
                        if (text != null) {
                            destination = text;
                        }
                    } else if (localName.equals(DumpConstants.ASSOCIATION_ENTRY_TYPE)) {
                        String text = xmlReader.getElementText();
                        if (text != null) {
                            type = text;
                        }
                    }
                    do {
                        xmlReader.next();
                    } while (!xmlReader.isStartElement() && xmlReader.hasNext());
                    if (xmlReader.hasNext()) {
                        localName = xmlReader.getLocalName();
                    }
                }
                // get the source and destination as absolute paths
                source = RegistryUtils.getAbsoluteAssociationPath(source, path);
                if (destination.startsWith(DumpConstants.EXTERNAL_ASSOCIATION_DESTINATION_PREFIX)) {
                    destination = destination
                            .substring(DumpConstants.EXTERNAL_ASSOCIATION_DESTINATION_PREFIX.length());
                } else {
                    destination = RegistryUtils.getAbsoluteAssociationPath(destination, path);
                }
                associationList.add(new Association(source, destination, type));
            }
        }
        // getting children, just storing in array list now, will used at the end
        // we are keeping old name to keep backward compatibility.
        else if (localName.equals(DumpConstants.CHILDREN) || localName.equals(DumpConstants.CHILDS)) {
            // we keep the stream to call this function recursively
            break;
        } else if (localName.equals(DumpConstants.RESOURCE)) {
            // we keep the stream to call this function recursively
            break;
        } else {
            // we don't mind having unwanted elements, now go to the next element
            do {
                xmlReader.next();
            } while (!xmlReader.isStartElement() && xmlReader.hasNext());
        }
    }
    if (!ignoreConflicts) {
        // so we handling the conflicts.
        if (dumpingResourceVersion > 0) {
            if (currentVersion == -1) {
                // the current version == -1 means the resource is deleted in the server
                // but since the client is sending a version number, it has a previously checkout
                // resource
                String msg = "Resource is deleted in the server, resource path: " + path + ".";
                log.error(msg);
                throw new RegistryException(msg);
            }
            // we should check whether our dump is up-to-date
            if (currentVersion > dumpingResourceVersion) {
                // that mean the current resource is updated before the current version
                // so we have to notify user to get an update
                String msg = "Resource is in a newer version than the restoring version. " + "resource path: "
                        + path + ".";
                log.error(msg);
                throw new RegistryException(msg);
            }
        }
    }

    // completing the empty fields
    if (!isCreatorExisting) {
        String creator = CurrentSession.getUser();
        resourceImpl.setAuthorUserName(creator);
    }
    if (!isCreatedTimeExisting) {
        long now = System.currentTimeMillis();
        resourceImpl.setCreatedTime(new Date(now));
    }
    if (!isUpdaterExisting) {
        String updater = CurrentSession.getUser();
        resourceImpl.setLastUpdaterUserName(updater);
    }
    if (!isUpdatedTimeExisting) {
        long now = System.currentTimeMillis();
        resourceImpl.setLastModified(new Date(now));
    }

    if (resourceImpl.getUUID() == null) {
        setUUIDForResource(resourceImpl);
    }

    // create sym links
    String linkRestoration = resourceImpl.getProperty(RegistryConstants.REGISTRY_LINK_RESTORATION);
    if (linkRestoration != null) {
        String[] parts = linkRestoration.split(RegistryConstants.URL_SEPARATOR);
        if (parts.length == 4) {
            if (parts[2] != null && parts[2].length() == 0) {
                parts[2] = null;
            }
            if (parts[0] != null && parts[1] != null && parts[3] != null) {
                RegistryUtils.registerHandlerForRemoteLinks(RegistryContext.getBaseInstance(), parts[0],
                        parts[1], parts[2], parts[3]);
            }
        } else if (parts.length == 3) {
            // here parts[0] the current path, path[1] is the target path.
            if (parts[0] != null && parts[1] != null) {
                // first we are calculating the relative path of path[1] to path[0]
                String relativeTargetPath = RegistryUtils.getRelativeAssociationPath(parts[1], parts[0]);
                // then we derive the absolute path with reference to the current path.
                String absoluteTargetPath = RegistryUtils.getAbsoluteAssociationPath(relativeTargetPath, path);
                RegistryUtils.registerHandlerForSymbolicLinks(RegistryContext.getBaseInstance(), path,
                        absoluteTargetPath, parts[2]);
            }
        }
    }

    synchronized (this) {
        ResourceIDImpl resourceID = null;
        ResourceDO resourceDO = null;
        if (resourceDAO.resourceExists(path)) {
            resourceID = resourceDAO.getResourceID(path);
            resourceDO = resourceDAO.getResourceDO(resourceID);
            if (resourceDO == null) {
                if (isCollection) {
                    resourceID = resourceDAO.getResourceID(path, isCollection);
                    if (resourceID != null) {
                        resourceDO = resourceDAO.getResourceDO(resourceID);
                    }
                }
                if (resourceDO == null) {
                    return;
                }
            }
        }

        if (DumpConstants.RESOURCE_UPDATED.equals(status) || DumpConstants.RESOURCE_ADDED.equals(status)
                || DumpConstants.RESOURCE_DUMP.equals(status)) {
            if (resourceDAO.resourceExists(path)) {
                if (DumpConstants.RESOURCE_DUMP.equals(status)) {
                    delete(path);
                } else {
                    deleteNode(resourceID, resourceDO, true);
                }
            }
            if (resourceID == null) {
                // need to create a resourceID
                String parentPath = RegistryUtils.getParentPath(path);

                ResourceIDImpl parentResourceID = resourceDAO.getResourceID(parentPath, true);
                if (parentResourceID == null || !resourceDAO.resourceExists(parentResourceID)) {
                    addEmptyCollection(parentPath);
                    if (parentResourceID == null) {
                        parentResourceID = resourceDAO.getResourceID(parentPath, true);
                    }
                }
                resourceDAO.createAndApplyResourceID(path, parentResourceID, resourceImpl);
            } else {
                resourceImpl.setPathID(resourceID.getPathID());
                resourceImpl.setPath(path);
                resourceImpl.setName(resourceID.getName());
            }

            // adding resource followed by content (for nonCollection)
            if (!isCollection) {
                int contentId = 0;
                if (contentBytes.length > 0) {
                    contentId = resourceDAO.addContentBytes(new ByteArrayInputStream(contentBytes));
                }
                resourceImpl.setDbBasedContentID(contentId);
            }

            resourceDO = resourceImpl.getResourceDO();
            resourceDAO.addResourceDO(resourceDO);
            resourceImpl.setVersionNumber(resourceDO.getVersion());

            // adding the properties.
            resourceDAO.addProperties(resourceImpl);

            // adding comments
            commentsDAO.addComments(resourceImpl, commentDOList.toArray(new CommentDO[commentDOList.size()]));

            // adding tags
            tagsDAO.addTaggings(resourceImpl, taggingDOList.toArray(new TaggingDO[taggingDOList.size()]));

            // adding ratings
            ratingsDAO.addRatings(resourceImpl, ratingDOList.toArray(new RatingDO[ratingDOList.size()]));

            for (Association association : associationList) {
                associationDAO.addAssociation(association.getSourcePath(), association.getDestinationPath(),
                        association.getAssociationType());
            }
        }
    }

    if (!xmlReader.hasNext() || !(xmlReader.getLocalName().equals(DumpConstants.CHILDREN)
            || xmlReader.getLocalName().equals(DumpConstants.CHILDS))) {
        // finished the recursion
        return;
    }

    do {
        xmlReader.next();
        if (xmlReader.isEndElement() && (xmlReader.getLocalName().equals(DumpConstants.CHILDREN)
                || xmlReader.getLocalName().equals(DumpConstants.CHILDS))) {
            // this means empty children, just quit from here
            // before that we have to set the cursor to the start of the next element
            if (xmlReader.hasNext()) {
                do {
                    xmlReader.next();
                } while ((!xmlReader.isStartElement() && xmlReader.hasNext()) && !(xmlReader.isEndElement()
                        && xmlReader.getLocalName().equals(DumpConstants.RESOURCE)));
            }
            Resource resource = get(path);
            if (resource instanceof Collection) {
                String[] existingChildren = ((Collection) resource).getChildren();
                for (String existingChild : existingChildren) {
                    delete(existingChild);
                }
            }
            return;
        }
    } while (!xmlReader.isStartElement() && xmlReader.hasNext());

    int i = 0;
    if (xmlReader.hasNext() && xmlReader.getLocalName().equals(DumpConstants.RESOURCE)) {
        Set<String> childPathSet = new HashSet<String>();
        while (true) {
            if (i != 0) {
                dumpReader.setReadingChildResourceIndex(i);

                // otherwise we will set the stuff for the next resource
                // get an xlm reader in the checking child by parent mode.
                xmlReader = XMLInputFactory.newInstance().createXMLStreamReader(dumpReader);

                while (!xmlReader.isStartElement() && xmlReader.hasNext()) {
                    xmlReader.next();
                }
            }

            String absoluteChildPath;
            if (incomingParentPath != null) {
                // the code to support backward compatibility.
                // prepare the children absolute path
                String incomingChildPath = xmlReader.getAttributeValue(null, DumpConstants.RESOURCE_PATH);
                /*                    if (!incomingChildPath.startsWith(incomingParentPath)) {
                //break;
                                    }*/

                String relativeChildPath;
                if (incomingParentPath.equals(RegistryConstants.ROOT_PATH)) {
                    relativeChildPath = incomingChildPath;
                } else {
                    if (incomingParentPath.contains(incomingChildPath)) {
                        relativeChildPath = incomingChildPath.substring(incomingParentPath.length());
                    } else {
                        // this happens only at some custom editing of dump.xml
                        relativeChildPath = null;
                    }
                }
                if (relativeChildPath != null) {
                    if (path.equals(RegistryConstants.ROOT_PATH)) {
                        absoluteChildPath = relativeChildPath;
                    } else {
                        absoluteChildPath = path + relativeChildPath;
                    }
                } else {
                    String checkoutRoot = path.substring(0, path.length() - incomingParentPath.length());
                    absoluteChildPath = checkoutRoot + incomingChildPath;
                }
            } else if (resourceName != null) {
                String childName = xmlReader.getAttributeValue(null, DumpConstants.RESOURCE_NAME);
                absoluteChildPath = path
                        + (path.equals(RegistryConstants.ROOT_PATH) ? "" : RegistryConstants.PATH_SEPARATOR)
                        + childName;
            } else {
                String msg = "Error in deriving the child paths for collection. path: " + path + ".";
                log.error(msg);
                throw new RegistryException(msg);
            }

            // we give the control back to the child.
            dumpReader.setCheckingChildByParent(false);

            dumpReader.setReadingChildResourceIndex(i);
            // call the check in method recursively

            recursionRepository.restoreRecursively(absoluteChildPath, dumpReader);
            childPathSet.add(absoluteChildPath);

            dumpReader.setCheckingChildByParent(true);
            try {
                if (dumpReader.isLastResource(i)) {
                    dumpReader.setCheckingChildByParent(false);
                    break;
                }
            } catch (IOException e) {
                String msg = "Error in checking the last resource exists.";
                log.error(msg, e);
                throw new RegistryException(msg + e.getMessage(), e);
            }
            // by this time i ++ child resource should exist
            i++;
        }
        Collection parent = (Collection) get(path);
        String[] existingChildren = parent.getChildren();
        for (String existingChild : existingChildren) {
            if (!childPathSet.contains(existingChild)) {
                delete(existingChild);
            }
        }
    }
}

From source file:org.wso2.carbon.registry.synchronization.operation.CheckOutCommand.java

private void checkOutRecursively(XMLStreamReader xmlReader, String filePath, String path,
        UserInputCallback callback) throws SynchronizationException, XMLStreamException {
    // we will first generate the axiom node from the reader,
    OMElement root = Utils.readMetaElement(xmlReader);
    // adding path and the registryUrl
    root.addAttribute(DumpConstants.RESOURCE_PATH, path, null);
    if (registryUrl != null) {
        root.addAttribute("registryUrl", registryUrl, null);
    }//  w  ww  .ja  v a2s . co  m

    String isCollectionString = root.getAttributeValue(new QName(DumpConstants.RESOURCE_IS_COLLECTION));
    boolean isCollection = isCollectionString.equals("true");

    String name = root.getAttributeValue(new QName(DumpConstants.RESOURCE_NAME));

    byte[] contentBytes = new byte[0];
    File file = new File(filePath);
    boolean overwrite = true;
    boolean fileAlreadyExist = false;

    String parentDirName = file.getAbsoluteFile().getParent();

    String metaDirectoryName;
    String metaFilePath;
    if (isCollection) {
        metaDirectoryName = filePath + File.separator + SynchronizationConstants.META_DIRECTORY;
        metaFilePath = filePath + File.separator + SynchronizationConstants.META_DIRECTORY + File.separator
                + SynchronizationConstants.META_FILE_PREFIX + SynchronizationConstants.META_FILE_EXTENSION;
    } else {
        metaDirectoryName = parentDirName + File.separator + SynchronizationConstants.META_DIRECTORY;
        metaFilePath = parentDirName + File.separator + SynchronizationConstants.META_DIRECTORY + File.separator
                + SynchronizationConstants.META_FILE_PREFIX + Utils.encodeResourceName(name)
                + SynchronizationConstants.META_FILE_EXTENSION;
    }

    if (file.exists()) {
        fileAlreadyExist = true;
    }

    if (!isCollection && fileAlreadyExist) {
        if (!Utils.resourceUpdated(metaFilePath, root) || (callback != null && !callback.getConfirmation(
                new Message(MessageCode.FILE_OVERWRITE_CONFIRMATION, new String[] { filePath }),
                SynchronizationConstants.OVERWRITE_CONFIRMATION_CONTEXT))) {
            overwrite = false;
        }
    }
    try {
        // Create file if it does not exist
        if (isCollection) {
            if (!fileAlreadyExist && Utils.resourceUpdated(metaFilePath, root)) {
                boolean ignore = file.mkdir(); // ignores the return value purposely
            } else {
                overwrite = false;
            }
        } else if (overwrite) {
            boolean ignore = file.createNewFile(); // ignores the return value purposely
        }
    } catch (IOException e) {
        throw new SynchronizationException(MessageCode.FILE_CREATION_FAILED, e,
                new String[] { "file: " + filePath });
    }

    // we are extracting the content from the meta element.
    Iterator children = root.getChildren();
    while (children.hasNext()) {
        OMElement child = (OMElement) children.next();
        String localName = child.getLocalName();

        // LastModified
        if (localName.equals(DumpConstants.LAST_MODIFIED)) {
            OMText text = (OMText) child.getFirstOMChild();
            if (text != null) {
                long date = Long.parseLong(text.getText());
                // We are not bothered whether this failed to set the last-modified time. If we
                // cannot modify the file, we would fail when attempting to write to it anyway.
                boolean ignore = file.setLastModified(date);
            }
        }
        // get content
        else if (localName.equals(DumpConstants.CONTENT)) {
            OMText text = (OMText) child.getFirstOMChild();
            // we keep content as base64 encoded
            if (text != null) {
                contentBytes = Base64.decode(text.getText());
            }
            String md5 = Utils.getMD5(contentBytes);
            root.addAttribute("md5", md5, null);
            child.detach();
        }
    }

    if (!isCollection && overwrite) {
        try {
            FileOutputStream fileStream = null;
            try {
                fileStream = new FileOutputStream(file);
                fileStream.write(contentBytes);
                fileStream.flush();
            } finally {
                if (fileStream != null) {
                    fileStream.close();
                }
            }
        } catch (IOException e) {
            throw new SynchronizationException(MessageCode.PROBLEM_IN_CREATING_CONTENT, e,
                    new String[] { "file: " + filePath });
        }
    }

    // creating the meta directory
    File metaDirectory = new File(metaDirectoryName);
    if (!metaDirectory.exists() && !metaDirectory.mkdir()) {
        throw new SynchronizationException(MessageCode.ERROR_CREATING_META_FILE,
                new String[] { "file: " + metaDirectoryName });
    }

    // creating the meta file
    Utils.createMetaFile(metaFilePath, root);

    // printing out the information of the file
    if (!fileAlreadyExist) {
        if (callback != null) {
            callback.displayMessage(new Message(MessageCode.ADDED, new String[] { filePath }));
        }
        addedCount++;
    } else {
        if (overwrite) {
            if (callback != null) {
                callback.displayMessage(new Message(MessageCode.OVERWRITTEN, new String[] { filePath }));
            }
            overwrittenCount++;
        } else {
            if (callback != null) {
                callback.displayMessage(new Message(MessageCode.NON_OVERWRITTEN, new String[] { filePath }));
            }
            nonOverwrittenCount++;
        }
    }

    if (!xmlReader.hasNext()
            || !(xmlReader.isStartElement() && xmlReader.getLocalName().equals(DumpConstants.CHILDREN))) {
        // finished the recursion
        // consuming the stream until the resource end element found
        while (xmlReader.hasNext()
                && !(xmlReader.isEndElement() && xmlReader.getLocalName().equals(DumpConstants.RESOURCE))) {
            xmlReader.next();
        }
        return;
    }

    do {
        xmlReader.next();
        if (xmlReader.isEndElement() && xmlReader.getLocalName().equals(DumpConstants.CHILDREN)) {
            // this means empty children, just quit from here
            // before that we have to set the cursor to the end of the current resource
            if (xmlReader.hasNext()) {
                do {
                    xmlReader.next();
                } while (xmlReader.hasNext() && !(xmlReader.isEndElement()
                        && xmlReader.getLocalName().equals(DumpConstants.RESOURCE)));
            }
            return;
        }
    } while (!xmlReader.isStartElement() && xmlReader.hasNext());

    while (xmlReader.hasNext() && xmlReader.isStartElement()
            && xmlReader.getLocalName().equals(DumpConstants.RESOURCE)) {
        // prepare the children absolute path
        String childName = xmlReader.getAttributeValue(null, DumpConstants.RESOURCE_NAME);
        String fileResourceName = childName;
        String childFilePath = filePath + File.separator + fileResourceName;
        String childPath = (path.equals("/") ? "" : path) + "/" + childName;

        checkOutRecursively(xmlReader, childFilePath, childPath, callback);

        while ((!xmlReader.isStartElement() && xmlReader.hasNext())
                && !(xmlReader.isEndElement() && xmlReader.getLocalName().equals(DumpConstants.CHILDREN))) {
            xmlReader.next();
        }
        if (xmlReader.isEndElement() && xmlReader.getLocalName().equals(DumpConstants.CHILDREN)) {
            // we are in the end of the children tag.
            break;
        }
    }
    // consuming the stream until the resource end element found
    while (xmlReader.hasNext()
            && !(xmlReader.isEndElement() && xmlReader.getLocalName().equals(DumpConstants.RESOURCE))) {
        xmlReader.next();
    }
}

From source file:org.wso2.carbon.registry.synchronization.operation.UpdateCommand.java

private void updateRecursively(XMLStreamReader xmlReader, String filePath, String path,
        UserInputCallback callback) throws SynchronizationException, XMLStreamException {

    // we will first generate the axiom node from the reader,
    OMElement root = Utils.readMetaElement(xmlReader);
    // adding path and the registryUrl
    root.addAttribute("path", path, null);
    if (registryUrl != null) {
        root.addAttribute("registryUrl", registryUrl, null);
    }//from   www .  jav  a 2  s .  c  o  m

    String isCollectionString = root.getAttributeValue(new QName("isCollection"));
    boolean isCollection = isCollectionString.equals("true");
    String name = root.getAttributeValue(new QName("name"));

    byte[] contentBytes = new byte[0];

    File file = new File(filePath);

    boolean isUpdating = false;
    boolean isConflicting = false;
    boolean collectionIsNotUpdated = false; // valid only for the collection.
    String updatingMD5 = null;
    Iterator children = root.getChildren();
    while (children.hasNext()) {
        OMElement child = (OMElement) children.next();
        String localName = child.getLocalName();

        // get content
        if (localName.equals("content")) {
            OMText text = (OMText) child.getFirstOMChild();
            // we keep content as base64 encoded
            if (text != null) {
                contentBytes = Base64.decode(text.getText());
            }
            updatingMD5 = Utils.getMD5(contentBytes);
            root.addAttribute("md5", updatingMD5, null);
            child.detach();
        }
    }

    // access the meta info of the current
    String metaFilePath;

    if (isCollection) {
        metaFilePath = filePath + File.separator + SynchronizationConstants.META_DIRECTORY + File.separator
                + SynchronizationConstants.META_FILE_PREFIX + SynchronizationConstants.META_FILE_EXTENSION;
    } else {
        String parentDirName = file.getAbsoluteFile().getParent();
        metaFilePath = parentDirName + File.separator + SynchronizationConstants.META_DIRECTORY + File.separator
                + SynchronizationConstants.META_FILE_PREFIX + Utils.encodeResourceName(name)
                + SynchronizationConstants.META_FILE_EXTENSION;
    }

    File metaFile = new File(metaFilePath);

    if (file.exists()) {
        isUpdating = true;
        if (isCollection != file.isDirectory()) {
            throw new SynchronizationException(MessageCode.COLLECTION_AND_RESOURCE_SAME_NAME,
                    new String[] { "file name: " + filePath });
        }

        if (metaFile.exists()) {
            // we need to check the last updated times of the current resource
            // and the updating resource

            OMElement updatingVersionElement = root.getFirstChildWithName(new QName("version"));
            if (updatingVersionElement == null) {
                throw new SynchronizationException(MessageCode.CHECKOUT_OLD_VERSION,
                        new String[] { "missing element: version", "path: " + path });
            }
            String updatingVersionStr = updatingVersionElement.getText();

            // get the meta file OMElement
            OMElement metaFileElement = Utils.getOMElementFromMetaFile(metaFilePath);

            OMElement metaFileVersionElement = metaFileElement.getFirstChildWithName(new QName("version"));

            String metaFileVersionStr;
            if (metaFileVersionElement == null) {
                //Version not defined for the newly added files. They are added when updating.
                metaFileVersionStr = updatingVersionStr;
                root.addAttribute("version", metaFileVersionStr, null);
                Utils.createMetaFile(metaFilePath, root);
            } else {
                metaFileVersionStr = metaFileVersionElement.getText();
            }

            if (isCollection) {
                if (metaFileVersionStr.equals(updatingVersionStr)) {
                    // so there is no server updates for the collection
                    Utils.createMetaFile(metaFilePath, root);
                    collectionIsNotUpdated = true;
                }
            } else {
                // here we not just check server side updates, but also check local changes using md5s
                byte[] currentFileContent = Utils.getBytesFromFile(file);

                String metaFileMD5 = metaFileElement.getAttributeValue(new QName("md5"));
                String currentMD5 = Utils.getMD5(currentFileContent);

                if (metaFileMD5 != null && metaFileMD5.equals(currentMD5)) {
                    // there is no modifications happens to the current file locally,
                    if (metaFileVersionStr.equals(updatingVersionStr)) {
                        // the file in the server is not updated, so just keep the current file locally.
                        // so we are only storing the meta information in the meta file.
                        Utils.createMetaFile(metaFilePath, root);
                        return;
                    }
                    // else:
                    // there is a server update to the file, so lets allow it to update the local one
                    // local one is not updated, so it will be overwritten by the server one
                } else if (metaFileVersionStr.equals(updatingVersionStr)) {
                    // there is no server side changes, but there are client side changes,
                    // just don't update the content, but let the meta file get updated.
                    Utils.createMetaFile(metaFilePath, root);
                    return;
                } else {
                    // this is the following scenario
                    // (!metaFileMD5.equals(currentMD5) &&
                    //    !metaFileVersionStr.equals(updatingVersionStr))
                    if (updatingMD5 != null && !updatingMD5.equals(currentMD5)) {
                        isConflicting = true;
                        root.addAttribute("md5", "", null);
                    }
                }
            }
        } else if (!isCollection) {
            // if there is no meta file exists, that mean there is a conflict
            // a new resource is created both locally and in server
            isConflicting = true;
        }

        if (isConflicting && !isSilentUpdate && !ignoreConflicts) {
            // should rename the current file as file.mine
            String mineFileName = filePath + SynchronizationConstants.MINE_FILE_POSTFIX;
            File mineFile = new File(mineFileName);
            Utils.copy(file, mineFile);

            // updating the current file as versionedFileName
            String versionedFileName = filePath + SynchronizationConstants.SERVER_FILE_POSTFIX;
            file = new File(versionedFileName);

            // set the conflicting flag
            root.addAttribute("conflicting", "true", null);
        }
    } else if (isSilentUpdate) {
        // if no files exists locally, the silent update will return
        return;
    } else if (metaFile.exists()) {
        // now the meta file is there but the direct file is deleted, so we will
        // ask whether he want to get the up. Default behaviour is not to take the update from
        // the server. This is because the working copy is up-to-date.
        if (callback == null || callback.getConfirmation(
                new Message(MessageCode.KEEP_DELETED_FILE, new String[] { filePath }),
                SynchronizationConstants.DELETE_CONFIRMATION_CONTEXT)) {
            return;
        }
    }
    if (!isUpdating) {
        try {
            // Create file if it does not exist
            if (isCollection) {
                boolean ignore = file.mkdir(); // ignores the return value purposely
            } else {
                boolean ignore = file.createNewFile(); // ignores the return value purposely
            }
        } catch (IOException e) {
            throw new SynchronizationException(MessageCode.FILE_CREATION_FAILED, e,
                    new String[] { "file name: " + filePath });
        }
    }

    if (!isCollection) {
        FileOutputStream fileOutputStream = null;
        try {
            boolean writeToFile = true;

            if (file.exists()) {
                byte[] currentContentBytes = Utils.getBytesFromFile(file);
                if (currentContentBytes != null && contentBytes != null) {
                    String currentContentMd5 = Utils.getMD5(currentContentBytes);
                    String writingContentMd5 = Utils.getMD5(contentBytes);
                    if (writingContentMd5 != null && writingContentMd5.equals(currentContentMd5)) {
                        writeToFile = false;
                    }
                }
            }
            if (writeToFile) {
                fileOutputStream = new FileOutputStream(file);
                fileOutputStream.write(contentBytes);
                fileOutputStream.flush();
                fileOutputStream.close();
            }

        } catch (IOException e) {
            throw new SynchronizationException(MessageCode.PROBLEM_IN_CREATING_CONTENT, e,
                    new String[] { "file name: " + filePath });
        } finally {
            try {
                if (fileOutputStream != null) {
                    fileOutputStream.close();
                }
            } catch (IOException e) {
                log.error("Failed to close the stream", e);
            }
        }
    } else {
        // creating the meta directory
        String metaDirectoryName = filePath + File.separator + SynchronizationConstants.META_DIRECTORY;
        File metaDirectory = new File(metaDirectoryName);
        if (!metaDirectory.exists() && !metaDirectory.mkdir()) {
            throw new SynchronizationException(MessageCode.ERROR_CREATING_META_FILE,
                    new String[] { "file: " + metaDirectoryName });
        }
    }

    boolean iterateChildren = true;

    if (!xmlReader.hasNext() || !(xmlReader.isStartElement() && xmlReader.getLocalName().equals("children"))) {
        // finished the recursion
        // consuming the stream until the resource end element found
        while (xmlReader.hasNext()
                && !(xmlReader.isEndElement() && xmlReader.getLocalName().equals("resource"))) {
            xmlReader.next();
        }
        iterateChildren = false;
    }
    if (iterateChildren) {
        do {
            xmlReader.next();
            if (xmlReader.isEndElement() && xmlReader.getLocalName().equals("children")) {
                // this means empty children, just quit from here
                // before that we have to set the cursor to the end of the current resource
                if (xmlReader.hasNext()) {
                    do {
                        xmlReader.next();
                    } while (xmlReader.hasNext()
                            && !(xmlReader.isEndElement() && xmlReader.getLocalName().equals("resource")));
                }
                iterateChildren = false;
                break;
            }
        } while (!xmlReader.isStartElement() && xmlReader.hasNext());
    }

    Map<String, Boolean> childNames = new HashMap<String, Boolean>();

    if (iterateChildren) {
        while (xmlReader.hasNext() && xmlReader.isStartElement()
                && xmlReader.getLocalName().equals("resource")) {
            // prepare the children absolute path

            String childName = xmlReader.getAttributeValue(null, "name");
            String fileResourceName = childName;
            String childFilePath = filePath + File.separator + fileResourceName;
            String childPath = (path.equals("/") ? "" : path) + "/" + childName;

            updateRecursively(xmlReader, childFilePath, childPath, callback);
            childNames.put(fileResourceName, true);

            while ((!xmlReader.isStartElement() && xmlReader.hasNext())
                    && !(xmlReader.isEndElement() && xmlReader.getLocalName().equals("children"))) {
                xmlReader.next();
            }
            if (xmlReader.isEndElement() && xmlReader.getLocalName().equals("children")) {
                // we are in the end of the children tag.
                break;
            }
        }
        // consuming the stream until the resource end element found
        while (xmlReader.hasNext()
                && !(xmlReader.isEndElement() && xmlReader.getLocalName().equals("resource"))) {
            xmlReader.next();
        }

        // now we are checking which files have been deleted at the server end.
        String[] childFileNames = file.list();
        if (childFileNames != null) {
            for (String childFileName : childFileNames) {
                if (childFileName.equals(SynchronizationConstants.META_DIRECTORY)) {
                    continue;
                }
                if (childNames.get(childFileName) != null && childNames.get(childFileName)) {
                    // this files stays on the server as well, so nothing to worry
                    continue;
                }
                // hm, we have a situation that stuff exist local, but not at the server
                // first need to check whether they are newly added.
                // we can do that by checking the existence of meta directory
                String childFilePath = file + File.separator + childFileName;
                File childFile = new File(file, childFileName);
                boolean shouldDelete = false;
                File childMetaFile;
                if (childFile.isDirectory()) {
                    // the meta directory should exist in .meta
                    String metaDirName = filePath + File.separator + childFileName + File.separator
                            + SynchronizationConstants.META_DIRECTORY + File.separator + File.separator
                            + SynchronizationConstants.META_FILE_PREFIX
                            + SynchronizationConstants.META_FILE_EXTENSION;
                    childMetaFile = new File(metaDirName);

                    if (childMetaFile.exists()) {
                        // looks like it's bean earlier checkout from registry, mean it is now deleted
                        shouldDelete = true;
                    }
                } else {
                    String metaFileName = filePath + File.separator + SynchronizationConstants.META_DIRECTORY
                            + File.separator + SynchronizationConstants.META_FILE_PREFIX
                            + Utils.encodeResourceName(childFileName)
                            + SynchronizationConstants.META_FILE_EXTENSION;
                    childMetaFile = new File(metaFileName);
                    if (childMetaFile.exists()) {
                        // looks like it's bean earlier checkout from registry, mean it is now deleted
                        shouldDelete = true;
                    }
                }
                if (shouldDelete && !isSilentUpdate) {
                    deleteFile(callback, childFilePath, childFile, childMetaFile);
                }
            }
        }
    } else {
        //            Seems like the user has deleted all the resources under a particular collection

        String[] allFilesNames = file.list();
        if (allFilesNames != null) {
            for (String filesName : allFilesNames) {
                String childFilePath;
                File childFile;
                File childMetaFile;

                childFilePath = filePath + File.separator + filesName;
                childFile = new File(childFilePath);
                if (childFile.isDirectory()) {
                    //                    Here we are deleting all the collections that were deleted from the server
                    String childMetaCollectionPath = childFilePath + File.separator
                            + SynchronizationConstants.META_DIRECTORY;
                    childMetaFile = new File(childMetaCollectionPath);
                    if (childMetaFile.exists() && !isSilentUpdate) {
                        deleteFile(callback, childFilePath, childFile, childMetaFile);
                    }
                } else {
                    //                    Here we remove all the resource that have been deleted from the server
                    String metaFileFullName = filePath + File.separator
                            + SynchronizationConstants.META_DIRECTORY + File.separator
                            + SynchronizationConstants.META_FILE_PREFIX + Utils.encodeResourceName(filesName)
                            + SynchronizationConstants.META_FILE_EXTENSION;

                    childMetaFile = new File(metaFileFullName);
                    if (childMetaFile.exists() && !isSilentUpdate) {
                        deleteFile(callback, childFilePath, childFile, childMetaFile);
                    }
                }
            }
        }
    }

    if (file.isDirectory() && collectionIsNotUpdated) {
        return;
    }

    // creating the meta file
    String metaFileName;
    if (isCollection) {
        metaFileName = filePath + File.separator + SynchronizationConstants.META_DIRECTORY + File.separator
                + SynchronizationConstants.META_FILE_PREFIX + SynchronizationConstants.META_FILE_EXTENSION;
    } else {
        String parentDirName = file.getAbsoluteFile().getParent();
        metaFileName = parentDirName + File.separator + SynchronizationConstants.META_DIRECTORY + File.separator
                + SynchronizationConstants.META_FILE_PREFIX + Utils.encodeResourceName(name)
                + SynchronizationConstants.META_FILE_EXTENSION;
    }
    Utils.createMetaFile(metaFileName, root);

    // printing out the information of the file
    if (isConflicting) {
        if (callback != null && !isSilentUpdate) {
            callback.displayMessage(
                    new Message(MessageCode.CONFLICTED, new String[] { refinedPathToPrint(filePath) }));
        }
        conflictedCount++;
    } else if (isUpdating) {
        if (callback != null && !isSilentUpdate) {
            callback.displayMessage(
                    new Message(MessageCode.UPDATED, new String[] { refinedPathToPrint(filePath) }));
        }
        updatedCount++;
        updated = true;
    } else {
        if (callback != null && !isSilentUpdate) {
            callback.displayMessage(
                    new Message(MessageCode.ADDED, new String[] { refinedPathToPrint(filePath) }));
        }
        addedCount++;
        updated = true;
    }
}

From source file:org.wso2.carbon.registry.synchronization.Utils.java

/**
 * This method reads the xml stream up to the children and return the meta element.
 *
 * @param xmlReader the xml reader./*from  ww w. j  av a 2 s  . c  o m*/
 *
 * @return the meta element.
 * @throws SynchronizationException if the provided XML is invalid.
 * @throws XMLStreamException       if XML parsing failed.
 */
public static OMElement readMetaElement(XMLStreamReader xmlReader)
        throws SynchronizationException, XMLStreamException {
    try {
        while (!xmlReader.isStartElement() && xmlReader.hasNext()) {
            xmlReader.next();
        }

        if (!xmlReader.hasNext()) {
            // nothing to parse
            return null;
        }

        if (!xmlReader.getLocalName().equals(Utils.ELEM_RESOURCE)) {
            throw new SynchronizationException(MessageCode.INVALID_DUMP_CREATE_META_FILE);

        }

        // alerting non-backward compatibility...
        //            String pathAttribute = xmlReader.getAttributeValue(null, ATTR_PATH);
        //            if (pathAttribute != null) {
        //                throw new SynchronizationException(MessageCode.CHECKOUT_OLD_VERSION);
        //            }

        OMFactory factory = OMAbstractFactory.getOMFactory();
        OMElement root = factory.createOMElement(new QName(Utils.ELEM_RESOURCE));

        String resourceName = xmlReader.getAttributeValue(null, ATTR_NAME);
        String isCollectionString = xmlReader.getAttributeValue(null, ATTR_IS_COLLECTION);

        root.addAttribute(ATTR_NAME, resourceName, null);
        root.addAttribute(ATTR_IS_COLLECTION, isCollectionString, null);

        // traversing to the next element
        do {
            xmlReader.next();
        } while (!xmlReader.isStartElement() && xmlReader.hasNext());

        while (xmlReader.hasNext()) {
            String localName = xmlReader.getLocalName();

            // version
            if (localName.equals(ELEM_VERSION)) {
                String text = xmlReader.getElementText();
                OMElement versionElement = factory.createOMElement(new QName(ELEM_VERSION));
                if (text != null) {
                    versionElement.setText(text);
                }
                root.addChild(versionElement);
                // now go to the next element
                do {
                    xmlReader.next();
                } while (!xmlReader.isStartElement() && xmlReader.hasNext()
                        && !(xmlReader.isEndElement() && xmlReader.getLocalName().equals(Utils.ELEM_RESOURCE)));
            }
            // setMediaType
            else if (localName.equals(ELEM_MEDIA_TYPE)) {
                String text = xmlReader.getElementText();
                OMElement mediaTypeElement = factory.createOMElement(new QName(ELEM_MEDIA_TYPE));
                if (text != null) {
                    mediaTypeElement.setText(text);
                }
                root.addChild(mediaTypeElement);
                // now go to the next element
                do {
                    xmlReader.next();
                } while (!xmlReader.isStartElement() && xmlReader.hasNext()
                        && !(xmlReader.isEndElement() && xmlReader.getLocalName().equals(Utils.ELEM_RESOURCE)));
            }
            // creator
            else if (localName.equals(ELEM_CREATOR)) {
                String text = xmlReader.getElementText();
                OMElement creatorElement = factory.createOMElement(new QName(ELEM_CREATOR));
                if (text != null) {
                    creatorElement.setText(text);
                }
                root.addChild(creatorElement);
                // now go to the next element
                do {
                    xmlReader.next();
                } while (!xmlReader.isStartElement() && xmlReader.hasNext()
                        && !(xmlReader.isEndElement() && xmlReader.getLocalName().equals(Utils.ELEM_RESOURCE)));
            }
            // createdTime
            else if (localName.equals(ELEM_CREATED_TIME)) {
                String text = xmlReader.getElementText();
                OMElement createdTimeElement = factory.createOMElement(new QName(ELEM_CREATED_TIME));
                if (text != null) {
                    createdTimeElement.setText(text);
                }
                root.addChild(createdTimeElement);
                // now go to the next element
                do {
                    xmlReader.next();
                } while (!xmlReader.isStartElement() && xmlReader.hasNext()
                        && !(xmlReader.isEndElement() && xmlReader.getLocalName().equals(Utils.ELEM_RESOURCE)));
            }
            // createdTime
            else if (localName.equals(ELEM_CONTENT)) {
                // currently we are keeping the content within the root element, and remove it
                // later. Before Carbon 3.0.0 the content was in the middle of the other
                // resource attributes
                String text = xmlReader.getElementText();
                OMElement contentElement = factory.createOMElement(new QName(ELEM_CONTENT));
                if (text != null) {
                    contentElement.setText(text);
                }
                root.addChild(contentElement);
                // now go to the next element
                do {
                    xmlReader.next();
                } while (!xmlReader.isStartElement() && xmlReader.hasNext()
                        && !(xmlReader.isEndElement() && xmlReader.getLocalName().equals(Utils.ELEM_RESOURCE)));
            }
            // setLastUpdater
            else if (localName.equals(ELEM_LAST_UPDATER)) {
                String text = xmlReader.getElementText();
                OMElement lastUpdaterElement = factory.createOMElement(new QName(ELEM_LAST_UPDATER));
                if (text != null) {
                    lastUpdaterElement.setText(text);
                }
                root.addChild(lastUpdaterElement);
                // now go to the next element
                do {
                    xmlReader.next();
                } while (!xmlReader.isStartElement() && xmlReader.hasNext()
                        && !(xmlReader.isEndElement() && xmlReader.getLocalName().equals(Utils.ELEM_RESOURCE)));
            }
            // LastModified
            else if (localName.equals(ELEM_LAST_MODIFIED)) {
                String text = xmlReader.getElementText();
                OMElement lastModifiedElement = factory.createOMElement(new QName(ELEM_LAST_MODIFIED));
                if (text != null) {
                    lastModifiedElement.setText(text);
                }
                root.addChild(lastModifiedElement);
                // now go to the next element
                do {
                    xmlReader.next();
                } while (!xmlReader.isStartElement() && xmlReader.hasNext()
                        && !(xmlReader.isEndElement() && xmlReader.getLocalName().equals(Utils.ELEM_RESOURCE)));
            }
            // get description
            else if (localName.equals(ELEM_DESCRIPTION)) {
                String text = xmlReader.getElementText();
                OMElement description = factory.createOMElement(new QName(ELEM_DESCRIPTION));
                if (text != null) {
                    description.setText(text);
                }
                root.addChild(description);
                // now go to the next element
                do {
                    xmlReader.next();
                } while (!xmlReader.isStartElement() && xmlReader.hasNext()
                        && !(xmlReader.isEndElement() && xmlReader.getLocalName().equals(Utils.ELEM_RESOURCE)));
                // now go to the next element while
                // (!xmlReader.isStartElement() && xmlReader.hasNext());
            }
            // get uuid
            else if (localName.equals(ELEM_UUID)) {
                String text = xmlReader.getElementText();
                OMElement description = factory.createOMElement(new QName(ELEM_UUID));
                if (text != null) {
                    description.setText(text);
                }
                root.addChild(description);
                // now go to the next element
                do {
                    xmlReader.next();
                } while (!xmlReader.isStartElement() && xmlReader.hasNext()
                        && !(xmlReader.isEndElement() && xmlReader.getLocalName().equals(Utils.ELEM_RESOURCE)));
                // now go to the next element while
                // (!xmlReader.isStartElement() && xmlReader.hasNext());
            }
            // get properties
            else if (localName.equals(ELEM_PROPERTIES)) {
                // iterating trying to find the children..
                OMElement properties = factory.createOMElement(new QName(ELEM_PROPERTIES));
                root.addChild(properties);
                do {
                    xmlReader.next();
                } while (!xmlReader.isStartElement() && xmlReader.hasNext()
                        && !(xmlReader.isEndElement() && xmlReader.getLocalName().equals(Utils.ELEM_RESOURCE)));
                while (xmlReader.hasNext() && xmlReader.getLocalName().equals(ELEM_PROPERTY)) {
                    String key = xmlReader.getAttributeValue(null, ATTR_KEY);
                    String text = xmlReader.getElementText();
                    OMElement property = factory.createOMElement(new QName(ELEM_PROPERTY));
                    property.addAttribute(ATTR_KEY, key, null);
                    properties.addChild(property);

                    if (text.equals("")) {
                        text = null;
                    }
                    if (text != null) {
                        property.setText(text);
                    }
                    do {
                        xmlReader.next();
                    } while (!xmlReader.isStartElement() && xmlReader.hasNext() && !(xmlReader.isEndElement()
                            && xmlReader.getLocalName().equals(Utils.ELEM_RESOURCE)));
                }
                // getting comment information
            } else if (localName.equals(ELEM_COMMENTS)) {
                // iterating trying to find the children..
                OMElement commentsElement = factory.createOMElement(new QName(ELEM_COMMENTS));
                root.addChild(commentsElement);
                do {
                    xmlReader.next();
                } while (!xmlReader.isStartElement() && xmlReader.hasNext());
                while (xmlReader.hasNext() && xmlReader.getLocalName().equals(ELEM_COMMENT)) {
                    do {
                        xmlReader.next();
                    } while (!xmlReader.isStartElement() && xmlReader.hasNext() && !(xmlReader.isEndElement()
                            && xmlReader.getLocalName().equals(Utils.ELEM_RESOURCE)));

                    localName = xmlReader.getLocalName();
                    OMElement commentElement = factory.createOMElement(new QName(ELEM_COMMENT));
                    commentsElement.addChild(commentElement);
                    while (xmlReader.hasNext()
                            && (localName.equals(ELEM_USER) || localName.equals(ELEM_TEXT))) {
                        if (localName.equals(ELEM_USER)) {
                            String text = xmlReader.getElementText();
                            if (text != null) {
                                OMElement userElement = factory.createOMElement(new QName(ELEM_USER));
                                userElement.setText(text);
                                commentElement.addChild(userElement);
                            }
                        } else if (localName.equals(ELEM_TEXT)) {
                            String text = xmlReader.getElementText();
                            if (text != null) {
                                OMElement textElement = factory.createOMElement(new QName(ELEM_TEXT));
                                textElement.setText(text);
                                commentElement.addChild(textElement);
                            }
                        }

                        do {
                            xmlReader.next();
                        } while (!xmlReader.isStartElement() && xmlReader.hasNext()
                                && !(xmlReader.isEndElement()
                                        && xmlReader.getLocalName().equals(Utils.ELEM_RESOURCE)));
                        if (xmlReader.hasNext()) {
                            localName = xmlReader.getLocalName();
                        }
                    }
                }
            }
            // getting tagging information
            else if (localName.equals(ELEM_TAGGINGS)) {
                // iterating trying to find the children..
                OMElement taggingsElement = factory.createOMElement(new QName(ELEM_TAGGINGS));
                root.addChild(taggingsElement);
                do {
                    xmlReader.next();
                } while (!xmlReader.isStartElement() && xmlReader.hasNext()
                        && !(xmlReader.isEndElement() && xmlReader.getLocalName().equals(Utils.ELEM_RESOURCE)));
                while (xmlReader.hasNext() && xmlReader.getLocalName().equals(ELEM_TAGGING)) {
                    do {
                        xmlReader.next();
                    } while (!xmlReader.isStartElement() && xmlReader.hasNext() && !(xmlReader.isEndElement()
                            && xmlReader.getLocalName().equals(Utils.ELEM_RESOURCE)));

                    localName = xmlReader.getLocalName();

                    OMElement taggingElement = factory.createOMElement(new QName(ELEM_TAGGING));
                    taggingsElement.addChild(taggingElement);

                    while (xmlReader.hasNext() && (localName.equals(ELEM_USER) || localName.equals(ELEM_DATE)
                            || localName.equals(ELEM_TAG_NAME))) {
                        if (localName.equals(ELEM_USER)) {
                            String text = xmlReader.getElementText();
                            if (text != null) {
                                OMElement userElement = factory.createOMElement(new QName(ELEM_USER));
                                userElement.setText(text);
                                taggingElement.addChild(userElement);
                            }
                        } else if (localName.equals(ELEM_DATE)) {
                            String text = xmlReader.getElementText();
                            if (text != null) {
                                OMElement dateElement = factory.createOMElement(new QName(ELEM_DATE));
                                dateElement.setText(text);
                                taggingElement.addChild(dateElement);
                            }
                        } else if (localName.equals(ELEM_TAG_NAME)) {
                            String text = xmlReader.getElementText();
                            if (text != null) {
                                OMElement tagNameElement = factory.createOMElement(new QName(ELEM_TAG_NAME));
                                tagNameElement.setText(text);
                                taggingElement.addChild(tagNameElement);
                            }
                        }
                        do {
                            xmlReader.next();
                        } while (!xmlReader.isStartElement() && xmlReader.hasNext()
                                && !(xmlReader.isEndElement()
                                        && xmlReader.getLocalName().equals(Utils.ELEM_RESOURCE)));
                        if (xmlReader.hasNext()) {
                            localName = xmlReader.getLocalName();
                        }
                    }
                }
            }
            // getting rating information
            else if (localName.equals(ELEM_RATINGS)) {
                // iterating trying to find the children..
                OMElement ratingsElement = factory.createOMElement(new QName(ELEM_RATINGS));
                root.addChild(ratingsElement);
                do {
                    xmlReader.next();
                } while (!xmlReader.isStartElement() && xmlReader.hasNext()
                        && !(xmlReader.isEndElement() && xmlReader.getLocalName().equals(Utils.ELEM_RESOURCE)));
                while (xmlReader.hasNext() && xmlReader.getLocalName().equals(ELEM_RATING)) {
                    do {
                        xmlReader.next();
                    } while (!xmlReader.isStartElement() && xmlReader.hasNext());

                    localName = xmlReader.getLocalName();

                    OMElement ratingElement = factory.createOMElement(new QName(ELEM_RATING));
                    ratingsElement.addChild(ratingElement);

                    while (xmlReader.hasNext() && (localName.equals(ELEM_USER) || localName.equals(ELEM_DATE)
                            || localName.equals(ELEM_RATE))) {
                        if (localName.equals(ELEM_USER)) {
                            String text = xmlReader.getElementText();
                            if (text != null) {
                                OMElement userElement = factory.createOMElement(new QName(ELEM_USER));
                                userElement.setText(text);
                                ratingElement.addChild(userElement);
                            }
                        } else if (localName.equals(ELEM_DATE)) {
                            String text = xmlReader.getElementText();
                            if (text != null) {
                                OMElement dateElement = factory.createOMElement(new QName(ELEM_DATE));
                                dateElement.setText(text);
                                ratingElement.addChild(dateElement);
                            }
                        } else if (localName.equals(ELEM_RATE)) {
                            String text = xmlReader.getElementText();
                            if (text != null) {
                                OMElement rateElement = factory.createOMElement(new QName(ELEM_RATE));
                                rateElement.setText(text);
                                ratingElement.addChild(rateElement);
                            }
                        }
                        do {
                            xmlReader.next();
                        } while (!xmlReader.isStartElement() && xmlReader.hasNext()
                                && !(xmlReader.isEndElement()
                                        && xmlReader.getLocalName().equals(Utils.ELEM_RESOURCE)));
                        if (xmlReader.hasNext()) {
                            localName = xmlReader.getLocalName();
                        }
                    }
                }
            }
            // getting rating information
            else if (localName.equals(ELEM_ASSOCIATIONS)) {
                // iterating trying to find the children..
                OMElement associationsElement = factory.createOMElement(new QName(ELEM_ASSOCIATIONS));
                root.addChild(associationsElement);
                do {
                    xmlReader.next();
                } while (!xmlReader.isStartElement() && xmlReader.hasNext()
                        && !(xmlReader.isEndElement() && xmlReader.getLocalName().equals(Utils.ELEM_RESOURCE)));
                while (xmlReader.hasNext() && xmlReader.getLocalName().equals(ELEM_ASSOCIATION)) {

                    do {
                        xmlReader.next();
                    } while (!xmlReader.isStartElement() && xmlReader.hasNext() && !(xmlReader.isEndElement()
                            && xmlReader.getLocalName().equals(Utils.ELEM_RESOURCE)));

                    localName = xmlReader.getLocalName();

                    OMElement associationElement = factory.createOMElement(new QName(ELEM_ASSOCIATION));
                    associationsElement.addChild(associationElement);

                    while (xmlReader.hasNext() && (localName.equals(ELEM_SOURCE)
                            || localName.equals(ELEM_DESTINATION) || localName.equals(ELEM_TYPE))) {
                        if (localName.equals(ELEM_SOURCE)) {
                            String text = xmlReader.getElementText();
                            if (text != null) {
                                OMElement sourceElement = factory.createOMElement(new QName(ELEM_SOURCE));
                                sourceElement.setText(text);
                                associationElement.addChild(sourceElement);
                            }
                        } else if (localName.equals(ELEM_DESTINATION)) {
                            String text = xmlReader.getElementText();
                            if (text != null) {
                                OMElement destinationElement = factory
                                        .createOMElement(new QName(ELEM_DESTINATION));
                                destinationElement.setText(text);
                                associationElement.addChild(destinationElement);
                            }
                        } else if (localName.equals(ELEM_TYPE)) {
                            String text = xmlReader.getElementText();
                            if (text != null) {
                                OMElement typeElement = factory.createOMElement(new QName(ELEM_TYPE));
                                typeElement.setText(text);
                                associationElement.addChild(typeElement);
                            }
                        }
                        do {
                            xmlReader.next();
                        } while (!xmlReader.isStartElement() && xmlReader.hasNext()
                                && !(xmlReader.isEndElement()
                                        && xmlReader.getLocalName().equals(Utils.ELEM_RESOURCE)));
                        if (xmlReader.hasNext()) {
                            localName = xmlReader.getLocalName();
                        }
                    }
                }
            } else if (localName.equals(ELEM_CHILDREN) || localName.equals(Utils.ELEM_RESOURCE)) {
                // checking the children or content element to terminate the check.
                break;
            } else {
                // we do mind having unwanted elements, now go to the next element
                break;
            }

            if ((xmlReader.isEndElement() && xmlReader.getLocalName().equals(Utils.ELEM_RESOURCE))) {
                // here we come the end of the resource tag
                break;
            }
        }
        return root;
    } catch (XMLStreamException e) {
        throw new SynchronizationException(MessageCode.ERROR_IN_READING_STREAM_TO_CREATE_META_FILE, e);
    }
}