Example usage for org.dom4j Element elementTextTrim

List of usage examples for org.dom4j Element elementTextTrim

Introduction

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

Prototype

String elementTextTrim(QName qname);

Source Link

Usage

From source file:net.techest.railgun.action.IndexActionNode.java

License:Apache License

@Override
public Shell execute(Element node, Shell shell) throws Exception {
    // ?// w  w w.  j  a va 2s .  c o  m
    String indexdir = Configure.getSystemConfig().getString("INDEX_DIR", "indexes");
    Index index = null;
    try {
        index = new Index(indexdir, false);
    } catch (Exception ex) {
        throw new ActionException(ex.getMessage());
    }
    // data
    Element data = node.element("data");

    ArrayList<String> colsName = new ArrayList<String>();
    ArrayList<String> colsValue = new ArrayList<String>();

    if (data.elements("enty") == null) {
        throw new ActionException("dataenty");
    }
    // ?? Consistoffset
    Iterator enties = data.elements("enty").iterator();
    while (enties.hasNext()) {
        Element entry = (Element) enties.next();
        colsName.add(entry.elementTextTrim("name"));
        colsValue.add(entry.elementTextTrim("content"));
    }
    // ???
    // ?
    for (Iterator i = shell.getResources().iterator(); i.hasNext();) {
        Resource res = (Resource) i.next();
        String consist = data.attributeValue("consist");
        if (consist != null) {
            int pos = colsName.indexOf(consist);
            if (pos == -1) {
                throw new ActionException(shell.getName() + " Consist???" + " [KEY]:" + consist);
            }
            // ?
            ArrayList<String> valueConverted = PatternHelper.convertAll(colsValue.get(pos), res, shell);
            String content = valueConverted.get(0);
            if (index.existed(consist, content)) {
                Log4j.getInstance().debug(shell.getName() + " Index : Consist" + " [VAL]:" + content);
                continue;
            }
        }

        // 
        enties = data.elements("enty").iterator();
        Document doc = new Document();
        // 
        while (enties.hasNext()) {
            Element entry = (Element) enties.next();
            Field f = null;
            String type = entry.elementTextTrim("type");
            // ?
            ArrayList<String> valueConverted = PatternHelper.convertAll(entry.elementTextTrim("content"), res,
                    shell);
            String content = valueConverted.get(0);
            if (type == null) {
                type = "text";
            }
            if (type.equals("fulltext")) {
                f = new Field(entry.elementTextTrim("name"), content, Field.Store.YES, Field.Index.ANALYZED,
                        Field.TermVector.YES);
            }
            if (type.equals("index")) {
                f = new Field(entry.elementTextTrim("name"), content, Field.Store.YES, Field.Index.ANALYZED,
                        Field.TermVector.NO);
            }
            if (type.equals("text")) {
                f = new Field(entry.elementTextTrim("name"), content, Field.Store.YES, Field.Index.NO,
                        Field.TermVector.NO);
            }
            doc.add(f);
        }
        index.addToRam(doc);
        Log4j.getInstance().debug(shell.getName() + " Index ?" + " [VAL]:" + doc);
    }
    index.applyToDisk();
    data.detach();
    Log4j.getInstance().info(shell.getName() + " Index ?");
    return shell;
}

From source file:net.techest.railgun.action.ParseActionNode.java

License:Apache License

