org.jxmpp.jid.DomainBareJid Java Examples

The following examples show how to use org.jxmpp.jid.DomainBareJid. 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 File: MultiUserChatManager.java    From Smack with Apache License 2.0 6 votes vote down vote up
/**
 * Returns a Map of HostedRooms where each HostedRoom has the XMPP address of the room and the room's name.
 * Once discovered the rooms hosted by a chat service it is possible to discover more detailed room information or
 * join the room.
 *
 * @param serviceName the service that is hosting the rooms to discover.
 * @return a map from the room's address to its HostedRoom information.
 * @throws XMPPErrorException if there was an XMPP error returned.
 * @throws NoResponseException if there was no response from the remote entity.
 * @throws NotConnectedException if the XMPP connection is not connected.
 * @throws InterruptedException if the calling thread was interrupted.
 * @throws NotAMucServiceException if the entity is not a MUC serivce.
 * @since 4.3.1
 */
public Map<EntityBareJid, HostedRoom> getRoomsHostedBy(DomainBareJid serviceName) throws NoResponseException, XMPPErrorException,
                NotConnectedException, InterruptedException, NotAMucServiceException {
    if (!providesMucService(serviceName)) {
        throw new NotAMucServiceException(serviceName);
    }
    DiscoverItems discoverItems = serviceDiscoveryManager.discoverItems(serviceName);
    List<DiscoverItems.Item> items = discoverItems.getItems();

    Map<EntityBareJid, HostedRoom> answer = new HashMap<>(items.size());
    for (DiscoverItems.Item item : items) {
        HostedRoom hostedRoom = new HostedRoom(item);
        HostedRoom previousRoom = answer.put(hostedRoom.getJid(), hostedRoom);
        assert previousRoom == null;
    }

    return answer;
}
 
Example #2
Source File: MultiUserChatLightManager.java    From Smack with Apache License 2.0 6 votes vote down vote up
/**
 * Get users and rooms blocked.
 *
 * @param mucLightService TODO javadoc me please
 * @return the list of users and rooms blocked
 * @throws NoResponseException if there was no response from the remote entity.
 * @throws XMPPErrorException if there was an XMPP error returned.
 * @throws NotConnectedException if the XMPP connection is not connected.
 * @throws InterruptedException if the calling thread was interrupted.
 */
public List<Jid> getUsersAndRoomsBlocked(DomainBareJid mucLightService)
        throws NoResponseException, XMPPErrorException, NotConnectedException, InterruptedException {
    MUCLightBlockingIQ muclIghtBlockingIQResult = getBlockingList(mucLightService);

    List<Jid> jids = new ArrayList<>();
    if (muclIghtBlockingIQResult.getRooms() != null) {
        jids.addAll(muclIghtBlockingIQResult.getRooms().keySet());
    }

    if (muclIghtBlockingIQResult.getUsers() != null) {
        jids.addAll(muclIghtBlockingIQResult.getUsers().keySet());
    }

    return jids;
}
 
Example #3
Source File: ChatManager.java    From Spark with Apache License 2.0 6 votes vote down vote up
/**
 * Creates a new public Conference Room.
 *
 * @param roomName    the name of the room.
 * @param serviceName the service name to use (ex.conference.jivesoftware.com)
 * @return the new ChatRoom created. If an error occured, null will be returned.
 */
public ChatRoom createConferenceRoom(Localpart roomName, DomainBareJid serviceName) {
    EntityBareJid roomAddress = JidCreate.entityBareFrom(roomName, serviceName);
    final MultiUserChat chatRoom = MultiUserChatManager.getInstanceFor( SparkManager.getConnection()).getMultiUserChat( roomAddress);

    final GroupChatRoom room = UIComponentRegistry.createGroupChatRoom(chatRoom);

    try {
        LocalPreferences pref = SettingsManager.getLocalPreferences();
        Resourcepart nickname = pref.getNickname();
        chatRoom.create(nickname);

        // Send an empty room configuration form which indicates that we want
        // an instant room
        chatRoom.sendConfigurationForm(new Form( DataForm.Type.submit ));
    }
    catch (XMPPException | SmackException | InterruptedException e1) {
        Log.error("Unable to send conference room chat configuration form.", e1);
        return null;
    }

    getChatContainer().addChatRoom(room);
    return room;
}
 
