Java Code Examples for org.jivesoftware.smack.util.StringUtils#isNullOrEmpty()

The following examples show how to use org.jivesoftware.smack.util.StringUtils#isNullOrEmpty() . 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: ServiceDiscoveryManager.java    From Smack with Apache License 2.0 6 votes vote down vote up
public DomainBareJid findService(String feature, boolean useCache, String category, String type)
                throws NoResponseException, XMPPErrorException, NotConnectedException,
                InterruptedException {
    boolean noCategory = StringUtils.isNullOrEmpty(category);
    boolean noType = StringUtils.isNullOrEmpty(type);
    if (noType != noCategory) {
        throw new IllegalArgumentException("Must specify either both, category and type, or none");
    }

    List<DiscoverInfo> services = findServicesDiscoverInfo(feature, false, useCache);
    if (services.isEmpty()) {
        return null;
    }

    if (!noCategory && !noType) {
        for (DiscoverInfo info : services) {
            if (info.hasIdentity(category, type)) {
                return info.getFrom().asDomainBareJid();
            }
        }
    }

    return services.get(0).getFrom().asDomainBareJid();
}
 
Example 2
Source File: Presence.java    From Smack with Apache License 2.0 6 votes vote down vote up
@Override
public String toString() {
    StringBuilder sb = new StringBuilder();
    sb.append("Presence Stanza [");
    logCommonAttributes(sb);
    sb.append("type=").append(type).append(',');
    if (mode != null) {
        sb.append("mode=").append(mode).append(',');
    }
    if (!StringUtils.isNullOrEmpty(status)) {
        sb.append("status=").append(status).append(',');
    }
    if (priority != null) {
        sb.append("prio=").append(priority).append(',');
    }
    sb.append(']');
    return sb.toString();
}
 
Example 3
Source File: StreamError.java    From Smack with Apache License 2.0 6 votes vote down vote up
public StreamError(Condition condition, String conditionText, Map<String, String> descriptiveTexts, List<ExtensionElement> extensions) {
    super(descriptiveTexts, extensions);
    // Some implementations may send the condition as non-empty element containing the empty string, that is
    // <condition xmlns='foo'></condition>, in this case the parser may calls this constructor with the empty string
    // as conditionText, therefore reset it to null if it's the empty string
    if (StringUtils.isNullOrEmpty(conditionText)) {
        conditionText = null;
    }
    if (conditionText != null) {
        switch (condition) {
        case see_other_host:
            break;
        default:
            throw new IllegalArgumentException("The given condition '" + condition
                            + "' can not contain a conditionText");
        }
    }
    this.condition = condition;
    this.conditionText = conditionText;
}
 
Example 4
Source File: AccountManager.java    From Smack with 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 5
Source File: OnceForThisStanza.java    From Smack with 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;
}
 
Example 6
Source File: DeliveryReceiptManager.java    From Smack with Apache License 2.0 5 votes vote down vote up
/**
 * Create and return a new message including a delivery receipt extension for the given message.
 * <p>
 * If {@code messageWithReceiptRequest} does not have a Stanza ID set, then {@code null} will be returned.
 * </p>
 *
 * @param messageWithReceiptRequest the given message with a receipt request extension.
 * @return a new message with a receipt or <code>null</code>.
 * @since 4.1
 */
public static Message receiptMessageFor(Message messageWithReceiptRequest) {
    String stanzaId = messageWithReceiptRequest.getStanzaId();
    if (StringUtils.isNullOrEmpty(stanzaId)) {
        return null;
    }
    Message message = StanzaBuilder.buildMessage()
            .ofType(messageWithReceiptRequest.getType())
            .to(messageWithReceiptRequest.getFrom())
            .addExtension(new DeliveryReceipt(stanzaId))
            .build();
    return message;
}
 
