Example usage for org.dom4j Document getRootElement

List of usage examples for org.dom4j Document getRootElement

Introduction

In this page you can find the example usage for org.dom4j Document getRootElement.

Prototype

Element getRootElement();

Source Link

Document

Returns the root Element for this document.

Usage

From source file:com.collabnet.ccf.teamforge.TFWriter.java

License:Open Source License

@Override
public Document[] deleteAttachment(Document gaDocument) {
    GenericArtifact ga = null;//www . j  av  a  2s  . co  m
    try {
        ga = GenericArtifactHelper.createGenericArtifactJavaObject(gaDocument);
    } catch (GenericArtifactParsingException e) {
        String cause = "Problem occured while parsing the GenericArtifact into Document";
        log.error(cause, e);
        XPathUtils.addAttribute(gaDocument.getRootElement(), GenericArtifactHelper.ERROR_CODE,
                GenericArtifact.ERROR_GENERIC_ARTIFACT_PARSING);
        throw new CCFRuntimeException(cause, e);
    }
    this.initializeArtifact(ga);
    // String targetRepositoryId = ga.getTargetRepositoryId();
    String targetArtifactId = ga.getTargetArtifactId();
    String artifactId = ga.getDepParentTargetArtifactId();
    // String tracker = targetRepositoryId;
    Connection connection = null;
    GenericArtifact parentArtifact = null;
    try {
        connection = connect(ga);
        try {
            attachmentHandler.deleteAttachment(connection, targetArtifactId, artifactId, ga);
        } catch (AxisFault e) {
            javax.xml.namespace.QName faultCode = e.getFaultCode();
            if (faultCode.getLocalPart().equals("NoSuchObjectFault")) {
                log.warn("Attachment " + targetArtifactId + " does not exist any more!");
                return null;
            } else {
                throw e;
            }
        }
        log.info("Attachment " + targetArtifactId + " is deleted successfully.");
        ArtifactDO artifact = null;
        try {
            artifact = trackerHandler.getTrackerItem(connection, artifactId);
        } catch (AxisFault e) {
            javax.xml.namespace.QName faultCode = e.getFaultCode();
            if (faultCode.getLocalPart().equals("NoSuchObjectFault")) {
                log.warn("Artifact " + artifactId + " does not exist any more!");
                return null;
            } else {
                throw e;
            }
        }
        parentArtifact = new GenericArtifact();
        // make sure that we do not update the synchronization status record
        // for replayed attachments
        parentArtifact.setTransactionId(ga.getTransactionId());
        parentArtifact.setArtifactType(GenericArtifact.ArtifactTypeValue.PLAINARTIFACT);
        parentArtifact.setArtifactAction(GenericArtifact.ArtifactActionValue.UPDATE);
        parentArtifact.setArtifactMode(GenericArtifact.ArtifactModeValue.CHANGEDFIELDSONLY);
        parentArtifact.setConflictResolutionPriority(ga.getConflictResolutionPriority());
        parentArtifact.setSourceArtifactId(ga.getDepParentSourceArtifactId());
        parentArtifact.setSourceArtifactLastModifiedDate(ga.getSourceArtifactLastModifiedDate());
        parentArtifact.setSourceArtifactVersion(ga.getSourceArtifactVersion());
        parentArtifact.setSourceRepositoryId(ga.getSourceRepositoryId());
        parentArtifact.setSourceSystemId(ga.getSourceSystemId());
        parentArtifact.setSourceSystemKind(ga.getSourceSystemKind());
        parentArtifact.setSourceRepositoryKind(ga.getSourceRepositoryKind());
        parentArtifact.setSourceSystemTimezone(ga.getSourceSystemTimezone());

        parentArtifact.setTargetArtifactId(artifactId);
        parentArtifact.setTargetArtifactLastModifiedDate(DateUtil.format(artifact.getLastModifiedDate()));
        parentArtifact.setTargetArtifactVersion(Integer.toString(artifact.getVersion()));
        parentArtifact.setTargetRepositoryId(ga.getTargetRepositoryId());
        parentArtifact.setTargetRepositoryKind(ga.getTargetRepositoryKind());
        parentArtifact.setTargetSystemId(ga.getTargetSystemId());
        parentArtifact.setTargetSystemKind(ga.getTargetSystemKind());
        parentArtifact.setTargetSystemTimezone(ga.getTargetSystemTimezone());
    } catch (RemoteException e) {

        String message = "Exception while deleting attachment " + artifactId;
        log.error(message, e);
        throw new CCFRuntimeException(message, e);
    } finally {
        if (connection != null) {
            this.disconnect(connection);
        }
    }
    Document returnDocument = null;
    Document returnParentDocument = null;
    try {
        returnDocument = GenericArtifactHelper.createGenericArtifactXMLDocument(ga);
        returnParentDocument = GenericArtifactHelper.createGenericArtifactXMLDocument(parentArtifact);
    } catch (GenericArtifactParsingException e) {
        String message = "Exception while deleting attachment " + artifactId
                + ". Could not parse Generic artifact";
        log.error(message, e);
        throw new CCFRuntimeException(message, e);
    }
    return new Document[] { returnDocument, returnParentDocument };
}