@Override
public Shell execute(Element node, Shell shell) throws Exception {
    if (node.attribute("method") == null || node.element("rule") == null) {
        throw new ActionException("ParseNode ?rule");
    }//from   ww w  . j ava2 s. c o m
    String rule = node.elementTextTrim("rule");
    node.element("rule").detach();
    String returnType = "html";
    if (node.element("returnType") != null) {
        returnType = node.elementTextTrim("returnType");
        node.element("returnType").detach();
    }
    String set = node.elementTextTrim("set");
    if (node.element("set") != null) {
        node.element("set").detach();
    }

    Log4j.getInstance().info("??" + shell.getResources().size());
    LinkedList<Resource> resnew = new LinkedList<Resource>();
    for (Iterator i = shell.getResources().iterator(); i.hasNext();) {
        Resource res = (Resource) i.next();
        if (node.attributeValue("method").equals("dom")) {
            resnew = DomParser.parse(res, rule, set, returnType);
        }
        if (node.attributeValue("method").equals("regxp")) {
            resnew = RegxpParser.parse(res, rule, set, returnType);
        }
    }
    // ?
    Log4j.getInstance().info("??" + resnew.size());
    shell.setResources(resnew);

    return shell;
}

From source file:org.alfresco.web.config.ActionsElementReader.java

License:Open Source License

/**
 * @see org.springframework.extensions.config.xml.elementreader.ConfigElementReader#parse(org.dom4j.Element)
 *///from w  w  w.  j av  a  2  s. com
@SuppressWarnings("unchecked")
public ConfigElement parse(Element element) {
    ActionsConfigElement configElement = new ActionsConfigElement();

    if (element != null) {
        if (ActionsConfigElement.CONFIG_ELEMENT_ID.equals(element.getName()) == false) {
            throw new ConfigException("ActionsElementReader can only parse config elements of type 'Actions'");
        }

        Iterator<Element> actionItr = element.elementIterator(ELEMENT_ACTION);
        while (actionItr.hasNext()) {
            // work on each 'action' element in turn
            Element actionElement = actionItr.next();

            // parse the action definition for the element
            ActionDefinition actionDef = parseActionDefinition(actionElement);

            // add our finished action def to the map of all actions
            configElement.addActionDefinition(actionDef);
        }

        Iterator<Element> actionGroupItr = element.elementIterator(ELEMENT_ACTIONGROUP);
        while (actionGroupItr.hasNext()) {
            // work on each 'action-group' element in turn
            Element groupElement = actionGroupItr.next();
            String groupId = groupElement.attributeValue(ATTRIBUTE_ID);
            if (groupId == null || groupId.length() == 0) {
                throw new ConfigException(
                        "'action-group' config element specified without mandatory 'id' attribute.");
            }

            // build a structure to represent the action group
            ActionGroup actionGroup = new ActionGroup(groupId);

            // loop round each action ref and add them to the list for this action group
            Iterator<Element> actionRefItr = groupElement.elementIterator(ELEMENT_ACTION);
            while (actionRefItr.hasNext()) {
                Element actionRefElement = actionRefItr.next();

                // look for an action referred to be Id - this is the common use-case
                String idRef = actionRefElement.attributeValue(ATTRIBUTE_IDREF);
                if (idRef == null || idRef.length() == 0) {
                    // look for an action defined directly rather than referenced by Id
                    String id = actionRefElement.attributeValue(ATTRIBUTE_ID);
                    if (id != null && id.length() != 0) {
                        ActionDefinition def = parseActionDefinition(actionRefElement);
                        // override action definition ID based on the group name to avoid conflicts
                        def.id = actionGroup.getId() + '_' + def.getId();
                        configElement.addActionDefinition(def);
                        actionGroup.addAction(def.getId());
                    }
                } else {
                    // look for the hide attribute
                    String hide = actionRefElement.attributeValue(ATTRIBUTE_HIDE);
                    if (hide != null && Boolean.parseBoolean(hide)) {
                        actionGroup.hideAction(idRef);
                    } else {
                        // add the action definition ID to the group
                        actionGroup.addAction(idRef);
                    }
                }
            }

            // get simple string properties for the action group
            actionGroup.Style = groupElement.elementTextTrim(ELEMENT_STYLE);
            actionGroup.StyleClass = groupElement.elementTextTrim(ELEMENT_STYLECLASS);
            if (groupElement.element(ELEMENT_SHOWLINK) != null) {
                actionGroup.ShowLink = Boolean
                        .parseBoolean(groupElement.element(ELEMENT_SHOWLINK).getTextTrim());
            }

            // add the action group to the map of all action groups
            configElement.addActionGroup(actionGroup);
        }
    }

    return configElement;
}

