Example usage for org.jdom2 Element getAttributes

List of usage examples for org.jdom2 Element getAttributes

Introduction

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

Prototype

public List<Attribute> getAttributes() 

Source Link

Document

This returns the complete set of attributes for this element, as a List of Attribute objects in no particular order, or an empty list if there are none.

Usage

From source file:org.mycore.access.mcrimpl.MCRAccessControlSystem.java

License:Open Source License

/**
 * method, that normalizes the jdom-representation of a mycore access condition
 *
 * @param rule//  w ww. j  a  va  2s  .c  o  m
 *            condition-JDOM of an access-rule
 * @return the normalized JDOM-Rule
 */
public Element normalize(Element rule) {
    Element newRule = new Element(rule.getName());
    rule.getAttributes().stream().map(Attribute::clone).forEach(newRule::setAttribute);
    rule.getChildren().stream().map(Element::clone).map(this::normalize)
            .sorted(MCRAccessControlSystem::compareAccessConditions).forEachOrdered(newRule::addContent);
    return newRule;
}

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

License:Open Source License

/**
 * This method adds MCRMetaElement's from a given MCRObjectMetadata to
 * this data set if there are any differences between the data sets.
 * /*from   w  ww.  j av  a  2 s . c  o  m*/
 * @param input
 *            the MCRObjectMetadata, that should merged into this data set
 *            
 * @deprecated use {@link MCRObjectMerger#mergeMetadata(MCRObject, boolean)} instead
 */
public final void mergeMetadata(MCRObjectMetadata input) {

    for (MCRMetaElement metaElement : input) {
        int pos = -1;
        for (int j = 0; j < size(); j++) {
            if (meta_list.get(j).getTag().equals(metaElement.getTag())) {
                pos = j;
            }
        }
        if (pos != -1) {
            for (int j = 0; j < metaElement.size(); j++) {
                boolean found = false;
                for (MCRMetaInterface mcrMetaInterface : meta_list.get(pos)) {
                    Element xml = mcrMetaInterface.createXML();
                    Element xmlNEW = metaElement.getElement(j).createXML();
                    List<Element> childrenXML = xml.getChildren();
                    if (childrenXML.size() > 0 && xmlNEW.getChildren().size() > 0) {
                        int i = 0;
                        for (Element element : childrenXML) {
                            Element elementNew = xmlNEW.getChild(element.getName());

                            if (elementNew != null && element != null) {
                                if (element.getText().equals(elementNew.getText())) {
                                    i++;
                                }
                            }
                        }
                        if (i == childrenXML.size()) {
                            found = true;
                        }
                    } else {
                        if (xml.getText().equals(xmlNEW.getText())) {
                            found = true;
                        } else if (!found) {
                            int i = 0;
                            List<Attribute> attributes = xml.getAttributes();
                            for (Attribute attribute : attributes) {
                                Attribute attr = xmlNEW.getAttribute(attribute.getName());
                                if ((attr != null) && attr.equals(attribute)) {
                                    i++;
                                }
                            }
                            if (i == attributes.size()) {
                                found = true;
                            }

                        }
                    }
                }
                MCRMetaInterface obj = metaElement.getElement(j);
                if (!found) {
                    meta_list.get(pos).addMetaObject(obj);
                } else if (LOGGER.isDebugEnabled()) {
                    LOGGER.debug("Found equal tags: \n\r"
                            + new XMLOutputter(Format.getPrettyFormat()).outputString(obj.createXML()));
                }
            }
        } else {
            meta_list.add(metaElement);
        }
    }
}

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

License:Open Source License

private void setVariablesFromXML(String prefix, Element element, Hashtable predecessors) {
    String key = getNamespacePrefix(element.getNamespace()) + element.getName();

    setVariablesFromXML(prefix, key, element, predecessors);

    List attributes = element.getAttributes();
    for (Object attribute1 : attributes) {
        Attribute attribute = (Attribute) attribute1;
        String name = getNamespacePrefix(attribute.getNamespace()) + attribute.getName();
        String value = attribute.getValue().replace(BLANK, BLANK_ESCAPED).replace(SLASH, SLASH_ESCAPED);
        if (value == null || value.length() == 0) {
            continue;
        }/*from   www  .j  a v a2s.  c o  m*/
        key = getNamespacePrefix(element.getNamespace()) + element.getName() + ATTR_SEP + name + ATTR_SEP
                + value;
        if (predicates.containsKey(key)) {
            setVariablesFromXML(prefix, key, element, predecessors);
        }
    }
}

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

License:Open Source License

private void setVariablesFromXML(String prefix, String key, Element element, Hashtable predecessors) {
    int pos = 1;/*w w  w . j a  v  a 2s. c  o m*/
    if (predecessors.containsKey(key)) {
        pos = (Integer) predecessors.get(key) + 1;
    }
    predecessors.put(key, pos);

    String path = prefix + "/" + key;
    if (pos > 1) {
        path = path + "[" + pos + "]";
    }

    // Add element text
    addVariable(path, element.getText());

    // Add value of all attributes
    List attributes = element.getAttributes();
    for (Object attribute1 : attributes) {
        Attribute attribute = (Attribute) attribute1;
        String value = attribute.getValue();
        if (value != null && value.length() > 0) {
            addVariable(path + "/@" + getNamespacePrefix(attribute.getNamespace()) + attribute.getName(),
                    value);
        }
    }

    // Add values of all children
    predecessors = new Hashtable();
    List children = element.getChildren();
    for (Object aChildren : children) {
        Element child = (Element) aChildren;
        setVariablesFromXML(path, child, predecessors);
    }
}

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

License:Open Source License

private void setValidatorProperties(MCRValidator validator, Element condition) {
    for (Attribute attribute : (List<Attribute>) (condition.getAttributes())) {
        if (!attribute.getValue().isEmpty())
            validator.setProperty(attribute.getName(), attribute.getValue());
    }//from  www.j  a v  a2 s . c o  m
}

From source file:org.mycore.mir.wizard.command.MIRWizardMCRCommand.java

License:Open Source License

@Override
public void doExecute() {
    Session currentSession = MCRHIBConnection.instance().getSession();

    try {/*from  w  w w . j  a  va2  s . c om*/
        for (Element command : getInputXML().getChildren()) {
            String cmd = command.getTextTrim();
            cmd = cmd.replaceAll("\n", "").replaceAll("\r", "").replaceAll("  ", " ");
            cmd = cmd.replaceAll("  ", " ");

            for (Attribute attr : command.getAttributes()) {
                if (attr.getValue().startsWith("resource:")) {
                    File tmpFile = File.createTempFile("resfile", ".xml");
                    MCRContent source = new MCRJDOMContent(MCRURIResolver.instance().resolve(attr.getValue()));
                    source.sendTo(tmpFile);

                    cmd = cmd.replace("{" + attr.getName() + "}", tmpFile.getAbsolutePath());
                } else {
                    cmd = cmd.replace("{" + attr.getName() + "}", attr.getValue());
                }
            }

            MCRCommandManager mcrCmdMgr = new MCRCommandManager();

            Transaction tx = currentSession.beginTransaction();
            try {
                mcrCmdMgr.invokeCommand(cmd);
                tx.commit();
            } catch (HibernateException e) {
                tx.rollback();

                this.result.setResult(result + e.toString());
                this.result.setSuccess(false);
                return;
            } catch (InvocationTargetException e) {
                e.printStackTrace();
                this.result.setResult(result + e.toString());
                this.result.setSuccess(false);
                return;
            }

        }

        this.result.setSuccess(true);
    } catch (Exception ex) {
        ex.printStackTrace();
        this.result.setResult(ex.toString());
        this.result.setSuccess(false);
    }
}

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  .ja v a  2s .co 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.olanto.myterm.extractor.model.posfix.LoadModelPosfix.java

License:Open Source License

static String getExtraElement(Element e) {
    StringBuilder collect = new StringBuilder();
    boolean attributeverbose = false;
    collect.append("<" + e.getName());
    List<Attribute> attlist = e.getAttributes();
    Iterator i = attlist.iterator();
    while (i.hasNext()) {
        Attribute att = (Attribute) i.next();
        String av = att.getName() + "=\"" + getAtt(e, att.getName(), noNS, attributeverbose) + "\"";
        collect.append(" " + av);
        //System.out.println(av);
    }/*  www  .  j  av  a2s. c  om*/
    collect.append(">");
    List listNode = e.getChildren();
    i = listNode.iterator();
    while (i.hasNext()) {
        Element info = (Element) i.next();
        collect.append("\n");
        collect.append(getExtraElement(info));
    }
    //System.out.println(e.getTextTrim());
    collect.append(e.getTextNormalize());
    collect.append("</" + e.getName() + ">");
    String res = collect.toString();
    res = res.replace("><", ">\n<");
    res = res.replace("  ", " ");
    //System.out.println(res);      
    return res;
}

From source file:org.openconcerto.xml.JDOM2Utils.java

License:Open Source License

static String getDiff(Element elem1, Element elem2, final boolean normalizeText) {
    if (elem1 == elem2)
        return null;
    if (!equals(elem1, elem2))
        return "element name or namespace";

    // ignore attributes order
    final List<Attribute> attr1 = elem1.getAttributes();
    final List<Attribute> attr2 = elem2.getAttributes();
    if (attr1.size() != attr2.size())
        return "attributes count";
    for (final Attribute attr : attr1) {
        if (!attr.getValue().equals(elem2.getAttributeValue(attr.getName(), attr.getNamespace())))
            return "attribute value";
    }/*from   www  . jav  a 2 s. co m*/

    // use content order
    final IPredicate<Content> filter = new IPredicate<Content>() {
        @Override
        public boolean evaluateChecked(Content input) {
            return input instanceof Text || input instanceof Element;
        }
    };
    // only check Element and Text (also merge them)
    final Iterator<Content> contents1 = getContent(elem1, filter, true);
    final Iterator<Content> contents2 = getContent(elem2, filter, true);
    while (contents1.hasNext() && contents2.hasNext()) {
        final Content content1 = contents1.next();
        final Content content2 = contents2.next();
        if (content1.getClass() != content2.getClass())
            return "content";
        if (content1 instanceof Text) {
            final String s1 = normalizeText ? ((Text) content1).getTextNormalize() : content1.getValue();
            final String s2 = normalizeText ? ((Text) content2).getTextNormalize() : content2.getValue();
            if (!s1.equals(s2))
                return "text";
        } else {
            final String rec = getDiff((Element) content1, (Element) content2, normalizeText);
            if (rec != null)
                return rec;
        }
    }
    if (contents1.hasNext() || contents2.hasNext())
        return "content size";

    return null;
}

From source file:org.openflexo.foundation.fml.rm.ViewPointResourceImpl.java

License:Open Source License

private static ViewPointInfo findViewPointInfo(InputStream inputStream) {
    Document document;//from  w w  w. ja  v a 2s .  c om
    try {
        document = readXMLInputStream(inputStream);
        Element root = getElement(document, "ViewPoint");
        if (root != null) {
            ViewPointInfo returned = new ViewPointInfo();
            Iterator<Attribute> it = root.getAttributes().iterator();
            while (it.hasNext()) {
                Attribute at = it.next();
                if (at.getName().equals("uri")) {
                    logger.fine("Returned " + at.getValue());
                    returned.uri = at.getValue();
                } else if (at.getName().equals("name")) {
                    logger.fine("Returned " + at.getValue());
                    returned.name = at.getValue();
                } else if (at.getName().equals("version")) {
                    logger.fine("Returned " + at.getValue());
                    returned.version = at.getValue();
                } else if (at.getName().equals("modelVersion")) {
                    logger.fine("Returned " + at.getValue());
                    returned.modelVersion = at.getValue();
                }
            }
            if (StringUtils.isEmpty(returned.name)) {
                if (StringUtils.isNotEmpty(returned.uri)) {
                    if (returned.uri.indexOf("/") > -1) {
                        returned.name = returned.uri.substring(returned.uri.lastIndexOf("/") + 1);
                    } else if (returned.uri.indexOf("\\") > -1) {
                        returned.name = returned.uri.substring(returned.uri.lastIndexOf("\\") + 1);
                    } else {
                        returned.name = returned.uri;
                    }
                }
            }
            return returned;

        }
    } catch (JDOMException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    logger.fine("Returned null");
    return null;
}