Java Code Examples for org.jivesoftware.smack.XMPPConnection#isConnected()

The following examples show how to use org.jivesoftware.smack.XMPPConnection#isConnected() . 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: InstantMessagingClient.java    From olat with Apache License 2.0 6 votes vote down vote up
/**
 * Close the connection to the server
 */
public void closeConnection(final boolean closeSynchronously) {
    // Set isConnected to false first since connection.close triggers an
    // XMPPConnListener.connectionClosed() event which would result in
    // in a cyclic call of this close method.
    isConnected = false;
    final XMPPConnection connectionToClose = connection;
    final Runnable connectionCloseRunnable = new Runnable() {
        @Override
        public void run() {
            try {
                if (connectionToClose != null && connectionToClose.isConnected()) {
                    connectionToClose.disconnect();
                }
            } catch (final RuntimeException e) {
                log.warn("Error while trying to close instant messaging connection", e);
            }
        }
    };
    if (closeSynchronously) {
        connectionCloseRunnable.run();
    } else {
        taskExecutorService.runTask(connectionCloseRunnable);
    }
}
 
Example 2
Source File: MainWindow.java    From Spark with Apache License 2.0 6 votes vote down vote up
/**
 * Closes the current connection and restarts Spark.
 *
 * @param reason the reason for logging out. This can be if user gave no reason.
 */
public void closeConnectionAndInvoke(String reason) {
    final XMPPConnection con = SparkManager.getConnection();
    if (con.isConnected()) {
        if (reason != null) {
            Presence byePresence = new Presence(Presence.Type.unavailable, reason, -1, null);
            try
            {
                ((AbstractXMPPConnection)con).disconnect(byePresence);
            }
            catch ( SmackException.NotConnectedException e )
            {
                Log.error( "Unable to sign out with presence.", e);
                ((AbstractXMPPConnection)con).disconnect();
            }
        }
        else {
            ((AbstractXMPPConnection)con).disconnect();
        }
    }
    if (!restartApplicationWithScript()) {
        restartApplicationWithJava();
    }
}
 
Example 3
Source File: MainWindow.java    From Spark with Apache License 2.0 6 votes vote down vote up
/**
 * Prepares Spark for shutting down by first calling all {@link MainWindowListener}s and
 * setting the Agent to be offline.
 */
public void shutdown() {
    final XMPPConnection con = SparkManager.getConnection();

    if (con.isConnected()) {
        // Send disconnect.
        ((AbstractXMPPConnection)con).disconnect();
    }

    // Notify all MainWindowListeners
    try {
        fireWindowShutdown();
    }
    catch (Exception ex) {
        Log.error(ex);
    }
    // Close application.
    System.exit(1);

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

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

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

    StanzaCollector collector = connection.createStanzaCollectorAndSend(stunPacket);

    STUN response = collector.nextResult();

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

    return response;
}
 
Example 5
Source File: RTPBridge.java    From Smack with Apache License 2.0 6 votes vote down vote up
/**
 * Get a new RTPBridge Candidate from the server.
 * If a error occurs or the server don't support RTPBridge Service, null is returned.
 *
 * @param connection TODO javadoc me please
 * @param sessionID TODO javadoc me please
 * @return the new RTPBridge
 * @throws NotConnectedException if the XMPP connection is not connected.
 * @throws InterruptedException if the calling thread was interrupted.
 */
public static RTPBridge getRTPBridge(XMPPConnection connection, String sessionID) throws NotConnectedException, InterruptedException {

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

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

    StanzaCollector collector = connection.createStanzaCollectorAndSend(rtpPacket);

    RTPBridge response = collector.nextResult();

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

    return response;
}
 
Example 6
Source File: InstantMessagingClient.java    From olat with Apache License 2.0 6 votes vote down vote up
/**
 * Close the connection to the server
 */
