Java Code Examples for org.dom4j.QName

The following are top voted examples for showing how to use org.dom4j.QName. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: directory-ldap-api   File: ExtendedRequestDsml.java   View source code 6 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public Element toDsml( Element root )
{
    Element element = super.toDsml( root );

    // Request Name
    if ( getDecorated().getRequestName() != null )
    {
        element.addElement( "requestName" ).setText(
            getDecorated().getRequestName() );
    }

    // Request Value        
    Namespace xsdNamespace = new Namespace( "xsd", ParserUtils.XML_SCHEMA_URI );
    Namespace xsiNamespace = new Namespace( "xsi", ParserUtils.XML_SCHEMA_INSTANCE_URI );
    element.getDocument().getRootElement().add( xsdNamespace );
    element.getDocument().getRootElement().add( xsiNamespace );

    Element valueElement = element.addElement( "requestValue" ).addText(
        ParserUtils.base64Encode( getRequestValue() ) );
    valueElement.addAttribute( new QName( "type", xsiNamespace ),
        "xsd:" + ParserUtils.BASE64BINARY );

    return element;
}
 
Example 2
Project: joai-project   File: StructureWalker.java   View source code 6 votes vote down vote up
/**
 *  Tries to resolve give QName into a "top-level" namespace and prefix. If the
 *  there is no prefix and the namespace is the default namespace, assign the
 *  NAMED defaultNamespace.
 *
 * @param  qName          Description of the Parameter
 * @return                Description of the Return Value
 * @exception  Exception  Description of the Exception
 */
private QName resolveQName(QName qName) throws Exception {
	String prefix = qName.getNamespacePrefix();
	String name = qName.getName();
	String uri = qName.getNamespaceURI();
	prtln("\n\t resolveQName: ", 1);
	prtln("\t\t name: " + name, 1);
	prtln("\t\t prefix: " + prefix, 1);
	prtln("\t\t uri: " + uri, 1);
	Namespace topLevelNS = namespaces.getNSforUri(uri);
	if (topLevelNS == null) {
		prtlnErr("ERROR: resolveQName could not find top-level namespace for " + uri);
		return null;
	}
	else if (topLevelNS == namespaces.getDefaultNamespace()) {
		topLevelNS = namespaces.getNamedDefaultNamespace();
	}

	return df.createQName(name, topLevelNS);
}
 
Example 3
Project: joai-project   File: StructureWalker.java   View source code 6 votes vote down vote up
/**
 *  Resolve qualified name against top-level namespace registry
 *
 * @param  name  NOT YET DOCUMENTED
 * @return       NOT YET DOCUMENTED
 */
private Element createChildElement(String name) {
	prtln("\n createChildElement() name: " + name, 1);
	Namespace ns = getCurrentNamespace();
	prtln("\t currentNamespace -- " + ns.getPrefix() + ": " + ns.getURI(), 1);
	Element child = null;
	if (ns == null || !namespaceEnabled) {
		child = df.createElement(name);
	}
	else {
		QName baseQName = df.createQName(name, ns);
		try {
			child = df.createElement(resolveQName(baseQName));
		} catch (Exception e) {
			prtlnErr("createChildElement error: " + e.getMessage());
			e.printStackTrace();
			return null;
		}
	}
	prtln("   ... child: " + child.asXML(), 1);
	return child;
}
 
Example 4
Project: apache-archiva   File: XMLReader.java   View source code 6 votes vote down vote up
/**
 * Remove namespaces from element recursively.
 */
@SuppressWarnings("unchecked")
public void removeNamespaces( Element elem )
{
    elem.setQName( QName.get( elem.getName(), Namespace.NO_NAMESPACE, elem.getQualifiedName() ) );

    Node n;

    Iterator<Node> it = elem.elementIterator();
    while ( it.hasNext() )
    {
        n = it.next();

        switch ( n.getNodeType() )
        {
            case Node.ATTRIBUTE_NODE:
                ( (Attribute) n ).setNamespace( Namespace.NO_NAMESPACE );
                break;
            case Node.ELEMENT_NODE:
                removeNamespaces( (Element) n );
                break;
        }
    }
}
 
Example 5
Project: androidpn-server   File: NotificationManager.java   View source code 6 votes vote down vote up
/**
 * 创建一个新的通知IQ,并返回它。
 * 
 * @param imageUrl
 */
private IQ createNotificationIQ(String id, String apiKey, String title,
		String message, String uri, String imageUrl) {
	// Random random = new Random();
	// String id = Integer.toHexString(random.nextInt());
	// String id = String.valueOf(System.currentTimeMillis());

	Element notification = DocumentHelper.createElement(QName.get(
			"notification", NOTIFICATION_NAMESPACE));
	notification.addElement("id").setText(id);
	notification.addElement("apiKey").setText(apiKey);
	notification.addElement("title").setText(title);
	notification.addElement("message").setText(message);
	notification.addElement("uri").setText(uri);
	notification.addElement("imageUrl").setText(imageUrl);

	IQ iq = new IQ();
	iq.setType(IQ.Type.set);
	iq.setChildElement(notification);

	return iq;
}
 
