Example usage for org.dom4j Element getNamespaceURI

List of usage examples for org.dom4j Element getNamespaceURI

Introduction

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

Prototype

String getNamespaceURI();

Source Link

Document

Returns the URI mapped to the namespace of this element if one exists otherwise an empty String is returned.

Usage

From source file:org.frogx.service.games.hearts.Match.java

License:Open Source License

public void setConfiguration(Collection<Element> config) {
    log.info("setConfiguration: init");
    Element formElement = null;

    if (config != null && !config.isEmpty())
        formElement = config.iterator().next();

    if (config != null && !config.isEmpty() && config.size() != 1)
        throw new GameConfigurationException();

    if (formElement != null) {
        if (!formElement.getName().equals("x") || !formElement.getNamespaceURI().equals("jabber:x:data"))
            throw new GameConfigurationException();
    }//from w  ww  . java 2 s .  c  o  m

    status = Status.inactive;
    if (formElement != null) {
        int newBots = this.botUsers;
        try {
            DataForm completedForm = new DataForm(formElement);

            if (!DataForm.Type.submit.equals(completedForm.getType()))
                throw new GameConfigurationException();

            List<String> values;
            FormField field;
            field = completedForm.getField("mug/hearts#config_bot");
            if (field != null) {
                values = field.getValues();
                if (!values.isEmpty())
                    newBots = Integer.parseInt(values.get(0));
            }
            log.info("setConfiguration" + config.toString());
        } catch (Exception e) {
            reset();
            calculateStateElement();
            throw new GameConfigurationException();
        }
        botUsers = newBots;
    }
    reset();
    calculateStateElement();
}

From source file:org.ifsoft.rayo.RayoComponent.java

License:Apache License

@Override
synchronized protected IQ handleIQGet(IQ iq) throws Exception {

    Log.info("RayoComponent handleIQGet \n" + iq.toString());

    final Element element = iq.getChildElement();
    final String namespace = element.getNamespaceURI();

    try {/*from   w  w  w.j  a v  a2s  . c  om*/

        if (RAYO_HANDSET.equals(namespace)) {
            IQ reply = null;

            Object object = handsetProvider.fromXML(element);

            if (object instanceof OnHookCommand) {
                OnHookCommand command = (OnHookCommand) object;
                reply = handleOnOffHookCommand(command, iq);

            } else if (object instanceof OffHookCommand) {
                OffHookCommand command = (OffHookCommand) object;
                reply = handleOnOffHookCommand(command, iq);

            } else if (object instanceof MuteCommand) {
                reply = handleMuteCommand((MuteCommand) object, iq);

            } else if (object instanceof UnmuteCommand) {
                reply = handleMuteCommand((UnmuteCommand) object, iq);

            } else if (object instanceof HoldCommand) {
                reply = handleHoldCommand((HoldCommand) object, iq);

            } else if (object instanceof PrivateCommand) {
                reply = handlePrivateCommand(object, iq);

            } else if (object instanceof PublicCommand) {
                reply = handlePrivateCommand(object, iq);

            } else if (object instanceof CreateSpeakerCommand) {
                reply = handleCreateSpeakerCommand(object, iq);

            } else if (object instanceof DestroySpeakerCommand) {
                reply = handleDestroySpeakerCommand(object, iq);

            } else if (object instanceof PutOnSpeakerCommand) {
                reply = handleOnOffSpeakerCommand(object, iq, true);

            } else if (object instanceof TakeOffSpeakerCommand) {
                reply = handleOnOffSpeakerCommand(object, iq, false);

            } else if (object instanceof TalkCommand) {
                reply = handleOnOffTalkCommand(object, iq, false);

            } else if (object instanceof UntalkCommand) {
                reply = handleOnOffTalkCommand(object, iq, true);
            }
            return reply;
        }

        if (RAYO_RECORD.equals(namespace)) {
            IQ reply = null;

            Object object = recordProvider.fromXML(element);

            if (object instanceof Record) {
                reply = handleRecord((Record) object, iq);

            } else if (object instanceof PauseCommand) {
                reply = handlePauseRecordCommand(true, iq);

            } else if (object instanceof ResumeCommand) {
                reply = handlePauseRecordCommand(false, iq);
            }
            return reply;
        }

        if (RAYO_SAY.equals(namespace)) {
            IQ reply = null;

            Object object = sayProvider.fromXML(element);

            if (object instanceof Say) {
                reply = handleSay((Say) object, iq);

            } else if (object instanceof PauseCommand) {
                reply = handlePauseSayCommand(true, iq);

            } else if (object instanceof ResumeCommand) {
                reply = handlePauseSayCommand(false, iq);
            }
            return reply;
        }

        if (RAYO_CORE.equals(namespace)) {
            IQ reply = null;

            Object object = rayoProvider.fromXML(element);

            if (object instanceof JoinCommand) {
                reply = handleJoinCommand((JoinCommand) object, iq);

            } else if (object instanceof UnjoinCommand) {
                reply = handleUnjoinCommand((UnjoinCommand) object, iq);

            } else if (object instanceof AcceptCommand) {
                reply = handleAcceptCommand((AcceptCommand) object, iq);

            } else if (object instanceof AnswerCommand) {
                reply = handleAnswerCommand((AnswerCommand) object, iq);

            } else if (object instanceof HangupCommand) {
                reply = handleHangupCommand(iq);

            } else if (object instanceof RejectCommand) {
                // implemented as hangup on client

            } else if (object instanceof RedirectCommand) {
                RedirectCommand redirect = (RedirectCommand) object;
                DialCommand dial = new DialCommand();
                dial.setTo(redirect.getTo());
                dial.setFrom(new URI("xmpp:" + iq.getFrom()));
                dial.setHeaders(redirect.getHeaders());

                reply = handleDialCommand((DialCommand) dial, iq, true);

            } else if (object instanceof DialCommand) {
                reply = handleDialCommand((DialCommand) object, iq, false);

            } else if (object instanceof StopCommand) {

            } else if (object instanceof DtmfCommand) {
                reply = handleDtmfCommand((DtmfCommand) object, iq);

            } else if (object instanceof DestroyMixerCommand) {

            }

            return reply;
        }
        return null; // feature not implemented.

    } catch (Exception e) {
        e.printStackTrace();

        final IQ reply = IQ.createResultIQ(iq);
        reply.setError(PacketError.Condition.internal_server_error);
        return reply;
    }
}