public void closeConnection(final boolean closeSynchronously) {
    // Set isConnected to false first since connection.close triggers an
    // XMPPConnListener.connectionClosed() event which would result in
    // in a cyclic call of this close method.
    isConnected = false;
    final XMPPConnection connectionToClose = connection;
    final Runnable connectionCloseRunnable = new Runnable() {
        @Override
        public void run() {
            try {
                if (connectionToClose != null && connectionToClose.isConnected()) {
                    connectionToClose.disconnect();
                }
            } catch (final RuntimeException e) {
                log.warn("Error while trying to close instant messaging connection", e);
            }
        }
    };
    if (closeSynchronously) {
        connectionCloseRunnable.run();
    } else {
        taskExecutorService.runTask(connectionCloseRunnable);
    }
}
 
Example 7
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 8
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 9
Source File: YiIMUtils.java    From yiim_v2 with GNU General Public License v2.0 5 votes vote down vote up
public static int addGroup(Context context, String groupName) {
	String owner = UserInfo.getUserInfo(context).getUser();
	Cursor groupCursor = null;
	try {
		groupCursor = context.getContentResolver().query(
				RosterGroupColumns.CONTENT_URI,
				new String[] { RosterGroupColumns._ID },
				RosterGroupColumns.NAME + "='" + groupName + "' and "
						+ RosterGroupColumns.OWNER + "='" + owner + "'",
				null, null);
		if (groupCursor != null && groupCursor.getCount() != 0) {
			return -1;
		}

		XMPPConnection connection = XmppConnectionUtils.getInstance()
				.getConnection();
		if (connection != null && connection.isConnected()
				&& connection.isAuthenticated()) {
			connection.getRoster().createGroup(groupName);

			ContentValues values = new ContentValues();
			values.put(RosterGroupColumns.NAME, groupName);
			values.put(RosterGroupColumns.OWNER, owner);

			context.getContentResolver().insert(
					RosterGroupColumns.CONTENT_URI, values);
			return 0;
		} else {
			return -2;
		}
	} catch (Exception e) {
		return -2;
	} finally {
		if (groupCursor != null) {
			groupCursor.close();
			groupCursor = null;
		}
	}
}
 
Example 10
Source File: RTPBridge.java    From Smack with Apache License 2.0 5 votes vote down vote up
/**
     * Check if the server support RTPBridge Service.
     *
     * @param connection TODO javadoc me please
     * @return true if the server supports the RTPBridge service
     * @throws XMPPErrorException if there was an XMPP error returned.
     * @throws NoResponseException if there was no response from the remote entity.
     * @throws NotConnectedException if the XMPP connection is not connected.
     * @throws InterruptedException if the calling thread was interrupted.
     */
    public static boolean serviceAvailable(XMPPConnection connection) throws NoResponseException,
                    XMPPErrorException, NotConnectedException, InterruptedException {

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

        LOGGER.fine("Service listing");

        ServiceDiscoveryManager disco = ServiceDiscoveryManager
                .getInstanceFor(connection);
//            DiscoverItems items = disco.discoverItems(connection.getXMPPServiceDomain());
//            Iterator iter = items.getItems();
//            while (iter.hasNext()) {
//                DiscoverItems.Item item = (DiscoverItems.Item) iter.next();
//                if (item.getEntityID().startsWith("rtpbridge.")) {
//                    return true;
//                }
//            }

        DiscoverInfo discoInfo = disco.discoverInfo(connection.getXMPPServiceDomain());
        for (DiscoverInfo.Identity identity : discoInfo.getIdentities()) {
            if (identity.getName() != null && identity.getName().startsWith("rtpbridge")) {
                return true;
            }
        }

        return false;
    }
 
Example 11
Source File: RTPBridge.java    From Smack with Apache License 2.0 5 votes vote down vote up
/**
 * Check if the server support RTPBridge Service.
 *
 * @param connection TODO javadoc me please
 * @param sessionID the session id.
 * @param pass the password.
 * @param proxyCandidate the proxy candidate.
 * @param localCandidate the local candidate.
 * @return the RTPBridge
 * @throws NotConnectedException if the XMPP connection is not connected.
 * @throws InterruptedException if the calling thread was interrupted.
 */
