org.jivesoftware.smack.ConnectionConfiguration.SecurityMode Java Examples

The following examples show how to use org.jivesoftware.smack.ConnectionConfiguration.SecurityMode. 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: XmppLogin.java    From xyTalk-pc with GNU Affero General Public License v3.0 6 votes vote down vote up
protected XMPPTCPConnectionConfiguration retrieveConnectionConfiguration() {

		try {

			DebugUtil.debug("login:" + getUsername() + "--" + getPassword() + "--" + Launcher.HOSTPORT + "--"
					+ Launcher.DOMAIN + "--" + InetAddress.getByName(Launcher.HOSTNAME));

			XMPPTCPConnectionConfiguration.Builder builder = XMPPTCPConnectionConfiguration.builder()
					.setUsernameAndPassword(getUsername(), getPassword()).setResource(Launcher.RESOURCE)
					.setPort(Launcher.HOSTPORT).setConnectTimeout(5000).setXmppDomain(Launcher.DOMAIN)
					.setHost(Launcher.HOSTNAME).setHostAddress(InetAddress.getByName(Launcher.HOSTNAME)) .setSecurityMode(SecurityMode.disabled)
					.setDebuggerEnabled(true).setSendPresence(true);
			DebugUtil.debug("builder:" + builder.toString());
			return builder.build();

		} catch (Exception e) {

			e.printStackTrace();
		}
		return null;
	}
 
Example #2
Source File: XmppManager.java    From weixin with Apache License 2.0 6 votes vote down vote up
/**
 * 与服务器建立连接
 * 
 * @return
 */
public boolean connectServer() {
	ConnectionConfiguration connConfig = new ConnectionConfiguration(xmppHost, Integer.parseInt(xmppPort));
	//设置安全模式
	connConfig.setSecurityMode(SecurityMode.required);
	//设置SASL认证是否启用
	connConfig.setSASLAuthenticationEnabled(false);
	//设置数据压缩是否启用
	connConfig.setCompressionEnabled(false);
	//是否启用调试模式
	connConfig.setDebuggerEnabled(true);

	/** 创建connection连接 */
	XMPPConnection connection = new XMPPConnection(connConfig);
	this.setConnection(connection);

	try {
		// 连接到服务器
		connection.connect();
		L.i(LOGTAG, "XMPP connected successfully");
		return true;
	} catch (XMPPException e) {
		L.e(LOGTAG, "XMPP connection failed", e);
	}
	return false;
}
 
Example #3
Source File: XmppTcpTransportModule.java    From Smack with Apache License 2.0 6 votes vote down vote up
@Override
public StateTransitionResult.TransitionImpossible isTransitionToPossible(WalkStateGraphContext walkStateGraphContext)
        throws SecurityRequiredByClientException, SecurityRequiredByServerException {
    StartTls startTlsFeature = connectionInternal.connection.getFeature(StartTls.ELEMENT, StartTls.NAMESPACE);
    SecurityMode securityMode = connectionInternal.connection.getConfiguration().getSecurityMode();

    switch (securityMode) {
    case required:
    case ifpossible:
        if (startTlsFeature == null) {
            if (securityMode == SecurityMode.ifpossible) {
                return new StateTransitionResult.TransitionImpossibleReason("Server does not announce support for TLS and we do not required it");
            }
            throw new SecurityRequiredByClientException();
        }
        // Allows transition by returning null.
        return null;
    case disabled:
        if (startTlsFeature != null && startTlsFeature.required()) {
            throw new SecurityRequiredByServerException();
        }
        return new StateTransitionResult.TransitionImpossibleReason("TLS disabled in client settings and server does not require it");
    default:
        throw new AssertionError("Unknown security mode: " + securityMode);
    }
}
 