Example 6
Project: dls-repository-stack   File: StructureWalker.java   View source code 6 votes vote down vote up
/**
 *  Tries to resolve give QName into a "top-level" namespace and prefix. If the
 *  there is no prefix and the namespace is the default namespace, assign the
 *  NAMED defaultNamespace.
 *
 * @param  qName          Description of the Parameter
 * @return                Description of the Return Value
 * @exception  Exception  Description of the Exception
 */
private QName resolveQName(QName qName) throws Exception {
	String prefix = qName.getNamespacePrefix();
	String name = qName.getName();
	String uri = qName.getNamespaceURI();
	prtln("\n\t resolveQName: ", 1);
	prtln("\t\t name: " + name, 1);
	prtln("\t\t prefix: " + prefix, 1);
	prtln("\t\t uri: " + uri, 1);
	Namespace topLevelNS = namespaces.getNSforUri(uri);
	if (topLevelNS == null) {
		prtlnErr("ERROR: resolveQName could not find top-level namespace for " + uri);
		return null;
	}
	else if (topLevelNS == namespaces.getDefaultNamespace()) {
		topLevelNS = namespaces.getNamedDefaultNamespace();
	}

	return DocumentHelper.createQName(name, topLevelNS);
}
 
Example 7
Project: dls-repository-stack   File: StructureWalker.java   View source code 6 votes vote down vote up
/**
 *  Resolve qualified name against top-level namespace registry
 *
 * @param  name  NOT YET DOCUMENTED
 * @return       NOT YET DOCUMENTED
 */
private Element createChildElement(String name) {
	prtln("\n createChildElement() name: " + name, 1);
	Namespace ns = getCurrentNamespace();
	prtln("\t currentNamespace -- " + ns.getPrefix() + ": " + ns.getURI(), 1);
	Element child = null;
	if (ns == null || !namespaceEnabled) {
		child = DocumentHelper.createElement(name);
	}
	else {
		QName baseQName = DocumentHelper.createQName(name, ns);
		try {
			child = DocumentHelper.createElement(resolveQName(baseQName));
		} catch (Exception e) {
			prtlnErr("createChildElement error: " + e.getMessage());
			e.printStackTrace();
			return null;
		}
	}
	prtln("   ... child: " + child.asXML(), 1);
	return child;
}
 
Example 8
Project: Intercloud   File: ResultSet.java   View source code 6 votes vote down vote up
/**
 * Generates a Result Set Management 'set' element that describes the parto
 * of the result set that was generated. You typically would use the List
 * that was returned by {@link #applyRSMDirectives(Element)} as an argument
 * to this method.
 * 
 * @param returnedResults
 *            The subset of Results that is returned by the current query.
 * @return An Element named 'set' that can be included in the result IQ
 *         stanza, which returns the subset of results.
 */
public Element generateSetElementFromResults(List<E> returnedResults) {
	if (returnedResults == null) {
		throw new IllegalArgumentException(
				"Argument 'returnedResults' cannot be null.");
	}
	final Element setElement = DocumentHelper.createElement(QName.get(
			"set", ResultSet.NAMESPACE_RESULT_SET_MANAGEMENT));
	// the size element contains the size of this entire result set.
	setElement.addElement("count").setText(String.valueOf(size()));

	// if the query wasn't a 'count only' query, add two more elements
	if (returnedResults.size() > 0) {
		final Element firstElement = setElement.addElement("first");
		firstElement.addText(returnedResults.get(0).getUID());
		firstElement.addAttribute("index", String
				.valueOf(indexOf(returnedResults.get(0))));

		setElement.addElement("last").addText(
				returnedResults.get(returnedResults.size() - 1).getUID());
	}

	return setElement;
}
 
Example 9
Project: Intercloud   File: Roster.java   View source code 6 votes vote down vote up
/**
 * Returns an unmodifiable copy of the {@link Item Items} in the roster packet.
 *
 * @return an unmodifable copy of the {@link Item Items} in the roster packet.
 */
@SuppressWarnings("unchecked")
public Collection<Item> getItems() {
    Collection<Item> items = new ArrayList<Item>();
    Element query = element.element(new QName("query", Namespace.get("jabber:iq:roster")));
    if (query != null) {
        for (Iterator<Element> i=query.elementIterator("item"); i.hasNext(); ) {
            Element item = i.next();
            String jid = item.attributeValue("jid");
            String name = item.attributeValue("name");
            String ask = item.attributeValue("ask");
            String subscription = item.attributeValue("subscription");
            Collection<String> groups = new ArrayList<String>();
            for (Iterator<Element> j=item.elementIterator("group"); j.hasNext(); ) {
                Element group = j.next();
                groups.add(group.getText().trim());
            }
            Ask askStatus = ask == null ? null : Ask.valueOf(ask);
            Subscription subStatus = subscription == null ?
                    null : Subscription.valueOf(subscription);
            items.add(new Item(new JID(jid), name, askStatus, subStatus, groups));
        }
    }
    return Collections.unmodifiableCollection(items);
}
 
Example 10
Project: Intercloud   File: IQ.java   View source code 6 votes vote down vote up
/**
 * Returns a {@link PacketExtension} on the first element found in this packet's
 * child element for the specified <tt>name</tt> and <tt>namespace</tt> or <tt>null</tt> if
 * none was found. If the IQ packet does not have a child element then <tt>null</tt>
 * will be returned.<p>
 *
 * Note: packet extensions on IQ packets are only for use in specialized situations.
 * In most cases, you should only need to set the child element of the IQ.
 *
 * @param name the child element name.
 * @param namespace the child element namespace.
 * @return a PacketExtension on the first element found in this packet for the specified
 *         name and namespace or <tt>null</tt> if none was found.
 */
