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:itensil.workflow.activities.web.ActivityServlet.java

License:Open Source License

/**
 *  /launch/*w ww  . ja  va  2s . c om*/
 *
 * Inject a new activity into a flow.
 *
 * Request XML:
 *
 *      <launch>
 *
 *          <flow>/path/xxx.flow</flow>
 *          <master-flow>/optional/master-path/xxx.flow</master-flow>
 *          <name>text</name>
 *          <description>text</description>
 *          <start>date</start>
 *          <end>date</end>
 *          <priority>number</priority>
 *          <parent>activity.id</parent>
 *          <parentStep>step.id</parentStep>
 *          <project>id</project>
 *          <meet>0</meet>          
 *
 *          <!-- maybe this for more file inputs? -->
 *          <file name="...">uri</file> ...
 *      </launch>
 *
 */
@SuppressWarnings("unchecked")
@ContentType("text/xml")
public void webLaunch(HttpServletRequest request, HttpServletResponse response) throws Exception {

    Document doc = XMLDocument.readStream(request.getInputStream());
    Element root = doc.getRootElement();
    if ("launch".equals(root.getName())) {

        HibernateUtil.beginTransaction();
        User user = (User) request.getUserPrincipal();
        User subUser = null;

        String submitId = root.elementTextTrim("submitId");

        if (!Check.isEmpty(submitId) && UserUtil.isAdmin((AuthenticatedUser) user)) {
            user = user.getUserSpace().resolve(new DefaultUser(submitId));
            subUser = user;
        }

        UserActivities uActivities = new UserActivities(user, HibernateUtil.getSession());

        boolean isMeet = "1".equals(root.elementTextTrim("meet"));

        String name = root.elementTextTrim("name");
        if (Check.isEmpty(name))
            throw new NotFoundException("[blank activity]");

        // resolve the flow
        String flowUri = root.elementTextTrim("flow");
        String path = root.elementTextTrim("path");
        if (!Check.isEmpty(flowUri)) {
            if (!flowUri.startsWith("/"))
                flowUri = UriHelper.absoluteUri(Check.isEmpty(path) ? "/home/process" : path, flowUri);
            flowUri = RepositoryHelper.resolveUri(flowUri);
        } else {
            flowUri = UriHelper.absoluteUri(
                    RepositoryHelper.getPrimaryRepository().getMount() + (isMeet ? "/meeting" : "/process"),
                    UriHelper.filterName(name));

            // auto meeting folder
            if (isMeet) {
                String meetFolder = RepositoryHelper.getPrimaryRepository().getMount() + "/meeting";
                try {
                    RepositoryHelper.getNode(meetFolder, false);
                } catch (NotFoundException nfe) {
                    RepositoryHelper.createCollection(meetFolder);
                }
            }

            flowUri = RepositoryHelper.getAvailableUri(flowUri);
        }

        HashMap<String, String> roles = new HashMap<String, String>();

        // Pre-assign some roles
        for (Element rolEl : (List<Element>) root.elements("role")) {
            String role = rolEl.attributeValue("role");
            String assignId = rolEl.attributeValue("assignId");
            if (role != null)
                role = role.trim();
            if (!Check.isEmpty(role) && !Check.isEmpty(assignId)) {
                roles.put(role, assignId);
            }
        }

        String parentId = root.elementTextTrim("parent");
        String parentStep = root.elementTextTrim("parentStep");

        // Launch it!
        Activity activityEnt = uActivities.launch(name, root.elementTextTrim("description"), flowUri,
                RepositoryHelper.resolveUri(root.elementTextTrim("master-flow")), parentId,
                root.elementTextTrim("project"), root.elementTextTrim("contextGroup"),
                ActivityXML.parseDate(root.elementTextTrim("dueDate")), roles);

        // is the submit user different than the thread user?
        if (subUser != null) {
            ((MutableRepositoryNode) activityEnt.getNode())
                    .grantPermission(new DefaultNodePermission(subUser, DefaultNodePermission.WRITE, true));
        }

        // Connect the parent step... this probably shouldn't be in the servlet
        if (!Check.isEmpty(parentStep) && !Check.isEmpty(parentId)) {
            Activity parAct = uActivities.getActivity(parentId);
            ActivityStepState aStat = parAct.getStates().get(parentStep);
            if (aStat != null) {
                aStat.setSubActivityId(activityEnt.getId());
                HibernateUtil.getSession().update(aStat);
            }
        }

        if (isMeet) {

            // flag repo node
            MutableRepositoryNode actRepoNode = (MutableRepositoryNode) activityEnt.getNode();
            HashMap<QName, String> propMap = new HashMap<QName, String>(1);
            propMap.put(PropertyHelper.itensilQName("meet-setup"), "1");
            PropertyHelper.setNodeValues(actRepoNode, propMap);

            // throw out initial end state
            ActivityStepState endState = null;
            for (ActivityStepState actState : activityEnt.getStates().values()) {
                if (actState.getSubState() == SubState.ENTER_END) {
                    endState = actState;
                    break;
                }
            }
            if (endState != null) {
                activityEnt.getStates().remove(endState.getStepId());
                HibernateUtil.getSession().delete(endState);
            }
        }

        // return activity's status
        Document retDoc = DocumentHelper.createDocument(ActivityXML.display(activityEnt));
        HibernateUtil.commitTransaction();

        retDoc.write(response.getWriter());
    }

}

From source file:itensil.workflow.activities.web.ActivityServlet.java

License:Open Source License