Example #4
Source File: AbstractXMPPConnection.java    From Smack with Apache License 2.0 6 votes vote down vote up
protected final void parseFeaturesAndNotify(XmlPullParser parser) throws Exception {
    parseFeatures(parser);

    if (hasFeature(Mechanisms.ELEMENT, Mechanisms.NAMESPACE)) {
        // Only proceed with SASL auth if TLS is disabled or if the server doesn't announce it
        if (!hasFeature(StartTls.ELEMENT, StartTls.NAMESPACE)
                        || config.getSecurityMode() == SecurityMode.disabled) {
            tlsHandled = saslFeatureReceived = true;
            notifyWaitingThreads();
        }
    }

    // If the server reported the bind feature then we are that that we did SASL and maybe
    // STARTTLS. We can then report that the last 'stream:features' have been parsed
    if (hasFeature(Bind.ELEMENT, Bind.NAMESPACE)) {
        if (!hasFeature(Compress.Feature.ELEMENT, Compress.NAMESPACE)
                        || !config.isCompressionEnabled()) {
            // This where the last stream features from the server, either it did not contain
            // compression or we disabled it.
            lastFeaturesReceived = true;
            notifyWaitingThreads();
        }
    }
    afterFeaturesReceived();
}
 
Example #5
Source File: SmackGcmSenderChannel.java    From arcusplatform with Apache License 2.0 5 votes vote down vote up
/**
 * Connects to GCM Cloud Connection Server using the supplied credentials.
 *
 * @param senderId
 *            Your GCM project number
 * @param apiKey
 *            API Key of your project
 */
protected void connect(long senderId, String apiKey, int keepAliveInterval) throws XMPPException, IOException, SmackException {

    // Configure connection
    ConnectionConfiguration config = new ConnectionConfiguration(GcmServiceConstants.GCM_SERVER, GcmServiceConstants.GCM_PORT);
    config.setSecurityMode(SecurityMode.enabled);
    config.setReconnectionAllowed(true);
    config.setRosterLoadedAtLogin(false);
    config.setSendPresence(false);
    config.setSocketFactory(SSLSocketFactory.getDefault());

    // Create connection object and initiate connection
    connection = new XMPPTCPConnection(config);
    pingManager = PingManager.getInstanceFor(connection);
    pingManager.setPingInterval(keepAliveInterval);
    pingManager.registerPingFailedListener(this);
    connection.connect();

    // Register listener to log connection state events
    connection.addConnectionListener(new SmackLoggingConnectionListener());

    // Handle incoming messages (delivery receipts and Google control messages)
    connection.addPacketListener(upstreamListener, new PacketTypeFilter(Message.class));

    // Log in...
    connection.login(senderId + "@" + GcmServiceConstants.GCM_SERVER, apiKey);
}
 
Example #6
Source File: XmppManager.java    From androidpn-client with Apache License 2.0 5 votes vote down vote up
public void run() {
    Log.i(LOGTAG, "ConnectTask.run()...");
    boolean connected = false;
    if (!xmppManager.isConnected()) {
        // Create the configuration for this new connection
        ConnectionConfiguration connConfig = new ConnectionConfiguration(
                xmppHost, xmppPort);
        // connConfig.setSecurityMode(SecurityMode.disabled);
        connConfig.setSecurityMode(SecurityMode.required);
        connConfig.setSASLAuthenticationEnabled(false);
        connConfig.setCompressionEnabled(false);

        XMPPConnection connection = new XMPPConnection(connConfig);
        xmppManager.setConnection(connection);

        try {
            // Connect to the server
            connection.connect();
            Log.i(LOGTAG, "XMPP connected successfully");

            // packet provider
            ProviderManager.getInstance().addIQProvider("notification",
                    "androidpn:iq:notification",
                    new NotificationIQProvider());
            connected = true;

        } catch (XMPPException e) {
            Log.e(LOGTAG, "XMPP connection failed", e);
        }

        if (connected) {
            xmppManager.runTask();
        }

    } else {
        Log.i(LOGTAG, "XMPP connected already");
        xmppManager.runTask();
    }
}
 