Example 7
Source File: MultipleRecipientManager.java    From Smack with Apache License 2.0 5 votes vote down vote up
/**
 * Sends the specified stanza to the collection of specified recipients using the specified
 * connection. If the server has support for XEP-33 then only one stanza is going to be sent to
 * the server with the multiple recipient instructions. However, if XEP-33 is not supported by
 * the server then the client is going to send the stanza to each recipient.
 *
 * @param connection the connection to use to send the packet.
 * @param packet the stanza to send to the list of recipients.
 * @param to the collection of JIDs to include in the TO list or <code>null</code> if no TO list exists.
 * @param cc the collection of JIDs to include in the CC list or <code>null</code> if no CC list exists.
 * @param bcc the collection of JIDs to include in the BCC list or <code>null</code> if no BCC list
 *        exists.
 * @param replyTo address to which all replies are requested to be sent or <code>null</code>
 *        indicating that they can reply to any address.
 * @param replyRoom JID of a MUC room to which responses should be sent or <code>null</code>
 *        indicating that they can reply to any address.
 * @param noReply true means that receivers should not reply to the message.
 * @throws XMPPErrorException if server does not support XEP-33: Extended Stanza Addressing and
 *         some XEP-33 specific features were requested.
 * @throws NoResponseException if there was no response from the server.
 * @throws FeatureNotSupportedException if special XEP-33 features where requested, but the
 *         server does not support them.
 * @throws NotConnectedException if the XMPP connection is not connected.
 * @throws InterruptedException if the calling thread was interrupted.
 */
public static void send(XMPPConnection connection, Stanza packet, Collection<? extends Jid> to, Collection<? extends Jid> cc, Collection<? extends Jid> bcc,
        Jid replyTo, Jid replyRoom, boolean noReply) throws NoResponseException, XMPPErrorException, FeatureNotSupportedException, NotConnectedException, InterruptedException {
    // Check if *only* 'to' is set and contains just *one* entry, in this case extended stanzas addressing is not
    // required at all and we can send it just as normal stanza without needing to add the extension element
    if (to != null && to.size() == 1 && (cc == null || cc.isEmpty()) && (bcc == null || bcc.isEmpty()) && !noReply
                    && StringUtils.isNullOrEmpty(replyTo) && StringUtils.isNullOrEmpty(replyRoom)) {
        Jid toJid = to.iterator().next();
        packet.setTo(toJid);
        connection.sendStanza(packet);
        return;
    }
    DomainBareJid serviceAddress = getMultipleRecipientServiceAddress(connection);
    if (serviceAddress != null) {
        // Send packet to target users using multiple recipient service provided by the server
        sendThroughService(connection, packet, to, cc, bcc, replyTo, replyRoom, noReply,
                serviceAddress);
    }
    else {
        // Server does not support XEP-33 so try to send the packet to each recipient
        if (noReply || replyTo != null ||
                replyRoom != null) {
            // Some specified XEP-33 features were requested so throw an exception alerting
            // the user that this features are not available
            throw new FeatureNotSupportedException("Extended Stanza Addressing");
        }
        // Send the packet to each individual recipient
        sendToIndividualRecipients(connection, packet, to, cc, bcc);
    }
}
 
Example 8
Source File: FormField.java    From Smack with Apache License 2.0 5 votes vote down vote up
protected Builder(String fieldName, Type type) {
    if (StringUtils.isNullOrEmpty(fieldName) && type != Type.fixed) {
        throw new IllegalArgumentException("Fields of type " + type + " must have a field name set");
    }
    this.fieldName = fieldName;
    this.type = type;
}
 
Example 9
Source File: FilledForm.java    From Smack with Apache License 2.0 5 votes vote down vote up
public FilledForm(DataForm dataForm) {
    this.dataForm = Objects.requireNonNull(dataForm);
    String formType = dataForm.getFormType();
    if (StringUtils.isNullOrEmpty(formType)) {
        throw new IllegalArgumentException("The provided data form has no hidden FROM_TYPE field.");
    }
    if (dataForm.getType() == Type.cancel) {
        throw new IllegalArgumentException("Forms of type 'cancel' are not filled nor fillable");
    }
    formTypeFormField = dataForm.getHiddenFormTypeField();
}
 
