idx
int64
0
41.2k
question
stringlengths
74
4.21k
target
stringlengths
5
888
36,800
public static int insertPopsForAllParameters ( MethodVisitor mv , String desc ) { String descSequence = Utils . getParamSequence ( desc ) ; if ( descSequence == null ) { return 0 ; } int count = descSequence . length ( ) ; for ( int dpos = count - 1 ; dpos >= 0 ; dpos -- ) { char ch = descSequence . charAt ( dpos ) ; switch ( ch ) { case 'O' : case 'I' : case 'Z' : case 'F' : case 'S' : case 'C' : case 'B' : mv . visitInsn ( POP ) ; break ; case 'J' : case 'D' : mv . visitInsn ( POP2 ) ; break ; default : throw new IllegalStateException ( "Unexpected character: " + ch + " from " + desc + ":" + dpos ) ; } } return count ; }
Looks at the supplied descriptor and inserts enough pops to remove all parameters . Should be used when about to avoid a method call .
36,801
public static String discoverClassname ( byte [ ] classbytes ) { ClassReader cr = new ClassReader ( classbytes ) ; ClassnameDiscoveryVisitor v = new ClassnameDiscoveryVisitor ( ) ; cr . accept ( v , 0 ) ; return v . classname ; }
Discover the classname specified in the supplied bytecode and return it .
36,802
public static byte [ ] invoke ( byte [ ] bytesIn , String ... descriptors ) { ClassReader cr = new ClassReader ( bytesIn ) ; EmptyCtor ca = new EmptyCtor ( descriptors ) ; cr . accept ( ca , 0 ) ; byte [ ] newbytes = ca . getBytes ( ) ; return newbytes ; }
Empty the constructors with the specified descriptors .
36,803
public static Object emulateInvokeDynamic ( ReloadableType rtype , Class < ? > executorClass , Handle handle , Object [ ] bsmArgs , Object lookup , String indyNameAndDescriptor , Object [ ] indyParams ) { try { CallSite callsite = callLambdaMetaFactory ( rtype , bsmArgs , lookup , indyNameAndDescriptor , executorClass ) ; return callsite . dynamicInvoker ( ) . invokeWithArguments ( indyParams ) ; } catch ( Throwable t ) { throw new RuntimeException ( t ) ; } }
Programmatic emulation of INVOKEDYNAMIC so initialize the callsite via use of the bootstrap method then invoke the result .
36,804
public static void main ( String [ ] args ) throws Exception { File [ ] fs = new File ( "./bin" ) . listFiles ( ) ; checkThemAll ( fs ) ; System . out . println ( "total=" + total / 1000000d ) ; }
Test entry point just goes through all the code in the bin folder
36,805
private String accessUtf8 ( int cpIndex ) { Object object = cpdata [ cpIndex ] ; if ( object instanceof String ) { return ( String ) object ; } int [ ] ptrAndLen = ( int [ ] ) object ; String value ; try { value = new String ( classbytes , ptrAndLen [ 0 ] , ptrAndLen [ 1 ] , "UTF8" ) ; } catch ( UnsupportedEncodingException e ) { throw new IllegalStateException ( "Bad data found at constant pool position " + cpIndex + " offset=" + ptrAndLen [ 0 ] + " length=" + ptrAndLen [ 1 ] , e ) ; } cpdata [ cpIndex ] = value ; return value ; }
Return the UTF8 at the specified index in the constant pool . The data found at the constant pool for that index may not have been unpacked yet if this is the first access of the string . If not unpacked the constant pool entry is a pair of ints in an array representing the offset and length within the classbytes where the UTF8 string is encoded . Once decoded the constant pool entry is flipped from an int array to a String for future fast access .
36,806
private static void computeAnyMethodDifferences ( MethodNode oMethod , MethodNode nMethod , TypeDelta td ) { MethodDelta md = new MethodDelta ( oMethod . name , oMethod . desc ) ; if ( oMethod . access != nMethod . access ) { md . setAccessChanged ( oMethod . access , nMethod . access ) ; } InsnList oInstructions = oMethod . instructions ; InsnList nInstructions = nMethod . instructions ; if ( oInstructions . size ( ) != nInstructions . size ( ) ) { md . setInstructionsChanged ( oInstructions . toArray ( ) , nInstructions . toArray ( ) ) ; } else { if ( oMethod . name . charAt ( 0 ) == '<' ) { String oInvokeSpecialDescriptor = null ; String nInvokeSpecialDescriptor = null ; int oUninitCount = 0 ; int nUninitCount = 0 ; boolean codeChange = false ; for ( int i = 0 , max = oInstructions . size ( ) ; i < max ; i ++ ) { AbstractInsnNode oInstruction = oInstructions . get ( i ) ; AbstractInsnNode nInstruction = nInstructions . get ( i ) ; if ( ! codeChange ) { if ( ! sameInstruction ( oInstruction , nInstruction ) ) { codeChange = true ; } } if ( oInstruction . getType ( ) == AbstractInsnNode . TYPE_INSN ) { if ( oInstruction . getOpcode ( ) == Opcodes . NEW ) { oUninitCount ++ ; } } if ( nInstruction . getType ( ) == AbstractInsnNode . TYPE_INSN ) { if ( nInstruction . getOpcode ( ) == Opcodes . NEW ) { nUninitCount ++ ; } } if ( oInstruction . getType ( ) == AbstractInsnNode . METHOD_INSN ) { MethodInsnNode mi = ( MethodInsnNode ) oInstruction ; if ( mi . getOpcode ( ) == INVOKESPECIAL && mi . name . equals ( "<init>" ) ) { if ( oUninitCount == 0 ) { oInvokeSpecialDescriptor = mi . desc ; } else { oUninitCount -- ; } } } if ( nInstruction . getType ( ) == AbstractInsnNode . METHOD_INSN ) { MethodInsnNode mi = ( MethodInsnNode ) nInstruction ; if ( mi . getOpcode ( ) == INVOKESPECIAL && mi . name . equals ( "<init>" ) ) { if ( nUninitCount == 0 ) { nInvokeSpecialDescriptor = mi . desc ; } else { nUninitCount -- ; } } } } if ( oInvokeSpecialDescriptor == null ) { if ( nInvokeSpecialDescriptor != null ) { md . setInvokespecialChanged ( oInvokeSpecialDescriptor , nInvokeSpecialDescriptor ) ; } } else { if ( ! oInvokeSpecialDescriptor . equals ( nInvokeSpecialDescriptor ) ) { md . setInvokespecialChanged ( oInvokeSpecialDescriptor , nInvokeSpecialDescriptor ) ; } } if ( codeChange ) { md . setCodeChanged ( oInstructions . toArray ( ) , nInstructions . toArray ( ) ) ; } } } if ( md . hasAnyChanges ( ) ) { td . addChangedMethod ( md ) ; } }
Determine if there any differences between the methods supplied . A MethodDelta object is built to record any differences and stored against the type delta .
36,807
public InputStream receiveFile ( ) throws SmackException , XMPPErrorException , InterruptedException { if ( inputStream != null ) { throw new IllegalStateException ( "Transfer already negotiated!" ) ; } try { inputStream = negotiateStream ( ) ; } catch ( XMPPErrorException e ) { setException ( e ) ; throw e ; } return inputStream ; }
Negotiates the stream method to transfer the file over and then returns the negotiated stream .
36,808
public void receiveFile ( final File file ) throws SmackException , IOException { if ( file == null ) { throw new IllegalArgumentException ( "File cannot be null" ) ; } if ( ! file . exists ( ) ) { file . createNewFile ( ) ; } if ( ! file . canWrite ( ) ) { throw new IllegalArgumentException ( "Cannot write to provided file" ) ; } Thread transferThread = new Thread ( new Runnable ( ) { public void run ( ) { try { inputStream = negotiateStream ( ) ; } catch ( Exception e ) { setStatus ( FileTransfer . Status . error ) ; setException ( e ) ; return ; } OutputStream outputStream = null ; try { outputStream = new FileOutputStream ( file ) ; setStatus ( Status . in_progress ) ; writeToStream ( inputStream , outputStream ) ; } catch ( FileNotFoundException e ) { setStatus ( Status . error ) ; setError ( Error . bad_file ) ; setException ( e ) ; } catch ( IOException e ) { setStatus ( Status . error ) ; setError ( Error . stream ) ; setException ( e ) ; } if ( getStatus ( ) . equals ( Status . in_progress ) ) { setStatus ( Status . complete ) ; } CloseableUtil . maybeClose ( inputStream , LOGGER ) ; CloseableUtil . maybeClose ( outputStream , LOGGER ) ; } } , "File Transfer " + streamID ) ; transferThread . start ( ) ; }
This method negotiates the stream and then transfer s the file over the negotiated stream . The transferred file will be saved at the provided location .
36,809
public static AudioFormat getAudioFormat ( PayloadType payloadtype ) { switch ( payloadtype . getId ( ) ) { case 0 : return new AudioFormat ( AudioFormat . ULAW_RTP ) ; case 3 : return new AudioFormat ( AudioFormat . GSM_RTP ) ; case 4 : return new AudioFormat ( AudioFormat . G723_RTP ) ; default : return null ; } }
Return a JMF AudioFormat for a given Jingle Payload type . Return null if the payload is not supported by this jmf API .
36,810
public TransportResolver getResolver ( JingleSession session ) throws XMPPException , SmackException , InterruptedException { TransportResolver resolver = createResolver ( session ) ; if ( resolver == null ) { resolver = new BasicResolver ( ) ; } resolver . initializeAndWait ( ) ; return resolver ; }
Get a new Transport Resolver to be used in a Jingle Session .
36,811
public void setInstructions ( List < String > instructions ) { synchronized ( this . instructions ) { this . instructions . clear ( ) ; this . instructions . addAll ( instructions ) ; } }
Sets the list of instructions that explain how to fill out the form and what the form is about . The dataform could include multiple instructions since each instruction could not contain newlines characters .
36,812
public void addField ( FormField field ) { String fieldVariableName = field . getVariable ( ) ; if ( fieldVariableName != null && hasField ( fieldVariableName ) ) { throw new IllegalArgumentException ( "This data form already contains a form field with the variable name '" + fieldVariableName + "'" ) ; } synchronized ( fields ) { fields . put ( fieldVariableName , field ) ; } }
Adds a new field as part of the form .
36,813
public boolean addFields ( Collection < FormField > fieldsToAdd ) { boolean fieldOverridden = false ; synchronized ( fields ) { for ( FormField field : fieldsToAdd ) { FormField previousField = fields . put ( field . getVariable ( ) , field ) ; if ( previousField != null ) { fieldOverridden = true ; } } } return fieldOverridden ; }
Add the given fields to this form .
36,814
public FormField getHiddenFormTypeField ( ) { FormField field = getField ( FormField . FORM_TYPE ) ; if ( field != null && field . getType ( ) == FormField . Type . hidden ) { return field ; } return null ; }
Returns the hidden FORM_TYPE field or null if this data form has none .
36,815
public void setAnswer ( String variable , int value ) { FormField field = getField ( variable ) ; if ( field == null ) { throw new IllegalArgumentException ( "Field not found for the specified variable name." ) ; } validateThatFieldIsText ( field ) ; setAnswer ( field , value ) ; }
Sets a new int value to a given form s field . The field whose variable matches the requested variable will be completed with the specified value . If no field could be found for the specified variable then an exception will be raised .
36,816
public void setAnswer ( String variable , boolean value ) { FormField field = getField ( variable ) ; if ( field == null ) { throw new IllegalArgumentException ( "Field not found for the specified variable name." ) ; } if ( field . getType ( ) != FormField . Type . bool ) { throw new IllegalArgumentException ( "This field is not of type boolean." ) ; } setAnswer ( field , Boolean . toString ( value ) ) ; }
Sets a new boolean value to a given form s field . The field whose variable matches the requested variable will be completed with the specified value . If no field could be found for the specified variable then an exception will be raised .
36,817
public void setDefaultAnswer ( String variable ) { if ( ! isSubmitType ( ) ) { throw new IllegalStateException ( "Cannot set an answer if the form is not of type " + "\"submit\"" ) ; } FormField field = getField ( variable ) ; if ( field != null ) { field . resetValues ( ) ; for ( CharSequence value : field . getValues ( ) ) { field . addValue ( value ) ; } } else { throw new IllegalArgumentException ( "Couldn't find a field for the specified variable." ) ; } }
Sets the default value as the value of a given form s field . The field whose variable matches the requested variable will be completed with its default value . If no field could be found for the specified variable then an exception will be raised .
36,818
public String getInstructions ( ) { StringBuilder sb = new StringBuilder ( ) ; for ( Iterator < String > it = dataForm . getInstructions ( ) . iterator ( ) ; it . hasNext ( ) ; ) { sb . append ( it . next ( ) ) ; if ( it . hasNext ( ) ) { sb . append ( '\n' ) ; } } return sb . toString ( ) ; }
Returns the instructions that explain how to fill out the form and what the form is about .
36,819
public void setInstructions ( String instructions ) { ArrayList < String > instructionsList = new ArrayList < > ( ) ; StringTokenizer st = new StringTokenizer ( instructions , "\n" ) ; while ( st . hasMoreTokens ( ) ) { instructionsList . add ( st . nextToken ( ) ) ; } dataForm . setInstructions ( instructionsList ) ; }
Sets instructions that explain how to fill out the form and what the form is about .
36,820
public synchronized void enable ( ) { ServiceDiscoveryManager . getInstanceFor ( connection ( ) ) . addFeature ( NAMESPACE ) ; StanzaFilter filter = new AndFilter ( OUTGOING_FILTER , new NotFilter ( OUTGOING_FILTER ) ) ; connection ( ) . addStanzaInterceptor ( ADD_ORIGIN_ID_INTERCEPTOR , filter ) ; }
Start appending origin - id elements to outgoing stanzas and add the feature to disco .
36,821
public void addPayloadType ( final PayloadType pt ) { synchronized ( payloads ) { if ( pt == null ) { LOGGER . severe ( "Null payload type" ) ; } else { payloads . add ( pt ) ; } } }
Adds a audio payload type to the packet .
36,822
public String [ ] getGroupArrayNames ( ) { synchronized ( groupNames ) { return Collections . unmodifiableList ( groupNames ) . toArray ( new String [ groupNames . size ( ) ] ) ; } }
Returns a String array for the group names that the roster entry belongs to .
36,823
public static synchronized ChatStateManager getInstance ( final XMPPConnection connection ) { ChatStateManager manager = INSTANCES . get ( connection ) ; if ( manager == null ) { manager = new ChatStateManager ( connection ) ; INSTANCES . put ( connection , manager ) ; } return manager ; }
Returns the ChatStateManager related to the XMPPConnection and it will create one if it does not yet exist .
36,824
public static synchronized MultiUserChatManager getInstanceFor ( XMPPConnection connection ) { MultiUserChatManager multiUserChatManager = INSTANCES . get ( connection ) ; if ( multiUserChatManager == null ) { multiUserChatManager = new MultiUserChatManager ( connection ) ; INSTANCES . put ( connection , multiUserChatManager ) ; } return multiUserChatManager ; }
Get a instance of a multi user chat manager for the given connection .
36,825
public boolean isServiceEnabled ( Jid user ) throws NoResponseException , XMPPErrorException , NotConnectedException , InterruptedException { return serviceDiscoveryManager . supportsFeature ( user , MUCInitialPresence . NAMESPACE ) ; }
Returns true if the specified user supports the Multi - User Chat protocol .
36,826
public RoomInfo getRoomInfo ( EntityBareJid room ) throws NoResponseException , XMPPErrorException , NotConnectedException , InterruptedException { DiscoverInfo info = serviceDiscoveryManager . discoverInfo ( room ) ; return new RoomInfo ( info ) ; }
Returns the discovered information of a given room without actually having to join the room . The server will provide information only for rooms that are public .
36,827
public List < DomainBareJid > getMucServiceDomains ( ) throws NoResponseException , XMPPErrorException , NotConnectedException , InterruptedException { return serviceDiscoveryManager . findServices ( MUCInitialPresence . NAMESPACE , false , false ) ; }
Returns a collection with the XMPP addresses of the Multi - User Chat services .
36,828
public boolean providesMucService ( DomainBareJid domainBareJid ) throws NoResponseException , XMPPErrorException , NotConnectedException , InterruptedException { return serviceDiscoveryManager . supportsFeature ( domainBareJid , MUCInitialPresence . NAMESPACE ) ; }
Check if the provided domain bare JID provides a MUC service .
36,829
public Map < EntityBareJid , HostedRoom > getRoomsHostedBy ( DomainBareJid serviceName ) throws NoResponseException , XMPPErrorException , NotConnectedException , InterruptedException , NotAMucServiceException { if ( ! providesMucService ( serviceName ) ) { throw new NotAMucServiceException ( serviceName ) ; } DiscoverItems discoverItems = serviceDiscoveryManager . discoverItems ( serviceName ) ; List < DiscoverItems . Item > items = discoverItems . getItems ( ) ; Map < EntityBareJid , HostedRoom > answer = new HashMap < > ( items . size ( ) ) ; for ( DiscoverItems . Item item : items ) { HostedRoom hostedRoom = new HostedRoom ( item ) ; HostedRoom previousRoom = answer . put ( hostedRoom . getJid ( ) , hostedRoom ) ; assert previousRoom == null ; } return answer ; }
Returns a Map of HostedRooms where each HostedRoom has the XMPP address of the room and the room s name . Once discovered the rooms hosted by a chat service it is possible to discover more detailed room information or join the room .
36,830
public void decline ( EntityBareJid room , EntityBareJid inviter , String reason ) throws NotConnectedException , InterruptedException { Message message = new Message ( room ) ; MUCUser mucUser = new MUCUser ( ) ; MUCUser . Decline decline = new MUCUser . Decline ( reason , inviter ) ; mucUser . setDecline ( decline ) ; message . addExtension ( mucUser ) ; connection ( ) . sendStanza ( message ) ; }
Informs the sender of an invitation that the invitee declines the invitation . The rejection will be sent to the room which in turn will forward the rejection to the inviter .
36,831
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 ) ) ; } connection . sendNonza ( responseStanza ) ; }
The server is challenging the SASL mechanism for the stanza he just sent . Send a response to the server s challenge .
36,832
public VCard loadVCard ( EntityBareJid bareJid ) throws NoResponseException , XMPPErrorException , NotConnectedException , InterruptedException { VCard vcardRequest = new VCard ( ) ; vcardRequest . setTo ( bareJid ) ; VCard result = connection ( ) . createStanzaCollectorAndSend ( vcardRequest ) . nextResultOrThrow ( ) ; return result ; }
Load VCard information for a given user .
36,833
public static void setDebuggerClass ( Class < ? extends SmackDebugger > debuggerClass ) { if ( debuggerClass == null ) { System . clearProperty ( DEBUGGER_CLASS_PROPERTY_NAME ) ; } else { System . setProperty ( DEBUGGER_CLASS_PROPERTY_NAME , debuggerClass . getCanonicalName ( ) ) ; } }
Sets custom debugger class to be created by this factory .
36,834
@ SuppressWarnings ( "unchecked" ) public static Class < SmackDebugger > getDebuggerClass ( ) { String customDebuggerClassName = getCustomDebuggerClassName ( ) ; if ( customDebuggerClassName == null ) { return getOneOfDefaultDebuggerClasses ( ) ; } else { try { return ( Class < SmackDebugger > ) Class . forName ( customDebuggerClassName ) ; } catch ( Exception e ) { LOGGER . log ( Level . WARNING , "Unable to instantiate debugger class " + customDebuggerClassName , e ) ; } } return null ; }
Returns debugger class used by this factory .
36,835
public static final String replace ( String string , String oldString , String newString ) { if ( string == null ) { return null ; } if ( newString == null ) { return string ; } int i = 0 ; if ( ( i = string . indexOf ( oldString , i ) ) >= 0 ) { char [ ] string2 = string . toCharArray ( ) ; char [ ] newString2 = newString . toCharArray ( ) ; int oLength = oldString . length ( ) ; StringBuilder buf = new StringBuilder ( string2 . length ) ; buf . append ( string2 , 0 , i ) . append ( newString2 ) ; i += oLength ; int j = i ; while ( ( i = string . indexOf ( oldString , i ) ) > 0 ) { buf . append ( string2 , j , i - j ) . append ( newString2 ) ; i += oLength ; j = i ; } buf . append ( string2 , j , string2 . length - j ) ; return buf . toString ( ) ; } return string ; }
Replaces all instances of oldString with newString in string .
36,836
public void send ( Roster roster , Jid targetUserID ) throws NotConnectedException , InterruptedException { Message msg = new Message ( targetUserID ) ; RosterExchange rosterExchange = new RosterExchange ( roster ) ; msg . addExtension ( rosterExchange ) ; XMPPConnection connection = weakRefConnection . get ( ) ; connection . sendStanza ( msg ) ; }
Sends a roster to userID . All the entries of the roster will be sent to the target user .
36,837
public void send ( RosterEntry rosterEntry , Jid targetUserID ) throws NotConnectedException , InterruptedException { Message msg = new Message ( targetUserID ) ; RosterExchange rosterExchange = new RosterExchange ( ) ; rosterExchange . addRosterEntry ( rosterEntry ) ; msg . addExtension ( rosterExchange ) ; XMPPConnection connection = weakRefConnection . get ( ) ; connection . sendStanza ( msg ) ; }
Sends a roster entry to userID .
36,838
public void send ( RosterGroup rosterGroup , Jid targetUserID ) throws NotConnectedException , InterruptedException { Message msg = new Message ( targetUserID ) ; RosterExchange rosterExchange = new RosterExchange ( ) ; for ( RosterEntry entry : rosterGroup . getEntries ( ) ) { rosterExchange . addRosterEntry ( entry ) ; } msg . addExtension ( rosterExchange ) ; XMPPConnection connection = weakRefConnection . get ( ) ; connection . sendStanza ( msg ) ; }
Sends a roster group to userID . All the entries of the group will be sent to the target user .
36,839
private void fireRosterExchangeListeners ( Jid from , Iterator < RemoteRosterEntry > remoteRosterEntries ) { RosterExchangeListener [ ] listeners ; synchronized ( rosterExchangeListeners ) { listeners = new RosterExchangeListener [ rosterExchangeListeners . size ( ) ] ; rosterExchangeListeners . toArray ( listeners ) ; } for ( RosterExchangeListener listener : listeners ) { listener . entriesReceived ( from , remoteRosterEntries ) ; } }
Fires roster exchange listeners .
36,840
public Form getSearchForm ( XMPPConnection con , DomainBareJid searchService ) throws NoResponseException , XMPPErrorException , NotConnectedException , InterruptedException { UserSearch search = new UserSearch ( ) ; search . setType ( IQ . Type . get ) ; search . setTo ( searchService ) ; IQ response = con . createStanzaCollectorAndSend ( search ) . nextResultOrThrow ( ) ; return Form . getFormFrom ( response ) ; }
Returns the form for all search fields supported by the search service .
36,841
public static String addTo ( Message message ) { if ( message . getStanzaId ( ) == null ) { message . setStanzaId ( StanzaIdUtil . newStanzaId ( ) ) ; } message . addExtension ( new DeliveryReceiptRequest ( ) ) ; return message . getStanzaId ( ) ; }
Add a delivery receipt request to an outgoing packet .
36,842
public static void publishPublicKey ( PepManager pepManager , PubkeyElement pubkeyElement , OpenPgpV4Fingerprint fingerprint ) throws InterruptedException , PubSubException . NotALeafNodeException , XMPPException . XMPPErrorException , SmackException . NotConnectedException , SmackException . NoResponseException { String keyNodeName = PEP_NODE_PUBLIC_KEY ( fingerprint ) ; PubSubManager pm = pepManager . getPepPubSubManager ( ) ; LeafNode keyNode = pm . getOrCreateLeafNode ( keyNodeName ) ; changeAccessModelIfNecessary ( keyNode , AccessModel . open ) ; List < Item > items = keyNode . getItems ( 1 ) ; if ( items . isEmpty ( ) ) { LOGGER . log ( Level . FINE , "Node " + keyNodeName + " is empty. Publish." ) ; keyNode . publish ( new PayloadItem < > ( pubkeyElement ) ) ; } else { LOGGER . log ( Level . FINE , "Node " + keyNodeName + " already contains key. Skip." ) ; } LeafNode metadataNode = pm . getOrCreateLeafNode ( PEP_NODE_PUBLIC_KEYS ) ; changeAccessModelIfNecessary ( metadataNode , AccessModel . open ) ; List < PayloadItem < PublicKeysListElement > > metadataItems = metadataNode . getItems ( 1 ) ; PublicKeysListElement . Builder builder = PublicKeysListElement . builder ( ) ; if ( ! metadataItems . isEmpty ( ) && metadataItems . get ( 0 ) . getPayload ( ) != null ) { PublicKeysListElement publishedList = metadataItems . get ( 0 ) . getPayload ( ) ; for ( PublicKeysListElement . PubkeyMetadataElement meta : publishedList . getMetadata ( ) . values ( ) ) { builder . addMetadata ( meta ) ; } } builder . addMetadata ( new PublicKeysListElement . PubkeyMetadataElement ( fingerprint , new Date ( ) ) ) ; metadataNode . publish ( new PayloadItem < > ( builder . build ( ) ) ) ; }
Publish the users OpenPGP public key to the public key node if necessary . Also announce the key to other users by updating the metadata node .
36,843
public static PublicKeysListElement fetchPubkeysList ( XMPPConnection connection ) throws InterruptedException , XMPPException . XMPPErrorException , PubSubException . NotAPubSubNodeException , PubSubException . NotALeafNodeException , SmackException . NotConnectedException , SmackException . NoResponseException { return fetchPubkeysList ( connection , null ) ; }
Consult the public key metadata node and fetch a list of all of our published OpenPGP public keys .
36,844
public static boolean deletePubkeysListNode ( PepManager pepManager ) throws XMPPException . XMPPErrorException , SmackException . NotConnectedException , InterruptedException , SmackException . NoResponseException { PubSubManager pm = pepManager . getPepPubSubManager ( ) ; return pm . deleteNode ( PEP_NODE_PUBLIC_KEYS ) ; }
Delete our metadata node .
36,845
public static boolean deleteSecretKeyNode ( PepManager pepManager ) throws XMPPException . XMPPErrorException , SmackException . NotConnectedException , InterruptedException , SmackException . NoResponseException { PubSubManager pm = pepManager . getPepPubSubManager ( ) ; return pm . deleteNode ( PEP_NODE_SECRET_KEY ) ; }
Delete the private backup node .
36,846
public Jid findRegistry ( ) throws NoResponseException , XMPPErrorException , NotConnectedException , InterruptedException { if ( preconfiguredRegistry != null ) { return preconfiguredRegistry ; } final XMPPConnection connection = connection ( ) ; ServiceDiscoveryManager sdm = ServiceDiscoveryManager . getInstanceFor ( connection ) ; List < DiscoverInfo > discoverInfos = sdm . findServicesDiscoverInfo ( Constants . IOT_DISCOVERY_NAMESPACE , true , true ) ; if ( ! discoverInfos . isEmpty ( ) ) { return discoverInfos . get ( 0 ) . getFrom ( ) ; } return null ; }
Try to find an XMPP IoT registry .
36,847
public boolean isRegistry ( BareJid jid ) throws NoResponseException , XMPPErrorException , NotConnectedException , InterruptedException { Objects . requireNonNull ( jid , "JID argument must not be null" ) ; Jid registry = findRegistry ( ) ; if ( jid . equals ( registry ) ) { return true ; } if ( usedRegistries . contains ( jid ) ) { return true ; } return false ; }
Registry utility methods
36,848
public ArrayList < STUNService > loadSTUNServers ( java . io . InputStream stunConfigStream ) { ArrayList < STUNService > serversList = new ArrayList < > ( ) ; String serverName ; int serverPort ; try { XmlPullParser parser = XmlPullParserFactory . newInstance ( ) . newPullParser ( ) ; parser . setFeature ( XmlPullParser . FEATURE_PROCESS_NAMESPACES , true ) ; parser . setInput ( stunConfigStream , "UTF-8" ) ; int eventType = parser . getEventType ( ) ; do { if ( eventType == XmlPullParser . START_TAG ) { if ( parser . getName ( ) . equals ( "stunServer" ) ) { serverName = null ; serverPort = - 1 ; parser . next ( ) ; parser . next ( ) ; serverName = parser . nextText ( ) ; parser . next ( ) ; parser . next ( ) ; try { serverPort = Integer . parseInt ( parser . nextText ( ) ) ; } catch ( Exception e ) { } if ( serverName != null && serverPort != - 1 ) { STUNService service = new STUNService ( serverName , serverPort ) ; serversList . add ( service ) ; } } } eventType = parser . next ( ) ; } while ( eventType != XmlPullParser . END_DOCUMENT ) ; } catch ( XmlPullParserException e ) { LOGGER . log ( Level . SEVERE , "Exception" , e ) ; } catch ( IOException e ) { LOGGER . log ( Level . SEVERE , "Exception" , e ) ; } currentServer = bestSTUNServer ( serversList ) ; return serversList ; }
Load the STUN configuration from a stream .
36,849
private STUNService bestSTUNServer ( ArrayList < STUNService > listServers ) { if ( listServers . isEmpty ( ) ) { return null ; } else { return listServers . get ( 0 ) ; } }
Get the best usable STUN server from a list .
36,850
public void initialize ( ) throws XMPPException { LOGGER . fine ( "Initialized" ) ; if ( ! isResolving ( ) && ! isResolved ( ) ) { if ( currentServer . isNull ( ) ) { loadSTUNServers ( ) ; } if ( ! currentServer . isNull ( ) ) { clearCandidates ( ) ; resolverThread = new Thread ( new Runnable ( ) { public void run ( ) { try { Enumeration < NetworkInterface > ifaces = NetworkInterface . getNetworkInterfaces ( ) ; String candAddress ; int candPort ; while ( ifaces . hasMoreElements ( ) ) { NetworkInterface iface = ifaces . nextElement ( ) ; Enumeration < InetAddress > iaddresses = iface . getInetAddresses ( ) ; while ( iaddresses . hasMoreElements ( ) ) { InetAddress iaddress = iaddresses . nextElement ( ) ; if ( ! iaddress . isLoopbackAddress ( ) && ! iaddress . isLinkLocalAddress ( ) ) { candAddress = null ; candPort = - 1 ; DiscoveryTest test = new DiscoveryTest ( iaddress , currentServer . getHostname ( ) , currentServer . getPort ( ) ) ; try { DiscoveryInfo di = test . test ( ) ; candAddress = di . getPublicIP ( ) != null ? di . getPublicIP ( ) . getHostAddress ( ) : null ; if ( defaultPort == 0 ) { candPort = getFreePort ( ) ; } else { candPort = defaultPort ; } if ( candAddress != null && candPort >= 0 ) { TransportCandidate candidate = new TransportCandidate . Fixed ( candAddress , candPort ) ; candidate . setLocalIp ( iaddress . getHostAddress ( ) != null ? iaddress . getHostAddress ( ) : iaddress . getHostName ( ) ) ; addCandidate ( candidate ) ; resolvedPublicIP = candidate . getIp ( ) ; resolvedLocalIP = candidate . getLocalIp ( ) ; return ; } } catch ( Exception e ) { LOGGER . log ( Level . SEVERE , "Exception" , e ) ; } } } } } catch ( SocketException e ) { LOGGER . log ( Level . SEVERE , "Exception" , e ) ; } finally { setInitialized ( ) ; } } } , "Waiting for all the transport candidates checks..." ) ; resolverThread . setName ( "STUN resolver" ) ; resolverThread . start ( ) ; } else { throw new IllegalStateException ( "No valid STUN server found." ) ; } } }
Initialize the resolver .
36,851
CipherAndAuthTag retrieveMessageKeyAndAuthTag ( OmemoDevice sender , OmemoElement element ) throws CryptoFailedException , NoRawSessionException { int keyId = omemoManager . getDeviceId ( ) ; byte [ ] unpackedKey = null ; List < CryptoFailedException > decryptExceptions = new ArrayList < > ( ) ; List < OmemoKeyElement > keys = element . getHeader ( ) . getKeys ( ) ; boolean preKey = false ; for ( OmemoKeyElement k : keys ) { if ( k . getId ( ) == keyId ) { try { unpackedKey = doubleRatchetDecrypt ( sender , k . getData ( ) ) ; preKey = k . isPreKey ( ) ; break ; } catch ( CryptoFailedException e ) { decryptExceptions . add ( e ) ; } catch ( CorruptedOmemoKeyException e ) { decryptExceptions . add ( new CryptoFailedException ( e ) ) ; } catch ( UntrustedOmemoIdentityException e ) { LOGGER . log ( Level . WARNING , "Received message from " + sender + " contained unknown identityKey. Ignore message." , e ) ; } } } if ( unpackedKey == null ) { if ( ! decryptExceptions . isEmpty ( ) ) { throw MultipleCryptoFailedException . from ( decryptExceptions ) ; } throw new CryptoFailedException ( "Transported key could not be decrypted, since no suitable message key " + "was provided. Provides keys: " + keys ) ; } byte [ ] messageKey = new byte [ 16 ] ; byte [ ] authTag = null ; if ( unpackedKey . length == 32 ) { authTag = new byte [ 16 ] ; System . arraycopy ( unpackedKey , 0 , messageKey , 0 , 16 ) ; System . arraycopy ( unpackedKey , 16 , authTag , 0 , 16 ) ; } else if ( element . isKeyTransportElement ( ) && unpackedKey . length == 16 ) { messageKey = unpackedKey ; } else { throw new CryptoFailedException ( "MessageKey has wrong length: " + unpackedKey . length + ". Probably legacy auth tag format." ) ; } return new CipherAndAuthTag ( messageKey , element . getHeader ( ) . getIv ( ) , authTag , preKey ) ; }
Try to decrypt the transported message key using the double ratchet session .
36,852
static String decryptMessageElement ( OmemoElement element , CipherAndAuthTag cipherAndAuthTag ) throws CryptoFailedException { if ( ! element . isMessageElement ( ) ) { throw new IllegalArgumentException ( "decryptMessageElement cannot decrypt OmemoElement which is no MessageElement!" ) ; } if ( cipherAndAuthTag . getAuthTag ( ) == null || cipherAndAuthTag . getAuthTag ( ) . length != 16 ) { throw new CryptoFailedException ( "AuthenticationTag is null or has wrong length: " + ( cipherAndAuthTag . getAuthTag ( ) == null ? "null" : cipherAndAuthTag . getAuthTag ( ) . length ) ) ; } byte [ ] encryptedBody = payloadAndAuthTag ( element , cipherAndAuthTag . getAuthTag ( ) ) ; try { String plaintext = new String ( cipherAndAuthTag . getCipher ( ) . doFinal ( encryptedBody ) , StringUtils . UTF8 ) ; return plaintext ; } catch ( UnsupportedEncodingException | IllegalBlockSizeException | BadPaddingException e ) { throw new CryptoFailedException ( "decryptMessageElement could not decipher message body: " + e . getMessage ( ) ) ; } }
Use the symmetric key in cipherAndAuthTag to decrypt the payload of the omemoMessage . The decrypted payload will be the body of the returned Message .
36,853
static byte [ ] payloadAndAuthTag ( OmemoElement element , byte [ ] authTag ) { if ( ! element . isMessageElement ( ) ) { throw new IllegalArgumentException ( "OmemoElement has no payload." ) ; } byte [ ] payload = new byte [ element . getPayload ( ) . length + authTag . length ] ; System . arraycopy ( element . getPayload ( ) , 0 , payload , 0 , element . getPayload ( ) . length ) ; System . arraycopy ( authTag , 0 , payload , element . getPayload ( ) . length , authTag . length ) ; return payload ; }
Return the concatenation of the payload of the OmemoElement and the given auth tag .
36,854
private void updateStatistics ( ) { statisticsTable . setValueAt ( Integer . valueOf ( receivedIQPackets ) , 0 , 1 ) ; statisticsTable . setValueAt ( Integer . valueOf ( sentIQPackets ) , 0 , 2 ) ; statisticsTable . setValueAt ( Integer . valueOf ( receivedMessagePackets ) , 1 , 1 ) ; statisticsTable . setValueAt ( Integer . valueOf ( sentMessagePackets ) , 1 , 2 ) ; statisticsTable . setValueAt ( Integer . valueOf ( receivedPresencePackets ) , 2 , 1 ) ; statisticsTable . setValueAt ( Integer . valueOf ( sentPresencePackets ) , 2 , 2 ) ; statisticsTable . setValueAt ( Integer . valueOf ( receivedOtherPackets ) , 3 , 1 ) ; statisticsTable . setValueAt ( Integer . valueOf ( sentOtherPackets ) , 3 , 2 ) ; statisticsTable . setValueAt ( Integer . valueOf ( receivedPackets ) , 4 , 1 ) ; statisticsTable . setValueAt ( Integer . valueOf ( sentPackets ) , 4 , 2 ) ; }
Updates the statistics table
36,855
private void addReadPacketToTable ( final SimpleDateFormat dateFormatter , final TopLevelStreamElement packet ) { SwingUtilities . invokeLater ( new Runnable ( ) { public void run ( ) { String messageType ; Jid from ; String stanzaId ; if ( packet instanceof Stanza ) { Stanza stanza = ( Stanza ) packet ; from = stanza . getFrom ( ) ; stanzaId = stanza . getStanzaId ( ) ; } else { from = null ; stanzaId = "(Nonza)" ; } String type = "" ; Icon packetTypeIcon ; receivedPackets ++ ; if ( packet instanceof IQ ) { packetTypeIcon = iqPacketIcon ; messageType = "IQ Received (class=" + packet . getClass ( ) . getName ( ) + ")" ; type = ( ( IQ ) packet ) . getType ( ) . toString ( ) ; receivedIQPackets ++ ; } else if ( packet instanceof Message ) { packetTypeIcon = messagePacketIcon ; messageType = "Message Received" ; type = ( ( Message ) packet ) . getType ( ) . toString ( ) ; receivedMessagePackets ++ ; } else if ( packet instanceof Presence ) { packetTypeIcon = presencePacketIcon ; messageType = "Presence Received" ; type = ( ( Presence ) packet ) . getType ( ) . toString ( ) ; receivedPresencePackets ++ ; } else { packetTypeIcon = unknownPacketTypeIcon ; messageType = packet . getClass ( ) . getName ( ) + " Received" ; receivedOtherPackets ++ ; } if ( EnhancedDebuggerWindow . MAX_TABLE_ROWS > 0 && messagesTable . getRowCount ( ) >= EnhancedDebuggerWindow . MAX_TABLE_ROWS ) { messagesTable . removeRow ( 0 ) ; } messagesTable . addRow ( new Object [ ] { XmlUtil . prettyFormatXml ( packet . toXML ( ) . toString ( ) ) , dateFormatter . format ( new Date ( ) ) , packetReceivedIcon , packetTypeIcon , messageType , stanzaId , type , "" , from } ) ; updateStatistics ( ) ; } } ) ; }
Adds the received stanza detail to the messages table .
36,856
private void addSentPacketToTable ( final SimpleDateFormat dateFormatter , final TopLevelStreamElement packet ) { SwingUtilities . invokeLater ( new Runnable ( ) { public void run ( ) { String messageType ; Jid to ; String stanzaId ; if ( packet instanceof Stanza ) { Stanza stanza = ( Stanza ) packet ; to = stanza . getTo ( ) ; stanzaId = stanza . getStanzaId ( ) ; } else { to = null ; stanzaId = "(Nonza)" ; } String type = "" ; Icon packetTypeIcon ; sentPackets ++ ; if ( packet instanceof IQ ) { packetTypeIcon = iqPacketIcon ; messageType = "IQ Sent (class=" + packet . getClass ( ) . getName ( ) + ")" ; type = ( ( IQ ) packet ) . getType ( ) . toString ( ) ; sentIQPackets ++ ; } else if ( packet instanceof Message ) { packetTypeIcon = messagePacketIcon ; messageType = "Message Sent" ; type = ( ( Message ) packet ) . getType ( ) . toString ( ) ; sentMessagePackets ++ ; } else if ( packet instanceof Presence ) { packetTypeIcon = presencePacketIcon ; messageType = "Presence Sent" ; type = ( ( Presence ) packet ) . getType ( ) . toString ( ) ; sentPresencePackets ++ ; } else { packetTypeIcon = unknownPacketTypeIcon ; messageType = packet . getClass ( ) . getName ( ) + " Sent" ; sentOtherPackets ++ ; } if ( EnhancedDebuggerWindow . MAX_TABLE_ROWS > 0 && messagesTable . getRowCount ( ) >= EnhancedDebuggerWindow . MAX_TABLE_ROWS ) { messagesTable . removeRow ( 0 ) ; } messagesTable . addRow ( new Object [ ] { XmlUtil . prettyFormatXml ( packet . toXML ( ) . toString ( ) ) , dateFormatter . format ( new Date ( ) ) , packetSentIcon , packetTypeIcon , messageType , stanzaId , type , to , "" } ) ; updateStatistics ( ) ; } } ) ; }
Adds the sent stanza detail to the messages table .
36,857
void cancel ( ) { connection . removeConnectionListener ( connListener ) ; ( ( ObservableReader ) reader ) . removeReaderListener ( readerListener ) ; ( ( ObservableWriter ) writer ) . removeWriterListener ( writerListener ) ; messagesTable = null ; }
Stops debugging the connection . Removes any listener on the connection .
36,858
private void notifyListeners ( ) { WriterListener [ ] writerListeners ; synchronized ( listeners ) { writerListeners = new WriterListener [ listeners . size ( ) ] ; listeners . toArray ( writerListeners ) ; } String str = stringBuilder . toString ( ) ; stringBuilder . setLength ( 0 ) ; for ( WriterListener writerListener : writerListeners ) { writerListener . write ( str ) ; } }
Notify that a new string has been written .
36,859
public void addWriterListener ( WriterListener writerListener ) { if ( writerListener == null ) { return ; } synchronized ( listeners ) { if ( ! listeners . contains ( writerListener ) ) { listeners . add ( writerListener ) ; } } }
Adds a writer listener to this writer that will be notified when new strings are sent .
36,860
public boolean supportsFlexibleRetrieval ( ) throws NoResponseException , XMPPErrorException , NotConnectedException , InterruptedException { return ServiceDiscoveryManager . getInstanceFor ( connection ) . serverSupportsFeature ( namespace ) ; }
Returns true if the server supports Flexible Offline Message Retrieval . When the server supports Flexible Offline Message Retrieval it is possible to get the header of the offline messages get specific messages delete specific messages etc .
36,861
public int getMessageCount ( ) throws NoResponseException , XMPPErrorException , NotConnectedException , InterruptedException { DiscoverInfo info = ServiceDiscoveryManager . getInstanceFor ( connection ) . discoverInfo ( null , namespace ) ; Form extendedInfo = Form . getFormFrom ( info ) ; if ( extendedInfo != null ) { String value = extendedInfo . getField ( "number_of_messages" ) . getFirstValue ( ) ; return Integer . parseInt ( value ) ; } return 0 ; }
Returns the number of offline messages for the user of the connection .
36,862
public void deleteMessages ( List < String > nodes ) throws NoResponseException , XMPPErrorException , NotConnectedException , InterruptedException { OfflineMessageRequest request = new OfflineMessageRequest ( ) ; request . setType ( IQ . Type . set ) ; for ( String node : nodes ) { OfflineMessageRequest . Item item = new OfflineMessageRequest . Item ( node ) ; item . setAction ( "remove" ) ; request . addItem ( item ) ; } connection . createStanzaCollectorAndSend ( request ) . nextResultOrThrow ( ) ; }
Deletes the specified list of offline messages . The request will include the list of stamps that uniquely identifies the offline messages to delete .
36,863
public void deleteMessages ( ) throws NoResponseException , XMPPErrorException , NotConnectedException , InterruptedException { OfflineMessageRequest request = new OfflineMessageRequest ( ) ; request . setType ( IQ . Type . set ) ; request . setPurge ( true ) ; connection . createStanzaCollectorAndSend ( request ) . nextResultOrThrow ( ) ; }
Deletes all offline messages of the user .
36,864
public Form getSearchForm ( DomainBareJid searchService ) throws NoResponseException , XMPPErrorException , NotConnectedException , InterruptedException { return userSearch . getSearchForm ( con , searchService ) ; }
Returns the form to fill out to perform a search .
36,865
public List < DomainBareJid > getSearchServices ( ) throws NoResponseException , XMPPErrorException , NotConnectedException , InterruptedException { ServiceDiscoveryManager discoManager = ServiceDiscoveryManager . getInstanceFor ( con ) ; return discoManager . findServices ( UserSearch . NAMESPACE , false , false ) ; }
Returns a collection of search services found on the server .
36,866
public static synchronized BoBManager getInstanceFor ( XMPPConnection connection ) { BoBManager bobManager = INSTANCES . get ( connection ) ; if ( bobManager == null ) { bobManager = new BoBManager ( connection ) ; INSTANCES . put ( connection , bobManager ) ; } return bobManager ; }
Get the singleton instance of BoBManager .
36,867
public boolean isSupportedByServer ( ) throws NoResponseException , XMPPErrorException , NotConnectedException , InterruptedException { return ServiceDiscoveryManager . getInstanceFor ( connection ( ) ) . serverSupportsFeature ( NAMESPACE ) ; }
Returns true if Bits of Binary is supported by the server .
36,868
public BoBData requestBoB ( Jid to , BoBHash bobHash ) throws NotLoggedInException , NoResponseException , XMPPErrorException , NotConnectedException , InterruptedException { BoBData bobData = BOB_CACHE . lookup ( bobHash ) ; if ( bobData != null ) { return bobData ; } BoBIQ requestBoBIQ = new BoBIQ ( bobHash ) ; requestBoBIQ . setType ( Type . get ) ; requestBoBIQ . setTo ( to ) ; XMPPConnection connection = getAuthenticatedConnectionOrThrow ( ) ; BoBIQ responseBoBIQ = connection . createStanzaCollectorAndSend ( requestBoBIQ ) . nextResultOrThrow ( ) ; bobData = responseBoBIQ . getBoBData ( ) ; BOB_CACHE . put ( bobHash , bobData ) ; return bobData ; }
Request BoB data .
36,869
public static Thread go ( Runnable runnable ) { Thread thread = daemonThreadFrom ( runnable ) ; thread . start ( ) ; return thread ; }
Creates a new thread with the given Runnable marks it daemon starts it and returns the started thread .
36,870
public static Thread go ( Runnable runnable , String threadName ) { Thread thread = daemonThreadFrom ( runnable ) ; thread . setName ( threadName ) ; thread . start ( ) ; return thread ; }
Creates a new thread with the given Runnable marks it daemon sets the name starts it and returns the started thread .
36,871
public static synchronized HttpFileUploadManager getInstanceFor ( XMPPConnection connection ) { HttpFileUploadManager httpFileUploadManager = INSTANCES . get ( connection ) ; if ( httpFileUploadManager == null ) { httpFileUploadManager = new HttpFileUploadManager ( connection ) ; INSTANCES . put ( connection , httpFileUploadManager ) ; } return httpFileUploadManager ; }
Obtain the HttpFileUploadManager responsible for a connection .
36,872
public boolean discoverUploadService ( ) throws XMPPException . XMPPErrorException , SmackException . NotConnectedException , InterruptedException , SmackException . NoResponseException { ServiceDiscoveryManager sdm = ServiceDiscoveryManager . getInstanceFor ( connection ( ) ) ; List < DiscoverInfo > servicesDiscoverInfo = sdm . findServicesDiscoverInfo ( NAMESPACE , true , true ) ; if ( servicesDiscoverInfo . isEmpty ( ) ) { servicesDiscoverInfo = sdm . findServicesDiscoverInfo ( NAMESPACE_0_2 , true , true ) ; if ( servicesDiscoverInfo . isEmpty ( ) ) { return false ; } } DiscoverInfo discoverInfo = servicesDiscoverInfo . get ( 0 ) ; defaultUploadService = uploadServiceFrom ( discoverInfo ) ; return true ; }
Discover upload service .
36,873
public URL uploadFile ( File file ) throws InterruptedException , XMPPException . XMPPErrorException , SmackException , IOException { return uploadFile ( file , null ) ; }
Request slot and uploaded file to HTTP file upload service .
36,874
public URL uploadFile ( File file , UploadProgressListener listener ) throws InterruptedException , XMPPException . XMPPErrorException , SmackException , IOException { if ( ! file . isFile ( ) ) { throw new FileNotFoundException ( "The path " + file . getAbsolutePath ( ) + " is not a file" ) ; } final Slot slot = requestSlot ( file . getName ( ) , file . length ( ) , "application/octet-stream" ) ; uploadFile ( file , slot , listener ) ; return slot . getGetUrl ( ) ; }
Request slot and uploaded file to HTTP file upload service with progress callback .
36,875
public Slot requestSlot ( String filename , long fileSize , String contentType , DomainBareJid uploadServiceAddress ) throws SmackException , InterruptedException , XMPPException . XMPPErrorException { final XMPPConnection connection = connection ( ) ; final UploadService defaultUploadService = this . defaultUploadService ; UploadService uploadService ; if ( uploadServiceAddress == null ) { uploadService = defaultUploadService ; } else { if ( defaultUploadService != null && defaultUploadService . getAddress ( ) . equals ( uploadServiceAddress ) ) { uploadService = defaultUploadService ; } else { DiscoverInfo discoverInfo = ServiceDiscoveryManager . getInstanceFor ( connection ) . discoverInfo ( uploadServiceAddress ) ; if ( ! containsHttpFileUploadNamespace ( discoverInfo ) ) { throw new IllegalArgumentException ( "There is no HTTP upload service running at the given address '" + uploadServiceAddress + '\'' ) ; } uploadService = uploadServiceFrom ( discoverInfo ) ; } } if ( uploadService == null ) { throw new SmackException . SmackMessageException ( "No upload service specified and also none discovered." ) ; } if ( ! uploadService . acceptsFileOfSize ( fileSize ) ) { throw new IllegalArgumentException ( "Requested file size " + fileSize + " is greater than max allowed size " + uploadService . getMaxFileSize ( ) ) ; } SlotRequest slotRequest ; switch ( uploadService . getVersion ( ) ) { case v0_3 : slotRequest = new SlotRequest ( uploadService . getAddress ( ) , filename , fileSize , contentType ) ; break ; case v0_2 : slotRequest = new SlotRequest_V0_2 ( uploadService . getAddress ( ) , filename , fileSize , contentType ) ; break ; default : throw new AssertionError ( ) ; } return connection . createStanzaCollectorAndSend ( slotRequest ) . nextResultOrThrow ( ) ; }
Request a new upload slot with optional content type from custom upload service .
36,876
public static synchronized MultiUserChatLightManager getInstanceFor ( XMPPConnection connection ) { MultiUserChatLightManager multiUserChatLightManager = INSTANCES . get ( connection ) ; if ( multiUserChatLightManager == null ) { multiUserChatLightManager = new MultiUserChatLightManager ( connection ) ; INSTANCES . put ( connection , multiUserChatLightManager ) ; } return multiUserChatLightManager ; }
Get a instance of a MUC Light manager for the given connection .
36,877
public synchronized MultiUserChatLight getMultiUserChatLight ( EntityBareJid jid ) { WeakReference < MultiUserChatLight > weakRefMultiUserChat = multiUserChatLights . get ( jid ) ; if ( weakRefMultiUserChat == null ) { return createNewMucLightAndAddToMap ( jid ) ; } MultiUserChatLight multiUserChatLight = weakRefMultiUserChat . get ( ) ; if ( multiUserChatLight == null ) { return createNewMucLightAndAddToMap ( jid ) ; } return multiUserChatLight ; }
Obtain the MUC Light .
36,878
public boolean isFeatureSupported ( DomainBareJid mucLightService ) throws NoResponseException , XMPPErrorException , NotConnectedException , InterruptedException { return ServiceDiscoveryManager . getInstanceFor ( connection ( ) ) . discoverInfo ( mucLightService ) . containsFeature ( MultiUserChatLight . NAMESPACE ) ; }
Returns true if Multi - User Chat Light feature is supported by the server .
36,879
public List < Jid > getOccupiedRooms ( DomainBareJid mucLightService ) throws NoResponseException , XMPPErrorException , NotConnectedException , InterruptedException { DiscoverItems result = ServiceDiscoveryManager . getInstanceFor ( connection ( ) ) . discoverItems ( mucLightService ) ; List < DiscoverItems . Item > items = result . getItems ( ) ; List < Jid > answer = new ArrayList < > ( items . size ( ) ) ; for ( DiscoverItems . Item item : items ) { Jid mucLight = item . getEntityID ( ) ; answer . add ( mucLight ) ; } return answer ; }
Returns a List of the rooms the user occupies .
36,880
public List < DomainBareJid > getLocalServices ( ) throws NoResponseException , XMPPErrorException , NotConnectedException , InterruptedException { ServiceDiscoveryManager sdm = ServiceDiscoveryManager . getInstanceFor ( connection ( ) ) ; return sdm . findServices ( MultiUserChatLight . NAMESPACE , false , false ) ; }
Returns a collection with the XMPP addresses of the MUC Light services .
36,881
public List < Jid > getUsersAndRoomsBlocked ( DomainBareJid mucLightService ) throws NoResponseException , XMPPErrorException , NotConnectedException , InterruptedException { MUCLightBlockingIQ muclIghtBlockingIQResult = getBlockingList ( mucLightService ) ; List < Jid > jids = new ArrayList < > ( ) ; if ( muclIghtBlockingIQResult . getRooms ( ) != null ) { jids . addAll ( muclIghtBlockingIQResult . getRooms ( ) . keySet ( ) ) ; } if ( muclIghtBlockingIQResult . getUsers ( ) != null ) { jids . addAll ( muclIghtBlockingIQResult . getUsers ( ) . keySet ( ) ) ; } return jids ; }
Get users and rooms blocked .
36,882
public List < Jid > getRoomsBlocked ( DomainBareJid mucLightService ) throws NoResponseException , XMPPErrorException , NotConnectedException , InterruptedException { MUCLightBlockingIQ mucLightBlockingIQResult = getBlockingList ( mucLightService ) ; List < Jid > jids = new ArrayList < > ( ) ; if ( mucLightBlockingIQResult . getRooms ( ) != null ) { jids . addAll ( mucLightBlockingIQResult . getRooms ( ) . keySet ( ) ) ; } return jids ; }
Get rooms blocked .
36,883
public void blockRoom ( DomainBareJid mucLightService , Jid roomJid ) throws NoResponseException , XMPPErrorException , NotConnectedException , InterruptedException { HashMap < Jid , Boolean > rooms = new HashMap < > ( ) ; rooms . put ( roomJid , false ) ; sendBlockRooms ( mucLightService , rooms ) ; }
Block a room .
36,884
public void blockRooms ( DomainBareJid mucLightService , List < Jid > roomsJids ) throws NoResponseException , XMPPErrorException , NotConnectedException , InterruptedException { HashMap < Jid , Boolean > rooms = new HashMap < > ( ) ; for ( Jid jid : roomsJids ) { rooms . put ( jid , false ) ; } sendBlockRooms ( mucLightService , rooms ) ; }
Block rooms .
36,885
public void blockUser ( DomainBareJid mucLightService , Jid userJid ) throws NoResponseException , XMPPErrorException , NotConnectedException , InterruptedException { HashMap < Jid , Boolean > users = new HashMap < > ( ) ; users . put ( userJid , false ) ; sendBlockUsers ( mucLightService , users ) ; }
Block a user .
36,886
public void blockUsers ( DomainBareJid mucLightService , List < Jid > usersJids ) throws NoResponseException , XMPPErrorException , NotConnectedException , InterruptedException { HashMap < Jid , Boolean > users = new HashMap < > ( ) ; for ( Jid jid : usersJids ) { users . put ( jid , false ) ; } sendBlockUsers ( mucLightService , users ) ; }
Block users .
36,887
public void unblockRoom ( DomainBareJid mucLightService , Jid roomJid ) throws NoResponseException , XMPPErrorException , NotConnectedException , InterruptedException { HashMap < Jid , Boolean > rooms = new HashMap < > ( ) ; rooms . put ( roomJid , true ) ; sendUnblockRooms ( mucLightService , rooms ) ; }
Unblock a room .
36,888
public void unblockRooms ( DomainBareJid mucLightService , List < Jid > roomsJids ) throws NoResponseException , XMPPErrorException , NotConnectedException , InterruptedException { HashMap < Jid , Boolean > rooms = new HashMap < > ( ) ; for ( Jid jid : roomsJids ) { rooms . put ( jid , true ) ; } sendUnblockRooms ( mucLightService , rooms ) ; }
Unblock rooms .
36,889
public void unblockUser ( DomainBareJid mucLightService , Jid userJid ) throws NoResponseException , XMPPErrorException , NotConnectedException , InterruptedException { HashMap < Jid , Boolean > users = new HashMap < > ( ) ; users . put ( userJid , true ) ; sendUnblockUsers ( mucLightService , users ) ; }
Unblock a user .
36,890
public void unblockUsers ( DomainBareJid mucLightService , List < Jid > usersJids ) throws NoResponseException , XMPPErrorException , NotConnectedException , InterruptedException { HashMap < Jid , Boolean > users = new HashMap < > ( ) ; for ( Jid jid : usersJids ) { users . put ( jid , true ) ; } sendUnblockUsers ( mucLightService , users ) ; }
Unblock users .
36,891
public static void addPrivateDataProvider ( String elementName , String namespace , PrivateDataProvider provider ) { String key = XmppStringUtils . generateKey ( elementName , namespace ) ; privateDataProviders . put ( key , provider ) ; }
Adds a private data provider with the specified element name and name space . The provider will override any providers loaded through the classpath .
36,892
public static void removePrivateDataProvider ( String elementName , String namespace ) { String key = XmppStringUtils . generateKey ( elementName , namespace ) ; privateDataProviders . remove ( key ) ; }
Removes a private data provider with the specified element name and namespace .
36,893
public void setPrivateData ( final PrivateData privateData ) throws NoResponseException , XMPPErrorException , NotConnectedException , InterruptedException { IQ privateDataSet = new PrivateDataIQ ( privateData ) ; connection ( ) . createStanzaCollectorAndSend ( privateDataSet ) . nextResultOrThrow ( ) ; }
Sets a private data value . Each chunk of private data is uniquely identified by an element name and namespace pair . If private data has already been set with the element name and namespace then the new private data will overwrite the old value .
36,894
public boolean isSupported ( ) throws NoResponseException , NotConnectedException , InterruptedException , XMPPErrorException { try { setPrivateData ( DUMMY_PRIVATE_DATA ) ; return true ; } catch ( XMPPErrorException e ) { if ( e . getStanzaError ( ) . getCondition ( ) == Condition . service_unavailable ) { return false ; } else { throw e ; } } }
Check if the service supports private data .
36,895
static void moveAuthTag ( byte [ ] messageKey , byte [ ] cipherText , byte [ ] messageKeyWithAuthTag , byte [ ] cipherTextWithoutAuthTag ) { if ( messageKeyWithAuthTag . length != messageKey . length + 16 ) { throw new IllegalArgumentException ( "Length of messageKeyWithAuthTag must be length of messageKey + " + "length of AuthTag (16)" ) ; } if ( cipherTextWithoutAuthTag . length != cipherText . length - 16 ) { throw new IllegalArgumentException ( "Length of cipherTextWithoutAuthTag must be length of cipherText " + "- length of AuthTag (16)" ) ; } System . arraycopy ( messageKey , 0 , messageKeyWithAuthTag , 0 , 16 ) ; System . arraycopy ( cipherText , 0 , cipherTextWithoutAuthTag , 0 , cipherTextWithoutAuthTag . length ) ; System . arraycopy ( cipherText , cipherText . length - 16 , messageKeyWithAuthTag , 16 , 16 ) ; }
Move the auth tag from the end of the cipherText to the messageKey .
36,896
public void addRecipient ( OmemoDevice contactsDevice ) throws NoIdentityKeyException , CorruptedOmemoKeyException , UndecidedOmemoIdentityException , UntrustedOmemoIdentityException { OmemoFingerprint fingerprint ; fingerprint = OmemoService . getInstance ( ) . getOmemoStoreBackend ( ) . getFingerprint ( userDevice , contactsDevice ) ; switch ( trustCallback . getTrust ( contactsDevice , fingerprint ) ) { case undecided : throw new UndecidedOmemoIdentityException ( contactsDevice ) ; case trusted : CiphertextTuple encryptedKey = ratchet . doubleRatchetEncrypt ( contactsDevice , messageKey ) ; keys . add ( new OmemoKeyElement ( encryptedKey . getCiphertext ( ) , contactsDevice . getDeviceId ( ) , encryptedKey . isPreKeyMessage ( ) ) ) ; break ; case untrusted : throw new UntrustedOmemoIdentityException ( contactsDevice , fingerprint ) ; } }
Add a new recipient device to the message .
36,897
public OmemoElement finish ( ) { OmemoHeaderElement_VAxolotl header = new OmemoHeaderElement_VAxolotl ( userDevice . getDeviceId ( ) , keys , initializationVector ) ; return new OmemoElement_VAxolotl ( header , ciphertextMessage ) ; }
Assemble an OmemoMessageElement from the current state of the builder .
36,898
public static byte [ ] generateKey ( String keyType , int keyLength ) throws NoSuchAlgorithmException { KeyGenerator generator = KeyGenerator . getInstance ( keyType ) ; generator . init ( keyLength ) ; return generator . generateKey ( ) . getEncoded ( ) ; }
Generate a new AES key used to encrypt the message .
36,899
public Version getVersion ( Jid jid ) throws NoResponseException , XMPPErrorException , NotConnectedException , InterruptedException { if ( ! isSupported ( jid ) ) { return null ; } return connection ( ) . createStanzaCollectorAndSend ( new Version ( jid ) ) . nextResultOrThrow ( ) ; }
Request version information from a given JID .