Example usage for org.dom4j Element elementText

List of usage examples for org.dom4j Element elementText

Introduction

In this page you can find the example usage for org.dom4j Element elementText.

Prototype

String elementText(QName qname);

Source Link

Usage

From source file:org.snipsnap.snip.XMLSnipImport.java

License:Open Source License

/**
 * Load snips and users into the SnipSpace from an xml document out of a stream.
 *
 * @param in    the input stream to load from
 * @param flags whether or not to overwrite existing content
 *///ww  w.ja va2 s.  com
public static void load(InputStream in, final int flags) throws IOException {
    SAXReader saxReader = new SAXReader();
    try {
        saxReader.addHandler("/snipspace/user", new ElementHandler() {
            public void onStart(ElementPath elementPath) {
                // nothing to do here ...
            }

            public void onEnd(ElementPath elementPath) {
                Element userElement = elementPath.getCurrent();
                if ((flags & IMPORT_USERS) != 0) {
                    try {
                        XMLSnipImport.loadUser(elementPath.getCurrent(), flags);
                    } catch (Exception e) {
                        Logger.fatal("XMLSnipImport: error importing user: " + userElement.elementText("name"));
                    }
                    getStatus().inc();
                }
                // prune the element to save memory
                userElement.detach();
            }
        });

        saxReader.addHandler("/snipspace/snip", new ElementHandler() {
            public void onStart(ElementPath elementPath) {
                // nothing to do here ...
            }

            public void onEnd(ElementPath elementPath) {
                Element snipElement = elementPath.getCurrent();
                if ((flags & IMPORT_SNIPS) != 0) {
                    try {
                        XMLSnipImport.loadSnip(snipElement, flags);
                    } catch (Exception e) {
                        Logger.fatal("XMLSnipImport: error importing snip: " + snipElement.elementText("name"));
                    }
                    getStatus().inc();
                }
                // prune the element to save memory
                snipElement.detach();
            }
        });

        // add a reader wrapper to remove illegal characters from input stream
        // it looks like the database export (XMLWriter) allows these to get through
        InputStreamReader reader = new InputStreamReader(in, "UTF-8") {
            public int read(char[] chars) throws IOException {
                int n = super.read(chars);
                for (int i = 0; i < n; i++) {
                    chars[i] = replaceIfIllegal(chars[i]);
                }
                return n;
            }

            public int read(char[] chars, int start, int length) throws IOException {
                int n = super.read(chars, start, length);
                for (int i = 0; i < n; i++) {
                    chars[i] = replaceIfIllegal(chars[i]);
                }
                return n;
            }

            private char replaceIfIllegal(char c) {
                if (c < 0x20 && !(c == 0x09 || c == 0x0a || c == 0x0d)) {
                    charErrCount++;
                    return (char) 0x20;
                }
                return c;
            }
        };

        saxReader.read(reader);
        Logger.warn("XMLSnipImport: corrected " + charErrCount + " characters in input");
        Logger.log("XMLSnipImport: imported " + getStatus().getValue() + " data records");
    } catch (DocumentException e) {
        Logger.warn("XMLSnipImport: unable to parse document", e);
        throw new IOException("Error parsing document: " + e);
    }
}

From source file:org.snipsnap.snip.XMLSnipImport.java

License:Open Source License

private static void restoreAttachments(Element snipEl) {
    Configuration config = snipsnap.api.app.Application.get().getConfiguration();
    File attRoot = config.getFilePath();
    Element attachmentsEl = snipEl.element("attachments");
    if (null != attachmentsEl) {
        Iterator attIt = attachmentsEl.elements("attachment").iterator();
        while (attIt.hasNext()) {
            Element att = (Element) attIt.next();
            if (att.element("data") != null) {
                File attFile = new File(attRoot, att.elementText("location"));
                try {
                    // make sure the directory hierarchy exists
                    attFile.getParentFile().mkdirs();
                    byte buffer[] = Base64.decodeBase64(att.elementText("data").getBytes("UTF-8"));
                    BufferedOutputStream os = new BufferedOutputStream(new FileOutputStream(attFile));
                    os.write(buffer);/* ww w  .j  a  v a2  s.  c  om*/
                    os.flush();
                    os.close();
                } catch (Exception e) {
                    Logger.fatal("unable to store attachment: " + e);
                    e.printStackTrace();
                }
                att.element("data").detach();
            }
        }
    }
}