From source file:com.collabnet.ccf.teamforge.TFWriter.java

License:Open Source License

@Override
public Document updateArtifact(Document data) {
    GenericArtifact ga = null;/* w  ww  .j a  v  a2  s  .com*/
    try {
        ga = GenericArtifactHelper.createGenericArtifactJavaObject(data);
    } catch (GenericArtifactParsingException e) {
        String cause = "Problem occured while parsing the GenericArtifact into Document";
        log.error(cause, e);
        XPathUtils.addAttribute(data.getRootElement(), GenericArtifactHelper.ERROR_CODE,
                GenericArtifact.ERROR_GENERIC_ARTIFACT_PARSING);
        throw new CCFRuntimeException(cause, e);
    }
    Connection connection = connect(ga);
    try {
        String targetRepositoryId = ga.getTargetRepositoryId();
        if (TFConnectionFactory.isTrackerRepository(targetRepositoryId)) {
            this.initializeArtifact(ga);

            String tracker = targetRepositoryId;

            ArtifactDO result = null;
            try {
                // update and do conflict resolution
                result = this.updateArtifact(ga, tracker, connection);
            } catch (NumberFormatException e) {
                String cause = "Number format exception while trying to extract the field data.";
                log.error(cause, e);
                XPathUtils.addAttribute(data.getRootElement(), GenericArtifactHelper.ERROR_CODE,
                        GenericArtifact.ERROR_GENERIC_ARTIFACT_PARSING);
                throw new CCFRuntimeException(cause, e);
            }
            // otherwise a conflict has happened and the generic artifact
            // has been
            // already prepared
            if (result != null) {
                this.populateTargetArtifactAttributes(ga, result);
            }
            return this.returnDocument(ga);
        } else if (TFConnectionFactory.isPlanningFolderRepository(targetRepositoryId)) {
            // we write planning folders, so first do a check whether we
            // support this feature
            if (!connection.supports53()) {
                // we do not support planning folders
                throw new CCFRuntimeException(
                        "Planning Folders are not supported since TeamForge target system does not provide them.");
            }

            PlanningFolderDO result = null;
            try {
                // update and do conflict resolution
                String project = TFConnectionFactory.extractProjectFromRepositoryId(targetRepositoryId);
                result = updatePlanningFolder(ga, project, connection);
            } catch (NumberFormatException e) {
                String cause = "Number format exception while trying to extract the field data.";
                log.error(cause, e);
                XPathUtils.addAttribute(data.getRootElement(), GenericArtifactHelper.ERROR_CODE,
                        GenericArtifact.ERROR_GENERIC_ARTIFACT_PARSING);
                throw new CCFRuntimeException(cause, e);
            } catch (RemoteException e) {
                String cause = "While trying to update a planning folder within TF, an error occured";
                log.error(cause, e);
                ga.setErrorCode(GenericArtifact.ERROR_EXTERNAL_SYSTEM_WRITE);
                throw new CCFRuntimeException(cause, e);
            } catch (PlanningFolderRuleViolationException e) {
                String cause = "While trying to move a planning folder within TF, a planning folder rule violation occured";
                log.error(cause, e);
                ga.setErrorCode(GenericArtifact.ERROR_EXTERNAL_SYSTEM_WRITE);
                throw new CCFRuntimeException(cause, e);
            }
            // otherwise a conflict has happened and the generic artifact
            // has been
            // already prepared
            if (result != null) {
                populateTargetArtifactAttributesFromPlanningFolder(ga, result);
            }
            return returnDocument(ga);
        } else if (TFConnectionFactory.isTrackerMetaDataRepository(targetRepositoryId)) {
            TrackerDO result = null;
            String trackerId = TFConnectionFactory.extractTrackerFromMetaDataRepositoryId(targetRepositoryId);
            result = updateTrackerMetaData(ga, trackerId, connection);
            populateTargetArtifactAttributesFromTracker(ga, result);
            return returnDocument(ga);
        } else {
            throw new CCFRuntimeException("Unknown repository id format: " + targetRepositoryId);
        }
    } finally {
        disconnect(connection);
    }
}

From source file:com.compliance.webapp.filter.LicenseFilter.java

