Example usage for org.dom4j Element remove

List of usage examples for org.dom4j Element remove

Introduction

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

Prototype

boolean remove(Text text);

Source Link

Document

Removes the given Text if the node is an immediate child of this element.

Usage

From source file:net.sf.jguard.ext.authentication.manager.XmlAuthenticationManager.java

License:Open Source License

public boolean deletePrincipal(Principal principal) throws AuthenticationException {
    Principal ppalReference = principals.remove(principal.getName());
    if (ppalReference == null) {
        return false;
    }// ww w  .  ja v a2 s .c  o  m
    principalsSet.remove(ppalReference);

    if (isRoleAndLocal(principal) && localPrincipalsSet.contains(principal)) {
        localPrincipalsSet.remove(principal);
        localPrincipals.remove(principal);
    }
    Element principalsElement = root.element("principals");
    Element principalElement = (Element) principalsElement
            .selectSingleNode("//principal[name='" + principal.getName() + "']");
    principalsElement.remove(principalElement);
    if (ppalReference.getClass().equals(RolePrincipal.class)) {
        //delete all the references of this principal
        XMLUtils.deletePrincipalRefs(root, (RolePrincipal) ppalReference);
    }
    try {
        XMLUtils.write(fileLocation, document);
    } catch (IOException e) {
        logger.error("deletePrincipal(String)", e);
        throw new AuthenticationException(e.getMessage(), e);
    }
    return true;

}

From source file:net.sf.jguard.ext.authentication.manager.XmlAuthenticationManager.java

License:Open Source License

public void updateOrganization(String organizationId, Organization organization)
        throws AuthenticationException {
    Element organizationElement = getOrganization(organizationId);
    if (organizationElement == null) {
        throw new IllegalArgumentException("organization cannot be updated : it doesn't exist ");
    }/*from   w  ww  .  j  a v a 2 s  . com*/

    //remove userTemplate
    Element userTemplate = organizationElement.element(XmlAuthenticationManager.USER_TEMPLATE);
    if (userTemplate != null) {
        organizationElement.remove(userTemplate);
    }

    //remove credentilasElement
    Element credentialsElement = organizationElement.element(XmlAuthenticationManager.CREDENTIALS);
    organizationElement.remove(credentialsElement);

    Element oldPrincipalsRefElement = organizationElement.element(XmlAuthenticationManager.PRINCIPALS_REF);
    organizationElement.remove(oldPrincipalsRefElement);
    persistOrganization(organization, organizationElement);
}

From source file:net.sf.jguard.ext.authentication.manager.XmlAuthenticationManager.java

License:Open Source License

public void setOrganizationTemplate(OrganizationTemplate organizationTemplate) throws AuthenticationException {
    Element organizationsElement = root.element(XmlAuthenticationManager.ORGANIZATIONS);
    Element organizationTemplateElement = organizationsElement
            .element(XmlAuthenticationManager.ORGANIZATION_TEMPLATE);

    Element requiredCredentialsElement = organizationTemplateElement
            .element(XmlAuthenticationManager.CREDENTIALS);

    List reqCredsElement = requiredCredentialsElement.elements(XmlAuthenticationManager.CRED_TEMPLATE_ID);
    for (Object aReqCredsElement : reqCredsElement) {
        Element elt = (Element) aReqCredsElement;
        requiredCredentialsElement.remove(elt);
    }/*from   w  ww  .  j a v  a 2s  .c  o m*/

    Set creds = organizationTemplate.getCredentials();
    for (Object cred1 : creds) {
        JGuardCredential cred = (JGuardCredential) cred1;
        String name = cred.getName();
        Element credTemplateId = requiredCredentialsElement
                .addElement(XmlAuthenticationManager.CRED_TEMPLATE_ID);
        credTemplateId.setText(name);
    }

    persistPrincipalRefs(organizationTemplate.getPrincipals(), organizationTemplateElement);
    persistSubjectTemplate(organizationTemplateElement, organizationTemplate.getSubjectTemplate());

}

From source file:net.sf.jguard.ext.authorization.manager.XmlAuthorizationManager.java

License:Open Source License

