Example usage for org.jdom2 Element getChildText

List of usage examples for org.jdom2 Element getChildText

Introduction

In this page you can find the example usage for org.jdom2 Element getChildText.

Prototype

public String getChildText(final String cname) 

Source Link

Document

Returns the textual content of the named child element, or null if there's no such child.

Usage

From source file:org.knoxcraft.database.xml.XmlDatabase.java

License:Open Source License

private void sortElements(Document doc) {
    // Need tableProperties to be at the top
    doc.getRootElement().sortChildren(new Comparator<Element>() {
        @Override/*from  w  w w.  ja v a  2  s  .c o  m*/
        public int compare(Element o1, Element o2) {
            if (o1.getName().equals("tableProperties")) {
                return -1;
            } else if (o2.getName().equals("tableProperties")) {
                return 1;
            } else {
                return Integer.valueOf(o1.getChildText("id")).compareTo(Integer.valueOf(o2.getChildText("id")));
            }
        }
    });

    /* Why is this necessary? */
    for (Element e : doc.getRootElement().getChildren()) {
        e.sortChildren(new Comparator<Element>() {
            @Override
            public int compare(Element o1, Element o2) {
                return o1.getName().compareTo(o2.getName());
            }
        });
    }
}

From source file:org.mycore.common.MCRMailer.java

License:Open Source License

/**
 * Generates e-mail from the given input document by transforming it with an xsl stylesheet,
 * and sends the e-mail afterwards.//w ww.  j  av a  2s.  c  om
 * 
 * @param input the xml input document
 * @param stylesheet the xsl stylesheet that will generate the e-mail, without the ending ".xsl" 
 * @param parameters the optionally empty table of xsl parameters
 * @return the generated e-mail
 * 
 * @see org.mycore.common.MCRMailer
 */
public static Element sendMail(Document input, String stylesheet, Map<String, String> parameters)
        throws Exception {
    LOGGER.info("Generating e-mail from " + input.getRootElement().getName() + " using " + stylesheet + ".xsl");
    if (LOGGER.isDebugEnabled())
        debug(input.getRootElement());

    Element eMail = transform(input, stylesheet, parameters).getRootElement();
    if (LOGGER.isDebugEnabled())
        debug(eMail);

    if (eMail.getChildren("to").isEmpty())
        LOGGER.warn("Will not send e-mail, no 'to' address specified");
    else {
        LOGGER.info("Sending e-mail to " + eMail.getChildText("to") + ": " + eMail.getChildText("subject"));
        MCRMailer.send(eMail);
    }

    return eMail;
}

From source file:org.mycore.datamodel.metadata.MCRDerivate.java

License:Open Source License

/**
 * Reads all files and urns from the derivate.
 * /*from   w w w .ja va 2 s  .co  m*/
 * @return A {@link Map} which contains the files as key and the urns as value. If no URN assigned the map will be empty.
 */
public Map<String, String> getUrnMap() {
    Map<String, String> fileUrnMap = new HashMap<String, String>();

    XPathExpression<Element> filesetPath = XPathFactory.instance().compile("./mycorederivate/derivate/fileset",
            Filters.element());

    Element result = filesetPath.evaluateFirst(this.createXML());
    if (result == null) {
        return fileUrnMap;
    }
    String urn = result.getAttributeValue("urn");

    if (urn != null) {
        XPathExpression<Element> filePath = XPathFactory.instance()
                .compile("./mycorederivate/derivate/fileset[@urn='" + urn + "']/file", Filters.element());
        List<Element> files = filePath.evaluate(this.createXML());

        for (Element currentFileElement : files) {
            String currentUrn = currentFileElement.getChildText("urn");
            String currentFile = currentFileElement.getAttributeValue("name");
            fileUrnMap.put(currentFile, currentUrn);
        }
    }
    return fileUrnMap;
}

From source file:org.mycore.datamodel.metadata.MCRFileMetadata.java

License:Open Source License

public MCRFileMetadata(Element file) {
    this.name = file.getAttributeValue("name");
    this.urn = file.getChildText("urn");
    this.handle = file.getChildText("handle");

    List<Element> categoryElements = file.getChildren("category");
    this.categories = Collections.emptySet();
    if (!categoryElements.isEmpty()) {
        categories = new ArrayList<MCRCategoryID>(categoryElements.size());
        for (Element categElement : categoryElements) {
            MCRCategoryID categId = MCRCategoryID.fromString(categElement.getAttributeValue("id"));
            categories.add(categId);//from   ww w .j  a v  a  2  s  .co m
        }
    }
}