public Boolean resolve(HttpServletRequest hRequest) {
    Boolean fileIsExist = false;//  w  w w .  java 2s  .  c o  m
    try {
        String path = hRequest.getSession().getServletContext().getRealPath("/");
        File file = new File(path + "compliance.licence");
        if (file.exists()) {
            fileIsExist = true;
            FileInputStream in = null;

            in = new FileInputStream(file);
            byte[] buf = new byte[4096];
            int len = in.read(buf, 0, 4096);
            in.close();

            byte[] buffer = new byte[len];
            for (int i = 0; i < len; i++) {
                buffer[i] = buf[i];
            }

            char[] key1 = { 0x3F, 0xEE, 0x3F, 0x5A, 0xAE, 0xFA, 0x1F, 0x0A };
            char[] key2 = { 0x3D, 0xAE, 0x3A, 0x5B, 0x3F, 0x6A, 0x11, 0xAA };
            char[] key3 = { 0x0B, 0x9E, 0xDF, 0x2A, 0xAA, 0xF0, 0x7D, 0x6E };

            buffer = EncodeUtil.xorDecode(buffer, key3);

            buffer = EncodeUtil.xorDecode(buffer, key2);

            buffer = EncodeUtil.xorDecode(buffer, key1);

            // ?XML
            Document document = DocumentHelper.parseText(new String(buffer));
            Element root = document.getRootElement();
            if (root.getName().equals("reginfo")) {
                List<Element> elementsList = root.elements();
                Iterator<Element> iterator = elementsList.iterator();
                while (iterator.hasNext()) {
                    Element element = (Element) iterator.next();
                    if (element.getName().equals("name")) {
                        Serial.SERIAL_NAME = element.getText();
                    } else if (element.getName().equals("versions")) {
                        Serial.SERIAL_VERSIONS = element.getText();
                    } else if (element.getName().equals("auth_day")) {
                        Serial.SERIAL_AUTH_DAY = Integer.parseInt(element.getText());
                    } else if (element.getName().equals("gen_time")) {
                        Serial.SERIAL_GEN_TIME = Long.parseLong(element.getText());
                    } else if (element.getName().equals("resource_num")) {
                        Serial.SERIAL_RESOURCE_NUM = Integer.parseInt(element.getText());
                    } else if (element.getName().equals("sign")) {
                        Serial.SERIAL_SIGN = element.getText();
                    }
                }
            }
        }
    } catch (Exception e) {
        fileIsExist = false;
        e.printStackTrace();

    }
    return fileIsExist;
}

From source file:com.controlj.addon.weather.wbug.service.WeatherBugDataUtils.java

License:Open Source License

/**
 * Navigates a XML document through an XPath and, for each encountered element, creates a specific WeatherBug data object (<i>Location</i>,
 * <i>Station</i>, and so on). Java reflection errors are silently ignored.
 * //from w  w w .j a  v  a 2s . c o m
 * 
 * @param doc
 *            the XML document being accessed.
 * @param path
 *            the XPath used to find specific sub-elements.
 * @param dataClass
 *            the class of objects being instantiated (<i>Location</i>, <i>Station</i>, and so on).
 * @return a list of <i>dataClass</i> objects.
 */
public static <T> List<T> bind(Document doc, String path, Class<T> dataClass)
        throws WeatherBugServiceException {
    List<T> objects = bind(doc.getRootElement(), path, dataClass);
    if (objects.isEmpty())
        extractError(doc);
    return objects;
}

From source file:com.controlj.addon.weather.wbug.service.WeatherBugDataUtils.java

License:Open Source License

private static void extractError(Document doc) throws WeatherBugServiceException {
    Node h1 = doc.getRootElement().selectSingleNode("/h1");
    if (h1 != null)
        throw new WeatherBugServiceException(h1.getText());

    Node title = doc.getRootElement().selectSingleNode("/rss/channel/title");
    if (title != null && "Observations from ,  - USA".equals(title.getText()))
        throw new WeatherBugServiceException("Missing station content");

    Logging.logDocument("unknown", "Unknown error", doc);
    throw new WeatherBugServiceException("Unknown error");
}

From source file:com.core.util.wx.XmlUtils.java

License:Apache License

/**
 * xmlmap// w w  w.  j a va 2 s . co m
 * 
 * @param xml
 * @return
 */
@SuppressWarnings("rawtypes")
public static Map<String, String> xmlToMap(String xml) {
    Map<String, String> map = new HashMap<String, String>();
    Document doc = null;
    try {
        doc = DocumentHelper.parseText(xml);
    } catch (DocumentException e) {
        LOG.error(e.getMessage(), e);
    }
    if (null == doc)
        return map;
    Element root = doc.getRootElement();
    for (Iterator iterator = root.elementIterator(); iterator.hasNext();) {
        Element e = (Element) iterator.next();
        map.put(e.getName(), e.getText());
    }
    return map;
}

From source file:com.core.util.wx.XmlUtils.java

License:Apache License

