public byte [ ] encode ( ) throws IllegalStateException { prepareForEncoding ( ) ; // make sure we have everything necessary to encode a proper message validateAttributePresentity ( ) ; final char dataLength = getDataLength ( ) ; byte binMsg [ ] = new byte [ HEADER_LENGTH + dataLength ] ; int offset = 0 ; // STUN Message Type binMsg [ offset ++ ] = ( byte ) ( getMessageType ( ) >> 8 ) ; binMsg [ offset ++ ] = ( byte ) ( getMessageType ( ) & 0xFF ) ; // Message Length final int messageLengthOffset = offset ; offset += 2 ; byte tranID [ ] = getTransactionId ( ) ; if ( tranID . length == 12 ) { System . arraycopy ( MAGIC_COOKIE , 0 , binMsg , offset , 4 ) ; offset += 4 ; System . arraycopy ( tranID , 0 , binMsg , offset , TRANSACTION_ID_LENGTH ) ; offset += TRANSACTION_ID_LENGTH ; } else { /* RFC3489 behavior */ System . arraycopy ( tranID , 0 , binMsg , offset , RFC3489_TRANSACTION_ID_LENGTH ) ; offset += RFC3489_TRANSACTION_ID_LENGTH ; } Vector < Map . Entry < Character , StunAttribute > > v = new Vector < Map . Entry < Character , StunAttribute > > ( ) ; Iterator < Map . Entry < Character , StunAttribute > > iter = null ; char dataLengthForContentDependentAttribute = 0 ; synchronized ( attributes ) { v . addAll ( attributes . entrySet ( ) ) ; } iter = v . iterator ( ) ; while ( iter . hasNext ( ) ) { StunAttribute attribute = iter . next ( ) . getValue ( ) ; int attributeLength = attribute . getDataLength ( ) + StunAttribute . HEADER_LENGTH ; // take attribute padding into account: attributeLength += ( 4 - attributeLength % 4 ) % 4 ; dataLengthForContentDependentAttribute += attributeLength ; // special handling for message integrity and fingerprint values byte [ ] binAtt ; if ( attribute instanceof ContextDependentAttribute ) { /* * The "Message Length" seen by a ContextDependentAttribute is * up to and including the very Attribute but without any other * Attribute instances after it. */ binMsg [ messageLengthOffset ] = ( byte ) ( dataLengthForContentDependentAttribute >> 8 ) ; binMsg [ messageLengthOffset + 1 ] = ( byte ) ( dataLengthForContentDependentAttribute & 0xFF ) ; binAtt = ( ( ContextDependentAttribute ) attribute ) . encode ( binMsg , 0 , offset ) ; } else { binAtt = attribute . encode ( ) ; } System . arraycopy ( binAtt , 0 , binMsg , offset , binAtt . length ) ; /* * Offset by attributeLength and not by binAtt.length because * attributeLength takes the attribute padding into account and * binAtt.length does not. */ offset += attributeLength ; } // Message Length binMsg [ messageLengthOffset ] = ( byte ) ( dataLength >> 8 ) ; binMsg [ messageLengthOffset + 1 ] = ( byte ) ( dataLength & 0xFF ) ; return binMsg ; }
Returns a binary representation of this message .