Example #4
Source File: ChatManager.java    From Spark with Apache License 2.0 6 votes vote down vote up
/**
 * Returns the default conference service. (ex. conference.jivesoftware.com)
 *
 * @return the default conference service to interact with MUC.
 */
public String getDefaultConferenceService() {
    if (conferenceService == null) {
        try {
            final MultiUserChatManager multiUserChatManager = MultiUserChatManager.getInstanceFor( SparkManager.getConnection() );
            List<DomainBareJid> col = multiUserChatManager.getMucServiceDomains();
            if (col.size() > 0) {
                conferenceService = col.iterator().next().toString();
            }
        }
        catch (XMPPException | SmackException | InterruptedException e) {
            Log.error(e);
        }
    }

    return conferenceService;
}
 
Example #5
Source File: ConferenceServices.java    From Spark with Apache License 2.0 6 votes vote down vote up
private void startConference(Collection<ContactItem> items) {
    final ContactList contactList = SparkManager.getWorkspace().getContactList();
    List<Jid> jids = new ArrayList<>();
    for (ContactItem item : items) {
        ContactGroup contactGroup = contactList.getContactGroup(item.getGroupName());
        contactGroup.clearSelection();

        if (item.isAvailable()) {
            jids.add(item.getJid());
        }
    }

    Localpart userName = SparkManager.getSessionManager().getJID().getLocalpart();
    final EntityBareJid roomName = JidCreate.entityBareFromOrThrowUnchecked(userName + "_" + StringUtils.randomString(3));

    DomainBareJid serviceName = getDefaultServiceName();
    if (serviceName != null) {
        ConferenceUtils.inviteUsersToRoom(serviceName, roomName, jids, true);
    }
}
 
Example #6
Source File: Gateway.java    From Spark with Apache License 2.0 6 votes vote down vote up
/**
 * Returns the fully qualified JID of a user.
 *
 * @param serviceName the service the user belongs to.
 * @param username    the name of the user.
 * @return the JID.
 * @throws InterruptedException 
 */
public static String getJID(DomainBareJid serviceName, String username) throws SmackException.NotConnectedException, InterruptedException
{
    Gateway registration = new Gateway();
    registration.setType(IQ.Type.set);
    registration.setTo(serviceName);
    registration.setUsername(username);

    XMPPConnection con = SparkManager.getConnection();
    StanzaCollector collector = con.createStanzaCollector(new StanzaIdFilter(registration.getStanzaId()));
    try
    {
        con.sendStanza( registration );

        Gateway response = collector.nextResult();
        return response.getJid();
    }
    finally
    {
        collector.cancel();
    }
}
 
Example #7
Source File: ConferenceUtils.java    From Spark with Apache License 2.0 6 votes vote down vote up
/**
 * Invites users to an existing room.
 *
 * @param serviceName the service name to use.
 * @param roomName    the name of the room.
 * @param jids        a collection of the users to invite.
 */
public static void inviteUsersToRoom(DomainBareJid serviceName, EntityBareJid roomName, Collection<Jid> jids, boolean randomName) {
    final LocalPreferences pref = SettingsManager.getLocalPreferences();
    boolean useTextField = pref.isUseAdHocRoom();
    Collection<BookmarkedConference> rooms = null;
    if (!useTextField) {
        try {
            rooms = retrieveBookmarkedConferences();
        } catch (Exception ex) {
            Log.error(ex);
        }
        useTextField = !randomName || (rooms == null || rooms.size() == 0);
    }
    InvitationDialog inviteDialog = new InvitationDialog(useTextField);
    inviteDialog.inviteUsersToRoom(serviceName, rooms, roomName.toString(), jids);
}
 