From source file:org.alfresco.web.config.ActionsElementReader.java

License:Open Source License

/**
 * Parse an ActionDefinition from the specific config element.
 * /*from   w ww  .  j  av  a2 s  .  co m*/
 * @param actionElement    The config element containing the action def
 * 
 * @return The populated ActionDefinition
 */
public ActionDefinition parseActionDefinition(Element actionElement) {
    String actionId = actionElement.attributeValue(ATTRIBUTE_ID);
    if (actionId == null || actionId.length() == 0) {
        throw new ConfigException("'action' config element specified without mandatory 'id' attribute.");
    }

    // build a structure to represent the action definition
    ActionDefinition actionDef = new ActionDefinition(actionId);

    // look for the permissions element - it can contain many permission
    Element permissionsElement = actionElement.element(ELEMENT_PERMISSIONS);
    if (permissionsElement != null) {
        // read and process each permission element
        Iterator<Element> permissionItr = permissionsElement.elementIterator(ELEMENT_PERMISSION);
        while (permissionItr.hasNext()) {
            Element permissionElement = permissionItr.next();
            boolean allow = true;
            if (permissionElement.attributeValue(ATTRIBUTE_ALLOW) != null) {
                allow = Boolean.parseBoolean(permissionElement.attributeValue(ATTRIBUTE_ALLOW));
            }
            String permissionValue = permissionElement.getTextTrim();
            if (allow) {
                actionDef.addAllowPermission(permissionValue);
            } else {
                actionDef.addDenyPermission(permissionValue);
            }
        }
    }

    // find and construct the specified evaluator class
    Element evaluatorElement = actionElement.element(ELEMENT_EVALUATOR);
    if (evaluatorElement != null) {
        Object evaluator;
        String className = evaluatorElement.getTextTrim();
        try {
            Class clazz = Class.forName(className);
            evaluator = clazz.newInstance();
        } catch (Throwable err) {
            throw new ConfigException(
                    "Unable to construct action '" + actionId + "' evaluator classname: " + className);
        }
        if (evaluator instanceof ActionEvaluator == false) {
            throw new ConfigException("Action '" + actionId + "' evaluator class '" + className
                    + "' does not implement ActionEvaluator interface.");
        }
        actionDef.Evaluator = (ActionEvaluator) evaluator;
    }

    // find any parameter values that the action requires
    Element paramsElement = actionElement.element(ELEMENT_PARAMS);
    if (paramsElement != null) {
        Iterator<Element> paramsItr = paramsElement.elementIterator(ELEMENT_PARAM);
        while (paramsItr.hasNext()) {
            Element paramElement = paramsItr.next();
            String name = paramElement.attributeValue(ATTRIBUTE_NAME);
            if (name == null || name.length() == 0) {
                throw new ConfigException(
                        "Action '" + actionId + "' param does not have mandatory 'name' attribute.");
            }
            String value = paramElement.getTextTrim();
            if (value == null || value.length() == 0) {
                throw new ConfigException(
                        "Action '" + actionId + "' param '" + name + "'" + "' does not have a value.");
            }
            actionDef.addParam(name, value);
        }
    }

    // get simple string properties for the action
    actionDef.Label = actionElement.elementTextTrim(ELEMENT_LABEL);
    actionDef.LabelMsg = actionElement.elementTextTrim(ELEMENT_LABELMSG);
    actionDef.Tooltip = actionElement.elementTextTrim(ELEMENT_TOOLTIP);
    actionDef.TooltipMsg = actionElement.elementTextTrim(ELEMENT_TOOLTIPMSG);
    actionDef.Href = actionElement.elementTextTrim(ELEMENT_HREF);
    actionDef.Target = actionElement.elementTextTrim(ELEMENT_TARGET);
    actionDef.Script = actionElement.elementTextTrim(ELEMENT_SCRIPT);
    actionDef.Action = actionElement.elementTextTrim(ELEMENT_ACTION);
    actionDef.ActionListener = actionElement.elementTextTrim(ELEMENT_ACTIONLISTENER);
    actionDef.Onclick = actionElement.elementTextTrim(ELEMENT_ONCLICK);
    actionDef.Image = actionElement.elementTextTrim(ELEMENT_IMAGE);
    actionDef.Style = actionElement.elementTextTrim(ELEMENT_STYLE);
    actionDef.StyleClass = actionElement.elementTextTrim(ELEMENT_STYLECLASS);
    if (actionElement.element(ELEMENT_SHOWLINK) != null) {
        actionDef.ShowLink = Boolean.parseBoolean(actionElement.element(ELEMENT_SHOWLINK).getTextTrim());
    }

    return actionDef;
}

