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.arquillian.graphene.visual.testing.impl.JCRMaskHandler.java

private void addMasksToTest(List<MaskFromREST> masks, Document doc) {
    Namespace ns = Namespace.get(RushEye.NAMESPACE_VISUAL_SUITE);
    for (MaskFromREST mask : masks) {
        String testName = mask.getName().split(":")[1].replaceAll("/", ".");
        testName = testName.substring(0, testName.lastIndexOf(".png"));
        String xPath = "/*[namespace-uri()=\"" + ns.getURI()
                + "\" and name()=\"visual-suite\"]/*[namespace-uri()=\"" + ns.getURI()
                + "\" and name()=\"test\" and @name=\"" + testName + "\"]";
        Element testElement = (Element) doc.selectSingleNode(xPath);
        Element patternElement = testElement.element(QName.get("pattern", ns));
        patternElement.detach();// w w  w  .  j  ava2 s. c  o m
        Element maskElement = testElement.addElement(QName.get("mask", ns));
        maskElement.addAttribute("id", mask.getId());
        maskElement.addAttribute("source", mask.getSourceUrl());
        maskElement.addAttribute("type", mask.getMaskType().value());
        testElement.add(patternElement);
    }
}

From source file:org.b5chat.crossfire.xmpp.auth.IQAuthHandler.java

License:Open Source License

/**
 * Clients are not authenticated when accessing this handler.
 *///from  w  ww  .ja v  a  2 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 = Globals.getBooleanProperty("xmpp.auth.anonymous");
}

From source file:org.b5chat.crossfire.xmpp.disco.IQDiscoItemsHandler.java

License:Open Source License

@Override
public IQ handleIQ(IQ packet) {
    // Create a copy of the sent pack that will be used as the reply
    // we only need to add the requested items to the reply if any otherwise add 
    // a not found error
    IQ reply = IQ.createResultIQ(packet);

    // TODO Implement publishing client items
    if (IQ.Type.set == packet.getType()) {
        reply.setChildElement(packet.getChildElement().createCopy());
        reply.setError(PacketError.Condition.feature_not_implemented);
        return reply;
    }/*from  ww w. jav a  2s. c om*/

    // Look for a IDiscoItemsProvider associated with the requested entity.
    // We consider the host of the recipient JID of the packet as the entity. It's the 
    // IDiscoItemsProvider responsibility to provide the items associated with the JID's name  
    // together with any possible requested node.
    IDiscoItemsProvider itemsProvider = getProvider(
            packet.getTo() == null ? XmppServer.getInstance().getServerInfo().getXMPPDomain()
                    : packet.getTo().getDomain());
    if (itemsProvider != null) {
        // Get the JID's name
        String name = packet.getTo() == null ? null : packet.getTo().getNode();
        if (name == null || name.trim().length() == 0) {
            name = null;
        }
        // Get the requested node
        Element iq = packet.getChildElement();
        String node = iq.attributeValue("node");

        // Check if we have items associated with the requested name and node
        Iterator<DiscoItem> itemsItr = itemsProvider.getItems(name, node, packet.getFrom());
        if (itemsItr != null) {
            reply.setChildElement(iq.createCopy());
            Element queryElement = reply.getChildElement();

            // See if the requesting entity would like to apply 'result set
            // management'
            final Element rsmElement = packet.getChildElement()
                    .element(QName.get("set", ResultSet.NAMESPACE_RESULT_SET_MANAGEMENT));

            // apply RSM only if the element exists, and the (total) results
            // set is not empty.
            final boolean applyRSM = rsmElement != null && itemsItr.hasNext();

            if (applyRSM) {
                if (!ResultSet.isValidRSMRequest(rsmElement)) {
                    reply.setError(PacketError.Condition.bad_request);
                    return reply;
                }

                // Calculate which results to include.
                final List<DiscoItem> rsmResults;
                final List<DiscoItem> allItems = new ArrayList<DiscoItem>();
                while (itemsItr.hasNext()) {
                    allItems.add(itemsItr.next());
                }
                final ResultSet<DiscoItem> rs = new ResultSetImpl<DiscoItem>(allItems);
                try {
                    rsmResults = rs.applyRSMDirectives(rsmElement);
                } catch (NullPointerException e) {
                    final IQ itemNotFound = IQ.createResultIQ(packet);
                    itemNotFound.setError(PacketError.Condition.item_not_found);
                    return itemNotFound;
                }

                // add the applicable results to the IQ-result
                for (DiscoItem item : rsmResults) {
                    final Element resultElement = item.getElement();
                    resultElement.setQName(new QName(resultElement.getName(), queryElement.getNamespace()));
                    queryElement.add(resultElement.createCopy());
                }

                // overwrite the 'set' element.
                queryElement.remove(
                        queryElement.element(QName.get("set", ResultSet.NAMESPACE_RESULT_SET_MANAGEMENT)));
                queryElement.add(rs.generateSetElementFromResults(rsmResults));
            } else {
                // don't apply RSM:
                // Add to the reply all the items provided by the IDiscoItemsProvider
                Element item;
                while (itemsItr.hasNext()) {
                    item = itemsItr.next().getElement();
                    item.setQName(new QName(item.getName(), queryElement.getNamespace()));
                    queryElement.add(item.createCopy());
                }
            }
        } else {
            // If the IDiscoItemsProvider has no items for the requested name and node 
            // then answer a not found error
            reply.setChildElement(packet.getChildElement().createCopy());
            reply.setError(PacketError.Condition.item_not_found);
        }
    } else {
        // If we didn't find a IDiscoItemsProvider then answer a not found error
        reply.setChildElement(packet.getChildElement().createCopy());
        reply.setError(PacketError.Condition.item_not_found);
    }

    return reply;
}