/**
 *  /submit//from   w ww. ja v  a  2s.  c  o  m
 *
 * Submit an Activity for flow routing
 *
 * Request XML:
 *      <submit>
 *          <activity>activity.id</activity>
 *          <step>step.id</step>
 *          <expr>expression</expr>
 *
 *          <!-- maybe this for more wiki inputs? -->
 *          <data name="...">value</data> ...
 *      </submit>
 */
@SuppressWarnings("unchecked")
@ContentType("text/xml")
public void webSubmit(HttpServletRequest request, HttpServletResponse response) throws Exception {

    Document doc = XMLDocument.readStream(request.getInputStream());
    Element root = doc.getRootElement();
    if ("submit".equals(root.getName())) {

        User user = (User) request.getUserPrincipal();

        HibernateUtil.beginTransaction();
        Session session = HibernateUtil.getSession();
        UserActivities uActivities = new UserActivities(user, session);

        // resolve the activity
        String activityId = root.elementTextTrim("activity");
        Activity activityEnt = uActivities.getActivity(activityId);
        if (activityEnt == null) {
            throw new NotFoundException(activityId);
        }
        String step = root.elementTextTrim("step");
        if (Check.isEmpty(step)) {
            throw new NotFoundException("[empty step]");
        }

        HashMap<String, String> submitValues = null;
        Element data = root.element("rule-data");
        if (data != null) {
            List<Element> kids = data.elements();
            if (!kids.isEmpty()) {
                submitValues = new HashMap<String, String>();
                for (Element attrElem : kids) {
                    submitValues.put(attrElem.getName(), attrElem.getText());
                }
            }
        }
        Element swPath = root.element("switch-path");
        String resTx;
        if (swPath != null && swPath.hasContent()) {
            resTx = uActivities.exitSwitch(activityEnt, step, swPath.getTextTrim());
        } else {
            resTx = uActivities.submit(activityEnt, step, submitValues, root.elementTextTrim("expr"));
        }

        // return activity's status
        Element actElem = ActivityXML.display(activityEnt);
        actElem.addAttribute("resTx", resTx);

        Document retDoc = DocumentHelper.createDocument(actElem);
        HibernateUtil.commitTransaction();

        retDoc.write(response.getWriter());
    }

}

From source file:net.emiva.crossfire.plugin.muc.spi.IQAdminHandler.java

License:Open Source License

/**
 * Handles packets that includes item elements. Depending on the item's attributes the
 * interpretation of the request may differ. For example, an item that only contains the
 * "affiliation" attribute is requesting the list of participants or members. Whilst if the item
 * contains the affiliation together with a jid means that the client is changing the
 * affiliation of the requested jid.//from  w  ww . j a v  a2  s .com
 *
 * @param senderRole the role of the user that sent the request packet.
 * @param itemsList  the list of items sent by the client.
 * @param reply      the iq packet that will be sent back as a reply to the client's request.
 * @throws ForbiddenException If the user is not allowed to perform his request.
 * @throws ConflictException If the desired room nickname is already reserved for the room or
 *                           if the room was going to lose all of its owners.
 * @throws NotAllowedException Thrown if trying to ban an owner or an administrator.
 * @throws CannotBeInvitedException If the user being invited as a result of being added to a members-only room still does not have permission
 */