public static RTPBridge relaySession(XMPPConnection connection, String sessionID, String pass, TransportCandidate proxyCandidate, TransportCandidate localCandidate) throws NotConnectedException, InterruptedException {

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

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

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

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

    StanzaCollector collector = connection.createStanzaCollectorAndSend(rtpPacket);

    RTPBridge response = collector.nextResult();

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

    return response;
}
 
Example 12
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 13
Source File: STUN.java    From Smack with Apache License 2.0 5 votes vote down vote up
/**
 * Check if the server support STUN Service.
 *
 * @param connection the connection
 * @return true if the server support STUN
 * @throws SmackException if Smack detected an exceptional situation.
 * @throws XMPPException if an XMPP protocol error was received.
 * @throws InterruptedException if the calling thread was interrupted.
 */
public static boolean serviceAvailable(XMPPConnection connection) throws XMPPException, SmackException, InterruptedException {

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

    LOGGER.fine("Service listing");

    ServiceDiscoveryManager disco = ServiceDiscoveryManager.getInstanceFor(connection);
    DiscoverItems items = disco.discoverItems(connection.getXMPPServiceDomain());

    for (DiscoverItems.Item item : items.getItems()) {
        DiscoverInfo info = disco.discoverInfo(item.getEntityID());

        for (DiscoverInfo.Identity identity : info.getIdentities()) {
            if (identity.getCategory().equals("proxy") && identity.getType().equals("stun"))
                if (info.containsFeature(NAMESPACE))
                    return true;
        }

        LOGGER.fine(item.getName() + "-" + info.getType());

    }

    return false;
}
 
Example 14
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 15
Source File: MainWindow.java    From Spark with Apache License 2.0 5 votes vote down vote up
/**
 * Prepares Spark for shutting down by first calling all {@link MainWindowListener}s and
 * setting the Agent to be offline.
 *
 * @param sendStatus true if Spark should send a presence with a status message.
 */
public void logout(boolean sendStatus) {
    final XMPPConnection con = SparkManager.getConnection();
    String status = null;

    if (con.isConnected() && sendStatus) {
        final InputTextAreaDialog inputTextDialog = new InputTextAreaDialog();
        status = inputTextDialog.getInput(Res.getString("title.status.message"), Res.getString("message.current.status"),
            SparkRes.getImageIcon(SparkRes.USER1_MESSAGE_24x24), this);
    }

    if (status != null || !sendStatus)
    {
     // Notify all MainWindowListeners
     try {
         // Set auto-login to false;
         SettingsManager.getLocalPreferences().setAutoLogin(false);
         SettingsManager.saveSettings();

         fireWindowShutdown();
         setVisible(false);
     }
     finally {
         closeConnectionAndInvoke(status);
     }
    }
}
 
Example 16
Source File: XmppService.java    From yiim_v2 with GNU General Public License v2.0 4 votes vote down vote up
public boolean isXmppServiceStarted() {
	XMPPConnection connection = XmppConnectionUtils.getInstance()
			.getRawConnection();
	return connection != null && connection.isConnected();
}
 
