Example usage for org.dom4j DocumentHelper parseText

List of usage examples for org.dom4j DocumentHelper parseText

Introduction

In this page you can find the example usage for org.dom4j DocumentHelper parseText.

Prototype

public static Document parseText(String text) throws DocumentException 

Source Link

Document

parseText parses the given text as an XML document and returns the newly created Document.

Usage

From source file:com.buddycloud.channeldirectory.crawler.node.CrawlerHelper.java

License:Apache License

@SuppressWarnings("unchecked")
public static Element getAtomEntry(Item item) throws DocumentException {
    PayloadItem<PacketExtension> payloadItem = (PayloadItem<PacketExtension>) item;
    PacketExtension payload = payloadItem.getPayload();

    Element atomEntry = DocumentHelper.parseText(payload.toXML().toString()).getRootElement();
    return atomEntry;
}

From source file:com.buddycloud.channeldirectory.crawler.node.PostCrawler.java

License:Apache License

@SuppressWarnings("unchecked")
private void processPost(String nodeFullJid, String nodeId, Item item) throws Exception {

    PayloadItem<PacketExtension> payloadItem = (PayloadItem<PacketExtension>) item;
    PacketExtension payload = payloadItem.getPayload();

    Element atomEntry = DocumentHelper.parseText(payload.toXML()).getRootElement();

    PostData postData = new PostData();

    postData.setParentFullId(nodeFullJid);
    postData.setParentSimpleId(nodeId);//from   www .  j ava2 s  .  c  o m

    Element authorElement = atomEntry.element("author");
    String authorName = authorElement.elementText("name");
    String authorUri = authorElement.elementText("uri");

    postData.setAuthor(authorName);
    postData.setAuthorURI(authorUri);

    String content = atomEntry.elementText("content");
    String updated = atomEntry.elementText("updated");
    String published = atomEntry.elementText("published");
    String id = atomEntry.elementText("id");

    postData.setContent(content);
    postData.setUpdated(DATE_FORMAT.parse(updated));
    postData.setPublished(DATE_FORMAT.parse(published));
    postData.setId(id);

    Element geolocElement = atomEntry.element("geoloc");

    if (geolocElement != null) {
        Geolocation geolocation = new Geolocation();

        String text = geolocElement.elementText("text");
        geolocation.setText(text);

        String lat = geolocElement.elementText("lat");
        String lon = geolocElement.elementText("lon");

        if (lat != null && lon != null) {
            geolocation.setLat(Double.valueOf(lat));
            geolocation.setLng(Double.valueOf(lon));
        }

        postData.setGeolocation(geolocation);
    }

    Element inReplyToElement = atomEntry.element("in-reply-to");
    if (inReplyToElement != null) {
        String replyRef = inReplyToElement.attributeValue("ref");
        postData.setInReplyTo(replyRef);
    }

    insert(postData);
    ActivityHelper.updateActivity(postData, dataSource, configuration);
}

From source file:com.chinarewards.license.util.XmlUtil_dom4j.java

public static Element getElementAsBytes(byte[] bytes) {
    Element element = null;/*from   w w  w .  j a v a  2 s .  com*/
    try {
        element = DocumentHelper.parseText(new String(bytes)).getRootElement();
    } catch (DocumentException e) {
        e.printStackTrace();
    }
    return element;
}

From source file:com.church.gateway.Global.java

/**
 * Parses the theme xml.//w  w  w. j  a  v  a 2s  . c  om
 * 
 * @param xml
 *            the xml
 */
private static void parseThemeXML(String xml) {
    try {
        Document doc = DocumentHelper.parseText(xml);
        Element elmt = doc.getRootElement();
        List l = elmt.selectNodes("/themes/theme");
        Element e = null;
        theme_class = new String[l.size()];
        for (int i = 0; i < l.size(); i++) {
            e = (Element) l.get(i);
            theme_class[i] = e.attribute("class").getValue();
        }
    } catch (DocumentException e) {
        System.out.println(e);
    }
}

From source file:com.church.gateway.Global.java

/**
 * Gets the modified menu xml./*from   ww  w  . j a  va2s  .  co  m*/
 * 
 * @param disallowed_modules
 *            the disallowed_modules
 * 
 * @return the modified menu xml
 * 
 * @throws Exception
 *             the exception
 */
