Example usage for org.dom4j QName get

List of usage examples for org.dom4j QName get

Introduction

In this page you can find the example usage for org.dom4j QName get.

Prototype

public static QName get(String qualifiedName, String uri) 

Source Link

Usage

From source file:org.jivesoftware.openfire.handler.IQAuthHandler.java

License:Open Source License

/**
 * Clients are not authenticated when accessing this handler.
 *//*w ww  .  j  av  a2  s.  c om*/
public IQAuthHandler() {
    super("XMPP Authentication handler");
    info = new IQHandlerInfo("query", "jabber:iq:auth");

    probeResponse = DocumentHelper.createElement(QName.get("query", "jabber:iq:auth"));
    probeResponse.addElement("username");
    if (AuthFactory.isPlainSupported()) {
        probeResponse.addElement("password");
    }
    if (AuthFactory.isDigestSupported()) {
        probeResponse.addElement("digest");
    }
    probeResponse.addElement("resource");
    anonymousAllowed = JiveGlobals.getBooleanProperty("xmpp.auth.anonymous");
}

From source file:org.jivesoftware.openfire.handler.IQBlockingHandler.java

License:Open Source License

@Override
public IQ handleIQ(IQ iq) throws UnauthorizedException {
    if (iq.isResponse()) {
        return null;
    }//from w ww  .j  a v a  2s.  c o m

    final JID requester = iq.getFrom();

    if (!XMPPServer.getInstance().getUserManager().isRegisteredUser(requester)) {
        final IQ error = IQ.createResultIQ(iq);
        error.setError(PacketError.Condition.not_authorized);
        return error;
    }

    final User user;
    try {
        user = UserManager.getInstance().getUser(requester.getNode());
    } catch (UserNotFoundException e) {
        Log.error("Unable to retrieve user '{}' that was verified to be an existing user!", requester.getNode(),
                e);
        final IQ error = IQ.createResultIQ(iq);
        error.setError(PacketError.Condition.internal_server_error);
        return error;
    }

    try {
        if (iq.getType().equals(IQ.Type.get) && "blocklist".equals(iq.getChildElement().getName())) {
            final Set<JID> blocklist = getBlocklist(user);
            final IQ response = IQ.createResultIQ(iq);

            final Element blocklistElement = DocumentHelper
                    .createElement(QName.get(getInfo().getName(), getInfo().getNamespace()));
            for (final JID blocked : blocklist) {
                blocklistElement.addElement("item").addAttribute("jid", blocked.toString());
            }
            response.setChildElement(blocklistElement);

            sessionManager.getSession(iq.getFrom()).setHasRequestedBlocklist(true);
            return response;
        } else if (iq.getType().equals(IQ.Type.set) && "block".equals(iq.getChildElement().getName())) {
            final List<Element> items = iq.getChildElement().elements("item");
            if (items == null || items.isEmpty()) {
                final IQ error = IQ.createResultIQ(iq);
                error.setError(PacketError.Condition.bad_request);
                return error;
            }

            final List<JID> toBlocks = new ArrayList<>();
            for (final Element item : items) {
                toBlocks.add(new JID(item.attributeValue("jid")));
            }

            addToBlockList(user, toBlocks);
            pushBlocklistUpdates(user, toBlocks);

            return IQ.createResultIQ(iq);
        } else if (iq.getType().equals(IQ.Type.set) && "unblock".equals(iq.getChildElement().getName())) {
            final Set<JID> unblocked;
            final List<Element> items = iq.getChildElement().elements("item");
            if (items == null || items.isEmpty()) {
                unblocked = removeAllFromBlocklist(user);
            } else {
                final Collection<JID> toUnblocks = new ArrayList<>();
                for (final Element item : items) {
                    toUnblocks.add(new JID(item.attributeValue("jid")));
                }
                unblocked = removeFromBlockList(user, toUnblocks);
            }

            pushBlocklistUpdates(user, unblocked);
            sendPresence(user, unblocked);

            return IQ.createResultIQ(iq);
        } else {
            final IQ error = IQ.createResultIQ(iq);
            error.setError(PacketError.Condition.feature_not_implemented);
            return error;
        }
    } catch (Exception e) {
        Log.warn("An exception occurred while trying to process an IQ block request from '{}':", iq.getFrom(),
                e);
        final IQ error = IQ.createResultIQ(iq);
        error.setError(PacketError.Condition.internal_server_error);
        return error;
    }
}

From source file:org.jivesoftware.openfire.handler.IQEntityTimeHandler.java

