Java Code Examples for org.jivesoftware.smack.util.StringUtils

The following examples show how to use org.jivesoftware.smack.util.StringUtils. These examples are extracted from open source projects. 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 Project: Smack   Source File: EntityCapsManagerTest.java    License: Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("UnusedVariable")
private static void testSimpleDirectoryCache(StringEncoder<String> stringEncoder) throws IOException {

    EntityCapsPersistentCache cache = new SimpleDirectoryPersistentCache(createTempDirectory());
    EntityCapsManager.setPersistentCache(cache);

    DiscoverInfo di = createComplexSamplePacket();
    CapsVersionAndHash versionAndHash = EntityCapsManager.generateVerificationString(di, StringUtils.SHA1);
    String nodeVer = di.getNode() + "#" + versionAndHash.version;

    // Save the data in EntityCapsManager
    EntityCapsManager.addDiscoverInfoByNode(nodeVer, di);

    // Lose all the data
    EntityCapsManager.clearMemoryCache();

    DiscoverInfo restored_di = EntityCapsManager.getDiscoveryInfoByNodeVer(nodeVer);
    assertNotNull(restored_di);
    assertEquals(di.toXML().toString(), restored_di.toXML().toString());
}
 
Example 2
Source Project: Spark   Source File: InvitationManager.java    License: 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 3
Source Project: Smack   Source File: LoginIntegrationTest.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Check that the server is returning the correct error when trying to login using an invalid
 * (i.e. non-existent) user.
 *
 * @throws InterruptedException if the calling thread was interrupted.
 * @throws XMPPException if an XMPP protocol error was received.
 * @throws IOException if an I/O error occurred.
 * @throws SmackException if Smack detected an exceptional situation.
 * @throws NoSuchAlgorithmException if no such algorithm is available.
 * @throws KeyManagementException if there was a key mangement error.
 */
@SmackIntegrationTest
public void testInvalidLogin() throws SmackException, IOException, XMPPException,
                InterruptedException, KeyManagementException, NoSuchAlgorithmException {
    final String nonExistentUserString = StringUtils.insecureRandomString(24);
    final String invalidPassword = "invalidPassword";

    AbstractXMPPConnection connection = getUnconnectedConnection();
    connection.connect();

    try {
        SASLErrorException saslErrorException = assertThrows(SASLErrorException.class,
                        () -> connection.login(nonExistentUserString, invalidPassword));

        SaslNonza.SASLFailure saslFailure = saslErrorException.getSASLFailure();
        assertEquals(SASLError.not_authorized, saslFailure.getSASLError());
    } finally {
        connection.disconnect();
    }
}
 
Example 4
Source Project: Smack   Source File: NodeInfo.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public boolean equals(Object other) {
    if (this == other) {
        return true;
    }
    if (other == null) {
        return false;
    }
    if (!(other instanceof NodeInfo)) {
        return false;
    }
    NodeInfo otherNodeInfo = (NodeInfo) other;
    if (!nodeId.equals(otherNodeInfo.nodeId)) {
        return false;
    }
    if (StringUtils.nullSafeCharSequenceEquals(sourceId, otherNodeInfo.sourceId)
                    && StringUtils.nullSafeCharSequenceEquals(cacheType, otherNodeInfo.cacheType)) {
        return true;
    }
    return false;
}
 
Example 5
Source Project: Smack   Source File: HashElementTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void stanzaTest() throws Exception {
    String message = "Hello World!";
    HashElement element = HashManager.calculateHashElement(SHA_256, StringUtils.toUtf8Bytes(message));
    String expected = "<hash xmlns='urn:xmpp:hashes:2' algo='sha-256'>f4OxZX/x/FO5LcGBSKHWXfwtSx+j1ncoSt3SABJtkGk=</hash>";
    assertEquals(expected, element.toXML().toString());

    HashElement parsed = new HashElementProvider().parse(TestUtils.getParser(expected));
    assertEquals(expected, parsed.toXML().toString());
    assertEquals(SHA_256, parsed.getAlgorithm());
    assertEquals("f4OxZX/x/FO5LcGBSKHWXfwtSx+j1ncoSt3SABJtkGk=", parsed.getHashB64());
    assertArrayEquals(HashManager.sha_256(message), parsed.getHash());

    assertEquals(element, parsed);
    assertTrue(element.equals(parsed));

    HashElement other = new HashElement(HashManager.ALGORITHM.SHA_512,
            "861844d6704e8573fec34d967e20bcfef3d424cf48be04e6dc08f2bd58c729743371015ead891cc3cf1c9d34b49264b510751b1ff9e537937bc46b5d6ff4ecc8".getBytes(StandardCharsets.UTF_8));
    assertFalse(element.equals(other));
}
 
