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:org.jivesoftware.openfire.handler.IQPrivateHandler.java

License:Open Source License

@Override
public IQ handleIQ(IQ packet) throws UnauthorizedException, PacketException {
    IQ replyPacket;//from   w  w  w.j  a v  a 2s . co m
    Element child = packet.getChildElement();
    Element dataElement = (Element) child.elementIterator().next();

    if (dataElement != null) {
        if (IQ.Type.get.equals(packet.getType())) {
            replyPacket = IQ.createResultIQ(packet);
            Element dataStored = privateStorage.get(packet.getFrom().getNode(), dataElement);
            dataStored.setParent(null);

            child.remove(dataElement);
            child.setParent(null);
            replyPacket.setChildElement(child);
            child.add(dataStored);
        } else {
            replyPacket = IQ.createResultIQ(packet);

            if (privateStorage.isEnabled()) {
                privateStorage.add(packet.getFrom().getNode(), dataElement);
            } else {
                replyPacket.setChildElement(packet.getChildElement().createCopy());
                replyPacket.setError(PacketError.Condition.service_unavailable);
            }
        }
    } else {
        replyPacket = IQ.createResultIQ(packet);
        replyPacket.setChildElement("query", "jabber:iq:private");
    }
    return replyPacket;
}

From source file:org.jivesoftware.openfire.ldap.LdapVCardProvider.java

License:Open Source License

/**
 * Loads the avatar from LDAP, based off the vcard template.
 *
 * If enabled, will replace a blank PHOTO element with one from a DB stored vcard.
 *
 * @param username User we are loading the vcard for.
 * @return The loaded vcard element, or null if none found.
 */// w w w  . j  a v a2 s  . c  o m
public Element loadVCard(String username) {
    // Un-escape username.
    username = JID.unescapeNode(username);
    Map<String, String> map = getLdapAttributes(username);
    Log.debug("LdapVCardProvider: Getting mapped vcard for " + username);
    Element vcard = new VCard(template).getVCard(map);
    // If we have a vcard from ldap, but it doesn't have an avatar filled in, then we
    // may fill it with a locally stored vcard element.
    if (dbStorageEnabled && vcard != null
            && (vcard.element("PHOTO") == null || vcard.element("PHOTO").element("BINVAL") == null
                    || vcard.element("PHOTO").element("BINVAL").getText().matches("\\s*"))) {
        Element avatarElement = loadAvatarFromDatabase(username);
        if (avatarElement != null) {
            Log.debug("LdapVCardProvider: Adding avatar element from local storage");
            Element currentElement = vcard.element("PHOTO");
            if (currentElement != null) {
                vcard.remove(currentElement);
            }
            vcard.add(avatarElement);
        }
    }
    Log.debug("LdapVCardProvider: Returning vcard");
    return vcard;
}

From source file:org.jivesoftware.openfire.ldap.LdapVCardProvider.java

License:Open Source License

/**
 * Returns a merged LDAP vCard combined with a PHOTO element provided in specified vCard.
 *
 * @param username User whose vCard this is.
 * @param mergeVCard vCard element that we are merging PHOTO element from into the LDAP vCard.
 * @return vCard element after merging in PHOTO element to LDAP data.
 *///from   w  w w .j  ava 2s .c  om
private Element getMergedVCard(String username, Element mergeVCard) {
    // Un-escape username.
    username = JID.unescapeNode(username);
    Map<String, String> map = getLdapAttributes(username);
    Log.debug("LdapVCardProvider: Retrieving LDAP mapped vcard for " + username);
    if (map.isEmpty()) {
        return null;
    }
    Element vcard = new VCard(template).getVCard(map);
    if (mergeVCard == null) {
        // No vcard passed in?  Hrm.  Fine, return LDAP vcard.
        return vcard;
    }
    if (mergeVCard.element("PHOTO") == null) {
        // Merged vcard has no photo element, return LDAP vcard as is.
        return vcard;
    }
    Element photoElement = mergeVCard.element("PHOTO").createCopy();
    if (photoElement == null || photoElement.element("BINVAL") == null
            || photoElement.element("BINVAL").getText().matches("\\s*")) {
        // We were passed something null or empty, so lets just return the LDAP based vcard.
        return vcard;
    }
    // Now we need to check that the LDAP vcard doesn't have a PHOTO element that's filled in.
    if (!((vcard.element("PHOTO") == null || vcard.element("PHOTO").element("BINVAL") == null
            || vcard.element("PHOTO").element("BINVAL").getText().matches("\\s*")))) {
        // Hrm, it does, return the original vcard;
        return vcard;
    }
    Log.debug("LdapVCardProvider: Merging avatar element from passed vcard");
    Element currentElement = vcard.element("PHOTO");
    if (currentElement != null) {
        vcard.remove(currentElement);
    }
    vcard.add(photoElement);
    return vcard;
}

