Search in sources :

Example 1 with Namespace

use of org.dom4j.Namespace in project Openfire by igniterealtime.

the class SASLAuthentication method getSASLMechanismsElement.

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 KeyStore keyStore = connection.getConfiguration().getIdentityStore().getStore();
        final KeyStore trustStore = session.getConnection().getConfiguration().getTrustStore().getStore();
        final X509Certificate trusted = CertificateManager.getEndEntityCertificate(session.getConnection().getPeerCertificates(), keyStore, trustStore);
        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;
}
Also used : QName(org.dom4j.QName) Element(org.dom4j.Element) Connection(org.jivesoftware.openfire.Connection) KeyStore(java.security.KeyStore) Namespace(org.dom4j.Namespace) X509Certificate(java.security.cert.X509Certificate)

Example 2 with Namespace

use of org.dom4j.Namespace in project Openfire by igniterealtime.

the class MUCRoomHistory method addOldMessage.

/**
     * Creates a new message and adds it to the history. The new message will be created based on
     * the provided information. This information will likely come from the database when loading
     * the room history from the database.
     *
     * @param senderJID the sender's JID of the message to add to the history.
     * @param nickname the sender's nickname of the message to add to the history.
     * @param sentDate the date when the message was sent to the room.
     * @param subject the subject included in the message.
     * @param body the body of the message.
     */
public void addOldMessage(String senderJID, String nickname, Date sentDate, String subject, String body, String stanza) {
    Message message = new Message();
    message.setType(Message.Type.groupchat);
    if (stanza != null) {
        // payload initialized as XML string from DB
        SAXReader xmlReader = new SAXReader();
        xmlReader.setEncoding("UTF-8");
        try {
            Element element = xmlReader.read(new StringReader(stanza)).getRootElement();
            for (Element child : (List<Element>) element.elements()) {
                Namespace ns = child.getNamespace();
                if (ns == null || ns.getURI().equals("jabber:client") || ns.getURI().equals("jabber:server")) {
                    continue;
                }
                Element added = message.addChildElement(child.getName(), child.getNamespaceURI());
                if (!child.getText().isEmpty()) {
                    added.setText(child.getText());
                }
                for (Attribute attr : (List<Attribute>) child.attributes()) {
                    added.addAttribute(attr.getQName(), attr.getValue());
                }
                for (Element el : (List<Element>) child.elements()) {
                    added.add(el.createCopy());
                }
            }
            if (element.attribute("id") != null) {
                message.setID(element.attributeValue("id"));
            }
        } catch (Exception ex) {
            Log.error("Failed to parse payload XML", ex);
        }
    }
    message.setSubject(subject);
    message.setBody(body);
    // Set the sender of the message
    if (nickname != null && nickname.trim().length() > 0) {
        JID roomJID = room.getRole().getRoleAddress();
        // Recreate the sender address based on the nickname and room's JID
        message.setFrom(new JID(roomJID.getNode(), roomJID.getDomain(), nickname, true));
    } else {
        // Set the room as the sender of the message
        message.setFrom(room.getRole().getRoleAddress());
    }
    // Add the delay information to the message
    Element delayInformation = message.addChildElement("delay", "urn:xmpp:delay");
    delayInformation.addAttribute("stamp", XMPPDateTimeFormat.format(sentDate));
    if (room.canAnyoneDiscoverJID()) {
        // Set the Full JID as the "from" attribute
        delayInformation.addAttribute("from", senderJID);
    } else {
        // Set the Room JID as the "from" attribute
        delayInformation.addAttribute("from", room.getRole().getRoleAddress().toString());
    }
    historyStrategy.addMessage(message);
}
Also used : Message(org.xmpp.packet.Message) JID(org.xmpp.packet.JID) Attribute(org.dom4j.Attribute) SAXReader(org.dom4j.io.SAXReader) Element(org.dom4j.Element) StringReader(java.io.StringReader) List(java.util.List) Namespace(org.dom4j.Namespace) UserNotFoundException(org.jivesoftware.openfire.user.UserNotFoundException)

Example 3 with Namespace

use of org.dom4j.Namespace in project zm-mailbox by Zimbra.

the class WsdlGenerator method makeWsdlDoc.

