001/* 002 * 003 * Copyright the original author or authors 004 * 005 * Licensed under the Apache License, Version 2.0 (the "License"); 006 * you may not use this file except in compliance with the License. 007 * You may obtain a copy of the License at 008 * 009 * http://www.apache.org/licenses/LICENSE-2.0 010 * 011 * Unless required by applicable law or agreed to in writing, software 012 * distributed under the License is distributed on an "AS IS" BASIS, 013 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 014 * See the License for the specific language governing permissions and 015 * limitations under the License. 016 */ 017package org.jivesoftware.smackx.bytestreams.ibb; 018 019import java.io.IOException; 020import java.io.InputStream; 021import java.io.OutputStream; 022import java.net.SocketTimeoutException; 023import java.util.concurrent.BlockingQueue; 024import java.util.concurrent.LinkedBlockingQueue; 025import java.util.concurrent.TimeUnit; 026import java.util.logging.Level; 027import java.util.logging.Logger; 028 029import org.jivesoftware.smack.SmackException.NotConnectedException; 030import org.jivesoftware.smack.SmackException.NotLoggedInException; 031import org.jivesoftware.smack.StanzaListener; 032import org.jivesoftware.smack.XMPPConnection; 033import org.jivesoftware.smack.datatypes.UInt16; 034import org.jivesoftware.smack.filter.AndFilter; 035import org.jivesoftware.smack.filter.StanzaFilter; 036import org.jivesoftware.smack.filter.StanzaTypeFilter; 037import org.jivesoftware.smack.packet.IQ; 038import org.jivesoftware.smack.packet.Message; 039import org.jivesoftware.smack.packet.Stanza; 040import org.jivesoftware.smack.packet.StanzaBuilder; 041import org.jivesoftware.smack.packet.StanzaError; 042import org.jivesoftware.smack.util.stringencoder.Base64; 043 044import org.jivesoftware.smackx.bytestreams.BytestreamSession; 045import org.jivesoftware.smackx.bytestreams.ibb.packet.Close; 046import org.jivesoftware.smackx.bytestreams.ibb.packet.Data; 047import org.jivesoftware.smackx.bytestreams.ibb.packet.DataPacketExtension; 048import org.jivesoftware.smackx.bytestreams.ibb.packet.Open; 049 050import org.jxmpp.jid.Jid; 051 052/** 053 * InBandBytestreamSession class represents an In-Band Bytestream session. 054 * <p> 055 * In-band bytestreams are bidirectional and this session encapsulates the streams for both 056 * directions. 057 * <p> 058 * Note that closing the In-Band Bytestream session will close both streams. If both streams are 059 * closed individually the session will be closed automatically once the second stream is closed. 060 * Use the {@link #setCloseBothStreamsEnabled(boolean)} method if both streams should be closed 061 * automatically if one of them is closed. 062 * 063 * @author Henning Staib 064 */ 065public class InBandBytestreamSession implements BytestreamSession { 066 067 private static final Logger LOGGER = Logger.getLogger(InBandBytestreamSession.class.getName()); 068 069 static final String UNEXPECTED_IBB_SEQUENCE = "Unexpected IBB sequence"; 070 071 /* XMPP connection */ 072 private final XMPPConnection connection; 073 074 /* the In-Band Bytestream open request for this session */ 075 private final Open byteStreamRequest; 076 077 /* 078 * the input stream for this session (either IQIBBInputStream or MessageIBBInputStream) 079 */ 080 private IBBInputStream inputStream; 081 082 /* 083 * the output stream for this session (either IQIBBOutputStream or MessageIBBOutputStream) 084 */ 085 private IBBOutputStream outputStream; 086 087 /* JID of the remote peer */ 088 private Jid remoteJID; 089 090 /* flag to close both streams if one of them is closed */ 091 private boolean closeBothStreamsEnabled = false; 092 093 /* flag to indicate if session is closed */ 094 private boolean isClosed = false; 095 096 /** 097 * Constructor. 098 * 099 * @param connection the XMPP connection 100 * @param byteStreamRequest the In-Band Bytestream open request for this session 101 * @param remoteJID JID of the remote peer 102 */ 103 protected InBandBytestreamSession(XMPPConnection connection, Open byteStreamRequest, 104 Jid remoteJID) { 105 this.connection = connection; 106 this.byteStreamRequest = byteStreamRequest; 107 this.remoteJID = remoteJID; 108 109 // initialize streams dependent to the uses stanza type 110 switch (byteStreamRequest.getStanza()) { 111 case IQ: 112 this.inputStream = new IQIBBInputStream(); 113 this.outputStream = new IQIBBOutputStream(); 114 break; 115 case MESSAGE: 116 this.inputStream = new MessageIBBInputStream(); 117 this.outputStream = new MessageIBBOutputStream(); 118 break; 119 } 120 121 } 122 123 @Override 124 public InputStream getInputStream() { 125 return this.inputStream; 126 } 127 128 @Override 129 public OutputStream getOutputStream() { 130 return this.outputStream; 131 } 132 133 @Override 134 public int getReadTimeout() { 135 return this.inputStream.readTimeout; 136 } 137 138 @Override 139 public void setReadTimeout(int timeout) { 140 if (timeout < 0) { 141 throw new IllegalArgumentException("Timeout must be >= 0"); 142 } 143 this.inputStream.readTimeout = timeout; 144 } 145 146 /** 147 * Returns whether both streams should be closed automatically if one of the streams is closed. 148 * Default is <code>false</code>. 149 * 150 * @return <code>true</code> if both streams will be closed if one of the streams is closed, 151 * <code>false</code> if both streams can be closed independently. 152 */ 153 public boolean isCloseBothStreamsEnabled() { 154 return closeBothStreamsEnabled; 155 } 156 157 /** 158 * Sets whether both streams should be closed automatically if one of the streams is closed. 159 * Default is <code>false</code>. 160 * 161 * @param closeBothStreamsEnabled <code>true</code> if both streams should be closed if one of 162 * the streams is closed, <code>false</code> if both streams should be closed 163 * independently 164 */ 165 public void setCloseBothStreamsEnabled(boolean closeBothStreamsEnabled) { 166 this.closeBothStreamsEnabled = closeBothStreamsEnabled; 167 } 168 169 @Override 170 public void close() throws IOException { 171 closeByLocal(true); // close input stream 172 closeByLocal(false); // close output stream 173 } 174 175 /** 176 * This method is invoked if a request to close the In-Band Bytestream has been received. 177 * 178 * @param closeRequest the close request from the remote peer 179 * @throws NotConnectedException if the XMPP connection is not connected. 180 * @throws InterruptedException if the calling thread was interrupted. 181 */ 182 protected void closeByPeer(Close closeRequest) throws NotConnectedException, InterruptedException { 183 184 /* 185 * close streams without flushing them, because stream is already considered closed on the 186 * remote peers side 187 */ 188 this.inputStream.closeInternal(); 189 this.inputStream.cleanup(); 190 this.outputStream.closeInternal(false); 191 192 // acknowledge close request 193 IQ confirmClose = IQ.createResultIQ(closeRequest); 194 this.connection.sendStanza(confirmClose); 195 196 } 197 198 /** 199 * This method is invoked if one of the streams has been closed locally, if an error occurred 200 * locally or if the whole session should be closed. 201 * 202 * @param in do we want to close the Input- or OutputStream? 203 * @throws IOException if an error occurs while sending the close request 204 */ 205 protected synchronized void closeByLocal(boolean in) throws IOException { 206 if (this.isClosed) { 207 return; 208 } 209 210 if (this.closeBothStreamsEnabled) { 211 this.inputStream.closeInternal(); 212 this.outputStream.closeInternal(true); 213 } 214 else { 215 if (in) { 216 this.inputStream.closeInternal(); 217 } 218 else { 219 // close stream but try to send any data left 220 this.outputStream.closeInternal(true); 221 } 222 } 223 224 if (this.inputStream.isClosed && this.outputStream.isClosed) { 225 this.isClosed = true; 226 227 // send close request 228 Close close = new Close(this.byteStreamRequest.getSessionID()); 229 close.setTo(this.remoteJID); 230 try { 231 connection.sendIqRequestAndWaitForResponse(close); 232 } 233 catch (Exception e) { 234 throw new IOException(e); 235 } 236 237 this.inputStream.cleanup(); 238 239 // remove session from manager 240 // Thanks Google Error Prone for finding the bug where remove() was called with 'this' as argument. Changed 241 // now to remove(byteStreamRequest.getSessionID). 242 InBandBytestreamManager.getByteStreamManager(this.connection).getSessions().remove(byteStreamRequest.getSessionID()); 243 } 244 245 } 246 247 /** 248 * IBBInputStream class is the base implementation of an In-Band Bytestream input stream. 249 * Subclasses of this input stream must provide a stanza listener along with a stanza filter to 250 * collect the In-Band Bytestream data packets. 251 */ 252 private abstract class IBBInputStream extends InputStream { 253 254 /* the data packet listener to fill the data queue */ 255 private final StanzaListener dataPacketListener; 256 257 /* queue containing received In-Band Bytestream data packets */ 258 final BlockingQueue<DataPacketExtension> dataQueue = new LinkedBlockingQueue<DataPacketExtension>(); 259 260 /* buffer containing the data from one data packet */ 261 private byte[] buffer; 262 263 /* pointer to the next byte to read from buffer */ 264 private int bufferPointer = -1; 265 266 /* data packet sequence (range from 0 to 65535) */ 267 private UInt16 expectedSeq = UInt16.MIN_VALUE; 268 269 /* flag to indicate if input stream is closed */ 270 private boolean isClosed = false; 271 272 /* flag to indicate if close method was invoked */ 273 private boolean closeInvoked = false; 274 275 /* timeout for read operations */ 276 private int readTimeout = 0; 277 278 /** 279 * Constructor. 280 */ 281 IBBInputStream() { 282 // add data packet listener to connection 283 this.dataPacketListener = getDataPacketListener(); 284 connection.addSyncStanzaListener(this.dataPacketListener, getDataPacketFilter()); 285 } 286 287 /** 288 * Returns the stanza listener that processes In-Band Bytestream data packets. 289 * 290 * @return the data stanza listener 291 */ 292 abstract StanzaListener getDataPacketListener(); 293 294 /** 295 * Returns the stanza filter that accepts In-Band Bytestream data packets. 296 * 297 * @return the data stanza filter 298 */ 299 abstract StanzaFilter getDataPacketFilter(); 300 301 @Override 302 public synchronized int read() throws IOException { 303 checkClosed(); 304 305 // if nothing read yet or whole buffer has been read fill buffer 306 if (bufferPointer == -1 || bufferPointer >= buffer.length) { 307 // if no data available and stream was closed return -1 308 if (!loadBuffer()) { 309 return -1; 310 } 311 } 312 313 // return byte and increment buffer pointer 314 return buffer[bufferPointer++] & 0xff; 315 } 316 317 @Override 318 public synchronized int read(byte[] b, int off, int len) throws IOException { 319 if (b == null) { 320 throw new NullPointerException(); 321 } 322 else if ((off < 0) || (off > b.length) || (len < 0) || ((off + len) > b.length) 323 || ((off + len) < 0)) { 324 throw new IndexOutOfBoundsException(); 325 } 326 else if (len == 0) { 327 return 0; 328 } 329 330 checkClosed(); 331 332 // if nothing read yet or whole buffer has been read fill buffer 333 if (bufferPointer == -1 || bufferPointer >= buffer.length) { 334 // if no data available and stream was closed return -1 335 if (!loadBuffer()) { 336 return -1; 337 } 338 } 339 340 // if more bytes wanted than available return all available 341 int bytesAvailable = buffer.length - bufferPointer; 342 if (len > bytesAvailable) { 343 len = bytesAvailable; 344 } 345 346 System.arraycopy(buffer, bufferPointer, b, off, len); 347 bufferPointer += len; 348 return len; 349 } 350 351 @Override 352 public synchronized int read(byte[] b) throws IOException { 353 return read(b, 0, b.length); 354 } 355 356 /** 357 * This method blocks until a data stanza is received, the stream is closed or the current 358 * thread is interrupted. 359 * 360 * @return <code>true</code> if data was received, otherwise <code>false</code> 361 * @throws IOException if data packets are out of sequence 362 */ 363 private synchronized boolean loadBuffer() throws IOException { 364 365 // wait until data is available or stream is closed 366 DataPacketExtension data = null; 367 try { 368 if (this.readTimeout == 0) { 369 while (data == null) { 370 if (isClosed && this.dataQueue.isEmpty()) { 371 return false; 372 } 373 data = this.dataQueue.poll(1000, TimeUnit.MILLISECONDS); 374 } 375 } 376 else { 377 data = this.dataQueue.poll(this.readTimeout, TimeUnit.MILLISECONDS); 378 if (data == null) { 379 throw new SocketTimeoutException(); 380 } 381 } 382 } 383 catch (InterruptedException e) { 384 // Restore the interrupted status 385 Thread.currentThread().interrupt(); 386 return false; 387 } 388 389 final UInt16 dataSeq = data.getSeq(); 390 // check if data packets sequence is successor of last seen sequence 391 if (!expectedSeq.equals(dataSeq)) { 392 // packets out of order; close stream/session 393 InBandBytestreamSession.this.close(); 394 String message = UNEXPECTED_IBB_SEQUENCE + " " + dataSeq + " received, expected " 395 + expectedSeq; 396 throw new IOException(message); 397 } 398 expectedSeq = dataSeq.incrementedByOne(); 399 400 // set buffer to decoded data 401 buffer = data.getDecodedData(); 402 bufferPointer = 0; 403 return true; 404 } 405 406 /** 407 * Checks if this stream is closed and throws an IOException if necessary 408 * 409 * @throws IOException if stream is closed and no data should be read anymore 410 */ 411 private void checkClosed() throws IOException { 412 // Throw an exception if, and only if, this stream has been already 413 // closed by the user using the close() method 414 if (closeInvoked) { 415 // clear data queue in case additional data was received after stream was closed 416 this.dataQueue.clear(); 417 throw new IOException("Stream is closed"); 418 } 419 } 420 421 @Override 422 public boolean markSupported() { 423 return false; 424 } 425 426 @Override 427 public void close() throws IOException { 428 if (closeInvoked) { 429 return; 430 } 431 432 this.closeInvoked = true; 433 434 InBandBytestreamSession.this.closeByLocal(true); 435 } 436 437 /** 438 * This method sets the close flag and removes the data stanza listener. 439 */ 440 private void closeInternal() { 441 if (isClosed) { 442 return; 443 } 444 isClosed = true; 445 } 446 447 /** 448 * Invoked if the session is closed. 449 */ 450 private void cleanup() { 451 connection.removeSyncStanzaListener(this.dataPacketListener); 452 } 453 454 } 455 456 /** 457 * IQIBBInputStream class implements IBBInputStream to be used with IQ stanzas encapsulating the 458 * data packets. 459 */ 460 private final class IQIBBInputStream extends IBBInputStream { 461 462 @Override 463 protected StanzaListener getDataPacketListener() { 464 return new StanzaListener() { 465 466 private UInt16 expectedSequence = UInt16.MIN_VALUE;; 467 468 @Override 469 public void processStanza(Stanza packet) throws NotConnectedException, InterruptedException { 470 final Data dataIq = (Data) packet; 471 // get data packet extension 472 DataPacketExtension data = dataIq.getDataPacketExtension(); 473 474 final UInt16 seq = data.getSeq(); 475 /* 476 * check if sequence was not used already (see XEP-0047 Section 2.2) 477 */ 478 if (!expectedSequence.equals(seq)) { 479 String descriptiveEnTest = UNEXPECTED_IBB_SEQUENCE + " " + seq + " received, expected " 480 + expectedSequence; 481 StanzaError stanzaError = StanzaError.getBuilder() 482 .setCondition(StanzaError.Condition.unexpected_request) 483 .setDescriptiveEnText(descriptiveEnTest) 484 .build(); 485 IQ unexpectedRequest = IQ.createErrorResponse(dataIq, stanzaError); 486 connection.sendStanza(unexpectedRequest); 487 488 try { 489 // TODO: It would be great if close would take a "close error reason" argument. Also there 490 // is the question if this is really a reason to close the stream. We could have some more 491 // tolerance regarding out-of-sequence stanzas arriving: Even though XMPP has the in-order 492 // guarantee, I could imagine that there are cases where stanzas are, for example, 493 // duplicated because of stream resumption. 494 close(); 495 } catch (IOException e) { 496 LOGGER.log(Level.FINER, "Could not close session, because of IOException. Close reason: " 497 + descriptiveEnTest); 498 } 499 500 return; 501 } 502 503 // check if encoded data is valid (see XEP-0047 Section 2.2) 504 if (data.getDecodedData() == null) { 505 // data is invalid; respond with bad-request error 506 IQ badRequest = IQ.createErrorResponse((IQ) packet, 507 StanzaError.Condition.bad_request); 508 connection.sendStanza(badRequest); 509 return; 510 } 511 512 expectedSequence = seq.incrementedByOne(); 513 514 // data is valid; add to data queue 515 dataQueue.offer(data); 516 517 // confirm IQ 518 IQ confirmData = IQ.createResultIQ((IQ) packet); 519 connection.sendStanza(confirmData); 520 } 521 522 }; 523 } 524 525 @Override 526 protected StanzaFilter getDataPacketFilter() { 527 /* 528 * filter all IQ stanzas having type 'SET' (represented by Data class), containing a 529 * data stanza extension, matching session ID and recipient 530 */ 531 return new AndFilter(new StanzaTypeFilter(Data.class), new IBBDataPacketFilter()); 532 } 533 534 } 535 536 /** 537 * MessageIBBInputStream class implements IBBInputStream to be used with message stanzas 538 * encapsulating the data packets. 539 */ 540 private final class MessageIBBInputStream extends IBBInputStream { 541 542 @Override 543 protected StanzaListener getDataPacketListener() { 544 return new StanzaListener() { 545 546 @Override 547 public void processStanza(Stanza packet) { 548 // get data packet extension 549 DataPacketExtension data = packet.getExtension( 550 DataPacketExtension.class); 551 552 // check if encoded data is valid 553 if (data.getDecodedData() == null) { 554 /* 555 * TODO once a majority of XMPP server implementation support XEP-0079 556 * Advanced Message Processing the invalid message could be answered with an 557 * appropriate error. For now we just ignore the packet. Subsequent packets 558 * with an increased sequence will cause the input stream to close the 559 * stream/session. 560 */ 561 return; 562 } 563 564 // data is valid; add to data queue 565 dataQueue.offer(data); 566 567 // TODO confirm packet once XMPP servers support XEP-0079 568 } 569 570 }; 571 } 572 573 @Override 574 protected StanzaFilter getDataPacketFilter() { 575 /* 576 * filter all message stanzas containing a data stanza extension, matching session ID 577 * and recipient 578 */ 579 return new AndFilter(new StanzaTypeFilter(Message.class), new IBBDataPacketFilter()); 580 } 581 582 } 583 584 /** 585 * IBBDataPacketFilter class filters all packets from the remote peer of this session, 586 * containing an In-Band Bytestream data stanza extension whose session ID matches this sessions 587 * ID. 588 */ 589 private final class IBBDataPacketFilter implements StanzaFilter { 590 591 @Override 592 public boolean accept(Stanza packet) { 593 // sender equals remote peer 594 if (!packet.getFrom().equals(remoteJID)) { 595 return false; 596 } 597 598 DataPacketExtension data; 599 if (packet instanceof Data) { 600 data = ((Data) packet).getDataPacketExtension(); 601 } else { 602 // stanza contains data packet extension 603 data = packet.getExtension( 604 DataPacketExtension.class); 605 if (data == null) { 606 return false; 607 } 608 } 609 610 // session ID equals this session ID 611 if (!data.getSessionID().equals(byteStreamRequest.getSessionID())) { 612 return false; 613 } 614 615 return true; 616 } 617 618 } 619 620 /** 621 * IBBOutputStream class is the base implementation of an In-Band Bytestream output stream. 622 * Subclasses of this output stream must provide a method to send data over XMPP stream. 623 */ 624 private abstract class IBBOutputStream extends OutputStream { 625 626 /* buffer with the size of this sessions block size */ 627 private final byte[] buffer; 628 629 /* pointer to next byte to write to buffer */ 630 private int bufferPointer = 0; 631 632 /* data packet sequence (range from 0 to 65535) */ 633 private UInt16 seq = UInt16.from(0); 634 635 /* flag to indicate if output stream is closed */ 636 boolean isClosed = false; 637 638 /** 639 * Constructor. 640 */ 641 private IBBOutputStream() { 642 this.buffer = new byte[byteStreamRequest.getBlockSize()]; 643 } 644 645 /** 646 * Writes the given data stanza to the XMPP stream. 647 * 648 * @param data the data packet 649 * @throws IOException if an I/O error occurred while sending or if the stream is closed 650 * @throws NotConnectedException if the XMPP connection is not connected. 651 * @throws InterruptedException if the calling thread was interrupted. 652 */ 653 abstract void writeToXML(DataPacketExtension data) throws IOException, NotConnectedException, InterruptedException; 654 655 @Override 656 public synchronized void write(int b) throws IOException { 657 if (this.isClosed) { 658 throw new IOException("Stream is closed"); 659 } 660 661 // if buffer is full flush buffer 662 if (bufferPointer >= buffer.length) { 663 flushBuffer(); 664 } 665 666 buffer[bufferPointer++] = (byte) b; 667 } 668 669 @Override 670 public synchronized void write(byte[] b, int off, int len) throws IOException { 671 if (b == null) { 672 throw new NullPointerException(); 673 } 674 else if ((off < 0) || (off > b.length) || (len < 0) || ((off + len) > b.length) 675 || ((off + len) < 0)) { 676 throw new IndexOutOfBoundsException(); 677 } 678 else if (len == 0) { 679 return; 680 } 681 682 if (this.isClosed) { 683 throw new IOException("Stream is closed"); 684 } 685 686 // is data to send greater than buffer size 687 if (len >= buffer.length) { 688 689 // "byte" off the first chunk to write out 690 writeOut(b, off, buffer.length); 691 692 // recursively call this method with the lesser amount 693 write(b, off + buffer.length, len - buffer.length); 694 } 695 else { 696 writeOut(b, off, len); 697 } 698 } 699 700 @Override 701 public synchronized void write(byte[] b) throws IOException { 702 write(b, 0, b.length); 703 } 704 705 /** 706 * Fills the buffer with the given data and sends it over the XMPP stream if the buffers 707 * capacity has been reached. This method is only called from this class so it is assured 708 * that the amount of data to send is <= buffer capacity 709 * 710 * @param b the data 711 * @param off the data 712 * @param len the number of bytes to write 713 * @throws IOException if an I/O error occurred while sending or if the stream is closed 714 */ 715 private synchronized void writeOut(byte[] b, int off, int len) throws IOException { 716 if (this.isClosed) { 717 throw new IOException("Stream is closed"); 718 } 719 720 // set to 0 in case the next 'if' block is not executed 721 int available = 0; 722 723 // is data to send greater that buffer space left 724 if (len > buffer.length - bufferPointer) { 725 // fill buffer to capacity and send it 726 available = buffer.length - bufferPointer; 727 System.arraycopy(b, off, buffer, bufferPointer, available); 728 bufferPointer += available; 729 flushBuffer(); 730 } 731 732 // copy the data left to buffer 733 System.arraycopy(b, off + available, buffer, bufferPointer, len - available); 734 bufferPointer += len - available; 735 } 736 737 @Override 738 public synchronized void flush() throws IOException { 739 if (this.isClosed) { 740 throw new IOException("Stream is closed"); 741 } 742 flushBuffer(); 743 } 744 745 private synchronized void flushBuffer() throws IOException { 746 747 // do nothing if no data to send available 748 if (bufferPointer == 0) { 749 return; 750 } 751 752 // create data packet 753 String enc = Base64.encodeToString(buffer, 0, bufferPointer); 754 DataPacketExtension data = new DataPacketExtension(byteStreamRequest.getSessionID(), 755 this.seq, enc); 756 757 // write to XMPP stream 758 try { 759 writeToXML(data); 760 } 761 catch (InterruptedException | NotConnectedException e) { 762 IOException ioException = new IOException(); 763 ioException.initCause(e); 764 throw ioException; 765 } 766 767 // reset buffer pointer 768 bufferPointer = 0; 769 770 // increment sequence, considering sequence overflow 771 seq = seq.incrementedByOne(); 772 773 } 774 775 @Override 776 public void close() throws IOException { 777 if (isClosed) { 778 return; 779 } 780 InBandBytestreamSession.this.closeByLocal(false); 781 } 782 783 /** 784 * Sets the close flag and optionally flushes the stream. 785 * 786 * @param flush if <code>true</code> flushes the stream 787 */ 788 void closeInternal(boolean flush) { 789 if (this.isClosed) { 790 return; 791 } 792 this.isClosed = true; 793 794 try { 795 if (flush) { 796 flushBuffer(); 797 } 798 } 799 catch (IOException e) { 800 /* 801 * ignore, because writeToXML() will not throw an exception if stream is already 802 * closed 803 */ 804 } 805 } 806 807 } 808 809 /** 810 * IQIBBOutputStream class implements IBBOutputStream to be used with IQ stanzas encapsulating 811 * the data packets. 812 */ 813 private final class IQIBBOutputStream extends IBBOutputStream { 814 815 @Override 816 protected synchronized void writeToXML(DataPacketExtension data) throws IOException { 817 // create IQ stanza containing data packet 818 IQ iq = new Data(data); 819 iq.setTo(remoteJID); 820 821 try { 822 connection.sendIqRequestAndWaitForResponse(iq); 823 } 824 catch (Exception e) { 825 // close session unless it is already closed 826 if (!this.isClosed) { 827 InBandBytestreamSession.this.close(); 828 throw new IOException(e); 829 } 830 } 831 832 } 833 834 } 835 836 /** 837 * MessageIBBOutputStream class implements IBBOutputStream to be used with message stanzas 838 * encapsulating the data packets. 839 */ 840 private final class MessageIBBOutputStream extends IBBOutputStream { 841 842 @Override 843 protected synchronized void writeToXML(DataPacketExtension data) throws NotConnectedException, InterruptedException { 844 // create message stanza containing data packet 845 Message message = StanzaBuilder.buildMessage().to(remoteJID) 846 .addExtension(data) 847 .build(); 848 849 connection.sendStanza(message); 850 851 } 852 853 } 854 855 /** 856 * Process IQ stanza. 857 * @param data TODO javadoc me please 858 * @throws NotConnectedException if the XMPP connection is not connected. 859 * @throws InterruptedException if the calling thread was interrupted. 860 * @throws NotLoggedInException if the XMPP connection is not authenticated. 861 */ 862 public void processIQPacket(Data data) throws NotConnectedException, InterruptedException, NotLoggedInException { 863 inputStream.dataPacketListener.processStanza(data); 864 } 865 866}