Example 17
Source File: YiIMUtils.java    From yiim_v2 with GNU General Public License v2.0 4 votes vote down vote up
public static void updatePresenceType(Context context, String user) {
	String currentUser = UserInfo.getUserInfo(context).getUser();
	user = StringUtils.escapeUserResource(user);

	Cursor cursor = null;
	try {
		cursor = context.getContentResolver().query(
				RosterColumns.CONTENT_URI,
				new String[] { RosterColumns._ID },
				RosterColumns.USERID + "='" + user + "' and "
						+ RosterColumns.OWNER + "='" + currentUser + "'",
				null, null);
		if (cursor != null && cursor.getCount() > 0) {
			cursor.moveToFirst();
			XMPPConnection connection = XmppConnectionUtils.getInstance()
					.getConnection();
			if (connection != null && connection.isConnected()
					&& connection.isAuthenticated()) {
				RosterEntry rosterEntry = connection.getRoster().getEntry(
						user);
				if (rosterEntry != null) {
					do {
						ContentValues values = new ContentValues();
						values.put(RosterColumns.ROSTER_TYPE, rosterEntry
								.getType().toString());
						context.getContentResolver().update(
								ContentUris.withAppendedId(
										RosterColumns.CONTENT_URI,
										cursor.getLong(0)), values, null,
								null);
					} while (cursor.moveToNext());
				}
			}
		}
	} catch (Exception e) {

	} finally {
		if (cursor != null) {
			cursor.close();
			cursor = null;
		}
	}
}
 
Example 18
Source File: YiIMUtils.java    From yiim_v2 with GNU General Public License v2.0 4 votes vote down vote up
public static int deleteGroup(Context context, long groupId) {
	String owner = UserInfo.getUserInfo(context).getUser();

	Cursor groupCursor = null;
	Cursor entriesCursor = null;
	Cursor defaultGroupCursor = null;
	try {
		groupCursor = context.getContentResolver().query(
				ContentUris.withAppendedId(RosterGroupColumns.CONTENT_URI,
						groupId), new String[] { RosterGroupColumns.NAME },
				null, null, null);
		if (groupCursor == null || groupCursor.getCount() != 1) {
			return -1;
		}
		groupCursor.moveToFirst();
		String groupName = groupCursor.getString(0);
		if ("unfiled".equals(groupName)) {
			return -2;
		}

		defaultGroupCursor = context.getContentResolver().query(
				RosterGroupColumns.CONTENT_URI,
				new String[] { RosterGroupColumns._ID },
				RosterGroupColumns.NAME + "='unfiled' and "
						+ RosterGroupColumns.OWNER + "='" + owner + "'",
				null, null);
		if (defaultGroupCursor == null
				|| defaultGroupCursor.getCount() != 1) {
			return -1;
		}
		defaultGroupCursor.moveToFirst();
		int defaultGroupId = defaultGroupCursor.getInt(0);

		XMPPConnection connection = XmppConnectionUtils.getInstance()
				.getConnection();
		if (connection == null || !connection.isConnected()
				|| !connection.isAuthenticated()) {
			return -1;
		}

		RosterGroup rosterGroup = connection.getRoster()
				.getGroup(groupName);
		if (rosterGroup == null) {
			return -1;
		}

		Collection<RosterEntry> entries = rosterGroup.getEntries();
		if (entries != null && entries.size() > 0) {
			for (RosterEntry rosterEntry : entries) {
				rosterGroup.removeEntry(rosterEntry);
			}
		}

		entriesCursor = context.getContentResolver().query(
				RosterColumns.CONTENT_URI,
				new String[] { RosterColumns._ID },
				RosterColumns.GROUP_ID + "=" + groupId, null, null);
		List<Integer> mIntegers = new ArrayList<Integer>();
		if (entriesCursor != null && entriesCursor.getCount() > 0) {
			entriesCursor.moveToFirst();
			do {
				mIntegers.add(entriesCursor.getInt(0));
			} while (entriesCursor.moveToNext());
		}

		for (Integer integer : mIntegers) {
			ContentValues values = new ContentValues();
			values.put(RosterColumns.GROUP_ID, defaultGroupId);
			context.getContentResolver().update(
					ContentUris.withAppendedId(RosterColumns.CONTENT_URI,
							integer), values, null, null);
		}

		context.getContentResolver().delete(
				ContentUris.withAppendedId(RosterGroupColumns.CONTENT_URI,
						groupId), null, null);
		return 0;
	} catch (Exception e) {
		return -1;
	} finally {
		if (groupCursor != null) {
			groupCursor.close();
			groupCursor = null;
		}

		if (entriesCursor != null) {
			entriesCursor.close();
			entriesCursor = null;
		}

		if (defaultGroupCursor != null) {
			defaultGroupCursor.close();
			defaultGroupCursor = null;
		}
	}
}
 