/**
 * remove the permission./*ww  w. ja va  2s.  c  o  m*/
 *
 * @param permission
 * @see net.sf.jguard.core.authorization.manager.AuthorizationManager #deletePermission(java.lang.String)
 */
public void deletePermission(Permission permission) {
    Element permissionElement = getElement(XPATH_PERMISSION_BY_ID + permission.getId() + "']");
    if (permissionElement == null) {
        throw new IllegalStateException(
                "permission with id '" + permission.getId() + "' is not found in the xml file");
    }
    permissionElement.remove(permissionElement);
    Permission oldPermission = permissions.remove(permission.getId());
    permissions.remove(oldPermission.getId());
    permissionsSet.remove(oldPermission);
    urlp.removePermission(oldPermission.toJavaPermission());
    removePermissionFromPrincipals(permission.getId());

    try {
        XMLUtils.write(fileLocation, document);
    } catch (IOException e) {
        logger.error("deletePermission(String)", e);
    }
}

From source file:net.sf.jguard.ext.authorization.manager.XmlAuthorizationManager.java

License:Open Source License

/**
 * remove the corrspoding principal/role
 *
 * @param principal name//from w  w w .j  av  a 2 s  .c o m
 * @see net.sf.jguard.core.authorization.manager.AuthorizationManager #deletePrincipal(java.security.Principal)
 */
public void deletePrincipal(RolePrincipal principal) throws AuthorizationManagerException {
    if (principal == null) {
        throw new IllegalArgumentException("principal parameter is null ");
    }
    Principal ppalReference = principals.remove(principal.getId());
    if ((ppalReference == null)) {
        logger.warn(" there is no principal intitled " + principal.getName() + " to delete");
        return;
    }
    principalsSet.remove(ppalReference);
    Element principalsElement = root.element(PRINCIPALS);
    Element principalElement = getElement(XPATH_PRINCIPAL_BY_NAME + getLocalName(principal) + "']");
    principalsElement.remove(principalElement);
    if (ppalReference.getClass().equals(RolePrincipal.class)) {
        deleteReferenceInHierarchy((RolePrincipal) ppalReference);
        //delete all the references of this principal
        XMLUtils.deletePrincipalRefs(root, (RolePrincipal) ppalReference);
    }
    try {
        XMLUtils.write(fileLocation, document);
    } catch (IOException e) {
        logger.error("deleteRole(String)", e);
    }
}

From source file:net.sf.kraken.BaseTransport.java

License:Open Source License

/**
 * Intercepts disco items packets to filter out users who aren't allowed to register.
 *
 * @see org.jivesoftware.openfire.interceptor.PacketInterceptor#interceptPacket(org.xmpp.packet.Packet, org.jivesoftware.openfire.session.Session, boolean, boolean)
 *//*from   w w  w.  ja  va 2  s  .  com*/
