Java Code Examples for org.jivesoftware.smack.util.stringencoder.Base64

The following examples show how to use org.jivesoftware.smack.util.stringencoder.Base64. 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: mangosta-android   Source File: XMPPSession.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * This method is not necessary on this app, is only to show how BoB could be used
 */
private void sendResponse(BoBIQ bobIQ) {
    BoBHash bobHash = bobIQ.getBoBHash();

    Resources resources = MangostaApplication.getInstance().getResources();
    final int resourceId = resources.getIdentifier("sticker_" + Base64.decodeToString(bobHash.getHash()), "drawable",
            MangostaApplication.getInstance().getPackageName());
    Drawable drawable = resources.getDrawable(resourceId);

    Bitmap bitmap = ((BitmapDrawable) drawable).getBitmap();
    ByteArrayOutputStream stream = new ByteArrayOutputStream();
    bitmap.compress(Bitmap.CompressFormat.WEBP, 100, stream);
    byte[] bitMapData = stream.toByteArray();

    try {
        BoBData bobData = new BoBData(0, "image/png", bitMapData);
        getBoBManager().responseBoB(bobIQ, bobData);
    } catch (InterruptedException | SmackException.NotConnectedException | SmackException.NotLoggedInException e) {
        e.printStackTrace();
    }
}
 
Example 2
Source Project: mangosta-android   Source File: XMPPSession.java    License: Apache License 2.0 6 votes vote down vote up
private void manageMessageAlreadyExists(Message message, Date delayDate, String messageId) {
    Realm realm = RealmManager.getInstance().getRealm();
    realm.beginTransaction();

    ChatMessage chatMessage = realm.where(ChatMessage.class).equalTo("messageId", messageId).findFirst();
    chatMessage.setStatus(ChatMessage.STATUS_SENT);

    if (isBoBMessage(message)) {
        BoBExtension bobExtension = BoBExtension.from(message);
        chatMessage.setContent(Base64.decodeToString(bobExtension.getBoBHash().getHash()));
    } else {
        chatMessage.setContent(message.getBody());
    }

    if (delayDate != null) {
        chatMessage.setDate(delayDate);
    }

    realm.copyToRealmOrUpdate(chatMessage);
    realm.commitTransaction();
    realm.close();
}
 
Example 3
Source Project: Smack   Source File: PainlessOpenPgpProvider.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public OpenPgpElementAndMetadata sign(SignElement element, OpenPgpSelf self)
        throws IOException, PGPException {
    InputStream plainText = element.toInputStream();
    ByteArrayOutputStream cipherText = new ByteArrayOutputStream();

    EncryptionStream cipherStream = PGPainless.createEncryptor().onOutputStream(cipherText)
            .doNotEncrypt()
            .signWith(getStore().getKeyRingProtector(), self.getSigningKeyRing())
            .noArmor();

    Streams.pipeAll(plainText, cipherStream);
    plainText.close();
    cipherStream.flush();
    cipherStream.close();
    cipherText.close();

    String base64 = Base64.encodeToString(cipherText.toByteArray());
    OpenPgpElement openPgpElement = new OpenPgpElement(base64);

    return new OpenPgpElementAndMetadata(openPgpElement, cipherStream.getResult());
}
 
Example 4
Source Project: Smack   Source File: SASLMechanism.java    License: Apache License 2.0 6 votes vote down vote up
private void authenticate() throws SmackSaslException, NotConnectedException, InterruptedException {
    byte[] authenticationBytes = getAuthenticationText();
    String authenticationText;
    // Some SASL mechanisms do return an empty array (e.g. EXTERNAL from javax), so check that
    // the array is not-empty. Mechanisms are allowed to return either 'null' or an empty array
    // if there is no authentication text.
    if (authenticationBytes != null && authenticationBytes.length > 0) {
        authenticationText = Base64.encodeToString(authenticationBytes);
    } else {
        // RFC6120 6.4.2 "If the initiating entity needs to send a zero-length initial response,
        // it MUST transmit the response as a single equals sign character ("="), which
        // indicates that the response is present but contains no data."
        authenticationText = "=";
    }
    // Send the authentication to the server
    connection.sendNonza(new AuthMechanism(getName(), authenticationText));
}
 
Example 5
Source Project: Smack   Source File: SASLMechanism.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * The server is challenging the SASL mechanism for the stanza he just sent. Send a
 * response to the server's challenge.
 *
 * @param challengeString a base64 encoded string representing the challenge.
 * @param finalChallenge true if this is the last challenge send by the server within the success stanza
 * @throws SmackSaslException if a SASL related error occurs.
 * @throws InterruptedException if the connection is interrupted
 * @throws NotConnectedException if the XMPP connection is not connected.
 */