From source file:org.intalio.tempo.workflow.fds.core.UserProcessMessageConvertor.java

License:Open Source License

/**
 * Converts a SOAP message from a user process to the WorkflowProcesses
 * format. <br>//  w  ww  .j av a 2s .com
 * The conversion is done in-place. The passed <code>Document</code>
 * instance gets converted to the Workflow Processes format and its previous
 * format is lost.
 * 
 * @param message
 *            The SOAP message from a user process to convert to the
 *            Workflow Processes format.
 * @throws MessageFormatException
 *             If the specified message has an invalid format. Note that if
 *             this exception is thrown, <code>message</code> may have
 *             already been partly processed and therefore should be assumed
 *             to be corrupted.
 */
@SuppressWarnings("unchecked")
public void convertMessage(Document message) throws MessageFormatException, AxisFault {
    FormDispatcherConfiguration config = FormDispatcherConfiguration.getInstance();

    XPath xpath = null;
    xpath = DocumentHelper.createXPath("/soapenv:Envelope/soapenv:Body/soapenv:Fault");
    List<Node> fault = xpath.selectNodes(message);
    if (fault.size() != 0)
        throw new RuntimeException(fault.toString());

    // Check SOAP action
    xpath = DocumentHelper.createXPath("/soapenv:Envelope/soapenv:Body");
    xpath.setNamespaceURIs(MessageConstants.get_nsMap());
    List<Node> bodyQueryResult = xpath.selectNodes(message);
    if (bodyQueryResult.size() != 0) {
        Element root = (Element) bodyQueryResult.get(0);
        if (root.asXML().indexOf("createTaskRequest") != -1) {
            _soapAction = "createTask";
            xpath = DocumentHelper.createXPath("/soapenv:Envelope/soapenv:Header/addr:Action");
            xpath.setNamespaceURIs(MessageConstants.get_nsMap());
            List<Node> wsaActionQueryResult = xpath.selectNodes(message);
            if (wsaActionQueryResult.size() != 0) {
                Element wsaToElement = (Element) wsaActionQueryResult.get(0);
                wsaToElement.setText(_soapAction);
            } else
                _log.warn("Did not find addr:Action in SOAP header");
        }
    }
    _log.debug("Converted SOAP Action: " + _soapAction);

    /*
     * Change the wsa:To endpoint to Workflow Processes, if a wsa:To header
     * is present.
     */
    xpath = DocumentHelper.createXPath("/soapenv:Envelope/soapenv:Header/addr:To");
    xpath.setNamespaceURIs(MessageConstants.get_nsMap());
    List<Node> wsaToQueryResult = xpath.selectNodes(message);
    if (wsaToQueryResult.size() != 0) {
        Element wsaToElement = (Element) wsaToQueryResult.get(0);
        String workflowProcessesUrl = config.getPxeBaseUrl() + config.getWorkflowProcessesRelativeUrl();
        wsaToElement.setText(workflowProcessesUrl);
    } else
        _log.debug("Did not find addr:To in SOAP header");

    /*
     * Change the session address to be FDS endpoint and retrieve sender
     * endpoint
     */
    xpath = DocumentHelper.createXPath("/soapenv:Envelope/soapenv:Header/intalio:callback/addr:Address");
    xpath.setNamespaceURIs(MessageConstants.get_nsMap());
    List<Node> callbackToQueryResult = xpath.selectNodes(message);
    if (callbackToQueryResult.size() != 0) {
        Element wsaToElement = (Element) callbackToQueryResult.get(0);
        _userProcessEndpoint = wsaToElement.getText();
        wsaToElement.setText(config.getFdsUrl());
    } else
        _log.debug("Did not find intalio:callback/addr:Address in SOAP header");

    /* Next, fetch the user process namespace URI from the task metadata */
    /*
     * 1. fetch the first element of SOAP envelope body.
     */
    List<Node> allSoapBodyElements = DocumentHelper.createXPath("/soapenv:Envelope/soapenv:Body//*")
            .selectNodes(message);
    if (allSoapBodyElements.size() == 0) {
        throw new MessageFormatException("No elements found inside soapenv:Body.");
    }
    Element firstPayloadElement = (Element) allSoapBodyElements.get(0);

    /*
     * 2. fetch its namespace and use it to fetch the userProcessEndpoint
     * and userProcessNamespaceURI element (which should be in the same
     * namespace). If those elements are not found, nothing is reported.
     * This is necessary for converting responses, where this information is
     * not present.
     */
    String messageNamespace = firstPayloadElement.getNamespaceURI();
    _userProcessNamespaceUri = messageNamespace;

    Map<String, String> namespaceURIs = new HashMap<String, String>(MessageConstants.get_nsMap());
    namespaceURIs.put(REQUEST_PREFIX, _userProcessNamespaceUri);

    /*
     * Add session in task meta data so that it can be retrieved when
     * workflow process needs to send a message to the user process
     */
    xpath = DocumentHelper.createXPath("/soapenv:Envelope/soapenv:Header/intalio:callback/intalio:session");
    xpath.setNamespaceURIs(namespaceURIs/* MessageConstants.get_nsMap() */);
    List<Node> sessionQueryResult = xpath.selectNodes(message);
    if (sessionQueryResult.size() != 0) {
        Element wsaToElement = (Element) sessionQueryResult.get(0);
        String session = wsaToElement.getText();
        xpath = DocumentHelper.createXPath("//" + REQUEST_PREFIX + ":taskMetaData");
        xpath.setNamespaceURIs(namespaceURIs/* MessageConstants.get_nsMap() */);
        List<Node> tmdQueryResult = xpath.selectNodes(message);
        Element tmdElement = (Element) tmdQueryResult.get(0);
        Element sessionElement = tmdElement.addElement("session", MessageConstants.IB4P_NS);
        sessionElement.setText(session);
    }

    // retrieve userProcessEndpoint from task meta data
    // or put sender endpoint in task meta data if not defined
    xpath = DocumentHelper
            .createXPath("//" + REQUEST_PREFIX + ":taskMetaData/" + REQUEST_PREFIX + ":userProcessEndpoint");
    xpath.setNamespaceURIs(namespaceURIs/* MessageConstants.get_nsMap() */);
    List<Node> endpointQueryResult = xpath.selectNodes(message);
    if (endpointQueryResult.size() != 0) {
        Element userProcessEndpointElement = (Element) endpointQueryResult.get(0);
        String value = userProcessEndpointElement.getText();
        if (value != null && value.length() > 0)
            _userProcessEndpoint = value;
        else if (_userProcessEndpoint != null) {
            _log.info("User process endpoint is empty in task metadata, adding " + _userProcessEndpoint);
            userProcessEndpointElement.setText(_userProcessEndpoint);
        }
    } else if (_userProcessEndpoint != null) {
        _log.info("User process endpoint is not defined in task metadata, adding " + _userProcessEndpoint);
        xpath = DocumentHelper.createXPath("//" + REQUEST_PREFIX + ":taskMetaData");
        xpath.setNamespaceURIs(namespaceURIs/* MessageConstants.get_nsMap() */);
        List<Node> tmdQueryResult = xpath.selectNodes(message);
        if (tmdQueryResult.size() > 0) {
            Element wsaToElement = (Element) tmdQueryResult.get(0);
            Element nsElement = wsaToElement.addElement("userProcessEndpoint", MessageConstants.IB4P_NS);
            nsElement.setText(_userProcessEndpoint);
        }
    }

    // Add user process namespace to taskmetadata if not already defined
    xpath = DocumentHelper.createXPath(
            "//" + REQUEST_PREFIX + ":taskMetaData/" + REQUEST_PREFIX + ":userProcessNamespaceURI");
    xpath.setNamespaceURIs(namespaceURIs/* MessageConstants.get_nsMap() */);
    List<Node> nsQueryResult = xpath.selectNodes(message);
    if (nsQueryResult.size() == 0 && _userProcessNamespaceUri != null) {
        xpath = DocumentHelper.createXPath("//" + REQUEST_PREFIX + ":taskMetaData");
        xpath.setNamespaceURIs(namespaceURIs/* MessageConstants.get_nsMap() */);
        List<Node> tmdQueryResult = xpath.selectNodes(message);
        if (tmdQueryResult.size() > 0) {
            _log.info("User process namespace is not defined in task metadata, adding "
                    + _userProcessNamespaceUri);
            Element wsaToElement = (Element) tmdQueryResult.get(0);
            Element nsElement = wsaToElement.addElement("userProcessNamespaceURI", MessageConstants.IB4P_NS);
            nsElement.setText(_userProcessNamespaceUri);
        }
    } else {
        Element wsaToElement = (Element) nsQueryResult.get(0);
        if (wsaToElement.getTextTrim().length() == 0) {
            _log.info("User process namespace is empty in task metadata, adding " + _userProcessNamespaceUri);
            wsaToElement.setText(_userProcessNamespaceUri);
        }
    }

    /*
     * Now, change the namespace of all soapenv:Body elements, except the
     * task input and the attachments, to ib4p.
     */
    xpath = DocumentHelper.createXPath("//" + REQUEST_PREFIX + ":taskInput//*");
    xpath.setNamespaceURIs(namespaceURIs/* MessageConstants.get_nsMap() */);
    List<Node> allTaskInputElements = xpath.selectNodes(message);
    xpath = DocumentHelper.createXPath("//" + REQUEST_PREFIX + ":attachments//*");
    xpath.setNamespaceURIs(namespaceURIs/* MessageConstants.get_nsMap() */);
    List<Node> allAttachmentsElements = xpath.selectNodes(message);
    for (int i = 0; i < allSoapBodyElements.size(); ++i) {
        Node node = (Node) allSoapBodyElements.get(i);
        if (!allTaskInputElements.contains(node) && !allAttachmentsElements.contains(node)) {

            Element element = (Element) node;
            element.remove(element.getNamespace());
            element.setQName(QName.get(element.getName(), "ib4p", MessageConstants.IB4P_NS));
        }
    }
}