From source file:org.alfresco.web.site.servlet.config.KerberosConfigElement.java

License:Open Source License

/**
 * Constructs a new instance from an XML Element.
 * /*from  w w w  .j a v a2  s .  c  om*/
 * @param elem
 *            the XML element
 * @return the Kerberos configuration element
 */
protected static KerberosConfigElement newInstance(Element elem) {
    KerberosConfigElement configElement = new KerberosConfigElement();

    String password = elem.elementTextTrim("password");
    if (password != null && password.length() > 0) {
        configElement.password = password;
    }

    String realm = elem.elementTextTrim("realm");
    if (realm != null && realm.length() > 0) {
        configElement.realm = realm;
    }

    String endpointSPN = elem.elementTextTrim("endpoint-spn");
    if (endpointSPN != null && endpointSPN.length() > 0) {
        configElement.endpointSPN = endpointSPN;
    }

    String loginEntryName = elem.elementTextTrim("config-entry");
    if (loginEntryName != null && loginEntryName.length() > 0) {
        configElement.loginEntryName = loginEntryName;
    }

    String stripUserNameSuffix = elem.elementTextTrim("stripUserNameSuffix");
    if (stripUserNameSuffix != null && stripUserNameSuffix.length() > 0) {
        configElement.stripUserNameSuffix = Boolean.parseBoolean(stripUserNameSuffix);
    }

    return configElement;
}

From source file:org.apache.archiva.maven2.metadata.MavenMetadataReader.java

License:Apache License

/**
 * Read and return the {@link org.apache.archiva.model.ArchivaRepositoryMetadata} object from the provided xml file.
 *
 * @param metadataFile the maven-metadata.xml file to read.
 * @return the archiva repository metadata object that represents the provided file contents.
 * @throws XMLException//w w  w. j  ava2  s  .c o  m
 */
public static ArchivaRepositoryMetadata read(File metadataFile) throws XMLException {

    XMLReader xml = new XMLReader("metadata", metadataFile);
    // invoke this to remove namespaces, see MRM-1136
    xml.removeNamespaces();

    ArchivaRepositoryMetadata metadata = new ArchivaRepositoryMetadata();

    metadata.setGroupId(xml.getElementText("//metadata/groupId"));
    metadata.setArtifactId(xml.getElementText("//metadata/artifactId"));
    metadata.setVersion(xml.getElementText("//metadata/version"));
    metadata.setFileLastModified(new Date(metadataFile.lastModified()));
    metadata.setFileSize(metadataFile.length());

    metadata.setLastUpdated(xml.getElementText("//metadata/versioning/lastUpdated"));
    metadata.setLatestVersion(xml.getElementText("//metadata/versioning/latest"));
    metadata.setReleasedVersion(xml.getElementText("//metadata/versioning/release"));
    metadata.setAvailableVersions(xml.getElementListText("//metadata/versioning/versions/version"));

    Element snapshotElem = xml.getElement("//metadata/versioning/snapshot");
    if (snapshotElem != null) {
        SnapshotVersion snapshot = new SnapshotVersion();
        snapshot.setTimestamp(snapshotElem.elementTextTrim("timestamp"));
        String tmp = snapshotElem.elementTextTrim("buildNumber");
        if (NumberUtils.isNumber(tmp)) {
            snapshot.setBuildNumber(NumberUtils.toInt(tmp));
        }
        metadata.setSnapshotVersion(snapshot);
    }

    for (Element plugin : xml.getElementList("//metadata/plugins/plugin")) {
        Plugin p = new Plugin();
        p.setPrefix(plugin.elementTextTrim("prefix"));
        p.setArtifactId(plugin.elementTextTrim("artifactId"));
        p.setName(plugin.elementTextTrim("name"));
        metadata.addPlugin(p);
    }

    return metadata;

}