From source file:org.jivesoftware.openfire.mediaproxy.MediaProxyService.java

License:Open Source License

private void processIQ(IQ iq) {
    IQ reply = IQ.createResultIQ(iq);//ww  w  .  j av a2s  . c  o m
    Element childElement = iq.getChildElement();
    String namespace = childElement.getNamespaceURI();
    Element childElementCopy = iq.getChildElement().createCopy();
    reply.setChildElement(childElementCopy);

    if ("http://jabber.org/protocol/disco#info".equals(namespace)) {
        reply = XMPPServer.getInstance().getIQDiscoInfoHandler().handleIQ(iq);
        router.route(reply);
        return;
    } else if ("http://jabber.org/protocol/disco#items".equals(namespace)) {
        // a component
        reply = XMPPServer.getInstance().getIQDiscoItemsHandler().handleIQ(iq);
        router.route(reply);
        return;
    } else if (NAMESPACE.equals(namespace) && enabled) {

        Element candidateElement = childElementCopy.element("candidate");
        String sid = childElementCopy.attribute("sid").getValue() + "-" + iq.getFrom();

        if (candidateElement != null) {
            childElementCopy.remove(candidateElement);
            Element candidate = childElementCopy.addElement("candidate ");
            ProxyCandidate proxyCandidate = mediaProxy.addRelayAgent(sid, iq.getFrom().toString());
            Log.debug("MediaProxyService: " + sid);
            proxyCandidate.start();
            candidate.addAttribute("name", "voicechannel");
            candidate.addAttribute("ip", mediaProxy.getPublicIP());
            candidate.addAttribute("porta", String.valueOf(proxyCandidate.getLocalPortA()));
            candidate.addAttribute("portb", String.valueOf(proxyCandidate.getLocalPortB()));
            candidate.addAttribute("pass", proxyCandidate.getPass());

        } else {
            candidateElement = childElementCopy.element("relay");
            if (candidateElement != null) {
                MediaProxySession session = mediaProxy.getSession(sid);
                Log.debug("MediaProxyService: " + sid);
                if (session != null) {
                    Attribute pass = candidateElement.attribute("pass");

                    if (pass != null && pass.getValue().trim().equals(session.getPass().trim())) {
                        Attribute portA = candidateElement.attribute("porta");
                        Attribute portB = candidateElement.attribute("portb");
                        Attribute hostA = candidateElement.attribute("hosta");
                        Attribute hostB = candidateElement.attribute("hostb");

                        try {
                            if (hostA != null && portA != null) {
                                for (int i = 0; i < 2; i++) {
                                    session.sendFromPortA(hostB.getValue(), Integer.parseInt(portB.getValue()));
                                }
                            }
                        } catch (Exception e) {
                            Log.error(e.getMessage(), e);
                        }

                    } else {
                        reply.setError(PacketError.Condition.forbidden);
                    }
                }
                childElementCopy.remove(candidateElement);
            } else {
                candidateElement = childElementCopy.element("publicip");
                if (candidateElement != null) {
                    childElementCopy.remove(candidateElement);
                    Element publicIp = childElementCopy.addElement("publicip");
                    try {
                        String ip = sessionManager.getSession(iq.getFrom()).getHostAddress();
                        if (ip != null) {
                            publicIp.addAttribute("ip", ip);
                        }
                    } catch (UnknownHostException e) {
                        Log.error(e.getMessage(), e);
                    }

                } else {
                    childElementCopy.remove(candidateElement);
                    reply.setError(PacketError.Condition.forbidden);
                }

            }
        }
    } else {
        // Answer an error since the server can't handle the requested namespace
        reply.setError(PacketError.Condition.service_unavailable);
    }

    try {
        if (Log.isDebugEnabled()) {
            Log.debug("MediaProxyService: RETURNED:" + reply.toXML());
        }
        router.route(reply);
    } catch (Exception e) {
        Log.error(e.getMessage(), e);
    }
}