From source file:org.intalio.tempo.workflow.fds.dispatches.EscalateDispatcher.java

License:Open Source License

public Document dispatchRequest(Document request) throws InvalidInputFormatException {
    Namespace ns = new Namespace(NS_PREFIX, NS_URI);
    Element rootElement = request.getRootElement();
    userProcessNamespace = rootElement.getNamespaceURI();
    userProcessPrefix = rootElement.getNamespacePrefix();
    List nodes = DocumentHelper.createXPath("//*").selectNodes(request);
    for (int i = 0; i < nodes.size(); ++i) {
        Element element = (Element) nodes.get(i);
        element.remove(element.getNamespaceForURI(userProcessNamespace));
        element.setQName(new QName(element.getName(), ns));
    }//from w w  w. ja  va 2 s.  c om

    rootElement.setQName(new QName("escalateTaskRequest", ns));
    // TODO: fix this in VC!
    return request;
}

From source file:org.intalio.tempo.workflow.fds.dispatches.NotifyDispatcher.java

License:Open Source License

public Document dispatchRequest(Document request) throws InvalidInputFormatException {
    Element rootElement = request.getRootElement();
    userProcessNamespace = rootElement.getNamespaceURI();

    Namespace ns = new Namespace("tms", TMS_NS);
    rootElement.setQName(new QName("createTaskRequest", ns));

    Element metadataElement = rootElement.element("metadata");
    metadataElement.setQName(new QName("metadata", ns));
    metadataElement.detach();//from w ww  .  j a va  2s .c  o  m

    Element taskElement = rootElement.addElement("task");
    taskElement.setQName(new QName("task", ns));

    taskElement.add(metadataElement);
    if (metadataElement.selectSingleNode("taskId") == null) {
        Element taskIdElement = metadataElement.addElement(new QName("taskId", ns));
        taskIdElement.setText(generateUID());
    }
    if (metadataElement.selectSingleNode("taskType") == null) {
        Element taskTypeElement = metadataElement.addElement(new QName("taskType", ns));
        taskTypeElement.setText("NOTIFICATION");
    }

    Element inputElement = rootElement.element("input");
    inputElement.setQName(new QName("input", ns));
    //inputElement.addNamespace("fe", userProcessNamespace);
    inputElement.detach();
    taskElement.add(inputElement);

    //TODO remove from TMS. Not needed
    rootElement.addElement("participantToken");

    /*
     * Now, change the namespace the
     * input, to TMS_NS.
     */

    XPath xpath = DocumentHelper.createXPath("/tms:createTaskRequest/tms:task/tms:input//*");
    HashMap map = MessageConstants._nsMap;
    map.put("tms", TMS_NS);
    xpath.setNamespaceURIs(MessageConstants._nsMap);
    List allTaskInputElements = xpath.selectNodes(request);

    xpath = DocumentHelper.createXPath("//*");
    List allBody = xpath.selectNodes(request);
    int size = allBody.size();
    LOG.debug(allTaskInputElements.size() + ":" + size);
    for (int i = 0; i < size; ++i) {
        Node node = (Node) allBody.get(i);
        if (!allTaskInputElements.contains(node)) {
            Element element = (Element) node;
            element.remove(element.getNamespaceForURI(userProcessNamespace));
            element.setQName(new QName(element.getName(), ns));
        }
    }

    return request;
}