public final void challengeReceived(String challengeString, boolean finalChallenge) throws SmackSaslException, InterruptedException, NotConnectedException {
    byte[] challenge = Base64.decode((challengeString != null && challengeString.equals("=")) ? "" : challengeString);
    byte[] response = evaluateChallenge(challenge);
    if (finalChallenge) {
        return;
    }

    Response responseStanza;
    if (response == null) {
        responseStanza = new Response();
    }
    else {
        responseStanza = new Response(Base64.encodeToString(response));
    }

    // Send the authentication to the server
    connection.sendNonza(responseStanza);
}
 
Example 6
Source Project: Smack   Source File: SCRAMSHA1MechanismTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testScramSha1Mechanism() throws NotConnectedException, SmackException, InterruptedException {
    final DummyConnection con = new DummyConnection();
    SCRAMSHA1Mechanism mech = new SCRAMSHA1Mechanism() {
        @Override
        public String getRandomAscii() {
            this.connection = con;
            return "fyko+d2lbbFgONRv9qkxdawL";
        }
    };

    mech.authenticate(USERNAME, "unusedFoo", JidTestUtil.DOMAIN_BARE_JID_1, PASSWORD, null, null);
    AuthMechanism authMechanism = con.getSentPacket();
    assertEquals(SCRAMSHA1Mechanism.NAME, authMechanism.getMechanism());
    assertEquals(CLIENT_FIRST_MESSAGE, saslLayerString(authMechanism.getAuthenticationText()));

    mech.challengeReceived(Base64.encode(SERVER_FIRST_MESSAGE), false);
    Response response = con.getSentPacket();
    assertEquals(CLIENT_FINAL_MESSAGE, saslLayerString(response.getAuthenticationText()));

    mech.challengeReceived(Base64.encode(SERVER_FINAL_MESSAGE), true);
    mech.checkIfSuccessfulOrThrow();
}
 
Example 7
Source Project: Smack   Source File: DataPacketExtension.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Returns the decoded data or null if data could not be decoded.
 * <p>
 * The encoded data is invalid if it contains bad Base64 input characters or
 * if it contains the pad ('=') character on a position other than the last
 * character(s) of the data. See <a
 * href="http://xmpp.org/extensions/xep-0047.html#sec">XEP-0047</a> Section
 * 6.
 *
 * @return the decoded data
 */
public byte[] getDecodedData() {
    // return cached decoded data
    if (this.decodedData != null) {
        return this.decodedData;
    }

    // data must not contain the pad (=) other than end of data
    if (data.matches(".*={1,2}+.+")) {
        return null;
    }

    // decodeBase64 will return null if bad characters are included
    this.decodedData = Base64.decode(data);
    return this.decodedData;
}
 
Example 8
Source Project: Smack   Source File: DataTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void shouldReturnValidIQStanzaXML() throws Exception {
    String encodedData = Base64.encode("Test");

    String control = XMLBuilder.create("iq")
        .a("from", "[email protected]/orchard")
        .a("to", "[email protected]/balcony")
        .a("id", "kr91n475")
        .a("type", "set")
        .e("data")
            .a("xmlns", "http://jabber.org/protocol/ibb")
            .a("seq", "0")
            .a("sid", "i781hf64")
            .t(encodedData)
        .asString(outputProperties);

    DataPacketExtension dpe = new DataPacketExtension("i781hf64", 0, encodedData);
    Data data = new Data(dpe);
    data.setFrom(JidCreate.from("[email protected]/orchard"));
    data.setTo(JidCreate.from("[email protected]/balcony"));
    data.setStanzaId("kr91n475");

    assertXmlSimilar(control, data.toXML(StreamOpen.CLIENT_NAMESPACE).toString());
}
 
Example 9
Source Project: Smack   Source File: InBandBytestreamSessionTest.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Valid data packets should be confirmed.
 *
 * @throws Exception should not happen
 */