@SuppressWarnings("unchecked")
public PacketExtension getExtension(String name, String namespace) {
    Element childElement = getChildElement();
    if (childElement == null) {
        return null;
    }
    // Search for extensions in the child element
    List<Element> extensions = childElement.elements(QName.get(name, namespace));
    if (!extensions.isEmpty()) {
        Class<? extends PacketExtension> extensionClass = PacketExtension.getExtensionClass(name, namespace);
        if (extensionClass != null) {
            try {
                Constructor<? extends PacketExtension> constructor = extensionClass.getDeclaredConstructor(new Class[]{
                    Element.class});
                return constructor.newInstance(new Object[]{
                    extensions.get(0)});
            }
            catch (Exception e) {
                Log.warn("Packet extension (name "+name+", namespace "+namespace+") cannot be found.", e);
            }
        }
    }
    return null;
}
 
Example 11
Project: Intercloud   File: PacketError.java   View source code 6 votes vote down vote up
/**
 * Sets the text description of the error. Optionally, a language code
 * can be specified to indicate the language of the description.
 *
 * @param text the text description of the error.
 * @param lang the language code of the description, or <tt>null</tt> to specify
 *      no language code.
 */
public void setText(String text, String lang) {
    Element textElement = element.element("text");
    // If text is null, clear the text.
    if (text == null) {
        if (textElement != null) {
            element.remove(textElement);
        }
        return;
    }

    if (textElement == null) {
        textElement = docFactory.createElement("text", ERROR_NAMESPACE);
        if (lang != null) {
            textElement.addAttribute(QName.get("lang", "xml",
                    "http://www.w3.org/XML/1998/namespace"), lang);
        }
        element.add(textElement);
    }
    textElement.setText(text);
}
 
Example 12
Project: Intercloud   File: StreamError.java   View source code 6 votes vote down vote up
/**
 * Sets the text description of the error. Optionally, a language code
 * can be specified to indicate the language of the description.
 *
 * @param text the text description of the error.
 * @param language the language code of the description, or <tt>null</tt> to specify
 *      no language code.
 */
public void setText(String text, String language) {
    Element textElement = element.element("text");
    // If text is null, clear the text.
    if (text == null) {
        if (textElement != null) {
            element.remove(textElement);
        }
        return;
    }

    if (textElement == null) {
        textElement = docFactory.createElement("text", ERROR_NAMESPACE);
        if (language != null) {
            textElement.addAttribute(QName.get("lang", "xml",
                    "http://www.w3.org/XML/1998/namespace"), language);
        }
        element.add(textElement);
    }
    textElement.setText(text);
}
 
Example 13
Project: Intercloud   File: Packet.java   View source code 6 votes vote down vote up
/**
 * Returns a {@link PacketExtension} on the first element found in this packet
 * for the specified <tt>name</tt> and <tt>namespace</tt> or <tt>null</tt> if
 * none was found.
 *
 * @param name the child element name.
 * @param namespace the child element namespace.
 * @return a PacketExtension on the first element found in this packet for the specified
 *         name and namespace or null if none was found.
 */
@SuppressWarnings("unchecked")
public PacketExtension getExtension(String name, String namespace) {
    List<Element> extensions = element.elements(QName.get(name, namespace));
    if (!extensions.isEmpty()) {
        Class<? extends PacketExtension> extensionClass = PacketExtension.getExtensionClass(name, namespace);
        // If a specific PacketExtension implementation has been registered, use that.
        if (extensionClass != null) {
            try {
                Constructor<? extends PacketExtension> constructor = extensionClass.getDeclaredConstructor(Element.class);
                return constructor.newInstance(extensions.get(0));
            }
            catch (Exception e) {
                Log.warn("Packet extension (name "+name+", namespace "+namespace+") cannot be found.", e);
            }
        }
        // Otherwise, use a normal PacketExtension.
        else {
            return new PacketExtension(extensions.get(0));
        }
    }
    return null;
}
 
Example 14
Project: AndroidXMLToJava   File: AX2JClassTranslator.java   View source code 6 votes vote down vote up
public void addAttribute(QName name, AX2JMethod method, int methodType) {
    AX2JAttribute attribute = findAttribute(name);
    if (attribute == null) {
        attribute = new AX2JAttribute(name, type);
        attributeList.add(attribute);
    }

    AX2JMethod oldMethod = findMethod(method);
    if (oldMethod != null) {
        method = oldMethod;
    } else {
        methodList.add(method);
    }

    if (method.findAttribute(attribute) == null) {
        method.addRelativeAttribute(attribute);
    }
    if (attribute.findMethod(method) == null) {
        attribute.addRelativeMethod(method, methodType);
    }
}
 