From source file:org.mycore.restapi.v1.utils.MCRRestAPIObjectsHelper.java

License:Open Source License

private static Element listDerivateContent(MCRObject mcrObj, MCRDerivate derObj, String deriPath, UriInfo info)
        throws IOException {
    Element eContents = new Element("contents");
    eContents.setAttribute("mycoreobject", mcrObj.getId().toString());
    eContents.setAttribute("derivate", derObj.getId().toString());
    if (!deriPath.endsWith("/")) {
        deriPath += "/";
    }/*from w ww  .  j av  a  2 s  .com*/
    MCRPath p = MCRPath.getPath(derObj.getId().toString(), deriPath);
    if (p != null) {
        eContents.addContent(MCRPathXML.getDirectoryXML(p).getRootElement().detach());
    }

    String baseURL = MCRJerseyUtil.getBaseURL(info)
            + MCRConfiguration.instance().getString("MCR.RestAPI.v1.Files.URL.path");
    baseURL = baseURL.replace("${mcrid}", mcrObj.getId().toString()).replace("${derid}",
            derObj.getId().toString());
    XPathExpression<Element> xp = XPathFactory.instance().compile(".//child[@type='file']", Filters.element());
    for (Element e : xp.evaluate(eContents)) {
        String uri = e.getChildText("uri");
        if (uri != null) {
            int pos = uri.lastIndexOf(":/");
            String path = uri.substring(pos + 2);
            while (path.startsWith("/")) {
                path = path.substring(1);
            }
            e.setAttribute("href", baseURL + path);
        }
    }
    return eContents;
}

From source file:org.mycore.user2.MCRUserServlet.java

License:Open Source License

/**
 * Handles MCRUserServlet?action=save&id={userID}.
 * This is called by user-editor.xml editor form to save the
 * changed user data from editor submission. Redirects to
 * show user data afterwards. //w  w  w .  j av a 2s  .com
 */
private void saveUser(HttpServletRequest req, HttpServletResponse res) throws Exception {
    MCRUser currentUser = MCRUserManager.getCurrentUser();
    if (!checkUserIsNotNull(res, currentUser, null)) {
        return;
    }
    boolean hasAdminPermission = MCRAccessManager.checkPermission(MCRUser2Constants.USER_ADMIN_PERMISSION);
    boolean allowed = hasAdminPermission
            || MCRAccessManager.checkPermission(MCRUser2Constants.USER_CREATE_PERMISSION);
    if (!allowed) {
        String msg = MCRTranslation.translate("component.user2.UserServlet.noCreatePermission");
        res.sendError(HttpServletResponse.SC_FORBIDDEN, msg);
        return;
    }

    Document doc = (Document) (req.getAttribute("MCRXEditorSubmission"));
    Element u = doc.getRootElement();
    String userName = u.getAttributeValue("name");

    String realmID = MCRRealmFactory.getLocalRealm().getID();
    if (hasAdminPermission) {
        realmID = u.getAttributeValue("realm");
    }

    MCRUser user;
    boolean userExists = MCRUserManager.exists(userName, realmID);
    if (!userExists) {
        user = new MCRUser(userName, realmID);
        LOGGER.info("create new user " + userName + " " + realmID);

        // For new local users, set password
        String pwd = u.getChildText("password");
        if ((pwd != null) && (pwd.trim().length() > 0)
                && user.getRealm().equals(MCRRealmFactory.getLocalRealm())) {
            MCRUserManager.updatePasswordHashToSHA256(user, pwd);
        }
    } else {
        user = MCRUserManager.getUser(userName, realmID);
        if (!(hasAdminPermission || currentUser.equals(user) || currentUser.equals(user.getOwner()))) {
            res.sendError(HttpServletResponse.SC_FORBIDDEN);
            return;
        }
    }

    XPathExpression<Attribute> hintPath = XPathFactory.instance().compile("password/@hint",
            Filters.attribute());
    Attribute hintAttr = hintPath.evaluateFirst(u);
    String hint = hintAttr == null ? null : hintAttr.getValue();
    if ((hint != null) && (hint.trim().length() == 0)) {
        hint = null;
    }
    user.setHint(hint);

    updateBasicUserInfo(u, user);

    if (hasAdminPermission) {
        boolean locked = "true".equals(u.getAttributeValue("locked"));
        user.setLocked(locked);

        boolean disabled = "true".equals(u.getAttributeValue("disabled"));
        user.setDisabled(disabled);

        Element o = u.getChild("owner");
        if (o != null && !o.getAttributes().isEmpty()) {
            String ownerName = o.getAttributeValue("name");
            String ownerRealm = o.getAttributeValue("realm");
            MCRUser owner = MCRUserManager.getUser(ownerName, ownerRealm);
            if (!checkUserIsNotNull(res, owner, ownerName + "@" + ownerRealm)) {
                return;
            }
            user.setOwner(owner);
        } else {
            user.setOwner(null);
        }
        String validUntilText = u.getChildTextTrim("validUntil");
        if (validUntilText == null || validUntilText.length() == 0) {
            user.setValidUntil(null);
        } else {

            String dateInUTC = validUntilText;
            if (validUntilText.length() == 10) {
                dateInUTC = convertToUTC(validUntilText, "yyyy-MM-dd");
            }

            MCRISO8601Date date = new MCRISO8601Date(dateInUTC);
            user.setValidUntil(date.getDate());
        }
    } else { // save read user of creator
        user.setRealm(MCRRealmFactory.getLocalRealm());
        user.setOwner(currentUser);
    }
    Element gs = u.getChild("roles");
    if (gs != null) {
        user.getSystemRoleIDs().clear();
        user.getExternalRoleIDs().clear();
        List<Element> groupList = (List<Element>) gs.getChildren("role");
        for (Element group : groupList) {
            String groupName = group.getAttributeValue("name");
            if (hasAdminPermission || currentUser.isUserInRole(groupName)) {
                user.assignRole(groupName);
            } else {
                LOGGER.warn("Current user " + currentUser.getUserID()
                        + " has not the permission to add user to group " + groupName);
            }
        }
    }

    if (userExists) {
        MCRUserManager.updateUser(user);
    } else {
        MCRUserManager.createUser(user);
    }

    res.sendRedirect(res.encodeRedirectURL(
            "MCRUserServlet?action=show&id=" + URLEncoder.encode(user.getUserID(), "UTF-8")));
}