License:Open Source License

@Override
public IQ handleIQ(IQ packet) {
    IQ response = IQ.createResultIQ(packet);
    Element timeElement = DocumentHelper.createElement(QName.get(info.getName(), info.getNamespace()));
    timeElement.addElement("tzo").setText(formatsTimeZone(TimeZone.getDefault()));
    timeElement.addElement("utc").setText(getUtcDate(new Date()));
    response.setChildElement(timeElement);
    return response;
}

From source file:org.jivesoftware.openfire.handler.IQFindUserByPlateHandler.java

License:Open Source License

public IQFindUserByPlateHandler() {
    super("XMPP Server Time Handler");
    info = new IQHandlerInfo("query", "jabber:iq:plate");
    responseElement = DocumentHelper.createElement(QName.get("query", "jabber:iq:plate"));
    responseElement.addElement("username");
}

From source file:org.jivesoftware.openfire.handler.IQRegisterHandler.java

License:Open Source License

@Override
public void initialize(XMPPServer server) {
    super.initialize(server);
    userManager = server.getUserManager();
    rosterManager = server.getRosterManager();

    if (probeResult == null) {
        // Create the basic element of the probeResult which contains the basic registration
        // information (e.g. username, passoword and email)
        probeResult = DocumentHelper.createElement(QName.get("query", "jabber:iq:register"));
        probeResult.addElement("username");
        probeResult.addElement("password");
        probeResult.addElement("email");
        probeResult.addElement("name");

        // Create the registration form to include in the probeResult. The form will include
        // the basic information plus name and visibility of name and email.
        // TODO Future versions could allow plugin modules to add new fields to the form 
        final DataForm registrationForm = new DataForm(DataForm.Type.form);
        registrationForm.setTitle("XMPP Client Registration");
        registrationForm.addInstruction("Please provide the following information");

        final FormField fieldForm = registrationForm.addField();
        fieldForm.setVariable("FORM_TYPE");
        fieldForm.setType(FormField.Type.hidden);
        fieldForm.addValue("jabber:iq:register");

        final FormField fieldUser = registrationForm.addField();
        fieldUser.setVariable("username");
        fieldUser.setType(FormField.Type.text_single);
        fieldUser.setLabel("Username");
        fieldUser.setRequired(true);//from  www  .j  ava  2 s.  co m

        final FormField fieldName = registrationForm.addField();
        fieldName.setVariable("name");
        fieldName.setType(FormField.Type.text_single);
        fieldName.setLabel("Full name");
        if (UserManager.getUserProvider().isNameRequired()) {
            fieldName.setRequired(true);
        }

        final FormField fieldMail = registrationForm.addField();
        fieldMail.setVariable("email");
        fieldMail.setType(FormField.Type.text_single);
        fieldMail.setLabel("Email");
        if (UserManager.getUserProvider().isEmailRequired()) {
            fieldMail.setRequired(true);
        }

        final FormField fieldPwd = registrationForm.addField();
        fieldPwd.setVariable("password");
        fieldPwd.setType(FormField.Type.text_private);
        fieldPwd.setLabel("Password");
        fieldPwd.setRequired(true);

        // Add the registration form to the probe result.
        probeResult.add(registrationForm.getElement());
    }

    JiveGlobals.migrateProperty("register.inband");
    JiveGlobals.migrateProperty("register.password");

    // See if in-band registration should be enabled (default is true).
    registrationEnabled = JiveGlobals.getBooleanProperty("register.inband", true);
    // See if users can change their passwords (default is true).
    canChangePassword = JiveGlobals.getBooleanProperty("register.password", true);
}

From source file:org.jivesoftware.openfire.handler.IQRegisterHandler.java

License:Open Source License