Example #8
Source File: XmppTools.java    From Smack with Apache License 2.0 6 votes vote down vote up
public static boolean createAccount(DomainBareJid xmppDomain, Localpart username, String password)
        throws KeyManagementException, NoSuchAlgorithmException, SmackException, IOException, XMPPException,
        InterruptedException {
    XMPPTCPConnectionConfiguration.Builder configBuilder = XMPPTCPConnectionConfiguration.builder()
            .setXmppDomain(xmppDomain);
    TLSUtils.acceptAllCertificates(configBuilder);
    XMPPTCPConnectionConfiguration config = configBuilder.build();
    XMPPTCPConnection connection = new XMPPTCPConnection(config);
    connection.connect();
    try {
        if (!supportsIbr(connection))
            return false;

        AccountManager accountManager = AccountManager.getInstance(connection);
        accountManager.createAccount(username, password);
        return true;
    } finally {
        connection.disconnect();
    }
}
 
Example #9
Source File: STUN.java    From Smack with Apache License 2.0 6 votes vote down vote up
/**
 * Get a new STUN Server Address and port from the server.
 * If a error occurs or the server don't support STUN Service, null is returned.
 *
 * @param connection TODO javadoc me please
 * @return the STUN server address
 * @throws NotConnectedException if the XMPP connection is not connected.
 * @throws InterruptedException if the calling thread was interrupted.
 */
public static STUN getSTUNServer(XMPPConnection connection) throws NotConnectedException, InterruptedException {

    if (!connection.isConnected()) {
        return null;
    }

    STUN stunPacket = new STUN();
    DomainBareJid jid;
    try {
        jid = JidCreate.domainBareFrom(DOMAIN + "." + connection.getXMPPServiceDomain());
    } catch (XmppStringprepException e) {
        throw new AssertionError(e);
    }
    stunPacket.setTo(jid);

    StanzaCollector collector = connection.createStanzaCollectorAndSend(stunPacket);

    STUN response = collector.nextResult();

    // Cancel the collector.
    collector.cancel();

    return response;
}
 
Example #10
Source File: AbstractXMPPConnection.java    From Smack with Apache License 2.0 6 votes vote down vote up
protected void onStreamOpen(XmlPullParser parser) {
    // We found an opening stream.
    if ("jabber:client".equals(parser.getNamespace(null))) {
        streamId = parser.getAttributeValue("", "id");
        incomingStreamXmlEnvironment = XmlEnvironment.from(parser);

        String reportedServerDomainString = parser.getAttributeValue("", "from");
        if (reportedServerDomainString == null) {
            // RFC 6120 § 4.7.1. makes no explicit statement whether or not 'from' in the stream open from the server
            // in c2s connections is required or not.
            return;
        }
        DomainBareJid reportedServerDomain;
        try {
            reportedServerDomain = JidCreate.domainBareFrom(reportedServerDomainString);
            DomainBareJid configuredXmppServiceDomain = config.getXMPPServiceDomain();
            if (!configuredXmppServiceDomain.equals(reportedServerDomain)) {
                LOGGER.warning("Domain reported by server '" + reportedServerDomain
                        + "' does not match configured domain '" + configuredXmppServiceDomain + "'");
            }
        } catch (XmppStringprepException e) {
            LOGGER.log(Level.WARNING, "XMPP service domain '" + reportedServerDomainString
                    + "' as reported by server could not be transformed to a valid JID", e);
        }
    }
}
 
Example #11
Source File: ServiceDiscoveryManager.java    From Smack with Apache License 2.0 6 votes vote down vote up
public DomainBareJid findService(String feature, boolean useCache, String category, String type)
                throws NoResponseException, XMPPErrorException, NotConnectedException,
                InterruptedException {
    boolean noCategory = StringUtils.isNullOrEmpty(category);
    boolean noType = StringUtils.isNullOrEmpty(type);
    if (noType != noCategory) {
        throw new IllegalArgumentException("Must specify either both, category and type, or none");
    }

    List<DiscoverInfo> services = findServicesDiscoverInfo(feature, false, useCache);
    if (services.isEmpty()) {
        return null;
    }

    if (!noCategory && !noType) {
        for (DiscoverInfo info : services) {
            if (info.hasIdentity(category, type)) {
                return info.getFrom().asDomainBareJid();
            }
        }
    }

    return services.get(0).getFrom().asDomainBareJid();
}
 
