org.jivesoftware.smack.SmackConfiguration Java Examples

The following examples show how to use org.jivesoftware.smack.SmackConfiguration. 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: XmppMessageEngine.java    From vicinity-gateway-api with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Constructor for the XMPP message engine. It initialises fields and a {@link java.util.Timer Timer} that periodically
 * in interval that is randomly set, executes the {@link #renewPresenceAndRoster() renewPresenceAndRoster} method.
 * 
 * @param objectId String with the object ID that connects via this engine.
 * @param password Password string for authentication.
 * @param config Configuration of the OGWAPI.
 * @param logger Logger of the OGWAPI. 
 * @param connectionDescriptor Connection descriptor that is using this particular instance of engine.
 */
public XmppMessageEngine(String objectId, String password, XMLConfiguration config, Logger logger, 
																	ConnectionDescriptor connectionDescriptor) {
	super(objectId, password, config, logger, connectionDescriptor);
	
	connection = null;
	chatManager = null;
	roster = null;
	
	// initialise map with opened chats
	openedChats = new HashMap<EntityBareJid, Chat>();
	
	// compute the random time in seconds after which a roster will be renewed
	long timeForRosterRenewal = (long) ((Math.random() * ((ROSTER_RELOAD_TIME_MAX - ROSTER_RELOAD_TIME_MIN) + 1)) 
			+ ROSTER_RELOAD_TIME_MIN) * 1000;
	
	logger.finest("The roster for " + objectId + " will be renewed every " 
			+ timeForRosterRenewal + "ms.");
	
	
	// timer for roster renewing
	Timer timerForRosterRenewal = new Timer();
	timerForRosterRenewal.schedule(new TimerTask() {
		@Override
		public void run() {
			renewPresenceAndRoster();
		}
	}, timeForRosterRenewal, timeForRosterRenewal);
	
	// enable debugging if desired
	boolean debuggingEnabled = config.getBoolean(CONFIG_PARAM_XMPPDEBUG, CONFIG_DEF_XMPPDEBUG);
	if (debuggingEnabled) {
		SmackConfiguration.DEBUG = debuggingEnabled;
		logger.config("XMPP debugging enabled.");
	}
}
 
Example #2
Source File: ConfigureFormTest.java    From Smack with Apache License 2.0 6 votes vote down vote up
@Test
public void getConfigFormWithTimeout() throws XMPPException, InterruptedException, SmackException, IOException {
    ThreadedDummyConnection con = ThreadedDummyConnection.newInstance();
    PubSubManager mgr = new PubSubManager(con, PubSubManagerTest.DUMMY_PUBSUB_SERVICE);
    DiscoverInfoBuilder info = DiscoverInfo.builder("disco-result")
                                           .ofType(IQ.Type.result)
                                           .from(PubSubManagerTest.DUMMY_PUBSUB_SERVICE);

    Identity ident = new Identity("pubsub", null, "leaf");
    info.addIdentity(ident);

    DiscoverInfo discoverInfo = info.build();
    con.addIQReply(discoverInfo);

    Node node = mgr.getNode("princely_musings");

    SmackConfiguration.setDefaultReplyTimeout(100);
    con.setTimeout();

    assertThrows(SmackException.class, () -> {
        node.getNodeConfiguration();
    });
}
 
Example #3
Source File: XmppManager.java    From weixin with Apache License 2.0 6 votes vote down vote up
/**
 * 加入会议室
 * 
 * @param user 昵称
 * @param password 会议室密码
 * @param roomsName 会议室名
 */
public MultiUserChat joinMultiUserChat(String user, String password, String roomsName) {
	try {
		// 使用XMPPConnection创建一个MultiUserChat窗口  
		MultiUserChat muc = new MultiUserChat(getConnection(), roomsName + "@conference." + getConnection().getServiceName());
		// 聊天室服务将会决定要接受的历史记录数量  
		DiscussionHistory history = new DiscussionHistory();
		history.setMaxStanzas(0);
		//history.setSince(new Date());  
		// 用户加入聊天室  
		muc.join(user, password, history, SmackConfiguration.getPacketReplyTimeout());
		L.i(LOGTAG, "会议室加入成功........");
		return muc;
	} catch (XMPPException e) {
		e.printStackTrace();
		L.i(LOGTAG, "会议室加入失败........");
		return null;
	}
}
 
Example #4
Source File: XmppConnection.java    From weixin with Apache License 2.0 6 votes vote down vote up
/**
 * 加入会议室
 * 
 * @param user 昵称
 * @param password 会议室密码
 * @param roomsName 会议室名
 */
public MultiUserChat joinMultiUserChat(String user, String roomsName, String password) {
	if (getConnection() == null)
		return null;
	try {
		// 使用XMPPConnection创建一个MultiUserChat窗口
		MultiUserChat muc = new MultiUserChat(getConnection(), roomsName + "@conference." + getConnection().getServiceName());
		// 聊天室服务将会决定要接受的历史记录数量
		DiscussionHistory history = new DiscussionHistory();
		history.setMaxChars(0);
		// history.setSince(new Date());
		// 用户加入聊天室
		muc.join(user, password, history, SmackConfiguration.getPacketReplyTimeout());
		Log.i("MultiUserChat", "会议室【" + roomsName + "】加入成功........");
		return muc;
	} catch (XMPPException e) {
		e.printStackTrace();
		Log.i("MultiUserChat", "会议室【" + roomsName + "】加入失败........");
		return null;
	}
}
 
Example #5
Source File: RemotePluginVersionOverXMPP.java    From olat with Apache License 2.0 5 votes vote down vote up
/**
*/
  @Override
  public String getPluginVersion() {
      final XMPPConnection con = adminUser.getConnection();
      if (con != null && con.isConnected()) {
          PluginVersion response;
          try {
              final IQ packet = new PluginVersion();
              packet.setFrom(con.getUser());
              final PacketCollector collector = con.createPacketCollector(new PacketIDFilter(packet.getPacketID()));
              // TODO:gs is sending packets over one connection thread save?
              con.sendPacket(packet);
              response = (PluginVersion) collector.nextResult(SmackConfiguration.getPacketReplyTimeout());
              collector.cancel();
              if (response == null) {
                  log.error("Error while trying to get version at IM server. Response was null!");
                  return version;
              }
              if (response.getError() != null) {
                  log.error("Error while trying to get version at IM server. " + response.getError().getMessage());
                  return version;
              } else if (response.getType() == IQ.Type.ERROR) {
                  log.error("Error while trying to get version at IM server");
                  return version;
              }
              return response.getVersion();

          } catch (final Exception e) {
              log.error("Error while trying to get version at IM server. Response was null!", e);
              return version;
          }

      }
      return version;
  }
 
Example #6
Source File: AndroidSmackInitializer.java    From Smack with Apache License 2.0 5 votes vote down vote up
@Override
public List<Exception> initialize() {
    SmackConfiguration.setDefaultHostnameVerifier(new StrictHostnameVerifier());
    Base64.setEncoder(AndroidBase64Encoder.getInstance());
    Base64UrlSafeEncoder.setEncoder(AndroidBase64UrlSafeEncoder.getInstance());
    return null;
}
 
Example #7
Source File: Java7SmackInitializer.java    From Smack with Apache License 2.0 5 votes vote down vote up
@Override
public List<Exception> initialize() {
    if (SystemUtil.onAndroid()) {
        // @formatter:off
        throw new RuntimeException(
                        "You need to remove the smack-java7 dependency/jar from your build, " +
                        "as it does not run on Android. " +
                        "Use smack-android instead.");
        // @formatter:on
    }
    SmackConfiguration.setDefaultHostnameVerifier(new XmppHostnameVerifier());
    Base64.setEncoder(Java7Base64Encoder.getInstance());
    Base64UrlSafeEncoder.setEncoder(Java7Base64UrlSafeEncoder.getInstance());
    return null;
}
 
Example #8
Source File: PubSubIntegrationTest.java    From Smack with Apache License 2.0 5 votes vote down vote up
/**
 * Asserts that an error is returned when a publish request to a node that is both
 * 'notification-only' as well as 'transient' contains an item element.
 *
 * <p>From XEP-0060 § 7.1.3.6:</p>
 * <blockquote>
 * If the event type is notification + transient and the publisher provides an item,
 * the service MUST bounce the publication request with a &lt;bad-request/&gt; error
 * and a pubsub-specific error condition of &lt;item-forbidden/&gt;.
 * </blockquote>
 *
 * @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="https://xmpp.org/extensions/xep-0060.html#publisher-publish-error-badrequest">
 *     7.1.3.6 Request Does Not Match Configuration</a>
 */
@SmackIntegrationTest
public void transientNotificationOnlyNodeWithItemTest() throws NoResponseException, XMPPErrorException, NotConnectedException, InterruptedException {
    final String nodename = "sinttest-transient-notificationonly-withitem-nodename-" + testRunId;
    final String itemId = "sinttest-transient-notificationonly-withitem-itemid-" + testRunId;

    ConfigureForm defaultConfiguration = pubSubManagerOne.getDefaultConfiguration();
    FillableConfigureForm config = defaultConfiguration.getFillableForm();
    // Configure the node as "Notification-Only Node".
    config.setDeliverPayloads(false);
    // Configure the node as "transient" (set persistent_items to 'false')
    config.setPersistentItems(false);
    Node node = pubSubManagerOne.createNode(nodename, config);

    // Add a dummy payload. If there is no payload, but just an item ID, then ejabberd will *not* return an error,
    // which I believe to be non-compliant behavior (although, granted, the XEP is not very clear about this). A user
    // which sends an empty item with ID to an node that is configured to be notification-only and transient probably
    // does something wrong, as the item's ID will never appear anywhere. Hence it would be nice if the user would be
    // made aware of this issue by returning an error. Sadly ejabberd does not do so.
    // See also https://github.com/processone/ejabberd/issues/2864#issuecomment-500741915
    final StandardExtensionElement dummyPayload = StandardExtensionElement.builder("dummy-payload",
                    SmackConfiguration.SMACK_URL_STRING).setText(testRunId).build();

    try {
        XMPPErrorException e = assertThrows(XMPPErrorException.class, () -> {
            LeafNode leafNode = (LeafNode) node;

            Item item = new PayloadItem<>(itemId, dummyPayload);
            leafNode.publish(item);
        });
        assertEquals(StanzaError.Type.MODIFY, e.getStanzaError().getType());
        assertNotNull(e.getStanzaError().getExtension("item-forbidden", "http://jabber.org/protocol/pubsub#errors"));
    }
    finally {
        pubSubManagerOne.deleteNode(nodename);
    }
}
 
Example #9
Source File: XMPPTCPConnection.java    From Smack with Apache License 2.0 5 votes vote down vote up
/**
 * Returns the compression handler that can be used for one compression methods offered by the server.
 *
 * @return a instance of XMPPInputOutputStream or null if no suitable instance was found
 *
 */
private static XMPPInputOutputStream maybeGetCompressionHandler(Compress.Feature compression) {
    for (XMPPInputOutputStream handler : SmackConfiguration.getCompressionHandlers()) {
            String method = handler.getCompressionMethod();
            if (compression.getMethods().contains(method))
                return handler;
    }
    return null;
}
 
Example #10
Source File: XmppManager.java    From weixin with Apache License 2.0 5 votes vote down vote up
/**
 * 注册
 * 
 * @param account 注册帐号
 * @param password 注册密码
 * @return 0、 服务器没有返回结果<br>
 *         1、注册成功 <br>
 *         2、这个帐号已经存在 <br>
 *         3、注册失败
 */
public String regist(String account, String password) {
	if (!isConnected()) {
		return "0";
	}
	Registration reg = new Registration();
	reg.setType(IQ.Type.SET);
	reg.setTo(getConnection().getServiceName());
	reg.setUsername(account);
	reg.setPassword(password);
	reg.addAttribute("android", "geolo_createUser_android");

	//数据包过滤器
	PacketFilter filter = new AndFilter(new PacketIDFilter(reg.getPacketID()), new PacketTypeFilter(IQ.class));
	PacketCollector collector = getConnection().createPacketCollector(filter);
	getConnection().sendPacket(reg);

	IQ result = (IQ) collector.nextResult(SmackConfiguration.getPacketReplyTimeout());
	//停止请求result(是否成功的结果)
	collector.cancel();
	if (result == null) {
		L.e(LOGTAG, "No response from server.");
		return "0";
	} else if (result.getType() == IQ.Type.RESULT) {
		return "1";
	} else {
		if (result.getError().toString().equalsIgnoreCase("conflict(409)")) {
			L.e(LOGTAG, "IQ.Type.ERROR: " + result.getError().toString());
			return "2";
		} else {
			L.e(LOGTAG, "IQ.Type.ERROR: " + result.getError().toString());
			return "3";
		}
	}
}
 
Example #11
Source File: XmppConnection.java    From weixin with Apache License 2.0 5 votes vote down vote up
/**
 * 注册
 * 
 * @param account 注册帐号
 * @param password 注册密码
 * @return 1、注册成功 0、服务器没有返回结果2、这个账号已经存在3、注册失败
 */
public String regist(String account, String password) {
	if (getConnection() == null)
		return "0";
	Registration reg = new Registration();
	reg.setType(IQ.Type.SET);
	reg.setTo(getConnection().getServiceName());
	// 注意这里createAccount注册时,参数是UserName,不是jid,是"@"前面的部分。
	reg.setUsername(account);
	reg.setPassword(password);
	// 这边addAttribute不能为空,否则出错。所以做个标志是android手机创建的吧!!!!!
	reg.addAttribute("android", "geolo_createUser_android");
	PacketFilter filter = new AndFilter(new PacketIDFilter(reg.getPacketID()), new PacketTypeFilter(IQ.class));
	PacketCollector collector = getConnection().createPacketCollector(filter);
	getConnection().sendPacket(reg);
	IQ result = (IQ) collector.nextResult(SmackConfiguration.getPacketReplyTimeout());
	// Stop queuing results停止请求results(是否成功的结果)
	collector.cancel();
	if (result == null) {
		Log.e("regist", "No response from server.");
		return "0";
	} else if (result.getType() == IQ.Type.RESULT) {
		Log.v("regist", "regist success.");
		return "1";
	} else { // if (result.getType() == IQ.Type.ERROR)
		if (result.getError().toString().equalsIgnoreCase("conflict(409)")) {
			Log.e("regist", "IQ.Type.ERROR: " + result.getError().toString());
			return "2";
		} else {
			Log.e("regist", "IQ.Type.ERROR: " + result.getError().toString());
			return "3";
		}
	}
}
 
Example #12
Source File: ServiceManager.java    From AndroidPNClient with Apache License 2.0 5 votes vote down vote up
public ServiceManager(Context context) {
    this.context = context;

    if (context instanceof Activity) {
        Log.i(LOGTAG, "Callback Activity...");
        Activity callbackActivity = (Activity) context;
        callbackActivityPackageName = callbackActivity.getPackageName();
        callbackActivityClassName = callbackActivity.getClass().getName();
    }

    props = loadProperties();
    apiKey = props.getProperty(Constants.PROP_API_KEY, "");
    xmppHost = props.getProperty(Constants.PROP_XMPP_HOST, Constants.DEFAULT_HOST);
    xmppPort = props.getProperty(Constants.PROP_XMPP_PORT, Constants.DEFAULT_PORT);
    NotifierConfig.packetListener = props.getProperty(Constants.PROP_PACKET_LISTENER, null);
    NotifierConfig.iq = props.getProperty(Constants.PROP_IQ, null);
    NotifierConfig.iqProvider = props.getProperty(Constants.PROP_IQ_PROVIDER, null);
    NotifierConfig.notifyActivity = props.getProperty(Constants.PROP_NOTIFY_ACTIVITY, null);
    Log.i(LOGTAG, "apiKey=" + apiKey);
    Log.i(LOGTAG, "xmppHost=" + xmppHost);
    Log.i(LOGTAG, "xmppPort=" + xmppPort);
    Log.i(LOGTAG, "packetListener=" + NotifierConfig.packetListener);
    Log.i(LOGTAG, "iq=" + NotifierConfig.iq);
    Log.i(LOGTAG, "iqProvider=" + NotifierConfig.iqProvider);
    Log.i(LOGTAG, "notifyActivity" + NotifierConfig.notifyActivity);

    sharedPrefs = context.getSharedPreferences(
            Constants.SHARED_PREFERENCE_NAME, Context.MODE_PRIVATE);
    Editor editor = sharedPrefs.edit();
    editor.putString(Constants.API_KEY, apiKey);
    editor.putString(Constants.VERSION, version);
    editor.putString(Constants.XMPP_HOST, xmppHost);
    editor.putInt(Constants.XMPP_PORT, Integer.parseInt(xmppPort));
    editor.putString(Constants.CALLBACK_ACTIVITY_PACKAGE_NAME,
            callbackActivityPackageName);
    editor.putString(Constants.CALLBACK_ACTIVITY_CLASS_NAME,
            callbackActivityClassName);
    editor.commit();
    SmackConfiguration.setKeepAliveInterval(60000);
}
 
Example #13
Source File: SmackRepl.java    From Smack with Apache License 2.0 5 votes vote down vote up
public static void init() {
    SmackConfiguration.getVersion();
    // smack-repl also pulls in smack-resolver-minidns which has higher precedence the smack-resolver-javax but
    // won't work on Java SE platforms. Therefore explicitly setup JavaxResolver.
    JavaxResolver.setup();
    // CHECKSTYLE:OFF
    System.out.println("Smack REPL");
    // CHECKSTYLE:ON
}
 
Example #14
Source File: RemoteGroupCreationOverXMPP.java    From olat with Apache License 2.0 5 votes vote down vote up
private boolean sendPacket(final IQ packet) {
    final XMPPConnection con = adminUser.getConnection();
    try {
        packet.setFrom(con.getUser());
        final PacketCollector collector = con.createPacketCollector(new PacketIDFilter(packet.getPacketID()));
        con.sendPacket(packet);
        final IQ response = (IQ) collector.nextResult(SmackConfiguration.getPacketReplyTimeout());
        collector.cancel();

        if (response == null) {
            log.error("Error while trying to create/delete group at IM server. Response was null! packet type: " + packet.getClass());
            return false;
        }
        if (response.getError() != null) {
            if (response.getError().getCode() == 409) {
                // 409 -> conflict / group already exists
                return true;
            } else if (response.getError().getCode() == 404) {
                // 404 -> not found, does not matter when trying to delete
                return true;
            }
            log.error("Error while trying to create/delete group at IM server. " + response.getError().getMessage());
            return false;
        } else if (response.getType() == IQ.Type.ERROR) {
            log.error("Error while trying to create/delete group at IM server");
            return false;
        }
        return true;
    } catch (final RuntimeException e) {
        log.error("Error while trying to create/delete group at IM server");
        return false;
    }
}
 
Example #15
Source File: RemoteSessionCountOverXMPP.java    From olat with Apache License 2.0 5 votes vote down vote up
/**
*/
  @Override
  public int countSessions() {
      final XMPPConnection con = adminUser.getConnection();
      if (con != null && con.isConnected()) {
          // TODO:gs may put in other thread???
          SessionCount response;
          try {
              final IQ packet = new SessionCount();
              packet.setFrom(con.getUser());
              final PacketCollector collector = con.createPacketCollector(new PacketIDFilter(packet.getPacketID()));
              con.sendPacket(packet);
              response = (SessionCount) collector.nextResult(SmackConfiguration.getPacketReplyTimeout());
              collector.cancel();
              if (response == null) {
                  log.warn("Error while trying to count sessions at IM server. Response was null!");
                  return sessionCount;
              }
              if (response.getError() != null) {
                  log.warn("Error while trying to count sessions at IM server. " + response.getError().getMessage());
                  return sessionCount;
              } else if (response.getType() == IQ.Type.ERROR) {
                  log.warn("Error while trying to count sessions at IM server");
                  return sessionCount;
              }
              sessionCount = response.getNumberOfSessions();
              if (sessionCount > 0) {
                  return sessionCount - 1;
              }
              return sessionCount;

          } catch (final Exception e) {
              log.warn("Error while trying to count sessions at IM server. Response was null!", e);
              return sessionCount;
          }

      }
      return sessionCount;
  }
 
Example #16
Source File: RemotePluginVersionOverXMPP.java    From olat with Apache License 2.0 5 votes vote down vote up
/**
*/
  @Override
  public String getPluginVersion() {
      final XMPPConnection con = adminUser.getConnection();
      if (con != null && con.isConnected()) {
          PluginVersion response;
          try {
              final IQ packet = new PluginVersion();
              packet.setFrom(con.getUser());
              final PacketCollector collector = con.createPacketCollector(new PacketIDFilter(packet.getPacketID()));
              // TODO:gs is sending packets over one connection thread save?
              con.sendPacket(packet);
              response = (PluginVersion) collector.nextResult(SmackConfiguration.getPacketReplyTimeout());
              collector.cancel();
              if (response == null) {
                  log.error("Error while trying to get version at IM server. Response was null!");
                  return version;
              }
              if (response.getError() != null) {
                  log.error("Error while trying to get version at IM server. " + response.getError().getMessage());
                  return version;
              } else if (response.getType() == IQ.Type.ERROR) {
                  log.error("Error while trying to get version at IM server");
                  return version;
              }
              return response.getVersion();

          } catch (final Exception e) {
              log.error("Error while trying to get version at IM server. Response was null!", e);
              return version;
          }

      }
      return version;
  }
 
Example #17
Source File: OmemoClient.java    From Smack with Apache License 2.0 5 votes vote down vote up
public static void main(String[] args)
        throws XMPPException, SmackException, IOException, InterruptedException, CorruptedOmemoKeyException {
    SmackConfiguration.DEBUG = true;
    if (args.length != 2) {
        print("Missing arguments: <jid> <password>");
        return;
    }
    SignalOmemoService.acknowledgeLicense();
    SignalOmemoService.setup();
    SignalOmemoService omemoService = (SignalOmemoService) SignalOmemoService.getInstance();
    Path omemoStoreDirectory = Files.createTempDirectory("omemo-store");
    omemoService.setOmemoStoreBackend(new SignalCachingOmemoStore(new SignalFileBasedOmemoStore(omemoStoreDirectory.toFile())));

    EntityBareJid jid = JidCreate.entityBareFromOrThrowUnchecked(args[0]);
    String password = args[1];
    OmemoClient client = new OmemoClient(jid, password);
    try {
        client.start();

        while (true) {
            String input = scanner.nextLine();
            if (input.startsWith("/quit")) {
                break;
            }
            if (input.isEmpty()) {
                continue;
            }
            client.handleInput(input);
        }
    } finally {
        client.stop();
    }
}
 
Example #18
Source File: RemoteGroupCreationOverXMPP.java    From olat with Apache License 2.0 5 votes vote down vote up
private boolean sendPacket(final IQ packet) {
    final XMPPConnection con = adminUser.getConnection();
    try {
        packet.setFrom(con.getUser());
        final PacketCollector collector = con.createPacketCollector(new PacketIDFilter(packet.getPacketID()));
        con.sendPacket(packet);
        final IQ response = (IQ) collector.nextResult(SmackConfiguration.getPacketReplyTimeout());
        collector.cancel();

        if (response == null) {
            log.error("Error while trying to create/delete group at IM server. Response was null! packet type: " + packet.getClass());
            return false;
        }
        if (response.getError() != null) {
            if (response.getError().getCode() == 409) {
                // 409 -> conflict / group already exists
                return true;
            } else if (response.getError().getCode() == 404) {
                // 404 -> not found, does not matter when trying to delete
                return true;
            }
            log.error("Error while trying to create/delete group at IM server. " + response.getError().getMessage());
            return false;
        } else if (response.getType() == IQ.Type.ERROR) {
            log.error("Error while trying to create/delete group at IM server");
            return false;
        }
        return true;
    } catch (final RuntimeException e) {
        log.error("Error while trying to create/delete group at IM server");
        return false;
    }
}
 
Example #19
Source File: RemoteSessionCountOverXMPP.java    From olat with Apache License 2.0 5 votes vote down vote up
/**
*/
  @Override
  public int countSessions() {
      final XMPPConnection con = adminUser.getConnection();
      if (con != null && con.isConnected()) {
          // TODO:gs may put in other thread???
          SessionCount response;
          try {
              final IQ packet = new SessionCount();
              packet.setFrom(con.getUser());
              final PacketCollector collector = con.createPacketCollector(new PacketIDFilter(packet.getPacketID()));
              con.sendPacket(packet);
              response = (SessionCount) collector.nextResult(SmackConfiguration.getPacketReplyTimeout());
              collector.cancel();
              if (response == null) {
                  log.warn("Error while trying to count sessions at IM server. Response was null!");
                  return sessionCount;
              }
              if (response.getError() != null) {
                  log.warn("Error while trying to count sessions at IM server. " + response.getError().getMessage());
                  return sessionCount;
              } else if (response.getType() == IQ.Type.ERROR) {
                  log.warn("Error while trying to count sessions at IM server");
                  return sessionCount;
              }
              sessionCount = response.getNumberOfSessions();
              if (sessionCount > 0) {
                  return sessionCount - 1;
              }
              return sessionCount;

          } catch (final Exception e) {
              log.warn("Error while trying to count sessions at IM server. Response was null!", e);
              return sessionCount;
          }

      }
      return sessionCount;
  }
 
Example #20
Source File: XmppConnection.java    From Zom-Android-XMPP with GNU General Public License v3.0 5 votes vote down vote up
public void reconnectAll ()
{
    MultiUserChatManager mucMgr = MultiUserChatManager.getInstanceFor(mConnection);
    mucMgr.setAutoJoinOnReconnect(true);

    Enumeration<MultiUserChat> eMuc = mMUCs.elements();
    while (eMuc.hasMoreElements())
    {
        MultiUserChat muc = eMuc.nextElement();

        MultiUserChat reMuc = mucMgr.getMultiUserChat(muc.getRoom());

        try {
            DiscussionHistory history = new DiscussionHistory();
            history.setMaxStanzas(Integer.MAX_VALUE);
            reMuc.join(Resourcepart.from(mUser.getName()), null, history, SmackConfiguration.getDefaultPacketReplyTimeout());

            mMUCs.put(muc.getRoom().toString(),reMuc);
            ChatGroup group = mGroups.get(muc.getRoom().toString());

            addMucListeners(reMuc, group);
            loadMembers(muc, group);

            queryArchive(muc.getRoom());

        } catch (Exception e) {
            Log.w(TAG,"unable to join MUC: " + e.getMessage());
        }
    }
}
 
Example #21
Source File: XMPPManager.java    From Yahala-Messenger with MIT License 5 votes vote down vote up
public XMPPManager() {
    //SmackAndroid.init(ApplicationLoader.applicationContext);
    //SmackConfiguration.setDefaultPacketReplyTimeout(packetReplyTimeout);
    SmackConfiguration.setDefaultPacketReplyTimeout(20 * 300);
    SmackConfiguration.DEBUG = true;

    createAlarm();
    // mReconnectHandler = new Handler(mServiceLooper);
}
 
Example #22
Source File: XMPPManager.java    From Yahala-Messenger with MIT License 5 votes vote down vote up
public XMPPManager(String server, int port) {
    // SmackAndroid.init(ApplicationLoader.applicationContext);
    // SmackConfiguration.setDefaultPacketReplyTimeout(packetReplyTimeout);
    SmackConfiguration.setDefaultPacketReplyTimeout(20 * 300);
    SmackConfiguration.DEBUG = true;
    // createAlarm();
    //mServiceLooper = Looper.getMainLooper();
    this.HOST = server;
    this.PORT = port;
    //mReconnectHandler = new Handler(mServiceLooper);
}
 
Example #23
Source File: XSCHelper.java    From PracticeCode with Apache License 2.0 4 votes vote down vote up
/**
 * 注册。网络操作不可以在主线程中进行。多线程无法等待return,所以必须使用Handler
 *
 * @param account  登陆账户
 * @param password 登录密码
 * @param handler  处理信息的Handler
 */
public void regist(final String account, final String password, final Handler handler) {
    new Thread(){
        @Override
        public void run() {
            //如果无法连接服务器,Handle Error
            if (getConnection() == null) {
                Log.e("------->", "ERROR");
                handler.sendEmptyMessage(ERROR);
                return;
            }

            //如果已经是登录状态,Handle Failure
            if (getConnection().isAuthenticated()) {
                Log.e("------->", "hasAuthenticated");
                handler.sendEmptyMessage(FAILURE);
                return;
            }

            //如果状态正常则配置注册信息
            Registration reg = new Registration();
            reg.setType(IQ.Type.SET);
            reg.setTo(getConnection().getServiceName());
            reg.setUsername(account);
            reg.setPassword(password);
            reg.addAttribute("H-S-A-2015", "ThronBird");

            //配置Filter过滤器,注明包ID信息
            PacketFilter filter = new AndFilter(
                    new PacketIDFilter(reg.getPacketID()),
                    new PacketTypeFilter(IQ.class));

            //用Filter过滤器配置Collector接受器以便接受信息,并发送封包
            PacketCollector collector =
                    getConnection().createPacketCollector(filter);
            getConnection().sendPacket(reg);

            //等待信息,注明超时时间
            IQ result = (IQ) collector.nextResult(
                    SmackConfiguration.getPacketReplyTimeout());

            //接收到信息就可以取消掉Collector了,处理接受的信息
            collector.cancel();
            if(result == null) {
                handler.sendEmptyMessage(ERROR);
                return;
            }

            if(result.getType() == IQ.Type.RESULT) {
                handler.sendEmptyMessage(SUCCESS);
                return;
            }

            //以上是超时或者成功的情况,一下是失败的情况(已有/失败)
            if(result.getError().toString().equalsIgnoreCase("conflict(409)")) {
                handler.sendEmptyMessage(EXIST);
                return;
            }

            handler.sendEmptyMessage(FAILURE);

        }
    }.run();
}
 
Example #24
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 #25
Source File: DoX.java    From Smack with Apache License 2.0 4 votes vote down vote up
public static void main(String[] args) throws XMPPException, SmackException, IOException, InterruptedException {
    SmackConfiguration.DEBUG = true;

    XMPPTCPConnection connection = new XMPPTCPConnection(args[0], args[1]);
    connection.setReplyTimeout(60000);

    connection.connect().login();

    DnsOverXmppManager dox = DnsOverXmppManager.getInstanceFor(connection);

    Jid target = JidCreate.from("[email protected]/listener");
    Question question = new Question("geekplace.eu", Record.TYPE.A);

    DnsMessage response = dox.query(target, question);

    // CHECKSTYLE:OFF
    System.out.println(response);
    // CHECKSTYLE:ON

    connection.disconnect();
}
 
Example #26
Source File: JingleProviderTest.java    From Smack with Apache License 2.0 4 votes vote down vote up
/**
 * Test for parsing a Jingle
 */
public void testParseIQSimple() {

	// Create a dummy packet for testing...
	IQfake iqSent = new IQfake (
			" <jingle xmlns='urn:xmpp:tmp:jingle'" +
			" initiator=\"[email protected]\"" +
			" responder=\"[email protected]\"" +
			" action=\"transport-info\" sid=\"\">" +
			" <transport xmlns='urn:xmpp:tmp:jingle:transports:ice-udp'>" +
			" <candidate generation=\"1\"" +
			" ip=\"192.168.1.1\"" +
			" password=\"secret\"" +
			" port=\"8080\"" +
			" username=\"username\"" +
			" preference=\"1\"/>" +
			" </transport>" +
	"</jingle>");

	iqSent.setTo(getFullJID(0));
	iqSent.setFrom(getFullJID(0));
	iqSent.setType(IQ.Type.get);

	// Create a filter and a collector...
	PacketFilter filter = new StanzaTypeFilter(IQ.class);
	StanzaCollector collector = getConnection(0).createStanzaCollector(filter);

	System.out.println("Testing if a Jingle IQ can be sent and received...");

	// Send the iq packet with an invalid namespace
	getConnection(0).sendStanza(iqSent);

	// Receive the packet
	IQ iqReceived = (IQ)collector.nextResult(SmackConfiguration.getPacketReplyTimeout());

	// Stop queuing results
	collector.cancel();

	if (iqReceived == null) {
		fail("No response from server");
	}
	else if (iqReceived.getType() == IQ.Type.error) {
		fail("The server did reply with an error packet: " + iqReceived.getError().getCode());
	}
	else {
		assertTrue(iqReceived instanceof Jingle);

		Jingle jin = (Jingle) iqReceived;

		System.out.println("Sent:     " + iqSent.toXML());
		System.out.println("Received: " + jin.toXML());
	}
}
 
Example #27
Source File: MultipleRecipientManagerTest.java    From Smack with Apache License 2.0 4 votes vote down vote up
/**
 * Ensures that sending and receiving of packets is ok.
 */
public void testSending() throws XMPPException {

    StanzaCollector collector1 =
            getConnection(1).createStanzaCollector(new MessageTypeFilter(Message.Type.normal));
    StanzaCollector collector2 =
            getConnection(2).createStanzaCollector(new MessageTypeFilter(Message.Type.normal));
    StanzaCollector collector3 =
            getConnection(3).createStanzaCollector(new MessageTypeFilter(Message.Type.normal));

    Message message = new Message();
    message.setBody("Hola");
    List<String> to = Arrays.asList(new String[]{getBareJID(1)});
    List<String> cc = Arrays.asList(new String[]{getBareJID(2)});
    List<String> bcc = Arrays.asList(new String[]{getBareJID(3)});
    MultipleRecipientManager.send(getConnection(0), message, to, cc, bcc);

    Packet message1 = collector1.nextResult(SmackConfiguration.getPacketReplyTimeout());
    assertNotNull("XMPPConnection 1 never received the message", message1);
    MultipleRecipientInfo info1 = MultipleRecipientManager.getMultipleRecipientInfo(message1);
    assertNotNull("Message 1 does not contain MultipleRecipientInfo", info1);
    assertFalse("Message 1 should be 'replyable'", info1.shouldNotReply());
    List<?> addresses1 = info1.getTOAddresses();
    assertEquals("Incorrect number of TO addresses", 1, addresses1.size());
    String address1 = ((MultipleAddresses.Address) addresses1.get(0)).getJid();
    assertEquals("Incorrect TO address", getBareJID(1), address1);
    addresses1 = info1.getCCAddresses();
    assertEquals("Incorrect number of CC addresses", 1, addresses1.size());
    address1 = ((MultipleAddresses.Address) addresses1.get(0)).getJid();
    assertEquals("Incorrect CC address", getBareJID(2), address1);

    Packet message2 = collector2.nextResult(SmackConfiguration.getPacketReplyTimeout());
    assertNotNull("XMPPConnection 2 never received the message", message2);
    MultipleRecipientInfo info2 = MultipleRecipientManager.getMultipleRecipientInfo(message2);
    assertNotNull("Message 2 does not contain MultipleRecipientInfo", info2);
    assertFalse("Message 2 should be 'replyable'", info2.shouldNotReply());
    List<MultipleAddresses.Address> addresses2 = info2.getTOAddresses();
    assertEquals("Incorrect number of TO addresses", 1, addresses2.size());
    String address2 = ((MultipleAddresses.Address) addresses2.get(0)).getJid();
    assertEquals("Incorrect TO address", getBareJID(1), address2);
    addresses2 = info2.getCCAddresses();
    assertEquals("Incorrect number of CC addresses", 1, addresses2.size());
    address2 = ((MultipleAddresses.Address) addresses2.get(0)).getJid();
    assertEquals("Incorrect CC address", getBareJID(2), address2);

    Packet message3 = collector3.nextResult(SmackConfiguration.getPacketReplyTimeout());
    assertNotNull("XMPPConnection 3 never received the message", message3);
    MultipleRecipientInfo info3 = MultipleRecipientManager.getMultipleRecipientInfo(message3);
    assertNotNull("Message 3 does not contain MultipleRecipientInfo", info3);
    assertFalse("Message 3 should be 'replyable'", info3.shouldNotReply());
    List<MultipleAddresses.Address> addresses3 = info3.getTOAddresses();
    assertEquals("Incorrect number of TO addresses", 1, addresses3.size());
    String address3 = ((MultipleAddresses.Address) addresses3.get(0)).getJid();
    assertEquals("Incorrect TO address", getBareJID(1), address3);
    addresses3 = info3.getCCAddresses();
    assertEquals("Incorrect number of CC addresses", 1, addresses3.size());
    address3 = ((MultipleAddresses.Address) addresses3.get(0)).getJid();
    assertEquals("Incorrect CC address", getBareJID(2), address3);

    collector1.cancel();
    collector2.cancel();
    collector3.cancel();
}
 
Example #28
Source File: MultiUserChatTest.java    From Smack with Apache License 2.0 4 votes vote down vote up
public void testDiscussionHistory() {
    try {
        // User1 sends some messages to the room
        muc.sendMessage("Message 1");
        muc.sendMessage("Message 2");
        // Wait 5 seconds before sending the last message
        Thread.sleep(5000);
        muc.sendMessage("Message 3");

        // User2 joins the room requesting to receive the messages of the last 2 seconds.
        MultiUserChat muc2 = new MultiUserChat(getConnection(1), room);
        DiscussionHistory history = new DiscussionHistory();
        history.setSeconds(2);
        muc2.join("testbot2", null, history, SmackConfiguration.getPacketReplyTimeout());

        Message msg;
        // Get first historic message
        msg = muc2.nextMessage(1000);
        assertNotNull("First message is null", msg);
        DelayInformation delay = DelayInformationManager.getDelayInformation(msg);
        assertNotNull("Message contains no delay information", delay);
        SimpleDateFormat UTC_FORMAT = new SimpleDateFormat("yyyyMMdd'T'HH:mm:ss");
        UTC_FORMAT.setTimeZone(TimeZone.getDefault());
        System.out.println(UTC_FORMAT.format(delay.getStamp()));

        assertEquals("Body of first message is incorrect", "Message 3", msg.getBody());
        // Try to get second historic message
        msg = muc2.nextMessage(1000);
        assertNull("Second message is not null", msg);


        // User3 joins the room requesting to receive the last 2 messages.
        MultiUserChat muc3 = new MultiUserChat(getConnection(2), room);
        history = new DiscussionHistory();
        history.setMaxStanzas(2);
        muc3.join("testbot3", null, history, SmackConfiguration.getPacketReplyTimeout());

        // Get first historic message
        msg = muc3.nextMessage(1000);
        assertNotNull("First message is null", msg);
        assertEquals("Body of first message is incorrect", "Message 2", msg.getBody());
        // Get second historic message
        msg = muc3.nextMessage(1000);
        assertNotNull("Second message is null", msg);
        assertEquals("Body of second message is incorrect", "Message 3", msg.getBody());
        // Try to get third historic message
        msg = muc3.nextMessage(1000);
        assertNull("Third message is not null", msg);

        // User2 leaves the room
        muc2.leave();
        // User3 leaves the room
        muc3.leave();

    }
    catch (Exception e) {
        e.printStackTrace();
        fail(e.getMessage());
    }
}
 
Example #29
Source File: VersionManager.java    From Smack with Apache License 2.0 4 votes vote down vote up
private static Version generateVersionFrom(String name, String version, String os) {
    if (autoAppendSmackVersion) {
        name += " (Smack " + SmackConfiguration.getVersion() + ')';
    }
    return new Version(name, version, os);
}
 
Example #30
Source File: PrivateDataManager.java    From Smack with Apache License 2.0 4 votes vote down vote up
@Override
public String getNamespace() {
    return SmackConfiguration.SMACK_URL_STRING;
}