@Override
public IQ handleIQ(IQ packet) throws PacketException, UnauthorizedException {
    ClientSession session = sessionManager.getSession(packet.getFrom());
    IQ reply = null;//from w w  w  .j  av a2s .  co m
    // If no session was found then answer an error (if possible)
    if (session == null) {
        Log.error("Error during registration. Session not found in " + sessionManager.getPreAuthenticatedKeys()
                + " for key " + packet.getFrom());
        // This error packet will probably won't make it through
        reply = IQ.createResultIQ(packet);
        reply.setChildElement(packet.getChildElement().createCopy());
        reply.setError(PacketError.Condition.internal_server_error);
        return reply;
    }
    if (IQ.Type.get.equals(packet.getType())) {
        // If inband registration is not allowed, return an error.
        if (!registrationEnabled) {
            reply = IQ.createResultIQ(packet);
            reply.setChildElement(packet.getChildElement().createCopy());
            reply.setError(PacketError.Condition.forbidden);
        } else {
            reply = IQ.createResultIQ(packet);
            if (session.getStatus() == Session.STATUS_AUTHENTICATED) {
                try {
                    User user = userManager.getUser(session.getUsername());
                    Element currentRegistration = probeResult.createCopy();
                    currentRegistration.addElement("registered");
                    currentRegistration.element("username").setText(user.getUsername());
                    currentRegistration.element("password").setText("");
                    currentRegistration.element("email")
                            .setText(user.getEmail() == null ? "" : user.getEmail());
                    currentRegistration.element("name").setText(user.getName());

                    Element form = currentRegistration.element(QName.get("x", "jabber:x:data"));
                    Iterator fields = form.elementIterator("field");
                    Element field;
                    while (fields.hasNext()) {
                        field = (Element) fields.next();
                        if ("username".equals(field.attributeValue("var"))) {
                            field.addElement("value").addText(user.getUsername());
                        } else if ("name".equals(field.attributeValue("var"))) {
                            field.addElement("value").addText(user.getName());
                        } else if ("email".equals(field.attributeValue("var"))) {
                            field.addElement("value").addText(user.getEmail() == null ? "" : user.getEmail());
                        }
                    }
                    reply.setChildElement(currentRegistration);
                } catch (UserNotFoundException e) {
                    reply.setChildElement(probeResult.createCopy());
                }
            } else {
                // This is a workaround. Since we don't want to have an incorrect TO attribute
                // value we need to clean up the TO attribute. The TO attribute will contain an
                // incorrect value since we are setting a fake JID until the user actually
                // authenticates with the server.
                reply.setTo((JID) null);
                reply.setChildElement(probeResult.createCopy());
            }
        }
    } else if (IQ.Type.set.equals(packet.getType())) {
        try {
            Element iqElement = packet.getChildElement();
            if (iqElement.element("remove") != null) {
                // If inband registration is not allowed, return an error.
                if (!registrationEnabled) {
                    reply = IQ.createResultIQ(packet);
                    reply.setChildElement(packet.getChildElement().createCopy());
                    reply.setError(PacketError.Condition.forbidden);
                } else {
                    if (session.getStatus() == Session.STATUS_AUTHENTICATED) {
                        User user = userManager.getUser(session.getUsername());
                        // Delete the user
                        userManager.deleteUser(user);
                        // Delete the roster of the user
                        rosterManager.deleteRoster(session.getAddress());
                        // Delete the user from all the Groups
                        GroupManager.getInstance().deleteUser(user);

                        reply = IQ.createResultIQ(packet);
                        session.process(reply);
                        // Take a quick nap so that the client can process the result
                        Thread.sleep(10);
                        // Close the user's connection
                        final StreamError error = new StreamError(StreamError.Condition.not_authorized);
                        for (ClientSession sess : sessionManager.getSessions(user.getUsername())) {
                            sess.deliverRawText(error.toXML());
                            sess.close();
                        }
                        // The reply has been sent so clean up the variable
                        reply = null;
                    } else {
                        throw new UnauthorizedException();
                    }
                }
            } else {
                String username;
                String password = null;
                String email = null;
                String name = null;
                User newUser;
                DataForm registrationForm;
                FormField field;

                Element formElement = iqElement.element("x");
                // Check if a form was used to provide the registration info
                if (formElement != null) {
                    // Get the sent form
                    registrationForm = new DataForm(formElement);
                    // Get the username sent in the form
                    List<String> values = registrationForm.getField("username").getValues();
                    username = (!values.isEmpty() ? values.get(0) : " ");
                    // Get the password sent in the form
                    field = registrationForm.getField("password");
                    if (field != null) {
                        values = field.getValues();
                        password = (!values.isEmpty() ? values.get(0) : " ");
                    }
                    // Get the email sent in the form
                    field = registrationForm.getField("email");
                    if (field != null) {
                        values = field.getValues();
                        email = (!values.isEmpty() ? values.get(0) : " ");
                    }
                    // Get the name sent in the form
                    field = registrationForm.getField("name");
                    if (field != null) {
                        values = field.getValues();
                        name = (!values.isEmpty() ? values.get(0) : " ");
                    }
                } else {
                    // Get the registration info from the query elements
                    username = iqElement.elementText("username");
                    password = iqElement.elementText("password");
                    email = iqElement.elementText("email");
                    name = iqElement.elementText("name");
                }
                if (email != null && email.matches("\\s*")) {
                    email = null;
                }
                if (name != null && name.matches("\\s*")) {
                    name = null;
                }

                // So that we can set a more informative error message back, lets test this for
                // stringprep validity now.
                if (username != null) {
                    Stringprep.nodeprep(username);
                }

                if (session.getStatus() == Session.STATUS_AUTHENTICATED) {
                    // Flag that indicates if the user is *only* changing his password
                    boolean onlyPassword = false;
                    if (iqElement.elements().size() == 2 && iqElement.element("username") != null
                            && iqElement.element("password") != null) {
                        onlyPassword = true;
                    }
                    // If users are not allowed to change their password, return an error.
                    if (password != null && !canChangePassword) {
                        reply = IQ.createResultIQ(packet);
                        reply.setChildElement(packet.getChildElement().createCopy());
                        reply.setError(PacketError.Condition.forbidden);
                        return reply;
                    }
                    // If inband registration is not allowed, return an error.
                    else if (!onlyPassword && !registrationEnabled) {
                        reply = IQ.createResultIQ(packet);
                        reply.setChildElement(packet.getChildElement().createCopy());
                        reply.setError(PacketError.Condition.forbidden);
                        return reply;
                    } else {
                        User user = userManager.getUser(session.getUsername());
                        if (user.getUsername().equalsIgnoreCase(username)) {
                            if (password != null && password.trim().length() > 0) {
                                user.setPassword(password);
                            }
                            if (!onlyPassword) {
                                user.setEmail(email);
                            }
                            newUser = user;
                        } else if (password != null && password.trim().length() > 0) {
                            // An admin can create new accounts when logged in.
                            newUser = userManager.createUser(username, password, null, email);
                        } else {
                            // Deny registration of users with no password
                            reply = IQ.createResultIQ(packet);
                            reply.setChildElement(packet.getChildElement().createCopy());
                            reply.setError(PacketError.Condition.not_acceptable);
                            return reply;
                        }
                    }
                } else {
                    // If inband registration is not allowed, return an error.
                    if (!registrationEnabled) {
                        reply = IQ.createResultIQ(packet);
                        reply.setChildElement(packet.getChildElement().createCopy());
                        reply.setError(PacketError.Condition.forbidden);
                        return reply;
                    }
                    // Inform the entity of failed registration if some required
                    // information was not provided
                    else if (password == null || password.trim().length() == 0) {
                        reply = IQ.createResultIQ(packet);
                        reply.setChildElement(packet.getChildElement().createCopy());
                        reply.setError(PacketError.Condition.not_acceptable);
                        return reply;
                    } else {
                        // Create the new account
                        newUser = userManager.createUser(username, password, name, email);
                    }
                }
                // Set and save the extra user info (e.g. full name, etc.)
                if (newUser != null && name != null && !name.equals(newUser.getName())) {
                    newUser.setName(name);
                }

                reply = IQ.createResultIQ(packet);
            }
        } catch (UserAlreadyExistsException e) {
            reply = IQ.createResultIQ(packet);
            reply.setChildElement(packet.getChildElement().createCopy());
            reply.setError(PacketError.Condition.conflict);
        } catch (UserNotFoundException e) {
            reply = IQ.createResultIQ(packet);
            reply.setChildElement(packet.getChildElement().createCopy());
            reply.setError(PacketError.Condition.bad_request);
        } catch (StringprepException e) {
            // The specified username is not correct according to the stringprep specs
            reply = IQ.createResultIQ(packet);
            reply.setChildElement(packet.getChildElement().createCopy());
            reply.setError(PacketError.Condition.jid_malformed);
        } catch (IllegalArgumentException e) {
            // At least one of the fields passed in is not valid
            reply = IQ.createResultIQ(packet);
            reply.setChildElement(packet.getChildElement().createCopy());
            reply.setError(PacketError.Condition.not_acceptable);
            Log.warn(e.getMessage(), e);
        } catch (UnsupportedOperationException e) {
            // The User provider is read-only so this operation is not allowed
            reply = IQ.createResultIQ(packet);
            reply.setChildElement(packet.getChildElement().createCopy());
            reply.setError(PacketError.Condition.not_allowed);
        } catch (Exception e) {
            // Some unexpected error happened so return an internal_server_error
            reply = IQ.createResultIQ(packet);
            reply.setChildElement(packet.getChildElement().createCopy());
            reply.setError(PacketError.Condition.internal_server_error);
            Log.error(e.getMessage(), e);
        }
    }
    if (reply != null) {
        // why is this done here instead of letting the iq handler do it?
        session.process(reply);
    }
    return null;
}

