Java Code Examples for org.dom4j.QName

The following examples show how to use org.dom4j.QName. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source Project: sailfish-core   Source File: ServiceResource.java    License: Apache License 2.0 6 votes vote down vote up
private Element marshal(IServiceSettings settings) throws Exception {
 BeanMap beanMap = new BeanMap(settings);
 
 DOMElement rootElement = new DOMElement(new QName("settings"));
 
 for (Object key : beanMap.keySet()) {
         Object value = beanMap.get(key);
         if (value != null) {
             DOMElement domElement = new DOMElement(new QName(key.toString()));
             domElement.setText(value.toString());
             rootElement.add(domElement);
         }
    }
 
 return rootElement;
}
 
Example 2
Source Project: directory-ldap-api   Source File: ExtendedRequestDsml.java    License: Apache License 2.0 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 3
private static File createPernsistenceXml(List<Class<?>> classes, File directory) throws Exception {
	Document document = DocumentHelper.createDocument();
	Element persistence = document.addElement("persistence", "http://java.sun.com/xml/ns/persistence");
	persistence.addAttribute(QName.get("schemaLocation", "xsi", "http://www.w3.org/2001/XMLSchema-instance"),
			"http://java.sun.com/xml/ns/persistence  http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd");
	persistence.addAttribute("version", "2.0");
	Element unit = persistence.addElement("persistence-unit");
	unit.addAttribute("name", "enhance");
	for (Class<?> o : classes) {
		Element element = unit.addElement("class");
		element.addText(o.getCanonicalName());
	}
	OutputFormat format = OutputFormat.createPrettyPrint();
	format.setEncoding("UTF-8");
	File file = new File(directory, "persistence.xml");
	XMLWriter writer = new XMLWriter(new FileWriter(file), format);
	writer.write(document);
	writer.close();
	return file;
}
 
Example 4
Source Project: Openfire   Source File: SASLAuthentication.java    License: Apache License 2.0 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 5
Source Project: Openfire   Source File: SASLAuthentication.java    License: Apache License 2.0 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();
                if ( SKIP_PEER_CERT_REVALIDATION_CLIENT.getValue() ) {
                    // Trust that the peer certificate has been validated when TLS got established.
                    trustedCert = connection.getPeerCertificates() != null && connection.getPeerCertificates().length > 0;
                } else {
                    // Re-evaluate the validity of the peer certificate.
                    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 6
Source Project: Openfire   Source File: StanzaIDUtilTest.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Test if {@link StanzaIDUtil.ensureUniqueAndStableStanzaID} adds a stanza-id element
 * with proper 'by' and UUID value if the provided input does not have a 'origin-id'
 * element.
 */
@Test
public void testGeneratesStanzaIDElement() throws Exception
{
    // Setup fixture.
    final Packet input = new Message();
    final JID self = new JID( "foobar" );

    // Execute system under test.
    final Packet result = StanzaIDUtil.ensureUniqueAndStableStanzaID( input, self );

    // Verify results.
    Assert.assertNotNull( result );
    final Element stanzaIDElement = result.getElement().element( QName.get( "stanza-id", "urn:xmpp:sid:0" ) );
    Assert.assertNotNull( stanzaIDElement );
    try
    {
        UUID.fromString( stanzaIDElement.attributeValue( "id" ) );
    }
    catch ( IllegalArgumentException ex )
    {
        Assert.fail();
    }
    assertEquals( self.toString(), stanzaIDElement.attributeValue( "by" ) );
}
 
Example 7
Source Project: Openfire   Source File: Forwarded.java    License: Apache License 2.0 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 8
Source Project: Openfire   Source File: ResultSet.java    License: Apache License 2.0 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
Source Project: Openfire   Source File: HttpSession.java    License: Apache License 2.0 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<>();

    if (getAuthToken() == null) {
        Element sasl = SASLAuthentication.getSASLMechanismsElement(this);
        if (sasl != null) {
            elements.add(sasl);
        }
    }

    if (XMPPServer.getInstance().getIQRegisterHandler().isInbandRegEnabled()) {
        elements.add(DocumentHelper.createElement(new QName("register",
                new Namespace("", "http://jabber.org/features/iq-register"))));
    }
    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")));
    session.addElement("optional");
    elements.add(session);
    return elements;
}
 