@SuppressWarnings("unchecked")
public void interceptPacket(Packet packet, Session session, boolean incoming, boolean processed) {
    // If not IQ, return immediately.
    if (!(packet instanceof IQ)) {
        return;
    }

    // If it's a result IQ, process for possible filtering.
    if (((IQ) packet).getType().equals(IQ.Type.result)) {

        // If the packet is not outgoing back to the user or not processed yet, we don't care.
        if (processed || incoming) {
            return;
        }

        // If not query, return immediately.
        Element child = packet.getElement().element("query");
        if (child == null) {
            return;
        }

        // If no namespace uri, return immediately.
        if (child.getNamespaceURI() == null) {
            return;
        }

        // If not disco#items, return immediately.
        if (!child.getNamespaceURI().equals(NameSpace.DISCO_ITEMS)) {
            return;
        }

        // If the node is null, we don't care, not directly related to a user.
        JID to = packet.getTo();
        if (to.getNode() == null) {
            return;
        }

        JID from = packet.getFrom();
        // If not from server itself, return immediately.
        if (!XMPPServer.getInstance().isLocal(from)) {
            return;
        }

        // If user registered, return immediately.
        if (RegistrationManager.getInstance().isRegistered(to, transportType)) {
            return;
        }

        // Check if allowed, if so return immediately.
        if (permissionManager.hasAccess(to)) {
            return;
        }

        // Filter out item associated with transport.
        Iterator iter = child.elementIterator();
        while (iter.hasNext()) {
            Element elem = (Element) iter.next();
            try {
                if (elem.attribute("jid").getText().equals(this.jid.toString())) {
                    child.remove(elem);
                }
            } catch (Exception e) {
                // No worries.  Wasn't what we were looking for.
            }
        }

        //TODO: should filter conference as well at some point.

        return;
    }

    // If it's a set IQ, process for possible roster activity.
    if (((IQ) packet).getType().equals(IQ.Type.set)) {

        // If the packet is not coming from the user, we don't care.
        if (!incoming) {
            return;
        }

        // If not query, return immediately.
        Element child = packet.getElement().element("query");
        if (child == null) {
            return;
        }

        // If not jabber:iq:roster, return immediately.
        if (!child.getNamespaceURI().equals(NameSpace.IQ_ROSTER)) {
            return;
        }

        // Example items in roster modification.
        Iterator iter = child.elementIterator();
        while (iter.hasNext()) {
            Element elem = (Element) iter.next();
            if (!elem.getName().equals("item")) {
                continue;
            }
            String jidStr;
            String nickname = null;
            String sub = null;
            ArrayList<String> groups = new ArrayList<String>();
            try {
                jidStr = elem.attributeValue("jid");
            } catch (Exception e) {
                // No JID found, we don't want this then.
                continue;
            }
            JID jid = new JID(jidStr);
            if (!jid.getDomain().equals(this.getJID().toString())) {
                // Not for our domain, moving on.
                continue;
            }
            if (jid.getNode() == null) {
                // Gateway itself, don't care.
                return;
            }
            try {
                nickname = elem.attributeValue("name");
            } catch (Exception e) {
                // No nickname, ok then.
            }
            try {
                sub = elem.attributeValue("subscription");
            } catch (Exception e) {
                // No subscription, no worries.
            }
            Iterator groupIter = elem.elementIterator();
            while (groupIter.hasNext()) {
                Element groupElem = (Element) groupIter.next();
                if (!groupElem.getName().equals("group")) {
                    continue;
                }
                groups.add(groupElem.getText());
            }
            if (sub != null && sub.equals("remove")) {
                try {
                    TransportSession trSession = sessionManager.getSession(session.getAddress().getNode());
                    if (!trSession.isRosterLocked(jid.toString())) {
                        Log.debug(getType().toString() + ": contact delete " + session.getAddress().getNode()
                                + ":" + jid);
                        trSession.getBuddyManager().removeBuddy(convertJIDToID(jid));
                    }
                } catch (NotFoundException e) {
                    // Well we just don't care then.
                }
            } else {
                try {
                    TransportSession trSession = sessionManager.getSession(session.getAddress().getNode());
                    if (!trSession.isRosterLocked(jid.toString())) {
                        try {
                            TransportBuddy buddy = trSession.getBuddyManager().getBuddy(jid);
                            Log.debug(
                                    getType().toString() + ": contact update " + session.getAddress().getNode()
                                            + ":" + jid + ":" + nickname + ":" + groups);
                            buddy.setNicknameAndGroups(nickname, groups);
                        } catch (NotFoundException e) {
                            Log.debug(getType().toString() + ": contact add " + session.getAddress().getNode()
                                    + ":" + jid + ":" + nickname + ":" + groups);
                            trSession.addContact(jid, nickname, groups);
                        }
                    }
                } catch (NotFoundException e) {
                    // Well we just don't care then.
                }
            }
        }
    }
}

From source file:net.unicon.toro.installer.tools.MergeConfiguration.java

License:Open Source License

