Example usage for org.jdom2 Element getChildTextTrim

List of usage examples for org.jdom2 Element getChildTextTrim

Introduction

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

Prototype

public String getChildTextTrim(final String cname) 

Source Link

Document

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

Usage

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

License:Open Source License

/**
 * This method reads the XML input stream part from a DOM part for the
 * metadata of the document.//from   w ww.  ja va2s  . c o m
 * 
 * @param element
 *            a relevant DOM element for the metadata
 */
@Override
public final void setFromDOM(org.jdom2.Element element) {
    super.setFromDOM(element);
    fullname = element.getChildTextTrim("fullname");

    if (fullname == null) {
        fullname = "";
    }

    nickname = element.getChildTextTrim("nickname");

    if (nickname == null) {
        nickname = "";
    }

    property = element.getChildTextTrim("property");

    if (property == null) {
        property = "";
    }
}

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

License:Open Source License

/**
 * This method reads the XML input stream part from a DOM part for the
 * metadata of the document.//from   w w  w.j  a v  a  2 s.c o  m
 * 
 * @param element
 *            a relevant JDOM element for the metadata
 */
@Override
public final void setFromDOM(org.jdom2.Element element) {
    super.setFromDOM(element);
    setFirstName(element.getChildTextTrim("firstname"));
    setCallName(element.getChildTextTrim("callname"));
    setSurName(element.getChildTextTrim("surname"));
    setFullName(element.getChildTextTrim("fullname"));
    setAcademic(element.getChildTextTrim("academic"));
    setPeerage(element.getChildTextTrim("peerage"));
    setNumeration(element.getChildTextTrim("numeration"));
    setTitle(element.getChildTextTrim("title"));
    setPrefix(element.getChildTextTrim("prefix"));
    setAffix(element.getChildTextTrim("affix"));
}

From source file:org.mycore.frontend.basket.MCRBasketXMLParser.java

License:Open Source License

/**
 * Parses an XML element that represents a basket entry.
 *///w w w. j  a va2s . c o m
public MCRBasketEntry parseXML(Element xml) {
    String id = xml.getAttributeValue("id");
    String uri = xml.getAttributeValue("uri");
    MCRBasketEntry entry = new MCRBasketEntry(id, uri);

    String comment = xml.getChildTextTrim("comment");
    if (comment != null)
        entry.setComment(comment);

    return entry;
}

From source file:org.mycore.frontend.editor.MCREditorSubmission.java

License:Open Source License

private void setVariablesFromSubmission(MCRRequestParameters parms, Element editor) {
    for (Enumeration e = parms.getParameterNames(); e.hasMoreElements();) {
        String name = (String) e.nextElement();

        if (name.startsWith("_")) {
            continue; // Skip internal request params
        }// www.  j av  a 2s .co m

        String[] values = parms.getParameterValues(name);
        String sortNr = parms.getParameter("_sortnr-" + name);
        String ID = parms.getParameter("_id@" + name);

        // Skip files that should be deleted
        String delete = parms.getParameter("_delete-" + name);

        if ("true".equals(delete) && parms.getFileItem(name) == null) {
            continue;
        }

        // Skip request params that are not input but target params
        if (sortNr == null) {
            continue;
        }

        // For each value
        for (int k = 0; values != null && k < values.length; k++) {
            String value = values[k];

            if (value == null || value.trim().length() == 0) {
                continue;
            }

            // Handle multiple variables with same name: checkboxes & select
            // multiple
            String nname = k == 0 ? name : name + "[" + (k + 1) + "]";

            MCREditorVariable var = new MCREditorVariable(nname, value);
            var.setSortNr(sortNr);

            // Add associated component from editor definition
            if (ID != null && ID.trim().length() > 0) {
                Element component = MCREditorDefReader.findElementByID(ID, editor);

                if (component != null) {
                    // Skip variables with values equal to autofill text
                    String attrib = component.getAttributeValue("autofill");
                    String elem = component.getChildTextTrim("autofill");
                    String autofill = null;

                    if (attrib != null && attrib.trim().length() > 0) {
                        autofill = attrib.trim();
                    } else if (attrib != null && attrib.trim().length() > 0) {
                        autofill = elem.trim();
                    }

                    if (value.trim().equals(autofill)) {
                        continue;
                    }
                }
            }

            variables.add(var);

            FileItem file = parms.getFileItem(name);

            if (file != null) // Add associated uploaded file if it exists
            {
                var.setFile(file);
                files.add(file);
            }
        }
    }
}

From source file:org.mycore.frontend.editor.MCREditorSubmission.java