From source file:org.jivesoftware.openfire.muc.spi.IQMUCRegisterHandler.java

License:Open Source License

public IQ handleIQ(IQ packet) {
    IQ reply = null;//from  w w w. j  ava 2s . c o  m
    // Get the target room
    MUCRoom room = null;
    String name = packet.getTo().getNode();
    if (name != null) {
        room = mucService.getChatRoom(name);
    }
    if (room == null) {
        // The room doesn't exist so answer a NOT_FOUND error
        reply = IQ.createResultIQ(packet);
        reply.setChildElement(packet.getChildElement().createCopy());
        reply.setError(PacketError.Condition.item_not_found);
        return reply;
    } else if (!room.isRegistrationEnabled()) {
        // The room does not accept users to register
        reply = IQ.createResultIQ(packet);
        reply.setChildElement(packet.getChildElement().createCopy());
        reply.setError(PacketError.Condition.not_allowed);
        return reply;
    }

    if (IQ.Type.get == packet.getType()) {
        reply = IQ.createResultIQ(packet);
        String nickname = room.getReservedNickname(packet.getFrom());
        Element currentRegistration = probeResult.createCopy();
        if (nickname != null) {
            // The user is already registered with the room so answer a completed form
            ElementUtil.setProperty(currentRegistration, "query.registered", null);
            currentRegistration.addElement("username").addText(nickname);

            Element form = currentRegistration.element(QName.get("x", "jabber:x:data"));
            currentRegistration.remove(form);
            //                @SuppressWarnings("unchecked")
            //            Iterator<Element> fields = form.elementIterator("field");
            //
            //                Element field;
            //                while (fields.hasNext()) {
            //                    field = fields.next();
            //                    if ("muc#register_roomnick".equals(field.attributeValue("var"))) {
            //                        field.addElement("value").addText(nickname);
            //                    }
            //                }
            reply.setChildElement(currentRegistration);
        } else {
            // The user is not registered with the room so answer an empty form
            reply.setChildElement(currentRegistration);
        }
    } else if (IQ.Type.set == packet.getType()) {
        try {
            // Keep a registry of the updated presences
            List<Presence> presences = new ArrayList<Presence>();

            reply = IQ.createResultIQ(packet);
            Element iq = packet.getChildElement();

            if (ElementUtil.includesProperty(iq, "query.remove")) {
                // The user is deleting his registration
                presences.addAll(room.addNone(packet.getFrom(), room.getRole()));
            } else {
                // The user is trying to register with a room
                Element formElement = iq.element("x");
                // Check if a form was used to provide the registration info
                if (formElement != null) {
                    // Get the sent form
                    final DataForm registrationForm = new DataForm(formElement);
                    // Get the desired nickname sent in the form
                    List<String> values = registrationForm.getField("muc#register_roomnick").getValues();
                    String nickname = (!values.isEmpty() ? values.get(0) : null);

                    // TODO The rest of the fields of the form are ignored. If we have a
                    // requirement in the future where we need those fields we'll have to change
                    // MUCRoom.addMember in order to receive a RegistrationInfo (new class)

                    // Add the new member to the members list
                    presences.addAll(room.addMember(packet.getFrom(), nickname, room.getRole()));
                } else {
                    reply.setChildElement(packet.getChildElement().createCopy());
                    reply.setError(PacketError.Condition.bad_request);
                }
            }
            // Send the updated presences to the room occupants
            for (Presence presence : presences) {
                room.send(presence);
            }

        } catch (ForbiddenException e) {
            reply = IQ.createResultIQ(packet);
            reply.setChildElement(packet.getChildElement().createCopy());
            reply.setError(PacketError.Condition.forbidden);
        } catch (ConflictException e) {
            reply = IQ.createResultIQ(packet);
            reply.setChildElement(packet.getChildElement().createCopy());
            reply.setError(PacketError.Condition.conflict);
        } catch (Exception e) {
            Log.error(e.getMessage(), e);
        }
    }
    return reply;
}