From source file:org.jboss.seam.init.Initialization.java

License:LGPL

@SuppressWarnings("unchecked")
private void installComponentFromXmlElement(Element component, String name, String className,
        Properties replacements) throws ClassNotFoundException {
    String installText = component.attributeValue("installed");
    boolean installed = false;
    if (installText == null || "true".equals(replace(installText, replacements))) {
        installed = true;//from ww w.  j av a 2  s  .c  om
    }

    String scopeName = component.attributeValue("scope");
    String jndiName = component.attributeValue("jndi-name");
    String precedenceString = component.attributeValue("precedence");
    int precedence = precedenceString == null ? Install.APPLICATION : Integer.valueOf(precedenceString);
    ScopeType scope = scopeName == null ? null : ScopeType.valueOf(scopeName.toUpperCase());
    String autocreateAttribute = component.attributeValue("auto-create");
    Boolean autoCreate = autocreateAttribute == null ? null : "true".equals(autocreateAttribute);
    String startupAttribute = component.attributeValue("startup");
    Boolean startup = startupAttribute == null ? null : "true".equals(startupAttribute);
    String startupDependsAttribute = component.attributeValue("startupDepends");
    String[] startupDepends = startupDependsAttribute == null ? new String[0]
            : startupDependsAttribute.split(" ");

    if (className != null) {
        Class<?> clazz = getClassUsingImports(className);

        if (name == null) {
            if (!clazz.isAnnotationPresent(Name.class)) {
                throw new IllegalArgumentException(
                        "Component class must have @Name annotation or name must be specified in components.xml: "
                                + clazz.getName());
            }

            name = clazz.getAnnotation(Name.class).value();
        }

        ComponentDescriptor descriptor = new ComponentDescriptor(name, clazz, scope, autoCreate, startup,
                startupDepends, jndiName, installed, precedence);
        addComponentDescriptor(descriptor);
        installedComponentClasses.add(clazz);
    } else if (name == null) {
        throw new IllegalArgumentException("must specify either class or name in <component/> declaration");
    }

    for (Element prop : (List<Element>) component.elements()) {
        String propName = prop.attributeValue("name");
        if (propName == null) {
            propName = prop.getQName().getName();
        }
        String qualifiedPropName = name + '.' + toCamelCase(propName, false);
        properties.put(qualifiedPropName, getPropertyValue(prop, qualifiedPropName, replacements));
    }

    for (Attribute prop : (List<Attribute>) component.attributes()) {
        String attributeName = prop.getName();
        if (isProperty(prop.getNamespaceURI(), attributeName)) {
            String qualifiedPropName = name + '.' + toCamelCase(prop.getQName().getName(), false);
            Conversions.PropertyValue propValue = null;
            try {
                propValue = getPropertyValue(prop, replacements);
                properties.put(qualifiedPropName, propValue);
            } catch (Exception ex) {
                throw new IllegalArgumentException(String.format(
                        "Exception setting property %s on component %s.  Expression %s evaluated to %s.",
                        qualifiedPropName, name, prop.getValue(), propValue), ex);

            }
        }
    }
}