From source file:org.mycore.user2.MCRUserServlet.java

License:Open Source License

private void updateBasicUserInfo(Element u, MCRUser user) {
    String name = u.getChildText("realName");
    if ((name != null) && (name.trim().length() == 0)) {
        name = null;//from   w  w w  . j av a 2 s  . co  m
    }
    user.setRealName(name);

    String eMail = u.getChildText("eMail");
    if ((eMail != null) && (eMail.trim().length() == 0)) {
        eMail = null;
    }
    user.setEMail(eMail);

    Element attributes = u.getChild("attributes");
    if (attributes != null) {
        List<Element> attributeList = attributes.getChildren("attribute");
        user.getAttributes().clear();
        for (Element attribute : attributeList) {
            String key = attribute.getAttributeValue("name");
            String value = attribute.getAttributeValue("value");
            user.getAttributes().put(key, value);
        }
    }
}

From source file:org.rometools.feed.module.photocast.io.Parser.java

License:Open Source License

public Module parse(Element element) {
    if (element.getName().equals("channel") || element.getName().equals("feed")) {
        return new PhotocastModuleImpl();
    } else if (element.getChild("metadata", Parser.NS) == null && element.getChild("image", Parser.NS) == null)
        return null;
    PhotocastModule pm = new PhotocastModuleImpl();
    List children = element.getChildren();
    Iterator it = children.iterator();
    while (it.hasNext()) {
        Element e = (Element) it.next();
        if (!e.getNamespace().equals(Parser.NS))
            continue;
        if (e.getName().equals("photoDate")) {
            try {
                pm.setPhotoDate(Parser.PHOTO_DATE_FORMAT.parse(e.getText()));
            } catch (Exception ex) {
                LOG.warning("Unable to parse photoDate: " + e.getText() + " " + ex.toString());
            }/* w w  w . ja  v a 2 s.co m*/
        } else if (e.getName().equals("cropDate")) {
            try {
                pm.setCropDate(Parser.CROP_DATE_FORMAT.parse(e.getText()));
            } catch (Exception ex) {
                LOG.warning("Unable to parse cropDate: " + e.getText() + " " + ex.toString());
            }
        } else if (e.getName().equals("thumbnail")) {
            try {
                pm.setThumbnailUrl(new URL(e.getText()));
            } catch (Exception ex) {
                LOG.warning("Unable to parse thumnail: " + e.getText() + " " + ex.toString());
            }
        } else if (e.getName().equals("image")) {
            try {
                pm.setImageUrl(new URL(e.getText()));
            } catch (Exception ex) {
                LOG.warning("Unable to parse image: " + e.getText() + " " + ex.toString());
            }
        } else if (e.getName().equals("metadata")) {
            String comments = "";
            PhotoDate photoDate = null;
            if (e.getChildText("PhotoDate") != null) {
                try {
                    photoDate = new PhotoDate(Double.parseDouble(e.getChildText("PhotoDate")));
                } catch (Exception ex) {
                    LOG.warning("Unable to parse PhotoDate: " + e.getText() + " " + ex.toString());
                }
            }
            if (e.getChildText("Comments") != null) {
                comments = e.getChildText("Comments");
            }
            pm.setMetadata(new Metadata(photoDate, comments));
        }
    }
    return pm;
}