License:Open Source License

private void validate(MCRRequestParameters parms, Element editor) {
    LOGGER.info("Validating editor input... ");

    for (Enumeration e = parms.getParameterNames(); e.hasMoreElements();) {
        String name = (String) e.nextElement();

        if (!name.startsWith("_sortnr-")) {
            continue;
        }/*from  w  w w  . jav  a 2  s.  c o m*/

        name = name.substring(8);

        String ID = parms.getParameter("_id@" + name);

        if (ID == null || ID.trim().length() == 0) {
            continue;
        }

        String[] values = { "" };

        if (parms.getParameterValues(name) != null) {
            values = parms.getParameterValues(name);
        }

        Element component = MCREditorDefReader.findElementByID(ID, editor);

        if (component == null) {
            continue;
        }

        List conditions = component.getChildren("condition");

        if (conditions == null) {
            continue;
        }

        // Skip variables with values equal to autofill text
        String attrib = component.getAttributeValue("autofill");
        String elem = component.getChildTextTrim("autofill");
        String autofill = null;

        if (attrib != null && attrib.trim().length() > 0) {
            autofill = attrib.trim();
        } else if (attrib != null && attrib.trim().length() > 0) {
            autofill = elem.trim();
        }

        if (values[0].trim().equals(autofill)) {
            values[0] = "";
        }

        for (Object condition1 : conditions) {
            Element condition = (Element) condition1;

            boolean ok = true;
            for (int j = 0; j < values.length && ok; j++) {
                String nname = j == 0 ? name : name + "[" + (j + 1) + "]";
                ok = checkCondition(condition, nname, values[j]);

                if (!ok) {
                    String sortNr = parms.getParameter("_sortnr-" + name);
                    failed.put(sortNr, condition);

                    if (LOGGER.isDebugEnabled()) {
                        String cond = new XMLOutputter(Format.getCompactFormat()).outputString(condition);
                        LOGGER.debug("Validation condition failed:");
                        LOGGER.debug(nname + " = \"" + values[j] + "\"");
                        LOGGER.debug(cond);
                    }
                }
            }
        }
    }

    for (Enumeration e = parms.getParameterNames(); e.hasMoreElements();) {
        String name = (String) e.nextElement();

        if (!name.startsWith("_cond-")) {
            continue;
        }

        String path = name.substring(6);
        String[] ids = parms.getParameterValues(name);

        if (ids != null) {
            for (String id : ids) {
                Element condition = MCREditorDefReader.findElementByID(id, editor);

                if (condition == null) {
                    continue;
                }

                String field1 = condition.getAttributeValue("field1", "");
                String field2 = condition.getAttributeValue("field2", "");

                if (!field1.isEmpty() || !field2.isEmpty()) {
                    String pathA = path + ((!field1.isEmpty() && !field1.equals(".")) ? "/" + field1 : "");
                    String pathB = path + ((!field2.isEmpty() && !field2.equals(".")) ? "/" + field2 : "");

                    String valueA = parms.getParameter(pathA);
                    String valueB = parms.getParameter(pathB);

                    String sortNrA = parms.getParameter("_sortnr-" + pathA);
                    String sortNrB = parms.getParameter("_sortnr-" + pathB);

                    boolean pairValuesAlreadyInvalid = (failed.containsKey(sortNrA)
                            || failed.containsKey(sortNrB));

                    if (!pairValuesAlreadyInvalid) {
                        MCRValidator validator = MCRValidatorBuilder.buildPredefinedCombinedPairValidator();
                        setValidatorProperties(validator, condition);
                        if (!validator.isValid(valueA, valueB)) {
                            failed.put(sortNrA, condition);
                            failed.put(sortNrB, condition);
                        }
                    }
                } else {
                    XPathExpression<Element> xpath = XPathFactory.instance().compile(path, Filters.element(),
                            null, getNamespaceMap().values());
                    Element current = xpath.evaluateFirst(getXML());
                    if (current == null) {
                        LOGGER.debug("Could not validate, because no element found at xpath " + path);
                        continue;
                    }

                    MCRValidator validator = MCRValidatorBuilder.buildPredefinedCombinedElementValidator();
                    setValidatorProperties(validator, condition);
                    if (!validator.isValid(current)) {
                        String sortNr = parms.getParameter("_sortnr-" + path);
                        failed.put(sortNr, condition);
                    }
                }
            }
        }
    }
}

From source file:org.mycore.media.MCRMediaObject.java

License:Open Source License