Example 6
Source Project: Smack   Source File: HashTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void hashTest() {
    assertEquals(md5sum, StringUtils.encodeHex(HashManager.hash(HashManager.ALGORITHM.MD5, array())));
    assertEquals(sha1sum, StringUtils.encodeHex(HashManager.hash(HashManager.ALGORITHM.SHA_1, array())));
    assertEquals(sha224sum, StringUtils.encodeHex(HashManager.hash(HashManager.ALGORITHM.SHA_224, array())));
    assertEquals(sha256sum, StringUtils.encodeHex(HashManager.hash(HashManager.ALGORITHM.SHA_256, array())));
    assertEquals(sha384sum, StringUtils.encodeHex(HashManager.hash(HashManager.ALGORITHM.SHA_384, array())));
    assertEquals(sha512sum, StringUtils.encodeHex(HashManager.hash(HashManager.ALGORITHM.SHA_512, array())));
    assertEquals(sha3_224sum, StringUtils.encodeHex(HashManager.hash(HashManager.ALGORITHM.SHA3_224, array())));
    assertEquals(sha3_256sum, StringUtils.encodeHex(HashManager.hash(HashManager.ALGORITHM.SHA3_256, array())));
    assertEquals(sha3_384sum, StringUtils.encodeHex(HashManager.hash(HashManager.ALGORITHM.SHA3_384, array())));
    assertEquals(sha3_512sum, StringUtils.encodeHex(HashManager.hash(HashManager.ALGORITHM.SHA3_512, array())));
    assertEquals(b2_160sum, StringUtils.encodeHex(HashManager.hash(HashManager.ALGORITHM.BLAKE2B160, array())));
    assertEquals(b2_256sum, StringUtils.encodeHex(HashManager.hash(HashManager.ALGORITHM.BLAKE2B256, array())));
    assertEquals(b2_384sum, StringUtils.encodeHex(HashManager.hash(HashManager.ALGORITHM.BLAKE2B384, array())));
    assertEquals(b2_512sum, StringUtils.encodeHex(HashManager.hash(HashManager.ALGORITHM.BLAKE2B512, array())));
}
 
Example 7
Source Project: Smack   Source File: MetaDataUtils.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Serializes a Map of String name/value pairs into the meta-data XML format.
 *
 * @param metaData the Map of meta-data as Map&lt;String, List&lt;String&gt;&gt;
 * @return the meta-data values in XML form.
 */
public static String serializeMetaData(Map<String, List<String>> metaData) {
    StringBuilder buf = new StringBuilder();
    if (metaData != null && metaData.size() > 0) {
        buf.append("<metadata xmlns=\"http://jivesoftware.com/protocol/workgroup\">");
        for (String key : metaData.keySet()) {
            List<String> value = metaData.get(key);
            for (String v : value) {
                buf.append("<value name=\"").append(key).append("\">");
                buf.append(StringUtils.escapeForXmlText(v));
                buf.append("</value>");
            }
        }
        buf.append("</metadata>");
    }
    return buf.toString();
}
 
Example 8
Source Project: Smack   Source File: AccountManager.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Creates a new account using the specified username, password and account attributes.
 * The attributes Map must contain only String name/value pairs and must also have values
 * for all required attributes.
 *
 * @param username the username.
 * @param password the password.
 * @param attributes the account attributes.
 * @throws XMPPErrorException if an error occurs creating the account.
 * @throws NoResponseException if there was no response from the server.
 * @throws NotConnectedException if the XMPP connection is not connected.
 * @throws InterruptedException if the calling thread was interrupted.
 * @see #getAccountAttributes()
 */