Example 10
Source Project: Openfire   Source File: FMUCHandler.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Creates a stanza that represents a room 'join' in a MUC room.
 *
 * @param mucRole Representation of the (local) user that caused the join to be initiated.
 */
// TODO this does not have any FMUC specifics. Must this exist in this class?
private Presence generateJoinStanza( @Nonnull MUCRole mucRole )
{
    Log.debug( "(room: '{}'): Generating a stanza that represents the joining of local user '{}' (as '{}').", room.getJID(), mucRole.getUserAddress(), mucRole.getRoleAddress() );
    final Presence joinStanza = new Presence();
    joinStanza.getElement().addElement(QName.get("x", "http://jabber.org/protocol/muc"));
    final Element mucUser = joinStanza.getElement().addElement(QName.get("x", "http://jabber.org/protocol/muc#user"));
    final Element mucUserItem = mucUser.addElement("item");
    mucUserItem.addAttribute("affiliation", mucRole.getAffiliation().toString());
    mucUserItem.addAttribute("role", mucRole.getRole().toString());

    // Don't include the occupant's JID if the room is semi-anon and the new occupant is not a moderator
    if (!room.canAnyoneDiscoverJID()) {
        if (MUCRole.Role.moderator == mucRole.getRole()) {
            mucUserItem.addAttribute("jid", mucRole.getUserAddress().toString());
        }
        else {
            mucUserItem.addAttribute("jid", null);
        }
    }

    return joinStanza;
}
 
Example 11
Source Project: Openfire   Source File: StanzaIDUtil.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Returns a value that is an appropriate unique and stable stanza ID in
 * context of XEP-0359: it's either the origin-id value, or a UUID.
 *
 * @param packet The stanza for what to return the ID (cannot be null).
 * @return The ID (never null or empty string).
 */
public static String generateUniqueAndStableStanzaID( final Packet packet )
{
    String result = null;

    final Iterator<Element> existingElementIterator = packet.getElement().elementIterator( QName.get( "origin-id", "urn:xmpp:sid:0" ) );
    while (existingElementIterator.hasNext() && (result == null || result.isEmpty() ) )
    {
        final Element element = existingElementIterator.next();
        result = element.attributeValue( "id" );
    }

    if ( result == null || result.isEmpty() ) {
        result = UUID.randomUUID().toString();
        Log.debug( "Using newly generated value '{}' for stanza that has id '{}'.", result, packet.getID() );
    } else {
        Log.debug( "Using origin-id provided value '{}' for stanza that has id '{}'.", result, packet.getID() );
    }

    return result;
}
 
Example 12
Source Project: Openfire   Source File: PubSubEngine.java    License: Apache License 2.0 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 13
Source Project: Openfire   Source File: HttpBindBody.java    License: Apache License 2.0 5 votes vote down vote up
public String getLanguage()
{
    // Default language is English ("en").
    final String language = document.getRootElement().attributeValue( QName.get( "lang", XMLConstants.XML_NS_URI ) );
    if ( language == null || "".equals( language ) )
    {
        return "en";
    }

    return language;
}
 
Example 14
private static void write(Argument arg) throws Exception {
	try {
		Document document = DocumentHelper.createDocument();
		Element persistence = document.addElement("persistence", "http://java.sun.com/xml/ns/persistence");
		persistence.addAttribute(QName.get("schemaLocation", "xsi", "http://www.w3.org/2001/XMLSchema-instance"),
				"http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd");
		persistence.addAttribute("version", "2.0");
		for (Class<?> cls : scanContainerEntity(arg.getProject())) {
			Element unit = persistence.addElement("persistence-unit");
			unit.addAttribute("name", cls.getCanonicalName());
			unit.addAttribute("transaction-type", "RESOURCE_LOCAL");
			Element provider = unit.addElement("provider");
			provider.addText(PersistenceProviderImpl.class.getCanonicalName());
			for (Class<?> o : scanMappedSuperclass(cls)) {
				Element mapped_element = unit.addElement("class");
				mapped_element.addText(o.getCanonicalName());
			}
			Element slice_unit_properties = unit.addElement("properties");
			Map<String, String> properties = new LinkedHashMap<String, String>();
			for (Entry<String, String> entry : properties.entrySet()) {
				Element property = slice_unit_properties.addElement("property");
				property.addAttribute("name", entry.getKey());
				property.addAttribute("value", entry.getValue());
			}
		}
		OutputFormat format = OutputFormat.createPrettyPrint();
		format.setEncoding("UTF-8");
		File file = new File(arg.getPath());
		XMLWriter writer = new XMLWriter(new FileWriter(file), format);
		writer.write(document);
		writer.close();
		System.out.println("create persistence.xml at path:" + arg.getPath());
	} catch (Exception e) {
		e.printStackTrace();
	}
}
 
