org.jivesoftware.smack.XMPPException Java Examples

The following examples show how to use org.jivesoftware.smack.XMPPException. 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: PrivacyManager.java    From Spark with Apache License 2.0 6 votes vote down vote up
public void setListAsActive(String listname)
{
    try {
        privacyManager.setActiveListName(listname);
        fireListActivated(listname);
        if (hasActiveList())
        {
            _presenceHandler.removeIconsForList(getActiveList());
        }
        getPrivacyList(listname).setListAsActive(true);
        for (SparkPrivacyList plist : _privacyLists) {
            if (!plist.getListName().equals(listname))
                plist.setListAsActive(false);
        }
        _presenceHandler.setIconsForList(getActiveList());
        
    } catch (XMPPException | SmackException | InterruptedException e) {
        Log.warning("Could not activate PrivacyList " + listname, e);
    }
}
 
Example #2
Source File: XMPPTCPConnection.java    From Smack with Apache License 2.0 6 votes vote down vote up
/**
 * <p>
 * Starts using stream compression that will compress network traffic. Traffic can be
 * reduced up to 90%. Therefore, stream compression is ideal when using a slow speed network
 * connection. However, the server and the client will need to use more CPU time in order to
 * un/compress network data so under high load the server performance might be affected.
 * </p>
 * <p>
 * Stream compression has to have been previously offered by the server. Currently only the
 * zlib method is supported by the client. Stream compression negotiation has to be done
 * before authentication took place.
 * </p>
 *
 * @throws NotConnectedException if the XMPP connection is not connected.
 * @throws SmackException if Smack detected an exceptional situation.
 * @throws InterruptedException if the calling thread was interrupted.
 * @throws XMPPException if an XMPP protocol error was received.
 */
private void maybeEnableCompression() throws SmackException, InterruptedException, XMPPException {
    if (!config.isCompressionEnabled()) {
        return;
    }

    Compress.Feature compression = getFeature(Compress.Feature.ELEMENT, Compress.NAMESPACE);
    if (compression == null) {
        // Server does not support compression
        return;
    }
    // If stream compression was offered by the server and we want to use
    // compression then send compression request to the server
    if ((compressionHandler = maybeGetCompressionHandler(compression)) != null) {
        compressSyncPoint = false;
        sendNonza(new Compress(compressionHandler.getCompressionMethod()));
        waitForConditionOrThrowConnectionException(() -> compressSyncPoint, "establishing stream compression");
    } else {
        LOGGER.warning("Could not enable compression because no matching handler/method pair was found");
    }
}
 