Example #12
Source File: TransportUtils.java    From Spark with Apache License 2.0 6 votes vote down vote up
/**
 * Registers a user with a gateway.
 *
 * @param con           the XMPPConnection.
 * @param gatewayDomain the domain of the gateway (service name)
 * @param username      the username.
 * @param password      the password.
 * @param nickname      the nickname.
 * @throws InterruptedException 
 * @throws XMPPException thrown if there was an issue registering with the gateway.
 */
public static void registerUser(XMPPConnection con, DomainBareJid gatewayDomain, String username, String password, String nickname, StanzaListener callback) throws SmackException.NotConnectedException, InterruptedException
{
    Map<String, String> attributes = new HashMap<>();
    if (username != null) {
        attributes.put("username", username);
    }
    if (password != null) {
        attributes.put("password", password);
    }
    if (nickname != null) {
        attributes.put("nick", nickname);
    }
    Registration registration = new Registration( attributes );
    registration.setType(IQ.Type.set);
    registration.setTo(gatewayDomain);
    registration.addExtension(new GatewayRegisterExtension());

    con.sendStanzaWithResponseCallback( registration, new IQReplyFilter( registration, con ), callback);
}
 
Example #13
Source File: MultiUserChatLowLevelIntegrationTest.java    From Smack with Apache License 2.0 5 votes vote down vote up
@SmackIntegrationTest
public void testMucBookmarksAutojoin(AbstractXMPPConnection connection) throws InterruptedException,
                TestNotPossibleException, XMPPException, SmackException, IOException {
    final BookmarkManager bookmarkManager = BookmarkManager.getBookmarkManager(connection);
    if (!bookmarkManager.isSupported()) {
        throw new TestNotPossibleException("Private data storage not supported");
    }
    final MultiUserChatManager multiUserChatManager = MultiUserChatManager.getInstanceFor(connection);
    final Resourcepart mucNickname = Resourcepart.from("Nick-" + StringUtils.randomString(6));
    final String randomMucName = StringUtils.randomString(6);
    final DomainBareJid mucComponent = multiUserChatManager.getMucServiceDomains().get(0);
    final MultiUserChat muc = multiUserChatManager.getMultiUserChat(JidCreate.entityBareFrom(
                    Localpart.from(randomMucName), mucComponent));

    MucCreateConfigFormHandle handle = muc.createOrJoin(mucNickname);
    if (handle != null) {
        handle.makeInstant();
    }
    muc.leave();

    bookmarkManager.addBookmarkedConference("Smack Inttest: " + testRunId, muc.getRoom(), true,
                    mucNickname, null);

    connection.disconnect();
    connection.connect().login();

    // MucBookmarkAutojoinManager is also able to do its task automatically
    // after every login, it's not deterministic when this will be finished.
    // So we trigger it manually here.
    MucBookmarkAutojoinManager.getInstanceFor(connection).autojoinBookmarkedConferences();

   assertTrue(muc.isJoined());

   // If the test went well, leave the MUC
   muc.leave();
}
 
Example #14
Source File: BookmarksUI.java    From Spark with Apache License 2.0 5 votes vote down vote up
public void browseRooms(String serviceNameString) {
    DomainBareJid serviceName;
    try {
        serviceName = JidCreate.domainBareFrom(serviceNameString);
    } catch (XmppStringprepException e) {
        throw new IllegalStateException(e);
    }
    browseRooms(serviceName);
}
 