@Test
public void shouldConfirmReceivedDataPacket() throws Exception {
    // verify data packet confirmation is of type RESULT
    protocol.addResponse(null, Verification.requestTypeRESULT);

    InBandBytestreamSession session = new InBandBytestreamSession(connection, initBytestream,
                    initiatorJID);
    InputStream inputStream = session.getInputStream();
    StanzaListener listener = Whitebox.getInternalState(inputStream, "dataPacketListener", StanzaListener.class);

    String base64Data = Base64.encode("Data");
    DataPacketExtension dpe = new DataPacketExtension(sessionID, 0, base64Data);
    Data data = new Data(dpe);

    listener.processStanza(data);

    protocol.verifyAll();

}
 
Example 10
Source Project: Smack   Source File: OmemoKeyElement.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public XmlStringBuilder toXML(XmlEnvironment enclosingXmlEnvironment) {
    XmlStringBuilder sb = new XmlStringBuilder(this, enclosingXmlEnvironment);

    if (isPreKey()) {
        sb.attribute(ATTR_PREKEY, true);
    }

    sb.attribute(ATTR_RID, getId());
    sb.rightAngleBracket();
    sb.append(Base64.encodeToString(getData()));
    sb.closeElement(this);
    return sb;
}
 
Example 11
Source Project: Smack   Source File: OmemoHeaderElement.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public XmlStringBuilder toXML(XmlEnvironment enclosingXmlEnvironment) {
    XmlStringBuilder sb = new XmlStringBuilder(this, enclosingXmlEnvironment);
    sb.attribute(ATTR_SID, getSid()).rightAngleBracket();

    for (OmemoKeyElement k : getKeys()) {
        sb.append(k);
    }

    sb.openElement(ATTR_IV).append(Base64.encodeToString(getIv())).closeElement(ATTR_IV);

    return sb.closeElement(this);
}
 
Example 12
Source Project: Smack   Source File: OmemoElement.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public XmlStringBuilder toXML(org.jivesoftware.smack.packet.XmlEnvironment enclosingNamespace) {
    XmlStringBuilder sb = new XmlStringBuilder(this, enclosingNamespace).rightAngleBracket();

    sb.append(header);

    if (payload != null) {
        sb.openElement(ATTR_PAYLOAD).append(Base64.encodeToString(payload)).closeElement(ATTR_PAYLOAD);
    }

    sb.closeElement(this);
    return sb;
}
 
Example 13
Source Project: Smack   Source File: OmemoBundleElement.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Constructor to create a Bundle Element from decoded byte arrays.
 *
 * @param signedPreKeyId id
 * @param signedPreKey signedPreKey
 * @param signedPreKeySig signedPreKeySignature
 * @param identityKey identityKey
 * @param preKeys HashMap of preKeys
 */
public OmemoBundleElement(int signedPreKeyId, byte[] signedPreKey, byte[] signedPreKeySig, byte[] identityKey, HashMap<Integer, byte[]> preKeys) {
    this(signedPreKeyId,
            signedPreKey != null ? Base64.encodeToString(signedPreKey) : null,
            signedPreKeySig != null ? Base64.encodeToString(signedPreKeySig) : null,
            identityKey != null ? Base64.encodeToString(identityKey) : null,
            base64EncodePreKeys(preKeys));
    this.signedPreKey = signedPreKey;
    this.signedPreKeySignature = signedPreKeySig;
    this.identityKey = identityKey;
    this.preKeys = preKeys;
}
 
Example 14
Source Project: Smack   Source File: OmemoBundleElement.java    License: Apache License 2.0 5 votes vote down vote up
private static HashMap<Integer, String> base64EncodePreKeys(HashMap<Integer, byte[]> preKeys) {
    if (preKeys == null) {
        return null;
    }

    HashMap<Integer, String> converted = new HashMap<>();
    for (Integer id : preKeys.keySet()) {
        converted.put(id, Base64.encodeToString(preKeys.get(id)));
    }
    return converted;
}
 
Example 15
Source Project: Smack   Source File: OmemoBundleElement.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Return the signedPreKey of the OmemoBundleElement.
 *
 * @return signedPreKey as byte array
 */
public byte[] getSignedPreKey() {
    if (signedPreKey == null) {
        signedPreKey = Base64.decode(signedPreKeyB64);
    }
    return this.signedPreKey.clone();
}
 
Example 16
Source Project: Smack   Source File: OmemoBundleElement.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Get the signature of the signedPreKey.
 *
 * @return signature as byte array
 */
public byte[] getSignedPreKeySignature() {
    if (signedPreKeySignature == null) {
        signedPreKeySignature = Base64.decode(signedPreKeySignatureB64);
    }
    return signedPreKeySignature.clone();
}
 