public static String getModifiedMenuXml(String[] disallowed_modules) throws Exception {
    Document doc = DocumentHelper.parseText(Global.MENUS);
    Element root = doc.getRootElement();
    List<Node> list = root.selectNodes("//menu/menu");
    for (Node node : list) {
        Element elmt = (Element) node;
        if (elmt.attribute("class") != null) {
            for (String module : disallowed_modules)
                if (elmt.attribute("class").getValue().trim().equals(module))
                    elmt.addAttribute("visible", "false");
        }
    }
    return doc.asXML();
}

From source file:com.church.gateway.Global.java

/**
 * Load transition effects.//from   ww  w.  j a  v a2 s  .  c  om
 */
private static void loadTransitionEffects() {
    ArrayList<String> display = new ArrayList<String>();
    ArrayList<String> classname = new ArrayList<String>();

    try {
        byte[] xmlbytes = Network.getLocalFile("transitions.xml");
        Document doc = DocumentHelper.parseText(new String(xmlbytes));
        Element root = doc.getRootElement();
        List<Node> nodes = root.selectNodes("transition");
        transitionParameters = new HashMap<String, Object[]>();
        for (Node n : nodes) {
            Element elmt = (Element) n;
            display.add(elmt.selectSingleNode("display").getText());
            classname.add(elmt.selectSingleNode("class").getText());
            List<Node> ps = elmt.selectNodes("parameter");
            if (ps != null) {
                Object[] arr = new Object[ps.size()];
                for (int i = 0; i < ps.size(); i++) {
                    Element ep = (Element) ps.get(i);
                    arr[i] = ep.getTextTrim();
                }
                transitionParameters.put(elmt.selectSingleNode("display").getText(), arr);
            } else
                transitionParameters.put(elmt.selectSingleNode("display").getText(), new Object[] {});
        }
    } catch (DocumentException e) {
        Logger.getLogger(Global.class).error(e, e);
    }
    supportedTransitionClasses = new String[classname.size()];
    supportedTransitions = new String[display.size()];
    for (int i = 0; i < classname.size(); i++) {
        supportedTransitionClasses[i] = classname.get(i) + ":" + display.get(i);
        supportedTransitions[i] = display.get(i);
    }
}

From source file:com.cloopen.rest.sdk.CCPRestSDK.java

License:Open Source License

/**
 * @description xml??map/*from   w w w .j  a va  2s.co  m*/
 * @param xml
 * @return Map
 */
private HashMap<String, Object> xmlToMap(String xml) {
    HashMap<String, Object> map = new HashMap<String, Object>();
    Document doc = null;
    try {
        doc = DocumentHelper.parseText(xml); // XML
        Element rootElt = doc.getRootElement(); // ?
        HashMap<String, Object> hashMap2 = new HashMap<String, Object>();
        ArrayList<HashMap<String, Object>> arrayList = new ArrayList<HashMap<String, Object>>();
        for (Iterator i = rootElt.elementIterator(); i.hasNext();) {
            Element e = (Element) i.next();
            if ("statusCode".equals(e.getName()) || "statusMsg".equals(e.getName()))
                map.put(e.getName(), e.getText());
            else {
                if ("SubAccount".equals(e.getName()) || "TemplateSMS".equals(e.getName())
                        || "totalCount".equals(e.getName()) || "token".equals(e.getName())
                        || "callSid".equals(e.getName()) || "state".equals(e.getName())
                        || "downUrl".equals(e.getName())) {
                    if (!"SubAccount".equals(e.getName()) && !"TemplateSMS".equals(e.getName())) {
                        hashMap2.put(e.getName(), e.getText());
                    } else if ("SubAccount".equals(e.getName())) {

                        HashMap<String, Object> hashMap3 = new HashMap<String, Object>();
                        for (Iterator i2 = e.elementIterator(); i2.hasNext();) {
                            Element e2 = (Element) i2.next();
                            hashMap3.put(e2.getName(), e2.getText());
                        }
                        arrayList.add(hashMap3);
                        hashMap2.put("SubAccount", arrayList);
                    } else if ("TemplateSMS".equals(e.getName())) {

                        HashMap<String, Object> hashMap3 = new HashMap<String, Object>();
                        for (Iterator i2 = e.elementIterator(); i2.hasNext();) {
                            Element e2 = (Element) i2.next();
                            hashMap3.put(e2.getName(), e2.getText());
                        }
                        arrayList.add(hashMap3);
                        hashMap2.put("TemplateSMS", arrayList);
                    }
                    map.put("data", hashMap2);
                } else {

                    HashMap<String, Object> hashMap3 = new HashMap<String, Object>();
                    for (Iterator i2 = e.elementIterator(); i2.hasNext();) {
                        Element e2 = (Element) i2.next();
                        // hashMap2.put(e2.getName(),e2.getText());
                        hashMap3.put(e2.getName(), e2.getText());
                    }
                    if (hashMap3.size() != 0) {
                        hashMap2.put(e.getName(), hashMap3);
                    } else {
                        hashMap2.put(e.getName(), e.getText());
                    }
                    map.put("data", hashMap2);
                }
            }
        }
    } catch (DocumentException e) {
        e.printStackTrace();
        LoggerUtil.error(e.getMessage());
    } catch (Exception e) {
        LoggerUtil.error(e.getMessage());
        e.printStackTrace();
    }
    return map;
}