protected static String getXMLValue(Element xml, String tagName, String defaultValue) {
    String ret = defaultValue;/*from w w w. ja va 2  s  .c  o m*/
    if (tagName != null) {
        tagName = (tagName.startsWith("/") ? tagName.substring(1) : tagName);

        StringTokenizer st = new StringTokenizer(tagName, "/");
        if (st.hasMoreTokens() && st.countTokens() > 1) {
            String tagPart = st.nextToken().trim();

            Element elm = xml.getChild(tagPart);
            if (elm != null)
                ret = getXMLValue(elm, tagName.replace(tagPart, ""), defaultValue);
        } else if (tagName.startsWith("@")) {
            ret = (xml.getAttributeValue(tagName.substring(1)) != null
                    ? xml.getAttributeValue(tagName.substring(1))
                    : defaultValue);
        } else {
            ret = xml.getChildTextTrim(tagName);
            if (ret == null || ret.length() == 0)
                ret = defaultValue;
        }
    }

    return ret;
}

From source file:org.mycore.mir.wizard.MIRWizardServlet.java

License:Open Source License

public void doGetPost(final MCRServletJob job) throws Exception {
    final HttpServletRequest req = job.getRequest();
    final HttpServletResponse res = job.getResponse();

    final String path = req.getPathInfo();

    if (path != null) {
        final StringTokenizer st = new StringTokenizer(path, "/");
        final String request = st.nextToken();

        if ("shutdown".equals(request)) {
            LOGGER.info("Shutdown System....");
            MCRConfiguration.instance().set("MCR.LayoutTransformerFactory.Default.Stylesheets", "");
            MCRConfiguration.instance().set("MCR.Startup.Class", "%MCR.Startup.Class%");
            System.exit(0);//  www . j a  v a2 s.c om
        } else {
            LOGGER.info("Request file \"" + request + "\"...");
            getLayoutService().doLayout(job.getRequest(), job.getResponse(),
                    new MCRJDOMContent(MCRURIResolver.instance().resolve("resource:setup/" + request)));
        }
    } else {
        final Document doc = (Document) (job.getRequest().getAttribute("MCRXEditorSubmission"));
        final Element wizXML = doc.getRootElement();

        LOGGER.debug(new XMLOutputter().outputString(wizXML));

        final Element resXML = new Element("wizard");

        if (!MIRWizardRequestFilter.isAuthenticated(req)) {
            final String loginToken = wizXML.getChildTextTrim("login");
            String url = "wizard";

            if (loginToken != null && MIRWizardRequestFilter.getLoginToken(req).equals(loginToken)) {
                LOGGER.info("Authenticate with token \"" + loginToken + "\"...");
                MCRSessionMgr.getCurrentSession().put(MIRWizardStartupHandler.LOGIN_TOKEN, loginToken);
                MCRSessionMgr.getCurrentSession().put("ServerBaseURL",
                        req.getScheme() + "://" + req.getServerName() + ":" + req.getServerPort());
            } else {
                LOGGER.info("Redirect to login...");
                url += "/?action=login"
                        + (!MIRWizardRequestFilter.getLoginToken(req).equals(loginToken) ? "&token=invalid"
                                : "");

                // output login token again
                MIRWizardStartupHandler.outputLoginToken(req.getServletContext());
            }
            res.sendRedirect(res.encodeRedirectURL(MCRFrontendUtil.getBaseURL() + url));
            return;
        }

        final Element results = new Element("results");

        final Element commands = MCRURIResolver.instance().resolve("resource:setup/install.xml");

        final MIRWizardCommandChain chain = new MIRWizardCommandChain();

        for (Element command : commands.getChildren("command")) {
            final String cls = command.getAttributeValue("class");
            final String name = command.getAttributeValue("name");
            final String src = command.getAttributeValue("src");

            try {
                final Class<?> cmdCls = Class.forName(cls);
                MIRWizardCommand cmd = null;

                if (name != null) {
                    final Constructor<?> cmdC = cmdCls.getConstructor(String.class);
                    cmd = (MIRWizardCommand) cmdC.newInstance(name);
                } else {
                    final Constructor<?> cmdC = cmdCls.getConstructor();
                    cmd = (MIRWizardCommand) cmdC.newInstance();
                }

                if (src != null) {
                    cmd.setInputXML(MCRURIResolver.instance().resolve(src));
                }

                if (cmd != null) {
                    chain.addCommand(cmd);
                }
            } catch (final ClassNotFoundException | NoSuchMethodException | SecurityException
                    | InstantiationException | IllegalAccessException | IllegalArgumentException
                    | InvocationTargetException e) {
                LOGGER.error(e);
            }
        }

        initializeApplication(job);

        LOGGER.info("Execute Wizard Commands...");
        chain.execute(wizXML);
        LOGGER.info("done.");

        for (MIRWizardCommand cmd : chain.getCommands()) {
            if (cmd.getResult() != null)
                results.addContent(cmd.getResult().toElement());
        }

        results.setAttribute("success", Boolean.toString(chain.isSuccess()));

        resXML.addContent(results);

        getLayoutService().doLayout(job.getRequest(), job.getResponse(), new MCRJDOMContent(resXML));
    }
}

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