Example 15
public static List<String> write(String path, List<String> entities) throws Exception {
	List<String> names = new ArrayList<>();
	String name = "";
	try {
		names.addAll((List<String>) Config.resource(Config.RESOURCE_CONTAINERENTITYNAMES));
		names = ListTools.includesExcludesWildcard(names, entities, null);
		Document document = DocumentHelper.createDocument();
		Element persistence = document.addElement("persistence", "http://java.sun.com/xml/ns/persistence");
		persistence.addAttribute(QName.get("schemaLocation", "xsi", "http://www.w3.org/2001/XMLSchema-instance"),
				"http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd");
		persistence.addAttribute("version", "2.0");
		for (String className : names) {
			name = className;
			Class<? extends JpaObject> clazz = (Class<JpaObject>) Class.forName(className);
			Element unit = persistence.addElement("persistence-unit");
			unit.addAttribute("name", className);
			unit.addAttribute("transaction-type", "RESOURCE_LOCAL");
			Element provider = unit.addElement("provider");
			provider.addText(PersistenceProviderImpl.class.getName());
			for (Class<?> o : JpaObjectTools.scanMappedSuperclass(clazz)) {
				Element mapped_element = unit.addElement("class");
				mapped_element.addText(o.getName());
			}
		}
		OutputFormat format = OutputFormat.createPrettyPrint();
		format.setEncoding("UTF-8");
		File file = new File(path);
		FileUtils.touch(file);
		XMLWriter writer = new XMLWriter(new FileWriter(file), format);
		writer.write(document);
		writer.close();
		return names;
	} catch (Exception e) {
		throw new Exception("write error.className:" + name, e);
	}
}
 
Example 16
/**
 * Find and returns a 'storage' element as defined in XEP-0048 'Bookmarks' from a XML element that is expected to be a child element as defined in
 * XEP-0049 "Private XML Storage"
 *
 * @param privateXmlStorageElement a child element (can be null).
 * @return The XEP-0048-defined 'storage' element that was found in the child element, or null.
 */
static Element findStorageElementInPrivateXmlStorage( final Element privateXmlStorageElement )
{
    if ( privateXmlStorageElement == null )
    {
        return null;
    }

    return privateXmlStorageElement.element( QName.get( "storage", "storage:bookmarks" ) );
}
 
Example 17
Source Project: EasyML   Source File: ActionNodeDef.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * the detail xml configurations goes here, this will be called in append2XML
 * @param action
 */
public void generateActionXML(Element action) {
	Namespace xmlns = new Namespace("", "uri:oozie:shell-action:0.2"); // root namespace uri
	QName qName = QName.get("shell", xmlns); // your root element's name
	Element shell = action.addElement(qName);
	// action.appendChild( shell );

	generateElement(shell, "job-tracker", "${jobTracker}");
	generateElement(shell, "name-node", "${nameNode}");

	Element configuration = shell.addElement("configuration");
	createProperty(configuration, "mapred.job.queue.name", "${queueName}");
	createProperty(configuration, "mapreduce.map.memeory.mb", "10240");

	if( program.isScriptProgram() ){
		//单机脚本类型程序
		generateElement(shell, "exec", "./" + widgetId + ".startup");
	} else {
		generateElement(shell, "exec", "./run.sh");
	}

	command2XMLforShell(shell);

	if( program.isScriptProgram() ){
		generateElement(shell, "file", "${appPath}/" + widgetId
				+ ".startup");
		generateElement(shell, "file", "${appPath}/" + widgetId
				+ ".script");
	} else
		generateElement(shell, "file", "${nameNode}/" + program.getPath()
				+ "/run.sh");

	shell.addElement("capture-output");
}
 