public void createAccount(Localpart username, String password, Map<String, String> attributes)
                throws NoResponseException, XMPPErrorException, NotConnectedException, InterruptedException {
    if (!connection().isSecureConnection() && !allowSensitiveOperationOverInsecureConnection) {
        throw new IllegalStateException("Creating account over insecure connection");
    }
    if (username == null) {
        throw new IllegalArgumentException("Username must not be null");
    }
    if (StringUtils.isNullOrEmpty(password)) {
        throw new IllegalArgumentException("Password must not be null");
    }

    attributes.put("username", username.toString());
    attributes.put("password", password);
    Registration reg = new Registration(attributes);
    reg.setType(IQ.Type.set);
    reg.setTo(connection().getXMPPServiceDomain());
    createStanzaCollectorAndSend(reg).nextResultOrThrow();
}
 
Example 9
Source Project: Smack   Source File: XmlEnvironment.java    License: Apache License 2.0 5 votes vote down vote up
public String getEffectiveLanguage() {
    if (effectiveLanguageDetermined) {
        return effectiveLanguage;
    }

    if (StringUtils.isNotEmpty(language)) {
        effectiveLanguage = language;
    } else if (next != null) {
        effectiveLanguage = next.getEffectiveLanguage();
    }

    effectiveLanguageDetermined = true;
    return effectiveLanguage;
}
 
Example 10
Source Project: Smack   Source File: WorkgroupProperties.java    License: Apache License 2.0 5 votes vote down vote up
@Override
protected IQChildElementXmlStringBuilder getIQChildElementBuilder(IQChildElementXmlStringBuilder buf) {
    if (StringUtils.isNotEmpty(getJid())) {
        buf.append("jid=\"" + getJid() + "\" ");
    }
    buf.setEmptyElement();
    return buf;
}
 
Example 11
Source Project: Spark   Source File: ChatRoomImpl.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void sendMessage(String text) {
       final Message message = new Message();

       if (threadID == null) {
           threadID = StringUtils.randomString(6);
       }
       message.setThread(threadID);

       if ( privateChat )
       {
           // XEP-0045: 7.5 Sending a Private Message
           message.addExtension( new MUCUser() );
       }

       // Set the body of the message using typedMessage and remove control
       // characters
       text = text.replaceAll("[\\u0001-\\u0008\\u000B-\\u001F]", "");
       message.setBody(text);
       
       // IF there is no body, just return and do nothing
       if (!ModelUtil.hasLength(text)) {
           return;
       }

       // Fire Message Filters
       SparkManager.getChatManager().filterOutgoingMessage(this, message);

       // Fire Global Filters
       SparkManager.getChatManager().fireGlobalMessageSentListeners(this, message);

       sendMessage(message);          	    	
   }
 
Example 12
@Override
public boolean isTrustedOmemoIdentity(OmemoManager omemoManager, OmemoDevice device, OmemoFingerprint fingerprint) {
    File trustPath = hierarchy.getContactsTrustPath(omemoManager, device);
    try {
        String depositedFingerprint = new String(readBytes(trustPath), StringUtils.UTF8);

        return  depositedFingerprint.length() > 2
                && depositedFingerprint.charAt(0) == '1'
                && new OmemoFingerprint(depositedFingerprint.substring(2)).equals(fingerprint);
    } catch (IOException e) {
        return false;
    }
}
 
Example 13
@Override
public boolean isDecidedOmemoIdentity(OmemoManager omemoManager, OmemoDevice device, OmemoFingerprint fingerprint) {
    File trustPath = hierarchy.getContactsTrustPath(omemoManager, device);
    try {
        String depositedFingerprint = new String(readBytes(trustPath), StringUtils.UTF8);

        return  depositedFingerprint.length() > 2
                && (depositedFingerprint.charAt(0) == '1' || depositedFingerprint.charAt(0) == '2')
                && new OmemoFingerprint(depositedFingerprint.substring(2)).equals(fingerprint);
    } catch (IOException e) {
        return false;
    }
}
 
Example 14
@Override
public void trustOmemoIdentity(OmemoManager omemoManager, OmemoDevice device, OmemoFingerprint fingerprint) {
    File trustPath = hierarchy.getContactsTrustPath(omemoManager, device);
    try {
        writeBytes(trustPath, ("1 " + fingerprint.toString()).getBytes(StringUtils.UTF8));
    } catch (IOException e) {
        LOGGER.log(Level.SEVERE, "Could not trust " + device + ": " + e, e);
    }
}
 