private void handleItemsElement(MUCRole senderRole, List itemsList, IQ reply)
        throws ForbiddenException, ConflictException, NotAllowedException, CannotBeInvitedException {
    Element item;
    String affiliation;
    String roleAttribute;
    boolean hasJID = ((Element) itemsList.get(0)).attributeValue("jid") != null;
    boolean hasNick = ((Element) itemsList.get(0)).attributeValue("nick") != null;
    // Check if the client is requesting or changing the list of moderators/members/etc.
    if (!hasJID && !hasNick) {
        // The client is requesting the list of moderators/members/participants/outcasts
        for (Object anItem : itemsList) {
            item = (Element) anItem;
            affiliation = item.attributeValue("affiliation");
            roleAttribute = item.attributeValue("role");
            // Create the result that will hold an item for each
            // moderator/member/participant/outcast
            Element result = reply.setChildElement("query", "http://jabber.org/protocol/muc#admin");

            Element metaData;
            if ("outcast".equals(affiliation)) {
                // The client is requesting the list of outcasts
                if (MUCRole.Affiliation.admin != senderRole.getAffiliation()
                        && MUCRole.Affiliation.owner != senderRole.getAffiliation()) {
                    throw new ForbiddenException();
                }
                for (String jid : room.getOutcasts()) {
                    metaData = result.addElement("item", "http://jabber.org/protocol/muc#admin");
                    metaData.addAttribute("affiliation", "outcast");
                    metaData.addAttribute("jid", jid);
                }

            } else if ("member".equals(affiliation)) {
                // The client is requesting the list of members
                // In a members-only room members can get the list of members
                if (!room.isMembersOnly() && MUCRole.Affiliation.admin != senderRole.getAffiliation()
                        && MUCRole.Affiliation.owner != senderRole.getAffiliation()) {
                    throw new ForbiddenException();
                }
                for (String jid : room.getMembers()) {
                    metaData = result.addElement("item", "http://jabber.org/protocol/muc#admin");
                    metaData.addAttribute("affiliation", "member");
                    metaData.addAttribute("jid", jid);
                    try {
                        List<MUCRole> roles = room.getOccupantsByBareJID(jid);
                        MUCRole role = roles.get(0);
                        metaData.addAttribute("role", role.getRole().toString());
                        metaData.addAttribute("nick", role.getNickname());
                    } catch (UserNotFoundException e) {
                        // Do nothing
                    }
                }
            } else if ("moderator".equals(roleAttribute)) {
                // The client is requesting the list of moderators
                if (MUCRole.Affiliation.admin != senderRole.getAffiliation()
                        && MUCRole.Affiliation.owner != senderRole.getAffiliation()) {
                    throw new ForbiddenException();
                }
                for (MUCRole role : room.getModerators()) {
                    metaData = result.addElement("item", "http://jabber.org/protocol/muc#admin");
                    metaData.addAttribute("role", "moderator");
                    metaData.addAttribute("jid", role.getUserAddress().toString());
                    metaData.addAttribute("nick", role.getNickname());
                    metaData.addAttribute("affiliation", role.getAffiliation().toString());
                }
            } else if ("participant".equals(roleAttribute)) {
                // The client is requesting the list of participants
                if (MUCRole.Role.moderator != senderRole.getRole()) {
                    throw new ForbiddenException();
                }
                for (MUCRole role : room.getParticipants()) {
                    metaData = result.addElement("item", "http://jabber.org/protocol/muc#admin");
                    metaData.addAttribute("role", "participant");
                    metaData.addAttribute("jid", role.getUserAddress().toString());
                    metaData.addAttribute("nick", role.getNickname());
                    metaData.addAttribute("affiliation", role.getAffiliation().toString());
                }
            } else {
                reply.setError(PacketError.Condition.bad_request);
            }
        }
    } else {
        // The client is modifying the list of moderators/members/participants/outcasts
        JID jid;
        String nick;
        String target;
        boolean hasAffiliation = ((Element) itemsList.get(0)).attributeValue("affiliation") != null;

        // Keep a registry of the updated presences
        List<Presence> presences = new ArrayList<Presence>(itemsList.size());

        // Collect the new affiliations or roles for the specified jids
        for (Object anItem : itemsList) {
            try {
                item = (Element) anItem;
                target = (hasAffiliation ? item.attributeValue("affiliation") : item.attributeValue("role"));
                // jid could be of the form "full JID" or "bare JID" depending if we are
                // going to change a role or an affiliation
                if (hasJID) {
                    jid = new JID(item.attributeValue("jid"));
                    nick = null;
                } else {
                    // Get the JID based on the requested nick
                    nick = item.attributeValue("nick");
                    jid = room.getOccupant(nick).getUserAddress();
                }

                if ("moderator".equals(target)) {
                    // Add the user as a moderator of the room based on the full JID
                    presences.add(room.addModerator(jid, senderRole));
                } else if ("participant".equals(target)) {
                    // Add the user as a participant of the room based on the full JID
                    presences.add(room.addParticipant(jid, item.elementTextTrim("reason"), senderRole));
                } else if ("visitor".equals(target)) {
                    // Add the user as a visitor of the room based on the full JID
                    presences.add(room.addVisitor(jid, senderRole));
                } else if ("member".equals(target)) {
                    // Add the user as a member of the room based on the bare JID
                    boolean hadAffiliation = room.getAffiliation(jid.toBareJID()) != MUCRole.Affiliation.none;
                    presences.addAll(room.addMember(jid, nick, senderRole));
                    // If the user had an affiliation don't send an invitation. Otherwise
                    // send an invitation if the room is members-only and skipping invites
                    // are not disabled system-wide xmpp.muc.skipInvite
                    if (!skipInvite && !hadAffiliation && room.isMembersOnly()) {
                        room.sendInvitation(jid, null, senderRole, null);
                    }
                } else if ("outcast".equals(target)) {
                    // Add the user as an outcast of the room based on the bare JID
                    presences.addAll(room.addOutcast(jid, item.elementTextTrim("reason"), senderRole));
                } else if ("none".equals(target)) {
                    if (hasAffiliation) {
                        // Set that this jid has a NONE affiliation based on the bare JID
                        presences.addAll(room.addNone(jid, senderRole));
                    } else {
                        // Kick the user from the room
                        if (MUCRole.Role.moderator != senderRole.getRole()) {
                            throw new ForbiddenException();
                        }
                        presences.add(room.kickOccupant(jid, senderRole.getUserAddress(),
                                item.elementTextTrim("reason")));
                    }
                } else {
                    reply.setError(PacketError.Condition.bad_request);
                }
            } catch (UserNotFoundException e) {
                // Do nothing
            }
        }

        // Send the updated presences to the room occupants
        for (Presence presence : presences) {
            room.send(presence);
        }
    }
}

From source file:net.emiva.crossfire.plugin.muc.spi.IQOwnerHandler.java

License:Open Source License

/**
 * Handles the IQ packet sent by an owner of the room. Possible actions are:
 * <ul>/*from ww  w.  ja va 2  s.  co  m*/
 * <li>Return the list of owners</li>
 * <li>Return the list of admins</li>
 * <li>Change user's affiliation to owner</li>
 * <li>Change user's affiliation to admin</li>
 * <li>Change user's affiliation to member</li>
 * <li>Change user's affiliation to none</li>
 * <li>Destroy the room</li>
 * <li>Return the room configuration within a dataform</li>
 * <li>Update the room configuration based on the sent dataform</li>
 * </ul>
 *
 * @param packet the IQ packet sent by an owner of the room.
 * @param role the role of the user that sent the packet.
 * @throws ForbiddenException if the user does not have enough permissions (ie. is not an owner).
 * @throws ConflictException If the room was going to lose all of its owners.
 */