Example #7
Source File: ClientConService.java    From weixin with Apache License 2.0 5 votes vote down vote up
public boolean login(String account, String password) {
	ConnectionConfiguration connConfig = new ConnectionConfiguration(xmppHost, Integer.parseInt(xmppPort));
	//设置安全模式
	connConfig.setSecurityMode(SecurityMode.required);
	//设置SASL认证是否启用
	connConfig.setSASLAuthenticationEnabled(false);
	//设置数据压缩是否启用
	connConfig.setCompressionEnabled(false);
	//是否启用调试模式
	connConfig.setDebuggerEnabled(true);

	/** 创建connection连接 */
	XMPPConnection connection = new XMPPConnection(connConfig);
	setConnection(connection);

	try {
		// 连接到服务器
		connection.connect();
		L.i(LOGTAG, "XMPP connected successfully");

		//登陆
		connection.login(account, password);

		/** 开启读写线程,并加入到管理类中 */
		//ClientSendThread cst = new ClientSendThread(connection);
		//cst.start();
		//ManageClientThread.addClientSendThread(account,cst);

		return true;
	} catch (XMPPException e) {
		L.e(LOGTAG, "XMPP connection failed", e);
	}
	return false;
}
 
Example #8
Source File: XMPPTCPConnection.java    From Smack with Apache License 2.0 5 votes vote down vote up
@Override
protected void afterFeaturesReceived() throws NotConnectedException, InterruptedException, SecurityRequiredByServerException {
    StartTls startTlsFeature = getFeature(StartTls.ELEMENT, StartTls.NAMESPACE);
    if (startTlsFeature != null) {
        if (startTlsFeature.required() && config.getSecurityMode() == SecurityMode.disabled) {
            SecurityRequiredByServerException smackException = new SecurityRequiredByServerException();
            currentSmackException = smackException;
            notifyWaitingThreads();
            throw smackException;
        }

        if (config.getSecurityMode() != ConnectionConfiguration.SecurityMode.disabled) {
            sendNonza(new StartTls());
        } else {
            tlsHandled = true;
            notifyWaitingThreads();
        }
    } else {
        tlsHandled = true;
        notifyWaitingThreads();
    }

    if (isSaslAuthenticated()) {
        // If we have received features after the SASL has been successfully completed, then we
        // have also *maybe* received, as it is an optional feature, the compression feature
        // from the server.
        streamFeaturesAfterAuthenticationReceived = true;
        notifyWaitingThreads();
    }
}
 
Example #9
Source File: AbstractXMPPConnection.java    From Smack with Apache License 2.0 5 votes vote down vote up
/**
 * Establishes a connection to the XMPP server. It basically
 * creates and maintains a connection to the server.
 * <p>
 * Listeners will be preserved from a previous connection.
 * </p>
 *
 * @throws XMPPException if an error occurs on the XMPP protocol level.
 * @throws SmackException if an error occurs somewhere else besides XMPP protocol level.
 * @throws IOException if an I/O error occurred.
 * @return a reference to this object, to chain <code>connect()</code> with <code>login()</code>.
 * @throws InterruptedException if the calling thread was interrupted.
 */
public synchronized AbstractXMPPConnection connect() throws SmackException, IOException, XMPPException, InterruptedException {
    // Check if not already connected
    throwAlreadyConnectedExceptionIfAppropriate();

    // Reset the connection state
    initState();
    closingStreamReceived = false;
    streamId = null;

    try {
        // Perform the actual connection to the XMPP service
        connectInternal();

        // If TLS is required but the server doesn't offer it, disconnect
        // from the server and throw an error. First check if we've already negotiated TLS
        // and are secure, however (features get parsed a second time after TLS is established).
        if (!isSecureConnection() && getConfiguration().getSecurityMode() == SecurityMode.required) {
            throw new SecurityRequiredByClientException();
        }
    } catch (SmackException | IOException | XMPPException | InterruptedException e) {
        instantShutdown();
        throw e;
    }

    // Make note of the fact that we're now connected.
    connected = true;
    callConnectionConnectedListener();

    return this;
}
 
Example #10
Source File: Configuration.java    From Smack with Apache License 2.0 5 votes vote down vote up
public Builder setSecurityMode(String securityModeString) {
    if (securityModeString != null) {
        securityMode = SecurityMode.valueOf(securityModeString);
    }
    else {
        securityMode = SecurityMode.required;
    }
    return this;
}
 