public static Document makeWsdlDoc(List<WsdlInfoForNamespace> nsInfos, String serviceName, String targetNamespace) {
    Namespace nsSvc = new Namespace(svcPrefix, targetNamespace);
    final QName svcTypes = QName.get("types", nsWsdl);
    Document document = DocumentHelper.createDocument();
    Map<WsdlServiceInfo, Element> bindElems = Maps.newTreeMap();
    Map<WsdlServiceInfo, Element> portTypeElems = Maps.newTreeMap();
    Element root = document.addElement(QName.get("definitions", nsWsdl));
    root.add(nsSvc);
    for (WsdlInfoForNamespace wsdlNsInfo : nsInfos) {
        root.add(wsdlNsInfo.getXsdNamespace());
    }
    root.add(nsZimbra);
    root.add(nsSoap);
    root.add(nsXsd);
    root.add(nsWsdl);
    root.addAttribute("targetNamespace", targetNamespace);
    root.addAttribute("name", serviceName);
    addWsdlTypesElement(root, svcTypes, nsInfos);
    for (WsdlInfoForNamespace wsdlNsInfo : nsInfos) {
        WsdlServiceInfo svcInfo = wsdlNsInfo.getSvcInfo();
        if (!portTypeElems.containsKey(svcInfo)) {
            // wsdl:definitions/wsdl:portType
            Element portTypeElem = DocumentHelper.createElement(portType);
            portTypeElem.addAttribute("name", svcInfo.getPortTypeName());
            portTypeElems.put(svcInfo, portTypeElem);
        }
        if (!bindElems.containsKey(svcInfo)) {
            // wsdl:definitions/wsdl:binding
            Element bindingElem = DocumentHelper.createElement(wsdlBinding);
            bindingElem.addAttribute("name", svcInfo.getBindingName());
            bindingElem.addAttribute("type", svcPrefix + ":" + svcInfo.getPortTypeName());
            // wsdl:definitions/wsdl:binding/soap:binding
            Element soapBindElem = bindingElem.addElement(soapBinding);
            soapBindElem.addAttribute("transport", "http://schemas.xmlsoap.org/soap/http");
            soapBindElem.addAttribute("style", "document");
            bindElems.put(svcInfo, bindingElem);
        }
    }
    for (WsdlInfoForNamespace wsdlNsInfo : nsInfos) {
        WsdlServiceInfo svcInfo = wsdlNsInfo.getSvcInfo();
        for (String requestName : wsdlNsInfo.getRequests()) {
            String rootName = requestName.substring(0, requestName.length() - 7);
            String responseName = rootName + "Response";
            String reqOpName = requestName.substring(0, 1).toLowerCase() + requestName.substring(1);
            String reqMsgName = wsdlNsInfo.getTag() + requestName + "Message";
            String respMsgName = wsdlNsInfo.getTag() + responseName + "Message";
            addWsdlRequestAndResponseMessageElements(root, wsdlNsInfo, reqMsgName, respMsgName, requestName, responseName);
            addWsdlPortTypeOperationElements(portTypeElems.get(svcInfo), reqMsgName, respMsgName, reqOpName);
            addWsdlBindingOperationElements(bindElems.get(svcInfo), wsdlNsInfo, reqOpName, rootName);
        }
    }
    addWsdlSoapHdrContextMessageElement(root);
    for (Entry<WsdlServiceInfo, Element> entry : portTypeElems.entrySet()) {
        root.add(entry.getValue());
    }
    for (Entry<WsdlServiceInfo, Element> entry : bindElems.entrySet()) {
        root.add(entry.getValue());
    }
    Set<WsdlServiceInfo> svcSet = Sets.newHashSet();
    for (WsdlInfoForNamespace wsdlNsInfo : nsInfos) {
        WsdlServiceInfo svcInfo = wsdlNsInfo.getSvcInfo();
        if (!svcSet.contains(svcInfo)) {
            svcSet.add(svcInfo);
            addWsdlServiceElement(root, svcInfo);
        }
    }
    return document;
}
Also used : QName(org.dom4j.QName) Element(org.dom4j.Element) Document(org.dom4j.Document) Namespace(org.dom4j.Namespace) ZimbraNamespace(com.zimbra.common.soap.ZimbraNamespace)

Example 4 with Namespace

use of org.dom4j.Namespace in project uPortal by Jasig.

the class RDBMDistributedLayoutStore method importLayout.

