idx
int64 0
41.2k
| question
stringlengths 74
4.04k
| target
stringlengths 7
750
|
|---|---|---|
37,600
|
public void notifySipApplicationSessionListeners ( SipApplicationSessionEventType sipApplicationSessionEventType ) { List < SipApplicationSessionListener > listeners = sipContext . getListeners ( ) . getSipApplicationSessionListeners ( ) ; if ( listeners . size ( ) > 0 ) { ClassLoader oldClassLoader = java . lang . Thread . currentThread ( ) . getContextClassLoader ( ) ; sipContext . enterSipContext ( ) ; SipApplicationSessionEvent event = new SipApplicationSessionEvent ( this . getFacade ( ) ) ; if ( logger . isDebugEnabled ( ) ) { logger . debug ( "notifying sip application session listeners of context " + key . getApplicationName ( ) + " of following event " + sipApplicationSessionEventType ) ; } for ( SipApplicationSessionListener sipApplicationSessionListener : listeners ) { try { if ( logger . isDebugEnabled ( ) ) { logger . debug ( "notifying sip application session listener " + sipApplicationSessionListener . getClass ( ) . getName ( ) + " of context " + key . getApplicationName ( ) + " of following event " + sipApplicationSessionEventType ) ; } if ( SipApplicationSessionEventType . CREATION . equals ( sipApplicationSessionEventType ) ) { sipApplicationSessionListener . sessionCreated ( event ) ; } else if ( SipApplicationSessionEventType . DELETION . equals ( sipApplicationSessionEventType ) ) { sipApplicationSessionListener . sessionDestroyed ( event ) ; } else if ( SipApplicationSessionEventType . EXPIRATION . equals ( sipApplicationSessionEventType ) ) { sipApplicationSessionListener . sessionExpired ( event ) ; } else if ( SipApplicationSessionEventType . READYTOINVALIDATE . equals ( sipApplicationSessionEventType ) ) { sipApplicationSessionListener . sessionReadyToInvalidate ( event ) ; } } catch ( Throwable t ) { logger . error ( "SipApplicationSessionListener threw exception" , t ) ; } } sipContext . exitSipContext ( oldClassLoader ) ; } }
|
Notifies the listeners that a lifecycle event occured on that sip application session
|
37,601
|
public Set < MobicentsSipSession > getSipSessions ( boolean internal ) { Set < MobicentsSipSession > retSipSessions = new HashSet < MobicentsSipSession > ( ) ; if ( sipSessions != null ) { for ( SipSessionKey sipSessionKey : sipSessions ) { MobicentsSipSession sipSession = sipContext . getSipManager ( ) . getSipSession ( sipSessionKey , false , null , this ) ; if ( sipSession != null ) { if ( sipSession . isValidInternal ( ) ) { if ( internal ) { retSipSessions . add ( sipSession ) ; } else { retSipSessions . add ( sipSession . getFacade ( ) ) ; } } Iterator < MobicentsSipSession > derivedSessionsIterator = sipSession . getDerivedSipSessions ( ) ; while ( derivedSessionsIterator . hasNext ( ) ) { MobicentsSipSession derivedSipSession = derivedSessionsIterator . next ( ) ; if ( internal ) { retSipSessions . add ( derivedSipSession ) ; } else { retSipSessions . add ( derivedSipSession . getFacade ( ) ) ; } } } } } return retSipSessions ; }
|
to avoid serialization issues
|
37,602
|
public void addServletTimer ( ServletTimer servletTimer ) { if ( servletTimers == null ) { servletTimers = new ConcurrentHashMap < String , ServletTimer > ( 1 ) ; } servletTimers . putIfAbsent ( servletTimer . getId ( ) , servletTimer ) ; }
|
Add a servlet timer to this application session
|
37,603
|
public void removeServletTimer ( ServletTimer servletTimer , boolean updateAppSessionReadyToInvalidateState ) { if ( servletTimers != null ) { servletTimers . remove ( servletTimer . getId ( ) ) ; } if ( updateAppSessionReadyToInvalidateState ) { updateReadyToInvalidateState ( ) ; } }
|
Remove a servlet timer from this application session
|
37,604
|
public JSONObject jsonify ( ) { JSONObject ret = new JSONObject ( ) ; ret . put ( "title" , getTitle ( ) ) ; ret . put ( "category" , getCategory ( ) ) ; ret . put ( "subcategory" , getSubCategory ( ) ) ; ret . put ( "description" , getDescription ( ) ) ; if ( null != this . _extraAttributes && ! this . _extraAttributes . isEmpty ( ) ) { ret . putAll ( this . _extraAttributes ) ; } return ret ; }
|
Return a JSON representation of this object
|
37,605
|
private ClientCCASession getRoSession ( ) throws InternalException { return ( ( ISessionFactory ) super . sessionFactory ) . getNewAppSession ( null , roAppId , ClientCCASession . class , null ) ; }
|
Creates a new Ro Client Session
|
37,606
|
private JCreditControlRequest createCCR ( int ccRequestType , String subscriptionId , String serviceContextId ) throws Exception { ClientCCASession roSession = roSessions . get ( serviceContextId ) ; JCreditControlRequest ccr = createCreditControlRequest ( roSession . getSessions ( ) . get ( 0 ) . createRequest ( JCreditControlRequest . code , roAppId , realmName , serverHost ) ) ; AvpSet ccrAvps = ccr . getMessage ( ) . getAvps ( ) ; ccrAvps . removeAvp ( Avp . ORIGIN_HOST ) ; ccrAvps . addAvp ( Avp . ORIGIN_HOST , clientURI , true ) ; ccrAvps . addAvp ( Avp . AUTH_APPLICATION_ID , 4 ) ; AvpSet vsaid = ccrAvps . addGroupedAvp ( Avp . VENDOR_SPECIFIC_APPLICATION_ID ) ; vsaid . addAvp ( Avp . VENDOR_ID , 10415 ) ; vsaid . addAvp ( Avp . AUTH_APPLICATION_ID , 4 ) ; ccrAvps . addAvp ( 461 , serviceContextId + SERVICE_CONTEXT_DOMAIN , false ) ; ccrAvps . addAvp ( 416 , ccRequestType ) ; ccrAvps . addAvp ( 415 , this . ccRequestNumber ++ ) ; ccrAvps . removeAvp ( Avp . DESTINATION_HOST ) ; ccrAvps . addAvp ( Avp . DESTINATION_HOST , serverURI , false ) ; AvpSet subscriptionIdAvp = ccrAvps . addGroupedAvp ( 443 ) ; subscriptionIdAvp . addAvp ( 450 , 2 ) ; subscriptionIdAvp . addAvp ( 444 , subscriptionId , false ) ; AvpSet rsuAvp = ccrAvps . addGroupedAvp ( 437 ) ; rsuAvp . addAvp ( 420 , CHARGING_UNITS_TIME ) ; if ( ccRequestNumber >= 1 ) { AvpSet usedServiceUnit = ccrAvps . addGroupedAvp ( 446 ) ; usedServiceUnit . addAvp ( 420 , this . partialCallDurationCounter ) ; } DiameterUtilities . printMessage ( ccr . getMessage ( ) ) ; return ccr ; }
|
Create a Ro CCR message with the selected Request Type and Service Context ID
|
37,607
|
public void clean ( ) { this . sipApplicationSessionAttributeListeners . clear ( ) ; this . sipApplicationSessionBindingListeners . clear ( ) ; this . sipApplicationSessionActivationListeners . clear ( ) ; this . sipApplicationSessionListeners . clear ( ) ; this . sipSessionActivationListeners . clear ( ) ; this . sipSessionAttributeListeners . clear ( ) ; this . sipSessionBindingListeners . clear ( ) ; this . sipSessionListeners . clear ( ) ; this . sipServletsListeners . clear ( ) ; this . sipErrorListeners . clear ( ) ; this . servletContextListeners . clear ( ) ; this . sipConnectorListeners . clear ( ) ; this . proxyBranchListeners . clear ( ) ; this . listenerServlets . clear ( ) ; this . timerListener = null ; this . containerListener = null ; }
|
Empty vectors to allow garbage collection
|
37,608
|
public void onBranchTerminated ( ) { if ( outgoingRequest != null ) { String txid = ( ( ViaHeader ) outgoingRequest . getMessage ( ) . getHeader ( ViaHeader . NAME ) ) . getBranch ( ) ; proxy . removeTransaction ( txid ) ; } }
|
This will be called when we are sure this branch will not succeed and we moved on to other branches .
|
37,609
|
public void start ( ) { if ( logger . isDebugEnabled ( ) ) { logger . debug ( "start" ) ; } if ( started ) { throw new IllegalStateException ( "Proxy branch alredy started!" ) ; } if ( canceled ) { throw new IllegalStateException ( "Proxy branch was cancelled, you must create a new branch!" ) ; } if ( timedOut ) { throw new IllegalStateException ( "Proxy brnach has timed out!" ) ; } if ( proxy . getAckReceived ( ) ) { throw new IllegalStateException ( "An ACK request has been received on this proxy. Can not start new branches." ) ; } if ( logger . isDebugEnabled ( ) ) { logger . debug ( "start - calling updateTimer" ) ; } updateTimer ( false , originalRequest . getSipApplicationSession ( false ) ) ; SipURI recordRoute = null ; if ( proxy . getRecordRoute ( ) || this . getRecordRoute ( ) ) { if ( recordRouteURI == null && recordRouteURIString == null ) { recordRouteURIString = DEFAULT_RECORD_ROUTE_URI ; } if ( recordRouteURIString != null ) { try { recordRouteURI = ( ( SipURI ) proxy . getSipFactoryImpl ( ) . createURI ( recordRouteURIString ) ) ; } catch ( ServletParseException e ) { logger . error ( "A problem occured while setting the target URI while proxying a request " + recordRouteURIString , e ) ; } } recordRoute = recordRouteURI ; } addTransaction ( originalRequest ) ; URI destination = null ; if ( outgoingRequest . getRequestURI ( ) . equals ( this . getProxy ( ) . getOriginalRequest ( ) . getRequestURI ( ) ) ) { if ( targetURI != null ) { try { destination = proxy . getSipFactoryImpl ( ) . createURI ( targetURI ) ; } catch ( ServletParseException e ) { logger . error ( "A problem occured while setting the target URI while proxying a request " + targetURI , e ) ; } } } else { destination = outgoingRequest . getRequestURI ( ) ; } Request cloned = ProxyUtils . createProxiedRequest ( outgoingRequest , this , destination , this . outboundInterface , recordRoute , this . pathURI ) ; originalRequest . setRoutingState ( RoutingState . PROXIED ) ; if ( logger . isDebugEnabled ( ) ) { logger . debug ( "Proxy Branch 1xx Timeout set to " + proxyBranch1xxTimeout ) ; } if ( proxyBranch1xxTimeout > 0 ) { proxy1xxTimeoutTask = new ProxyBranchTimerTask ( this , ResponseType . INFORMATIONAL , originalRequest . getSipApplicationSession ( false ) ) ; proxy . getProxyTimerService ( ) . schedule ( proxy1xxTimeoutTask , proxyBranch1xxTimeout * 1000L ) ; proxyBranch1xxTimerStarted = true ; } started = true ; forwardRequest ( cloned , false ) ; }
|
After the branch is initialized this method proxies the initial request to the specified destination . Subsequent requests are proxied through proxySubsequentRequest
|
37,610
|
public void cancelTimer ( ) { synchronized ( cTimerLock ) { if ( proxyTimeoutTask != null && proxyBranchTimerStarted ) { proxyTimeoutTask . cancel ( ) ; proxyTimeoutTask = null ; proxyBranchTimerStarted = false ; } } }
|
Stop the C Timer .
|
37,611
|
public void cancel1xxTimer ( ) { if ( proxy1xxTimeoutTask != null && proxyBranch1xxTimerStarted ) { proxy1xxTimeoutTask . cancel ( ) ; proxy1xxTimeoutTask = null ; proxyBranch1xxTimerStarted = false ; } }
|
Stop the Extension Timer for 1xx .
|
37,612
|
public void begin ( String namespaceURI , String name , Attributes attributes ) throws Exception { XMLReader xmlReader = getDigester ( ) . getXMLReader ( ) ; Document doc = documentBuilder . newDocument ( ) ; NodeBuilder builder = null ; if ( nodeType == Node . ELEMENT_NODE ) { Element element = null ; if ( getDigester ( ) . getNamespaceAware ( ) ) { element = doc . createElementNS ( namespaceURI , name ) ; for ( int i = 0 ; i < attributes . getLength ( ) ; i ++ ) { element . setAttributeNS ( attributes . getURI ( i ) , attributes . getLocalName ( i ) , attributes . getValue ( i ) ) ; } } else { element = doc . createElement ( name ) ; for ( int i = 0 ; i < attributes . getLength ( ) ; i ++ ) { element . setAttribute ( attributes . getQName ( i ) , attributes . getValue ( i ) ) ; } } builder = new NodeBuilder ( doc , element ) ; } else { builder = new NodeBuilder ( doc , doc . createDocumentFragment ( ) ) ; } xmlReader . setContentHandler ( builder ) ; }
|
Implemented to replace the content handler currently in use by a NodeBuilder .
|
37,613
|
public T friends_areFriends ( int userId1 , int userId2 ) throws FacebookException , IOException { return this . callMethod ( FacebookMethod . FRIENDS_ARE_FRIENDS , new Pair < String , CharSequence > ( "uids1" , Integer . toString ( userId1 ) ) , new Pair < String , CharSequence > ( "uids2" , Integer . toString ( userId2 ) ) ) ; }
|
Retrieves whether two users are friends .
|
37,614
|
public T profile_getFBML ( Integer userId ) throws FacebookException , IOException { return this . callMethod ( FacebookMethod . PROFILE_GET_FBML , new Pair < String , CharSequence > ( "uid" , Integer . toString ( userId ) ) ) ; }
|
Gets the FBML for a user s profile including the content for both the profile box and the profile actions .
|
37,615
|
protected void handleFeedImages ( List < Pair < String , CharSequence > > params , Collection < IFeedImage > images ) { if ( images != null && images . size ( ) > 4 ) { throw new IllegalArgumentException ( "At most four images are allowed, got " + Integer . toString ( images . size ( ) ) ) ; } if ( null != images && ! images . isEmpty ( ) ) { int image_count = 0 ; for ( IFeedImage image : images ) { ++ image_count ; String imageUrl = image . getImageUrlString ( ) ; assert null != imageUrl && "" . equals ( imageUrl ) : "Image URL must be provided" ; params . add ( new Pair < String , CharSequence > ( String . format ( "image_%d" , image_count ) , image . getImageUrlString ( ) ) ) ; assert null != image . getLinkUrl ( ) : "Image link URL must be provided" ; params . add ( new Pair < String , CharSequence > ( String . format ( "image_%d_link" , image_count ) , image . getLinkUrl ( ) . toString ( ) ) ) ; } } }
|
Adds image parameters to a list of parameters
|
37,616
|
public boolean feed_publishTemplatizedAction ( Integer actorId , CharSequence titleTemplate ) throws FacebookException , IOException { if ( null != actorId && actorId != this . _userId ) { throw new IllegalArgumentException ( "Actor ID parameter is deprecated" ) ; } return feed_publishTemplatizedAction ( titleTemplate , null , null , null , null , null , null , null ) ; }
|
Publishes a Mini - Feed story describing an action taken by a user and publishes aggregating News Feed stories to the friends of that user . Stories are identified as being combinable if they have matching templates and substituted values .
|
37,617
|
public T groups_getMembers ( Number groupId ) throws FacebookException , IOException { assert ( null != groupId ) ; return this . callMethod ( FacebookMethod . GROUPS_GET_MEMBERS , new Pair < String , CharSequence > ( "gid" , groupId . toString ( ) ) ) ; }
|
Retrieves the membership list of a group
|
37,618
|
public T events_getMembers ( Number eventId ) throws FacebookException , IOException { assert ( null != eventId ) ; return this . callMethod ( FacebookMethod . EVENTS_GET_MEMBERS , new Pair < String , CharSequence > ( "eid" , eventId . toString ( ) ) ) ; }
|
Retrieves the membership list of an event
|
37,619
|
public T fql_query ( CharSequence query ) throws FacebookException , IOException { assert ( null != query ) ; return this . callMethod ( FacebookMethod . FQL_QUERY , new Pair < String , CharSequence > ( "query" , query ) ) ; }
|
Retrieves the results of a Facebook Query Language query
|
37,620
|
public T photos_getTags ( Collection < Long > photoIds ) throws FacebookException , IOException { return this . callMethod ( FacebookMethod . PHOTOS_GET_TAGS , new Pair < String , CharSequence > ( "pids" , delimit ( photoIds ) ) ) ; }
|
Retrieves the tags for the given set of photos .
|
37,621
|
public T groups_get ( Integer userId , Collection < Long > groupIds ) throws FacebookException , IOException { boolean hasGroups = ( null != groupIds && ! groupIds . isEmpty ( ) ) ; if ( null != userId ) return hasGroups ? this . callMethod ( FacebookMethod . GROUPS_GET , new Pair < String , CharSequence > ( "uid" , userId . toString ( ) ) , new Pair < String , CharSequence > ( "gids" , delimit ( groupIds ) ) ) : this . callMethod ( FacebookMethod . GROUPS_GET , new Pair < String , CharSequence > ( "uid" , userId . toString ( ) ) ) ; else return hasGroups ? this . callMethod ( FacebookMethod . GROUPS_GET , new Pair < String , CharSequence > ( "gids" , delimit ( groupIds ) ) ) : this . callMethod ( FacebookMethod . GROUPS_GET ) ; }
|
Retrieves the groups associated with a user
|
37,622
|
public boolean fbml_refreshRefUrl ( URL url ) throws FacebookException , IOException { return extractBoolean ( this . callMethod ( FacebookMethod . FBML_REFRESH_REF_URL , new Pair < String , CharSequence > ( "url" , url . toString ( ) ) ) ) ; }
|
Recaches the referenced url .
|
37,623
|
public T users_getInfo ( Collection < Integer > userIds , EnumSet < ProfileField > fields ) throws FacebookException , IOException { assert ( userIds != null ) ; assert ( fields != null ) ; assert ( ! fields . isEmpty ( ) ) ; return this . callMethod ( FacebookMethod . USERS_GET_INFO , new Pair < String , CharSequence > ( "uids" , delimit ( userIds ) ) , new Pair < String , CharSequence > ( "fields" , delimit ( fields ) ) ) ; }
|
Retrieves the requested info fields for the requested set of users .
|
37,624
|
public int users_getLoggedInUser ( ) throws FacebookException , IOException { T result = this . callMethod ( FacebookMethod . USERS_GET_LOGGED_IN_USER ) ; return extractInt ( result ) ; }
|
Retrieves the user ID of the user logged in to this API session
|
37,625
|
public int auth_getUserId ( String authToken ) throws FacebookException , IOException { if ( null == this . _sessionKey ) auth_getSession ( authToken ) ; return this . _userId ; }
|
Call this function to get the user ID .
|
37,626
|
public boolean users_hasAppPermission ( CharSequence permission ) throws FacebookException , IOException { return extractBoolean ( this . callMethod ( FacebookMethod . USERS_HAS_APP_PERMISSION , new Pair < String , CharSequence > ( "ext_perm" , permission ) ) ) ; }
|
Retrieves whether the logged - in user has granted the specified permission to this application .
|
37,627
|
public boolean users_setStatus ( String status ) throws FacebookException , IOException { return extractBoolean ( this . callMethod ( FacebookMethod . USERS_SET_STATUS , new Pair < String , CharSequence > ( "status" , status ) ) ) ; }
|
Sets the logged - in user s Facebook status . Requires the status_update extended permission .
|
37,628
|
public boolean users_clearStatus ( ) throws FacebookException , IOException { return extractBoolean ( this . callMethod ( FacebookMethod . USERS_SET_STATUS , new Pair < String , CharSequence > ( "clear" , "1" ) ) ) ; }
|
Clears the logged - in user s Facebook status . Requires the status_update extended permission .
|
37,629
|
public void notifications_send ( Collection < Integer > recipientIds , CharSequence notification ) throws FacebookException , IOException { assert ( null != notification ) ; ArrayList < Pair < String , CharSequence > > args = new ArrayList < Pair < String , CharSequence > > ( 3 ) ; if ( null != recipientIds && ! recipientIds . isEmpty ( ) ) { args . add ( new Pair < String , CharSequence > ( "to_ids" , delimit ( recipientIds ) ) ) ; } args . add ( new Pair < String , CharSequence > ( "notification" , notification ) ) ; this . callMethod ( FacebookMethod . NOTIFICATIONS_SEND , args ) ; }
|
Send a notification message to the specified users on behalf of the logged - in user .
|
37,630
|
public T photos_addTags ( Long photoId , Collection < PhotoTag > tags ) throws FacebookException , IOException { assert ( photoId > 0 ) ; assert ( null != tags && ! tags . isEmpty ( ) ) ; JSONArray jsonTags = new JSONArray ( ) ; for ( PhotoTag tag : tags ) { jsonTags . add ( tag . jsonify ( ) ) ; } return this . callMethod ( FacebookMethod . PHOTOS_ADD_TAG , new Pair < String , CharSequence > ( "pid" , photoId . toString ( ) ) , new Pair < String , CharSequence > ( "tags" , jsonTags . toString ( ) ) ) ; }
|
Adds several tags to a photo .
|
37,631
|
public T events_get ( Integer userId , Collection < Long > eventIds , Long startTime , Long endTime ) throws FacebookException , IOException { ArrayList < Pair < String , CharSequence > > params = new ArrayList < Pair < String , CharSequence > > ( FacebookMethod . EVENTS_GET . numParams ( ) ) ; boolean hasUserId = null != userId && 0 != userId ; boolean hasEventIds = null != eventIds && ! eventIds . isEmpty ( ) ; boolean hasStart = null != startTime && 0 != startTime ; boolean hasEnd = null != endTime && 0 != endTime ; if ( hasUserId ) params . add ( new Pair < String , CharSequence > ( "uid" , Integer . toString ( userId ) ) ) ; if ( hasEventIds ) params . add ( new Pair < String , CharSequence > ( "eids" , delimit ( eventIds ) ) ) ; if ( hasStart ) params . add ( new Pair < String , CharSequence > ( "start_time" , startTime . toString ( ) ) ) ; if ( hasEnd ) params . add ( new Pair < String , CharSequence > ( "end_time" , endTime . toString ( ) ) ) ; return this . callMethod ( FacebookMethod . EVENTS_GET , params ) ; }
|
Returns all visible events according to the filters specified . This may be used to find all events of a user or to query specific eids .
|
37,632
|
public boolean profile_setFBML ( CharSequence fbmlMarkup , Integer userId ) throws FacebookException , IOException { return extractBoolean ( this . callMethod ( FacebookMethod . PROFILE_SET_FBML , new Pair < String , CharSequence > ( "uid" , Integer . toString ( userId ) ) , new Pair < String , CharSequence > ( "markup" , fbmlMarkup ) ) ) ; }
|
Sets the FBML for a user s profile including the content for both the profile box and the profile actions .
|
37,633
|
public boolean profile_setProfileFBML ( CharSequence fbmlMarkup ) throws FacebookException , IOException { return profile_setFBML ( fbmlMarkup , null , null , null ) ; }
|
Sets the FBML for a profile box on the logged - in user s profile .
|
37,634
|
public boolean profile_setProfileActionFBML ( CharSequence fbmlMarkup ) throws FacebookException , IOException { return profile_setFBML ( null , fbmlMarkup , null , null ) ; }
|
Sets the FBML for profile actions for the logged - in user .
|
37,635
|
public boolean profile_setMobileFBML ( CharSequence fbmlMarkup ) throws FacebookException , IOException { return profile_setFBML ( null , null , fbmlMarkup , null ) ; }
|
Sets the FBML for the logged - in user s profile on mobile devices .
|
37,636
|
public boolean profile_setFBML ( CharSequence profileFbmlMarkup , CharSequence profileActionFbmlMarkup ) throws FacebookException , IOException { return profile_setFBML ( profileFbmlMarkup , profileActionFbmlMarkup , null , null ) ; }
|
Sets the FBML for the profile box and profile actions for the logged - in user . Refer to the FBML documentation for a description of the markup and its role in various contexts .
|
37,637
|
public T photos_getAlbums ( Collection < Long > albumIds ) throws FacebookException , IOException { return photos_getAlbums ( null , albumIds ) ; }
|
Retrieves album metadata for a list of album IDs .
|
37,638
|
public boolean fbml_refreshImgSrc ( URL imageUrl ) throws FacebookException , IOException { return extractBoolean ( this . callMethod ( FacebookMethod . FBML_REFRESH_IMG_SRC , new Pair < String , CharSequence > ( "url" , imageUrl . toString ( ) ) ) ) ; }
|
Recaches the image with the specified imageUrl .
|
37,639
|
public String auth_createToken ( ) throws FacebookException , IOException { T d = this . callMethod ( FacebookMethod . AUTH_CREATE_TOKEN ) ; return extractString ( d ) ; }
|
Call this function and store the result using it to generate the appropriate login url and then to retrieve the session information .
|
37,640
|
public Long marketplace_createListing ( Boolean showOnProfile , MarketplaceListing attrs ) throws FacebookException , IOException { T result = this . callMethod ( FacebookMethod . MARKETPLACE_CREATE_LISTING , new Pair < String , CharSequence > ( "show_on_profile" , showOnProfile ? "1" : "0" ) , new Pair < String , CharSequence > ( "listing_id" , "0" ) , new Pair < String , CharSequence > ( "listing_attrs" , attrs . jsonify ( ) . toString ( ) ) ) ; return this . extractLong ( result ) ; }
|
Create a marketplace listing
|
37,641
|
public boolean marketplace_removeListing ( Long listingId , CharSequence status ) throws FacebookException , IOException { assert MARKETPLACE_STATUS_DEFAULT . equals ( status ) || MARKETPLACE_STATUS_SUCCESS . equals ( status ) || MARKETPLACE_STATUS_NOT_SUCCESS . equals ( status ) : "Invalid status: " + status ; T result = this . callMethod ( FacebookMethod . MARKETPLACE_REMOVE_LISTING , new Pair < String , CharSequence > ( "listing_id" , listingId . toString ( ) ) , new Pair < String , CharSequence > ( "status" , status ) ) ; return this . extractBoolean ( result ) ; }
|
Remove a marketplace listing
|
37,642
|
public T marketplace_getSubCategories ( CharSequence category ) throws FacebookException , IOException { return this . callMethod ( FacebookMethod . MARKETPLACE_GET_SUBCATEGORIES , new Pair < String , CharSequence > ( "category" , category ) ) ; }
|
Get the subcategories available for a category .
|
37,643
|
public boolean pages_isAppAdded ( Long pageId ) throws FacebookException , IOException { return extractBoolean ( this . callMethod ( FacebookMethod . PAGES_IS_APP_ADDED , new Pair < String , CharSequence > ( "page_id" , pageId . toString ( ) ) ) ) ; }
|
Checks whether a page has added the application
|
37,644
|
public boolean admin_setAppProperties ( ApplicationPropertySet properties ) throws FacebookException , IOException { if ( null == properties || properties . isEmpty ( ) ) { throw new IllegalArgumentException ( "expecting a non-empty set of application properties" ) ; } return extractBoolean ( this . callMethod ( FacebookMethod . ADMIN_SET_APP_PROPERTIES , new Pair < String , CharSequence > ( "properties" , properties . toJsonString ( ) ) ) ) ; }
|
Sets several property values for an application . The properties available are analogous to the ones editable via the Facebook Developer application . A session is not required to use this method .
|
37,645
|
public void init ( ) { String darConfigurationFileLocation = getDarConfigurationFileLocation ( ) ; if ( log . isDebugEnabled ( ) ) { log . debug ( "Default Application Router file Location : " + darConfigurationFileLocation ) ; } File darConfigurationFile = null ; URL url = null ; try { url = new URL ( darConfigurationFileLocation ) ; } catch ( MalformedURLException e ) { log . fatal ( "Cannot find the default application router file ! " , e ) ; throw new IllegalArgumentException ( "The Default Application Router file Location : " + darConfigurationFileLocation + " is not valid ! " , e ) ; } try { darConfigurationFile = new File ( new URI ( darConfigurationFileLocation ) ) ; } catch ( URISyntaxException e ) { darConfigurationFile = new File ( url . getPath ( ) ) ; } FileInputStream fis = null ; try { fis = new FileInputStream ( darConfigurationFile ) ; properties . load ( fis ) ; } catch ( FileNotFoundException e ) { log . fatal ( "Cannot find the default application router file ! " , e ) ; throw new IllegalArgumentException ( "The Default Application Router file Location : " + darConfigurationFileLocation + " is not valid ! " , e ) ; } catch ( IOException e ) { log . fatal ( "Cannot load the default application router file ! " , e ) ; throw new IllegalArgumentException ( "The Default Application Router file Location : " + darConfigurationFileLocation + " cannot be loaded ! " , e ) ; } finally { if ( fis != null ) { try { fis . close ( ) ; } catch ( IOException e ) { log . error ( "fail to close the following file " + darConfigurationFile . getAbsolutePath ( ) , e ) ; } } } }
|
Load the configuration file as defined in JSR289 Appendix C ie as a system property javax . servlet . sip . dar
|
37,646
|
public Map < String , List < ? extends SipApplicationRouterInfo > > parse ( ) throws ParseException { Map < String , List < ? extends SipApplicationRouterInfo > > sipApplicationRoutingInfo = new HashMap < String , List < ? extends SipApplicationRouterInfo > > ( ) ; Iterator darEntriesIterator = properties . entrySet ( ) . iterator ( ) ; while ( darEntriesIterator . hasNext ( ) ) { Entry < String , String > darEntry = ( Entry < String , String > ) darEntriesIterator . next ( ) ; String sipMethod = darEntry . getKey ( ) ; String sipApplicationRouterInfosStringified = darEntry . getValue ( ) ; List < ? extends SipApplicationRouterInfo > sipApplicationRouterInfoList = parseSipApplicationRouterInfos ( sipApplicationRouterInfosStringified ) ; sipApplicationRoutingInfo . put ( sipMethod , sipApplicationRouterInfoList ) ; } return sipApplicationRoutingInfo ; }
|
Parse the global default application router file from the loaded properties file from the init method
|
37,647
|
public Map < String , List < ? extends SipApplicationRouterInfo > > parse ( String configuration ) throws ParseException { Properties tempProperties = new Properties ( ) ; ByteArrayInputStream stringStream = new ByteArrayInputStream ( configuration . getBytes ( ) ) ; try { tempProperties . load ( stringStream ) ; } catch ( IOException e ) { log . warn ( "Failed to update AR configuration. Will use the old properties." ) ; return null ; } this . properties = tempProperties ; return parse ( ) ; }
|
Same method as above but loads DAR configuration from a string .
|
37,648
|
public Map < String , List < ? extends SipApplicationRouterInfo > > parse ( Properties properties ) throws ParseException { this . properties = properties ; return parse ( ) ; }
|
Same method as above but loads DAR configuration from properties .
|
37,649
|
protected void registerJMX ( StandardContext ctx ) { ObjectName oname ; String parentName = ctx . getName ( ) ; parentName = ( "" . equals ( parentName ) ) ? "/" : parentName ; String hostName = ctx . getParent ( ) . getName ( ) ; hostName = ( hostName == null ) ? "DEFAULT" : hostName ; String domain = ctx . getDomain ( ) ; String webMod = "//" + hostName + parentName ; String onameStr = domain + ":j2eeType=SipServlet,name=" + getName ( ) + ",WebModule=" + webMod + ",J2EEApplication=" + ctx . getJ2EEApplication ( ) + ",J2EEServer=" + ctx . getJ2EEServer ( ) ; try { oname = new ObjectName ( onameStr ) ; Registry . getRegistry ( null , null ) . registerComponent ( this , oname , null ) ; if ( this . getObjectName ( ) != null ) { Notification notification = new Notification ( "j2ee.object.created" , this . getObjectName ( ) , sequenceNumber ++ ) ; broadcaster . sendNotification ( notification ) ; } } catch ( Exception ex ) { super . getLogger ( ) . info ( "Error registering servlet with jmx " + this ) ; } }
|
copied over from super class changing the JMX name being registered j2eeType is now SipServlet instead of Servlet
|
37,650
|
private void checkHandler ( SipServletRequest request ) { MobicentsSipSession sipSessionImpl = ( MobicentsSipSession ) request . getSession ( ) ; if ( sipSessionImpl . getHandler ( ) == null ) { try { sipSessionImpl . setHandler ( sipContext . getServletHandler ( ) ) ; } catch ( ServletException se ) { logger . error ( "Impossible to set the default handler on the newly created request " + request . toString ( ) , se ) ; } } }
|
set the handler for this request if none already exists . The handler will be the main servlet of the sip context
|
37,651
|
private BigDecimal round ( BigDecimal amount ) { return new BigDecimal ( amount . movePointRight ( 2 ) . add ( new BigDecimal ( ".5" ) ) . toBigInteger ( ) ) . movePointLeft ( 2 ) ; }
|
round a positive big decimal to 2 decimal points
|
37,652
|
private long doDiameterCharging ( String sessionId , String userId , Long cost , boolean refund ) { try { logger . info ( "Creating Diameter Charging " + ( refund ? "Refund" : "Debit" ) + " Request UserId[" + userId + "], Cost[" + cost + "]..." ) ; Request req = ( Request ) diameterBaseClient . createAccountingRequest ( sessionId , userId , cost , refund ) ; logger . info ( "Sending Diameter Charging " + ( refund ? "Refund" : "Debit" ) + " Request..." ) ; Message msg = diameterBaseClient . sendMessageSync ( req ) ; long resultCode = - 1 ; if ( msg instanceof Answer ) resultCode = ( ( Answer ) msg ) . getResultCode ( ) . getUnsigned32 ( ) ; return resultCode ; } catch ( Exception e ) { logger . error ( "Failure communicating with Diameter Charging Server." , e ) ; return 5012 ; } }
|
Method for doing the Charging either it s a debit or a refund .
|
37,653
|
public void addSipApplicationListener ( String listener ) { if ( logger . isDebugEnabled ( ) ) { logger . debug ( "addSipApplicationListener " + getName ( ) ) ; } sipApplicationListeners . add ( listener ) ; fireContainerEvent ( "addSipApplicationListener" , listener ) ; }
|
Add a new Listener class name to the set of Listeners configured for this application .
|
37,654
|
public void addAllToCart ( ) { for ( Product item : searchResults ) { Boolean selected = searchSelections . get ( item ) ; if ( selected != null && selected ) { searchSelections . put ( item , false ) ; cart . addProduct ( item , 1 ) ; } } }
|
Add many items to cart
|
37,655
|
private void postWorkDirectory ( ) { String workDir = getWorkDir ( ) ; if ( workDir == null || workDir . length ( ) == 0 ) { String hostName = null ; String engineName = null ; String hostWorkDir = null ; Container parentHost = getParent ( ) ; if ( parentHost != null ) { hostName = parentHost . getName ( ) ; if ( parentHost instanceof StandardHost ) { hostWorkDir = ( ( StandardHost ) parentHost ) . getWorkDir ( ) ; } Container parentEngine = parentHost . getParent ( ) ; if ( parentEngine != null ) { engineName = parentEngine . getName ( ) ; } } if ( ( hostName == null ) || ( hostName . length ( ) < 1 ) ) hostName = "_" ; if ( ( engineName == null ) || ( engineName . length ( ) < 1 ) ) engineName = "_" ; String temp = getBaseName ( ) ; if ( temp . startsWith ( "/" ) ) temp = temp . substring ( 1 ) ; temp = temp . replace ( '/' , '_' ) ; temp = temp . replace ( '\\' , '_' ) ; if ( temp . length ( ) < 1 ) temp = ContextName . ROOT_NAME ; if ( hostWorkDir != null ) { workDir = hostWorkDir + File . separator + temp ; } else { workDir = "work" + File . separator + engineName + File . separator + hostName + File . separator + temp ; } setWorkDir ( workDir ) ; } File dir = new File ( workDir ) ; if ( ! dir . isAbsolute ( ) ) { String catalinaHomePath = null ; try { catalinaHomePath = getCatalinaBase ( ) . getCanonicalPath ( ) ; dir = new File ( catalinaHomePath , workDir ) ; } catch ( IOException e ) { logger . warn ( sm . getString ( "standardContext.workCreateException" , workDir , catalinaHomePath , getName ( ) ) , e ) ; } } if ( ! dir . mkdirs ( ) && ! dir . isDirectory ( ) ) { logger . warn ( sm . getString ( "standardContext.workCreateFail" , dir , getName ( ) ) ) ; } if ( context == null ) { getServletContext ( ) ; } context . setAttribute ( ServletContext . TEMPDIR , dir ) ; }
|
Set the appropriate context attribute for our work directory .
|
37,656
|
public static boolean verifySignature ( EnumMap < FacebookParam , CharSequence > params , String secret ) { if ( null == params || params . isEmpty ( ) ) return false ; CharSequence sigParam = params . remove ( FacebookParam . SIGNATURE ) ; return ( null == sigParam ) ? false : verifySignature ( params , secret , sigParam . toString ( ) ) ; }
|
Verifies that a signature received matches the expected value . Removes FacebookParam . SIGNATURE from params if present .
|
37,657
|
public static boolean isValidIPV4Address ( String value ) { int periods = 0 ; int i = 0 ; int length = value . length ( ) ; if ( length > 15 ) return false ; char c = 0 ; String word = "" ; for ( i = 0 ; i < length ; i ++ ) { c = value . charAt ( i ) ; if ( c == '.' ) { periods ++ ; if ( periods > 3 ) return false ; if ( word == "" ) return false ; if ( Integer . parseInt ( word ) > 255 ) return false ; word = "" ; } else if ( ! ( Character . isDigit ( c ) ) ) return false ; else { if ( word . length ( ) > 2 ) return false ; word += c ; } } if ( word == "" || Integer . parseInt ( word ) > 255 ) return false ; if ( periods != 3 ) return false ; return true ; }
|
Takes a string and parses it to see if it is a valid IPV4 address .
|
37,658
|
public String extractString ( Object val ) { try { return ( String ) val ; } catch ( ClassCastException cce ) { logException ( cce ) ; return null ; } }
|
Extracts a String from a result consisting entirely of a String .
|
37,659
|
protected Object parseCallResult ( InputStream data , IFacebookMethod method ) throws FacebookException , IOException { Object json = JSONValue . parse ( new InputStreamReader ( data ) ) ; if ( isDebug ( ) ) { log ( method . methodName ( ) + ": " + ( null != json ? json . toString ( ) : "null" ) ) ; } if ( json instanceof JSONObject ) { JSONObject jsonObj = ( JSONObject ) json ; if ( jsonObj . containsKey ( "error_code" ) ) { Long errorCode = ( Long ) jsonObj . get ( "error_code" ) ; String message = ( String ) jsonObj . get ( "error_msg" ) ; throw new FacebookException ( errorCode . intValue ( ) , message ) ; } } return json ; }
|
Parses the result of an API call from JSON into Java Objects .
|
37,660
|
protected URL extractURL ( Object url ) throws IOException { if ( ! ( url instanceof String ) ) { return null ; } return ( null == url || "" . equals ( url ) ) ? null : new URL ( ( String ) url ) ; }
|
Extracts a URL from a result that consists of a URL only . For JSON that result is simply a String .
|
37,661
|
protected boolean extractBoolean ( Object val ) { try { return ( Boolean ) val ; } catch ( ClassCastException cce ) { logException ( cce ) ; return false ; } }
|
Extracts a Boolean from a result that consists of a Boolean only .
|
37,662
|
protected Long extractLong ( Object val ) { try { return ( Long ) val ; } catch ( ClassCastException cce ) { logException ( cce ) ; return null ; } }
|
Extracts a Long from a result that consists of an Long only .
|
37,663
|
public void add ( double lat , double lon , long time , T t , Optional < R > id ) { Info < T , R > info = new Info < T , R > ( lat , lon , time , t , id ) ; add ( info ) ; }
|
Adds a record to the in - memory store with the given position and time and id .
|
37,664
|
public void add ( Info < T , R > info ) { String hash = GeoHash . encodeHash ( info . lat ( ) , info . lon ( ) ) ; addToMap ( mapByGeoHash , info , hash ) ; addToMapById ( mapById , info , hash ) ; }
|
Adds a record to the in - memory store with the given position time and id .
|
37,665
|
public static long decodeBase32 ( String hash ) { boolean isNegative = hash . startsWith ( "-" ) ; int startIndex = isNegative ? 1 : 0 ; long base = 1 ; long result = 0 ; for ( int i = hash . length ( ) - 1 ; i >= startIndex ; i -- ) { int j = getCharIndex ( hash . charAt ( i ) ) ; result = result + base * j ; base = base * 32 ; } if ( isNegative ) result *= - 1 ; return result ; }
|
Returns the conversion of a base32 geohash to a long .
|
37,666
|
private static Map < Direction , Map < Parity , String > > createBorders ( ) { Map < Direction , Map < Parity , String > > m = createDirectionParityMap ( ) ; m . get ( Direction . RIGHT ) . put ( Parity . EVEN , "bcfguvyz" ) ; m . get ( Direction . LEFT ) . put ( Parity . EVEN , "0145hjnp" ) ; m . get ( Direction . TOP ) . put ( Parity . EVEN , "prxz" ) ; m . get ( Direction . BOTTOM ) . put ( Parity . EVEN , "028b" ) ; addOddParityEntries ( m ) ; return m ; }
|
Returns a map to be used in hash border calculations .
|
37,667
|
private static Map < Direction , Map < Parity , String > > createDirectionParityMap ( ) { Map < Direction , Map < Parity , String > > m = newHashMap ( ) ; m . put ( Direction . BOTTOM , GeoHash . < Parity , String > newHashMap ( ) ) ; m . put ( Direction . TOP , GeoHash . < Parity , String > newHashMap ( ) ) ; m . put ( Direction . LEFT , GeoHash . < Parity , String > newHashMap ( ) ) ; m . put ( Direction . RIGHT , GeoHash . < Parity , String > newHashMap ( ) ) ; return m ; }
|
Create a direction and parity map for use in adjacent hash calculations .
|
37,668
|
private static void addOddParityEntries ( Map < Direction , Map < Parity , String > > m ) { m . get ( Direction . BOTTOM ) . put ( Parity . ODD , m . get ( Direction . LEFT ) . get ( Parity . EVEN ) ) ; m . get ( Direction . TOP ) . put ( Parity . ODD , m . get ( Direction . RIGHT ) . get ( Parity . EVEN ) ) ; m . get ( Direction . LEFT ) . put ( Parity . ODD , m . get ( Direction . BOTTOM ) . get ( Parity . EVEN ) ) ; m . get ( Direction . RIGHT ) . put ( Parity . ODD , m . get ( Direction . TOP ) . get ( Parity . EVEN ) ) ; }
|
Puts odd parity entries in the map m based purely on the even entries .
|
37,669
|
public static List < String > neighbours ( String hash ) { List < String > list = new ArrayList < String > ( ) ; String left = adjacentHash ( hash , Direction . LEFT ) ; String right = adjacentHash ( hash , Direction . RIGHT ) ; list . add ( left ) ; list . add ( right ) ; list . add ( adjacentHash ( hash , Direction . TOP ) ) ; list . add ( adjacentHash ( hash , Direction . BOTTOM ) ) ; list . add ( adjacentHash ( left , Direction . TOP ) ) ; list . add ( adjacentHash ( left , Direction . BOTTOM ) ) ; list . add ( adjacentHash ( right , Direction . TOP ) ) ; list . add ( adjacentHash ( right , Direction . BOTTOM ) ) ; return list ; }
|
Returns a list of the 8 surrounding hashes for a given hash in order left right top bottom left - top left - bottom right - top right - bottom .
|
37,670
|
public static String encodeHash ( LatLong p , int length ) { return encodeHash ( p . getLat ( ) , p . getLon ( ) , length ) ; }
|
Returns a geohash of given length for the given WGS84 point .
|
37,671
|
static String fromLongToString ( long hash ) { int length = ( int ) ( hash & 0xf ) ; if ( length > 12 || length < 1 ) throw new IllegalArgumentException ( "invalid long geohash " + hash ) ; char [ ] geohash = new char [ length ] ; for ( int pos = 0 ; pos < length ; pos ++ ) { geohash [ pos ] = BASE32 . charAt ( ( ( int ) ( hash >>> 59 ) ) ) ; hash <<= 5 ; } return new String ( geohash ) ; }
|
Takes a hash represented as a long and returns it as a string .
|
37,672
|
private static void refineInterval ( double [ ] interval , int cd , int mask ) { if ( ( cd & mask ) != 0 ) interval [ 0 ] = ( interval [ 0 ] + interval [ 1 ] ) / 2 ; else interval [ 1 ] = ( interval [ 0 ] + interval [ 1 ] ) / 2 ; }
|
Refines interval by a factor or 2 in either the 0 or 1 ordinate .
|
37,673
|
public static int hashLengthToCoverBoundingBox ( double topLeftLat , double topLeftLon , double bottomRightLat , double bottomRightLon ) { boolean isEven = true ; double minLat = - 90.0 , maxLat = 90 ; double minLon = - 180.0 , maxLon = 180.0 ; for ( int bits = 0 ; bits < MAX_HASH_LENGTH * 5 ; bits ++ ) { if ( isEven ) { double mid = ( minLon + maxLon ) / 2 ; if ( topLeftLon >= mid ) { if ( bottomRightLon < mid ) return bits / 5 ; minLon = mid ; } else { if ( bottomRightLon >= mid ) return bits / 5 ; maxLon = mid ; } } else { double mid = ( minLat + maxLat ) / 2 ; if ( topLeftLat >= mid ) { if ( bottomRightLat < mid ) return bits / 5 ; minLat = mid ; } else { if ( bottomRightLat >= mid ) return bits / 5 ; maxLat = mid ; } } isEven = ! isEven ; } return MAX_HASH_LENGTH ; }
|
Returns the maximum length of hash that covers the bounding box . If no hash can enclose the bounding box then 0 is returned .
|
37,674
|
public static boolean hashContains ( String hash , double lat , double lon ) { LatLong centre = decodeHash ( hash ) ; return Math . abs ( centre . getLat ( ) - lat ) <= heightDegrees ( hash . length ( ) ) / 2 && Math . abs ( to180 ( centre . getLon ( ) - lon ) ) <= widthDegrees ( hash . length ( ) ) / 2 ; }
|
Returns true if and only if the bounding box corresponding to the hash contains the given lat and long .
|
37,675
|
public static Coverage coverBoundingBox ( double topLeftLat , final double topLeftLon , final double bottomRightLat , final double bottomRightLon , final int length ) { return new Coverage ( coverBoundingBoxLongs ( topLeftLat , topLeftLon , bottomRightLat , bottomRightLon , length ) ) ; }
|
Returns the hashes of given length that are required to cover the given bounding box .
|
37,676
|
private static double calculateWidthDegrees ( int n ) { double a ; if ( n % 2 == 0 ) a = - 1 ; else a = - 0.5 ; double result = 180 / Math . pow ( 2 , 2.5 * n + a ) ; return result ; }
|
Returns the width in degrees of the region represented by a geohash of length n .
|
37,677
|
public static String gridAsString ( String hash , int fromRight , int fromBottom , int toRight , int toBottom ) { return gridAsString ( hash , fromRight , fromBottom , toRight , toBottom , Collections . < String > emptySet ( ) ) ; }
|
Returns a String of lines of hashes to represent the relative positions of hashes on a map .
|
37,678
|
public void setLocation ( String latitude , String longitude ) { this . latitude = new BigDecimal ( latitude ) ; this . longitude = new BigDecimal ( longitude ) ; }
|
Sets the coordinates of the location object .
|
37,679
|
private BigDecimal getLongitudeHour ( Calendar date , Boolean isSunrise ) { int offset = 18 ; if ( isSunrise ) { offset = 6 ; } BigDecimal dividend = BigDecimal . valueOf ( offset ) . subtract ( getBaseLongitudeHour ( ) ) ; BigDecimal addend = divideBy ( dividend , BigDecimal . valueOf ( 24 ) ) ; BigDecimal longHour = getDayOfYear ( date ) . add ( addend ) ; return setScale ( longHour ) ; }
|
Computes the longitude time t in the algorithm .
|
37,680
|
private BigDecimal getMeanAnomaly ( BigDecimal longitudeHour ) { BigDecimal meanAnomaly = multiplyBy ( new BigDecimal ( "0.9856" ) , longitudeHour ) . subtract ( new BigDecimal ( "3.289" ) ) ; return setScale ( meanAnomaly ) ; }
|
Computes the mean anomaly of the Sun M in the algorithm .
|
37,681
|
public static Calendar getSunrise ( double latitude , double longitude , TimeZone timeZone , Calendar date , double degrees ) { SolarEventCalculator solarEventCalculator = new SolarEventCalculator ( new Location ( latitude , longitude ) , timeZone ) ; return solarEventCalculator . computeSunriseCalendar ( new Zenith ( 90 - degrees ) , date ) ; }
|
Computes the sunrise for an arbitrary declination .
|
37,682
|
public static Calendar getSunset ( double latitude , double longitude , TimeZone timeZone , Calendar date , double degrees ) { SolarEventCalculator solarEventCalculator = new SolarEventCalculator ( new Location ( latitude , longitude ) , timeZone ) ; return solarEventCalculator . computeSunsetCalendar ( new Zenith ( 90 - degrees ) , date ) ; }
|
Computes the sunset for an arbitrary declination .
|
37,683
|
private static synchronized void closeRegisteredConnections ( ) { for ( Connection connection : activeConnections ) { LOGGER . log ( Level . INFO , "Forcing connection to {0}:{1} closed." , new Object [ ] { connection . getHostname ( ) , connection . getPort ( ) } ) ; connection . close ( ) ; } activeConnections . clear ( ) ; }
|
Closes all the registered connections .
|
37,684
|
public List < String > getJavas ( SlaveComputer computer , TaskListener listener , Connection connection ) { return getJavas ( listener , connection ) ; }
|
Returns the list of possible places where java executable might exist .
|
37,685
|
private void cleanupConnection ( TaskListener listener ) { if ( connection != null ) { connection . close ( ) ; connection = null ; listener . getLogger ( ) . println ( Messages . SSHLauncher_ConnectionClosed ( getTimestamp ( ) ) ) ; } }
|
Called to terminate the SSH connection . Used liberally when we back out from an error .
|
37,686
|
private void verifyNoHeaderJunk ( TaskListener listener ) throws IOException , InterruptedException { ByteArrayOutputStream baos = new ByteArrayOutputStream ( ) ; connection . exec ( "exit 0" , baos ) ; final String s ; try { s = baos . toString ( Charset . defaultCharset ( ) . name ( ) ) ; } catch ( UnsupportedEncodingException ex ) { throw new IOException ( "Default encoding is unsupported" , ex ) ; } if ( s . length ( ) != 0 ) { listener . getLogger ( ) . println ( Messages . SSHLauncher_SSHHeaderJunkDetected ( ) ) ; listener . getLogger ( ) . println ( s ) ; throw new AbortException ( ) ; } }
|
Makes sure that SSH connection won t produce any unwanted text which will interfere with sftp execution .
|
37,687
|
private void startAgent ( SlaveComputer computer , final TaskListener listener , String java , String workingDirectory ) throws IOException { session = connection . openSession ( ) ; expandChannelBufferSize ( session , listener ) ; String cmd = "cd \"" + workingDirectory + "\" && " + java + " " + getJvmOptions ( ) + " -jar " + AGENT_JAR + getWorkDirParam ( workingDirectory ) ; cmd = getPrefixStartSlaveCmd ( ) + cmd + getSuffixStartSlaveCmd ( ) ; listener . getLogger ( ) . println ( Messages . SSHLauncher_StartingAgentProcess ( getTimestamp ( ) , cmd ) ) ; session . execCommand ( cmd ) ; session . pipeStderr ( new DelegateNoCloseOutputStream ( listener . getLogger ( ) ) ) ; try { computer . setChannel ( session . getStdout ( ) , session . getStdin ( ) , listener . getLogger ( ) , null ) ; } catch ( InterruptedException e ) { session . close ( ) ; throw new IOException ( Messages . SSHLauncher_AbortedDuringConnectionOpen ( ) , e ) ; } catch ( IOException e ) { try { throw new AbortException ( getSessionOutcomeMessage ( session , false ) ) ; } catch ( InterruptedException x ) { throw new IOException ( e ) ; } } }
|
Starts the agent process .
|
37,688
|
private void copyAgentJar ( TaskListener listener , String workingDirectory ) throws IOException , InterruptedException { String fileName = workingDirectory + SLASH_AGENT_JAR ; listener . getLogger ( ) . println ( Messages . SSHLauncher_StartingSFTPClient ( getTimestamp ( ) ) ) ; SFTPClient sftpClient = null ; try { sftpClient = new SFTPClient ( connection ) ; try { SFTPv3FileAttributes fileAttributes = sftpClient . _stat ( workingDirectory ) ; if ( fileAttributes == null ) { listener . getLogger ( ) . println ( Messages . SSHLauncher_RemoteFSDoesNotExist ( getTimestamp ( ) , workingDirectory ) ) ; sftpClient . mkdirs ( workingDirectory , 0700 ) ; } else if ( fileAttributes . isRegularFile ( ) ) { throw new IOException ( Messages . SSHLauncher_RemoteFSIsAFile ( workingDirectory ) ) ; } listener . getLogger ( ) . println ( Messages . SSHLauncher_CopyingAgentJar ( getTimestamp ( ) ) ) ; byte [ ] agentJar = new Slave . JnlpJar ( AGENT_JAR ) . readFully ( ) ; boolean overwrite = true ; if ( sftpClient . exists ( fileName ) ) { String sourceAgentHash = getMd5Hash ( agentJar ) ; String existingAgentHash = getMd5Hash ( readInputStreamIntoByteArrayAndClose ( sftpClient . read ( fileName ) ) ) ; listener . getLogger ( ) . println ( MessageFormat . format ( "Source agent hash is {0}. " + "Installed agent hash is {1}" , sourceAgentHash , existingAgentHash ) ) ; overwrite = ! sourceAgentHash . equals ( existingAgentHash ) ; } if ( overwrite ) { try { sftpClient . rm ( fileName ) ; } catch ( IOException e ) { } try ( OutputStream os = sftpClient . writeToFile ( fileName ) ) { os . write ( agentJar ) ; listener . getLogger ( ) . println ( Messages . SSHLauncher_CopiedXXXBytes ( getTimestamp ( ) , agentJar . length ) ) ; } catch ( Error error ) { throw error ; } catch ( Throwable e ) { throw new IOException ( Messages . SSHLauncher_ErrorCopyingAgentJarTo ( fileName ) , e ) ; } } else { listener . getLogger ( ) . println ( "Verified agent jar. No update is necessary." ) ; } } catch ( Error error ) { throw error ; } catch ( Throwable e ) { throw new IOException ( Messages . SSHLauncher_ErrorCopyingAgentJarInto ( workingDirectory ) , e ) ; } } catch ( IOException e ) { if ( sftpClient == null ) { e . printStackTrace ( listener . error ( Messages . SSHLauncher_StartingSCPClient ( getTimestamp ( ) ) ) ) ; copySlaveJarUsingSCP ( listener , workingDirectory ) ; } else { throw e ; } } finally { if ( sftpClient != null ) { sftpClient . close ( ) ; } } }
|
Method copies the agent jar to the remote system .
|
37,689
|
static String getMd5Hash ( byte [ ] bytes ) throws NoSuchAlgorithmException { String hash ; try { MessageDigest md = MessageDigest . getInstance ( "MD5" ) ; md . update ( bytes ) ; byte [ ] digest = md . digest ( ) ; char [ ] hexCode = "0123456789ABCDEF" . toCharArray ( ) ; StringBuilder r = new StringBuilder ( digest . length * 2 ) ; for ( byte b : digest ) { r . append ( hexCode [ ( b >> 4 ) & 0xF ] ) ; r . append ( hexCode [ ( b & 0xF ) ] ) ; } hash = r . toString ( ) . toUpperCase ( ) ; } catch ( NoSuchAlgorithmException e ) { throw e ; } return hash ; }
|
Method reads a byte array and returns an upper case md5 hash for it .
|
37,690
|
static byte [ ] readInputStreamIntoByteArrayAndClose ( InputStream inputStream ) throws IOException { byte [ ] bytes = null ; try { bytes = ByteStreams . toByteArray ( inputStream ) ; } catch ( IOException e ) { throw e ; } finally { IOUtils . closeQuietly ( inputStream ) ; if ( bytes == null ) { bytes = new byte [ 1 ] ; } } return bytes ; }
|
Method reads an input stream into a byte array and closes the input stream when finished . Added for reading the remoting jar and generating a hash value for it .
|
37,691
|
private void copySlaveJarUsingSCP ( TaskListener listener , String workingDirectory ) throws IOException , InterruptedException { SCPClient scp = new SCPClient ( connection ) ; try { if ( connection . exec ( "test -d " + workingDirectory , listener . getLogger ( ) ) != 0 ) { listener . getLogger ( ) . println ( Messages . SSHLauncher_RemoteFSDoesNotExist ( getTimestamp ( ) , workingDirectory ) ) ; if ( connection . exec ( "mkdir -p " + workingDirectory , listener . getLogger ( ) ) != 0 ) { listener . getLogger ( ) . println ( "Failed to create " + workingDirectory ) ; } } connection . exec ( "rm " + workingDirectory + SLASH_AGENT_JAR , new NullStream ( ) ) ; listener . getLogger ( ) . println ( Messages . SSHLauncher_CopyingAgentJar ( getTimestamp ( ) ) ) ; scp . put ( new Slave . JnlpJar ( AGENT_JAR ) . readFully ( ) , AGENT_JAR , workingDirectory , "0644" ) ; } catch ( IOException e ) { throw new IOException ( Messages . SSHLauncher_ErrorCopyingAgentJarInto ( workingDirectory ) , e ) ; } }
|
Method copies the agent jar to the remote system using scp .
|
37,692
|
private boolean reportTransportLoss ( Connection c , TaskListener listener ) { Throwable cause = c . getReasonClosedCause ( ) ; if ( cause != null ) { cause . printStackTrace ( listener . error ( "Socket connection to SSH server was lost" ) ) ; } return cause != null ; }
|
If the SSH connection as a whole is lost report that information .
|
37,693
|
private String getSessionOutcomeMessage ( Session session , boolean isConnectionLost ) throws InterruptedException { session . waitForCondition ( ChannelCondition . EXIT_STATUS | ChannelCondition . EXIT_SIGNAL , 3000 ) ; Integer exitCode = session . getExitStatus ( ) ; if ( exitCode != null ) return "Slave JVM has terminated. Exit code=" + exitCode ; String sig = session . getExitSignal ( ) ; if ( sig != null ) return "Slave JVM has terminated. Exit signal=" + sig ; if ( isConnectionLost ) return "Slave JVM has not reported exit code before the socket was lost" ; return "Slave JVM has not reported exit code. Is it still running?" ; }
|
Find the exit code or exit status which are differentiated in SSH protocol .
|
37,694
|
static TrileadVersionSupport getTrileadSupport ( ) { try { if ( isAfterTrilead8 ( ) ) { return createVersion9Instance ( ) ; } } catch ( Exception | LinkageError e ) { LOGGER . log ( Level . WARNING , "Could not create Trilead support class. Using legacy Trilead features" , e ) ; } return new LegacyTrileadVersionSupport ( ) ; }
|
Craetes an instance of TrileadVersionSupport that can provide functionality relevant to the version of Trilead available in the current executing instance of Jenkins .
|
37,695
|
protected String resolveJava ( ) throws InterruptedException , IOException { for ( JavaProvider provider : JavaProvider . all ( ) ) { for ( String javaCommand : provider . getJavas ( computer , listener , connection ) ) { LOGGER . fine ( "Trying Java at " + javaCommand ) ; try { return checkJavaVersion ( listener , javaCommand ) ; } catch ( IOException e ) { LOGGER . log ( FINE , "Failed to check the Java version" , e ) ; } } } throw new IOException ( "Java not found on " + computer + ". Install a Java 8 version on the Agent." ) ; }
|
return javaPath if specified in the configuration . Finds local Java .
|
37,696
|
public HostKey getHostKey ( Computer host ) throws IOException { HostKey key = cache . get ( host ) ; if ( null == key ) { File hostKeyFile = getSshHostKeyFile ( host . getNode ( ) ) ; if ( hostKeyFile . exists ( ) ) { XmlFile xmlHostKeyFile = new XmlFile ( hostKeyFile ) ; key = ( HostKey ) xmlHostKeyFile . read ( ) ; } else { key = null ; } cache . put ( host , key ) ; } return key ; }
|
Retrieve the currently trusted host key for the requested computer or null if no key is currently trusted .
|
37,697
|
public void saveHostKey ( Computer host , HostKey hostKey ) throws IOException { XmlFile xmlHostKeyFile = new XmlFile ( getSshHostKeyFile ( host . getNode ( ) ) ) ; xmlHostKeyFile . write ( hostKey ) ; cache . put ( host , hostKey ) ; }
|
Persists an SSH key to disk for the requested host . This effectively marks the requested key as trusted for all future connections to the host until any future save attempt replaces this key .
|
37,698
|
public void mkdirs ( String path , int posixPermission ) throws IOException { SFTPv3FileAttributes atts = _stat ( path ) ; if ( atts != null && atts . isDirectory ( ) ) return ; int idx = path . lastIndexOf ( '/' ) ; if ( idx > 0 ) mkdirs ( path . substring ( 0 , idx ) , posixPermission ) ; try { mkdir ( path , posixPermission ) ; } catch ( IOException e ) { throw new IOException ( "Failed to mkdir " + path , e ) ; } }
|
Makes sure that the directory exists by creating it if necessary .
|
37,699
|
public void chmod ( String path , int permissions ) throws IOException { SFTPv3FileAttributes atts = new SFTPv3FileAttributes ( ) ; atts . permissions = permissions ; setstat ( path , atts ) ; }
|
Change file or directory permissions .
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.