From source file:com.collabnet.ccf.core.AbstractReader.java

License:Open Source License

/**
 * The process method queues the sync info documents from the sync info
 * readers. It then takes each repository one by one and asks the repository
 * reader (which is a sub class to this AbstractReader) if there are any
 * changed artifacts. If the reader gives a list of artifacts that are
 * changed then the AbstractReader requests the repository reader to get the
 * data of the changed artifacts one by one along with the dependent
 * artifact data such as attachments and dependent artifacts in the Generic
 * Artifact xml format. On getting these data the abstract reader emits the
 * artifacts one by one to the next component in the pipeline. It does this
 * for each repository alternatively so that all the repositories get equal
 * chance to ship their artifacts. If there are no artifacts to be shipped
 * for all of the repositories configured then the AbstractReader pauses the
 * processing for sleepInterval milliseconds.
 *//*  ww  w .ja v a2 s . c  o  m*/
public Object[] process(Object data) {
    Document syncInfoIn = null;
    if (data instanceof Document) {
        syncInfoIn = (Document) data;
    } else {
        return null;
    }

    if (getAutoRestartPeriod() > 0) {
        if (new Date().getTime() - startedDate.getTime() > getAutoRestartPeriod()) {
            log.debug("Preparing to restart CCF, flushing buffers ...");
            setRestartConnector(true);
        }
    }

    String sourceRepositoryId = this.getSourceRepositoryId(syncInfoIn);
    String sourceSystemId = this.getSourceSystemId(syncInfoIn);
    String targetSystemId = this.getTargetSystemId(syncInfoIn);
    String targetRepositoryId = this.getTargetRepositoryId(syncInfoIn);
    String repositoryMappingDirectionID = this.getRepositoryMappingDirectionId(syncInfoIn);
    String repositoryKey = sourceSystemId + ":" + sourceRepositoryId + ":" + targetSystemId + ":"
            + targetRepositoryId;
    log.debug("Received the SyncInfo for repository with source system id" + sourceSystemId
            + ", source repository id " + sourceRepositoryId + ", target systemId " + targetSystemId
            + " and target repository id " + targetRepositoryId);
    RepositoryRecord record = repositoryRecordHashMap.get(repositoryKey);
    if (record == null) {
        log.debug("No RepositoryRecord available for source system id" + sourceSystemId
                + ", source repository id " + sourceRepositoryId + ", target systemId " + targetSystemId
                + " and target repository id " + targetRepositoryId + "... Creating one and registering");
        record = new RepositoryRecord(repositoryKey, syncInfoIn);
        repositoryRecordHashMap.put(repositoryKey, record);
    } else {
        connectorHasReadAllInitialSynchronizationStatusRecords = true;
        record.setNewSyncInfo(syncInfoIn);
    }
    if (!repositoryRecordsInRepositorySynchronizationWaitingList.contains(repositoryKey)) {
        log.debug(repositoryKey + " is not on the waiting list. Adding....");
        repositorySynchronizationWaitingList.add(0, record);
        repositoryRecordsInRepositorySynchronizationWaitingList.add(repositoryKey);
    }
    RepositoryRecord currentRecord = null;
    while (!repositorySynchronizationWaitingList.isEmpty()) {
        currentRecord = repositorySynchronizationWaitingList.get(0);
        log.debug("Processing the current repository " + currentRecord.getRepositoryId() + " record");
        // immediately move record to tail so that exceptions do not prevent
        // other repositories
        // from being synched
        moveToTail(currentRecord);
        Document syncInfo = currentRecord.getSyncInfo();
        loadRMDConfigExtractorToRMDHandlers(repositoryMappingDirectionID);
        // RepositoryRecord movedRecord =
        // repositorySynchronizationWaitingList.remove(0);
        // repositorySynchronizationWaitingList.add(movedRecord);
        List<GenericArtifact> artifactsToBeShippedList = currentRecord.getArtifactsToBeShippedList();
        List<ArtifactState> artifactsToBeReadList = currentRecord.getArtifactsToBeReadList();

        // If dryrun mode is set to stop,clear all already fetched artifacts for the RMD 
        // and set dry-mode to off
        if (rmdDryModeHandler.isDryRunEqualsStop(repositoryMappingDirectionID)) {
            artifactsToBeReadList.clear();
            rmdDryModeHandler.updateRMDConfigToOff(repositoryMappingDirectionID);
        }

        if (!artifactsToBeShippedList.isEmpty()) {
            log.debug("There are " + artifactsToBeShippedList.size() + " artifacts to be shipped.");
            GenericArtifact genericArtifact = artifactsToBeShippedList.remove(0);
            // if(artifactsToBeShippedList.isEmpty()){
            // repositorySynchronizationWaitingList.remove(currentRecord);
            // repositorySynchronizationWaitingList.add(currentRecord);
            // }
            String artifactId = genericArtifact.getSourceArtifactId();
            try {
                String conflictResolution = this.getConflictResolutionPriority(syncInfo);
                genericArtifact.setConflictResolutionPriority(conflictResolution);
                genericArtifact.setSourceSystemTimezone(this.getSourceSystemTimezone(syncInfo));
                genericArtifact.setTargetSystemTimezone(this.getTargetSystemTimezone(syncInfo));
                // genericArtifact.setSourceSystemEncoding(this.
                // getSourceSystemEncoding(syncInfo));
                // genericArtifact.setTargetSystemEncoding(this.
                // getTargetSystemEncoding(syncInfo));
                Document returnDoc = GenericArtifactHelper.createGenericArtifactXMLDocument(genericArtifact);
                Object[] returnObjects = new Object[] { returnDoc };
                return returnObjects;
            } catch (GenericArtifactParsingException e) {
                String cause = "Could not parse the artifact for " + artifactId;
                log.error(cause, e);
                genericArtifact.setErrorCode(GenericArtifact.ERROR_GENERIC_ARTIFACT_PARSING);
                throw new CCFRuntimeException(cause, e);
            }
        } else if (artifactsToBeReadList.isEmpty() && !isRestartConnector() && !isShutDownConnector()
                && !(isShutdownCCFAfterInitialSync()
                        && connectorHasReadAllInitialSynchronizationStatusRecords)) {
            // our buffer is empty, so we can ask for new synch info again
            currentRecord.readyForNewSynchInfo();
            if (!currentRecord.isNewSyncInfoReceived()) {
                log.debug("Have to wait until sync info for " + currentRecord.getRepositoryId()
                        + " is up to date again ...");
                return new Object[] {};
            }
            log.debug("There are no artifacts to be read. Checking if there are"
                    + " changed artifacts in repository or in hospital for " + currentRecord.getRepositoryId());
            // all our buffers are flushed, we take new syncInfo now
            currentRecord.switchToNewSyncInfo();
            syncInfo = currentRecord.getSyncInfo();
            // TODO Does it make sense to insert retry code here or is it
            // better just to try it again later?
            int numberOfTries = 1;
            boolean retry = false;
            List<ArtifactState> artifactsToBeRead = null;
            do {
                int msToSleep = (numberOfTries - 1) * connectionManager.getRetryIncrementTime();
                int maxMsToSleep = connectionManager.getMaximumRetryWaitingTime();
                try {
                    if (log.isDebugEnabled()) {
                        log.debug("Retrieving artifacts that have been changed for sync record "
                                + syncInfo.asXML());
                    }
                    artifactsToBeRead = this.getChangedArtifactsFromHospitalAndRepository(syncInfo);
                    retry = false;
                } catch (Exception e) {
                    boolean connectionException = connectionManager.isUseStandardTimeoutHandlingCode()
                            && this.handleException(e, connectionManager);
                    if (!connectionException) {
                        retry = false;
                        // remove repository record from list again
                        log.debug("Temporarily removing " + "from waiting list since an exception occured.");
                        removeFromWaitingList(currentRecord);
                        if (e instanceof CCFRuntimeException) {
                            throw (CCFRuntimeException) e;
                        } else if (e instanceof RuntimeException) {
                            throw (RuntimeException) e;
                        } else {
                            throw new CCFRuntimeException("An exception occured", e);
                        }
                    } else {
                        retry = true;
                        if (numberOfTries == 1) {
                            // first try, long error message
                            log.warn(
                                    "Network related problem occurred while connecting to external system. Try operation again",
                                    e);
                        } else if (msToSleep < maxMsToSleep) {
                            // error occurred again, short error message, go
                            // to sleep
                            // we switched to a linear increase of the
                            // timeout value, may
                            // have to revisit this decision later
                            // int timeOut = (int) Math.pow(2,
                            // numberOfTries);
                            log.warn("Network related error occurred again (" + e.getMessage()
                                    + "), incremented timeout, now sleeping for " + msToSleep
                                    + " milliseconds.");
                            try {
                                Thread.sleep(msToSleep);
                            } catch (InterruptedException e1) {
                                log.error("Interrupted sleep in timeout method: ", e1);
                            }
                        } else {
                            log.warn("Network related error occurred again, switched to maximum waiting time ("
                                    + e.getMessage() + "), sleeping for " + maxMsToSleep + " milliseconds.");
                            try {
                                Thread.sleep(maxMsToSleep);
                            } catch (InterruptedException e1) {
                                log.error("Interrupted sleep in timeout method: ", e1);
                            }
                        }
                    }
                }
                ++numberOfTries;
            } while (retry);
            if (!artifactsToBeRead.isEmpty()) {
                artifactsToBeReadList.addAll(artifactsToBeRead);
                /*
                 * we ship artifacts, so the retrieved synch info for this
                 * project mapping may not be up to date until the artifacts
                 * to be read buffer has been completely emptied
                 */
                currentRecord.notReadyForNewSynchInfo();
            }
        }
        if (!artifactsToBeReadList.isEmpty() && !isRestartConnector() && !isShutDownConnector()) {
            log.debug("There are " + artifactsToBeReadList.size() + " artifacts to be read.");
            ArtifactState artifactState = artifactsToBeReadList.remove(0);
            if (rmdForceHandler.isForceEnabled(repositoryMappingDirectionID)
                    && artifactsToBeReadList.isEmpty()) {
                rmdForceHandler.updateRMDConfigToOff(repositoryMappingDirectionID);
            }
            List<GenericArtifact> sortedGAs = null;
            if (artifactState.isReplayedArtifact()) {
                sortedGAs = new ArrayList<GenericArtifact>();
                log.debug(
                        "Parsing quarantined artifact with transaction id " + artifactState.getTransactionId());
                try {
                    GenericArtifact replayedArtifact = GenericArtifactHelper.createGenericArtifactJavaObject(
                            DocumentHelper.parseText(artifactState.getReplayedArtifactData()));
                    log.debug("Successfully parsed quarantined artifact with transaction id "
                            + artifactState.getTransactionId());
                    // reset error code and transaction id
                    replayedArtifact.setErrorCode(artifactState.getErrorCode());
                    replayedArtifact.setTransactionId(artifactState.getTransactionId());
                    sortedGAs.add(replayedArtifact);
                } catch (GenericArtifactParsingException e) {
                    log.warn("Could not parse quarantined artifact with transaction id "
                            + artifactState.getTransactionId(), e);
                } catch (DocumentException e) {
                    log.warn("Could not parse quarantine artifact with transaction id "
                            + artifactState.getTransactionId(), e);
                }
            } else {
                log.debug("Getting the data for artifact " + artifactState.getArtifactId());
                int numberOfTries = 1;

                boolean retry = false;
                do {
                    int msToSleep = (numberOfTries - 1) * connectionManager.getRetryIncrementTime();
                    int maxMsToSleep = connectionManager.getMaximumRetryWaitingTime();
                    try {
                        String artifactId = artifactState.getArtifactId();
                        if (!rmdFilterHandler.containsId(repositoryMappingDirectionID, artifactId)) {
                            return new Object[] {};
                        }
                        // To avoid tampering SyncInfo object we have created a clone
                        // As per java documentation Document.clone() method provides
                        //detached and deep copy of the Object
                        Document tempSyncInfo = (Document) syncInfo.clone();
                        if (getIdentityMappingDatabaseReader() != null) {
                            // Update the syncinfo with the artifact lastmodifiedtime and lastModifiedVersion
                            // fetched from the identity mapping.Modifying the syncinfo does not has any side effects
                            // because artifactsToBeShippedList has already been populated with the artifact data
                            updateSyncInfoFromIdentityMapping(tempSyncInfo, artifactId,
                                    ARTIFACT_TYPE_PLAIN_ARTIFACT);
                        }
                        if (artifactState.isForcedArtifact()) {
                            modifySyncInfo(tempSyncInfo, true);
                        }
                        GenericArtifact artifactData = this.getArtifactData(tempSyncInfo, artifactId);
                        if (artifactData != null) {
                            log.debug("Finding out whether artifact data is stale ...");
                            if (isArtifactStale(artifactState, artifactData)) {
                                log.debug("Artifact data is stale, pick up in next update cycle ...");
                                sortedGAs = new ArrayList<GenericArtifact>();
                            } else {
                                List<GenericArtifact> artifactAttachments = new ArrayList<GenericArtifact>();
                                List<GenericArtifact> artifactDependencies = new ArrayList<GenericArtifact>();
                                try {
                                    if (shipAttachments) {
                                        artifactAttachments = this.getArtifactAttachments(tempSyncInfo,
                                                artifactData);
                                    }
                                    artifactDependencies = this.getArtifactDependencies(tempSyncInfo,
                                            artifactId);
                                } catch (Exception e) {
                                    // if this is a connection exception, we
                                    // will retry, otherwise, we will
                                    // proceed
                                    // with a warning
                                    boolean connectionException = connectionManager
                                            .isUseStandardTimeoutHandlingCode()
                                            && this.handleException(e, connectionManager);
                                    if (connectionException) {
                                        // this will trigger a retry
                                        throw e;
                                    } else {
                                        log.warn("Could not retrieve all attachments/dependencies for artifact "
                                                + artifactId + ". Only plain artifact is synchronized ...");
                                    }
                                }

                                sortedGAs = combineAndSort(artifactData, artifactAttachments,
                                        artifactDependencies);
                            }
                        } else {
                            log.debug("No artifact data has been retrieved for id "
                                    + artifactState.getArtifactId());
                            sortedGAs = new ArrayList<GenericArtifact>();
                        }
                        retry = false;
                    } catch (Exception e) {
                        boolean connectionException = connectionManager.isUseStandardTimeoutHandlingCode()
                                && this.handleException(e, connectionManager);
                        if (!connectionException) {
                            retry = false;
                            log.error("Error retrieving artifact " + artifactState.getArtifactId());
                            if (e instanceof CCFRuntimeException) {
                                throw (CCFRuntimeException) e;
                            } else if (e instanceof RuntimeException) {
                                throw (RuntimeException) e;
                            } else {
                                throw new CCFRuntimeException("An exception occured ", e);
                            }
                        } else {
                            retry = true;
                            if (numberOfTries == 1) {
                                // first try, long error message
                                log.warn("Network related problem occurred while retrieving data for artifact "
                                        + artifactState.getArtifactId() + ". Try operation again", e);
                            } else if (msToSleep < maxMsToSleep) {
                                // error occurred again, short error
                                // message, go
                                // to sleep
                                // we switched to a linear increase of the
                                // timeout value, may
                                // have to revisit this decision later
                                // int timeOut = (int) Math.pow(2,
                                // numberOfTries);
                                log.warn("Network related error for artifact " + artifactState.getArtifactId()
                                        + " occurred again (" + e.getMessage()
                                        + "), incremented timeout, now sleeping for " + msToSleep
                                        + " milliseconds.");
                                try {
                                    Thread.sleep(msToSleep);
                                } catch (InterruptedException e1) {
                                    log.error("Interrupted sleep in timeout method: ", e1);
                                }
                            } else {
                                log.warn("Network related error for artifact " + artifactState.getArtifactId()
                                        + " occurred again, switched to maximum waiting time (" + e.getMessage()
                                        + "), sleeping for " + maxMsToSleep + " milliseconds.");
                                try {
                                    Thread.sleep(maxMsToSleep);
                                } catch (InterruptedException e1) {
                                    log.error("Interrupted sleep in timeout method: ", e1);
                                }
                            }
                        }
                    }
                    ++numberOfTries;
                } while (retry);
            }

            artifactsToBeShippedList.addAll(sortedGAs);
            if (artifactsToBeShippedList.isEmpty())
                return new Object[] {};

            GenericArtifact genericArtifact = artifactsToBeShippedList.remove(0);
            try {
                String conflictResolution = this.getConflictResolutionPriority(syncInfo);
                genericArtifact.setConflictResolutionPriority(conflictResolution);
                genericArtifact.setSourceSystemTimezone(this.getSourceSystemTimezone(syncInfo));
                genericArtifact.setTargetSystemTimezone(this.getTargetSystemTimezone(syncInfo));
                // genericArtifact.setSourceSystemEncoding(this.
                // getSourceSystemEncoding(syncInfo));
                // genericArtifact.setTargetSystemEncoding(this.
                // getTargetSystemEncoding(syncInfo));
                Document returnDoc = GenericArtifactHelper.createGenericArtifactXMLDocument(genericArtifact);
                Object[] returnObjects = new Object[] { returnDoc };
                return returnObjects;
            } catch (GenericArtifactParsingException e) {
                String cause = "Could not parse the artifact for " + artifactState.getArtifactId();
                log.error(cause, e);
                genericArtifact.setErrorCode(GenericArtifact.ERROR_GENERIC_ARTIFACT_PARSING);
                throw new CCFRuntimeException(cause, e);
            }
        } else {
            log.debug("No changed artifacts reported for " + currentRecord.getRepositoryId()
                    + ". Removing it from the waiting list");
            removeFromWaitingList(currentRecord);
        }
    }
    try {
        if (isRestartConnector()) {
            log.debug("All buffers are flushed now ..., exit with exit code " + RESTART_EXIT_CODE);
            ShutDownCCF.exitCCF(RESTART_EXIT_CODE);
        } else if (isShutDownConnector()) {
            log.debug("All buffers are flushed now ..., exit with exit code " + 0);
            ShutDownCCF.exitCCF(0);
        } else if (connectorHasReadAllInitialSynchronizationStatusRecords) {
            if (isShutdownCCFAfterInitialSync()) {
                log.info("All repositories are in synch at this time, shutting down");
                setShutDownConnector(true);
            } else {
                log.debug("There are no artifacts to be shipped from any of the repositories. Sleeping");
                Thread.sleep(sleepInterval);
            }
        }
    } catch (InterruptedException e) {
        String cause = "Thread is interrupted";
        log.warn(cause, e);
    }
    return new Object[] {};
}

