/** * 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(); } }
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(); }
@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 Java7HostnameVerifier()); Base64.setEncoder(Java7Base64Encoder.getInstance()); Base64UrlSafeEncoder.setEncoder(Java7Base64UrlSafeEncoder.getInstance()); DNSUtil.setIdnaTransformer(new StringTransformer() { @Override public String transform(String string) { return java.net.IDN.toASCII(string); } }); return null; }
private final void authenticate() throws SmackException, NotConnectedException { 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.send(new AuthMechanism(getName(), authenticationText)); }
/** * 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 NotConnectedException * @throws SmackException */ public final void challengeReceived(String challengeString, boolean finalChallenge) throws SmackException, NotConnectedException { byte[] challenge = Base64.decode(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.send(responseStanza); }
@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", "unusedBar", PASSWORD); 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(); }
/** * 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; }
/** * 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, StanzaListener.class); String base64Data = Base64.encode("Data"); DataPacketExtension dpe = new DataPacketExtension(sessionID, 0, base64Data); Data data = new Data(dpe); listener.processPacket(data); protocol.verifyAll(); }
@Override public List<Exception> initialize() { SmackConfiguration.setDefaultHostnameVerifier(new StrictHostnameVerifier()); Base64.setEncoder(AndroidBase64Encoder.getInstance()); Base64UrlSafeEncoder.setEncoder(AndroidBase64UrlSafeEncoder.getInstance()); return null; }
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 (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); }
/** * 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); }
/** * If a data stanza(/packet) 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, StanzaListener.class); // build invalid packet with out of order sequence String base64Data = Base64.encode("Data"); DataPacketExtension dpe = new DataPacketExtension(sessionID, 123, base64Data); Message dataMessage = new Message(); dataMessage.addExtension(dpe); // add data packets listener.processPacket(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(); }
/** * Test the input stream read(byte[], int, int) method. * * @throws Exception should not happen */ @Test public void shouldReadAllReceivedData1() 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, 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 = new Message(); dataMessage.addExtension(dpe); listener.processPacket(dataMessage); } byte[] bytes = new byte[3 * blockSize]; int read = 0; read = inputStream.read(bytes, 0, blockSize); assertEquals(blockSize, read); read = inputStream.read(bytes, 10, blockSize); assertEquals(blockSize, read); read = inputStream.read(bytes, 20, blockSize); assertEquals(blockSize, read); // verify data for (int i = 0; i < bytes.length; i++) { assertEquals(controlData[i], bytes[i]); } protocol.verifyAll(); }
/** * 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, 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 = new Message(); dataMessage.addExtension(dpe); listener.processPacket(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(); }
/** * 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, StanzaListener.class); String base64Data = Base64.encode("Data"); DataPacketExtension dpe = new DataPacketExtension(sessionID, 0, base64Data); Data data = new Data(dpe); listener.processPacket(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); }
/** * If the data stanza(/packet) has a sequence that is already used an 'unexpected-request' error should * be returned. See XEP-0047 Section 2.2. * * @throws Exception should not happen */ @Test public void shouldReplyWithErrorIfAlreadyUsedSequenceIsReceived() throws Exception { // verify reply to first valid data packet is of type RESULT protocol.addResponse(null, Verification.requestTypeRESULT); // verify reply to invalid data packet is an error protocol.addResponse(null, Verification.requestTypeERROR, new Verification<IQ, IQ>() { public void verify(IQ request, IQ response) { assertEquals(XMPPError.Condition.unexpected_request, request.getError().getCondition()); } }); // get IBB sessions data packet listener InBandBytestreamSession session = new InBandBytestreamSession(connection, initBytestream, initiatorJID); InputStream inputStream = session.getInputStream(); StanzaListener listener = Whitebox.getInternalState(inputStream, StanzaListener.class); // build data packets String base64Data = Base64.encode("Data"); DataPacketExtension dpe = new DataPacketExtension(sessionID, 0, base64Data); Data data1 = new Data(dpe); Data data2 = new Data(dpe); // notify listener listener.processPacket(data1); listener.processPacket(data2); protocol.verifyAll(); }
/** * If a data stanza(/packet) 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 { IQ resultIQ = IBBPacketUtils.createResultIQ(initiatorJID, targetJID); // confirm data packet with invalid sequence protocol.addResponse(resultIQ); // confirm close request 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, StanzaListener.class); // build invalid packet with out of order sequence String base64Data = Base64.encode("Data"); DataPacketExtension dpe = new DataPacketExtension(sessionID, 123, base64Data); Data data = new Data(dpe); // add data packets listener.processPacket(data); // 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(); }
/** * 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); IQ resultIQ = IBBPacketUtils.createResultIQ(initiatorJID, targetJID); // get IBB sessions data packet listener InBandBytestreamSession session = new InBandBytestreamSession(connection, initBytestream, initiatorJID); InputStream inputStream = session.getInputStream(); StanzaListener listener = Whitebox.getInternalState(inputStream, StanzaListener.class); // set data packet acknowledgment and notify listener for (int i = 0; i < controlData.length / blockSize; i++) { protocol.addResponse(resultIQ); String base64Data = Base64.encodeToString(controlData, i * blockSize, blockSize); DataPacketExtension dpe = new DataPacketExtension(sessionID, i, base64Data); Data data = new Data(dpe); listener.processPacket(data); } // 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(); }
/** * If the output stream is closed the input stream should not be closed as well. * * @throws Exception should not happen */ @Test public void shouldNotCloseBothStreamsIfInputStreamIsClosed() throws Exception { // acknowledgment for data packet IQ resultIQ = IBBPacketUtils.createResultIQ(initiatorJID, targetJID); protocol.addResponse(resultIQ); // get IBB sessions data packet listener InBandBytestreamSession session = new InBandBytestreamSession(connection, initBytestream, initiatorJID); InputStream inputStream = session.getInputStream(); StanzaListener listener = Whitebox.getInternalState(inputStream, StanzaListener.class); // build data packet String base64Data = Base64.encode("Data"); DataPacketExtension dpe = new DataPacketExtension(sessionID, 0, base64Data); Data data = new Data(dpe); // add data packets listener.processPacket(data); inputStream.close(); protocol.verifyAll(); try { while (inputStream.read() != -1) { } inputStream.read(); fail("should throw an exception"); } catch (IOException e) { assertTrue(e.getMessage().contains("closed")); } session.getOutputStream().flush(); }
private void manageMessageReceived(Message message, Date delayDate, String messageId, boolean fromMam) { String[] jidList = message.getFrom().toString().split("/"); ChatMessage chatMessage = new ChatMessage(); chatMessage.setMessageId(messageId); String chatRoomJID; if (!jidList[0].equals(Preferences.getInstance().getUserXMPPJid())) { chatRoomJID = jidList[0]; } else { chatRoomJID = message.getTo().toString().split("/")[0]; } chatMessage.setRoomJid(chatRoomJID); // not saving messages with my affiliation changes to "none", and delete the chat in that case if (checkIfMyIsAffiliationNone(message)) { deleteChat(chatRoomJID); return; } if (message.hasExtension(JivePropertiesExtension.ELEMENT, JivePropertiesExtension.NAMESPACE)) { return; } RoomsListManager.getInstance().createChatIfNotExists(chatRoomJID, true); manageSender(jidList, chatMessage, chatRoomJID); chatMessage.setStatus(ChatMessage.STATUS_SENT); chatMessage.setUnread(true); if (isBoBMessage(message)) { BoBExtension bobExtension = BoBExtension.from(message); chatMessage.setContent(Base64.decodeToString(bobExtension.getBoBHash().getHash())); chatMessage.setType(ChatMessage.TYPE_STICKER); } else { chatMessage.setContent(message.getBody()); chatMessage.setType(ChatMessage.TYPE_CHAT); } Realm realm = RealmManager.getInstance().getRealm(); Chat chatRoom = realm.where(Chat.class).equalTo("jid", chatRoomJID).findFirst(); realm.beginTransaction(); if (canBeTextMessageOrSticker(message) && !fromMam) { chatRoom.addUnreadMessage(); } // room name or subject change manageConfigurationsChange(message, chatMessage, chatRoom); // not saving invalid messages if (chatMessage.getContent() == null || chatMessage.getContent().isEmpty() || chatMessage.getUserSender() == null) { realm.commitTransaction(); realm.close(); return; } // assign date manageDelayDate(delayDate, chatMessage); realm.copyToRealmOrUpdate(chatMessage); realm.commitTransaction(); realm.close(); }
@Override protected byte[] getAuthenticationText() throws SmackException { // base64("\0" + user_name + "\0" + oauth_token) return Base64.encode(toBytes('\u0000' + authenticationId + '\u0000' + password)); }
private static String saslLayerString(String string) { return Base64.decodeToString(string); }
public byte[] getIncomingSoundBytes() { return Base64.decode(incomingSound); }
public byte[] getOutgoingSoundBytes() { return Base64.decode(outgoingSound); }
/** * Test the input stream read(byte[], int, int) method. * * @throws Exception should not happen */ @Test public void shouldReadAllReceivedData1() throws Exception { // create random data Random rand = new Random(); byte[] controlData = new byte[3 * blockSize]; rand.nextBytes(controlData); IQ resultIQ = IBBPacketUtils.createResultIQ(initiatorJID, targetJID); // get IBB sessions data packet listener InBandBytestreamSession session = new InBandBytestreamSession(connection, initBytestream, initiatorJID); InputStream inputStream = session.getInputStream(); StanzaListener listener = Whitebox.getInternalState(inputStream, StanzaListener.class); // set data packet acknowledgment and notify listener for (int i = 0; i < controlData.length / blockSize; i++) { protocol.addResponse(resultIQ); String base64Data = Base64.encodeToString(controlData, i * blockSize, blockSize); DataPacketExtension dpe = new DataPacketExtension(sessionID, i, base64Data); Data data = new Data(dpe); listener.processPacket(data); } byte[] bytes = new byte[3 * blockSize]; int read = 0; read = inputStream.read(bytes, 0, blockSize); assertEquals(blockSize, read); read = inputStream.read(bytes, 10, blockSize); assertEquals(blockSize, read); read = inputStream.read(bytes, 20, blockSize); assertEquals(blockSize, read); // verify data for (int i = 0; i < bytes.length; i++) { assertEquals(controlData[i], bytes[i]); } protocol.verifyAll(); }
public static byte[] getAvatarBinary() { return Base64.decode(getAvatarEncoded()); }
/** * Return the byte representation of the avatar(if one exists), otherwise returns null if * no avatar could be found. * <b>Example 1</b> * <pre> * // Load Avatar from VCard * byte[] avatarBytes = vCard.getAvatar(); * <p/> * // To create an ImageIcon for Swing applications * ImageIcon icon = new ImageIcon(avatar); * <p/> * // To create just an image object from the bytes * ByteArrayInputStream bais = new ByteArrayInputStream(avatar); * try { * Image image = ImageIO.read(bais); * } * catch (IOException e) { * e.printStackTrace(); * } * </pre> * * @return byte representation of avatar. */ public byte[] getAvatar() { if (photoBinval == null) { return null; } return Base64.decode(photoBinval); }