idx int64 0 41.2k | question stringlengths 74 4.21k | target stringlengths 5 888 |
|---|---|---|
36,900 | public static void reply ( XMPPConnection connection , Message original , Message reply ) throws XMPPErrorException , InterruptedException , NotConnectedException , NoResponseException , FeatureNotSupportedException { MultipleRecipientInfo info = getMultipleRecipientInfo ( original ) ; if ( info == null ) { throw new IllegalArgumentException ( "Original message does not contain multiple recipient info" ) ; } if ( info . shouldNotReply ( ) ) { throw new IllegalArgumentException ( "Original message should not be replied" ) ; } if ( info . getReplyRoom ( ) != null ) { throw new IllegalArgumentException ( "Reply should be sent through a room" ) ; } if ( original . getThread ( ) != null ) { reply . setThread ( original . getThread ( ) ) ; } MultipleAddresses . Address replyAddress = info . getReplyAddress ( ) ; if ( replyAddress != null && replyAddress . getJid ( ) != null ) { reply . setTo ( replyAddress . getJid ( ) ) ; connection . sendStanza ( reply ) ; } else { List < Jid > to = new ArrayList < > ( info . getTOAddresses ( ) . size ( ) ) ; List < Jid > cc = new ArrayList < > ( info . getCCAddresses ( ) . size ( ) ) ; for ( MultipleAddresses . Address jid : info . getTOAddresses ( ) ) { to . add ( jid . getJid ( ) ) ; } for ( MultipleAddresses . Address jid : info . getCCAddresses ( ) ) { cc . add ( jid . getJid ( ) ) ; } if ( ! to . contains ( original . getFrom ( ) ) && ! cc . contains ( original . getFrom ( ) ) ) { to . add ( original . getFrom ( ) ) ; } EntityFullJid from = connection . getUser ( ) ; if ( ! to . remove ( from ) && ! cc . remove ( from ) ) { EntityBareJid bareJID = from . asEntityBareJid ( ) ; to . remove ( bareJID ) ; cc . remove ( bareJID ) ; } send ( connection , reply , to , cc , null , null , null , false ) ; } } | Sends a reply to a previously received stanza that was sent to multiple recipients . Before attempting to send the reply message some checks are performed . If any of those checks fails then an XMPPException is going to be thrown with the specific error detail . |
36,901 | private static DomainBareJid getMultipleRecipientServiceAddress ( XMPPConnection connection ) throws NoResponseException , XMPPErrorException , NotConnectedException , InterruptedException { ServiceDiscoveryManager sdm = ServiceDiscoveryManager . getInstanceFor ( connection ) ; return sdm . findService ( MultipleAddresses . NAMESPACE , true ) ; } | Returns the address of the multiple recipients service . To obtain such address service discovery is going to be used on the connected server and if none was found then another attempt will be tried on the server items . The discovered information is going to be cached for 24 hours . |
36,902 | public static DelayInformation getDelayInformation ( Stanza packet ) { DelayInformation delayInformation = getXep203DelayInformation ( packet ) ; if ( delayInformation != null ) { return delayInformation ; } return getLegacyDelayInformation ( packet ) ; } | Get Delayed Delivery information . This method first looks for a PacketExtension with the XEP - 203 namespace and falls back to the XEP - 91 namespace . |
36,903 | public static synchronized PushNotificationsManager getInstanceFor ( XMPPConnection connection ) { PushNotificationsManager pushNotificationsManager = INSTANCES . get ( connection ) ; if ( pushNotificationsManager == null ) { pushNotificationsManager = new PushNotificationsManager ( connection ) ; INSTANCES . put ( connection , pushNotificationsManager ) ; } return pushNotificationsManager ; } | Get the singleton instance of PushNotificationsManager . |
36,904 | public boolean isSupported ( ) throws NoResponseException , XMPPErrorException , NotConnectedException , InterruptedException { return ServiceDiscoveryManager . getInstanceFor ( connection ( ) ) . accountSupportsFeatures ( PushNotificationsElements . NAMESPACE ) ; } | Returns true if Push Notifications are supported by this account . |
36,905 | public boolean disableAll ( Jid pushJid ) throws NoResponseException , XMPPErrorException , NotConnectedException , InterruptedException { return disable ( pushJid , null ) ; } | Disable all push notifications . |
36,906 | public boolean disable ( Jid pushJid , String node ) throws NoResponseException , XMPPErrorException , NotConnectedException , InterruptedException { DisablePushNotificationsIQ disablePushNotificationsIQ = new DisablePushNotificationsIQ ( pushJid , node ) ; return changePushNotificationsStatus ( disablePushNotificationsIQ ) ; } | Disable push notifications of an specific node . |
36,907 | public synchronized boolean removeIdentity ( DiscoverInfo . Identity identity ) { if ( identity . equals ( this . identity ) ) return false ; identities . remove ( identity ) ; renewEntityCapsVersion ( ) ; return true ; } | Remove an identity from the client . Note that the client needs at least one identity the default identity which can not be removed . |
36,908 | public Set < DiscoverInfo . Identity > getIdentities ( ) { Set < Identity > res = new HashSet < > ( identities ) ; res . add ( identity ) ; return Collections . unmodifiableSet ( res ) ; } | Returns all identities of this client as unmodifiable Collection . |
36,909 | public static synchronized ServiceDiscoveryManager getInstanceFor ( XMPPConnection connection ) { ServiceDiscoveryManager sdm = instances . get ( connection ) ; if ( sdm == null ) { sdm = new ServiceDiscoveryManager ( connection ) ; instances . put ( connection , sdm ) ; } return sdm ; } | Returns the ServiceDiscoveryManager instance associated with a given XMPPConnection . |
36,910 | public synchronized void addDiscoverInfoTo ( DiscoverInfo response ) { response . addIdentities ( getIdentities ( ) ) ; for ( String feature : getFeatures ( ) ) { response . addFeature ( feature ) ; } response . addExtension ( extendedInfo ) ; } | Add discover info response data . |
36,911 | public DiscoverInfo discoverInfo ( Jid entityID ) throws NoResponseException , XMPPErrorException , NotConnectedException , InterruptedException { if ( entityID == null ) return discoverInfo ( null , null ) ; synchronized ( discoInfoLookupShortcutMechanisms ) { for ( DiscoInfoLookupShortcutMechanism discoInfoLookupShortcutMechanism : discoInfoLookupShortcutMechanisms ) { DiscoverInfo info = discoInfoLookupShortcutMechanism . getDiscoverInfoByUser ( this , entityID ) ; if ( info != null ) { return info ; } } } return discoverInfo ( entityID , null ) ; } | Returns the discovered information of a given XMPP entity addressed by its JID . Use null as entityID to query the server |
36,912 | public DiscoverInfo discoverInfo ( Jid entityID , String node ) throws NoResponseException , XMPPErrorException , NotConnectedException , InterruptedException { DiscoverInfo disco = new DiscoverInfo ( ) ; disco . setType ( IQ . Type . get ) ; disco . setTo ( entityID ) ; disco . setNode ( node ) ; Stanza result = connection ( ) . createStanzaCollectorAndSend ( disco ) . nextResultOrThrow ( ) ; return ( DiscoverInfo ) result ; } | Returns the discovered information of a given XMPP entity addressed by its JID and note attribute . Use this message only when trying to query information which is not directly addressable . |
36,913 | public DiscoverItems discoverItems ( Jid entityID ) throws NoResponseException , XMPPErrorException , NotConnectedException , InterruptedException { return discoverItems ( entityID , null ) ; } | Returns the discovered items of a given XMPP entity addressed by its JID . |
36,914 | public boolean accountSupportsFeatures ( CharSequence ... features ) throws NoResponseException , XMPPErrorException , NotConnectedException , InterruptedException { return accountSupportsFeatures ( Arrays . asList ( features ) ) ; } | Check if the given features are supported by the connection account . This means that the discovery information lookup will be performed on the bare JID of the connection managed by this ServiceDiscoveryManager . |
36,915 | public boolean accountSupportsFeatures ( Collection < ? extends CharSequence > features ) throws NoResponseException , XMPPErrorException , NotConnectedException , InterruptedException { EntityBareJid accountJid = connection ( ) . getUser ( ) . asEntityBareJid ( ) ; return supportsFeatures ( accountJid , features ) ; } | Check if the given collection of features are supported by the connection account . This means that the discovery information lookup will be performed on the bare JID of the connection managed by this ServiceDiscoveryManager . |
36,916 | public boolean supportsFeature ( Jid jid , CharSequence feature ) throws NoResponseException , XMPPErrorException , NotConnectedException , InterruptedException { return supportsFeatures ( jid , feature ) ; } | Queries the remote entity for it s features and returns true if the given feature is found . |
36,917 | public List < DiscoverInfo > findServicesDiscoverInfo ( DomainBareJid serviceName , String feature , boolean stopOnFirst , boolean useCache , Map < ? super Jid , Exception > encounteredExceptions ) throws NoResponseException , XMPPErrorException , NotConnectedException , InterruptedException { List < DiscoverInfo > serviceDiscoInfo ; if ( useCache ) { serviceDiscoInfo = services . lookup ( feature ) ; if ( serviceDiscoInfo != null ) { return serviceDiscoInfo ; } } serviceDiscoInfo = new LinkedList < > ( ) ; DiscoverInfo info ; try { info = discoverInfo ( serviceName ) ; } catch ( XMPPErrorException e ) { if ( encounteredExceptions != null ) { encounteredExceptions . put ( serviceName , e ) ; } return serviceDiscoInfo ; } if ( info . containsFeature ( feature ) ) { serviceDiscoInfo . add ( info ) ; if ( stopOnFirst ) { if ( useCache ) { services . put ( feature , serviceDiscoInfo ) ; } return serviceDiscoInfo ; } } DiscoverItems items ; try { items = discoverItems ( serviceName ) ; } catch ( XMPPErrorException e ) { if ( encounteredExceptions != null ) { encounteredExceptions . put ( serviceName , e ) ; } return serviceDiscoInfo ; } for ( DiscoverItems . Item item : items . getItems ( ) ) { Jid address = item . getEntityID ( ) ; try { info = discoverInfo ( address ) ; } catch ( XMPPErrorException | NoResponseException e ) { if ( encounteredExceptions != null ) { encounteredExceptions . put ( address , e ) ; } continue ; } if ( info . containsFeature ( feature ) ) { serviceDiscoInfo . add ( info ) ; if ( stopOnFirst ) { break ; } } } if ( useCache ) { services . put ( feature , serviceDiscoInfo ) ; } return serviceDiscoInfo ; } | Find all services under a given service that provide a given feature . |
36,918 | public DomainBareJid findProvisioningServerComponent ( ) throws NoResponseException , XMPPErrorException , NotConnectedException , InterruptedException { final XMPPConnection connection = connection ( ) ; ServiceDiscoveryManager sdm = ServiceDiscoveryManager . getInstanceFor ( connection ) ; List < DiscoverInfo > discoverInfos = sdm . findServicesDiscoverInfo ( Constants . IOT_PROVISIONING_NAMESPACE , true , true ) ; if ( discoverInfos . isEmpty ( ) ) { return null ; } Jid jid = discoverInfos . get ( 0 ) . getFrom ( ) ; assert ( jid . isDomainBareJid ( ) ) ; return jid . asDomainBareJid ( ) ; } | Try to find a provisioning server component . |
36,919 | public boolean isFriend ( Jid provisioningServer , BareJid friendInQuestion ) throws NoResponseException , XMPPErrorException , NotConnectedException , InterruptedException { LruCache < BareJid , Void > cache = negativeFriendshipRequestCache . lookup ( provisioningServer ) ; if ( cache != null && cache . containsKey ( friendInQuestion ) ) { return false ; } IoTIsFriend iotIsFriend = new IoTIsFriend ( friendInQuestion ) ; iotIsFriend . setTo ( provisioningServer ) ; IoTIsFriendResponse response = connection ( ) . createStanzaCollectorAndSend ( iotIsFriend ) . nextResultOrThrow ( ) ; assert ( response . getJid ( ) . equals ( friendInQuestion ) ) ; boolean isFriend = response . getIsFriendResult ( ) ; if ( ! isFriend ) { if ( cache == null ) { cache = new LruCache < > ( 1024 ) ; negativeFriendshipRequestCache . put ( provisioningServer , cache ) ; } cache . put ( friendInQuestion , null ) ; } return isFriend ; } | As the given provisioning server is the given JID is a friend . |
36,920 | public void disconnect ( ) { Presence unavailablePresence = null ; if ( isAuthenticated ( ) ) { unavailablePresence = new Presence ( Presence . Type . unavailable ) ; } try { disconnect ( unavailablePresence ) ; } catch ( NotConnectedException e ) { LOGGER . log ( Level . FINEST , "Connection is already disconnected" , e ) ; } } | Closes the connection by setting presence to unavailable then closing the connection to the XMPP server . The XMPPConnection can still be used for connecting to the server again . |
36,921 | public synchronized void disconnect ( Presence unavailablePresence ) throws NotConnectedException { if ( unavailablePresence != null ) { try { sendStanza ( unavailablePresence ) ; } catch ( InterruptedException e ) { LOGGER . log ( Level . FINE , "Was interrupted while sending unavailable presence. Continuing to disconnect the connection" , e ) ; } } shutdown ( ) ; callConnectionClosedListener ( ) ; } | Closes the connection . A custom unavailable presence is sent to the server followed by closing the stream . The XMPPConnection can still be used for connecting to the server again . A custom unavailable presence is useful for communicating offline presence information such as On vacation . Typically just the status text of the presence stanza is set with online information but most XMPP servers will deliver the full presence stanza with whatever data is set . |
36,922 | protected final void notifyConnectionError ( final Exception exception ) { if ( ! isConnected ( ) ) { LOGGER . log ( Level . INFO , "Connection was already disconnected when attempting to handle " + exception , exception ) ; return ; } ASYNC_BUT_ORDERED . performAsyncButOrdered ( this , ( ) -> { currentConnectionException = exception ; for ( StanzaCollector collector : collectors ) { collector . notifyConnectionError ( exception ) ; } SmackWrappedException smackWrappedException = new SmackWrappedException ( exception ) ; tlsHandled . reportGenericFailure ( smackWrappedException ) ; saslFeatureReceived . reportGenericFailure ( smackWrappedException ) ; lastFeaturesReceived . reportGenericFailure ( smackWrappedException ) ; synchronized ( AbstractXMPPConnection . this ) { notifyAll ( ) ; instantShutdown ( ) ; } Async . go ( ( ) -> { callConnectionClosedOnErrorListener ( exception ) ; } , AbstractXMPPConnection . this + " callConnectionClosedOnErrorListener()" ) ; } ) ; } | Sends out a notification that there was an error with the connection and closes the connection . |
36,923 | private void firePacketInterceptors ( Stanza packet ) { List < StanzaListener > interceptorsToInvoke = new LinkedList < > ( ) ; synchronized ( interceptors ) { for ( InterceptorWrapper interceptorWrapper : interceptors . values ( ) ) { if ( interceptorWrapper . filterMatches ( packet ) ) { interceptorsToInvoke . add ( interceptorWrapper . getInterceptor ( ) ) ; } } } for ( StanzaListener interceptor : interceptorsToInvoke ) { try { interceptor . processStanza ( packet ) ; } catch ( Exception e ) { LOGGER . log ( Level . SEVERE , "Packet interceptor threw exception" , e ) ; } } } | Process interceptors . Interceptors may modify the stanza that is about to be sent . Since the thread that requested to send the stanza will invoke all interceptors it is important that interceptors perform their work as soon as possible so that the thread does not remain blocked for a long period . |
36,924 | protected void processStanza ( final Stanza stanza ) throws InterruptedException { assert ( stanza != null ) ; final SmackDebugger debugger = this . debugger ; if ( debugger != null ) { debugger . onIncomingStreamElement ( stanza ) ; } lastStanzaReceived = System . currentTimeMillis ( ) ; invokeStanzaCollectorsAndNotifyRecvListeners ( stanza ) ; } | Processes a stanza after it s been fully parsed by looping through the installed stanza collectors and listeners and letting them examine the stanza to see if they are a match with the filter . |
36,925 | protected void send ( ComposableBody body ) throws BOSHException { if ( ! connected ) { throw new IllegalStateException ( "Not connected to a server!" ) ; } if ( body == null ) { throw new NullPointerException ( "Body mustn't be null!" ) ; } if ( sessionID != null ) { body = body . rebuild ( ) . setAttribute ( BodyQName . create ( BOSH_URI , "sid" ) , sessionID ) . build ( ) ; } client . send ( body ) ; } | Send a HTTP request to the connection manager with the provided body element . |
36,926 | protected void initDebugger ( ) { writer = new Writer ( ) { public void write ( char [ ] cbuf , int off , int len ) { } public void close ( ) { } public void flush ( ) { } } ; try { readerPipe = new PipedWriter ( ) ; reader = new PipedReader ( readerPipe ) ; } catch ( IOException e ) { } super . initDebugger ( ) ; client . addBOSHClientResponseListener ( new BOSHClientResponseListener ( ) { public void responseReceived ( BOSHMessageEvent event ) { if ( event . getBody ( ) != null ) { try { readerPipe . write ( event . getBody ( ) . toXML ( ) ) ; readerPipe . flush ( ) ; } catch ( Exception e ) { } } } } ) ; client . addBOSHClientRequestListener ( new BOSHClientRequestListener ( ) { public void requestSent ( BOSHMessageEvent event ) { if ( event . getBody ( ) != null ) { try { writer . write ( event . getBody ( ) . toXML ( ) ) ; } catch ( Exception e ) { } } } } ) ; readerConsumer = new Thread ( ) { private Thread thread = this ; private int bufferLength = 1024 ; public void run ( ) { try { char [ ] cbuf = new char [ bufferLength ] ; while ( readerConsumer == thread && ! done ) { reader . read ( cbuf , 0 , bufferLength ) ; } } catch ( IOException e ) { } } } ; readerConsumer . setDaemon ( true ) ; readerConsumer . start ( ) ; } | Initialize the SmackDebugger which allows to log and debug XML traffic . |
36,927 | public String toXML ( org . jivesoftware . smack . packet . XmlEnvironment enclosingNamespace ) { StringBuilder buf = new StringBuilder ( ) ; buf . append ( '<' ) . append ( getElementName ( ) ) . append ( " xmlns=\"" ) ; buf . append ( getNamespace ( ) ) . append ( "\" " ) ; synchronized ( candidates ) { if ( getCandidatesCount ( ) > 0 ) { buf . append ( '>' ) ; Iterator < JingleTransportCandidate > iter = getCandidates ( ) ; while ( iter . hasNext ( ) ) { JingleTransportCandidate candidate = iter . next ( ) ; buf . append ( candidate . toXML ( ) ) ; } buf . append ( "</" ) . append ( getElementName ( ) ) . append ( '>' ) ; } else { buf . append ( "/>" ) ; } } return buf . toString ( ) ; } | Return the XML representation for this element . |
36,928 | public boolean setRosterStore ( RosterStore rosterStore ) { this . rosterStore = rosterStore ; try { reload ( ) ; } catch ( InterruptedException | NotLoggedInException | NotConnectedException e ) { LOGGER . log ( Level . FINER , "Could not reload roster" , e ) ; return false ; } return true ; } | Set the roster store may cause a roster reload . |
36,929 | public void createItemAndRequestSubscription ( BareJid jid , String name , String [ ] groups ) throws NotLoggedInException , NoResponseException , XMPPErrorException , NotConnectedException , InterruptedException { createItem ( jid , name , groups ) ; sendSubscriptionRequest ( jid ) ; } | Creates a new roster entry and presence subscription . The server will asynchronously update the roster with the subscription status . |
36,930 | public void preApproveAndCreateEntry ( BareJid user , String name , String [ ] groups ) throws NotLoggedInException , NoResponseException , XMPPErrorException , NotConnectedException , InterruptedException , FeatureNotSupportedException { preApprove ( user ) ; createItemAndRequestSubscription ( user , name , groups ) ; } | Creates a new pre - approved roster entry and presence subscription . The server will asynchronously update the roster with the subscription status . |
36,931 | public void preApprove ( BareJid user ) throws NotLoggedInException , NotConnectedException , InterruptedException , FeatureNotSupportedException { final XMPPConnection connection = connection ( ) ; if ( ! isSubscriptionPreApprovalSupported ( ) ) { throw new FeatureNotSupportedException ( "Pre-approving" ) ; } Presence presencePacket = new Presence ( Presence . Type . subscribed ) ; presencePacket . setTo ( user ) ; connection . sendStanza ( presencePacket ) ; } | Pre - approve user presence subscription . |
36,932 | public boolean isSubscriptionPreApprovalSupported ( ) throws NotLoggedInException { final XMPPConnection connection = getAuthenticatedConnectionOrThrow ( ) ; return connection . hasFeature ( SubscriptionPreApproval . ELEMENT , SubscriptionPreApproval . NAMESPACE ) ; } | Check for subscription pre - approval support . |
36,933 | public boolean removeSubscribeListener ( SubscribeListener subscribeListener ) { boolean removed = subscribeListeners . remove ( subscribeListener ) ; if ( removed && subscribeListeners . isEmpty ( ) ) { setSubscriptionMode ( previousSubscriptionMode ) ; } return removed ; } | Remove a subscribe listener . Also restores the previous subscription mode state if the last listener got removed . |
36,934 | public Set < RosterEntry > getEntries ( ) { Set < RosterEntry > allEntries ; synchronized ( rosterListenersAndEntriesLock ) { allEntries = new HashSet < > ( entries . size ( ) ) ; for ( RosterEntry entry : entries . values ( ) ) { allEntries . add ( entry ) ; } } return allEntries ; } | Returns a set of all entries in the roster including entries that don t belong to any groups . |
36,935 | public Presence getPresenceResource ( FullJid userWithResource ) { BareJid key = userWithResource . asBareJid ( ) ; Resourcepart resource = userWithResource . getResourcepart ( ) ; Map < Resourcepart , Presence > userPresences = getPresencesInternal ( key ) ; if ( userPresences == null ) { Presence presence = new Presence ( Presence . Type . unavailable ) ; presence . setFrom ( userWithResource ) ; return presence ; } else { Presence presence = userPresences . get ( resource ) ; if ( presence == null ) { presence = new Presence ( Presence . Type . unavailable ) ; presence . setFrom ( userWithResource ) ; return presence ; } else { return presence . clone ( ) ; } } } | Returns the presence info for a particular user s resource or unavailable presence if the user is offline or if no presence information is available such as when you are not subscribed to the user s presence updates . |
36,936 | public List < Presence > getAllPresences ( BareJid bareJid ) { Map < Resourcepart , Presence > userPresences = getPresencesInternal ( bareJid ) ; List < Presence > res ; if ( userPresences == null ) { Presence unavailable = new Presence ( Presence . Type . unavailable ) ; unavailable . setFrom ( bareJid ) ; res = new ArrayList < > ( Arrays . asList ( unavailable ) ) ; } else { res = new ArrayList < > ( userPresences . values ( ) . size ( ) ) ; for ( Presence presence : userPresences . values ( ) ) { res . add ( presence . clone ( ) ) ; } } return res ; } | Returns a List of Presence objects for all of a user s current presences if no presence information is available such as when you are not subscribed to the user s presence updates . |
36,937 | public boolean iAmSubscribedTo ( Jid jid ) { if ( jid == null ) { return false ; } BareJid bareJid = jid . asBareJid ( ) ; RosterEntry entry = getEntry ( bareJid ) ; if ( entry == null ) { return false ; } return entry . canSeeHisPresence ( ) ; } | Check if the XMPP entity this roster belongs to is subscribed to the presence of the given JID . |
36,938 | private void setOfflinePresences ( ) { Presence packetUnavailable ; outerloop : for ( Jid user : presenceMap . keySet ( ) ) { Map < Resourcepart , Presence > resources = presenceMap . get ( user ) ; if ( resources != null ) { for ( Resourcepart resource : resources . keySet ( ) ) { packetUnavailable = new Presence ( Presence . Type . unavailable ) ; EntityBareJid bareUserJid = user . asEntityBareJidIfPossible ( ) ; if ( bareUserJid == null ) { LOGGER . warning ( "Can not transform user JID to bare JID: '" + user + "'" ) ; continue ; } packetUnavailable . setFrom ( JidCreate . fullFrom ( bareUserJid , resource ) ) ; try { presencePacketListener . processStanza ( packetUnavailable ) ; } catch ( NotConnectedException e ) { throw new IllegalStateException ( "presencePacketListener should never throw a NotConnectedException when processStanza is called with a presence of type unavailable" , e ) ; } catch ( InterruptedException e ) { break outerloop ; } } } } } | Changes the presence of available contacts offline by simulating an unavailable presence sent from the server . |
36,939 | private void fireRosterPresenceEvent ( final Presence presence ) { synchronized ( rosterListenersAndEntriesLock ) { for ( RosterListener listener : rosterListeners ) { listener . presenceChanged ( presence ) ; } } } | Fires roster presence changed event to roster listeners . |
36,940 | private void removeEmptyGroups ( ) { for ( RosterGroup group : getGroups ( ) ) { if ( group . getEntryCount ( ) == 0 ) { groups . remove ( group . getName ( ) ) ; } } } | Removes all the groups with no entries . |
36,941 | private static void move ( BareJid entity , Map < BareJid , Map < Resourcepart , Presence > > from , Map < BareJid , Map < Resourcepart , Presence > > to ) { Map < Resourcepart , Presence > presences = from . remove ( entity ) ; if ( presences != null && ! presences . isEmpty ( ) ) { to . put ( entity , presences ) ; } } | Move presences from entity from one presence map to another . |
36,942 | private static boolean hasValidSubscriptionType ( RosterPacket . Item item ) { switch ( item . getItemType ( ) ) { case none : case from : case to : case both : return true ; default : return false ; } } | Ignore ItemTypes as of RFC 6121 2 . 1 . 2 . 5 . |
36,943 | public void addReaderListener ( ReaderListener readerListener ) { if ( readerListener == null ) { return ; } synchronized ( listeners ) { if ( ! listeners . contains ( readerListener ) ) { listeners . add ( readerListener ) ; } } } | Adds a reader listener to this reader that will be notified when new strings are read . |
36,944 | protected void shutdown ( ) { if ( isSmEnabled ( ) ) { try { sendSmAcknowledgementInternal ( ) ; } catch ( InterruptedException | NotConnectedException e ) { LOGGER . log ( Level . FINE , "Can not send final SM ack as connection is not connected" , e ) ; } } shutdown ( false ) ; } | Shuts the current connection down . After this method returns the connection must be ready for re - use by connect . |
36,945 | private void initConnection ( ) throws IOException , InterruptedException { compressionHandler = null ; initReaderAndWriter ( ) ; int availableReaderWriterSemaphorePermits = readerWriterSemaphore . availablePermits ( ) ; if ( availableReaderWriterSemaphorePermits < 2 ) { Object [ ] logObjects = new Object [ ] { this , availableReaderWriterSemaphorePermits , } ; LOGGER . log ( Level . FINE , "Not every reader/writer threads where terminated on connection re-initializtion of {0}. Available permits {1}" , logObjects ) ; } readerWriterSemaphore . acquire ( 2 ) ; packetWriter . init ( ) ; packetReader . init ( ) ; } | Initializes the connection by creating a stanza reader and writer and opening a XMPP stream to the server . |
36,946 | @ SuppressWarnings ( "LiteralClassName" ) private void proceedTLSReceived ( ) throws NoSuchAlgorithmException , CertificateException , IOException , KeyStoreException , NoSuchProviderException , UnrecoverableKeyException , KeyManagementException , SmackException { SmackTlsContext smackTlsContext = getSmackTlsContext ( ) ; Socket plain = socket ; socket = smackTlsContext . sslContext . getSocketFactory ( ) . createSocket ( plain , config . getXMPPServiceDomain ( ) . toString ( ) , plain . getPort ( ) , true ) ; final SSLSocket sslSocket = ( SSLSocket ) socket ; TLSUtils . setEnabledProtocolsAndCiphers ( sslSocket , config . getEnabledSSLProtocols ( ) , config . getEnabledSSLCiphers ( ) ) ; initReaderAndWriter ( ) ; sslSocket . startHandshake ( ) ; if ( smackTlsContext . daneVerifier != null ) { smackTlsContext . daneVerifier . finish ( sslSocket . getSession ( ) ) ; } final HostnameVerifier verifier = getConfiguration ( ) . getHostnameVerifier ( ) ; if ( verifier == null ) { throw new IllegalStateException ( "No HostnameVerifier set. Use connectionConfiguration.setHostnameVerifier() to configure." ) ; } else if ( ! verifier . verify ( getXMPPServiceDomain ( ) . toString ( ) , sslSocket . getSession ( ) ) ) { throw new CertificateException ( "Hostname verification of certificate failed. Certificate does not authenticate " + getXMPPServiceDomain ( ) ) ; } secureSocket = sslSocket ; } | The server has indicated that TLS negotiation can start . We now need to secure the existing plain connection and perform a handshake . This method won t return until the connection has finished the handshake or an error occurred while securing the connection . |
36,947 | private static XMPPInputOutputStream maybeGetCompressionHandler ( Compress . Feature compression ) { for ( XMPPInputOutputStream handler : SmackConfiguration . getCompressionHandlers ( ) ) { String method = handler . getCompressionMethod ( ) ; if ( compression . getMethods ( ) . contains ( method ) ) return handler ; } return null ; } | Returns the compression handler that can be used for one compression methods offered by the server . |
36,948 | void openStream ( ) throws SmackException , InterruptedException , XmlPullParserException { sendStreamOpen ( ) ; packetReader . parser = PacketParserUtils . newXmppParser ( reader ) ; } | Resets the parser using the latest connection s reader . Resetting the parser is necessary when the plain connection has been secured or when a new opening stream element is going to be sent by the server . |
36,949 | public boolean isSmResumptionPossible ( ) { if ( smSessionId == null ) return false ; final Long shutdownTimestamp = packetWriter . shutdownTimestamp ; if ( shutdownTimestamp == null ) { return true ; } long current = System . currentTimeMillis ( ) ; long maxResumptionMillies = ( ( long ) getMaxSmResumptionTime ( ) ) * 1000 ; if ( current > shutdownTimestamp + maxResumptionMillies ) { return false ; } else { return true ; } } | Returns true if the stream is resumable . |
36,950 | public static synchronized OmemoManager getInstanceFor ( XMPPConnection connection , Integer deviceId ) { if ( deviceId == null || deviceId < 1 ) { throw new IllegalArgumentException ( "DeviceId MUST NOT be null and MUST be greater than 0." ) ; } TreeMap < Integer , OmemoManager > managersOfConnection = INSTANCES . get ( connection ) ; if ( managersOfConnection == null ) { managersOfConnection = new TreeMap < > ( ) ; INSTANCES . put ( connection , managersOfConnection ) ; } OmemoManager manager = managersOfConnection . get ( deviceId ) ; if ( manager == null ) { manager = new OmemoManager ( connection , deviceId ) ; managersOfConnection . put ( deviceId , manager ) ; } return manager ; } | Return an OmemoManager instance for the given connection and deviceId . If there was an OmemoManager for the connection and id before return it . Otherwise create a new OmemoManager instance and return it . |
36,951 | public static synchronized OmemoManager getInstanceFor ( XMPPConnection connection ) { TreeMap < Integer , OmemoManager > managers = INSTANCES . get ( connection ) ; if ( managers == null ) { managers = new TreeMap < > ( ) ; INSTANCES . put ( connection , managers ) ; } OmemoManager manager ; if ( managers . size ( ) == 0 ) { manager = new OmemoManager ( connection , UNKNOWN_DEVICE_ID ) ; managers . put ( UNKNOWN_DEVICE_ID , manager ) ; } else { manager = managers . get ( managers . firstKey ( ) ) ; } return manager ; } | Returns an OmemoManager instance for the given connection . If there was one manager for the connection before return it . If there were multiple managers before return the one with the lowest deviceId . If there was no manager before return a new one . As soon as the connection gets authenticated the manager will look for local deviceIDs and select the lowest one as its id . If there are not local deviceIds the manager will assign itself a random id . |
36,952 | public void initialize ( ) throws SmackException . NotLoggedInException , CorruptedOmemoKeyException , InterruptedException , SmackException . NoResponseException , SmackException . NotConnectedException , XMPPException . XMPPErrorException , PubSubException . NotALeafNodeException { synchronized ( LOCK ) { if ( ! connection ( ) . isAuthenticated ( ) ) { throw new SmackException . NotLoggedInException ( ) ; } if ( getTrustCallback ( ) == null ) { throw new IllegalStateException ( "No TrustCallback set." ) ; } getOmemoService ( ) . init ( new LoggedInOmemoManager ( this ) ) ; ServiceDiscoveryManager . getInstanceFor ( connection ( ) ) . addFeature ( PEP_NODE_DEVICE_LIST_NOTIFY ) ; } } | Initializes the OmemoManager . This method must be called before the manager can be used . |
36,953 | public void initializeAsync ( final InitializationFinishedCallback finishedCallback ) { Async . go ( new Runnable ( ) { public void run ( ) { try { initialize ( ) ; finishedCallback . initializationFinished ( OmemoManager . this ) ; } catch ( Exception e ) { finishedCallback . initializationFailed ( e ) ; } } } ) ; } | Initialize the manager without blocking . Once the manager is successfully initialized the finishedCallback will be notified . It will also get notified if an error occurs . |
36,954 | public Set < OmemoDevice > getDevicesOf ( BareJid contact ) { OmemoCachedDeviceList list = getOmemoService ( ) . getOmemoStoreBackend ( ) . loadCachedDeviceList ( getOwnDevice ( ) , contact ) ; HashSet < OmemoDevice > devices = new HashSet < > ( ) ; for ( int deviceId : list . getActiveDevices ( ) ) { devices . add ( new OmemoDevice ( contact , deviceId ) ) ; } return devices ; } | Return a set of all OMEMO capable devices of a contact . Note that this method does not explicitly refresh the device list of the contact so it might be outdated . |
36,955 | public OmemoMessage . Sent encrypt ( BareJid recipient , String message ) throws CryptoFailedException , UndecidedOmemoIdentityException , InterruptedException , SmackException . NotConnectedException , SmackException . NoResponseException , SmackException . NotLoggedInException { synchronized ( LOCK ) { Set < BareJid > recipients = new HashSet < > ( ) ; recipients . add ( recipient ) ; return encrypt ( recipients , message ) ; } } | OMEMO encrypt a cleartext message for a single recipient . Note that this method does NOT set the to attribute of the message . |
36,956 | public OmemoMessage . Sent encrypt ( Set < BareJid > recipients , String message ) throws CryptoFailedException , UndecidedOmemoIdentityException , InterruptedException , SmackException . NotConnectedException , SmackException . NoResponseException , SmackException . NotLoggedInException { synchronized ( LOCK ) { LoggedInOmemoManager guard = new LoggedInOmemoManager ( this ) ; Set < OmemoDevice > devices = getDevicesOf ( getOwnJid ( ) ) ; for ( BareJid recipient : recipients ) { devices . addAll ( getDevicesOf ( recipient ) ) ; } return service . createOmemoMessage ( guard , devices , message ) ; } } | OMEMO encrypt a cleartext message for multiple recipients . |
36,957 | public OmemoMessage . Sent encrypt ( MultiUserChat muc , String message ) throws UndecidedOmemoIdentityException , CryptoFailedException , XMPPException . XMPPErrorException , SmackException . NotConnectedException , InterruptedException , SmackException . NoResponseException , NoOmemoSupportException , SmackException . NotLoggedInException { synchronized ( LOCK ) { if ( ! multiUserChatSupportsOmemo ( muc ) ) { throw new NoOmemoSupportException ( ) ; } Set < BareJid > recipients = new HashSet < > ( ) ; for ( EntityFullJid e : muc . getOccupants ( ) ) { recipients . add ( muc . getOccupant ( e ) . getJid ( ) . asBareJid ( ) ) ; } return encrypt ( recipients , message ) ; } } | Encrypt a message for all recipients in the MultiUserChat . |
36,958 | public List < MessageOrOmemoMessage > decryptMamQueryResult ( MamManager . MamQuery mamQuery ) throws SmackException . NotLoggedInException { return new ArrayList < > ( getOmemoService ( ) . decryptMamQueryResult ( new LoggedInOmemoManager ( this ) , mamQuery ) ) ; } | Decrypt messages from a MAM query . |
36,959 | public void trustOmemoIdentity ( OmemoDevice device , OmemoFingerprint fingerprint ) { if ( trustCallback == null ) { throw new IllegalStateException ( "No TrustCallback set." ) ; } trustCallback . setTrust ( device , fingerprint , TrustState . trusted ) ; } | Trust that a fingerprint belongs to an OmemoDevice . The fingerprint must be the lowercase hexadecimal fingerprint of the identityKey of the device and must be of length 64 . |
36,960 | public void sendRatchetUpdateMessage ( OmemoDevice recipient ) throws SmackException . NotLoggedInException , CorruptedOmemoKeyException , InterruptedException , SmackException . NoResponseException , NoSuchAlgorithmException , SmackException . NotConnectedException , CryptoFailedException , CannotEstablishOmemoSessionException { synchronized ( LOCK ) { Message message = new Message ( ) ; message . setFrom ( getOwnJid ( ) ) ; message . setTo ( recipient . getJid ( ) ) ; OmemoElement element = getOmemoService ( ) . createRatchetUpdateElement ( new LoggedInOmemoManager ( this ) , recipient ) ; message . addExtension ( element ) ; StoreHint . set ( message ) ; connection ( ) . sendStanza ( message ) ; } } | Send a ratchet update message . This can be used to advance the ratchet of a session in order to maintain forward secrecy . |
36,961 | public boolean contactSupportsOmemo ( BareJid contact ) throws InterruptedException , PubSubException . NotALeafNodeException , XMPPException . XMPPErrorException , SmackException . NotConnectedException , SmackException . NoResponseException { synchronized ( LOCK ) { OmemoCachedDeviceList deviceList = getOmemoService ( ) . refreshDeviceList ( connection ( ) , getOwnDevice ( ) , contact ) ; return ! deviceList . getActiveDevices ( ) . isEmpty ( ) ; } } | Returns true if the contact has any active devices published in a deviceList . |
36,962 | public static boolean serverSupportsOmemo ( XMPPConnection connection , DomainBareJid server ) throws XMPPException . XMPPErrorException , SmackException . NotConnectedException , InterruptedException , SmackException . NoResponseException { return ServiceDiscoveryManager . getInstanceFor ( connection ) . discoverInfo ( server ) . containsFeature ( PubSub . NAMESPACE ) ; } | Returns true if the Server supports PEP . |
36,963 | public OmemoFingerprint getOwnFingerprint ( ) throws SmackException . NotLoggedInException , CorruptedOmemoKeyException { synchronized ( LOCK ) { if ( getOwnJid ( ) == null ) { throw new SmackException . NotLoggedInException ( ) ; } return getOmemoService ( ) . getOmemoStoreBackend ( ) . getFingerprint ( getOwnDevice ( ) ) ; } } | Return the fingerprint of our identity key . |
36,964 | public OmemoFingerprint getFingerprint ( OmemoDevice device ) throws CannotEstablishOmemoSessionException , SmackException . NotLoggedInException , CorruptedOmemoKeyException , SmackException . NotConnectedException , InterruptedException , SmackException . NoResponseException { synchronized ( LOCK ) { if ( getOwnJid ( ) == null ) { throw new SmackException . NotLoggedInException ( ) ; } if ( device . equals ( getOwnDevice ( ) ) ) { return getOwnFingerprint ( ) ; } return getOmemoService ( ) . getOmemoStoreBackend ( ) . getFingerprintAndMaybeBuildSession ( new LoggedInOmemoManager ( this ) , device ) ; } } | Get the fingerprint of a contacts device . |
36,965 | public void requestDeviceListUpdateFor ( BareJid contact ) throws InterruptedException , PubSubException . NotALeafNodeException , XMPPException . XMPPErrorException , SmackException . NotConnectedException , SmackException . NoResponseException { synchronized ( LOCK ) { getOmemoService ( ) . refreshDeviceList ( connection ( ) , getOwnDevice ( ) , contact ) ; } } | Request a deviceList update from contact contact . |
36,966 | public void purgeDeviceList ( ) throws SmackException . NotLoggedInException , InterruptedException , XMPPException . XMPPErrorException , SmackException . NotConnectedException , SmackException . NoResponseException { synchronized ( LOCK ) { getOmemoService ( ) . purgeDeviceList ( new LoggedInOmemoManager ( this ) ) ; } } | Publish a new device list with just our own deviceId in it . |
36,967 | public BareJid getOwnJid ( ) { if ( ownJid == null && connection ( ) . isAuthenticated ( ) ) { ownJid = connection ( ) . getUser ( ) . asBareJid ( ) ; } return ownJid ; } | Return the BareJid of the user . |
36,968 | public Toml read ( Reader reader ) { BufferedReader bufferedReader = null ; try { bufferedReader = new BufferedReader ( reader ) ; StringBuilder w = new StringBuilder ( ) ; String line = bufferedReader . readLine ( ) ; while ( line != null ) { w . append ( line ) . append ( '\n' ) ; line = bufferedReader . readLine ( ) ; } read ( w . toString ( ) ) ; } catch ( IOException e ) { throw new RuntimeException ( e ) ; } finally { try { bufferedReader . close ( ) ; } catch ( IOException e ) { } } return this ; } | Populates the current Toml instance with values from reader . |
36,969 | public Toml read ( String tomlString ) throws IllegalStateException { Results results = TomlParser . run ( tomlString ) ; if ( results . errors . hasErrors ( ) ) { throw new IllegalStateException ( results . errors . toString ( ) ) ; } this . values = results . consume ( ) ; return this ; } | Populates the current Toml instance with values from tomlString . |
36,970 | public String write ( Object from ) { try { StringWriter output = new StringWriter ( ) ; write ( from , output ) ; return output . toString ( ) ; } catch ( IOException e ) { throw new RuntimeException ( e ) ; } } | Write an Object into TOML String . |
36,971 | public User parseResponse ( JSONObject response ) throws JSONException { GsonBuilder gsonBuilder = new GsonBuilder ( ) ; gsonBuilder . registerTypeAdapter ( Date . class , new JsonDeserializer < Date > ( ) { public Date deserialize ( JsonElement jsonElement , Type type , JsonDeserializationContext jsonDeserializationContext ) throws JsonParseException { try { SimpleDateFormat format = new SimpleDateFormat ( "yyyy-MM-dd HH:mm:ss" ) ; return format . parse ( jsonElement . getAsString ( ) ) ; } catch ( ParseException e ) { return null ; } } } ) ; Gson gson = gsonBuilder . setDateFormat ( "yyyy-MM-dd HH:mm:ss" ) . create ( ) ; User user = gson . fromJson ( String . valueOf ( response . get ( "data" ) ) , User . class ) ; user = parseArray ( user , response . getJSONObject ( "data" ) ) ; return user ; } | Parses user details response from server . |
36,972 | public User parseArray ( User user , JSONObject response ) throws JSONException { JSONArray productArray = response . getJSONArray ( "products" ) ; user . products = new String [ productArray . length ( ) ] ; for ( int i = 0 ; i < productArray . length ( ) ; i ++ ) { user . products [ i ] = productArray . getString ( i ) ; } JSONArray exchangesArray = response . getJSONArray ( "exchanges" ) ; user . exchanges = new String [ exchangesArray . length ( ) ] ; for ( int j = 0 ; j < exchangesArray . length ( ) ; j ++ ) { user . exchanges [ j ] = exchangesArray . getString ( j ) ; } JSONArray orderTypeArray = response . getJSONArray ( "order_types" ) ; user . orderTypes = new String [ orderTypeArray . length ( ) ] ; for ( int k = 0 ; k < orderTypeArray . length ( ) ; k ++ ) { user . orderTypes [ k ] = orderTypeArray . getString ( k ) ; } return user ; } | Parses array details of product exchange and order_type from json response . |
36,973 | public JSONObject getRequest ( String url , String apiKey , String accessToken ) throws IOException , KiteException , JSONException { Request request = createGetRequest ( url , apiKey , accessToken ) ; Response response = client . newCall ( request ) . execute ( ) ; String body = response . body ( ) . string ( ) ; return new KiteResponseHandler ( ) . handle ( response , body ) ; } | Makes a GET request . |
36,974 | public String getCSVRequest ( String url , String apiKey , String accessToken ) throws IOException , KiteException , JSONException { Request request = new Request . Builder ( ) . url ( url ) . header ( "User-Agent" , USER_AGENT ) . header ( "X-Kite-Version" , "3" ) . header ( "Authorization" , "token " + apiKey + ":" + accessToken ) . build ( ) ; Response response = client . newCall ( request ) . execute ( ) ; String body = response . body ( ) . string ( ) ; return new KiteResponseHandler ( ) . handle ( response , body , "csv" ) ; } | Makes GET request to fetch CSV dump . |
36,975 | public Request createPostRequest ( String url , Map < String , Object > params , String apiKey , String accessToken ) { FormBody . Builder builder = new FormBody . Builder ( ) ; for ( Map . Entry < String , Object > entry : params . entrySet ( ) ) { builder . add ( entry . getKey ( ) , entry . getValue ( ) . toString ( ) ) ; } RequestBody requestBody = builder . build ( ) ; Request request = new Request . Builder ( ) . url ( url ) . post ( requestBody ) . header ( "User-Agent" , USER_AGENT ) . header ( "X-Kite-Version" , "3" ) . header ( "Authorization" , "token " + apiKey + ":" + accessToken ) . build ( ) ; return request ; } | Creates a POST request . |
36,976 | public void getMargins ( KiteConnect kiteConnect ) throws KiteException , IOException { Margin margins = kiteConnect . getMargins ( "equity" ) ; System . out . println ( margins . available . cash ) ; System . out . println ( margins . utilised . debits ) ; System . out . println ( margins . utilised . m2mUnrealised ) ; } | Gets Margin . |
36,977 | public void placeBracketOrder ( KiteConnect kiteConnect ) throws KiteException , IOException { OrderParams orderParams = new OrderParams ( ) ; orderParams . quantity = 1 ; orderParams . orderType = Constants . ORDER_TYPE_LIMIT ; orderParams . price = 30.5 ; orderParams . transactionType = Constants . TRANSACTION_TYPE_BUY ; orderParams . tradingsymbol = "SOUTHBANK" ; orderParams . trailingStoploss = 1.0 ; orderParams . stoploss = 2.0 ; orderParams . exchange = Constants . EXCHANGE_NSE ; orderParams . validity = Constants . VALIDITY_DAY ; orderParams . squareoff = 3.0 ; orderParams . product = Constants . PRODUCT_MIS ; Order order10 = kiteConnect . placeOrder ( orderParams , Constants . VARIETY_BO ) ; System . out . println ( order10 . orderId ) ; } | Place bracket order . |
36,978 | public void placeCoverOrder ( KiteConnect kiteConnect ) throws KiteException , IOException { OrderParams orderParams = new OrderParams ( ) ; orderParams . price = 0.0 ; orderParams . quantity = 1 ; orderParams . transactionType = Constants . TRANSACTION_TYPE_BUY ; orderParams . orderType = Constants . ORDER_TYPE_MARKET ; orderParams . tradingsymbol = "SOUTHBANK" ; orderParams . exchange = Constants . EXCHANGE_NSE ; orderParams . validity = Constants . VALIDITY_DAY ; orderParams . triggerPrice = 30.5 ; orderParams . product = Constants . PRODUCT_MIS ; Order order11 = kiteConnect . placeOrder ( orderParams , Constants . VARIETY_CO ) ; System . out . println ( order11 . orderId ) ; } | Place cover order . |
36,979 | public void getTriggerRange ( KiteConnect kiteConnect ) throws KiteException , IOException { String [ ] instruments = { "BSE:INFY" , "NSE:APOLLOTYRE" , "NSE:SBIN" } ; Map < String , TriggerRange > triggerRangeMap = kiteConnect . getTriggerRange ( instruments , Constants . TRANSACTION_TYPE_BUY ) ; System . out . println ( triggerRangeMap . get ( "NSE:SBIN" ) . lower ) ; System . out . println ( triggerRangeMap . get ( "NSE:APOLLOTYRE" ) . upper ) ; System . out . println ( triggerRangeMap . get ( "BSE:INFY" ) . percentage ) ; } | Get trigger range . |
36,980 | public void getOrders ( KiteConnect kiteConnect ) throws KiteException , IOException { List < Order > orders = kiteConnect . getOrders ( ) ; for ( int i = 0 ; i < orders . size ( ) ; i ++ ) { System . out . println ( orders . get ( i ) . tradingSymbol + " " + orders . get ( i ) . orderId + " " + orders . get ( i ) . parentOrderId + " " + orders . get ( i ) . orderType + " " + orders . get ( i ) . averagePrice + " " + orders . get ( i ) . exchangeTimestamp ) ; } System . out . println ( "list of orders size is " + orders . size ( ) ) ; } | Get orderbook . |
36,981 | public void getOrder ( KiteConnect kiteConnect ) throws KiteException , IOException { List < Order > orders = kiteConnect . getOrderHistory ( "180111000561605" ) ; for ( int i = 0 ; i < orders . size ( ) ; i ++ ) { System . out . println ( orders . get ( i ) . orderId + " " + orders . get ( i ) . status ) ; } System . out . println ( "list size is " + orders . size ( ) ) ; } | Get order details |
36,982 | public void getTradesWithOrderId ( KiteConnect kiteConnect ) throws KiteException , IOException { List < Trade > trades = kiteConnect . getOrderTrades ( "180111000561605" ) ; System . out . println ( trades . size ( ) ) ; } | Get trades for an order . |
36,983 | public void modifyOrder ( KiteConnect kiteConnect ) throws KiteException , IOException { OrderParams orderParams = new OrderParams ( ) ; orderParams . quantity = 1 ; orderParams . orderType = Constants . ORDER_TYPE_LIMIT ; orderParams . tradingsymbol = "ASHOKLEY" ; orderParams . product = Constants . PRODUCT_CNC ; orderParams . exchange = Constants . EXCHANGE_NSE ; orderParams . transactionType = Constants . TRANSACTION_TYPE_BUY ; orderParams . validity = Constants . VALIDITY_DAY ; orderParams . price = 122.25 ; Order order21 = kiteConnect . modifyOrder ( "180116000984900" , orderParams , Constants . VARIETY_REGULAR ) ; System . out . println ( order21 . orderId ) ; } | Modify order . |
36,984 | public void modifyFirstLegBo ( KiteConnect kiteConnect ) throws KiteException , IOException { OrderParams orderParams = new OrderParams ( ) ; orderParams . quantity = 1 ; orderParams . price = 31.0 ; orderParams . transactionType = Constants . TRANSACTION_TYPE_BUY ; orderParams . tradingsymbol = "SOUTHBANK" ; orderParams . exchange = Constants . EXCHANGE_NSE ; orderParams . validity = Constants . VALIDITY_DAY ; orderParams . product = Constants . PRODUCT_MIS ; orderParams . tag = "myTag" ; orderParams . triggerPrice = 0.0 ; Order order = kiteConnect . modifyOrder ( "180116000798058" , orderParams , Constants . VARIETY_BO ) ; System . out . println ( order . orderId ) ; } | Modify first leg bracket order . |
36,985 | public void cancelOrder ( KiteConnect kiteConnect ) throws KiteException , IOException { Order order2 = kiteConnect . cancelOrder ( "180116000727266" , Constants . VARIETY_REGULAR ) ; System . out . println ( order2 . orderId ) ; } | Cancel an order |
36,986 | public void getPositions ( KiteConnect kiteConnect ) throws KiteException , IOException { Map < String , List < Position > > position = kiteConnect . getPositions ( ) ; System . out . println ( position . get ( "net" ) . size ( ) ) ; System . out . println ( position . get ( "day" ) . size ( ) ) ; } | Get all positions . |
36,987 | public void getHoldings ( KiteConnect kiteConnect ) throws KiteException , IOException { List < Holding > holdings = kiteConnect . getHoldings ( ) ; System . out . println ( holdings . size ( ) ) ; } | Get holdings . |
36,988 | public void getAllInstruments ( KiteConnect kiteConnect ) throws KiteException , IOException { List < Instrument > instruments = kiteConnect . getInstruments ( ) ; System . out . println ( instruments . size ( ) ) ; } | Get all instruments that can be traded using kite connect . |
36,989 | public void getInstrumentsForExchange ( KiteConnect kiteConnect ) throws KiteException , IOException { List < Instrument > nseInstruments = kiteConnect . getInstruments ( "CDS" ) ; System . out . println ( nseInstruments . size ( ) ) ; } | Get instruments for the desired exchange . |
36,990 | public void getQuote ( KiteConnect kiteConnect ) throws KiteException , IOException { String [ ] instruments = { "256265" , "BSE:INFY" , "NSE:APOLLOTYRE" , "NSE:NIFTY 50" } ; Map < String , Quote > quotes = kiteConnect . getQuote ( instruments ) ; System . out . println ( quotes . get ( "NSE:APOLLOTYRE" ) . instrumentToken + "" ) ; System . out . println ( quotes . get ( "NSE:APOLLOTYRE" ) . oi + "" ) ; System . out . println ( quotes . get ( "NSE:APOLLOTYRE" ) . depth . buy . get ( 4 ) . getPrice ( ) ) ; System . out . println ( quotes . get ( "NSE:APOLLOTYRE" ) . timestamp ) ; } | Get quote for a scrip . |
36,991 | public void getHistoricalData ( KiteConnect kiteConnect ) throws KiteException , IOException { SimpleDateFormat formatter = new SimpleDateFormat ( "yyyy-MM-dd HH:mm:ss" ) ; Date from = new Date ( ) ; Date to = new Date ( ) ; try { from = formatter . parse ( "2018-01-03 12:00:00" ) ; to = formatter . parse ( "2018-01-03 22:49:12" ) ; } catch ( ParseException e ) { e . printStackTrace ( ) ; } HistoricalData historicalData = kiteConnect . getHistoricalData ( from , to , "11946498" , "15minute" , false ) ; System . out . println ( historicalData . dataArrayList . size ( ) ) ; System . out . println ( historicalData . dataArrayList . get ( 0 ) . volume ) ; System . out . println ( historicalData . dataArrayList . get ( historicalData . dataArrayList . size ( ) - 1 ) . volume ) ; } | Get historical data for an instrument . |
36,992 | public void logout ( KiteConnect kiteConnect ) throws KiteException , IOException { JSONObject jsonObject10 = kiteConnect . logout ( ) ; System . out . println ( jsonObject10 ) ; } | Logout user . |
36,993 | public void getMFInstruments ( KiteConnect kiteConnect ) throws KiteException , IOException { List < MFInstrument > mfList = kiteConnect . getMFInstruments ( ) ; System . out . println ( "size of mf instrument list: " + mfList . size ( ) ) ; } | Retrieve mf instrument dump |
36,994 | public User generateSession ( String requestToken , String apiSecret ) throws KiteException , JSONException , IOException { String hashableText = this . apiKey + requestToken + apiSecret ; String sha256hex = sha256Hex ( hashableText ) ; Map < String , Object > params = new HashMap < String , Object > ( ) ; params . put ( "api_key" , apiKey ) ; params . put ( "request_token" , requestToken ) ; params . put ( "checksum" , sha256hex ) ; return new User ( ) . parseResponse ( new KiteRequestHandler ( proxy ) . postRequest ( routes . get ( "api.validate" ) , params , apiKey , accessToken ) ) ; } | Do the token exchange with the request_token obtained after the login flow and retrieve the access_token required for all subsequent requests . |
36,995 | public TokenSet renewAccessToken ( String refreshToken , String apiSecret ) throws IOException , KiteException , JSONException { String hashableText = this . apiKey + refreshToken + apiSecret ; String sha256hex = sha256Hex ( hashableText ) ; Map < String , Object > params = new HashMap < > ( ) ; params . put ( "api_key" , apiKey ) ; params . put ( "refresh_token" , refreshToken ) ; params . put ( "checksum" , sha256hex ) ; JSONObject response = new KiteRequestHandler ( proxy ) . postRequest ( routes . get ( "api.refresh" ) , params , apiKey , accessToken ) ; return gson . fromJson ( String . valueOf ( response . get ( "data" ) ) , TokenSet . class ) ; } | Get a new access token using refresh token . |
36,996 | public String sha256Hex ( String str ) { byte [ ] a = DigestUtils . sha256 ( str ) ; StringBuilder sb = new StringBuilder ( a . length * 2 ) ; for ( byte b : a ) sb . append ( String . format ( "%02x" , b ) ) ; return sb . toString ( ) ; } | Hex encodes sha256 output for android support . |
36,997 | public Profile getProfile ( ) throws IOException , KiteException , JSONException { String url = routes . get ( "user.profile" ) ; JSONObject response = new KiteRequestHandler ( proxy ) . getRequest ( url , apiKey , accessToken ) ; return gson . fromJson ( String . valueOf ( response . get ( "data" ) ) , Profile . class ) ; } | Get the profile details of the use . |
36,998 | public Margin getMargins ( String segment ) throws KiteException , JSONException , IOException { String url = routes . get ( "user.margins.segment" ) . replace ( ":segment" , segment ) ; JSONObject response = new KiteRequestHandler ( proxy ) . getRequest ( url , apiKey , accessToken ) ; return gson . fromJson ( String . valueOf ( response . get ( "data" ) ) , Margin . class ) ; } | Gets account balance and cash margin details for a particular segment . Example for segment can be equity or commodity . |
36,999 | public Map < String , Margin > getMargins ( ) throws KiteException , JSONException , IOException { String url = routes . get ( "user.margins" ) ; JSONObject response = new KiteRequestHandler ( proxy ) . getRequest ( url , apiKey , accessToken ) ; Type type = new TypeToken < Map < String , Margin > > ( ) { } . getType ( ) ; return gson . fromJson ( String . valueOf ( response . get ( "data" ) ) , type ) ; } | Gets account balance and cash margin details for a equity and commodity . |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.