@Override
@SuppressWarnings("unchecked")
@Transactional
public void importLayout(org.dom4j.Element layout) {
    if (layout.getNamespaceForPrefix("dlm") == null) {
        layout.add(new Namespace("dlm", Constants.NS_URI));
    }
    //Remove comments from the DOM they break import
    final List<org.dom4j.Node> comments = layout.selectNodes("//comment()");
    for (final org.dom4j.Node comment : comments) {
        comment.detach();
    }
    //Get a ref to the prefs element and then remove it from the layout
    final org.dom4j.Node preferencesElement = layout.selectSingleNode("preferences");
    if (preferencesElement != null) {
        preferencesElement.getParent().remove(preferencesElement);
    }
    final String ownerUsername = layout.valueOf("@username");
    //Get a ref to the profile element and then remove it from the layout
    final org.dom4j.Node profileElement = layout.selectSingleNode("profile");
    if (profileElement != null) {
        profileElement.getParent().remove(profileElement);
        final org.dom4j.Document profileDocument = new org.dom4j.DocumentFactory().createDocument();
        profileDocument.setRootElement((org.dom4j.Element) profileElement);
        profileDocument.setName(ownerUsername + ".profile");
        final DocumentSource profileSource = new DocumentSource(profileElement);
        this.portalDataHandlerService.importData(profileSource);
    }
    final IPerson person = new PersonImpl();
    person.setUserName(ownerUsername);
    int ownerId;
    try {
        //Can't just pass true for create here, if the user actually exists the create flag also updates the user data
        ownerId = this.userIdentityStore.getPortalUID(person);
    } catch (final AuthorizationException t) {
        if (this.errorOnMissingUser) {
            throw new RuntimeException("Unrecognized user " + person.getUserName() + "; you must import users before their layouts or set org.apereo.portal.io.layout.errorOnMissingUser to false.", t);
        }
        //Create the missing user
        ownerId = this.userIdentityStore.getPortalUID(person, true);
    }
    if (ownerId == -1) {
        throw new RuntimeException("Unrecognized user " + person.getUserName() + "; you must import users before their layouts or set org.apereo.portal.io.layout.errorOnMissingUser to false.");
    }
    person.setID(ownerId);
    IUserProfile profile = null;
    try {
        person.setSecurityContext(new BrokenSecurityContext());
        profile = this.getUserProfileByFname(person, "default");
    } catch (final Throwable t) {
        throw new RuntimeException("Failed to load profile for " + person.getUserName() + "; This user must have a profile for import to continue.", t);
    }
    // (6) Add database Ids & (5) Add dlm:plfID ...
    int nextId = 1;
    for (final Iterator<org.dom4j.Element> it = (Iterator<org.dom4j.Element>) layout.selectNodes("folder | dlm:* | channel").iterator(); it.hasNext(); ) {
        nextId = this.addIdAttributesIfNecessary(it.next(), nextId);
    }
    // Now update UP_USER...
    this.jdbcOperations.update("UPDATE up_user SET next_struct_id = ? WHERE user_id = ?", nextId, person.getID());
    // (4) Convert external DLM pathrefs to internal form (noderefs)...
    for (final Iterator<org.dom4j.Attribute> itr = (Iterator<org.dom4j.Attribute>) layout.selectNodes("//@dlm:origin").iterator(); itr.hasNext(); ) {
        final org.dom4j.Attribute a = itr.next();
        final Noderef dlmNoderef = nodeReferenceFactory.getNoderefFromPathref(ownerUsername, a.getValue(), null, true, layout);
        if (dlmNoderef != null) {
            // Change the value only if we have a valid pathref...
            a.setValue(dlmNoderef.toString());
            // For dlm:origin only, also use the noderef as the ID attribute...
            a.getParent().addAttribute("ID", dlmNoderef.toString());
        } else {
            // At least insure the value is between 1 and 35 characters
            a.setValue(BAD_PATHREF_MESSAGE);
        }
    }
    for (final Iterator<org.dom4j.Attribute> itr = (Iterator<org.dom4j.Attribute>) layout.selectNodes("//@dlm:target").iterator(); itr.hasNext(); ) {
        final org.dom4j.Attribute a = itr.next();
        final Noderef dlmNoderef = nodeReferenceFactory.getNoderefFromPathref(ownerUsername, a.getValue(), null, true, layout);
        // Put in the correct value, or at least insure the value is between 1 and 35 characters
        a.setValue(dlmNoderef != null ? dlmNoderef.toString() : BAD_PATHREF_MESSAGE);
    }
    for (final Iterator<org.dom4j.Attribute> names = (Iterator<org.dom4j.Attribute>) layout.selectNodes("//dlm:*/@name").iterator(); names.hasNext(); ) {
        final org.dom4j.Attribute a = names.next();
        final String value = a.getValue().trim();
        if (!VALID_PATHREF_PATTERN.matcher(value).matches()) {
            /* Don't send it to getDlmNoderef if we know in advance it's not
                 * going to work;  saves annoying/misleading log messages and
                 * possibly some processing.  NOTE this is _only_ a problem with
                 * the name attribute of some dlm:* elements, which seems to go
                 * unused intentionally in some circumstances
                 */
            continue;
        }
        final org.dom4j.Attribute fname = a.getParent().attribute("fname");
        Noderef dlmNoderef = null;
        if (fname != null) {
            dlmNoderef = nodeReferenceFactory.getNoderefFromPathref(ownerUsername, value, fname.getValue(), false, layout);
            // Remove the fname attribute now that we're done w/ it...
            fname.getParent().remove(fname);
        } else {
            dlmNoderef = nodeReferenceFactory.getNoderefFromPathref(ownerUsername, value, null, true, layout);
        }
        // Put in the correct value, or at least insure the value is between 1 and 35 characters
        a.setValue(dlmNoderef != null ? dlmNoderef.toString() : BAD_PATHREF_MESSAGE);
    }
    // (3) Restore chanID attributes on <channel> elements...
    for (final Iterator<org.dom4j.Element> it = (Iterator<org.dom4j.Element>) layout.selectNodes("//channel").iterator(); it.hasNext(); ) {
        final org.dom4j.Element c = it.next();
        final String fname = c.valueOf("@fname");
        final IPortletDefinition cd = this.portletDefinitionRegistry.getPortletDefinitionByFname(fname);
        if (cd == null) {
            final String msg = "No portlet with fname=" + fname + " exists referenced by node " + c.valueOf("@ID") + " from layout for " + ownerUsername;
            if (errorOnMissingPortlet) {
                throw new IllegalArgumentException(msg);
            } else {
                logger.warn(msg);
                //Remove the bad channel node
                c.getParent().remove(c);
            }
        } else {
            c.addAttribute("chanID", String.valueOf(cd.getPortletDefinitionId().getStringId()));
        }
    }
    // (2) Restore locale info...
    // (This step doesn't appear to be needed for imports)
    // (1) Process structure & theme attributes...
    Document layoutDom = null;
    try {
        final int structureStylesheetId = profile.getStructureStylesheetId();
        this.loadStylesheetUserPreferencesAttributes(person, profile, layout, structureStylesheetId, "structure");
        final int themeStylesheetId = profile.getThemeStylesheetId();
        this.loadStylesheetUserPreferencesAttributes(person, profile, layout, themeStylesheetId, "theme");
        // From this point forward we need the user's PLF set as DLM expects it...
        for (final Iterator<org.dom4j.Text> it = (Iterator<org.dom4j.Text>) layout.selectNodes("descendant::text()").iterator(); it.hasNext(); ) {
            // How many years have we used Java & XML, and this still isn't easy?
            final org.dom4j.Text txt = it.next();
            if (txt.getText().trim().length() == 0) {
                txt.getParent().remove(txt);
            }
        }
        final org.dom4j.Element copy = layout.createCopy();
        final org.dom4j.Document doc = this.fac.createDocument(copy);
        doc.normalize();
        layoutDom = this.writer.get().write(doc);
        person.setAttribute(Constants.PLF, layoutDom);
    } catch (final Throwable t) {
        throw new RuntimeException("Unable to set UserPreferences for user:  " + person.getUserName(), t);
    }
    // Finally store the layout...
    try {
        this.setUserLayout(person, profile, layoutDom, true, true);
    } catch (final Throwable t) {
        final String msg = "Unable to persist layout for user:  " + ownerUsername;
        throw new RuntimeException(msg, t);
    }
    if (preferencesElement != null) {
        final int ownerUserId = this.userIdentityStore.getPortalUserId(ownerUsername);
        //TODO this assumes a single layout, when multi-layout support exists portlet entities will need to be re-worked to allow for a layout id to be associated with the entity
        //track which entities from the user's pre-existing set are touched (all non-touched entities will be removed)
        final Set<IPortletEntity> oldPortletEntities = new LinkedHashSet<IPortletEntity>(this.portletEntityDao.getPortletEntitiesForUser(ownerUserId));
        final List<org.dom4j.Element> entries = preferencesElement.selectNodes("entry");
        for (final org.dom4j.Element entry : entries) {
            final String dlmPathRef = entry.attributeValue("entity");
            final String fname = entry.attributeValue("channel");
            final String prefName = entry.attributeValue("name");
            final Noderef dlmNoderef = nodeReferenceFactory.getNoderefFromPathref(person.getUserName(), dlmPathRef, fname, false, layout);
            if (dlmNoderef != null && fname != null) {
                final IPortletEntity portletEntity = this.getPortletEntity(fname, dlmNoderef.toString(), ownerUserId);
                oldPortletEntities.remove(portletEntity);
                final List<IPortletPreference> portletPreferences = portletEntity.getPortletPreferences();
                final List<org.dom4j.Element> valueElements = entry.selectNodes("value");
                final List<String> values = new ArrayList<String>(valueElements.size());
                for (final org.dom4j.Element valueElement : valueElements) {
                    values.add(valueElement.getText());
                }
                portletPreferences.add(new PortletPreferenceImpl(prefName, false, values.toArray(new String[values.size()])));
                this.portletEntityDao.updatePortletEntity(portletEntity);
            }
        }
        //Delete all portlet preferences for entities that were not imported
        for (final IPortletEntity portletEntity : oldPortletEntities) {
            portletEntity.setPortletPreferences(null);
            if (portletEntityRegistry.shouldBePersisted(portletEntity)) {
                this.portletEntityDao.updatePortletEntity(portletEntity);
            } else {
                this.portletEntityDao.deletePortletEntity(portletEntity);
            }
        }
    }
}
Also used : LinkedHashSet(java.util.LinkedHashSet) IPortletPreference(org.apereo.portal.portlet.om.IPortletPreference) AuthorizationException(org.apereo.portal.AuthorizationException) Node(org.w3c.dom.Node) Element(org.w3c.dom.Element) ArrayList(java.util.ArrayList) Document(org.w3c.dom.Document) IPerson(org.apereo.portal.security.IPerson) IPortletEntity(org.apereo.portal.portlet.om.IPortletEntity) Iterator(java.util.Iterator) PortletPreferenceImpl(org.apereo.portal.portlet.dao.jpa.PortletPreferenceImpl) IPortletDefinition(org.apereo.portal.portlet.om.IPortletDefinition) Namespace(org.dom4j.Namespace) PersonImpl(org.apereo.portal.security.provider.PersonImpl) DocumentSource(org.dom4j.io.DocumentSource) IUserProfile(org.apereo.portal.IUserProfile) BrokenSecurityContext(org.apereo.portal.security.provider.BrokenSecurityContext) Transactional(org.springframework.transaction.annotation.Transactional)