From source file:org.jinglenodes.JingleNodesComponent.java

License:Open Source License

@Override
protected IQ handleIQGet(IQ iq) throws Exception {
    final IQ reply = IQ.createResultIQ(iq);

    final Element element = iq.getChildElement();
    final String namespace = element.getNamespaceURI();

    if (JingleChannelIQ.NAME.equals(element.getName()) && JingleChannelIQ.NAMESPACE.equals(namespace)
            && UDP.equals(element.attributeValue(PROTOCOL))) {
        final Element childElement = iq.getChildElement().createCopy();
        final RelayChannel channel = plugin.createRelayChannel();

        if (channel != null) {

            childElement.addAttribute(HOST, plugin.getPublicIP());
            childElement.addAttribute(LOCAL_PORT, Integer.toString(channel.getPortA()));
            childElement.addAttribute(REMOTE_PORT, Integer.toString(channel.getPortB()));

            reply.setChildElement(childElement);

            Log.debug("Created relay channel {}:{}, {}:{}, {}:{}",
                    new Object[] { HOST, plugin.getPublicIP(), LOCAL_PORT, Integer.toString(channel.getPortA()),
                            REMOTE_PORT, Integer.toString(channel.getPortB()) });

        } else {/*from w ww. jav a2s.co  m*/
            reply.setError(PacketError.Condition.internal_server_error);
        }
        return reply;
    } else if (JingleTrackerIQ.NAME.equals(element.getName()) && JingleTrackerIQ.NAMESPACE.equals(namespace)) {

        final List<TrackerEntry> entries = new ArrayList<TrackerEntry>();
        entries.add(new TrackerEntry(TrackerEntry.Type.relay, TrackerEntry.Policy._roster,
                plugin.getServiceName() + "." + getDomain(), UDP));

        final String elements = getChildElementXML(entries);

        final Element e = DocumentHelper.parseText(elements).getRootElement();

        reply.setChildElement(e);

        return reply;
    }

    return null; // feature not implemented.
}