@SuppressWarnings("unchecked")
public void handleIQ(IQ packet, MUCRole role)
        throws ForbiddenException, ConflictException, CannotBeInvitedException {
    // Only owners can send packets with the namespace "http://jabber.org/protocol/muc#owner"
    if (MUCRole.Affiliation.owner != role.getAffiliation()) {
        throw new ForbiddenException();
    }

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

    // Analyze the action to perform based on the included element
    Element formElement = element.element(QName.get("x", "jabber:x:data"));
    if (formElement != null) {
        handleDataFormElement(role, formElement);
    } else {
        Element destroyElement = element.element("destroy");
        if (destroyElement != null) {
            if (((MultiUserChatServiceImpl) room.getMUCService()).getMUCDelegate() != null) {
                if (!((MultiUserChatServiceImpl) room.getMUCService()).getMUCDelegate()
                        .destroyingRoom(room.getName(), role.getUserAddress())) {
                    // Delegate said no, reject destroy request.
                    throw new ForbiddenException();
                }
            }

            room.destroyRoom(destroyElement.attributeValue("jid"), destroyElement.elementTextTrim("reason"));
        } else {
            List<Element> itemsList = element.elements("item");
            if (!itemsList.isEmpty()) {
                handleItemsElement(itemsList, role, reply);
            } else {
                // If no element was included in the query element then answer the
                // configuration form
                if (!element.elementIterator().hasNext()) {
                    refreshConfigurationFormValues();
                    reply.setChildElement(probeResult.createCopy());
                }
                // An unknown and possibly incorrect element was included in the query
                // element so answer a BAD_REQUEST error
                else {
                    reply.setChildElement(packet.getChildElement().createCopy());
                    reply.setError(PacketError.Condition.bad_request);
                }
            }
        }
    }
    if (reply.getTo() != null) {
        // Send a reply only if the sender of the original packet was from a real JID. (i.e. not
        // a packet generated locally)
        router.route(reply);
    }
}

From source file:net.emiva.crossfire.plugin.muc.spi.LocalMUCUser.java

License:Open Source License

/**
 * This method does all packet routing in the chat server. Packet routing is actually very
 * simple://from  w w  w .  j  av a 2  s.co  m
 * 
 * <ul>
 * <li>Discover the room the user is talking to (server packets are dropped)</li>
 * <li>If the room is not registered and this is a presence "available" packet, try to join the
 * room</li>
 * <li>If the room is registered, and presence "unavailable" leave the room</li>
 * <li>Otherwise, rewrite the sender address and send to the room.</li>
 * </ul>
 * 
 * @param packet The packet to route.
 */
public void process(Message packet) {
    // Ignore messages of type ERROR sent to a room 
    if (Message.Type.error == packet.getType()) {
        return;
    }
    lastPacketTime = System.currentTimeMillis();
    JID recipient = packet.getTo();
    String group = recipient.getNode();
    if (group == null) {
        // Ignore packets to the groupchat server
        // In the future, we'll need to support TYPE_IQ queries to the server for MUC
        Log.info(LocaleUtils.getLocalizedString("muc.error.not-supported") + " " + packet.toString());
    } else {
        MUCRole role = roles.get(group);
        if (role == null) {
            if (server.hasChatRoom(group)) {
                boolean declinedInvitation = false;
                Element userInfo = null;
                if (Message.Type.normal == packet.getType()) {
                    // An user that is not an occupant could be declining an invitation
                    userInfo = packet.getChildElement("x", "http://jabber.org/protocol/muc#user");
                    if (userInfo != null && userInfo.element("decline") != null) {
                        // A user has declined an invitation to a room
                        // WARNING: Potential fraud if someone fakes the "from" of the
                        // message with the JID of a member and sends a "decline"
                        declinedInvitation = true;
                    }
                }
                if (declinedInvitation) {
                    Element info = userInfo.element("decline");
                    server.getChatRoom(group).sendInvitationRejection(new JID(info.attributeValue("to")),
                            info.elementTextTrim("reason"), packet.getFrom());
                } else {
                    // The sender is not an occupant of the room
                    sendErrorPacket(packet, PacketError.Condition.not_acceptable);
                }
            } else {
                // The sender is not an occupant of a NON-EXISTENT room!!!
                sendErrorPacket(packet, PacketError.Condition.recipient_unavailable);
            }
        } else {
            // Check and reject conflicting packets with conflicting roles
            // In other words, another user already has this nickname
            if (!role.getUserAddress().equals(packet.getFrom())) {
                sendErrorPacket(packet, PacketError.Condition.conflict);
            } else {
                try {
                    if (packet.getSubject() != null && packet.getSubject().trim().length() > 0
                            && Message.Type.groupchat == packet.getType()
                            && (packet.getBody() == null || packet.getBody().trim().length() == 0)) {
                        // An occupant is trying to change the room's subject
                        role.getChatRoom().changeSubject(packet, role);

                    } else {
                        // An occupant is trying to send a private, send public message,
                        // invite someone to the room or reject an invitation
                        Message.Type type = packet.getType();
                        String resource = packet.getTo().getResource();
                        if (resource == null || resource.trim().length() == 0) {
                            resource = null;
                        }
                        if (resource == null && Message.Type.groupchat == type) {
                            // An occupant is trying to send a public message
                            role.getChatRoom().sendPublicMessage(packet, role);
                        } else if (resource != null
                                && (Message.Type.chat == type || Message.Type.normal == type)) {
                            // An occupant is trying to send a private message
                            role.getChatRoom().sendPrivatePacket(packet, role);
                        } else if (resource == null && Message.Type.normal == type) {
                            // An occupant could be sending an invitation or declining an
                            // invitation
                            Element userInfo = packet.getChildElement("x",
                                    "http://jabber.org/protocol/muc#user");
                            // Real real real UGLY TRICK!!! Will and MUST be solved when
                            // persistence will be added. Replace locking with transactions!
                            LocalMUCRoom room = (LocalMUCRoom) role.getChatRoom();
                            if (userInfo != null && userInfo.element("invite") != null) {
                                // An occupant is sending invitations

                                // Try to keep the list of extensions sent together with the
                                // message invitation. These extensions will be sent to the
                                // invitees.
                                @SuppressWarnings("unchecked")
                                List<Element> extensions = new ArrayList<Element>(
                                        packet.getElement().elements());
                                extensions.remove(userInfo);
                                // Send invitations to invitees
                                for (Iterator it = userInfo.elementIterator("invite"); it.hasNext();) {
                                    Element info = (Element) it.next();
                                    JID jid = new JID(info.attributeValue("to"));

                                    // Add the user as a member of the room if the room is
                                    // members only
                                    if (room.isMembersOnly()) {
                                        room.addMember(jid, null, role);
                                    }

                                    // Send the invitation to the invitee
                                    room.sendInvitation(jid, info.elementTextTrim("reason"), role, extensions);
                                }
                            } else if (userInfo != null && userInfo.element("decline") != null) {
                                // An occupant has declined an invitation
                                Element info = userInfo.element("decline");
                                room.sendInvitationRejection(new JID(info.attributeValue("to")),
                                        info.elementTextTrim("reason"), packet.getFrom());
                            } else {
                                sendErrorPacket(packet, PacketError.Condition.bad_request);
                            }
                        } else {
                            sendErrorPacket(packet, PacketError.Condition.bad_request);
                        }
                    }
                } catch (ForbiddenException e) {
                    sendErrorPacket(packet, PacketError.Condition.forbidden);
                } catch (NotFoundException e) {
                    sendErrorPacket(packet, PacketError.Condition.recipient_unavailable);
                } catch (ConflictException e) {
                    sendErrorPacket(packet, PacketError.Condition.conflict);
                } catch (CannotBeInvitedException e) {
                    sendErrorPacket(packet, PacketError.Condition.not_acceptable);
                } catch (IllegalArgumentException e) {
                    sendErrorPacket(packet, PacketError.Condition.jid_malformed);
                }
            }
        }
    }
}