Example 15
Project: ec2-plugin   File: SignalRequest.java   View source code 6 votes vote down vote up
@Override
protected void construct() {
    try {
        defaultHeader().action(new URI("http://schemas.microsoft.com/wbem/wsman/1/windows/shell/Command"))
        .resourceURI(new URI("http://schemas.microsoft.com/wbem/wsman/1/windows/shell/cmd")).shellId(shellId);

        Element body = DocumentHelper.createElement(QName.get("Signal", Namespaces.NS_WIN_SHELL)).addAttribute(
                                                                                                               "CommandId",
                                                                                                               commandId);

        body.addElement(QName.get("Code", Namespaces.NS_WIN_SHELL))
        .addText("http://schemas.microsoft.com/wbem/wsman/1/windows/shell/signal/terminate");
        setBody(body);
    } catch (URISyntaxException e) {
        throw new RuntimeException("Error while building request content", e);
    }
}
 
Example 16
Project: Openfire-connectionmanager   File: HttpSession.java   View source code 6 votes vote down vote up
/**
 * Returns the stream features which are available for this session.
 *
 * @return the stream features which are available for this session.
 */
public Collection<Element> getAvailableStreamFeaturesElements() {
    List<Element> elements = new ArrayList<Element>();

    if (getStatus() != Session.STATUS_AUTHENTICATED) {
        Element sasl = connectionManager.getServerSurrogate().getSASLMechanismsElement(this);
    	if (true || sasl != null) {
    		elements.add(sasl);
    	}
    }

    Element bind = DocumentHelper.createElement(new QName("bind",
            new Namespace("", "urn:ietf:params:xml:ns:xmpp-bind")));
    elements.add(bind);

    Element session = DocumentHelper.createElement(new QName("session",
            new Namespace("", "urn:ietf:params:xml:ns:xmpp-session")));
    elements.add(session);
    return elements;
}
 
Example 17
Project: community-edition-old   File: TestAbstractListItemsEndpointTest.java   View source code 6 votes vote down vote up
/**
 * ALF-19833: MacOS: Could not save to SharePoint
 */
@Test
public void canGetListUsingCorrectListAndSiteName() throws Exception
{
    VtiSoapRequest soapRequest = Mockito.mock(VtiSoapRequest.class);
    VtiSoapResponse soapResponse = new VtiSoapResponse(new MockHttpServletResponse());//Mockito.mock(VtiSoapResponse.class);
    Element requestElement = Mockito.mock(Element.class);
    SimpleNamespaceContext nc = Mockito.mock(SimpleNamespaceContext.class);

    Element rootElement = new DefaultElement(QName.get("root", "lists", "some://uri"));
    when(soapRequest.getDocument()).thenReturn(new DefaultDocument(rootElement));
    
    // Invoke the method under test.
    listItemsEndpoint.executeListActionDetails(soapRequest, soapResponse,
                "my-site", "documentLibrary", requestElement, nc);
    
    // Check the condition this test is for.
    verify(listHandler).getList("documentLibrary", "my-site");
}
 
Example 18
Project: g3server   File: BaseTransport.java   View source code 6 votes vote down vote up
/**
 * Handle version request.
 *
 * @param packet An IQ packet in the iq version namespace.
 * @return A list of IQ packets to be returned to the user.
 */
private List<Packet> handleIQVersion(IQ packet) {
    List<Packet> reply = new ArrayList<Packet>();

    if (packet.getType() == IQ.Type.get) {
        IQ result = IQ.createResultIQ(packet);
        Element query = DocumentHelper.createElement(QName.get("query", NameSpace.IQ_VERSION));
        query.addElement("name").addText("Openfire " + this.getDescription());
        query.addElement("version").addText(XMPPServer.getInstance().getServerInfo().getVersion().getVersionString() + " - " + this.getVersionString());
        query.addElement("os").addText(System.getProperty("os.name"));
        result.setChildElement(query);
        reply.add(result);
    }

    return reply;
}
 
Example 19
Project: openfire   File: SettingsManager.java   View source code 6 votes vote down vote up
public void setState(Workgroup workgroup, WorkgroupSettings workgroupSettings, QName namespace) {
    this.workgroupSettings = workgroupSettings;
    this.workgroup = workgroup;
    this.namespace = namespace;

    try {
        final Element element = workgroupSettings.get(workgroup.getJID().toBareJID(), DocumentHelper.createElement(namespace));
        final List list = element.elements();

        final Iterator iter = list.iterator();
        while (iter.hasNext()) {
            Element el = (Element)iter.next();
            addToSettings(el);
        }
    }
    catch (Exception ex) {
        Log.error(ex.getMessage(), ex);   
    }
}
 
Example 20
Project: Openfire   File: PubSubEngine.java   View source code 6 votes vote down vote up
private void getDefaultNodeConfiguration(PubSubService service, IQ iq,
                                         Element childElement, Element defaultElement) {
    String type = defaultElement.attributeValue("type");
    type = type == null ? "leaf" : type;

    boolean isLeafType = "leaf".equals(type);
    DefaultNodeConfiguration config = service.getDefaultNodeConfiguration(isLeafType);
    if (config == null) {
        // Service does not support the requested node type so return an error
        Element pubsubError = DocumentHelper.createElement(
                QName.get("unsupported", "http://jabber.org/protocol/pubsub#errors"));
        pubsubError.addAttribute("feature", isLeafType ? "leaf" : "collections");
        sendErrorPacket(iq, PacketError.Condition.feature_not_implemented, pubsubError);
        return;
    }

    // Return data form containing default node configuration
    IQ reply = IQ.createResultIQ(iq);
    Element replyChildElement = childElement.createCopy();
    reply.setChildElement(replyChildElement);
    replyChildElement.element("default").add(config.getConfigurationForm().getElement());
    router.route(reply);
}
 