From source file:org.b5chat.crossfire.xmpp.entitycaps.EntityCapabilitiesManager.java

License:Open Source License

/**
* Extracts a list of extended service discovery information from an IQ
* packet.//from www . j  a  va 2  s.  c o  m
* 
* @param packet
*            the packet
* @return a list of extended service discoverin information features.
*/
private static List<String> getExtendedDataForms(IQ packet) {
    List<String> results = new ArrayList<String>();
    Element query = packet.getChildElement();
    @SuppressWarnings("unchecked")
    Iterator<Element> extensionIterator = query.elementIterator(QName.get("x", "jabber:x:data"));
    if (extensionIterator != null) {
        while (extensionIterator.hasNext()) {
            Element extensionElement = extensionIterator.next();
            final StringBuilder formType = new StringBuilder();

            @SuppressWarnings("unchecked")
            Iterator<Element> fieldIterator = extensionElement.elementIterator("field");
            List<String> vars = new ArrayList<String>();
            while (fieldIterator != null && fieldIterator.hasNext()) {
                final Element fieldElement = fieldIterator.next();
                if (fieldElement.attributeValue("var").equals("FORM_TYPE")) {
                    formType.append(fieldElement.element("value").getText());
                    formType.append('<');
                } else {
                    final StringBuilder var = new StringBuilder();
                    var.append(fieldElement.attributeValue("var"));
                    var.append('<');
                    @SuppressWarnings("unchecked")
                    Iterator<Element> valIter = fieldElement.elementIterator("value");
                    List<String> values = new ArrayList<String>();
                    while (valIter != null && valIter.hasNext()) {
                        Element value = valIter.next();
                        values.add(value.getText());
                    }
                    Collections.sort(values);
                    for (String v : values) {
                        var.append(v);
                        var.append('<');
                    }
                    vars.add(var.toString());
                }
            }
            Collections.sort(vars);
            for (String v : vars) {
                formType.append(v);
            }

            results.add(formType.toString());
        }
    }
    return results;
}

From source file:org.b5chat.crossfire.xmpp.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 ww w  . j av a2 s .  c  o 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());
    }
    // See if in-band registration should be enabled (default is true).
    registrationEnabled = Globals.getBooleanProperty("register.inband", true);
    // See if users can change their passwords (default is true).
    canChangePassword = Globals.getBooleanProperty("register.password", true);
}

From source file:org.b5chat.crossfire.xmpp.handler.IQRegisterHandler.java

License:Open Source License

@Override
public IQ handleIQ(IQ packet) throws PacketException, UnauthorizedException {
    IClientSession session = sessionManager.getSession(packet.getFrom());
    IQ reply = null;/*from  www.j av  a2 s.  com*/
    // If no session was found then answer an error (if possible)
    if (session == null) {
        Log.error("Error during registration. ISession 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() == ISession.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() == ISession.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 (IClientSession 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() == ISession.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.b5chat.crossfire.xmpp.handler.IQTimeHandler.java

License:Open Source License

public IQTimeHandler() {
    super("XMPP Server Time Handler");
    info = new IQHandlerInfo("query", "jabber:iq:time");
    responseElement = DocumentHelper.createElement(QName.get("query", "jabber:iq:time"));
    responseElement.addElement("utc");
    responseElement.addElement("tz").setText(TIME_FORMAT.getTimeZone().getDisplayName());
    responseElement.addElement("display");
}

From source file:org.b5chat.crossfire.xmpp.handler.IQVersionHandler.java

License:Open Source License

public IQVersionHandler() {
    super("XMPP Server Version Handler");
    info = new IQHandlerInfo("query", "jabber:iq:version");
    if (bodyElement == null) {
        bodyElement = DocumentHelper.createElement(QName.get("query", "jabber:iq:version"));
        bodyElement.addElement("name").setText(AdminConsole.getAppName());
        bodyElement.addElement("version").setText(AdminConsole.getVersionString());
    }//from   w  w  w  .j  a  v  a  2 s  . c  om
}

From source file:org.codehaus.modello.plugin.jaxrs.JaxRSMappingModelloGenerator.java

License:Apache License

private Element addElement(Element base, String elementName, String elementText) {
    QName elem = QName.get(elementName, namespace);
    Element newElement = base.addElement(elem);
    if (elementText != null)
        newElement.setText(elementText);
    return newElement;
}

From source file:org.codehaus.modello.plugin.jpa.JpaOrmMappingModelloGenerator.java

License:Apache License

public static Element addElement(Element base, String elementName, String elementText) {
    QName elem = QName.get(elementName, namespace);
    Element newElement = base.addElement(elem);
    if (elementText != null)
        newElement.setText(elementText);
    return newElement;
}