private void removeOldNodes(Element source) {
    // remove any previous nodes added by academus
    Iterator contentItr = source.content().iterator();
    boolean sawBegin = false;
    boolean sawEnd = false;

    List<Node> removedNodes = new LinkedList<Node>();

    while (!sawEnd && contentItr.hasNext()) {
        Node node = (Node) contentItr.next();
        if (node instanceof Element) {
            removeOldNodes((Element) node);
        }//from  w w w .  jav a 2 s.  c  o m

        if (!sawBegin) {
            sawBegin = node instanceof Comment && ((Comment) node).getText().equals(CHANGE_START_COMMENT);
            if (sawBegin) {
                removedNodes.add(node);
            }
        } else {
            removedNodes.add(node);
            sawEnd = node instanceof Comment && ((Comment) node).getText().equals(CHANGE_END_COMMENT);
        }
    }

    for (Node n : removedNodes) {
        source.remove(n);
    }
}

From source file:net.unicon.toro.installer.tools.MergeConfiguration.java

License:Open Source License

private void replaceElement(Element sourceEl, Element replacementElement) {
    if (!sourceEl.getName().equals(replacementElement.getName())) {
        throw new RuntimeException("replacement element must have the same name: " + sourceEl.getName()
                + " and " + replacementElement.getName() + " differ.");
    }/*from w  w  w .  j a va2  s.com*/

    // remove all the existing
    sourceEl.attributes().clear();

    // remove all child elements
    sourceEl.elements().clear();

    // add all the new attributes
    sourceEl.appendAttributes(replacementElement);

    // add all the new child elements
    Iterator eItr = new ArrayList(replacementElement.elements()).iterator();
    while (eItr.hasNext()) {
        Element newEl = (Element) eItr.next();
        replacementElement.remove(newEl);
        sourceEl.add(newEl);
    }
}

From source file:nl.tue.gale.ae.processor.xmlmodule.AdaptLinkModule.java

License:Open Source License