Example 21
Project: Openfire   File: ResultSet.java   View source code 6 votes vote down vote up
/**
 * Generates a Result Set Management 'set' element that describes the parto
 * of the result set that was generated. You typically would use the List
 * that was returned by {@link #applyRSMDirectives(Element)} as an argument
 * to this method.
 * 
 * @param returnedResults
 *            The subset of Results that is returned by the current query.
 * @return An Element named 'set' that can be included in the result IQ
 *         stanza, which returns the subset of results.
 */
public Element generateSetElementFromResults(List<E> returnedResults) {
    if (returnedResults == null) {
        throw new IllegalArgumentException(
                "Argument 'returnedResults' cannot be null.");
    }
    final Element setElement = DocumentHelper.createElement(QName.get(
            "set", ResultSet.NAMESPACE_RESULT_SET_MANAGEMENT));
    // the size element contains the size of this entire result set.
    setElement.addElement("count").setText(String.valueOf(size()));

    // if the query wasn't a 'count only' query, add two more elements
    if (returnedResults.size() > 0) {
        final Element firstElement = setElement.addElement("first");
        firstElement.addText(returnedResults.get(0).getUID());
        firstElement.addAttribute("index", String
                .valueOf(indexOf(returnedResults.get(0))));

        setElement.addElement("last").addText(
                returnedResults.get(returnedResults.size() - 1).getUID());
    }

    return setElement;
}
 
Example 22
Project: tinder   File: StreamError.java   View source code 6 votes vote down vote up
/**
 * Sets the text description of the error. Optionally, a language code
 * can be specified to indicate the language of the description.
 *
 * @param text the text description of the error.
 * @param language the language code of the description, or <tt>null</tt> to specify
 *      no language code.
 */
public void setText(String text, String language) {
    Element textElement = element.element("text");
    // If text is null, clear the text.
    if (text == null) {
        if (textElement != null) {
            element.remove(textElement);
        }
        return;
    }

    if (textElement == null) {
        textElement = docFactory.createElement("text", ERROR_NAMESPACE);
        if (language != null) {
            textElement.addAttribute(QName.get("lang", "xml",
                    "http://www.w3.org/XML/1998/namespace"), language);
        }
        element.add(textElement);
    }
    textElement.setText(text);
}
 
Example 23
Project: Openfire   File: SASLAuthentication.java   View source code 6 votes vote down vote up
public static Element getSASLMechanismsElement( ClientSession session )
{
    final Element result = DocumentHelper.createElement( new QName( "mechanisms", new Namespace( "", SASL_NAMESPACE ) ) );
    for (String mech : getSupportedMechanisms()) {
        if (mech.equals("EXTERNAL")) {
            boolean trustedCert = false;
            if (session.isSecure()) {
                final Connection connection   = ( (LocalClientSession) session ).getConnection();
                final TrustStore trustStore   = connection.getConfiguration().getTrustStore();
                trustedCert = trustStore.isTrusted( connection.getPeerCertificates() );
            }
            if ( !trustedCert ) {
                continue; // Do not offer EXTERNAL.
            }
        }
        final Element mechanism = result.addElement("mechanism");
        mechanism.setText(mech);
    }
    return result;
}
 
Example 24
Project: Openfire   File: SASLAuthentication.java   View source code 6 votes vote down vote up
public static Element getSASLMechanismsElement( LocalIncomingServerSession session )
{
    final Element result = DocumentHelper.createElement( new QName( "mechanisms", new Namespace( "", SASL_NAMESPACE ) ) );
    if (session.isSecure()) {
        final Connection connection   = session.getConnection();
        final TrustStore trustStore   = connection.getConfiguration().getTrustStore();
        final X509Certificate trusted = trustStore.getEndEntityCertificate( session.getConnection().getPeerCertificates() );

        boolean haveTrustedCertificate = trusted != null;
        if (trusted != null && session.getDefaultIdentity() != null) {
            haveTrustedCertificate = verifyCertificate(trusted, session.getDefaultIdentity());
        }
        if (haveTrustedCertificate) {
            // Offer SASL EXTERNAL only if TLS has already been negotiated and the peer has a trusted cert.
            final Element mechanism = result.addElement("mechanism");
            mechanism.setText("EXTERNAL");
        }
    }
    return result;
}
 
Example 25
Project: Openfire   File: Forwarded.java   View source code 6 votes vote down vote up
private void populate(Element copy, Date delay, JID delayFrom) {

        copy.setQName(QName.get("message", "jabber:client"));

        for (Object element : copy.elements()) {
            if (element instanceof Element) {
                Element el = (Element) element;
                // Only set the "jabber:client" namespace if the namespace is empty (otherwise the resulting xml would look like <body xmlns=""/>)
                if ("".equals(el.getNamespace().getStringValue())) {
                    el.setQName(QName.get(el.getName(), "jabber:client"));
                }
            }
        }
        if (delay != null) {
            Element delayInfo = element.addElement("delay", "urn:xmpp:delay");
            delayInfo.addAttribute("stamp", XMPPDateTimeFormat.format(delay));
            if (delayFrom != null) {
                // Set the Full JID as the "from" attribute
                delayInfo.addAttribute("from", delayFrom.toString());
            }
        }
        element.add(copy);
    }
 