Example 18
Source Project: Openfire   Source File: StanzaIDUtilTest.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Test if {@link StanzaIDUtil.ensureUniqueAndStableStanzaID} uses the provided
 * origin-id value, if there's one.
 */
@Test
public void testUseOriginIdElement() throws Exception
{
    // Setup fixture.
    final Packet input = new Message();
    final JID self = new JID( "foobar" );
    final String expected = "de305d54-75b4-431b-adb2-eb6b9e546013";
    final Element toOverwrite = input.getElement().addElement( "origin-id", "urn:xmpp:sid:0" );
    toOverwrite.addAttribute( "id", expected );

    // Execute system under test.
    final Packet result = StanzaIDUtil.ensureUniqueAndStableStanzaID( input, self );

    // Verify results.
    Assert.assertNotNull( result );
    final Element stanzaIDElement = result.getElement().element( QName.get( "stanza-id", "urn:xmpp:sid:0" ) );
    Assert.assertNotNull( stanzaIDElement );
    try
    {
        UUID.fromString( stanzaIDElement.attributeValue( "id" ) );
    }
    catch ( IllegalArgumentException ex )
    {
        Assert.fail();
    }
    Assert.assertEquals( expected, stanzaIDElement.attributeValue( "id" ) );
    assertEquals( self.toString(), stanzaIDElement.attributeValue( "by" ) );
}
 
Example 19
private int readInt(Element e, QName attributeName, int defaultValue) throws MapException {
    String s = e.attributeValue(attributeName);
    if (s == null) {
        return defaultValue;
    }
    try {
        return Integer.parseInt(s);
    }
    catch (NumberFormatException ex) {
        throw new MapException("Attribute " + attributeName + " is not an integer: " + e);
    }
}
 
Example 20
Source Project: Openfire   Source File: StanzaIDUtilTest.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Test if {@link StanzaIDUtil.ensureUniqueAndStableStanzaID} overwrites a stanza-id
 * element when another is present with the same 'by' value.
 */
@Test
public void testOverwriteStanzaIDElement() throws Exception
{
    // Setup fixture.
    final Packet input = new Message();
    final JID self = new JID( "foobar" );
    final String notExpected = "de305d54-75b4-431b-adb2-eb6b9e546013";
    final Element toOverwrite = input.getElement().addElement( "stanza-id", "urn:xmpp:sid:0" );
    toOverwrite.addAttribute( "by", self.toString() );
    toOverwrite.addAttribute( "id", notExpected );

    // Execute system under test.
    final Packet result = StanzaIDUtil.ensureUniqueAndStableStanzaID( input, self );

    // Verify results.
    Assert.assertNotNull( result );
    final Element stanzaIDElement = result.getElement().element( QName.get( "stanza-id", "urn:xmpp:sid:0" ) );
    Assert.assertNotNull( stanzaIDElement );
    try
    {
        UUID.fromString( stanzaIDElement.attributeValue( "id" ) );
    }
    catch ( IllegalArgumentException ex )
    {
        Assert.fail();
    }
    Assert.assertNotEquals( notExpected, stanzaIDElement.attributeValue( "id" ) );
    assertEquals( self.toString(), stanzaIDElement.attributeValue( "by" ) );
}
 