From source file:org.jivesoftware.util.ElementUtil.java

License:Open Source License

/**
 * <p>Deletes the specified property.</p>
 * <p>You MAY NOT use the atttribute
 * markup (using a ':' in the last element name) with this call.
 * deleteProperty() removes both the containing text, and the element itself along with
 * any attributes associated with that element.</p>
 *
 * @param name the property to delete.//from w w  w  . jav  a 2 s  .co  m
 */
public static void deleteProperty(Element element, String name) {
    // Remove property from cache.
    String[] propName = parsePropertyName(name);

    // Search for this property by traversing down the XML heirarchy.
    for (int i = 0; i < propName.length - 1; i++) {
        element = element.element(propName[i]);
        // Can't find the property so return.
        if (element == null) {
            return;
        }
    }
    // Found the correct element to remove, so remove it...
    element.remove(element.element(propName[propName.length - 1]));
}

From source file:org.jivesoftware.util.XMLProperties.java

License:Open Source License

/**
 * Sets a property to an array of values. Multiple values matching the same property
 * is mapped to an XML file as multiple elements containing each value.
 * For example, using the name "foo.bar.prop", and the value string array containing
 * {"some value", "other value", "last value"} would produce the following XML:
 * <pre>/*  w  w w .j  a v  a2s  .c o m*/
 * &lt;foo&gt;
 *     &lt;bar&gt;
 *         &lt;prop&gt;some value&lt;/prop&gt;
 *         &lt;prop&gt;other value&lt;/prop&gt;
 *         &lt;prop&gt;last value&lt;/prop&gt;
 *     &lt;/bar&gt;
 * &lt;/foo&gt;
 * </pre>
 *
 * @param name the name of the property.
 * @param values the values for the property (can be empty but not null).
 */
public void setProperties(String name, List<String> values) {
    String[] propName = parsePropertyName(name);
    // Search for this property by traversing down the XML hierarchy,
    // stopping one short.
    Element element = document.getRootElement();
    for (int i = 0; i < propName.length - 1; i++) {
        // If we don't find this part of the property in the XML hierarchy
        // we add it as a new node
        if (element.element(propName[i]) == null) {
            element.addElement(propName[i]);
        }
        element = element.element(propName[i]);
    }
    String childName = propName[propName.length - 1];
    // We found matching property, clear all children.
    List<Element> toRemove = new ArrayList<Element>();
    Iterator<Element> iter = element.elementIterator(childName);
    while (iter.hasNext()) {
        toRemove.add(iter.next());
    }
    for (iter = toRemove.iterator(); iter.hasNext();) {
        element.remove((Element) iter.next());
    }
    // Add the new children.
    for (String value : values) {
        Element childElement = element.addElement(childName);
        if (value.startsWith("<![CDATA[")) {
            Iterator<Node> it = childElement.nodeIterator();
            while (it.hasNext()) {
                Node node = it.next();
                if (node instanceof CDATA) {
                    childElement.remove(node);
                    break;
                }
            }
            childElement.addCDATA(value.substring(9, value.length() - 3));
        } else {
            String propValue = StringEscapeUtils.escapeXml(value);
            // check to see if the property is marked as encrypted
            if (JiveGlobals.isPropertyEncrypted(name)) {
                propValue = JiveGlobals.getPropertyEncryptor().encrypt(value);
                childElement.addAttribute(ENCRYPTED_ATTRIBUTE, "true");
            }
            childElement.setText(propValue);
        }
    }
    saveProperties();

    // Generate event.
    Map<String, Object> params = new HashMap<String, Object>();
    params.put("value", values);
    PropertyEventDispatcher.dispatchEvent(name, PropertyEventDispatcher.EventType.xml_property_set, params);
}

From source file:org.jivesoftware.util.XMLProperties.java

License:Open Source License

/**
 * Sets the value of the specified property. If the property doesn't
 * currently exist, it will be automatically created.
 *
 * @param name  the name of the property to set.
 * @param value the new value for the property.
 *///from   w w w.j  av  a  2 s  .c o m