Example 17
Source Project: Smack   Source File: OmemoBundleElement.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Return the HashMap of preKeys in the bundle.
 * The map uses the preKeys ids as key and the preKeys as value.
 *
 * @return preKeys Pre-Keys contained in the bundle
 */
public HashMap<Integer, byte[]> getPreKeys() {
    if (preKeys == null) {
        preKeys = new HashMap<>();
        for (int id : preKeysB64.keySet()) {
            preKeys.put(id, Base64.decode(preKeysB64.get(id)));
        }
    }
    return this.preKeys;
}
 
Example 18
Source Project: Smack   Source File: OmemoVAxolotlElementTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void serializationTest() throws Exception {
    byte[] payload = "This is payload.".getBytes(StandardCharsets.UTF_8);
    int keyId1 = 8;
    int keyId2 = 33333;
    byte[] keyData1 = "KEYDATA".getBytes(StandardCharsets.UTF_8);
    byte[] keyData2 = "DATAKEY".getBytes(StandardCharsets.UTF_8);
    int sid = 12131415;
    byte[] iv = OmemoMessageBuilder.generateIv();

    ArrayList<OmemoKeyElement> keys = new ArrayList<>();
    keys.add(new OmemoKeyElement(keyData1, keyId1));
    keys.add(new OmemoKeyElement(keyData2, keyId2, true));

    OmemoHeaderElement_VAxolotl header = new OmemoHeaderElement_VAxolotl(sid, keys, iv);
    OmemoElement_VAxolotl element = new OmemoElement_VAxolotl(header, payload);

    String expected =
            "<encrypted xmlns='eu.siacs.conversations.axolotl'>" +
                "<header sid='12131415'>" +
                    "<key rid='8'>" + Base64.encodeToString(keyData1) + "</key>" +
                    "<key prekey='true' rid='33333'>" + Base64.encodeToString(keyData2) + "</key>" +
                    "<iv>" + Base64.encodeToString(iv) + "</iv>" +
                "</header>" +
                "<payload>" +
                    Base64.encodeToString(payload) +
                "</payload>" +
            "</encrypted>";

    String actual = element.toXML().toString();
    assertEquals("Serialized xml of OmemoElement must match.", expected, actual);

    OmemoElement_VAxolotl parsed = new OmemoVAxolotlProvider().parse(TestUtils.getParser(actual));
    assertEquals("Parsed OmemoElement must equal the original.",
            element.toXML().toString(),
            parsed.toXML().toString());
}
 
Example 19
Source Project: Smack   Source File: DnsIq.java    License: Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("ByteBufferBackingArray")
public String getDnsMessageBase64Encoded() {
    if (base64DnsMessage == null) {
        ByteBuffer byteBuffer = dnsMessage.getInByteBuffer();
        byte[] bytes = byteBuffer.array();
        base64DnsMessage = Base64.encodeToStringWithoutPadding(bytes);
    }
    return base64DnsMessage;
}
 
Example 20
Source Project: Smack   Source File: Java7SmackInitializer.java    License: 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 21
Source Project: Smack   Source File: PainlessOpenPgpProvider.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public OpenPgpElementAndMetadata signAndEncrypt(SigncryptElement element, OpenPgpSelf self, Collection<OpenPgpContact> recipients)
        throws IOException, PGPException {
    InputStream plainText = element.toInputStream();
    ByteArrayOutputStream cipherText = new ByteArrayOutputStream();

    ArrayList<PGPPublicKeyRingCollection> recipientKeys = new ArrayList<>();
    for (OpenPgpContact contact : recipients) {
        PGPPublicKeyRingCollection keys = contact.getTrustedAnnouncedKeys();
        if (keys != null) {
            recipientKeys.add(keys);
        } else {
            LOGGER.log(Level.WARNING, "There are no suitable keys for contact " + contact.getJid().toString());
        }
    }

    EncryptionStream cipherStream = PGPainless.createEncryptor().onOutputStream(cipherText)
            .toRecipients(recipientKeys.toArray(new PGPPublicKeyRingCollection[] {}))
            .andToSelf(self.getTrustedAnnouncedKeys())
            .usingSecureAlgorithms()
            .signWith(getStore().getKeyRingProtector(), self.getSigningKeyRing())
            .noArmor();

    Streams.pipeAll(plainText, cipherStream);
    plainText.close();
    cipherStream.flush();
    cipherStream.close();
    cipherText.close();

    String base64 = Base64.encodeToString(cipherText.toByteArray());
    OpenPgpElement openPgpElement = new OpenPgpElement(base64);

    return new OpenPgpElementAndMetadata(openPgpElement, cipherStream.getResult());
}
 