Example 19
Source File: YiIMUtils.java    From yiim_v2 with GNU General Public License v2.0 4 votes vote down vote up
/**
 * 加入会议室
 * 
 * @param user
 *            昵称
 * @param password
 *            会议室密码
 * @param roomsName
 *            会议室名
 */
public static MultiUserChat joinMultiUserChat(Context context, String user,
		String roomJid, String password) throws Exception {
	XMPPConnection connection = XmppConnectionUtils.getInstance()
			.getRawConnection();
	if (connection == null || !connection.isConnected()
			|| !connection.isAuthenticated())
		throw new Exception("connection not ready");

	Cursor cursor = null;
	try {
		// 使用XMPPConnection创建一个MultiUserChat窗口
		MultiUserChat muc = new MultiUserChat(connection, roomJid);
		// 聊天室服务将会决定要接受的历史记录数量
		DiscussionHistory history = new DiscussionHistory();

		cursor = context.getContentResolver().query(
				MultiChatRoomColumns.CONTENT_URI,
				new String[] { MultiChatRoomColumns.LAST_MSG_TIME },
				MultiChatRoomColumns.ROOM_JID + "='" + roomJid + "' and "
						+ MultiChatRoomColumns.OWNER + "='"
						+ UserInfo.getUserInfo(context).getUser() + "'",
				null, null);
		if (cursor != null && cursor.getCount() == 1) {
			cursor.moveToFirst();
			history.setSince(new Date(cursor.getLong(0)));
		} else {
			history.setMaxStanzas(15);
		}
		// 用户加入聊天室
		muc.join(StringUtils.escapeUserHost(user), password, history,
				SmackConfiguration.getPacketReplyTimeout());
		return muc;
	} catch (Exception e) {
		throw e;
	} finally {
		if (cursor != null) {
			cursor.close();
			cursor = null;
		}
	}
}
 
Example 20
Source File: JMeterXMPPSampler.java    From jmeter-bzm-plugins with Apache License 2.0 4 votes vote down vote up
@Override
public SampleResult sample(Entry entry) {
    SampleResult res = new SampleResult();
    res.setSampleLabel(getName());
    res.setDataType(SampleResult.TEXT);
    res.setSuccessful(true);
    res.setResponseCode("200");
    res.setResponseMessage("OK");

    res.sampleStart();
    try {
        if (connConfig == null) {
            throw new RuntimeException("Cannot sample XMPP without XMPP Connection component");
        }

        XMPPConnection conn = getXMPPConnection();

        if (conn == null) {
            throw new RuntimeException("No XMPP Connection available");
        }

        String headers = "Connection ID: " + conn.getConnectionID() + "\r\n";

        String action = getAction();
        if (!conn.isConnected() && !action.equals(Connect.class.getCanonicalName())) {
            log.error("Please call Connect before calling other actions");
            throw new SmackException.NotConnectedException();
        }

        headers += "User: " + conn.getUser() + "\r\n";

        res.setRequestHeaders(headers);

        AbstractXMPPAction actObject = connConfig.getActions().get(action);
        if (actObject.perform(this, res) == null) {
            return null;
        }
    } catch (Exception e) {
        log.error("Error in XMPP Sampler: ", e);
        res.setSuccessful(false);
        res.setResponseCode("500");
        res.setResponseMessage((e.getMessage() == null || e.getMessage().isEmpty()) ? e.toString() : e.getMessage());
        res.setResponseData(ExceptionUtils.getStackTrace(e).getBytes());
    }

    res.sampleEnd();
    return res;
}