Example 5 with Namespace

use of org.dom4j.Namespace in project Openfire by igniterealtime.

the class SASLAuthentication method getSASLMechanismsElement.

public static Element getSASLMechanismsElement(ClientSession session) {
    final Element result = DocumentHelper.createElement(new QName("mechanisms", new Namespace("", SASL_NAMESPACE)));
    for (String mech : getSupportedMechanisms()) {
        final Element mechanism = result.addElement("mechanism");
        mechanism.setText(mech);
    }
    return result;
}
Also used : QName(org.dom4j.QName) Element(org.dom4j.Element) Namespace(org.dom4j.Namespace)

Aggregations

Namespace (org.dom4j.Namespace)6 Element (org.dom4j.Element)4 QName (org.dom4j.QName)3 ZimbraNamespace (com.zimbra.common.soap.ZimbraNamespace)1 StringReader (java.io.StringReader)1 KeyStore (java.security.KeyStore)1 X509Certificate (java.security.cert.X509Certificate)1 ArrayList (java.util.ArrayList)1 Iterator (java.util.Iterator)1 LinkedHashSet (java.util.LinkedHashSet)1 List (java.util.List)1 QName (javax.xml.namespace.QName)1 AuthorizationException (org.apereo.portal.AuthorizationException)1 IUserProfile (org.apereo.portal.IUserProfile)1 PortletPreferenceImpl (org.apereo.portal.portlet.dao.jpa.PortletPreferenceImpl)1 IPortletDefinition (org.apereo.portal.portlet.om.IPortletDefinition)1 IPortletEntity (org.apereo.portal.portlet.om.IPortletEntity)1 IPortletPreference (org.apereo.portal.portlet.om.IPortletPreference)1 IPerson (org.apereo.portal.security.IPerson)1 BrokenSecurityContext (org.apereo.portal.security.provider.BrokenSecurityContext)1