Example #3
Source File: XMPPContactsService.java    From saros with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Remove a contact completely from roster.
 *
 * <p>This method runs asynchronous and can fail silently (logging errors). If the removal was
 * successful, the roster sends an update and this will change the contact list leading to a
 * notification to all {@link IContactsUpdate} listener.
 *
 * <p>Known errors:
 *
 * <ul>
 *   <li>Smack possibly includes 'ask' attribute in roster items when sending requests
 *       (https://issues.igniterealtime.org/browse/SMACK-766) - catching exception, deletion still
 *       works sometimes, should be fixed by Smack update 4.2.1
 * </ul>
 *
 * @param contact XMPPContact to remove from roster
 */
public void removeContact(XMPPContact contact) {
  contactsExecutor.execute(
      () -> {
        if (roster == null) return;

        RosterEntry entry = roster.getEntry(contact.getBareJid().getRAW());
        if (entry == null) {
          log.error("Remove of " + contact + " was not possible, RosterEntry not found!");
          return;
        }

        try {
          roster.removeEntry(entry);
        } catch (XMPPException e) {
          log.error("Remove of " + contact + " was not possible", e);
        }
      });
}
 
Example #4
Source File: Demo.java    From Smack with Apache License 2.0 6 votes vote down vote up
public Demo(String server, String user, String pass) {

        this.server = server;
        this.user = user;
        this.pass = pass;

        if (user.equals("jeffw")) {
            jid = new JTextField("eowyn" + "@" + server + "/Smack");
        } else {
            jid = new JTextField("jeffw" + "@" + server + "/Smack");
        }

        xmppConnection = new XMPPTCPConnection(server);
        try {
            xmppConnection.connect();
            xmppConnection.login(user, pass);
            initialize();
        }
        catch (XMPPException e) {
            LOGGER.log(Level.WARNING, "exception", e);
        }
    }
 
Example #5
Source File: MediaNegotiator.java    From Smack with Apache License 2.0 6 votes vote down vote up
/**
  *  The other side has sent us a content-accept.  The payload types in that message may not match with what
  *  we sent, but XEP-167 says that the other side should retain the order of the payload types we first sent.
  *
  *  This means we can walk through our list, in order, until we find one from their list that matches.  This
  *  will be the best payload type to use.
  *
  *  @param jingle TODO javadoc me please
  *  @return the iq
 * @throws NotConnectedException if the XMPP connection is not connected.
 * @throws InterruptedException if the calling thread was interrupted.
  */
private IQ receiveContentAcceptAction(Jingle jingle, JingleDescription description) throws XMPPException, NotConnectedException, InterruptedException {
    IQ response;

    List<PayloadType> offeredPayloads = description.getAudioPayloadTypesList();
    bestCommonAudioPt = calculateBestCommonAudioPt(offeredPayloads);

    if (bestCommonAudioPt == null) {

        setNegotiatorState(JingleNegotiatorState.FAILED);
        response = session.createJingleError(jingle, JingleError.NEGOTIATION_ERROR);

    } else {

        setNegotiatorState(JingleNegotiatorState.SUCCEEDED);
        triggerMediaEstablished(getBestCommonAudioPt());
        LOGGER.severe("Media choice:" + getBestCommonAudioPt().getName());

        response = session.createAck(jingle);
    }

    return response;
}
 
Example #6
Source File: Client.java    From desktopclient-java with GNU General Public License v3.0 6 votes vote down vote up
public boolean removeFromRoster(JID jid) {
    if (!this.isConnected()) {
        LOGGER.info("not connected");
        return false;
    }
    Roster roster = Roster.getInstanceFor(mConn);
    RosterEntry entry = roster.getEntry(jid.toBareSmack());
    if (entry == null) {
        LOGGER.info("can't find roster entry for jid: "+jid);
        return true;
    }
    try {
        // blocking
        roster.removeEntry(entry);
    } catch (SmackException.NotLoggedInException |
            SmackException.NoResponseException |
            XMPPException.XMPPErrorException |
            SmackException.NotConnectedException |
            InterruptedException ex) {
        LOGGER.log(Level.WARNING, "can't remove contact from roster", ex);
        return false;
    }
    return true;
}
 
Example #7
Source File: XmppTool.java    From xmpp with Apache License 2.0 6 votes vote down vote up
/**
 * 查找用户
 *
 * @param
 * @param userName
 * @return
 */
public List<XmppUser> searchUsers(String userName) {
    List<XmppUser> list = new ArrayList<XmppUser>();
    UserSearchManager userSearchManager = new UserSearchManager(con);
    try {
        Form searchForm = userSearchManager.getSearchForm("search."
                + con.getServiceName());
        Form answerForm = searchForm.createAnswerForm();
        answerForm.setAnswer("Username", true);
        answerForm.setAnswer("Name", true);
        answerForm.setAnswer("search", userName);
        ReportedData data = userSearchManager.getSearchResults(answerForm,
                "search." + con.getServiceName());
        Iterator<ReportedData.Row> rows = data.getRows();
        while (rows.hasNext()) {
            XmppUser user = new XmppUser(null, null);
            ReportedData.Row row = rows.next();
            user.setUserName(row.getValues("Username").next().toString());
            user.setName(row.getValues("Name").next().toString());
            list.add(user);
        }
    } catch (XMPPException e) {
        SLog.e(tag, Log.getStackTraceString(e));
    }
    return list;
}
 
Example #8
Source File: BookmarksUI.java    From Spark with Apache License 2.0 6 votes vote down vote up
private Collection<DomainBareJid> getConferenceServices(DomainBareJid server) throws Exception {
    List<DomainBareJid> answer = new ArrayList<>();
    ServiceDiscoveryManager discoManager = ServiceDiscoveryManager.getInstanceFor(SparkManager.getConnection());
    DiscoverItems items = discoManager.discoverItems(server);
    for (DiscoverItems.Item item : items.getItems()) {
        DomainBareJid entityID = item.getEntityID().asDomainBareJid();
        // TODO: We should not simply assumet that this is MUC service just because it starts with a given prefix.
        if (entityID.toString().startsWith("conference") || entityID.toString().startsWith("private")) {
            answer.add(entityID);
        }
        else {
            try {
                DiscoverInfo info = discoManager.discoverInfo(item.getEntityID());
                if (info.containsFeature("http://jabber.org/protocol/muc")) {
                    answer.add(entityID);
                }
            }
            catch (XMPPException | SmackException e) {
                Log.error("Problem when loading conference service.", e);
            }
        }
    }
    return answer;
}
 
Example #9
Source File: XMPPTCPConnection.java    From Smack with Apache License 2.0 6 votes vote down vote up
/**
 * Creates a new XMPP connection over TCP (optionally using proxies).
 * <p>
 * Note that XMPPTCPConnection constructors do not establish a connection to the server
 * and you must call {@link #connect()}.
 * </p>
 *
 * @param config the connection configuration.
 */
public XMPPTCPConnection(XMPPTCPConnectionConfiguration config) {
    super(config);
    this.config = config;
    addConnectionListener(new ConnectionListener() {
        @Override
        public void connectionClosedOnError(Exception e) {
            if (e instanceof XMPPException.StreamErrorException || e instanceof StreamManagementException) {
                dropSmState();
            }
        }
    });

    // Re-init the reader and writer in case of SASL <success/>. This is done to reset the parser since a new stream
    // is initiated.
    buildNonzaCallback().listenFor(SaslNonza.Success.class, s -> resetParser()).install();
}
 
Example #10
Source File: AbstractOpenPgpIntegrationTest.java    From Smack with Apache License 2.0 6 votes vote down vote up
protected AbstractOpenPgpIntegrationTest(SmackIntegrationTestEnvironment environment)
        throws XMPPException.XMPPErrorException, TestNotPossibleException, SmackException.NotConnectedException,
        InterruptedException, SmackException.NoResponseException {
    super(environment);

    throwIfPubSubNotSupported(conOne);
    throwIfPubSubNotSupported(conTwo);
    throwIfPubSubNotSupported(conThree);

    this.aliceConnection = conOne;
    this.bobConnection = conTwo;
    this.chloeConnection = conThree;

    this.alice = aliceConnection.getUser().asBareJid();
    this.bob = bobConnection.getUser().asBareJid();
    this.chloe = chloeConnection.getUser().asBareJid();

    this.alicePepManager = PepManager.getInstanceFor(aliceConnection);
    this.bobPepManager = PepManager.getInstanceFor(bobConnection);
    this.chloePepManager = PepManager.getInstanceFor(chloeConnection);

    OpenPgpPubSubUtil.deletePubkeysListNode(alicePepManager);
    OpenPgpPubSubUtil.deletePubkeysListNode(bobPepManager);
    OpenPgpPubSubUtil.deletePubkeysListNode(chloePepManager);
}
 
Example #11
Source File: ChatActivity.java    From weixin with Apache License 2.0 6 votes vote down vote up
/**
 * 发送消息
 */
private void sendMsg() {
	new Thread(new Runnable() {

		@Override
		public void run() {
			Chat chat = XmppManager.getInstance().getFriendChat(user.getUserAccount(), null);

			//	friend为好友名,不是JID;listener 监听器可以传null,利用聊天窗口对象调用sendMessage发送消息
			//	这里sendMessage我传的是一个JSON字符串,以便更灵活的控制,发送消息完成~
			try {
				// String msgjson = "{\"messageType\":\""+messageType+"\",\"chanId\":\""+chanId+"\",\"chanName\":\""+chanName+"\"}";
				// chat.sendMessage(msgjson);

				chat.sendMessage(msg);
				handler.sendEmptyMessage(HandlerTypeUtils.WX_HANDLER_TYPE_LOAD_DATA_SUCCESS);
			} catch (XMPPException e) {
				handler.sendEmptyMessage(HandlerTypeUtils.WX_HANDLER_TYPE_LOAD_DATA_FAIL);
				e.printStackTrace();
			}
		}
	}).start();
}
 
Example #12
Source File: InvitationManager.java    From Spark with Apache License 2.0 6 votes vote down vote up
/**
 * Invite or transfer a queue.
 *
 * @param chatRoom    the <code>ChatRoom</code> to invite or transfer.
 * @param sessionID   the sessionID of this Fastpath session.
 * @param jid         the jid of the room.
 * @param messageText the message to send to the user.
 * @param transfer    true if this is a transfer.
 */
public static void transferOrInviteToWorkgroup(ChatRoom chatRoom, String workgroup, String sessionID, final Jid jid, String messageText, final boolean transfer) {
    String msg = messageText != null ? StringUtils.escapeForXml(messageText).toString() : FpRes.getString("message.please.join.me.in.conference");
    try {
        if (!transfer) {
        	// TODO : CHECK FASHPATH
            FastpathPlugin.getAgentSession().sendRoomInvitation(RoomInvitation.Type.workgroup, jid, sessionID, msg);
        }
        else {
            FastpathPlugin.getAgentSession().sendRoomTransfer(RoomTransfer.Type.workgroup, jid.toString(), sessionID, msg);
        }
    }
    catch (XMPPException | SmackException | InterruptedException e) {
        Log.error(e);
    }


    String username = SparkManager.getUserManager().getUserNicknameFromJID(jid.asBareJid());

    String notification = FpRes.getString("message.user.has.been.invited", username);
    if (transfer) {
        notification = FpRes.getString("message.waiting.for.user", username);
    }
    chatRoom.getTranscriptWindow().insertNotificationMessage(notification, ChatManager.NOTIFICATION_COLOR);
}
 
Example #13
Source File: MultiUserChatTest.java    From Smack with Apache License 2.0 6 votes vote down vote up
private void makeRoomModerated() throws XMPPException {
    // User1 (which is the room owner) converts the instant room into a moderated room
    Form form = muc.getConfigurationForm();
    Form answerForm = form.createAnswerForm();
    answerForm.setAnswer("muc#roomconfig_moderatedroom", true);
    answerForm.setAnswer("muc#roomconfig_whois", Arrays.asList("moderators"));
    // Keep the room owner
    try {
        List<String> owners = new ArrayList<String>();
        owners.add(getBareJID(0));
        answerForm.setAnswer("muc#roomconfig_roomowners", owners);
    }
    catch (IllegalArgumentException e) {
        // Do nothing
    }
    muc.sendConfigurationForm(answerForm);
}
 
Example #14
Source File: Workpane.java    From Spark with Apache License 2.0 6 votes vote down vote up
public void presenceChanged(Presence presence) {
    String status = presence.getStatus();
    if (status == null) {
        status = "";
    }

    try {
        if (FastpathPlugin.getAgentSession().isOnline()) {
            Presence.Mode mode = presence.getMode();
            if (status == null) {
                status = "";
            }
            if (mode == null) {
                mode = Presence.Mode.available;
            }
            FastpathPlugin.getAgentSession().setStatus(presence.getMode(), status);
        }
    }
    catch (XMPPException | SmackException | InterruptedException e) {
        Log.error(e);
    }
}
 
Example #15
Source File: ConferenceServiceBrowser.java    From Spark with Apache License 2.0 6 votes vote down vote up
public Collection<String> getConferenceServices(String serverString) throws Exception {
    Jid server = JidCreate.from(serverString);
    List<String> answer = new ArrayList<>();
    ServiceDiscoveryManager discoManager = ServiceDiscoveryManager.getInstanceFor(SparkManager.getConnection());
    DiscoverItems items = discoManager.discoverItems(server);
    for (DiscoverItems.Item item : items.getItems() ) {
        if (item.getEntityID().toString().startsWith("conference") || item.getEntityID().toString().startsWith("private")) {
            answer.add(item.getEntityID().toString());
        }
        else {
            try {
                DiscoverInfo info = discoManager.discoverInfo(item.getEntityID());
                if (info.containsFeature("http://jabber.org/protocol/muc")) {
                    answer.add(item.getEntityID().toString());
                }
            }
            catch (XMPPException | SmackException e) {
                // Nothing to do
            }
        }
    }
    return answer;
}
 
Example #16
Source File: XmppConnection.java    From weixin with Apache License 2.0 6 votes vote down vote up
/**
 * 发送文件
 * 
 * @param user
 * @param filePath
 */
public void sendFile(String user, String filePath) {
	if (getConnection() == null)
		return;
	// 创建文件传输管理器
	FileTransferManager manager = new FileTransferManager(getConnection());

	// 创建输出的文件传输
	OutgoingFileTransfer transfer = manager.createOutgoingFileTransfer(user);

	// 发送文件
	try {
		transfer.sendFile(new File(filePath), "You won't believe this!");
	} catch (XMPPException e) {
		e.printStackTrace();
	}
}
 
Example #17
Source File: LastActivityManagerTest.java    From Smack with Apache License 2.0 6 votes vote down vote up
/**
 * This is a test to check if a LastActivity request for last logged out
 * lapsed time is answered and correct
 */
public void testLastLoggedOut() {
	TCPConnection conn0 = getConnection(0);

	LastActivity lastActivity = null;
	try {
		lastActivity = LastActivityManager.getLastActivity(conn0, getBareJID(1));
	} catch (XMPPException e) {
		e.printStackTrace();
		fail("An error occurred requesting the Last Activity");
	}

	assertNotNull("No last activity packet", lastActivity);
       assertTrue("The last activity idle time should be 0 since the user is logged in: " +
               lastActivity.getIdleTime(), lastActivity.getIdleTime() == 0);
   }
 
Example #18
Source File: XmppClient.java    From riotapi with Apache License 2.0 5 votes vote down vote up
public MultiUserChat joinChannelWithoutHashing(String name, String password) {
	MultiUserChat chat = new MultiUserChat(this, name);
	chatRooms.put(name, chat);
	try {
		chat.join(getUsername(), password);
		return chat;
	} catch (XMPPException.XMPPErrorException | SmackException e) {
		throw new IllegalStateException(e);
	}
}
 
Example #19
Source File: STUNResolver.java    From Smack with Apache License 2.0 5 votes vote down vote up
/**
 * Cancel any operation.
 *
 * @see TransportResolver#cancel()
 */
@Override
public synchronized void cancel() throws XMPPException {
    if (isResolving()) {
        resolverThread.interrupt();
        setResolveEnd();
    }
}
 
Example #20
Source File: PrivateKeyReceiver.java    From desktopclient-java with GNU General Public License v3.0 5 votes vote down vote up
private void sendRequestAsync(String registrationToken) {
    // connect
    try {
        mConn.connect();
    } catch (XMPPException | SmackException | IOException | InterruptedException ex) {
        LOGGER.log(Level.WARNING, "can't connect to "+mConn.getServer(), ex);
        mHandler.handle(new Callback<>(ex));
        return;
    }

    Registration iq = new Registration();
    iq.setType(IQ.Type.set);
    iq.setTo(mConn.getXMPPServiceDomain());
    Form form = new Form(DataForm.Type.submit);

    // form type field
    FormField type = new FormField(FormField.FORM_TYPE);
    type.setType(FormField.Type.hidden);
    type.addValue(FORM_TYPE_VALUE);
    form.addField(type);

    // token field
    FormField fieldKey = new FormField(FORM_TOKEN_VAR);
    fieldKey.setLabel("Registration token");
    fieldKey.setType(FormField.Type.text_single);
    fieldKey.addValue(registrationToken);
    form.addField(fieldKey);

    iq.addExtension(form.getDataFormToSend());

    mConn.sendIqRequestAsync(iq)
         .onSuccess(this)
         .onError(exception -> mHandler.handle(new Callback<>(exception)));
}
 
Example #21
Source File: IMAppender.java    From olat with Apache License 2.0 5 votes vote down vote up
/**
 * Options are activated and become effective only after calling this method.
 */
@Override
public void activateOptions() {
    try {
        cb = new CyclicBuffer(bufferSize);

        // Create a connection to the XMPP server
        LogLog.debug("Stablishing connection with XMPP server");
        con = new XMPPConnection(InstantMessagingModule.getConnectionConfiguration());
        // Most servers require you to login before performing other tasks
        LogLog.debug("About to login as [" + username + "/" + password + "]");
        con.connect();
        con.login(username, password);

        // Start a conversation with IMAddress
        if (chatroom) {
            LogLog.debug("About to create ChatGroup");
            groupchat = new MultiUserChat(con, (String) recipientsList.get(0));
            LogLog.debug("About to join room");
            groupchat.join(nickname != null ? nickname : username);
        } else {
            final Iterator iter = recipientsList.iterator();
            while (iter.hasNext()) {
                chats.add(con.getChatManager().createChat((String) iter.next(), null));
            }
            // chat = con.createChat(recipients);
        }

    } catch (final XMPPException xe) {
        errorHandler.error("Error while activating options for appender named [" + name + "] Could not connect to instant messaging server with user: "
                + getUsername(), xe, ErrorCode.GENERIC_FAILURE);
    } catch (final Exception e) {
        errorHandler.error("Error while activating options for appender named [" + name + "]", e, ErrorCode.GENERIC_FAILURE);
    }
}
 
Example #22
Source File: SingleUserChat.java    From saros with GNU General Public License v2.0 5 votes vote down vote up
@Override
public void sendMessage(String text) throws XMPPException {
  String participant;
  String threadId;

  synchronized (SingleUserChat.this) {
    threadId = chat.getThreadID();
    participant = chat.getParticipant();
  }

  Message message = new Message(participant, Message.Type.chat);
  message.setThread(threadId);
  message.setBody(text);
  sendMessage(message);
}
 
Example #23
Source File: JingleS5BTransportSession.java    From Smack with Apache License 2.0 5 votes vote down vote up
private UsedCandidate chooseFromProposedCandidates(JingleS5BTransport proposal) {
    for (JingleContentTransportCandidate c : proposal.getCandidates()) {
        JingleS5BTransportCandidate candidate = (JingleS5BTransportCandidate) c;

        try {
            return connectToTheirCandidate(candidate);
        } catch (InterruptedException | TimeoutException | XMPPException | SmackException | IOException e) {
            LOGGER.log(Level.WARNING, "Could not connect to " + candidate.getHost(), e);
        }
    }
    LOGGER.log(Level.WARNING, "Failed to connect to any candidate.");
    return null;
}
 
Example #24
Source File: ContentNegotiator.java    From Smack with Apache License 2.0 5 votes vote down vote up
@Override
public List<IQ> dispatchIncomingPacket(IQ iq, String id) throws XMPPException, SmackException, InterruptedException {
    List<IQ> responses = new ArrayList<>();

    // First only process IQ packets that contain <content> stanzas that
    // match this media manager.

    if (iq != null) {
        if (iq.getType().equals(IQ.Type.error)) {
            // Process errors
            // TODO getState().eventError(iq);
        } else if (iq.getType().equals(IQ.Type.result)) {
            // Process ACKs
            if (isExpectedId(iq.getStanzaId())) {
                removeExpectedId(iq.getStanzaId());
            }
        } else if (iq instanceof Jingle) {
            Jingle jingle = (Jingle) iq;

            // There are 1 or more <content> sections in a Jingle packet.
            // Find out which <content> section belongs to this content negotiator, and
            // then dispatch the Jingle packet to the media and transport negotiators.

            for (JingleContent jingleContent : jingle.getContentsList()) {
                if (jingleContent.getName().equals(name)) {
                    if (mediaNeg != null) {
                        responses.addAll(mediaNeg.dispatchIncomingPacket(iq, id));
                    }

                    if (transNeg != null) {
                        responses.addAll(transNeg.dispatchIncomingPacket(iq, id));
                    }
                }

            }
        }
    }
    return responses;
}
 
Example #25
Source File: MultiUserSubscriptionUseCases.java    From Smack with Apache License 2.0 5 votes vote down vote up
public void testGetItemsWithSingleSubscription() throws XMPPException
{
	LeafNode node = getRandomPubnode(getManager(0), true, false);
	node.send((Item)null);
	node.send((Item)null);
	node.send((Item)null);
	node.send((Item)null);
	node.send((Item)null);

	LeafNode user2Node = (LeafNode) getManager(1).getNode(node.getId());
	user2Node.subscribe(getBareJID(1));

	Collection<? extends Item> items = user2Node.getItems();
	assertTrue(items.size() == 5);
}
 
Example #26
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 #27
Source File: XMPP.java    From XMPPSample_Studio with Apache License 2.0 5 votes vote down vote up
public void login(String user, String pass, StatusItem status, String username)
            throws XMPPException, SmackException, IOException, InterruptedException {
        Log.i(TAG, "inside XMPP getlogin Method");
        long l = System.currentTimeMillis();
        XMPPTCPConnection connect = connect();
        if (connect.isAuthenticated()) {
            Log.i(TAG, "User already logged in");
            return;
        }

        Log.i(TAG, "Time taken to connect: " + (System.currentTimeMillis() - l));

        l = System.currentTimeMillis();
        connect.login(user, pass);
        Log.i(TAG, "Time taken to login: " + (System.currentTimeMillis() - l));

        Log.i(TAG, "login step passed");

        Presence p = new Presence(Presence.Type.available);
        p.setMode(Presence.Mode.available);
        p.setPriority(24);
        p.setFrom(connect.getUser());
        if (status != null) {
            p.setStatus(status.toJSON());
        } else {
            p.setStatus(new StatusItem().toJSON());
        }
//        p.setTo("");
        VCard ownVCard = new VCard();
        ownVCard.load(connect);
        ownVCard.setNickName(username);
        ownVCard.save(connect);

        PingManager pingManager = PingManager.getInstanceFor(connect);
        pingManager.setPingInterval(150000);
        connect.sendPacket(p);


    }
 
Example #28
Source File: ModularXmppClientToServerConnection.java    From Smack with Apache License 2.0 5 votes vote down vote up
protected void walkStateGraph(WalkStateGraphContext walkStateGraphContext)
                throws XMPPException, IOException, SmackException, InterruptedException {
    // Save a copy of the current state
    GraphVertex<State> previousStateVertex = currentStateVertex;
    try {
        walkStateGraphInternal(walkStateGraphContext);
    } catch (IOException | SmackException | InterruptedException | XMPPException e) {
        currentStateVertex = previousStateVertex;
        // Unwind the state.
        State revertedState = currentStateVertex.getElement();
        unwindState(revertedState);
        throw e;
    }
}
 
Example #29
Source File: PubSubTestCase.java    From Smack with Apache License 2.0 5 votes vote down vote up
protected LeafNode getRandomPubnode(PubSubManager pubMgr, boolean persistItems, boolean deliverPayload) throws XMPPException
{
	ConfigureForm form = new ConfigureForm(FormType.submit);
	form.setPersistentItems(persistItems);
	form.setDeliverPayloads(deliverPayload);
	form.setAccessModel(AccessModel.open);
	return (LeafNode)pubMgr.createNode("/test/Pubnode" + System.currentTimeMillis(), form);
}
 
Example #30
Source File: XmppConnection.java    From weixin with Apache License 2.0 5 votes vote down vote up
/**
 * 删除当前用户
 * 
 * @return
 */
public boolean deleteAccount() {
	if (getConnection() == null)
		return false;
	try {
		getConnection().getAccountManager().deleteAccount();
		return true;
	} catch (XMPPException e) {
		return false;
	}
}