/**
 * @param  ??xml//from  w  w  w  . ja  va 2s .co m
 * @return
 * @throws UnsupportedEncodingException
 * @throws DocumentException
 * ???xml???
 */
public static Map<String, String> sfxmlToMap(String xml)
        throws UnsupportedEncodingException, DocumentException {
    LOG.info("xml:" + xml);
    Map<String, String> map = new HashMap<String, String>();
    Document doc = null;
    try {
        doc = DocumentHelper.parseText(xml);
    } catch (DocumentException e) {
        LOG.error(e.getMessage(), e);
    }
    if (null == doc)
        return map;
    Element root = doc.getRootElement();
    for (Iterator iterator = root.elementIterator(); iterator.hasNext();) {
        Element e = (Element) iterator.next();
        if (e.getName().equals("Head")) {
            if (e.getText().equals("ERR")) {
                return null;
            }
        }
        if (e.getName().equals("Body")) {
            Element e1 = e.element("OrderResponse");
            if (e1 != null) {
                if (e1.attribute("mailno") != null) {
                    map.put("mailno", e1.attribute("mailno").getText());
                }
                if (e1.attribute("destcode") != null) {
                    map.put("destcode", e1.attribute("destcode").getText());
                }
                if (e1.attribute("filter_result") != null) {
                    map.put("filter_result", e1.attribute("filter_result").getText());
                }
            }
            Element e2 = e.element("OrderZDResponse");
            if (e2 != null) {
                Element s = e2.element("OrderZDResponse");
                if (s.attribute("mailno_zd") != null) {
                    map.put("mailno_zd", s.attribute("mailno_zd").getText());
                }
            }
            break;
        }
    }
    return map;
}

From source file:com.creativity.controller.CepWebService.java

@SuppressWarnings("rawtypes")
public CepWebService(String cep) {

    try {// www . j av a  2s.  c o  m
        URL url = new URL("http://cep.republicavirtual.com.br/web_cep.php?cep=" + cep + "&formato=xml");

        Document document = getDocumento(url);

        Element root = document.getRootElement();

        for (Iterator i = root.elementIterator(); i.hasNext();) {
            Element element = (Element) i.next();

            if (element.getQualifiedName().equals("uf")) {
                setEstado(element.getText());
            }

            if (element.getQualifiedName().equals("cidade")) {
                setCidade(element.getText());
            }

            if (element.getQualifiedName().equals("bairro")) {
                setBairro(element.getText());
            }

            if (element.getQualifiedName().equals("tipo_logradouro")) {
                setTipoLogradouro(element.getText());
            }

            if (element.getQualifiedName().equals("logradouro")) {
                setLogradouro(element.getText());
            }

            if (element.getQualifiedName().equals("resultado")) {
                setResultado(Integer.parseInt(element.getText()));
            }
        }
    } catch (Exception ex) {
        ex.printStackTrace();
    }
}

From source file:com.creditcloud.investmentfund.model.huaan.money.CommonRequestMessage.java

/**
 * ??XML content/*from   www  .j ava2  s  . co m*/
 *
 * @return
 */
public String buildXMLPayload() {
    try {
        Map<String, String> map = toMapFromXMLPayloadParameters();
        final String rootXMLNodeName = "order";
        XmlFactory factory = new XmlFactory(new InputFactoryImpl(), new CDataXmlOutputFactoryImpl());
        XmlMapper xmlMapper = new XmlMapper(factory);
        xmlMapper.configure(ToXmlGenerator.Feature.WRITE_XML_DECLARATION, true);
        String xml = xmlMapper.writeValueAsString(map);
        Document doc = DocumentHelper.parseText(xml);
        Element root = doc.getRootElement();
        root.setName(rootXMLNodeName);
        doc.setXMLEncoding(FundInterfaceConstants.HUA_AN_MONEY_FUND_HTTP_ENCODING);
        xml = doc.asXML();
        setContentXMLPayloadPlainText(xml);
        return xml;
    } catch (JsonProcessingException | DocumentException e) {
        throw new RuntimeException(e);
    }
}

From source file:com.creditcloud.investmentfund.model.lion.moneyfund.response.NotificationResponseMessage.java

/**
 * ???XML?/*w w  w. j  av  a2s  .  com*/
 *
 * @return
 * @throws JsonProcessingException
 * @throws org.dom4j.DocumentException
 */
public String toXMLMessage() throws JsonProcessingException, DocumentException {
    final String rootXMLNodeName = "Message";
    ObjectMapper xmlMapper = new XmlMapper();
    String xml = xmlMapper.writeValueAsString(this);
    Document doc = DocumentHelper.parseText(xml);
    Element root = doc.getRootElement();
    root.setName(rootXMLNodeName);
    doc.setXMLEncoding(FundInterfaceConstants.LION_MONEY_FUND_HTTP_ENCODING);
    xml = doc.asXML();
    return xml;
}