Example 26
Project: openfire   File: ResultSet.java   View source code 6 votes vote down vote up
/**
 * Generates a Result Set Management 'set' element that describes the parto
 * of the result set that was generated. You typically would use the List
 * that was returned by {@link #applyRSMDirectives(Element)} as an argument
 * to this method.
 * 
 * @param returnedResults
 *            The subset of Results that is returned by the current query.
 * @return An Element named 'set' that can be included in the result IQ
 *         stanza, which returns the subset of results.
 */
public Element generateSetElementFromResults(List<E> returnedResults) {
	if (returnedResults == null) {
		throw new IllegalArgumentException(
				"Argument 'returnedResults' cannot be null.");
	}
	final Element setElement = DocumentHelper.createElement(QName.get(
			"set", ResultSet.NAMESPACE_RESULT_SET_MANAGEMENT));
	// the size element contains the size of this entire result set.
	setElement.addElement("count").setText(String.valueOf(size()));

	// if the query wasn't a 'count only' query, add two more elements
	if (returnedResults.size() > 0) {
		final Element firstElement = setElement.addElement("first");
		firstElement.addText(returnedResults.get(0).getUID());
		firstElement.addAttribute("index", String
				.valueOf(indexOf(returnedResults.get(0))));

		setElement.addElement("last").addText(
				returnedResults.get(returnedResults.size() - 1).getUID());
	}

	return setElement;
}
 
Example 27
Project: Openfire   File: BaseTransport.java   View source code 6 votes vote down vote up
/**
 * Handle version request.
 *
 * @param packet An IQ packet in the iq version namespace.
 * @return A list of IQ packets to be returned to the user.
 */
private List<Packet> handleIQVersion(IQ packet) {
    List<Packet> reply = new ArrayList<Packet>();

    if (packet.getType() == IQ.Type.get) {
        IQ result = IQ.createResultIQ(packet);
        Element query = DocumentHelper.createElement(QName.get("query", NameSpace.IQ_VERSION));
        query.addElement("name").addText("Openfire " + this.getDescription());
        query.addElement("version").addText(XMPPServer.getInstance().getServerInfo().getVersion().getVersionString() + " - " + this.getVersionString());
        query.addElement("os").addText(System.getProperty("os.name"));
        result.setChildElement(query);
        reply.add(result);
    }

    return reply;
}
 
Example 28
Project: Openfire   File: QueryRequest.java   View source code 6 votes vote down vote up
public QueryRequest(Element queryElement, JID archive) {

        this.archive = archive;

        if (queryElement.attribute("queryid") != null)
        {
            this.queryid = queryElement.attributeValue("queryid");
        }

        Element xElement = queryElement.element(QName.get("x", DataForm.NAMESPACE));
        if(xElement != null) {
            this.dataForm = new DataForm(xElement);
        }

        Element setElement = queryElement.element(QName.get("set", XmppResultSet.NAMESPACE));
        if (setElement != null)
        {
            resultSet = new XmppResultSet(setElement);
        }

    }
 
Example 29
Project: Openfire   File: ListRequest.java   View source code 6 votes vote down vote up
public ListRequest(Element listElement)
{
    if (listElement.attribute("with") != null)
    {
        this.with = listElement.attributeValue("with");
    }
    if (listElement.attribute("start") != null)
    {
        this.start = XmppDateUtil.parseDate(listElement.attributeValue("start"));
    }
    if (listElement.attribute("end") != null)
    {
        this.end = XmppDateUtil.parseDate(listElement.attributeValue("end"));
    }

    Element setElement = listElement.element(QName.get("set", XmppResultSet.NAMESPACE));
    if (setElement != null)
    {
        resultSet = new XmppResultSet(setElement);
    }
}
 
Example 30
Project: Openfire-connectionmanager   File: HttpSessionManager.java   View source code 6 votes vote down vote up
/**
 * Forwards a client request, which is related to a session, to the server. A connection is
 * created and queued up in the provided session. When a connection reaches the top of a queue
 * any pending packets bound for the client will be forwarded to the client through the
 * connection.
 *
 * @param rid the unique, sequential, requestID sent from the client.
 * @param session the HTTP session of the client that made the request.
 * @param isSecure true if the request was made over a secure channel, HTTPS, and false if it
 * was not.
 * @param rootNode the XML body of the request.
 * @return the created HTTP connection.
 *
 * @throws HttpBindException for several reasons: if the encoding inside of an auth packet is
 * not recognized by the server, or if the packet type is not recognized.
 * @throws HttpConnectionClosedException if the session is no longer available.
 */
public HttpConnection forwardRequest(long rid, HttpSession session, boolean isSecure,
                                     Element rootNode) throws HttpBindException,
        HttpConnectionClosedException
{
    //noinspection unchecked
    List<Element> elements = rootNode.elements();boolean isPoll = (elements.size() == 0);
	if ("terminate".equals(rootNode.attributeValue("type")))
		isPoll = false;
	else if ("true".equals(rootNode.attributeValue(new QName("restart", rootNode.getNamespaceForPrefix("xmpp")))))
		isPoll = false;
	else if (rootNode.attributeValue("pause") != null)
		isPoll = false;
    HttpConnection connection = session.createConnection(rid, elements, isSecure, isPoll);
    for (Element packet : elements) {
        serverSurrogate.send(packet.asXML(), session.getStreamID());
    }
    return connection;
}
 