From source file:org.snipsnap.util.XMLSnipRepair.java

License:Open Source License

private static int storeAttachments(Element snipEl, File attRoot) {
    Element attachmentsEl = snipEl.element("attachments");
    attachmentsEl.detach();/*  w  ww . j a v  a  2s .  c  om*/
    String textContent = attachmentsEl.getText();
    if (textContent != null && textContent.length() > 0 && attachmentsEl.elements("attachment").size() == 0) {
        SAXReader saxReader = new SAXReader();
        try {
            attachmentsEl = saxReader.read(new StringReader("<attachments>" + textContent + "</attachments>"))
                    .getRootElement();
        } catch (DocumentException e) {
            System.err.println("Error parsing the attachments ...: " + e.getMessage());
        }
    }

    int attCount = 0;
    Iterator attIt = attachmentsEl.elements("attachment").iterator();
    while (attIt.hasNext()) {
        Element att = (Element) attIt.next();
        File file = new File(attRoot, att.elementText("location"));
        String snipName = snipEl.element("name").getText();
        if (att.element("data") == null) {
            if (file.exists()) {
                try {
                    addAttachmentFile(att, file);
                    attCount++;
                    //          System.err.println("Added '" + file.getPath() + "' to " + snipName);
                } catch (Exception e) {
                    System.err.println("Error adding '" + file.getPath() + "' to '" + snipName + "'");
                    e.printStackTrace();
                    att.detach();
                }
            } else {
                System.err.println("Missing file '" + file.getPath() + "' attached to '" + snipName + "'");
                att.detach();
            }
        }
    }
    snipEl.add(attachmentsEl);
    return attCount;
}

From source file:org.sonar.plugins.buildstability.ci.bamboo.BambooBuildUnmarshaller.java

License:Apache License

public Build toModel(Element domElement) {
    Build build = new Build();

    String state = domElement.attributeValue("state");
    build.setNumber(Integer.parseInt(domElement.attributeValue("number")));
    build.setResult(state);//from w w  w  .  j a  v a 2  s .co  m

    SimpleDateFormat sdf = new SimpleDateFormat(DATE_TIME_FORMAT);
    String buildStartedTime = domElement.elementText("buildStartedTime");
    try {
        Date date = sdf.parse(buildStartedTime);
        build.setTimestamp(date.getTime());
    } catch (ParseException ignored) {
        // ignore
    }
    build.setDuration(Double.parseDouble(domElement.elementText("buildDurationInSeconds")) * 1000);
    build.setSuccessful(SUCCESSFULL.equalsIgnoreCase(state));

    return build;
}

From source file:org.sonar.plugins.buildstability.ci.hudson.HudsonBuildUnmarshaller.java

License:Apache License

public Build toModel(Element domElement) {
    Build build = new Build();

    String result = domElement.elementText("result");
    build.setNumber(Integer.parseInt(domElement.elementText("number")));
    build.setTimestamp(Long.parseLong(domElement.elementText("timestamp")));
    build.setResult(result);/*w w  w .j a  va  2 s  .  c o  m*/
    build.setDuration(Long.parseLong(domElement.elementText("duration")));
    build.setSuccessful("SUCCESS".equalsIgnoreCase(result));

    return build;
}

From source file:org.sonar.plugins.buildstability.ci.jenkins.JenkinsBuildUnmarshaller.java

License:Open Source License

@Override
public Build toModel(Element domElement) {
    Build build = new Build();

    String result = domElement.elementText("result");
    build.setNumber(Integer.parseInt(domElement.elementText("number")));
    build.setTimestamp(Long.parseLong(domElement.elementText("timestamp")));
    build.setResult(result);//  ww  w.  j  ava  2  s . c o  m
    build.setDuration(Long.parseLong(domElement.elementText("duration")));
    build.setSuccessful("SUCCESS".equalsIgnoreCase(result));

    return build;
}

From source file:org.sonar.plugins.buildstability.ci.teamcity.TeamCityBuildUnmarshaller.java

License:Open Source License