From source file:com.collabnet.ccf.core.transformer.XsltProcessor.java

License:Open Source License

/**
 * Use the XML supplied to create a DOM document
 * /*from   www.j  a  va 2  s. c  om*/
 * @param xml
 *            valid XML
 * 
 * @return dom4j document object
 * 
 * @throws ProcessingException
 *             if the supplied XML cannot be parsed
 */
private Document createDOMFromString(String xml, Element element) {
    try {
        return DocumentHelper.parseText(xml);
    } catch (DocumentException e) {
        String cause = "Failed to parse XML: " + e.getMessage();
        log.error(cause, e);
        XPathUtils.addAttribute(element, GenericArtifactHelper.ERROR_CODE,
                GenericArtifact.ERROR_TRANSFORMER_TRANSFORMATION);
        throw new CCFRuntimeException(cause, e);
    }
}

From source file:com.collabnet.ccf.core.utils.GenericArtifactMultiLineParser.java

License:Open Source License

/**
 * Use the XML supplied to create a DOM document
 * //from  ww w . j ava 2 s  . co  m
 * @param xml
 *            valid XML
 * 
 * @return dom4j document object
 * 
 * @throws ProcessingException
 *             if the supplied XML cannot be parsed
 */
private Document createDOMFromString(String xml) {
    try {
        return DocumentHelper.parseText(xml);
    } catch (DocumentException e) {
        log.error("Failed to parse XML document: " + xml);
        throw new ProcessingException("Failed to parse XML: " + e.getMessage(), this);
    }
}