Example #11
Source File: IoT.java    From Smack with Apache License 2.0 5 votes vote down vote up
public static void iotScenario(String dataThingJidString, String dataThingPassword, String readingThingJidString,
        String readingThingPassword, IotScenario scenario) throws Exception {
    final EntityBareJid dataThingJid = JidCreate.entityBareFrom(dataThingJidString);
    final EntityBareJid readingThingJid = JidCreate.entityBareFrom(readingThingJidString);

    final XMPPTCPConnectionConfiguration dataThingConnectionConfiguration = XMPPTCPConnectionConfiguration.builder()
            .setUsernameAndPassword(dataThingJid.getLocalpart(), dataThingPassword)
            .setXmppDomain(dataThingJid.asDomainBareJid()).setSecurityMode(SecurityMode.disabled)
            .enableDefaultDebugger().build();
    final XMPPTCPConnectionConfiguration readingThingConnectionConfiguration = XMPPTCPConnectionConfiguration
            .builder().setUsernameAndPassword(readingThingJid.getLocalpart(), readingThingPassword)
            .setXmppDomain(readingThingJid.asDomainBareJid()).setSecurityMode(SecurityMode.disabled)
            .enableDefaultDebugger().build();

    final XMPPTCPConnection dataThingConnection = new XMPPTCPConnection(dataThingConnectionConfiguration);
    final XMPPTCPConnection readingThingConnection = new XMPPTCPConnection(readingThingConnectionConfiguration);

    dataThingConnection.setReplyTimeout(TIMEOUT);
    readingThingConnection.setReplyTimeout(TIMEOUT);

    dataThingConnection.setUseStreamManagement(false);
    readingThingConnection.setUseStreamManagement(false);

    try {
        dataThingConnection.connect().login();
        readingThingConnection.connect().login();
        scenario.iotScenario(dataThingConnection, readingThingConnection);
    } finally {
        dataThingConnection.disconnect();
        readingThingConnection.disconnect();
    }
}
 
Example #12
Source File: SmackIntegrationTestFramework.java    From Smack with Apache License 2.0 4 votes vote down vote up
public synchronized TestRunResult run()
        throws KeyManagementException, NoSuchAlgorithmException, SmackException, IOException, XMPPException,
        InterruptedException, InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {
    // The DNS resolver is not really a per sinttest run setting. It is not even a per connection setting. Instead
    // it is a global setting, but we treat it like a per sinttest run setting.
    switch (config.dnsResolver) {
    case minidns:
        MiniDnsResolver.setup();
        break;
    case javax:
        JavaxResolver.setup();
        break;
    case dnsjava:
        DNSJavaResolver.setup();
        break;
    }
    testRunResult = new TestRunResult();

    // Create a connection manager *after* we created the testRunId (in testRunResult).
    this.connectionManager = new XmppConnectionManager(this);

    LOGGER.info("SmackIntegrationTestFramework [" + testRunResult.testRunId + ']' + ": Starting\nSmack version: " + SmackConfiguration.getVersion());
    if (config.debugger != Configuration.Debugger.none) {
        // JUL Debugger will not print any information until configured to print log messages of
        // level FINE
        // TODO configure JUL for log?
        SmackConfiguration.addDisabledSmackClass("org.jivesoftware.smack.debugger.JulDebugger");
        SmackConfiguration.DEBUG = true;
    }
    if (config.replyTimeout > 0) {
        SmackConfiguration.setDefaultReplyTimeout(config.replyTimeout);
    }
    if (config.securityMode != SecurityMode.required && config.accountRegistration == AccountRegistration.inBandRegistration) {
        AccountManager.sensitiveOperationOverInsecureConnectionDefault(true);
    }
    // TODO print effective configuration

    String[] testPackages;
    if (config.testPackages == null || config.testPackages.isEmpty()) {
        testPackages = new String[] { "org.jivesoftware.smackx", "org.jivesoftware.smack" };
    }
    else {
        testPackages = config.testPackages.toArray(new String[config.testPackages.size()]);
    }
    Reflections reflections = new Reflections(testPackages, new SubTypesScanner(),
                    new TypeAnnotationsScanner(), new MethodAnnotationsScanner(), new MethodParameterScanner());
    Set<Class<? extends AbstractSmackIntegrationTest>> inttestClasses = reflections.getSubTypesOf(AbstractSmackIntegrationTest.class);
    Set<Class<? extends AbstractSmackLowLevelIntegrationTest>> lowLevelInttestClasses = reflections.getSubTypesOf(AbstractSmackLowLevelIntegrationTest.class);

    Set<Class<? extends AbstractSmackIntTest>> classes = new HashSet<>(inttestClasses.size()
                    + lowLevelInttestClasses.size());
    classes.addAll(inttestClasses);
    classes.addAll(lowLevelInttestClasses);

    {
        // Remove all abstract classes.
        // TODO: This may be a good candidate for Java stream filtering once Smack is Android API 24 or higher.
        Iterator<Class<? extends AbstractSmackIntTest>> it = classes.iterator();
        while (it.hasNext()) {
            Class<? extends AbstractSmackIntTest> clazz = it.next();
            if (Modifier.isAbstract(clazz.getModifiers())) {
                it.remove();
            }
        }
    }

    if (classes.isEmpty()) {
        throw new IllegalStateException("No test classes found");
    }

    LOGGER.info("SmackIntegrationTestFramework [" + testRunResult.testRunId
                    + "]: Finished scanning for tests, preparing environment");
    environment = prepareEnvironment();

    try {
        runTests(classes);
    }
    catch (Throwable t) {
        // Log the thrown Throwable to prevent it being shadowed in case the finally block below also throws.
        LOGGER.log(Level.SEVERE, "Unexpected abort because runTests() threw throwable", t);
        throw t;
    }
    finally {
        // Ensure that the accounts are deleted and disconnected before we continue
        connectionManager.disconnectAndCleanup();
    }

    return testRunResult;
}
 