Example #15
Source File: FastpathPlugin.java    From Spark with Apache License 2.0 5 votes vote down vote up
private void leaveWorkgroup() {
    workgroupLabel.setText(FpRes.getString("workgroup") + ":");
    logoutButton.setVisible(false);
    joinButton.setVisible(true);
    comboBox.setVisible(true);

    comboBox.removeAllItems();
    // Log into workgroup
    DomainBareJid workgroupService = JidCreate.domainBareFromOrThrowUnchecked("workgroup." + SparkManager.getSessionManager().getServerAddress());
    EntityFullJid jid = SparkManager.getSessionManager().getJID();

    try {
        Collection<String> col = Agent.getWorkgroups(workgroupService, jid, SparkManager.getConnection());
        // Add workgroups to combobox
        Iterator<String> workgroups = col.iterator();
        while (workgroups.hasNext()) {
            String workgroup = workgroups.next();
            String componentAddress = XmppStringUtils.parseDomain(workgroup);
            setComponentAddress(componentAddress);
            comboBox.addItem(XmppStringUtils.parseLocalpart(workgroup));
        }
    }
    catch (XMPPException | SmackException | InterruptedException ee) {
        // If the user does not belong to a workgroup, then don't initialize the rest of the plugin.
        return;
    }

    try {
        agentSession.setOnline(false);
    }
    catch (XMPPException | SmackException | InterruptedException e1) {
        Log.error(e1);
    }
    litWorkspace.unload();
    wgroup = null;

    // UnRegister tab handler
    SparkManager.getChatManager().removeSparkTabHandler(fastpathTabHandler);
}
 
Example #16
Source File: TransportUtils.java    From Spark with Apache License 2.0 5 votes vote down vote up
public static void setAutoJoin(DomainBareJid serviceName, boolean autoJoin) {
	if (gatewayPreferences != null) {
		gatewayPreferences.addService(serviceName, autoJoin);
		PrivateDataManager pdm = SparkManager.getSessionManager().getPersonalDataManager();
		try {
			pdm.setPrivateData(gatewayPreferences);
		}
		catch (XMPPException | SmackException | InterruptedException e) {
			Log.error(e);
		}
	} else {
		Log.warning("Cannot set privacy data as gatewayPreferences is NULL");
	}
}
 
Example #17
Source File: JidCreate.java    From jxmpp with Apache License 2.0 5 votes vote down vote up
/**
 * Get a {@link DomainBareJid} from a given {@link CharSequence} or {@code null} if the input does not represent a JID.
 *
 * @param cs the input {@link CharSequence}
 * @return a JID or {@code null}
 */
public static DomainBareJid domainBareFromOrNull(CharSequence cs) {
	try {
		return domainBareFrom(cs);
	} catch (XmppStringprepException e) {
		return null;
	}
}
 
Example #18
Source File: MultiUserChatLightManager.java    From Smack with Apache License 2.0 5 votes vote down vote up
/**
 * Get rooms blocked.
 *
 * @param mucLightService TODO javadoc me please
 * @return the list of rooms blocked
 * @throws NoResponseException if there was no response from the remote entity.
 * @throws XMPPErrorException if there was an XMPP error returned.
 * @throws NotConnectedException if the XMPP connection is not connected.
 * @throws InterruptedException if the calling thread was interrupted.
 */
public List<Jid> getRoomsBlocked(DomainBareJid mucLightService)
        throws NoResponseException, XMPPErrorException, NotConnectedException, InterruptedException {
    MUCLightBlockingIQ mucLightBlockingIQResult = getBlockingList(mucLightService);

    List<Jid> jids = new ArrayList<>();
    if (mucLightBlockingIQResult.getRooms() != null) {
        jids.addAll(mucLightBlockingIQResult.getRooms().keySet());
    }

    return jids;
}
 
Example #19
Source File: SlotRequest.java    From Smack with Apache License 2.0 5 votes vote down vote up
protected SlotRequest(DomainBareJid uploadServiceAddress, String filename, long size, String contentType, String namespace) {
    super(ELEMENT, namespace);

    if (size <= 0) {
        throw new IllegalArgumentException("File fileSize must be greater than zero.");
    }

    this.filename = filename;
    this.size = size;
    this.contentType = contentType;

    setType(Type.get);
    setTo(uploadServiceAddress);
}
 