Example 21
private void addIgnoreExchangeEventProperty(CamelProcessItem item) throws PersistenceException, DocumentException {
	String springContent = item.getSpringContent();
	if (null != springContent && !springContent.isEmpty()) {
		Document document = DocumentHelper.parseText(springContent);
		QName qname = QName.get("bean", SPRING_BEANS_NAMESPACE);
		List<Element> beans = document.getRootElement().elements(qname);
		for (Element bean : beans) {
			if ("jmxEventNotifier".equals(bean.attributeValue("id")) &&
					"org.apache.camel.management.JmxNotificationEventNotifier".equals(bean.attributeValue("class")))
			{
				List<Element> properties = bean.elements(QName.get("property", SPRING_BEANS_NAMESPACE));
				boolean hasIgnore = false;
				for (Element property : properties) {
					List<Attribute> propertyAttributes = property.attributes();
					for (Attribute propertyAttribute : propertyAttributes) {
						if (propertyAttribute.getValue().equals(IGNORE_EXCHANGE_EVENTS)) {
							hasIgnore = true;
							break;
						}
					}
				}
				if (!hasIgnore)
				{
					DefaultElement ignoreExchangeElement = new DefaultElement("property", bean.getNamespace());
					ignoreExchangeElement.add(DocumentHelper.createAttribute(ignoreExchangeElement, "name", IGNORE_EXCHANGE_EVENTS));
					ignoreExchangeElement.add(DocumentHelper.createAttribute(ignoreExchangeElement, "value", "true"));
					bean.add(ignoreExchangeElement);
					item.setSpringContent(document.asXML());
					saveItem(item);
				}
				break;
			}
		}
	}
}
 
Example 22
Source Project: Openfire   Source File: HttpSession.java    License: Apache License 2.0 5 votes vote down vote up
private String createSessionRestartResponse()
{
    final Element response = DocumentHelper.createElement( QName.get( "body", "http://jabber.org/protocol/httpbind" ) );
    response.addNamespace("stream", "http://etherx.jabber.org/streams");

    final Element features = response.addElement("stream:features");
    for (Element feature : getAvailableStreamFeaturesElements()) {
        features.add(feature);
    }

    return response.asXML();
}
 
Example 23
private static void moveNamespace(Element treeRoot, Namespace oldNsp, Namespace newNsp) {
    if (treeRoot.getNamespace().equals(oldNsp)) {
        treeRoot.setQName(QName.get(treeRoot.getName(), newNsp));
        treeRoot.remove(oldNsp);
    }
    moveNamespaceInChildren(treeRoot, oldNsp, newNsp);
}
 
Example 24
private static void moveNamespace(Element treeRoot, String oldNspURI, String newNspURI) {
    Namespace oldNsp = treeRoot.getNamespace();
    if (oldNspURI.equals(oldNsp.getURI())) {
        Namespace newNsp = Namespace.get(oldNsp.getPrefix(), newNspURI);
        treeRoot.setQName(QName.get(treeRoot.getName(), newNsp));
        treeRoot.remove(oldNsp);
    }
    moveNamespaceInChildren(treeRoot, oldNspURI, newNspURI);
}
 
Example 25
private static void moveNamespaceInChildren(Element treeRoot, String oldNspURI, String newNspURI) {
    for (Iterator<?> i = treeRoot.elementIterator(); i.hasNext();) {
        Element e = (Element) i.next();
        Namespace oldNsp = e.getNamespace();
        if (oldNspURI.equals(oldNsp.getURI())) {
            Namespace newNsp = Namespace.get(oldNsp.getPrefix(), newNspURI);
            e.setQName(QName.get(e.getName(), newNsp));
            e.remove(oldNsp);
        }
        moveNamespaceInChildren(e, oldNspURI, newNspURI);
    }
}
 
Example 26
Source Project: Openfire   Source File: AdHocCommandManager.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Stores in the SessionData the fields and their values as specified in the completed
 * data form by the user.
 *
 * @param iqCommand the command element containing the data form element.
 * @param session the SessionData for this command execution.
 */
private void saveCompletedForm(Element iqCommand, SessionData session) {
    Element formElement = iqCommand.element(QName.get("x", "jabber:x:data"));
    if (formElement != null) {
        // Generate a Map with the variable names and variables values
        Map<String, List<String>> data = new HashMap<>();
        DataForm dataForm = new DataForm(formElement);
        for (FormField field : dataForm.getFields()) {
            data.put(field.getVariable(), field.getValues());
        }
        // Store the variables and their values in the session data
        session.addStageForm(data);
    }
}
 