From source file:net.emiva.crossfire.plugin.muc.spi.LocalMUCUser.java

License:Open Source License

public void process(Presence packet) {
    // Ignore presences of type ERROR sent to a room
    if (Presence.Type.error == packet.getType()) {
        return;/*from  ww  w . jav  a  2 s .c  o m*/
    }
    lastPacketTime = System.currentTimeMillis();
    JID recipient = packet.getTo();
    String group = recipient.getNode();
    if (group != null) {
        MUCRole role = roles.get(group);
        if (role == 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 (packet.isAvailable()) {
                    try {
                        // Get or create the room
                        MUCRoom room = server.getChatRoom(group, packet.getFrom());
                        // User must support MUC in order to create a room
                        Element mucInfo = packet.getChildElement("x", "http://jabber.org/protocol/muc");
                        HistoryRequest historyRequest = null;
                        String password = null;
                        // Check for password & requested history if client supports MUC
                        if (mucInfo != null) {
                            password = mucInfo.elementTextTrim("password");
                            if (mucInfo.element("history") != null) {
                                historyRequest = new HistoryRequest(mucInfo);
                            }
                        }
                        // The user joins the room
                        role = room.joinRoom(recipient.getResource().trim(), password, historyRequest, this,
                                packet.createCopy());
                        // If the client that created the room is non-MUC compliant then
                        // unlock the room thus creating an "instant" room
                        if (mucInfo == null && room.isLocked() && !room.isManuallyLocked()) {
                            room.unlock(role);
                        }
                    } catch (UnauthorizedException e) {
                        sendErrorPacket(packet, PacketError.Condition.not_authorized);
                    } catch (ServiceUnavailableException e) {
                        sendErrorPacket(packet, PacketError.Condition.service_unavailable);
                    } catch (UserAlreadyExistsException e) {
                        sendErrorPacket(packet, PacketError.Condition.conflict);
                    } catch (RoomLockedException e) {
                        sendErrorPacket(packet, PacketError.Condition.recipient_unavailable);
                    } catch (ForbiddenException e) {
                        sendErrorPacket(packet, PacketError.Condition.forbidden);
                    } catch (RegistrationRequiredException e) {
                        sendErrorPacket(packet, PacketError.Condition.registration_required);
                    } catch (ConflictException e) {
                        sendErrorPacket(packet, PacketError.Condition.conflict);
                    } catch (NotAcceptableException e) {
                        sendErrorPacket(packet, PacketError.Condition.not_acceptable);
                    } catch (NotAllowedException e) {
                        sendErrorPacket(packet, PacketError.Condition.not_allowed);
                    }
                } else {
                    // TODO: send error message to user (can't send presence to group you
                    // haven't joined)
                }
            } else {
                if (packet.isAvailable()) {
                    // A resource is required in order to join a room
                    sendErrorPacket(packet, PacketError.Condition.bad_request);
                }
                // TODO: send error message to user (can't send packets to group you haven't
                // joined)
            }
        } else {
            // Check and reject conflicting packets with conflicting roles
            // In other words, another user already has this nickname
            if (!role.getUserAddress().equals(packet.getFrom())) {
                sendErrorPacket(packet, PacketError.Condition.conflict);
            } else {
                if (Presence.Type.unavailable == packet.getType()) {
                    try {
                        // TODO Consider that different nodes can be creating and processing this presence at the same time (when remote node went down)
                        removeRole(group);
                        role.getChatRoom().leaveRoom(role);
                    } catch (Exception e) {
                        Log.error(e.getMessage(), e);
                    }
                } else {
                    try {
                        String resource = (recipient.getResource() == null
                                || recipient.getResource().trim().length() == 0 ? null
                                        : recipient.getResource().trim());
                        if (resource == null || role.getNickname().equalsIgnoreCase(resource)) {
                            // Occupant has changed his availability status
                            role.getChatRoom().presenceUpdated(role, packet);
                        } else {
                            // Occupant has changed his nickname. Send two presences
                            // to each room occupant

                            // Check if occupants are allowed to change their nicknames
                            if (!role.getChatRoom().canChangeNickname()) {
                                sendErrorPacket(packet, PacketError.Condition.not_acceptable);
                            }
                            // Answer a conflic error if the new nickname is taken
                            else if (role.getChatRoom().hasOccupant(resource)) {
                                sendErrorPacket(packet, PacketError.Condition.conflict);
                            } else {
                                // Send "unavailable" presence for the old nickname
                                Presence presence = role.getPresence().createCopy();
                                // Switch the presence to OFFLINE
                                presence.setType(Presence.Type.unavailable);
                                presence.setStatus(null);
                                // Add the new nickname and status 303 as properties
                                Element frag = presence.getChildElement("x",
                                        "http://jabber.org/protocol/muc#user");
                                frag.element("item").addAttribute("nick", resource);
                                frag.addElement("status").addAttribute("code", "303");
                                role.getChatRoom().send(presence);

                                // Send availability presence for the new nickname
                                String oldNick = role.getNickname();
                                role.getChatRoom().nicknameChanged(role, packet, oldNick, resource);
                            }
                        }
                    } catch (Exception e) {
                        Log.error(LocaleUtils.getLocalizedString("admin.error"), e);
                    }
                }
            }
        }
    }
}