Example #20
Source File: XmppConnection.java    From Zom-Android-XMPP with GNU General Public License v3.0 5 votes vote down vote up
@Override
public String getDefaultGroupChatService ()
{
    try {
        // Create a MultiUserChat using a Connection for a room
        //TODO fix this with new smack
        MultiUserChatManager mucMgr = MultiUserChatManager.getInstanceFor(mConnection);

        if (!mucMgr.providesMucService(JidCreate.domainBareFrom(mUserJid)))
            return DEFAULT_CONFERENCE_SERVER;

        Collection<DomainBareJid> servers = mucMgr.getXMPPServiceDomains();

        //just grab the first one
        for (DomainBareJid server : servers)
            return server.toString();

    }
    catch (Exception xe)
    {
        Log.w(TAG, "Error discovering MUC server",xe);

        //unable to find conference server
        return DEFAULT_CONFERENCE_SERVER;
    }

    return DEFAULT_CONFERENCE_SERVER;
}
 
Example #21
Source File: XMPP.java    From XMPPSample_Studio with Apache License 2.0 5 votes vote down vote up
private XMPPTCPConnectionConfiguration buildConfiguration() throws XmppStringprepException {
    XMPPTCPConnectionConfiguration.Builder builder =
            XMPPTCPConnectionConfiguration.builder();


    builder.setHost(HOST1);
    builder.setPort(PORT);
    builder.setCompressionEnabled(false);
    builder.setDebuggerEnabled(true);
    builder.setSecurityMode(ConnectionConfiguration.SecurityMode.disabled);
    builder.setSendPresence(true);
    if (Build.VERSION.SDK_INT >= 14) {
        builder.setKeystoreType("AndroidCAStore");
        // config.setTruststorePassword(null);
        builder.setKeystorePath(null);
    } else {
        builder.setKeystoreType("BKS");
        String str = System.getProperty("javax.net.ssl.trustStore");
        if (str == null) {
            str = System.getProperty("java.home") + File.separator + "etc" + File.separator + "security"
                    + File.separator + "cacerts.bks";
        }
        builder.setKeystorePath(str);
    }
    DomainBareJid serviceName = JidCreate.domainBareFrom(HOST);
    builder.setServiceName(serviceName);


    return builder.build();
}
 
Example #22
Source File: MultiUserChatLightManager.java    From Smack with Apache License 2.0 5 votes vote down vote up
private void sendUnblockRooms(DomainBareJid mucLightService, HashMap<Jid, Boolean> rooms)
        throws NoResponseException, XMPPErrorException, InterruptedException, NotConnectedException {
    MUCLightBlockingIQ mucLightBlockingIQ = new MUCLightBlockingIQ(rooms, null);
    mucLightBlockingIQ.setType(Type.set);
    mucLightBlockingIQ.setTo(mucLightService);
    connection().createStanzaCollectorAndSend(mucLightBlockingIQ).nextResultOrThrow();
}
 
Example #23
Source File: XmppTools.java    From Smack with Apache License 2.0 5 votes vote down vote up
public static boolean createAccount(String xmppDomain, String username, String password)
        throws KeyManagementException, NoSuchAlgorithmException, SmackException, IOException, XMPPException,
        InterruptedException {
    DomainBareJid xmppDomainJid = JidCreate.domainBareFrom(xmppDomain);
    Localpart localpart = Localpart.from(username);
    return createAccount(xmppDomainJid, localpart, password);
}
 
Example #24
Source File: ChatManager.java    From Spark with Apache License 2.0 5 votes vote down vote up
/**
 * Creates a new public Conference Room.
 *
 * @param roomName    the name of the room.
 * @param serviceName the service name to use (ex.conference.jivesoftware.com)
 * @return the new ChatRoom created. If an error occured, null will be returned.
 * @deprecated use {@link #createConferenceRoom(Localpart, DomainBareJid)} instead.
 */