Example 31
Project: Openfire   File: SettingsManager.java   View source code 6 votes vote down vote up
public void setState(Workgroup workgroup, WorkgroupSettings workgroupSettings, QName namespace) {
    this.workgroupSettings = workgroupSettings;
    this.workgroup = workgroup;
    this.namespace = namespace;

    try {
        final Element element = workgroupSettings.get(workgroup.getJID().toBareJID(), DocumentHelper.createElement(namespace));
        final List list = element.elements();

        final Iterator iter = list.iterator();
        while (iter.hasNext()) {
            Element el = (Element)iter.next();
            addToSettings(el);
        }
    }
    catch (Exception ex) {
        Log.error(ex.getMessage(), ex);   
    }
}
 
Example 32
Project: g3server   File: ResultSet.java   View source code 6 votes vote down vote up
/**
 * Generates a Result Set Management 'set' element that describes the parto
 * of the result set that was generated. You typically would use the List
 * that was returned by {@link #applyRSMDirectives(Element)} as an argument
 * to this method.
 * 
 * @param returnedResults
 *            The subset of Results that is returned by the current query.
 * @return An Element named 'set' that can be included in the result IQ
 *         stanza, which returns the subset of results.
 */
public Element generateSetElementFromResults(List<E> returnedResults) {
	if (returnedResults == null) {
		throw new IllegalArgumentException(
				"Argument 'returnedResults' cannot be null.");
	}
	final Element setElement = DocumentHelper.createElement(QName.get(
			"set", ResultSet.NAMESPACE_RESULT_SET_MANAGEMENT));
	// the size element contains the size of this entire result set.
	setElement.addElement("count").setText(String.valueOf(size()));

	// if the query wasn't a 'count only' query, add two more elements
	if (returnedResults.size() > 0) {
		final Element firstElement = setElement.addElement("first");
		firstElement.addText(returnedResults.get(0).getUID());
		firstElement.addAttribute("index", String
				.valueOf(indexOf(returnedResults.get(0))));

		setElement.addElement("last").addText(
				returnedResults.get(returnedResults.size() - 1).getUID());
	}

	return setElement;
}
 
Example 33
Project: Androidpn   File: NotificationManager.java   View source code 6 votes vote down vote up
/**
 * Creates a new notification IQ and returns it.
 */
private IQ createNotificationIQ(String apiKey, String title,
        String message, String ticker, String url) {
    Random random = new Random();
    String id = Integer.toHexString(random.nextInt());
    // String id = String.valueOf(System.currentTimeMillis());

    Element notification = DocumentHelper.createElement(QName.get(
            "notification", NOTIFICATION_NAMESPACE));
    notification.addElement("id").setText(id);
    notification.addElement("apiKey").setText(apiKey);
    notification.addElement("title").setText(title);
    notification.addElement("message").setText(message);
    notification.addElement("ticker").setText(ticker);
    notification.addElement("url").setText(url);

    IQ iq = new IQ();
    iq.setType(IQ.Type.set);
    iq.setChildElement(notification);

    return iq;
}
 
Example 34
Project: Androidpn   File: NotificationManager.java   View source code 6 votes vote down vote up
/**
 * Creates a new notification IQ and returns it.
 */
private IQ createNotificationIQ(String apiKey, String title,
        String message, String uri) {
    Random random = new Random();
    String id = Integer.toHexString(random.nextInt());
    // String id = String.valueOf(System.currentTimeMillis());

    Element notification = DocumentHelper.createElement(QName.get(
            "notification", NOTIFICATION_NAMESPACE));
    notification.addElement("id").setText(id);
    notification.addElement("apiKey").setText(apiKey);
    notification.addElement("title").setText(title);
    notification.addElement("message").setText(message);
    notification.addElement("uri").setText(uri);

    IQ iq = new IQ();
    iq.setType(IQ.Type.set);
    iq.setChildElement(notification);

    return iq;
}
 
Example 35
Project: tinder   File: PacketError.java   View source code 6 votes vote down vote up
/**
 * Sets the text description of the error. Optionally, a language code
 * can be specified to indicate the language of the description.
 *
 * @param text the text description of the error.
 * @param lang the language code of the description, or <tt>null</tt> to specify
 *      no language code.
 */
public void setText(String text, String lang) {
    Element textElement = element.element("text");
    // If text is null, clear the text.
    if (text == null) {
        if (textElement != null) {
            element.remove(textElement);
        }
        return;
    }

    if (textElement == null) {
        textElement = docFactory.createElement("text", ERROR_NAMESPACE);
        if (lang != null) {
            textElement.addAttribute(QName.get("lang", "xml",
                    "http://www.w3.org/XML/1998/namespace"), lang);
        }
        element.add(textElement);
    }
    textElement.setText(text);
}
 