Example 15
Source Project: Smack   Source File: InBandBytestreamManager.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Returns a new unique session ID.
 *
 * @return a new unique session ID
 */
private static String getNextSessionID() {
    StringBuilder buffer = new StringBuilder();
    buffer.append(SESSION_ID_PREFIX);
    buffer.append(StringUtils.secureOnlineAttackSafeRandomString());
    return buffer.toString();
}
 
Example 16
@SmackIntegrationTest
public void testMucBookmarksAutojoin(AbstractXMPPConnection connection) throws InterruptedException,
                TestNotPossibleException, XMPPException, SmackException, IOException {
    final BookmarkManager bookmarkManager = BookmarkManager.getBookmarkManager(connection);
    if (!bookmarkManager.isSupported()) {
        throw new TestNotPossibleException("Private data storage not supported");
    }
    final MultiUserChatManager multiUserChatManager = MultiUserChatManager.getInstanceFor(connection);
    final Resourcepart mucNickname = Resourcepart.from("Nick-" + StringUtils.randomString(6));
    final String randomMucName = StringUtils.randomString(6);
    final DomainBareJid mucComponent = multiUserChatManager.getMucServiceDomains().get(0);
    final MultiUserChat muc = multiUserChatManager.getMultiUserChat(JidCreate.entityBareFrom(
                    Localpart.from(randomMucName), mucComponent));

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

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

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

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

   assertTrue(muc.isJoined());

   // If the test went well, leave the MUC
   muc.leave();
}
 
Example 17
Source Project: Smack   Source File: Base64.java    License: Apache License 2.0 5 votes vote down vote up
public static final byte[] decode(String string) {
    // xs:base64Binary may include XML whitespace which we need to delete before feeding the string into the Base64
    // decoder. See also XML Schema Part 2: Datatypes Second Edition § 3.2.16.
    string = StringUtils.deleteXmlWhitespace(string);
    try {
        return base64encoder.decode(string);
    } catch (IllegalArgumentException e) {
        return null;
    }
}
 
Example 18
Source Project: Smack   Source File: Version.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Creates a new Version object with given details.
 *
 * @param name The natural-language name of the software. This element is REQUIRED.
 * @param version The specific version of the software. This element is REQUIRED.
 * @param os The operating system of the queried entity. This element is OPTIONAL.
 */
public Version(String name, String version, String os) {
    super(ELEMENT, NAMESPACE);
    this.setType(IQ.Type.result);
    this.name = StringUtils.requireNotNullNorEmpty(name, "name must not be null");
    this.version = StringUtils.requireNotNullNorEmpty(version, "version must not be null");
    this.os = os;
}
 
Example 19
Source Project: AndroidPNClient   Source File: IQ.java    License: Apache License 2.0 5 votes vote down vote up
public String toXML() {
    StringBuilder buf = new StringBuilder();
    buf.append("<iq ");
    if (getPacketID() != null) {
        buf.append("id=\"" + getPacketID() + "\" ");
    }
    if (getTo() != null) {
        buf.append("to=\"").append(StringUtils.escapeForXML(getTo())).append("\" ");
    }
    if (getFrom() != null) {
        buf.append("from=\"").append(StringUtils.escapeForXML(getFrom())).append("\" ");
    }
    if (type == null) {
        buf.append("type=\"get\">");
    }
    else {
        buf.append("type=\"").append(getType()).append("\">");
    }
    // Add the query section if there is one.
    String queryXML = getChildElementXML();
    if (queryXML != null) {
        buf.append(queryXML);
    }
    // Add the error sub-packet, if there is one.
    XMPPError error = getError();
    if (error != null) {
        buf.append(error.toXML());
    }
    buf.append("</iq>");
    return buf.toString();
}
 