@Deprecated
public ChatRoom createConferenceRoom(String roomName, String serviceName) {
    DomainBareJid serviceAddress;
    Localpart localpart;
    try {
        localpart = Localpart.from(roomName);
        serviceAddress = JidCreate.domainBareFrom(serviceName);
    } catch (XmppStringprepException e) {
        throw new IllegalStateException(e);
    }
    return createConferenceRoom(localpart, serviceAddress);
}
 
Example #25
Source File: AbstractXMPPConnection.java    From Smack with Apache License 2.0 5 votes vote down vote up
@Override
public DomainBareJid getXMPPServiceDomain() {
    if (xmppServiceDomain != null) {
        return xmppServiceDomain;
    }
    return config.getXMPPServiceDomain();
}
 
Example #26
Source File: SASLAuthentication.java    From Smack with Apache License 2.0 5 votes vote down vote up
/**
 * Performs SASL authentication of the specified user. If SASL authentication was successful
 * then resource binding and session establishment will be performed. This method will return
 * the full JID provided by the server while binding a resource to the connection.<p>
 *
 * The server may assign a full JID with a username or resource different than the requested
 * by this method.
 *
 * @param username the username that is authenticating with the server.
 * @param password the password to send to the server.
 * @param authzid the authorization identifier (typically null).
 * @param sslSession the optional SSL/TLS session (if one was established)
 * @return the used SASLMechanism.
 * @throws XMPPErrorException if there was an XMPP error returned.
 * @throws SASLErrorException if a SASL protocol error was returned.
 * @throws IOException if an I/O error occurred.
 * @throws InterruptedException if the calling thread was interrupted.
 * @throws SmackSaslException if a SASL specific error occurred.
 * @throws NotConnectedException if the XMPP connection is not connected.
 * @throws NoResponseException if there was no response from the remote entity.
 */
SASLMechanism authenticate(String username, String password, EntityBareJid authzid, SSLSession sslSession)
                throws XMPPErrorException, SASLErrorException, IOException,
                InterruptedException, SmackSaslException, NotConnectedException, NoResponseException {
    final SASLMechanism mechanism = selectMechanism(authzid);
    final CallbackHandler callbackHandler = configuration.getCallbackHandler();
    final String host = connection.getHost();
    final DomainBareJid xmppServiceDomain = connection.getXMPPServiceDomain();

    synchronized (this) {
        currentMechanism = mechanism;

        if (callbackHandler != null) {
            currentMechanism.authenticate(host, xmppServiceDomain, callbackHandler, authzid, sslSession);
        }
        else {
            currentMechanism.authenticate(username, host, xmppServiceDomain, password, authzid, sslSession);
        }

        final long deadline = System.currentTimeMillis() + connection.getReplyTimeout();
        while (!mechanism.isFinished()) {
            final long now = System.currentTimeMillis();
            if (now >= deadline) break;
            // Wait until SASL negotiation finishes
            wait(deadline - now);
        }
    }

    mechanism.throwExceptionIfRequired();

    return mechanism;
}
 
Example #27
Source File: PubSubIntegrationTest.java    From Smack with Apache License 2.0 5 votes vote down vote up
public PubSubIntegrationTest(SmackIntegrationTestEnvironment environment)
                throws TestNotPossibleException, NoResponseException, XMPPErrorException,
                NotConnectedException, InterruptedException {
    super(environment);
    DomainBareJid pubSubService = PubSubManager.getPubSubService(conOne);
    if (pubSubService == null) {
        throw new TestNotPossibleException("No PubSub service found");
    }
    pubSubManagerOne = PubSubManager.getInstanceFor(conOne, pubSubService);
    if (!pubSubManagerOne.canCreateNodesAndPublishItems()) {
        throw new TestNotPossibleException("PubSub service does not allow node creation");
    }
}
 