Example #13
Source File: Nio.java    From Smack with Apache License 2.0 4 votes vote down vote up
public static void doNio(String username, String password, String service)
        throws SmackException, IOException, XMPPException, InterruptedException {
    boolean useTls = true;
    boolean useStreamMangement = false;
    boolean useCompression = true;
    boolean useFullFlush = true;
    boolean javaNetDebug = false;
    boolean smackDebug = true;

    if (useFullFlush) {
        XMPPInputOutputStream.setFlushMethod(FlushMethod.FULL_FLUSH);
    }

    if (javaNetDebug) {
        System.setProperty("javax.net.debug", "all");
    }

    final SecurityMode securityMode;
    if (useTls) {
        securityMode = SecurityMode.required;
    } else {
        securityMode = SecurityMode.disabled;
    }

    final SmackDebuggerFactory smackDebuggerFactory;
    if (smackDebug) {
        smackDebuggerFactory = ConsoleDebugger.Factory.INSTANCE;
    } else {
        smackDebuggerFactory = null;
    }

    ModularXmppClientToServerConnectionConfiguration.Builder configurationBuilder = ModularXmppClientToServerConnectionConfiguration.builder()
            .setUsernameAndPassword(username, password)
            .setXmppDomain(service)
            .setDebuggerFactory(smackDebuggerFactory)
            .setSecurityMode(securityMode)
            .removeAllModules()
            .addModule(XmppTcpTransportModuleDescriptor.class);

    if (useCompression) {
        configurationBuilder.addModule(CompressionModuleDescriptor.class);
        configurationBuilder.setCompressionEnabled(true);
    }
    if (useStreamMangement) {
        configurationBuilder.addModule(StreamManagementModuleDescriptor.class);
    }

    ModularXmppClientToServerConnectionConfiguration configuration = configurationBuilder.build();

    PrintWriter printWriter = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out, StandardCharsets.UTF_8)));
    configuration.printStateGraphInDotFormat(printWriter, false);
    printWriter.flush();

    ModularXmppClientToServerConnection connection = new ModularXmppClientToServerConnection(configuration);

    connection.setReplyTimeout(5 * 60 * 1000);

    connection.addConnectionStateMachineListener((event, c) -> {
        LOGGER.info("Connection event: " + event);
    });

    connection.connect();

    connection.login();

    Message message = connection.getStanzaFactory().buildMessageStanza()
            .to("[email protected]")
            .setBody("It is alive! " + XmppDateTime.formatXEP0082Date(new Date()))
            .build();
    connection.sendStanza(message);

    Thread.sleep(1000);

    connection.disconnect();

    ModularXmppClientToServerConnection.Stats connectionStats = connection.getStats();
    ServiceDiscoveryManager.Stats serviceDiscoveryManagerStats = ServiceDiscoveryManager.getInstanceFor(connection).getStats();

    // CHECKSTYLE:OFF
    System.out.println("NIO successfully finished, yeah!\n" + connectionStats + '\n' + serviceDiscoveryManagerStats);
    // CHECKSTYLE:ON
}
 