Example 10
Source File: JingleReason.java    From Smack with Apache License 2.0 5 votes vote down vote up
public AlternativeSession(String sessionId) {
    super(Reason.alternative_session);
    if (StringUtils.isNullOrEmpty(sessionId)) {
        throw new NullPointerException("SessionID must not be null or empty.");
    }
    this.sessionId = sessionId;
}
 
Example 11
Source File: PrivacyListManager.java    From Smack with Apache License 2.0 5 votes vote down vote up
/**
 * Answer the default privacy list. Returns <code>null</code> if there is no default list.
 *
 * @return the privacy list of the default 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 getDefaultList() throws NoResponseException, XMPPErrorException, NotConnectedException, InterruptedException {
    Privacy privacyAnswer = this.getPrivacyWithListNames();
    String listName = privacyAnswer.getDefaultName();
    if (StringUtils.isNullOrEmpty(listName)) {
        return null;
    }
    boolean isDefaultAndActive = listName.equals(privacyAnswer.getActiveName());
    return new PrivacyList(isDefaultAndActive, true, listName, getPrivacyListItems(listName));
}
 
Example 12
Source File: PrivacyListManager.java    From Smack with 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 13
Source File: StanzaError.java    From Smack with Apache License 2.0 5 votes vote down vote up
/**
 * Creates a new error with the specified type, condition and message.
 * This constructor is used when the condition is not recognized automatically by XMPPError
 * i.e. there is not a defined instance of ErrorCondition or it does not apply the default
 * specification.
 *
 * @param type the error type.
 * @param condition the error condition.
 * @param conditionText TODO javadoc me please
 * @param errorGenerator TODO javadoc me please
 * @param descriptiveTexts TODO javadoc me please
 * @param extensions list of stanza extensions
 */
public StanzaError(Condition condition, String conditionText, String errorGenerator, Type type, Map<String, String> descriptiveTexts,
        List<ExtensionElement> extensions) {
    super(descriptiveTexts, ERROR_CONDITION_AND_TEXT_NAMESPACE, extensions);
    this.condition = Objects.requireNonNull(condition, "condition must not be null");
    // Some implementations may send the condition as non-empty element containing the empty string, that is
    // <condition xmlns='foo'></condition>, in this case the parser may calls this constructor with the empty string
    // as conditionText, therefore reset it to null if it's the empty string
    if (StringUtils.isNullOrEmpty(conditionText)) {
        conditionText = null;
    }
    if (conditionText != null) {
        switch (condition) {
        case gone:
        case redirect:
            break;
        default:
            throw new IllegalArgumentException(
                            "Condition text can only be set with condtion types 'gone' and 'redirect', not "
                                            + condition);
        }
    }
    this.conditionText = conditionText;
    this.errorGenerator = errorGenerator;
    if (type == null) {
        Type determinedType = CONDITION_TO_TYPE.get(condition);
        if (determinedType == null) {
            LOGGER.warning("Could not determine type for condition: " + condition);
            determinedType = Type.CANCEL;
        }
        this.type = determinedType;
    } else {
        this.type = type;
    }
}
 
Example 14
Source File: XmlEnvironment.java    From Smack with 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 15
Source File: ProviderManager.java    From Smack with Apache License 2.0 5 votes vote down vote up
private static void validate(String elementName, String namespace) {
    if (StringUtils.isNullOrEmpty(elementName)) {
        throw new IllegalArgumentException("elementName must not be null or empty");
    }
    if (StringUtils.isNullOrEmpty(namespace)) {
        throw new IllegalArgumentException("namespace must not be null or empty");
    }
}
 
Example 16
Source File: SASLExternalMechanism.java    From Smack with Apache License 2.0 5 votes vote down vote up
@Override
protected byte[] getAuthenticationText() {
    if (authorizationId != null) {
      return toBytes(authorizationId.toString());
    }

    if (StringUtils.isNullOrEmpty(authenticationId)) {
        return null;
    }

    return toBytes(XmppStringUtils.completeJidFrom(authenticationId, serviceName));
}
 