@Override
@SuppressWarnings("unchecked")
public Element traverse(Element element, Resource resource) throws ProcessorException {
    GaleContext gale = GaleContext.of(resource);
    CacheSession<EntityValue> session = gale.openUmSession();
    try {/*from ww  w  . j  a  v a  2 s. c  o  m*/
        // initialization
        processor.traverseChildren(element, resource);
        boolean useParent = !(element.getName().equals("a"));
        Element a = (useParent ? element.getParent() : element);
        String href = a.attributeValue("href");
        URI uri = URIs.of(href);
        //System.out.println(href);
        String anchorid = uri.getFragment();
        href = URIs.builder().uri(uri).fragment(null).build().toString();
        session.setBaseUri(session.resolve(href));

        // possibly add content to the link, based on previous processing
        Node n = resource.getTyped(Node.class, "nl.tue.gale.ae.processor.xmlmodule.AdaptLinkModule.content");
        if (n != null) {
            n = (Node) n.clone();
            a.add(n);
        }

        // should we adapt the class attribute or hide the link
        boolean adapt = (!"false".equals(a.attributeValue("adapt")));
        a.addAttribute("adapt", null);

        // should the link be removed or hidden
        if (adapt) {
            String removeexpr = (String) gale.cfgm().getObject("gale://gale.tue.nl/config/link#remove",
                    resource);
            if (removeexpr != null) {
                boolean remove = false;
                try {
                    remove = (Boolean) gale.eval(session, removeexpr);
                } catch (Exception e) {
                    log.debug(e, e);
                }
                if (remove) {
                    GaleUtil.replaceNode(a, null);
                    return null;
                }
            }

            String hideexpr = (String) gale.cfgm().getObject("gale://gale.tue.nl/config/link#hide", resource);
            if (hideexpr != null) {
                boolean hide = false;
                try {
                    hide = (Boolean) gale.eval(session, hideexpr);
                } catch (Exception e) {
                    log.debug(e, e);
                }
                if (hide) {
                    GaleUtil.replaceNode(a, DocumentFactory.getInstance().createText(a.getText()));
                    return null;
                }
            }
        }

        // determine and set css class
        if (adapt) {
            EntityValue ev = session.get(session.resolve("#link.class"));
            String cssclass = (ev != null ? ev.getValue().toString() : null);
            if (cssclass == null) {
                String classexpr = (String) gale.cfgm().getObject("gale://gale.tue.nl/config/link#classexpr",
                        resource);
                try {
                    cssclass = gale.eval(session, classexpr).toString();
                } catch (Exception e) {
                    log.debug(e, e);
                    cssclass = "unknown";
                }
            }
            a.addAttribute("class", cssclass);
        }

        // add possible exec code
        String exec = element.attributeValue("exec");
        String query = URIs.of(href).getQuery();
        if (exec != null) {
            String guid = GaleUtil.newGUID();
            storeInSession(gale, guid, exec);
            Map<String, String> params = GaleUtil.getQueryParameters(query);
            params.put("plugin", "exec");
            params.put("guid", guid);
            query = GaleUtil.getQueryString(params);
        }

        // add proper link to concept
        String conceptName = (href.startsWith("?") ? gale.concept().getUriString()
                : Concept.getConceptURI(session.getBaseUri()).toString());
        uri = URIs.of(gale.gsb().getConceptManager().getConceptLink(URIs.of(conceptName), gale.req(), query));

        // Added by Vinicius Ramos to log the currentView: "?view=" + gale.currentView()
        a.addAttribute("href", uri.toString() + (anchorid != null ? "#" + anchorid : "")
                + (uri.toString().contains("?") ? "" : "?view=" + gale.currentView()));
        a.setQName(DocumentFactory.getInstance().createQName(a.getName(), "", GaleUtil.xhtmlns));
        if (useParent)
            a.remove(element);

        // add possible icons
        if (adapt) {
            List<String> iconList = (List<String>) gale.cfgm()
                    .getObject("gale://gale.tue.nl/config/link#iconlist", resource);
            Element span = null;
            for (String iconExpr : iconList) {
                try {
                    String icon = (String) gale.eval(session, iconExpr);
                    if (icon == null || "".equals(icon))
                        continue;
                    boolean pre = false;
                    if (icon.startsWith("pre:")) {
                        icon = icon.substring(4);
                        pre = true;
                    }
                    URI iconUri = URIs.of(icon);
                    if (iconUri.isAbsolute()) {
                        // absolute uri
                        if (iconUri.getScheme().equals("gale")) {
                            icon = GaleUtil.getContextURL(gale.req()) + "/"
                                    + GaleUtil.getServletName(gale.req()) + "/${home}" + iconUri.getPath();
                        }
                    } else {
                        // relative uri

                    }
                    if (span == null) {
                        span = DocumentFactory.getInstance().createElement("span", GaleUtil.xhtmlns);
                        a.getParent().content().add(a.getParent().content().indexOf(a), span);
                        a.getParent().content().remove(a);
                        span.add(a);
                    }
                    Element img = DocumentFactory.getInstance().createElement("img", GaleUtil.xhtmlns);
                    img.addAttribute("src", icon);
                    img.addAttribute("align", "bottom");
                    img.addAttribute("alt", "");
                    if (pre)
                        span.content().add(0, img);
                    else
                        span.add(img);
                } catch (Exception e) {
                    log.debug(e, e);
                }
            }
        }
        return null;
    } catch (Exception e) {
        log.debug(e, e);
        return (Element) GaleUtil.replaceNode(element, GaleUtil.createErrorElement("[" + e.getMessage() + "]"));
    } finally {
        session.rollback();
    }
}

From source file:nl.tue.gale.ae.processor.xmlmodule.CreoleTextHandler.java

License:Open Source License

@SuppressWarnings("unchecked")
private void traverse(Element textElement) {
    boolean flat = ("true".equals(textElement.attributeValue("flat")));
    List<Element> elements = ImmutableList.copyOf((List<Element>) textElement.elements());
    for (Element element : elements) {
        textElement.content().add(textElement.content().indexOf(element),
                DocumentFactory.getInstance().createText("(% " + GaleUtil.serializeXML(element) + " %)"));
        textElement.remove(element);
    }/* w w w.ja v a2s  . c o m*/
    textElement.normalize();
    List<Node> content = ImmutableList.copyOf((List<Node>) textElement.content());
    for (Node node : content)
        if (node.getNodeType() == Node.TEXT_NODE) {
            textElement.content().addAll(textElement.content().indexOf(node), parse(node.getText(), flat));
            textElement.content().remove(node);
        }
}