Example 36
Project: Androidpn   File: NotificationManager.java   View source code 6 votes vote down vote up
private IQ createNotificationIQ(String apiKey, String title,
        String message, String ticker, String url) {
    // TODO Create an unique id
    String id = String.valueOf(System.currentTimeMillis());

    Element notification = DocumentHelper.createElement(QName.get(
            "notification", "androidpn:iq:notification"));
    notification.addElement("id").setText(id);
    notification.addElement("apiKey").setText(apiKey);
    notification.addElement("title").setText(title);
    notification.addElement("message").setText(message);
    notification.addElement("ticker").setText(ticker);
    notification.addElement("url").setText(url);

    IQ iq = new IQ();
    iq.setType(IQ.Type.set);
    iq.setChildElement(notification);

    return iq;
}
 
Example 37
Project: g3server   File: SettingsManager.java   View source code 6 votes vote down vote up
public void setState(Workgroup workgroup, WorkgroupSettings workgroupSettings, QName namespace) {
    this.workgroupSettings = workgroupSettings;
    this.workgroup = workgroup;
    this.namespace = namespace;

    try {
        final Element element = workgroupSettings.get(workgroup.getJID().toBareJID(), DocumentHelper.createElement(namespace));
        final List list = element.elements();

        final Iterator iter = list.iterator();
        while (iter.hasNext()) {
            Element el = (Element)iter.next();
            addToSettings(el);
        }
    }
    catch (Exception ex) {
        Log.error(ex.getMessage(), ex);   
    }
}
 
Example 38
Project: tinder   File: ResultSet.java   View source code 6 votes vote down vote up
/**
 * Generates a Result Set Management 'set' element that describes the parto
 * of the result set that was generated. You typically would use the List
 * that was returned by {@link #applyRSMDirectives(Element)} as an argument
 * to this method.
 * 
 * @param returnedResults
 *            The subset of Results that is returned by the current query.
 * @return An Element named 'set' that can be included in the result IQ
 *         stanza, which returns the subset of results.
 */
public Element generateSetElementFromResults(List<E> returnedResults) {
	if (returnedResults == null) {
		throw new IllegalArgumentException(
				"Argument 'returnedResults' cannot be null.");
	}
	final Element setElement = DocumentHelper.createElement(QName.get(
			"set", ResultSet.NAMESPACE_RESULT_SET_MANAGEMENT));
	// the size element contains the size of this entire result set.
	setElement.addElement("count").setText(String.valueOf(size()));

	// if the query wasn't a 'count only' query, add two more elements
	if (returnedResults.size() > 0) {
		final Element firstElement = setElement.addElement("first");
		firstElement.addText(returnedResults.get(0).getUID());
		firstElement.addAttribute("index", String
				.valueOf(indexOf(returnedResults.get(0))));

		setElement.addElement("last").addText(
				returnedResults.get(returnedResults.size() - 1).getUID());
	}

	return setElement;
}
 
Example 39
Project: joai-project   File: OsmRecordExporter.java   View source code 5 votes vote down vote up
public void setUrl (String newValue) {
	Element general = (Element)selectSingleNode ("/record/general");
	if (general.element("urlOfRecord") == null) {
		QName qname = DocumentHelper.createQName("urlOfRecord", general.getNamespace());
		general.elements().add (1, DocumentHelper.createElement (qname));
	}
	this.setTextAtPath (url_path, newValue);
}
 
Example 40
Project: joai-project   File: StructureWalker.java   View source code 5 votes vote down vote up
/**
 *  Process an exention element of a DerivedContent model. For extensions (used
 *  in Simple and ComplexContent type definitions, we create a dummy element of
 *  the extension's base type. The dummy element has an attribute of
 *  "extension" so it can be identified and handled properly when it is fed
 *  back into processSchemaElement and expanded as if it were an element of the
 *  baseType.<p>
 *
 *  Finaly the attributes (if any) are processed as if they were defined in the
 *  parent of the parent element, which is the enclosing ComplexType.
 *
 * @param  e              The schema extention element being processed
 * @param  parent         The instanceDoc parent of the extention (a simple or
 *      complexContent element)
 * @exception  Exception  NOT YET DOCUMENTED
 */
private void processExtension(Element e, Element parent) throws Exception {

	String baseType = e.attributeValue("base");
	String parentName = XPathUtils.getNodeName(getPath(parent));

	prtln("\n processExtension() handling extension (baseType: " + baseType + ")", 1);
	prtln(pp(e));

	// create dummy element
	//  embed namespace information into the dummy element so it is available to "isBuiltInType"
	QName qname = df.createQName("element", e.getNamespace());
	Element extElement = df.createElement(qname);

	extElement.addAttribute("type", baseType);
	extElement.addAttribute("extension", "true");
	extElement.addAttribute("name", parentName);

	prtln("\t ... extn element: " + extElement.asXML() + "\n", 1);

	/*
	 *  // print out some DEBUGGING info
	 *  if (parentName.equals("catalog")) {
	 *  prtln("parent name = " + parentName, 1);
	 *  prtln("base = " + baseType, 1);
	 *  prtln("dummy extension element: " + extElement.asXML(), 1);
	 *  }
	 */
	// this (or something like it must be here to catch the extension attributes?
	processSchemaElement(extElement, parent);

	// take care of the attributes of this extention
	for (Iterator i = e.elementIterator(); i.hasNext(); ) {
		Element grandParent = parent.getParent();
		Element childAttribute = (Element) i.next();
		processSchemaElement(childAttribute, parent);
	}
}