Example #28
Source File: Workgroup.java    From Smack with Apache License 2.0 5 votes vote down vote up
/**
 * The workgroup service may be configured to send email. This queries the Workgroup Service
 * to see if the email service has been configured and is available.
 *
 * @return true if the email service is available, otherwise return false.
 * @throws SmackException if Smack detected an exceptional situation.
 * @throws InterruptedException if the calling thread was interrupted.
 */
public boolean isEmailAvailable() throws SmackException, InterruptedException {
    ServiceDiscoveryManager discoManager = ServiceDiscoveryManager.getInstanceFor(connection);

    try {
        DomainBareJid workgroupService = workgroupJID.asDomainBareJid();
        DiscoverInfo infoResult = discoManager.discoverInfo(workgroupService);
        return infoResult.containsFeature("jive:email:provider");
    }
    catch (XMPPException e) {
        return false;
    }
}
 
Example #29
Source File: RTPBridge.java    From Smack with Apache License 2.0 5 votes vote down vote up
/**
 * Check if the server support RTPBridge Service.
 *
 * @param connection TODO javadoc me please
 * @param sessionID the session id.
 * @param pass the password.
 * @param proxyCandidate the proxy candidate.
 * @param localCandidate the local candidate.
 * @return the RTPBridge
 * @throws NotConnectedException if the XMPP connection is not connected.
 * @throws InterruptedException if the calling thread was interrupted.
 */
public static RTPBridge relaySession(XMPPConnection connection, String sessionID, String pass, TransportCandidate proxyCandidate, TransportCandidate localCandidate) throws NotConnectedException, InterruptedException {

    if (!connection.isConnected()) {
        return null;
    }

    RTPBridge rtpPacket = new RTPBridge(sessionID, RTPBridge.BridgeAction.change);
    DomainBareJid jid;
    try {
        jid = JidCreate.domainBareFrom(RTPBridge.NAME + "." + connection.getXMPPServiceDomain());
    } catch (XmppStringprepException e) {
        throw new AssertionError(e);
    }
    rtpPacket.setTo(jid);
    rtpPacket.setType(Type.set);

    rtpPacket.setPass(pass);
    rtpPacket.setPortA(localCandidate.getPort());
    rtpPacket.setPortB(proxyCandidate.getPort());
    rtpPacket.setHostA(localCandidate.getIp());
    rtpPacket.setHostB(proxyCandidate.getIp());

    // LOGGER.debug("Relayed to: " + candidate.getIp() + ":" + candidate.getPort());

    StanzaCollector collector = connection.createStanzaCollectorAndSend(rtpPacket);

    RTPBridge response = collector.nextResult();

    // Cancel the collector.
    collector.cancel();

    return response;
}
 
Example #30
Source File: MultiUserChatManager.java    From Smack with Apache License 2.0 5 votes vote down vote up
/**
 * Check if the provided domain bare JID provides a MUC service.
 *
 * @param domainBareJid the domain bare JID to check.
 * @return <code>true</code> if the provided JID provides a MUC service, <code>false</code> otherwise.
 * @throws NoResponseException if there was no response from the remote entity.
 * @throws XMPPErrorException if there was an XMPP error returned.
 * @throws NotConnectedException if the XMPP connection is not connected.
 * @throws InterruptedException if the calling thread was interrupted.
 * @see <a href="http://xmpp.org/extensions/xep-0045.html#disco-service-features">XEP-45 § 6.2 Discovering the Features Supported by a MUC Service</a>
 * @since 4.2
 */
public boolean providesMucService(DomainBareJid domainBareJid) throws NoResponseException,
                XMPPErrorException, NotConnectedException, InterruptedException {
    boolean contains = KNOWN_MUC_SERVICES.containsKey(domainBareJid);
    if (!contains) {
        if (serviceDiscoveryManager.supportsFeature(domainBareJid,
                    MUCInitialPresence.NAMESPACE)) {
            KNOWN_MUC_SERVICES.put(domainBareJid, null);
            return true;
        }
    }

    return contains;
}