From source file:org.jitsi.jicofo.xmpp.IQUtils.java

License:LGPL

/**
 * Converts a specific <tt>org.xmpp.packet.iQ</tt> instance into a new
 * <tt>org.jivesoftware.smack.packet.IQ</tt> instance which represents the
 * same stanza./*  ww w. j a  v  a 2  s  .  co m*/
 *
 * @param iq the <tt>org.xmpp.packet.IQ</tt> instance to convert to a new
 * <tt>org.jivesoftware.smack.packet.IQ</tt> instance
 * @return a new <tt>org.jivesoftware.smack.packet.IQ</tt> instance which
 * represents the same stanza as the specified <tt>iq</tt>
 * @throws Exception if anything goes wrong during the conversion
 */
public static org.jivesoftware.smack.packet.IQ convert(org.xmpp.packet.IQ iq) throws Exception {
    Element element = iq.getChildElement();
    IQProvider iqProvider = (IQProvider) ProviderManager.getInstance().getIQProvider(element.getName(),
            element.getNamespaceURI());
    org.jivesoftware.smack.packet.IQ smackIQ = null;

    if (iqProvider != null) {
        XmlPullParserFactory xmlPullParserFactory;

        synchronized (IQUtils.class) {
            if (IQUtils.xmlPullParserFactory == null) {
                IQUtils.xmlPullParserFactory = XmlPullParserFactory.newInstance();
                IQUtils.xmlPullParserFactory.setNamespaceAware(true);
            }
            xmlPullParserFactory = IQUtils.xmlPullParserFactory;
        }

        XmlPullParser parser = xmlPullParserFactory.newPullParser();

        parser.setInput(new StringReader(iq.toXML()));

        int eventType = parser.next();

        if (XmlPullParser.START_TAG == eventType) {
            String name = parser.getName();

            if ("iq".equals(name)) {
                eventType = parser.next();
                if (XmlPullParser.START_TAG == eventType) {
                    smackIQ = iqProvider.parseIQ(parser);

                    if (smackIQ != null) {
                        eventType = parser.getEventType();
                        if (XmlPullParser.END_TAG != eventType) {
                            throw new IllegalStateException(
                                    Integer.toString(eventType) + " != XmlPullParser.END_TAG");
                        }
                    }
                } else {
                    throw new IllegalStateException(
                            Integer.toString(eventType) + " != XmlPullParser.START_TAG");
                }
            } else
                throw new IllegalStateException(name + " != iq");
        } else {
            throw new IllegalStateException(Integer.toString(eventType) + " != XmlPullParser.START_TAG");
        }
    }

    if (smackIQ != null) {
        org.xmpp.packet.JID fromJID = iq.getFrom();

        if (fromJID != null)
            smackIQ.setFrom(fromJID.toString());
        smackIQ.setPacketID(iq.getID());

        org.xmpp.packet.JID toJID = iq.getTo();

        if (toJID != null)
            smackIQ.setTo(toJID.toString());
        smackIQ.setType(convert(iq.getType()));
    }

    return smackIQ;
}

From source file:org.jitsi.jigasi.openfire.CallControlComponent.java

License:LGPL