Example 22
Source Project: Smack   Source File: PainlessOpenPgpProvider.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public OpenPgpElementAndMetadata encrypt(CryptElement element, OpenPgpSelf self, Collection<OpenPgpContact> recipients)
        throws IOException, PGPException {
    InputStream plainText = element.toInputStream();
    ByteArrayOutputStream cipherText = new ByteArrayOutputStream();

    ArrayList<PGPPublicKeyRingCollection> recipientKeys = new ArrayList<>();
    for (OpenPgpContact contact : recipients) {
        PGPPublicKeyRingCollection keys = contact.getTrustedAnnouncedKeys();
        if (keys != null) {
            recipientKeys.add(keys);
        } else {
            LOGGER.log(Level.WARNING, "There are no suitable keys for contact " + contact.getJid().toString());
        }
    }

    EncryptionStream cipherStream = PGPainless.createEncryptor().onOutputStream(cipherText)
            .toRecipients(recipientKeys.toArray(new PGPPublicKeyRingCollection[] {}))
            .andToSelf(self.getTrustedAnnouncedKeys())
            .usingSecureAlgorithms()
            .doNotSign()
            .noArmor();

    Streams.pipeAll(plainText, cipherStream);
    plainText.close();
    cipherStream.flush();
    cipherStream.close();
    cipherText.close();

    String base64 = Base64.encodeToString(cipherText.toByteArray());
    OpenPgpElement openPgpElement = new OpenPgpElement(base64);

    return new OpenPgpElementAndMetadata(openPgpElement, cipherStream.getResult());
}
 
Example 23
Source Project: Smack   Source File: SecretKeyBackupHelper.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Decrypt a secret key backup and return the {@link PGPSecretKeyRing} contained in it.
 * TODO: Return a PGPSecretKeyRingCollection instead?
 *
 * @param backup encrypted {@link SecretkeyElement} containing the backup
 * @param backupCode passphrase for decrypting the {@link SecretkeyElement}.
 * @return the TODO javadoc me please
 * @throws InvalidBackupCodeException in case the provided backup code is invalid.
 * @throws IOException IO is dangerous.
 * @throws PGPException PGP is brittle.
 */
public static PGPSecretKeyRing restoreSecretKeyBackup(SecretkeyElement backup, String backupCode)
        throws InvalidBackupCodeException, IOException, PGPException {
    byte[] encrypted = Base64.decode(backup.getB64Data());

    byte[] decrypted;
    try {
        decrypted = PGPainless.decryptWithPassword(encrypted, new Passphrase(backupCode.toCharArray()));
    } catch (IOException | PGPException e) {
        throw new InvalidBackupCodeException("Could not decrypt secret key backup. Possibly wrong passphrase?", e);
    }

    return PGPainless.readKeyRing().secretKeyRing(decrypted);
}
 
Example 24
Source Project: Smack   Source File: AndroidSmackInitializer.java    License: 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 25
Source Project: Smack   Source File: InBandBytestreamSession.java    License: Apache License 2.0 5 votes vote down vote up
private synchronized void flushBuffer() throws IOException {

            // do nothing if no data to send available
            if (bufferPointer == 0) {
                return;
            }

            // create data packet
            String enc = Base64.encodeToString(buffer, 0, bufferPointer);
            DataPacketExtension data = new DataPacketExtension(byteStreamRequest.getSessionID(),
                            this.seq, enc);

            // write to XMPP stream
            try {
                writeToXML(data);
            }
            catch (InterruptedException | NotConnectedException e) {
                IOException ioException = new IOException();
                ioException.initCause(e);
                throw ioException;
            }

            // reset buffer pointer
            bufferPointer = 0;

            // increment sequence, considering sequence overflow
            this.seq = this.seq + 1 == 65535 ? 0 : this.seq + 1;

        }
 
Example 26
Source Project: Smack   Source File: VCard.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Specify the bytes for the avatar to use as well as the mime type.
 *
 * @param bytes the bytes of the avatar.
 * @param mimeType the mime type of the avatar.
 */
public void setAvatar(byte[] bytes, String mimeType) {
    // If bytes is null, remove the avatar
    if (bytes == null) {
        removeAvatar();
        return;
    }

    // Otherwise, add to mappings.
    String encodedImage = Base64.encodeToString(bytes);

    setAvatar(encodedImage, mimeType);
}
 