From source file:org.axonframework.migration.eventstore.LegacyAxonEventUpcaster.java

License:Apache License

private String extractMetaDataValue(Element newRoot, String metaDataKey) {
    for (Object entry : newRoot.element("metaData").element("values").elements()) {
        Element element = (Element) entry;
        String key = element.elementTextTrim("string");
        if (metaDataKey.equals(key)) {
            element.detach();// ww  w.  j a v a  2s  .  co m
            return (element.node(1).getText());
        }
    }
    return null;
}

From source file:org.eclipse.ecr.core.io.impl.AbstractDocumentModelWriter.java

License:Open Source License

@SuppressWarnings("unchecked")
private static Object getElementData(ExportedDocument xdoc, Element element, Type type) {
    if (type.isSimpleType()) {
        return type.decode(element.getText());
    } else if (type.isListType()) {
        ListType ltype = (ListType) type;
        List<Object> list = new ArrayList<Object>();
        Iterator<Element> it = element.elementIterator();
        while (it.hasNext()) {
            Element el = it.next();
            list.add(getElementData(xdoc, el, ltype.getFieldType()));
        }/*from w w w .ja v  a  2 s .c  o  m*/
        Type ftype = ltype.getFieldType();
        if (ftype.isSimpleType()) { // these are stored as arrays
            Class klass = JavaTypes.getClass(ftype);
            if (klass.isPrimitive()) {
                return PrimitiveArrays.toPrimitiveArray(list, klass);
            } else {
                return list.toArray((Object[]) Array.newInstance(klass, list.size()));
            }
        }
        return list;
    } else {
        ComplexType ctype = (ComplexType) type;
        if (TypeConstants.isContentType(ctype)) {
            String mimeType = element.elementText(ExportConstants.BLOB_MIME_TYPE);
            String encoding = element.elementText(ExportConstants.BLOB_ENCODING);
            String content = element.elementTextTrim(ExportConstants.BLOB_DATA);
            String filename = element.elementTextTrim(ExportConstants.BLOB_FILENAME);
            if ((content == null || content.length() == 0) && (mimeType == null || mimeType.length() == 0)) {
                return null; // remove blob
            }
            Blob blob = null;
            if (xdoc.hasExternalBlobs()) {
                blob = xdoc.getBlob(content);
            }
            if (blob == null) { // maybe the blob is embedded in Base64
                // encoded data
                byte[] bytes = Base64.decode(content);
                blob = new StreamingBlob(new ByteArraySource(bytes));
            }
            blob.setMimeType(mimeType);
            blob.setEncoding(encoding);
            blob.setFilename(filename);
            return blob;
        } else { // a complex type
            Map<String, Object> map = new HashMap<String, Object>();
            Iterator<Element> it = element.elementIterator();
            while (it.hasNext()) {
                Element el = it.next();
                String name = el.getName();
                Object value = getElementData(xdoc, el, ctype.getField(el.getName()).getType());
                map.put(name, value);
            }
            return map;
        }
    }
}

From source file:org.frogx.service.core.DefaultMUGSession.java

License:Open Source License