From source file:org.jivesoftware.openfire.handler.IQvCardHandler.java

License:Open Source License

@Override
public IQ handleIQ(IQ packet) throws UnauthorizedException, PacketException {
    IQ result = IQ.createResultIQ(packet);
    IQ.Type type = packet.getType();
    if (type.equals(IQ.Type.set)) {
        try {/*  ww  w . ja  v  a 2 s  . c o m*/
            User user = userManager.getUser(packet.getFrom().getNode());
            Element vcard = packet.getChildElement();
            if (vcard != null) {
                VCardManager.getInstance().setVCard(user.getUsername(), vcard);
            }
        } catch (UserNotFoundException e) {
            result = IQ.createResultIQ(packet);
            result.setChildElement(packet.getChildElement().createCopy());
            result.setError(PacketError.Condition.item_not_found);
        } catch (Exception e) {
            Log.error(e.getMessage(), e);
            result.setError(PacketError.Condition.internal_server_error);
        }
    } else if (type.equals(IQ.Type.get)) {
        JID recipient = packet.getTo();
        // If no TO was specified then get the vCard of the sender of the packet
        if (recipient == null) {
            recipient = packet.getFrom();
        }
        // By default return an empty vCard
        result.setChildElement("vCard", "vcard-temp");
        // Only try to get the vCard values of non-anonymous users
        if (recipient != null) {
            if (recipient.getNode() != null && server.isLocal(recipient)) {
                VCardManager vManager = VCardManager.getInstance();
                Element userVCard = vManager.getVCard(recipient.getNode());
                if (userVCard != null) {
                    // Check if the requester wants to ignore some vCard's fields
                    Element filter = packet.getChildElement().element(QName.get("filter", "vcard-temp-filter"));
                    if (filter != null) {
                        // Create a copy so we don't modify the original vCard
                        userVCard = userVCard.createCopy();
                        // Ignore fields requested by the user
                        for (Iterator toFilter = filter.elementIterator(); toFilter.hasNext();) {
                            Element field = (Element) toFilter.next();
                            Element fieldToRemove = userVCard.element(field.getName());
                            if (fieldToRemove != null) {
                                fieldToRemove.detach();
                            }
                        }
                    }
                    result.setChildElement(userVCard);
                }
            } else {
                result = IQ.createResultIQ(packet);
                result.setChildElement(packet.getChildElement().createCopy());
                result.setError(PacketError.Condition.item_not_found);
            }
        } else {
            result = IQ.createResultIQ(packet);
            result.setChildElement(packet.getChildElement().createCopy());
            result.setError(PacketError.Condition.item_not_found);
        }
    } else {
        result.setChildElement(packet.getChildElement().createCopy());
        result.setError(PacketError.Condition.not_acceptable);
    }
    return result;
}