Example 27
Source Project: Smack   Source File: BoBData.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Get the content in a Base64 encoded String.
 *
 * @return the content in a Base64 encoded String
 */
public String getContentBase64Encoded() {
    if (contentString == null) {
        contentString = Base64.encodeToString(getContent());
    }
    return contentString;
}
 
Example 28
Source Project: Smack   Source File: InBandBytestreamSessionMessageTest.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * If a data stanza is received out of order the session should be closed. See XEP-0047 Section
 * 2.2.
 *
 * @throws Exception should not happen
 */
@Test
public void shouldSendCloseRequestIfInvalidSequenceReceived() throws Exception {
    // confirm close request
    IQ resultIQ = IBBPacketUtils.createResultIQ(initiatorJID, targetJID);
    protocol.addResponse(resultIQ, Verification.requestTypeSET,
                    Verification.correspondingSenderReceiver);

    // get IBB sessions data packet listener
    InBandBytestreamSession session = new InBandBytestreamSession(connection, initBytestream,
                    initiatorJID);
    InputStream inputStream = session.getInputStream();
    StanzaListener listener = Whitebox.getInternalState(inputStream, "dataPacketListener", StanzaListener.class);

    // build invalid packet with out of order sequence
    String base64Data = Base64.encode("Data");
    DataPacketExtension dpe = new DataPacketExtension(sessionID, 123, base64Data);
    Message dataMessage = StanzaBuilder.buildMessage()
            .addExtension(dpe)
            .build();

    // add data packets
    listener.processStanza(dataMessage);

    // read until exception is thrown
    try {
        inputStream.read();
        fail("exception should be thrown");
    }
    catch (IOException e) {
        assertTrue(e.getMessage().contains("Packets out of sequence"));
    }

    protocol.verifyAll();

}
 
Example 29
Source Project: Smack   Source File: InBandBytestreamSessionMessageTest.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Test the input stream read() method.
 *
 * @throws Exception should not happen
 */
@Test
public void shouldReadAllReceivedData2() throws Exception {
    // create random data
    Random rand = new Random();
    byte[] controlData = new byte[3 * blockSize];
    rand.nextBytes(controlData);

    // get IBB sessions data packet listener
    InBandBytestreamSession session = new InBandBytestreamSession(connection, initBytestream,
                    initiatorJID);
    InputStream inputStream = session.getInputStream();
    StanzaListener listener = Whitebox.getInternalState(inputStream, "dataPacketListener", StanzaListener.class);

    // verify data packet and notify listener
    for (int i = 0; i < controlData.length / blockSize; i++) {
        String base64Data = Base64.encodeToString(controlData, i * blockSize, blockSize);
        DataPacketExtension dpe = new DataPacketExtension(sessionID, i, base64Data);
        Message dataMessage = StanzaBuilder.buildMessage()
                .addExtension(dpe)
                .build();
        listener.processStanza(dataMessage);
    }

    // read data
    byte[] bytes = new byte[3 * blockSize];
    for (int i = 0; i < bytes.length; i++) {
        bytes[i] = (byte) inputStream.read();
    }

    // verify data
    for (int i = 0; i < bytes.length; i++) {
        assertEquals(controlData[i], bytes[i]);
    }

    protocol.verifyAll();

}
 
Example 30
Source Project: Smack   Source File: InBandBytestreamSessionTest.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * If the input stream is closed the output stream should not be closed as well.
 *
 * @throws Exception should not happen
 */
@Test
public void shouldNotCloseBothStreamsIfOutputStreamIsClosed() throws Exception {

    InBandBytestreamSession session = new InBandBytestreamSession(connection, initBytestream,
                    initiatorJID);
    OutputStream outputStream = session.getOutputStream();
    outputStream.close();

    // verify data packet confirmation is of type RESULT
    protocol.addResponse(null, Verification.requestTypeRESULT);

    // insert data to read
    InputStream inputStream = session.getInputStream();
    StanzaListener listener = Whitebox.getInternalState(inputStream, "dataPacketListener", StanzaListener.class);
    String base64Data = Base64.encode("Data");
    DataPacketExtension dpe = new DataPacketExtension(sessionID, 0, base64Data);
    Data data = new Data(dpe);
    listener.processStanza(data);

    // verify no packet send
    protocol.verifyAll();

    try {
        outputStream.flush();
        fail("should throw an exception");
    }
    catch (IOException e) {
        assertTrue(e.getMessage().contains("closed"));
    }

    assertTrue(inputStream.read() != 0);

}