/**
 * This method handles invitations, start messages, game moves
 * and private messages./*from   w  w w . j  a va  2  s  .  c om*/
 * 
 * @param message The XMPP stanza which should be handled.
 * @throws ComponentException 
 */
protected void process(Message message) throws ComponentException {
    /* handle messages with child:
     *  - <game><invite>    -> invitation
     *  - <game><decline>   -> decline invitation
     *  - <start>           -> start
     *  - <turn>            -> turn
     * 
     * type chat or normal  -> private message
     */

    // Ignore messages of type error
    if (Message.Type.error == message.getType()) {
        return;
    }

    JID recipient = message.getTo();
    String roomName = recipient.getNode();

    // Ignore packets for the game component
    if (roomName == null) {
        return;
    }

    MUGOccupant occupant = occupants.get(roomName);
    MUGRoom room = (occupant != null) ? occupant.getGameRoom() : component.getGameRoom(roomName);
    Element childElement = null;

    // An user that is not an occupant could be declining an invitation
    if (occupant == null) {
        if (room != null) {
            boolean declinedInvitation = false;
            if (Message.Type.normal == message.getType()) {
                childElement = message.getChildElement("game", MUGService.mugUserNS);
                if (childElement != null && childElement.element("decline") != null) {
                    // A user has declined an invitation to a room
                    declinedInvitation = true;
                }
            }
            if (declinedInvitation) {
                Element info = childElement.element("decline");
                room.sendInvitationRejection(new JID(info.attributeValue("to")), info.elementTextTrim("reason"),
                        message.getFrom());
                return;
            } else {
                // The sender is not an occupant of the room
                throw new NotAcceptableException();
            }
        } else {
            // The sender is not an occupant of a NON-EXISTENT room!!!
            throw new NotFoundException();
        }
    }

    // Check senders address and reject conflicting packets
    if (!occupant.getUserAddress().equals(message.getFrom())) {
        throw new ConflictException();
    }

    // An occupant is trying to send a private message
    String resource = message.getTo().getResource();
    if (resource != null && resource.trim().length() > 0) {
        if (Message.Type.chat == message.getType() || Message.Type.normal == message.getType()) {
            room.sendPrivatePacket(message, occupant);
            return;
        } else {
            throw new UnsupportedGameException();
        }
    }

    // Try to make a turn
    childElement = message.getChildElement("turn", MUGService.mugUserNS);
    if (childElement != null) {
        if (!occupant.hasRole())
            throw new ForbiddenException();

        Collection<Element> moves = childElement.elements();
        MUGMatch match = room.getMatch();

        if (moves == null || moves.size() == 0)
            throw new IllegalArgumentException();

        if (match.getStatus() != MUGMatch.Status.active)
            throw new NotAcceptableException();

        try {
            match.processTurn(occupant, moves);
        } catch (InvalidTurnException e) {
            try {
                // Create and send an application specific error
                PacketError error = new PacketError(Condition.undefined_condition, Type.cancel);
                error.setApplicationCondition("invalid-turn", MUGService.mugNS);
                sendErrorPacket(message, error);

                // Create and broadcast the specific unavailable presence
                Presence presence = new Presence(Presence.Type.unavailable);
                presence.addChildElement("invalid-turn", MUGService.mugNS);
                occupant.setPresence(presence);
            } finally {
                occupants.remove(roomName);
                room.leave(occupant);
            }
        }
    }

    // Try to start or continue the match
    childElement = message.getChildElement("start", MUGService.mugUserNS);
    if (childElement != null) {
        room.startMatch(occupant);
    }

    // Try to invite or decline an invitation
    childElement = message.getChildElement("game", MUGService.mugUserNS);
    if (childElement != null) {
        if (childElement.element("invite") != null) {
            if (!room.canOccupantsInvite() && occupant.getAffiliation() != Affiliation.owner)
                throw new CannotBeInvitedException();

            // Send invitations to invitee
            for (Iterator it = childElement.elementIterator("invite"); it.hasNext();) {
                Element invite = (Element) it.next();

                // Add the user as a member of the room if the room is
                // members only
                if (room.isMembersOnly()) {
                    room.addMember(new JID(invite.attributeValue("to")), occupant);
                }

                // Send the invitation to the invitee
                room.invite(new JID(invite.attributeValue("to")), invite.elementTextTrim("reason"), occupant);
            }
        }
        if (childElement.element("decline") != null) {
            // Try to reject an invitation
            Element info = childElement.element("decline");
            room.sendInvitationRejection(new JID(info.attributeValue("to")), info.elementTextTrim("reason"),
                    message.getFrom());
        }
    }
}