From source file:org.t3.metamediamanager.TheTvdbProvider.java

License:Apache License

/**
 * Download and parse banners.xml/*w  ww  .ja v  a 2s .c o  m*/
 * Map key : banner type (season, fanart, series...)
 * Map value : vector of urls
 * @return map
 * @throws ProviderException 
 */
public HashMap<String, String[]> bannersInfo(String seriesId) throws ProviderException {
    class BannerInfo implements Comparable<BannerInfo> {
        String url;
        double rating;

        @Override
        public int compareTo(BannerInfo o) {
            return (int) (rating - ((BannerInfo) o).rating);
        }
    }

    HashMap<String, List<BannerInfo>> res = new HashMap<String, List<BannerInfo>>();

    Document doc = downloadXml("http://thetvdb.com/api/" + apiKey + "/series/" + seriesId + "/banners.xml");

    Element root = doc.getRootElement();

    List<Element> banners = root.getChildren();

    for (Element bannerElem : banners) {

        String type = bannerElem.getChildText("BannerType");
        String url = bannerElem.getChildText("BannerPath");

        String rating = (bannerElem.getChildText("Rating").isEmpty()) ? "0" : bannerElem.getChildText("Rating");

        if (!res.containsKey(type))
            res.put(type, new ArrayList<BannerInfo>());
        BannerInfo bi = new BannerInfo();
        bi.url = url;
        bi.rating = Double.parseDouble(rating);
        res.get(type).add(bi);
    }

    HashMap<String, String[]> bannersMap = new HashMap<String, String[]>();

    //We sort banners info and limit 5 banners by type
    for (Entry<String, List<BannerInfo>> entry : res.entrySet()) {
        Collections.sort(entry.getValue(), Collections.reverseOrder());

        int size = (entry.getValue().size() > 10) ? 10 : entry.getValue().size();
        bannersMap.put(entry.getKey(), new String[size]);
        for (int i = 0; i < size; i++) {
            bannersMap.get(entry.getKey())[i] = entry.getValue().get(i).url;
        }
    }

    return bannersMap;
}

From source file:org.xwiki.contrib.jira.macro.internal.displayer.field.KeyJIRAFieldDisplayer.java

License:Open Source License

@Override
public List<Block> displayField(JIRAField field, Element issue, JIRAMacroParameters parameters) {
    List<Block> result = Collections.emptyList();
    String key = issue.getChildText(JIRAField.KEY.getId());
    if (key != null) {
        String link = issue.getChildText(JIRAField.LINK.getId());
        List<Block> labelBlocks = Arrays.<Block>asList(new VerbatimBlock(key, true));

        // If the Issue is closed then display it striked-out
        String resolutionId = issue.getChild(JIRAField.RESOLUTION.getId()).getAttributeValue("id");
        if (!"-1".equals(resolutionId)) {
            // The issue is resolved
            labelBlocks = Arrays.<Block>asList(new FormatBlock(labelBlocks, Format.STRIKEDOUT));
        }/* ww  w .  j  a v  a 2  s  . c  om*/

        if (link != null) {
            ResourceReference reference = new ResourceReference(link, ResourceType.URL);
            result = Arrays.<Block>asList(new LinkBlock(labelBlocks, reference, true));
        } else {
            result = labelBlocks;
        }
    }
    return result;
}