License:Open Source License

/**
 * /*from  ww  w. ja v  a 2s  .  c  o m*/
 */
private static void loadRealms() {
    Element root;
    try {
        root = getRealms().getRootElement();
    } catch (SAXException | JDOMException | TransformerException | IOException e) {
        throw new MCRException("Could not load realms from URI: " + realmsURI);
    }
    String localRealmID = root.getAttributeValue("local");
    /** Map of defined realms, key is the ID of the realm */
    HashMap<String, MCRRealm> realmsMap = new HashMap<String, MCRRealm>();

    HashMap<String, MCRUserAttributeMapper> attributeMapper = new HashMap<String, MCRUserAttributeMapper>();

    /** List of defined realms */
    List<MCRRealm> realmsList = new ArrayList<MCRRealm>();

    List<Element> realms = (List<Element>) (root.getChildren("realm"));
    for (Element child : realms) {
        String id = child.getAttributeValue("id");
        MCRRealm realm = new MCRRealm(id);

        List<Element> labels = (List<Element>) (child.getChildren("label"));
        for (Element label : labels) {
            String text = label.getTextTrim();
            String lang = label.getAttributeValue("lang", Namespace.XML_NAMESPACE);
            realm.setLabel(lang, text);
        }

        realm.setPasswordChangeURL(child.getChildTextTrim("passwordChangeURL"));
        Element login = child.getChild("login");
        if (login != null) {
            realm.setLoginURL(login.getAttributeValue("url"));
            realm.setRedirectParameter(login.getAttributeValue("redirectParameter"));
            realm.setRealmParameter(login.getAttributeValue("realmParameter"));
        }
        Element createElement = child.getChild("create");
        if (createElement != null) {
            realm.setCreateURL(createElement.getAttributeValue("url"));
        }

        attributeMapper.put(id, MCRUserAttributeMapper.instance(child));

        realmsMap.put(id, realm);
        realmsList.add(realm);
        if (localRealmID.equals(id)) {
            localRealm = realm;
        }
    }
    MCRRealmFactory.realmsDocument = root.getDocument();
    MCRRealmFactory.realmsMap = realmsMap;
    MCRRealmFactory.realmsList = realmsList;
    MCRRealmFactory.attributeMapper = attributeMapper;
}

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. /*from www .j av a  2  s.c  o m*/
 */
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.polago.deployconf.task.filter.FilterTask.java

License:Open Source License

/**
 * {@inheritDoc}//from   ww w  . ja  v  a  2s .c  om
 */
@Override
public void deserialize(Element root, ConfigGroupManager groupManager) throws IOException {
    super.deserialize(root, groupManager);
    String enc = root.getAttributeValue(ATTRIBUTE_ENCODING);
    if (enc != null) {
        encoding = enc;
    }
    for (Element e : root.getChildren()) {
        String name = e.getChildTextTrim(DOM_ELEMENT_NAME);
        if (name.length() == 0) {
            throw new IllegalStateException("Filter name element does not exists");
        }
        String regex = e.getChildTextTrim(DOM_ELEMENT_REGEX);
        if (regex.length() == 0) {
            throw new IllegalStateException("Filter regex element does not exists");
        }
        String description = e.getChildTextTrim(DOM_ELEMENT_DESCRIPTION);
        if (description.length() == 0) {
            throw new IllegalStateException("Filter description element does not exists");
        }
        String defaultValue = e.getChildTextTrim(DOM_ELEMENT_DEFAULT);

        String group = e.getAttributeValue(DOM_ATTRIBUTE_GROUP);
        String value = null;

        if (group != null) {
            value = groupManager.lookupGroup(group).getProperty(name);
        }

        if (value == null) {
            value = e.getChildTextTrim(DOM_ELEMENT_VALUE);
        }

        FilterToken t = new FilterToken(name, regex, description, defaultValue, value);

        if (group != null) {
            t.setGroup(group);
        }

        tokens.add(t);
    }
}