Example 27
Source Project: Openfire   Source File: LocalMUCRole.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Create a new role.
 * 
 * @param chatserver the server hosting the role.
 * @param chatroom the room the role is valid in.
 * @param nickname the nickname of the user in the role.
 * @param role the role of the user in the room.
 * @param affiliation the affiliation of the user in the room.
 * @param chatuser the user on the chat server.
 * @param presence the presence sent by the user to join the room.
 * @param packetRouter the packet router for sending messages from this role.
 */
public LocalMUCRole(MultiUserChatService chatserver, LocalMUCRoom chatroom, String nickname,
        MUCRole.Role role, MUCRole.Affiliation affiliation, LocalMUCUser chatuser, Presence presence,
        PacketRouter packetRouter)
{
    this.room = chatroom;
    this.nick = nickname;
    this.user = chatuser;
    this.server = chatserver;
    this.router = packetRouter;
    this.role = role;
    this.affiliation = affiliation;

    extendedInformation =
            DocumentHelper.createElement(QName.get("x", "http://jabber.org/protocol/muc#user"));
    calculateExtendedInformation();
    rJID = new JID(room.getName(), server.getServiceDomain(), nick);
    setPresence(presence);

    // Check if new occupant wants to be a deaf occupant
    Element element = presence.getElement()
            .element(QName.get("x", "http://jivesoftware.org/protocol/muc"));
    if (element != null) {
        voiceOnly = element.element("deaf-occupant") != null;
    }

    // Add the new role to the list of roles
    user.addRole(room.getName(), this);
}
 
Example 28
Source Project: Openfire   Source File: LocalMUCRole.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void setPresence(Presence newPresence) {
    // Try to remove the element whose namespace is "http://jabber.org/protocol/muc" since we
    // don't need to include that element in future presence broadcasts
    Element element = newPresence.getElement().element(QName.get("x", "http://jabber.org/protocol/muc"));
    if (element != null) {
        newPresence.getElement().remove(element);
    }

    this.presence = newPresence;
    this.presence.setFrom(getRoleAddress());
    updatePresence();
}
 
Example 29
Source Project: Openfire   Source File: LocalMUCRole.java    License: Apache License 2.0 5 votes vote down vote up
private void updatePresence() {
    if (extendedInformation != null && presence != null) {
        // Remove any previous extendedInformation, then re-add it.
        Element mucUser = presence.getElement().element(QName.get("x", "http://jabber.org/protocol/muc#user"));
        if (mucUser != null) {
            // Remove any previous extendedInformation, then re-add it.
            presence.getElement().remove(mucUser);
        }
        Element exi = extendedInformation.createCopy();
        presence.getElement().add(exi);
    }
}
 
Example 30
Source Project: Openfire   Source File: IQMuclumbusSearchHandler.java    License: Apache License 2.0 5 votes vote down vote up
static Element generateResultElement( final List<MUCRoom> rooms )
{
    Log.debug( "Generating result element." );
    final Element res = DocumentHelper.createElement( QName.get( RESPONSE_ELEMENT_NAME, NAMESPACE ) );
    for ( final MUCRoom room : rooms )
    {
        final Element item = res.addElement( "item" );
        item.addAttribute( "address", room.getJID().toString() );
        if ( room.getNaturalLanguageName() != null && !room.getNaturalLanguageName().isEmpty() )
        {
            item.addElement( "name" ).setText( room.getNaturalLanguageName() );
        }
        if ( room.getDescription() != null && !room.getDescription().isEmpty() )
        {
            item.addElement( "description" ).setText( room.getDescription() );
        }
        // Openfire does not support 'language'
        if ( !room.isLocked() && !room.isMembersOnly() && !room.isPasswordProtected() )
        {
            item.addElement( "is-open" );
        }

        final Element anonymityMode = item.addElement( "anonymity-mode" );
        if ( room.canAnyoneDiscoverJID() )
        {
            anonymityMode.setText( "none" );
        }
        else
        {
            anonymityMode.setText( "semi" );
        }

        item.addElement( "nusers" ).setText( Integer.toString( room.getOccupantsCount() ) );
    }
    return res;
}