From source file:org.frogx.service.core.DefaultMUGSession.java

License:Open Source License

/**
 * This method handles a {@see Presence} packets send to a
 * {@see MUGRoom} or {@see MUGOccupant}.
 * This can be creating or joining a game room, changing the
 * nickname, reserve a role, resignation or leaving a game room.
 * //from w  ww. j a v  a2s.c o m
 * @param presence The XMPP stanza which should be handled.
 */
protected void process(Presence presence) throws ComponentException {
    JID recipient = presence.getTo();
    String roomName = (recipient != null) ? recipient.getNode() : null;

    // Ignore Presence sending to the service
    if (roomName == null) {
        return;
    }

    MUGOccupant occupant = occupants.get(roomName);

    // Try to join a game room
    if (occupant == null) {
        // If we're not already in a room, we either are joining it or it's not
        // properly addressed and we drop it silently
        if (recipient.getResource() != null && recipient.getResource().trim().length() > 0) {
            if (presence.isAvailable()) {
                // get the game element
                Element game = presence.getChildElement("game", MUGService.mugNS);
                if (game == null)
                    throw new IllegalArgumentException();

                // extract the game namespace
                String gameNS = game.attributeValue("var");
                if (gameNS == null)
                    throw new IllegalArgumentException();

                MUGRoom room = component.getGameRoom(roomName, gameNS, presence.getFrom());
                occupants.put(roomName,
                        room.join(recipient.getResource(), game.elementTextTrim("password"), jid, presence));
            } else {
                // Ignore unavailable presence since we aren't in the room
            }
        } else {
            if (presence.isAvailable()) {
                // A resource is required in order to join a room
                sendErrorPacket(presence, PacketError.Condition.bad_request);
            }
            // Ignore unavailable presence since we aren't in the room
        }
        return;
    }

    // Check senders address and reject conflicting packets
    if (!occupant.getUserAddress().equals(presence.getFrom())) {
        throw new ConflictException();
    }

    // Try to leave a room
    if (Presence.Type.unavailable == presence.getType()) {
        MUGRoom room = occupant.getGameRoom();
        room.leave(occupant);
        occupants.remove(roomName);
        return;
    }

    // Get resource
    String resource = null;
    if (recipient.getResource() != null && recipient.getResource().trim().length() > 0)
        resource = recipient.getResource().trim();

    // Try to set new presence status
    if (resource == null || occupant.getNickname().equalsIgnoreCase(resource)) {
        Element gameElement = presence.getChildElement("game", MUGService.mugNS);
        if (gameElement != null) {
            Element item = gameElement.element("item");
            String roleName = (item != null) ? item.attributeValue("role") : null;

            if (roleName != null) {
                //TODO: Taking a role or resignation
                throw new UnsupportedGameException();
            }
        }

        // Occupant has changed his presence status
        occupant.setPresence(presence);
        occupant.getGameRoom().broadcastPresence(occupant);
        occupant.send(occupant.getPresence());
    } else {
        // Try to change nickname
        occupant = occupant.getGameRoom().changeNickname(occupant.getNickname(), resource, presence);
        // Refresh the occupant object
        occupants.remove(roomName);
        occupants.put(roomName, occupant);
    }
}