Example 20
Source Project: AndroidPNClient   Source File: Authentication.java    License: Apache License 2.0 5 votes vote down vote up
public String getChildElementXML() {
    StringBuilder buf = new StringBuilder();
    buf.append("<query xmlns=\"jabber:iq:auth\">");
    if (username != null) {
        if (username.equals("")) {
            buf.append("<username/>");
        }
        else {
            buf.append("<username>").append(username).append("</username>");
        }
    }
    if (digest != null) {
        if (digest.equals("")) {
            buf.append("<digest/>");
        }
        else {
            buf.append("<digest>").append(digest).append("</digest>");
        }
    }
    if (password != null && digest == null) {
        if (password.equals("")) {
            buf.append("<password/>");
        }
        else {
            buf.append("<password>").append(StringUtils.escapeForXML(password)).append("</password>");
        }
    }
    if (resource != null) {
        if (resource.equals("")) {
            buf.append("<resource/>");
        }
        else {
            buf.append("<resource>").append(resource).append("</resource>");
        }
    }
    buf.append("</query>");
    return buf.toString();
}
 
Example 21
Source Project: Smack   Source File: PrivacyListManager.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Answer the active privacy list. Returns <code>null</code> if there is no active list.
 *
 * @return the privacy list of the active list.
 * @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 PrivacyList getActiveList() throws NoResponseException, XMPPErrorException, NotConnectedException, InterruptedException  {
    Privacy privacyAnswer = this.getPrivacyWithListNames();
    String listName = privacyAnswer.getActiveName();
    if (StringUtils.isNullOrEmpty(listName)) {
        return null;
    }
    boolean isDefaultAndActive = listName != null && listName.equals(privacyAnswer.getDefaultName());
    return new PrivacyList(true, isDefaultAndActive, listName, getPrivacyListItems(listName));
}
 
Example 22
Source Project: weixin   Source File: XmppConnection.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 查询会议室成员名字
 * 
 * @param muc
 */
public List<String> findMulitUser(MultiUserChat muc) {
	if (getConnection() == null)
		return null;
	List<String> listUser = new ArrayList<String>();
	Iterator<String> it = muc.getOccupants();
	// 遍历出聊天室人员名称
	while (it.hasNext()) {
		// 聊天室成员名字
		String name = StringUtils.parseResource(it.next());
		listUser.add(name);
	}
	return listUser;
}
 
Example 23
Source Project: Spark   Source File: SparkTransferManager.java    License: Apache License 2.0 5 votes vote down vote up
/**
  * Send an image to a user.
  *
  * @param image the image to send.
  * @param room  the ChatRoom of the user you wish to send the image to.
  */
 public void sendImage(final BufferedImage image, final ChatRoom room) {
     File tmpDirectory = new File(Spark.getSparkUserHome(), "/tempImages");
     tmpDirectory.mkdirs();

     String imageName = "image_" + StringUtils.randomString(2) + ".png";
     final File imageFile = new File(tmpDirectory, imageName);

     // Write image to system.
     room.setCursor(new Cursor(Cursor.WAIT_CURSOR));

     SwingWorker writeImageThread = new SwingWorker() {
         @Override
public Object construct() {
             try {
                 // Write out file in separate thread.
                 ImageIO.write(image, "png", imageFile);
             }
             catch (IOException e) {
                 Log.error(e);
             }
             return true;
         }

         @Override
public void finished() {
             ChatRoomImpl roomImpl = (ChatRoomImpl)room;
             sendFile(imageFile, roomImpl.getParticipantJID());
             SparkManager.getChatManager().getChatContainer().activateChatRoom(room);
             room.setCursor(new Cursor(Cursor.DEFAULT_CURSOR));
         }
     };
     writeImageThread.start();
 }
 
Example 24
Source Project: weixin   Source File: XmppManager.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 修改用户头像
 * 
 * @param f
 * @throws XMPPException
 * @throws IOException
 */
public void changeUserImage(File f) throws XMPPException, IOException {
	VCard vCard = new VCard();
	vCard.load(getConnection());
	byte[] bytes = getFileBytes(f);

	String encodeImage = StringUtils.encodeBase64(bytes);
	vCard.setAvatar(bytes, encodeImage);
	vCard.setEncodedImage(encodeImage);
	vCard.setField("PHOTO", "<TYPE>image/jpg</TYPE><BINVAL>" + encodeImage + "</BINVAL>", true);

	ByteArrayInputStream bais = new ByteArrayInputStream(vCard.getAvatar());
	FormatTools.getInstance().InputStream2Bitmap(bais);
	vCard.save(getConnection());
}
 
Example 25
Source Project: weixin   Source File: XmppManager.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 查询会议室成员名字
 * 
 * @param muc
 */