public synchronized void setProperty(String name, String value) {
    if (!StringEscapeUtils.escapeXml(name).equals(name)) {
        throw new IllegalArgumentException("Property name cannot contain XML entities.");
    }
    if (name == null) {
        return;
    }
    if (value == null) {
        value = "";
    }

    // Set cache correctly with prop name and value.
    propertyCache.put(name, value);

    String[] propName = parsePropertyName(name);
    // Search for this property by traversing down the XML hierarchy.
    Element element = document.getRootElement();
    for (String aPropName : propName) {
        // If we don't find this part of the property in the XML hierarchy
        // we add it as a new node
        if (element.element(aPropName) == null) {
            element.addElement(aPropName);
        }
        element = element.element(aPropName);
    }
    // Set the value of the property in this node.
    if (value.startsWith("<![CDATA[")) {
        Iterator it = element.nodeIterator();
        while (it.hasNext()) {
            Node node = (Node) it.next();
            if (node instanceof CDATA) {
                element.remove(node);
                break;
            }
        }
        element.addCDATA(value.substring(9, value.length() - 3));
    } else {
        String propValue = StringEscapeUtils.escapeXml(value);
        // check to see if the property is marked as encrypted
        if (JiveGlobals.isPropertyEncrypted(name)) {
            propValue = JiveGlobals.getPropertyEncryptor().encrypt(value);
            element.addAttribute(ENCRYPTED_ATTRIBUTE, "true");
        }
        element.setText(propValue);
    }
    // Write the XML properties to disk
    saveProperties();

    // Generate event.
    Map<String, Object> params = new HashMap<String, Object>();
    params.put("value", value);
    PropertyEventDispatcher.dispatchEvent(name, PropertyEventDispatcher.EventType.xml_property_set, params);
}

From source file:org.jivesoftware.util.XMLProperties.java

License:Open Source License

/**
 * Deletes the specified property./*from   ww  w  .ja  v  a  2 s  .  co m*/
 *
 * @param name the property to delete.
 */
public synchronized void deleteProperty(String name) {
    // Remove property from cache.
    propertyCache.remove(name);

    String[] propName = parsePropertyName(name);
    // Search for this property by traversing down the XML hierarchy.
    Element element = document.getRootElement();
    for (int i = 0; i < propName.length - 1; i++) {
        element = element.element(propName[i]);
        // Can't find the property so return.
        if (element == null) {
            return;
        }
    }
    // Found the correct element to remove, so remove it...
    element.remove(element.element(propName[propName.length - 1]));
    if (element.elements().size() == 0) {
        element.getParent().remove(element);
    }
    // .. then write to disk.
    saveProperties();

    JiveGlobals.setPropertyEncrypted(name, false);
    // Generate event.
    Map<String, Object> params = Collections.emptyMap();
    PropertyEventDispatcher.dispatchEvent(name, PropertyEventDispatcher.EventType.xml_property_deleted, params);
}

From source file:org.jivesoftware.xmpp.workgroup.RequestQueue.java

License:Open Source License

public Presence getDetailedStatusPresence() {
    Presence queueStatus = new Presence();
    queueStatus.setFrom(address);//www .j  av a  2 s.  co m
    if (workgroup.getStatus() == Workgroup.Status.OPEN && presenceAvailable) {
        queueStatus.setType(null);
    } else {
        queueStatus.setType(Presence.Type.unavailable);
    }

    Element details = queueStatus.addChildElement("notify-queue-details",
            "http://jabber.org/protocol/workgroup");
    int i = 0;
    for (UserRequest request : getRequests()) {
        Element user = details.addElement("user", "http://jabber.org/protocol/workgroup");
        try {
            user.addAttribute("jid", request.getUserJID().toString());

            // Add Sub-Elements
            Element position = user.addElement("position");
            position.setText(Integer.toString(i));

            Element time = user.addElement("time");
            time.setText(Integer.toString(request.getTimeStatus()));

            Element joinTime = user.addElement("join-time");
            joinTime.setText(UTC_FORMAT.format(request.getCreationTime()));
            i++;
        } catch (Exception e) {
            // Since we are not locking the list of requests while doing this operation (for
            // performance reasons) it is possible that the request got accepted or cancelled
            // thus generating a NPE

            // Remove the request that generated the exception
            details.remove(user);
            // Log an error if the request still belongs to this queue
            if (this.equals(request.getRequestQueue())) {
                Log.error(e.getMessage(), e);
            }
        }
    }
    return queueStatus;
}