@Override
public Build toModel(Element domElement) {
    Build build = new Build();

    String result = domElement.attributeValue("status");

    LOG.debug("Parsing build detail: number: {}", domElement.attributeValue("number"));

    build.setNumber(domElement.attributeValue("number"));
    build.setTimestamp(getTimeStamp(domElement.elementText("startDate")));
    build.setResult(result);// w  w  w. j av a 2s.c  o  m
    build.setDuration(
            calculateDuration(domElement.elementText("startDate"), domElement.elementText("finishDate")));
    build.setSuccessful("SUCCESS".equalsIgnoreCase(result));

    return build;
}

From source file:org.soyatec.windowsazure.internal.util.HttpUtilities.java

License:Apache License

private static StorageExtendedErrorInformation getErrorDetailsFromStream(BlobStream stream) {
    StorageExtendedErrorInformation extendedError = new StorageExtendedErrorInformation();
    try {/*w  w  w. j a va 2s .c  o  m*/
        Document doc = XmlUtil.parseXmlString(new String(stream.getBytes()));
        Element root = doc.getRootElement();
        extendedError.setErrorCode(root.elementText(XmlElementNames.ErrorCode));
        extendedError.setErrorMessage(root.elementText(XmlElementNames.ErrorMessage));
        NameValueCollection details = new NameValueCollection();
        extendedError.setAdditionalDetails(details);

        for (Object o : root.elements()) {
            Element e = (Element) o;
            if (e.getName().equals(XmlElementNames.ErrorException)) {
                details.put(XmlElementNames.ErrorExceptionMessage,
                        e.elementText(XmlElementNames.ErrorExceptionMessage));
                details.put(XmlElementNames.ErrorExceptionStackTrace,
                        e.elementText(XmlElementNames.ErrorExceptionStackTrace));
            } else {
                details.put(e.getName(), e.getText());
            }
        }
    } catch (Exception e) {
        return null;
    }
    return extendedError;
}

From source file:org.talend.designer.alfrescooutput.data.AlfrescoOutputModelManager.java

License:Open Source License

/**
 * Fills a (parameter) property metadata row with property info
 *//*from w  ww. ja  v a2s  . c o  m*/
protected void fillPropertyMappingRow(Map<String, String> metadataMappingRow, Element metadata) {
    // NB. reputting PARAM_ITEM_NAME is not required if the metadata with
    // such a name already existed, but not a problem either
    metadataMappingRow.put(PARAM_ITEM_NAME, metadata.attributeValue("name")); //$NON-NLS-1$
    metadataMappingRow.put(PARAM_ITEM_TITLE, metadata.elementText("title")); //$NON-NLS-1$
    metadataMappingRow.put(PARAM_ITEM_TYPE, metadata.elementText("type")); //$NON-NLS-1$
    metadataMappingRow.put(PARAM_ITEM_MANDATORY, metadata.elementText("mandatory")); //$NON-NLS-1$
    metadataMappingRow.put(PARAM_ITEM_DEFAULT, metadata.elementText("default")); //$NON-NLS-1$
    // NB. no default for VALUE
}

From source file:org.talend.designer.alfrescooutput.data.AlfrescoOutputModelManager.java

License:Open Source License

/**
 * Fills a (parameter) association metadata row with association info
 *///from  ww  w .  ja  v  a2s  . com
protected void fillAssociationMappingRow(Map<String, String> metadataMappingRow, Element metadata) {
    // NB. reputting PARAM_ITEM_NAME is not required if the metadata with
    // such a name already existed, but not a problem either
    metadataMappingRow.put(PARAM_ITEM_NAME, metadata.attributeValue("name")); //$NON-NLS-1$
    metadataMappingRow.put(PARAM_ITEM_CHILD, String.valueOf("child-association".equals(metadata.getName()))); //$NON-NLS-1$
    metadataMappingRow.put(PARAM_ITEM_TITLE, metadata.elementText("title")); //$NON-NLS-1$
    Element associationTarget = metadata.element("target"); //$NON-NLS-1$
    if (associationTarget != null) {
        metadataMappingRow.put(PARAM_ITEM_TYPE, associationTarget.elementText("class")); //$NON-NLS-1$
        metadataMappingRow.put(PARAM_ITEM_MANDATORY, associationTarget.elementText("mandatory")); //$NON-NLS-1$
        metadataMappingRow.put(PARAM_ITEM_MANY, associationTarget.elementText("many")); //$NON-NLS-1$
    }
}