From source file:net.sf.eclipsecs.core.config.meta.MetadataFactory.java

License:Open Source License

@SuppressWarnings("unchecked")
private static void processModules(Element groupElement, RuleGroupMetadata groupMetadata,
        ResourceBundle metadataBundle) throws CheckstylePluginException {

    List<Element> moduleElements = groupElement.elements(XMLTags.RULE_METADATA_TAG);
    for (Element moduleEl : moduleElements) {

        // default severity
        String defaultSeverity = moduleEl.attributeValue(XMLTags.DEFAULT_SEVERITY_TAG);
        Severity severity = defaultSeverity == null || defaultSeverity.trim().length() == 0
                ? getDefaultSeverity()/*from  w  w w  . j  a v a  2s  . c om*/
                : Severity.valueOf(defaultSeverity);

        String name = moduleEl.attributeValue(XMLTags.NAME_TAG).trim();
        name = localize(name, metadataBundle);
        String internalName = moduleEl.attributeValue(XMLTags.INTERNAL_NAME_TAG).trim();

        String parentName = moduleEl.attributeValue(XMLTags.PARENT_TAG) != null
                ? moduleEl.attributeValue(XMLTags.PARENT_TAG).trim()
                : null;
        boolean hidden = Boolean.valueOf(moduleEl.attributeValue(XMLTags.HIDDEN_TAG)).booleanValue();
        boolean hasSeverity = !"false".equals(moduleEl.attributeValue(XMLTags.HAS_SEVERITY_TAG));
        boolean deletable = !"false".equals(moduleEl.attributeValue(XMLTags.DELETABLE_TAG)); //$NON-NLS-1$
        boolean isSingleton = Boolean.valueOf(moduleEl.attributeValue(XMLTags.IS_SINGLETON_TAG)).booleanValue();

        // create rule metadata
        RuleMetadata module = new RuleMetadata(name, internalName, parentName, severity, hidden, hasSeverity,
                deletable, isSingleton, groupMetadata);
        groupMetadata.getRuleMetadata().add(module);

        // register internal name
        sRuleMetadata.put(internalName, module);

        // process description
        String description = moduleEl.elementTextTrim(XMLTags.DESCRIPTION_TAG);
        description = localize(description, metadataBundle);
        module.setDescription(description);

        // process properties
        processProperties(moduleEl, module, metadataBundle);

        // process alternative names
        for (Element altNameEl : (List<Element>) moduleEl.elements(XMLTags.ALTERNATIVE_NAME_TAG)) {

            String alternativeName = altNameEl.attributeValue(XMLTags.INTERNAL_NAME_TAG);

            // register alternative name
            sAlternativeNamesMap.put(alternativeName, module);
            module.addAlternativeName(alternativeName);
        }

        // process quickfixes
        for (Element quickfixEl : (List<Element>) moduleEl.elements(XMLTags.QUCKFIX_TAG)) {

            String quickfixClassName = quickfixEl.attributeValue(XMLTags.CLASSNAME_TAG);
            module.addQuickfix(quickfixClassName);
        }

        // process message keys
        for (Element quickfixEl : (List<Element>) moduleEl.elements(XMLTags.MESSAGEKEY_TAG)) {

            String messageKey = quickfixEl.attributeValue(XMLTags.KEY_TAG);
            module.addMessageKey(messageKey);
        }
    }
}