Example #14
Source File: XmppManager.java    From android-demo-xmpp-androidpn with Apache License 2.0 4 votes vote down vote up
public void run() {
    Log.i(LOGTAG, "ConnectTask.run()...");

    if (!xmppManager.isConnected()) {		//未连接到XMPP服务器
        // Create the configuration for this new connection
    	/**
    	 * 设置连接的一些参数
    	 */
        ConnectionConfiguration connConfig = new ConnectionConfiguration(
                xmppHost, xmppPort);
        // connConfig.setSecurityMode(SecurityMode.disabled);
        connConfig.setSecurityMode(SecurityMode.required);
        connConfig.setSASLAuthenticationEnabled(false);
        connConfig.setCompressionEnabled(false);

        XMPPConnection connection = new XMPPConnection(connConfig);
        xmppManager.setConnection(connection);

        try {
            // Connect to the server
            connection.connect();
            Log.i(LOGTAG, "XMPP connected successfully");

            // packet provider
            /** 
             * 这个就是对于通信的xml文本进行解析的解析器,再把信息转换成IQ,这个相当于QQ的聊天信息 
             * 如果要用这个协议,其IQ的子类(NotificationIQ)
             * 和IQProvider的子类(NotificationIQProvider)要进行重写 
             */
            ProviderManager.getInstance().addIQProvider("notification",
                    "androidpn:iq:notification",
                    new NotificationIQProvider());

        } catch (XMPPException e) {
            Log.e(LOGTAG, "XMPP connection failed", e);
            running = false;
        }
        //执行任务
        xmppManager.runTask();

    } else {
        Log.i(LOGTAG, "XMPP connected already");
        //执行任务
        xmppManager.runTask();
    }
}
 
Example #15
Source File: XMPPConnect.java    From openhab1-addons with Eclipse Public License 2.0 4 votes vote down vote up
@Override
@SuppressWarnings("rawtypes")
public void updated(Dictionary config) throws ConfigurationException {
    if (config == null) {
        return;
    }
    XMPPConnect.servername = (String) config.get("servername");
    XMPPConnect.proxy = (String) config.get("proxy");
    String portString = (String) config.get("port");
    if (portString != null) {
        XMPPConnect.port = Integer.valueOf(portString);
    }
    XMPPConnect.username = (String) config.get("username");
    XMPPConnect.password = (String) config.get("password");
    XMPPConnect.chatroom = (String) config.get("chatroom");
    XMPPConnect.chatnickname = (String) config.get("chatnickname");
    XMPPConnect.chatpassword = (String) config.get("chatpassword");

    String securityModeString = (String) config.get("securitymode");
    if (securityModeString != null) {
        securityMode = SecurityMode.valueOf(securityModeString);
    }
    XMPPConnect.tlsPin = (String) config.get("tlspin");

    String users = (String) config.get("consoleusers");

    if (!StringUtils.isEmpty(users)) {
        XMPPConnect.consoleUsers = users.split(",");
    } else {
        XMPPConnect.consoleUsers = new String[0];
    }

    // check mandatory settings
    if (StringUtils.isEmpty(servername)) {
        return;
    }
    if (StringUtils.isEmpty(username)) {
        return;
    }
    if (StringUtils.isEmpty(password)) {
        return;
    }

    // set defaults for optional settings
    if (port == null) {
        port = 5222;
    }
    if (StringUtils.isEmpty(chatnickname)) {
        chatnickname = "openhab-bot";
    }

    establishConnection();
}