Example 17
Source File: VCardProvider.java    From Smack with Apache License 2.0 4 votes vote down vote up
private static void parseTel(XmlPullParser parser, VCard vCard) throws XmlPullParserException, IOException {
    final int initialDepth = parser.getDepth();
    boolean isWork = true;
    String telLabel = null;

    outerloop: while (true) {
        XmlPullParser.Event eventType = parser.next();
        switch (eventType) {
        case START_ELEMENT:
            String name = parser.getName();
            if ("HOME".equals(name)) {
                isWork = false;
            }
            else {
                if ("NUMBER".equals(name)) {
                    if (StringUtils.isNullOrEmpty(telLabel)) {
                        // RFC 2426 ยง 3.3.1:
                        // "The default type is 'voice'"
                        telLabel = "VOICE";
                    }
                    if (isWork) {
                        vCard.setPhoneWork(telLabel, parser.nextText());
                    }
                    else {
                        vCard.setPhoneHome(telLabel, parser.nextText());
                    }
                }
                else {
                    for (String tel : TEL) {
                        if (tel.equals(name)) {
                            telLabel = name;
                        }
                    }
                }
            }
            break;
        case END_ELEMENT:
            if (parser.getDepth() == initialDepth) {
                break outerloop;
            }
            break;
        default:
            break;
        }
    }
}
 
Example 18
Source File: RosterPacket.java    From Smack with Apache License 2.0 4 votes vote down vote up
public static ItemType fromString(String string) {
    if (StringUtils.isNullOrEmpty(string)) {
        return none;
    }
    return ItemType.valueOf(string.toLowerCase(Locale.US));
}
 
Example 19
Source File: StableAndUniqueIdElement.java    From Smack with Apache License 2.0 4 votes vote down vote up
public StableAndUniqueIdElement(String id) {
    if (StringUtils.isNullOrEmpty(id)) {
        throw new IllegalArgumentException("Argument 'id' cannot be null or empty.");
    }
    this.id = id;
}
 
Example 20
Source File: XmppConnectionManager.java    From Smack with Apache License 2.0 4 votes vote down vote up
private AbstractXMPPConnection getConnectedMainConnectionFor(AccountNum accountNum) throws SmackException, IOException, XMPPException,
        InterruptedException, KeyManagementException, NoSuchAlgorithmException, InstantiationException,
        IllegalAccessException, IllegalArgumentException, InvocationTargetException {
    String middlefix;
    String accountUsername;
    String accountPassword;
    switch (accountNum) {
    case One:
        accountUsername = sinttestConfiguration.accountOneUsername;
        accountPassword = sinttestConfiguration.accountOnePassword;
        middlefix = "one";
        break;
    case Two:
        accountUsername = sinttestConfiguration.accountTwoUsername;
        accountPassword = sinttestConfiguration.accountTwoPassword;
        middlefix = "two";
        break;
    case Three:
        accountUsername = sinttestConfiguration.accountThreeUsername;
        accountPassword = sinttestConfiguration.accountThreePassword;
        middlefix = "three";
        break;
    default:
        throw new IllegalStateException();
    }

    // Note that it is perfectly fine for account(Username|Password) to be 'null' at this point.
    final String finalAccountUsername = StringUtils.isNullOrEmpty(accountUsername) ? USERNAME_PREFIX + '-' + middlefix + '-' + testRunId : accountUsername;
    final String finalAccountPassword = StringUtils.isNullOrEmpty(accountPassword) ? StringUtils.insecureRandomString(16) : accountPassword;

    if (sinttestConfiguration.isAccountRegistrationPossible()) {
        registerAccount(finalAccountUsername, finalAccountPassword);
    }

    AbstractXMPPConnection mainConnection = defaultConnectionDescriptor.construct(sinttestConfiguration, builder -> {
        try {
            builder.setUsernameAndPassword(finalAccountUsername, finalAccountPassword)
                .setResource(middlefix + '-' + testRunId);
        } catch (XmppStringprepException e) {
            throw new IllegalArgumentException(e);
        }
    });

    connections.add(mainConnection);

    mainConnection.connect();
    mainConnection.login();

    return mainConnection;
}