From source file:net.sf.eclipsecs.core.config.meta.MetadataFactory.java

License:Open Source License

@SuppressWarnings("unchecked")
private static void processProperties(Element moduleElement, RuleMetadata moduleMetadata,
        ResourceBundle metadataBundle) throws CheckstylePluginException {

    List<Element> propertyElements = moduleElement.elements(XMLTags.PROPERTY_METADATA_TAG);
    for (Element propertyEl : propertyElements) {

        ConfigPropertyType type = ConfigPropertyType.valueOf(propertyEl.attributeValue(XMLTags.DATATYPE_TAG));

        String name = propertyEl.attributeValue(XMLTags.NAME_TAG).trim();
        String defaultValue = StringUtils.trim(propertyEl.attributeValue(XMLTags.DEFAULT_VALUE_TAG));
        String overrideDefaultValue = StringUtils
                .trim(propertyEl.attributeValue(XMLTags.DEFAULT_VALUE_OVERRIDE_TAG));

        ConfigPropertyMetadata property = new ConfigPropertyMetadata(type, name, defaultValue,
                overrideDefaultValue);//w w w  . j ava2s.  c o  m

        moduleMetadata.getPropertyMetadata().add(property);

        // get description
        String description = propertyEl.elementTextTrim(XMLTags.DESCRIPTION_TAG);
        description = localize(description, metadataBundle);
        property.setDescription(description);

        // get property enumeration values
        Element enumEl = propertyEl.element(XMLTags.ENUMERATION_TAG);
        if (enumEl != null) {
            String optionProvider = enumEl.attributeValue(XMLTags.OPTION_PROVIDER);
            if (optionProvider != null) {

                try {
                    Class<?> providerClass = CheckstylePlugin.getDefault().getAddonExtensionClassLoader()
                            .loadClass(optionProvider);

                    if (IOptionProvider.class.isAssignableFrom(providerClass)) {

                        IOptionProvider provider = (IOptionProvider) providerClass.newInstance();
                        property.getPropertyEnumeration().addAll(provider.getOptions());
                    } else if (Enum.class.isAssignableFrom(providerClass)) {

                        EnumSet<?> values = EnumSet.allOf((Class<Enum>) providerClass);
                        for (Enum e : values) {
                            property.getPropertyEnumeration().add(e.name().toLowerCase());
                        }
                    }
                } catch (ClassNotFoundException e) {
                    CheckstylePluginException.rethrow(e);
                } catch (InstantiationException e) {
                    CheckstylePluginException.rethrow(e);
                } catch (IllegalAccessException e) {
                    CheckstylePluginException.rethrow(e);
                }
            }

            // get explicit enumeration option values
            for (Element optionEl : (List<Element>) enumEl.elements(XMLTags.PROPERTY_VALUE_OPTIONS_TAG)) {
                property.getPropertyEnumeration().add(optionEl.attributeValue(XMLTags.VALUE_TAG));
            }
        }
    }
}

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

License:Apache License

@Override
public Shell execute(Element node, Shell shell) throws Exception {
    if (node.attribute("source") == null) {
        throw new ActionException("?");
    }//from www  . j a  va  2  s.  c o m
    String source = node.attributeValue("source").toUpperCase();
    DBConnection connection = null;
    try {
        connection = new DBConnection(source);
    } catch (DBException ex) {
        if (node.elements("mapping") != null) {
            node.elements("mapping").clear();
        }
        throw new ActionException(ex.getMessage());
    }
    Iterator mappings = node.elements("mapping").iterator();
    while (mappings.hasNext()) {
        Element mapping = (Element) mappings.next();
        String formName = mapping.attributeValue("form");
        String consist = mapping.attributeValue("consist");
        ArrayList<String> colNames = new ArrayList<String>();
        ArrayList<String> colsValue = new ArrayList<String>();
        // ??form?mapping cols??
        if (mapping.elements("enty") == null) {
            throw new ActionException("form mapping");
        }
        Iterator enties = mapping.elements("enty").iterator();
        while (enties.hasNext()) {
            Element entry = (Element) enties.next();
            colNames.add(entry.elementTextTrim("name"));
            colsValue.add(entry.elementTextTrim("content"));
        }
        // ??
        for (Iterator i = shell.getResources().iterator(); i.hasNext();) {
            Resource res = (Resource) i.next();
            // content
            ArrayList<String> colsValueConverted = new ArrayList<String>();
            Iterator<String> valueIterator = colsValue.iterator();
            while (valueIterator.hasNext()) {
                ArrayList<String> valueConverted = PatternHelper.convertAll(valueIterator.next(), res, shell);
                // ? $[xx,xx]
                colsValueConverted.add(valueConverted.get(0));
            }
            // consist?.??
            if (consist != null) {
                int pos = colNames.indexOf(consist);
                if (pos == -1) {
                    Log4j.getInstance().error("Consist???");
                }
                try {
                    String keys[] = { consist };
                    String values[] = { colsValueConverted.get(pos) };
                    if (connection.existed(formName, keys, values)) {
                        Log4j.getInstance()
                                .debug(shell.getName() + " DB : Consist " + " [VAL]:" + values[0]);
                        continue;
                    }
                } catch (DBException ex) {
                    Log4j.getInstance().error(ex.getMessage());
                }
            }

            try {
                int id = connection.insert(formName, colNames, colsValueConverted);
                if (id > 0) {
                    res.putParam("id", +id + "");
                    Log4j.getInstance()
                            .debug(shell.getName() + "[ID] " + id + "  " + formName + " ?");
                }
            } catch (DBException ex) {
                Log4j.getInstance().error(ex.getMessage());
            }

        }
        Log4j.getInstance().info(shell.getName() + "DB " + formName + " ?");
        mapping.detach();
    }

    connection.getConnection().close();

    return shell;
}

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