From source file:org.jivesoftware.openfire.http.HttpBindBody.java

License:Open Source License

public String getLanguage() {
    // Default language is English ("en").
    final String language = document.getRootElement()
            .attributeValue(QName.get("lang", XMLConstants.XML_NS_URI));
    if (language == null || "".equals(language)) {
        return "en";
    }//  w  ww  .j a  v  a  2 s  .co  m

    return language;
}

From source file:org.jivesoftware.openfire.MessageRouter.java

License:Open Source License

/**
 * <p>Performs the actual packet routing.</p>
 * <p>You routing is considered 'quick' and implementations may not take
 * excessive amounts of time to complete the routing. If routing will take
 * a long amount of time, the actual routing should be done in another thread
 * so this method returns quickly.</p>
 * <h2>Warning</h2>//from   w  w  w  .  j  a  va2  s.c o m
 * <p>Be careful to enforce concurrency DbC of concurrent by synchronizing
 * any accesses to class resources.</p>
 *
 * @param packet The packet to route
 * @throws NullPointerException If the packet is null
 */
public void route(Message packet) {
    if (packet == null) {
        throw new NullPointerException();
    }
    ClientSession session = sessionManager.getSession(packet.getFrom());

    try {
        // Invoke the interceptors before we process the read packet
        InterceptorManager.getInstance().invokeInterceptors(packet, session, true, false);
        if (session == null || session.getStatus() == Session.STATUS_AUTHENTICATED) {
            JID recipientJID = packet.getTo();

            // If the server receives a message stanza with no 'to' attribute, it MUST treat the message as if the 'to' address were the bare JID <localpart@domainpart> of the sending entity.
            if (recipientJID == null) {
                recipientJID = packet.getFrom().asBareJID();
            }

            // Check if the message was sent to the server hostname
            if (recipientJID.getNode() == null && recipientJID.getResource() == null
                    && serverName.equals(recipientJID.getDomain())) {
                if (packet.getElement().element("addresses") != null) {
                    // Message includes multicast processing instructions. Ask the multicastRouter
                    // to route this packet
                    multicastRouter.route(packet);
                } else {
                    // Message was sent to the server hostname so forward it to a configurable
                    // set of JID's (probably admin users)
                    sendMessageToAdmins(packet);
                }
                return;
            }

            boolean isAcceptable = true;
            if (session instanceof LocalClientSession) {
                // Check if we could process messages from the recipient.
                // If not, return a not-acceptable error as per XEP-0016:
                // If the user attempts to send an outbound stanza to a contact and that stanza type is blocked, the user's server MUST NOT route the stanza to the contact but instead MUST return a <not-acceptable/> error
                Message dummyMessage = packet.createCopy();
                dummyMessage.setFrom(packet.getTo());
                dummyMessage.setTo(packet.getFrom());
                if (!((LocalClientSession) session).canProcess(dummyMessage)) {
                    packet.setTo(session.getAddress());
                    packet.setFrom((JID) null);
                    packet.setError(PacketError.Condition.not_acceptable);
                    session.process(packet);
                    isAcceptable = false;
                }
            }
            if (isAcceptable) {
                boolean isPrivate = packet.getElement()
                        .element(QName.get("private", "urn:xmpp:carbons:2")) != null;
                try {
                    // Deliver stanza to requested route
                    routingTable.routePacket(recipientJID, packet, false);
                } catch (Exception e) {
                    log.error("Failed to route packet: " + packet.toXML(), e);
                    routingFailed(recipientJID, packet);
                }

                // Sent carbon copies to other resources of the sender:
                // When a client sends a <message/> of type "chat"
                if (packet.getType() == Message.Type.chat && !isPrivate && session != null) { // && session.isMessageCarbonsEnabled() ??? // must the own session also be carbon enabled?
                    List<JID> routes = routingTable.getRoutes(packet.getFrom().asBareJID(), null);
                    for (JID route : routes) {
                        // The sending server SHOULD NOT send a forwarded copy to the sending full JID if it is a Carbons-enabled resource.
                        if (!route.equals(session.getAddress())) {
                            ClientSession clientSession = sessionManager.getSession(route);
                            if (clientSession != null && clientSession.isMessageCarbonsEnabled()) {
                                Message message = new Message();
                                // The wrapping message SHOULD maintain the same 'type' attribute value
                                message.setType(packet.getType());
                                // the 'from' attribute MUST be the Carbons-enabled user's bare JID
                                message.setFrom(packet.getFrom().asBareJID());
                                // and the 'to' attribute SHOULD be the full JID of the resource receiving the copy
                                message.setTo(route);
                                // The content of the wrapping message MUST contain a <sent/> element qualified by the namespace "urn:xmpp:carbons:2", which itself contains a <forwarded/> qualified by the namespace "urn:xmpp:forward:0" that contains the original <message/> stanza.
                                message.addExtension(new Sent(new Forwarded(packet)));
                                clientSession.process(message);
                            }
                        }
                    }
                }
            }
        } else {
            packet.setTo(session.getAddress());
            packet.setFrom((JID) null);
            packet.setError(PacketError.Condition.not_authorized);
            session.process(packet);
        }
        // Invoke the interceptors after we have processed the read packet
        InterceptorManager.getInstance().invokeInterceptors(packet, session, true, true);
    } catch (PacketRejectedException e) {
        // An interceptor rejected this packet
        if (session != null && e.getRejectionMessage() != null && e.getRejectionMessage().trim().length() > 0) {
            // A message for the rejection will be sent to the sender of the rejected packet
            Message reply = new Message();
            reply.setID(packet.getID());
            reply.setTo(session.getAddress());
            reply.setFrom(packet.getTo());
            reply.setType(packet.getType());
            reply.setThread(packet.getThread());
            reply.setBody(e.getRejectionMessage());
            session.process(reply);
        }
    }
}

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

License:Open Source License

public IQ handleIQ(IQ packet) {
    IQ reply = null;//from  ww w  .j a  va 2 s  .  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;
}