public List<String> findMulitUser(MultiUserChat muc) {
	List<String> listUser = new ArrayList<String>();
	Iterator<String> it = muc.getOccupants();
	//遍历出聊天室人员名称  
	while (it.hasNext()) {
		// 聊天室成员名字  
		String name = StringUtils.parseResource(it.next());
		listUser.add(name);
	}
	return listUser;
}
 
Example 26
Source Project: Smack   Source File: Configuration.java    License: Apache License 2.0 5 votes vote down vote up
public Builder setUsernamesAndPassword(String accountOneUsername, String accountOnePassword,
                String accountTwoUsername, String accountTwoPassword, String accountThreeUsername, String accountThreePassword) {
    this.accountOneUsername = StringUtils.requireNotNullNorEmpty(accountOneUsername, "accountOneUsername must not be null nor empty");
    this.accountOnePassword = StringUtils.requireNotNullNorEmpty(accountOnePassword, "accountOnePassword must not be null nor empty");
    this.accountTwoUsername = StringUtils.requireNotNullNorEmpty(accountTwoUsername, "accountTwoUsername must not be null nor empty");
    this.accountTwoPassword = StringUtils.requireNotNullNorEmpty(accountTwoPassword, "accountTwoPasswordmust not be null nor empty");
    this.accountThreeUsername = StringUtils.requireNotNullNorEmpty(accountThreeUsername, "accountThreeUsername must not be null nor empty");
    this.accountThreePassword = StringUtils.requireNotNullNorEmpty(accountThreePassword, "accountThreePassword must not be null nor empty");
    return this;
}
 
Example 27
Source Project: weixin   Source File: TaxiChatManagerListener.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void chatCreated(Chat chat, boolean arg1) {
	chat.addMessageListener(new MessageListener() {

		@Override
		public void processMessage(Chat arg0, Message msg) {//登录用户
			StringUtils.parseName(XmppManager.getInstance().getConnection().getUser());
			//发送消息用户
			msg.getFrom();
			//消息内容
			String body = msg.getBody();
			System.out.println("body--->" + body);
			boolean left = body.substring(0, 1).equals("{");
			boolean right = body.substring(body.length() - 1, body.length()).equals("}");
			if (left && right) {
				try {
					JSONObject obj = new JSONObject(body);
					String type = obj.getString("messageType");
					String chanId = obj.getString("chanId");
					String chanName = obj.getString("chanName");

					System.out.println("---body--->" + body);
				} catch (JSONException e) {
					e.printStackTrace();
				}
			}
			
			
			Intent intent = new Intent("net.cgt.weixin.chat");
			intent.setFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES);// 包含从未启动过的应用
			intent.putExtra("from", msg.getFrom());
			intent.putExtra("body", body);
			GlobalParams.activity.sendBroadcast(intent);
		}
	});
}
 
Example 28
Source Project: League-of-Legends-XMPP-Chat-Library   Source File: RiotApi.java    License: MIT License 5 votes vote down vote up
public String getName(String userId) throws IOException {
	final String summonerId = StringUtils.parseName(userId).replace("sum",
			"");
	final String response = request("https://" + server.api + "/api/lol/"
			+ server.getApiRegion() + "/v1.4/summoner/" + summonerId + "/name?api_key="
			+ riotApiKey.getKey());
	final Map<String, String> summoner = new GsonBuilder().create()
			.fromJson(response, new TypeToken<Map<String, String>>() {
			}.getType());
	return summoner.get(summonerId);
}
 
Example 29
Source Project: Smack   Source File: XmlEnvironment.java    License: Apache License 2.0 5 votes vote down vote up
public String getEffectiveNamespaceOrUse(String namespace) {
    String effectiveNamespace = getEffectiveLanguage();
    if (StringUtils.isNullOrEmpty(effectiveNamespace)) {
        return namespace;
    }
    return effectiveNamespace;
}
 
Example 30
Source Project: Smack   Source File: OnceForThisStanza.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public boolean accept(Stanza packet) {
    String otherId = packet.getStanzaId();
    if (StringUtils.isNullOrEmpty(otherId)) {
        return false;
    }
    if (id.equals(otherId)) {
        connection.removeRequestAckPredicate(this);
        return true;
    }
    return false;
}