License:Apache License

@Override
public Shell execute(Element node, Shell shell) throws Exception {
    HttpClient client = (HttpClient) shell.getClient();
    shell.setClient(client);/* w w  w.  j  a  v a2s  .  co m*/
    // url
    if (node.element("url") == null) {
        throw new ActionException("FetchNode ?url");
    }
    String url = node.elementTextTrim("url");
    // Method
    if (node.element("method") != null) {
        String requestMethod = node.element("method").getData().toString();
        Log4j.getInstance().info("RequestMethod " + requestMethod);
        if (requestMethod.toLowerCase().equals("post")) {
            client.setRequestType(HttpClient.REQ_TYPE.POST);
        }
        node.element("method").detach();
    }
    String content = "";
    // ?body
    if (node.element("content") != null) {
        content = node.elementTextTrim("content");
        node.element("content").detach();
    }
    String charset = "auto";
    // ?
    if (node.element("charset") != null) {
        charset = node.elementTextTrim("charset");
        node.element("charset").detach();
    }
    // 
    if (node.element("timeout") != null) {
        int timemillons = Integer.parseInt(node.element("timeout").getData().toString());
        client.setResponseTimeOut(timemillons);
        client.setConnectTimeOut(timemillons);
        node.element("timeout").detach();
    }
    // ??cookie
    if (node.element("cookie") != null) {
        boolean cookieEnable = node.element("cookie").getData().toString().equals("true");
        client.enableCookie(cookieEnable);
        node.element("cookie").detach();
    }
    // ?param?
    if (node.element("params") != null) {
        List params = node.element("params").elements("param");
        for (Iterator i = params.iterator(); i.hasNext();) {
            Element e = (Element) i.next();
            if (e.element("key") == null || e.element("value") == null) {
                throw new ActionException("Param??keyvalue");
            }
            String key = e.element("key").getData().toString();
            String value = e.element("value").getData().toString();
            client.setRequestProperty(key, value);
        }
        node.element("params").detach();
    }
    Cookies cookie = new Cookies();
    String cookieString = "";
    // ?cookie?
    if (node.element("cookies") != null) {
        // cookie-string,?
        if (node.element("cookies").element("cookie-string") != null) {
            cookieString = node.element("cookies").elementTextTrim("cookie-string");
            cookie.fromString(node.element("cookies").elementTextTrim("cookie-string"));
        }
        List params = node.element("cookies").elements("cookie");
        for (Iterator i = params.iterator(); i.hasNext();) {
            Element e = (Element) i.next();
            if (e.element("key") == null || e.element("value") == null) {
                throw new ActionException("cookie??keyvalue");
            }
            String key = e.element("key").getData().toString();
            String value = e.element("value").getData().toString();
            cookie.put(key, value);
        }
        client.setCookie(cookie);
        Log4j.getInstance().debug("Cookie Setted " + cookie.toString());
        node.element("cookies").detach();
    }

    LinkedList<Resource> resnew = new LinkedList();
    // url??
    Log4j.getInstance().debug("Source Url : " + url);
    node.element("url").detach();
    // ?
    for (Iterator i = shell.getResources().iterator(); i.hasNext();) {
        Resource res = (Resource) i.next();
        PatternGroup pg = new PatternGroup(res, shell);
        pg.addNewString("url", url, true);
        pg.addNewString("content", content, true);
        pg.addNewString("cookie-string", cookieString, true);

        String newurl = url;
        ArrayList<HashMap<String, String>> pgs = pg.convert();
        // ?
        for (int pgi = 0, pgsize = pgs.size(); pgi < pgsize; pgi++) {
            HashMap<String, String> hash = pgs.get(pgi);
            newurl = hash.get("url");
            // url?
            try {
                new URL(newurl);
                // ?baseUrl ??
                if (!(shell.getBaseUrl().equals("*") || newurl.indexOf(shell.getBaseUrl()) != -1)) {
                    Log4j.getInstance().warn("URI " + newurl + " Doesn't Match BaseURL");
                    continue;
                }
            } catch (MalformedURLException ex) {
                Log4j.getInstance().warn("URI " + ex.getMessage());
            }
            Log4j.getInstance().info("Fetching " + newurl);
            // ???
            try {
                client.setUrl(newurl);
                // POST?,content
                if (client.getRequestType().toString().equals(HttpClient.REQ_TYPE.POST.toString())) {
                    client.setPostString(hash.get("content"));
                }
                // ??
                client.setCharset(charset);
                // ?cookie
                if (!hash.get("cookie-string").equals("")) {
                    cookie.fromString(hash.get("cookie-string"));
                    client.setCookie(cookie);
                }
                byte[] data = client.exec();
                Resource newResNode = new Resource();
                newResNode.putParam("bytedata", data);
                newResNode.putParam("charset", client.getCharset());
                newResNode.putParam("url", newurl);
                newResNode.putParam("cookie", client.getCookieString());
                resnew.add(newResNode);
            } catch (Exception ex) {
                Log4j.getInstance().warn("Fetch Error " + ex.getMessage());
            }
        }
        shell.setResources(resnew);
    }
    return shell;
}