@Override
public IQ handleIQSet(IQ iq) throws Exception {
    IQ reply = IQ.createResultIQ(iq);/*from  www .  ja v a 2s .c  o  m*/
    String domain = XMPPServer.getInstance().getServerInfo().getXMPPDomain();

    try {
        Log.info("CallControlComponent - handleIQSet\n" + iq);

        Element element = iq.getChildElement();
        String namespace = element.getNamespaceURI();
        String request = element.getName();

        String confJid = null;
        String confId = null;

        if ("dial".equals(request) && "urn:xmpp:rayo:1".equals(namespace)) {
            Log.info("CallControlComponent - Dial");

            String from = element.attributeValue("from");
            String to = element.attributeValue("to");

            for (Iterator i = element.elementIterator("header"); i.hasNext();) {
                Element header = (Element) i.next();
                String name = header.attributeValue("name");
                String value = header.attributeValue("value");

                if ("JvbRoomId".equals(name))
                    confId = value;
                if ("JvbRoomName".equals(name))
                    confJid = value;
            }

            if (confJid == null && confId == null) {
                reply.setError(PacketError.Condition.item_not_found);
                Log.error("No JvbRoomName or JvbRoomId header found");

            } else {

                if (confId == null) {
                    if (conferences.containsKey(confJid)) {
                        confId = conferences.get(confJid);
                    }
                }

                if (confJid == null) {
                    confJid = confId + "@conference."
                            + XMPPServer.getInstance().getServerInfo().getXMPPDomain();
                }

                if (confId != null) {
                    String callId = Long.toHexString(System.currentTimeMillis());

                    Log.info("Got dial request " + from + " -> " + to + " confId " + confId + " callId "
                            + callId);

                    String callResource = "xmpp:" + callId + "@" + getJID();

                    final Element childElement = reply.setChildElement("ref", "urn:xmpp:rayo:1");
                    childElement.addAttribute("uri", (String) "xmpp:" + callId + "@" + getJID());
                    childElement.addAttribute("id", (String) callId);

                    Conference conference = null;

                    for (Conference conf : getVideobridge().getConferences()) {
                        if (conf.getID().equals(confId)) {
                            conference = conf;
                            break;
                        }
                    }

                    if (conference != null) {
                        String username = iq.getFrom().getNode();
                        long startTimestamp = System.currentTimeMillis();

                        makeCall(conference, confJid, to, callId, username, startTimestamp);
                        createCallRecord(username, confJid, to, startTimestamp, 0, "dialed");

                    } else {
                        Log.error("CallControlComponent - can't find conference " + confId);
                        reply.setError(PacketError.Condition.item_not_found);
                    }

                } else {
                    Log.error("CallControlComponent - focus not ready " + confJid);
                    reply.setError(PacketError.Condition.item_not_found);
                }
            }
        }

        else if ("accept".equals(request) && "urn:xmpp:rayo:1".equals(namespace)) {
            Log.info("CallControlComponent - Accept");

            String confName = null;

            for (Iterator i = element.elementIterator("header"); i.hasNext();) {
                Element header = (Element) i.next();
                String name = header.attributeValue("name");
                String value = header.attributeValue("value");

                if ("JvbRoomId".equals(name))
                    confId = value;
                if ("JvbRoomName".equals(name))
                    confName = value;
            }

            if (confId != null && confName != null) {
                Log.info("CallControlComponent - Accept register " + confId + " " + confName);
                conferences.put(confName, confId);

            } else {
                reply.setError(PacketError.Condition.item_not_found);
                Log.error("No JvbRoomName or JvbRoomId header found");
            }
        }

        else if ("hangup".equals(request) && "urn:xmpp:rayo:1".equals(namespace)) {
            Log.info("CallControlComponent - HangUp");
            String callId = iq.getTo().getNode();
            hangupCall(callId);
        }

        else if ("record".equals(request) && "urn:xmpp:rayo:record:1".equals(namespace)) {
            Log.info("CallControlComponent - Record");

            String token = null;
            String state = null;
            String confName = null;

            for (Iterator i = element.elementIterator("hint"); i.hasNext();) {
                Element hint = (Element) i.next();
                String name = hint.attributeValue("name");
                String value = hint.attributeValue("value");

                if ("JvbToken".equals(name))
                    token = value;
                if ("JvbState".equals(name))
                    state = value;
                if ("JvbRoomName".equals(name))
                    confName = value;
            }

            if (token != null && state != null && confName != null) {
                if (conferences.containsKey(confName)) {
                    confId = conferences.get(confName);

                    Conference conference = null;

                    for (Conference conf : getVideobridge().getConferences()) {
                        if (conf.getID().equals(confId)) {
                            conference = conf;
                            break;
                        }
                    }

                    if (conference != null) {
                        recordCall(conference, token, state);

                    } else {
                        Log.error("CallControlComponent - can't find conference " + confId);
                        reply.setError(PacketError.Condition.item_not_found);
                    }
                } else {
                    Log.error("CallControlComponent - focus not ready " + confName);
                    reply.setError(PacketError.Condition.item_not_found);
                }
            } else {
                reply.setError(PacketError.Condition.item_not_found);
                Log.error("No JvbRoomName, JvbToken or JvbState headers found");
            }
        }

        else {
            Log.warn("CallControlComponent - Unknown");
            reply.setError(PacketError.Condition.item_not_found);
        }
    } catch (Exception e) {
        Log.error("CallControlComponent handleIQSet", e);
        reply.setError(PacketError.Condition.internal_server_error);
    }

    return reply;
}

From source file:org.jitsi.videobridge.xmpp.IQUtils.java

License:Apache License

/**
 * Converts a specific <tt>org.xmpp.packet.iQ</tt> instance into a new
 * <tt>org.jivesoftware.smack.packet.IQ</tt> instance which represents the
 * same stanza./*from ww  w .  j  av a 2s.  c o m*/
 *
 * @param iq the <tt>org.xmpp.packet.IQ</tt> instance to convert to a new
 * <tt>org.jivesoftware.smack.packet.IQ</tt> instance
 * @return a new <tt>org.jivesoftware.smack.packet.IQ</tt> instance which
 * represents the same stanza as the specified <tt>iq</tt>
 * @throws Exception if anything goes wrong during the conversion
 */
public static org.jivesoftware.smack.packet.IQ convert(org.xmpp.packet.IQ iq) throws Exception {
    Element element = iq.getChildElement();
    IQProvider iqProvider;

    if (element == null) {
        iqProvider = null;
    } else {
        iqProvider = (IQProvider) ProviderManager.getInstance().getIQProvider(element.getName(),
                element.getNamespaceURI());
    }

    IQ.Type type = iq.getType();
    org.jivesoftware.smack.packet.IQ smackIQ = null;
    org.jivesoftware.smack.packet.XMPPError smackError = null;

    if (iqProvider != null || iq.getError() != null) {
        XmlPullParserFactory xmlPullParserFactory;

        synchronized (IQUtils.class) {
            if (IQUtils.xmlPullParserFactory == null) {
                IQUtils.xmlPullParserFactory = XmlPullParserFactory.newInstance();
                IQUtils.xmlPullParserFactory.setNamespaceAware(true);
            }
            xmlPullParserFactory = IQUtils.xmlPullParserFactory;
        }

        XmlPullParser parser = xmlPullParserFactory.newPullParser();

        parser.setInput(new StringReader(iq.toXML()));

        int eventType = parser.next();

        if (XmlPullParser.START_TAG == eventType) {
            String name = parser.getName();

            if ("iq".equals(name)) {
                do {
                    eventType = parser.next();
                    name = parser.getName();
                    if (XmlPullParser.START_TAG == eventType) {
                        // 7. An IQ stanza of type "error" MAY include the
                        // child element contained in the associated "get"
                        // or "set" and MUST include an <error/> child.
                        if (IQ.Type.error.equals(type) && "error".equals(name)) {
                            smackError = PacketParserUtils.parseError(parser);
                        } else if (smackIQ == null && iqProvider != null) {
                            smackIQ = iqProvider.parseIQ(parser);
                            if (smackIQ != null && XmlPullParser.END_TAG != parser.getEventType()) {
                                throw new IllegalStateException(
                                        Integer.toString(eventType) + " != XmlPullParser.END_TAG");
                            }
                        }
                    } else if ((XmlPullParser.END_TAG == eventType && "iq".equals(name))
                            || (smackIQ != null && smackError != null)
                            || XmlPullParser.END_DOCUMENT == eventType) {
                        break;
                    }
                } while (true);

                eventType = parser.getEventType();
                if (XmlPullParser.END_TAG != eventType) {
                    throw new IllegalStateException(Integer.toString(eventType) + " != XmlPullParser.END_TAG");
                }
            } else {
                throw new IllegalStateException(name + " != iq");
            }
        } else {
            throw new IllegalStateException(Integer.toString(eventType) + " != XmlPullParser.START_TAG");
        }
    }

    // 6. An IQ stanza of type "result" MUST include zero or one child
    // elements.
    // 7. An IQ stanza of type "error" MAY include the child element
    // contained in the associated "get" or "set" and MUST include an
    // <error/> child.
    if (smackIQ == null && (IQ.Type.error.equals(type) || IQ.Type.result.equals(type))) {
        smackIQ = new org.jivesoftware.smack.packet.IQ() {
            @Override
            public String getChildElementXML() {
                return "";
            }
        };
    }

    if (smackIQ != null) {
        // from
        org.xmpp.packet.JID fromJID = iq.getFrom();

        if (fromJID != null)
            smackIQ.setFrom(fromJID.toString());
        // id
        smackIQ.setPacketID(iq.getID());

        // to
        org.xmpp.packet.JID toJID = iq.getTo();

        if (toJID != null)
            smackIQ.setTo(toJID.toString());
        // type
        smackIQ.setType(convert(type));

        if (smackError != null)
            smackIQ.setError(smackError);
    }

    return smackIQ;
}