idx
int64 0
165k
| question
stringlengths 73
4.15k
| target
stringlengths 5
918
| len_question
int64 21
890
| len_target
int64 3
255
|
|---|---|---|---|---|
151,900
|
static public String getDateAsString ( Date date , SnowflakeDateTimeFormat dateFormatter ) { return dateFormatter . format ( date , timeZoneUTC ) ; }
|
Convert a date value into a string
| 36
| 8
|
151,901
|
static public Date adjustDate ( Date date ) { long milliToAdjust = ResultUtil . msDiffJulianToGregorian ( date ) ; if ( milliToAdjust != 0 ) { // add the difference to the new date return new Date ( date . getTime ( ) + milliToAdjust ) ; } else { return date ; } }
|
Adjust date for before 1582 - 10 - 05
| 74
| 10
|
151,902
|
static public Date getDate ( String str , TimeZone tz , SFSession session ) throws SFException { try { long milliSecsSinceEpoch = Long . valueOf ( str ) * 86400000 ; SFTimestamp tsInUTC = SFTimestamp . fromDate ( new Date ( milliSecsSinceEpoch ) , 0 , TimeZone . getTimeZone ( "UTC" ) ) ; SFTimestamp tsInClientTZ = tsInUTC . moveToTimeZone ( tz ) ; if ( logger . isDebugEnabled ( ) ) { logger . debug ( "getDate: tz offset={}" , tsInClientTZ . getTimeZone ( ) . getOffset ( tsInClientTZ . getTime ( ) ) ) ; } // return the date adjusted to the JVM default time zone Date preDate = new Date ( tsInClientTZ . getTime ( ) ) ; // if date is on or before 1582-10-04, apply the difference // by (H-H/4-2) where H is the hundreds digit of the year according to: // http://en.wikipedia.org/wiki/Gregorian_calendar Date newDate = adjustDate ( preDate ) ; if ( logger . isDebugEnabled ( ) ) { logger . debug ( "Adjust date from {} to {}" , preDate . toString ( ) , newDate . toString ( ) ) ; } return newDate ; } catch ( NumberFormatException ex ) { throw ( SFException ) IncidentUtil . generateIncidentV2WithException ( session , new SFException ( ErrorCode . INTERNAL_ERROR , "Invalid date value: " + str ) , null , null ) ; } }
|
Convert a date internal object to a Date object in specified timezone .
| 368
| 15
|
151,903
|
static public int calculateUpdateCount ( SFBaseResultSet resultSet ) throws SFException , SQLException { int updateCount = 0 ; SFStatementType statementType = resultSet . getStatementType ( ) ; if ( statementType . isDML ( ) ) { while ( resultSet . next ( ) ) { if ( statementType == SFStatementType . COPY ) { SFResultSetMetaData resultSetMetaData = resultSet . getMetaData ( ) ; int columnIndex = resultSetMetaData . getColumnIndex ( "rows_loaded" ) ; updateCount += columnIndex == - 1 ? 0 : resultSet . getInt ( columnIndex + 1 ) ; } else if ( statementType == SFStatementType . INSERT || statementType == SFStatementType . UPDATE || statementType == SFStatementType . DELETE || statementType == SFStatementType . MERGE || statementType == SFStatementType . MULTI_INSERT ) { int columnCount = resultSet . getMetaData ( ) . getColumnCount ( ) ; for ( int i = 0 ; i < columnCount ; i ++ ) updateCount += resultSet . getLong ( i + 1 ) ; // add up number of rows updated } else { updateCount = 0 ; } } } else { updateCount = statementType . isGenerateResultSet ( ) ? - 1 : 0 ; } return updateCount ; }
|
Calculate number of rows updated given a result set Interpret result format based on result set s statement type
| 293
| 21
|
151,904
|
public static int listSearchCaseInsensitive ( List < String > source , String target ) { for ( int i = 0 ; i < source . size ( ) ; i ++ ) { if ( target . equalsIgnoreCase ( source . get ( i ) ) ) { return i ; } } return - 1 ; }
|
Given a list of String do a case insensitive search for target string Used by resultsetMetadata to search for target column name
| 66
| 25
|
151,905
|
private static List < String > getResultIds ( JsonNode result ) { JsonNode resultIds = result . path ( "data" ) . path ( "resultIds" ) ; if ( resultIds . isNull ( ) || resultIds . isMissingNode ( ) || resultIds . asText ( ) . isEmpty ( ) ) { return Collections . emptyList ( ) ; } return new ArrayList <> ( Arrays . asList ( resultIds . asText ( ) . split ( "," ) ) ) ; }
|
Return the list of result IDs provided in a result if available ; otherwise return an empty list .
| 118
| 19
|
151,906
|
private static List < SFStatementType > getResultTypes ( JsonNode result ) { JsonNode resultTypes = result . path ( "data" ) . path ( "resultTypes" ) ; if ( resultTypes . isNull ( ) || resultTypes . isMissingNode ( ) || resultTypes . asText ( ) . isEmpty ( ) ) { return Collections . emptyList ( ) ; } String [ ] typeStrs = resultTypes . asText ( ) . split ( "," ) ; List < SFStatementType > res = new ArrayList <> ( ) ; for ( String typeStr : typeStrs ) { long typeId = Long . valueOf ( typeStr ) ; res . add ( SFStatementType . lookUpTypeById ( typeId ) ) ; } return res ; }
|
Return the list of result types provided in a result if available ; otherwise return an empty list .
| 167
| 19
|
151,907
|
public static List < SFChildResult > getChildResults ( SFSession session , String requestId , JsonNode result ) throws SFException { List < String > ids = getResultIds ( result ) ; List < SFStatementType > types = getResultTypes ( result ) ; if ( ids . size ( ) != types . size ( ) ) { throw ( SFException ) IncidentUtil . generateIncidentV2WithException ( session , new SFException ( ErrorCode . CHILD_RESULT_IDS_AND_TYPES_DIFFERENT_SIZES , ids . size ( ) , types . size ( ) ) , null , requestId ) ; } List < SFChildResult > res = new ArrayList <> ( ) ; for ( int i = 0 ; i < ids . size ( ) ; i ++ ) { res . add ( new SFChildResult ( ids . get ( i ) , types . get ( i ) ) ) ; } return res ; }
|
Return the list of child results provided in a result if available ; otherwise return an empty list
| 213
| 18
|
151,908
|
private synchronized void openFile ( ) { try { String fName = _directory . getAbsolutePath ( ) + File . separatorChar + StreamLoader . FILE_PREFIX + _stamp + _fileCount ; if ( _loader . _compressDataBeforePut ) { fName += StreamLoader . FILE_SUFFIX ; } LOGGER . debug ( "openFile: {}" , fName ) ; OutputStream fileStream = new FileOutputStream ( fName ) ; if ( _loader . _compressDataBeforePut ) { OutputStream gzipOutputStream = new GZIPOutputStream ( fileStream , 64 * 1024 , true ) { { def . setLevel ( ( int ) _loader . _compressLevel ) ; } } ; _outstream = new BufferedOutputStream ( gzipOutputStream ) ; } else { _outstream = new BufferedOutputStream ( fileStream ) ; } _file = new File ( fName ) ; _fileCount ++ ; } catch ( IOException ex ) { _loader . abort ( new Loader . ConnectionError ( Utils . getCause ( ex ) ) ) ; } }
|
Create local file for caching data before upload
| 243
| 8
|
151,909
|
boolean stageData ( final byte [ ] line ) throws IOException { if ( this . _rowCount % 10000 == 0 ) { LOGGER . debug ( "rowCount: {}, currentSize: {}" , this . _rowCount , _currentSize ) ; } _outstream . write ( line ) ; _currentSize += line . length ; _outstream . write ( newLineBytes ) ; this . _rowCount ++ ; if ( _loader . _testRemoteBadCSV ) { // inject garbage for a negative test case // The file will be uploaded to the stage, but COPY command will // fail and raise LoaderError _outstream . write ( new byte [ ] { ( byte ) 0x01 , ( byte ) 0x02 } ) ; _outstream . write ( newLineBytes ) ; this . _rowCount ++ ; } if ( _currentSize >= this . _csvFileSize ) { LOGGER . debug ( "name: {}, currentSize: {}, Threshold: {}," + " fileCount: {}, fileBucketSize: {}" , _file . getAbsolutePath ( ) , _currentSize , this . _csvFileSize , _fileCount , this . _csvFileBucketSize ) ; _outstream . flush ( ) ; _outstream . close ( ) ; _outstream = null ; FileUploader fu = new FileUploader ( _loader , _location , _file ) ; fu . upload ( ) ; _uploaders . add ( fu ) ; openFile ( ) ; _currentSize = 0 ; } return _fileCount > this . _csvFileBucketSize ; }
|
not thread safe
| 349
| 3
|
151,910
|
void completeUploading ( ) throws IOException { LOGGER . debug ( "name: {}, currentSize: {}, Threshold: {}," + " fileCount: {}, fileBucketSize: {}" , _file . getAbsolutePath ( ) , _currentSize , this . _csvFileSize , _fileCount , this . _csvFileBucketSize ) ; _outstream . flush ( ) ; _outstream . close ( ) ; //last file if ( _currentSize > 0 ) { FileUploader fu = new FileUploader ( _loader , _location , _file ) ; fu . upload ( ) ; _uploaders . add ( fu ) ; } else { // delete empty file _file . delete ( ) ; } for ( FileUploader fu : _uploaders ) { // Finish all files being uploaded fu . join ( ) ; } // Delete the directory once we are done (for easier tracking // of what is going on) _directory . deleteOnExit ( ) ; if ( this . _rowCount == 0 ) { setState ( State . EMPTY ) ; } }
|
Wait for all files to finish uploading and schedule stage for processing
| 233
| 12
|
151,911
|
private static String escapeFileSeparatorChar ( String fname ) { if ( File . separatorChar == ' ' ) { return fname . replaceAll ( File . separator + File . separator , "_" ) ; } else { return fname . replaceAll ( File . separator , "_" ) ; } }
|
Escape file separator char to underscore . This prevents the file name from using file path separator .
| 69
| 21
|
151,912
|
@ CheckForNull private Object executeSyncMethod ( Method method , Object [ ] args ) throws ApplicationException { if ( preparingForShutdown . get ( ) ) { throw new JoynrIllegalStateException ( "Preparing for shutdown. Only stateless methods can be called." ) ; } return executeMethodWithCaller ( method , args , new ConnectorCaller ( ) { @ Override public Object call ( Method method , Object [ ] args ) throws ApplicationException { return connector . executeSyncMethod ( method , args ) ; } } ) ; }
|
executeSyncMethod is called whenever a method of the synchronous interface which is provided by the proxy is called . The ProxyInvocationHandler will check the arbitration status before the call is delegated to the connector . If the arbitration is still in progress the synchronous call will block until the arbitration was successful or the timeout elapsed .
| 115
| 64
|
151,913
|
public boolean waitForConnectorFinished ( ) throws InterruptedException { connectorStatusLock . lock ( ) ; try { if ( connectorStatus == ConnectorStatus . ConnectorSuccesful ) { return true ; } return connectorSuccessfullyFinished . await ( discoveryQos . getDiscoveryTimeoutMs ( ) , TimeUnit . MILLISECONDS ) ; } finally { connectorStatusLock . unlock ( ) ; } }
|
Checks the connector status before a method call is executed . Instantly returns True if the connector already finished successfully otherwise it will block up to the amount of milliseconds defined by the arbitrationTimeout or until the ProxyInvocationHandler is notified about a successful connection .
| 89
| 51
|
151,914
|
public boolean isConnectorReady ( ) { connectorStatusLock . lock ( ) ; try { if ( connectorStatus == ConnectorStatus . ConnectorSuccesful ) { return true ; } return false ; } finally { connectorStatusLock . unlock ( ) ; } }
|
Checks if the connector was set successfully . Returns immediately and does not block until the connector is finished .
| 55
| 21
|
151,915
|
private void sendQueuedInvocations ( ) { while ( true ) { MethodInvocation < ? > currentRPC = queuedRpcList . poll ( ) ; if ( currentRPC == null ) { return ; } try { connector . executeAsyncMethod ( currentRPC . getProxy ( ) , currentRPC . getMethod ( ) , currentRPC . getArgs ( ) , currentRPC . getFuture ( ) ) ; } catch ( JoynrRuntimeException e ) { currentRPC . getFuture ( ) . onFailure ( e ) ; } catch ( Exception e ) { currentRPC . getFuture ( ) . onFailure ( new JoynrRuntimeException ( e ) ) ; } } }
|
Executes previously queued remote calls . This method is called when arbitration is completed .
| 150
| 17
|
151,916
|
@ Override public void createConnector ( ArbitrationResult result ) { connector = connectorFactory . create ( proxyParticipantId , result , qosSettings , statelessAsyncParticipantId ) ; connectorStatusLock . lock ( ) ; try { connectorStatus = ConnectorStatus . ConnectorSuccesful ; connectorSuccessfullyFinished . signalAll ( ) ; if ( connector != null ) { sendQueuedInvocations ( ) ; sendQueuedSubscriptionInvocations ( ) ; sendQueuedUnsubscribeInvocations ( ) ; sendQueuedStatelessAsyncInvocations ( ) ; } } finally { connectorStatusLock . unlock ( ) ; } }
|
Sets the connector for this ProxyInvocationHandler after the DiscoveryAgent got notified about a successful arbitration . Should be called from the DiscoveryAgent
| 140
| 28
|
151,917
|
@ GET @ Produces ( { MediaType . TEXT_PLAIN } ) public String getTime ( ) { return String . valueOf ( System . currentTimeMillis ( ) ) ; }
|
get server time in ms
| 40
| 5
|
151,918
|
public static int findFreePort ( ) throws IOException { ServerSocket socket = null ; try { socket = new ServerSocket ( 0 ) ; return socket . getLocalPort ( ) ; } finally { if ( socket != null ) { socket . close ( ) ; } } }
|
Find a free port on the test system to be used by the servlet engine
| 57
| 16
|
151,919
|
@ DELETE @ Path ( "/clusters/{clusterid: ([A-Z,a-z,0-9,_,\\-]+)}" ) public Response migrateCluster ( @ PathParam ( "clusterid" ) final String clusterId ) { // as this is a long running task, this has to be asynchronous migrationService . startClusterMigration ( clusterId ) ; return Response . status ( 202 /* Accepted */ ) . build ( ) ; }
|
Migrates all bounce proxies of one cluster to a different cluster .
| 103
| 14
|
151,920
|
public String buildReportStartupUrl ( ControlledBounceProxyUrl controlledBounceProxyUrl ) throws UnsupportedEncodingException { String url4cc = URLEncoder . encode ( controlledBounceProxyUrl . getOwnUrlForClusterControllers ( ) , "UTF-8" ) ; String url4bpc = URLEncoder . encode ( controlledBounceProxyUrl . getOwnUrlForBounceProxyController ( ) , "UTF-8" ) ; return baseUrl + // "?bpid=" + this . bounceProxyId + // "&url4cc=" + url4cc + // "&url4bpc=" + url4bpc ; }
|
Returns the URL including query parameters to report bounce proxy startup .
| 143
| 12
|
151,921
|
@ POST @ Consumes ( { MediaType . APPLICATION_OCTET_STREAM } ) public Response postMessageWithoutContentType ( @ PathParam ( "ccid" ) String ccid , byte [ ] serializedMessage ) throws IOException { ImmutableMessage message ; try { message = new ImmutableMessage ( serializedMessage ) ; } catch ( EncodingException | UnsuppportedVersionException e ) { log . error ( "Failed to deserialize SMRF message: {}" , e . getMessage ( ) ) ; throw new WebApplicationException ( e ) ; } try { String msgId = message . getId ( ) ; log . debug ( "******POST message {} to cluster controller: {}" , msgId , ccid ) ; log . trace ( "******POST message {} to cluster controller: {} extended info: \r\n {}" , ccid , message ) ; response . setCharacterEncoding ( "UTF-8" ) ; // the location that can be queried to get the message // status // TODO REST URL for message status? String path = longPollingDelegate . postMessage ( ccid , serializedMessage ) ; URI location = ui . getBaseUriBuilder ( ) . path ( path ) . build ( ) ; // return the message status location to the sender. return Response . created ( location ) . header ( "msgId" , msgId ) . build ( ) ; } catch ( WebApplicationException e ) { log . error ( "Invalid request from host {}" , request . getRemoteHost ( ) ) ; throw e ; } catch ( Exception e ) { log . error ( "POST message for cluster controller: error: {}" , e . getMessage ( ) ) ; throw new WebApplicationException ( e ) ; } }
|
Send a message to the given cluster controller like the above method postMessage
| 379
| 14
|
151,922
|
public SubscriptionQos setValidityMs ( final long validityMs ) { if ( validityMs == - 1 ) { setExpiryDateMs ( NO_EXPIRY_DATE ) ; } else { long now = System . currentTimeMillis ( ) ; this . expiryDateMs = now + validityMs ; } return this ; }
|
Set how long the subscription should run for in milliseconds . This is a helper method that allows setting the expiryDate using a relative time .
| 74
| 28
|
151,923
|
public List < ChannelInformation > listChannels ( ) { LinkedList < ChannelInformation > entries = new LinkedList < ChannelInformation > ( ) ; Collection < Broadcaster > broadcasters = BroadcasterFactory . getDefault ( ) . lookupAll ( ) ; String name ; for ( Broadcaster broadcaster : broadcasters ) { if ( broadcaster instanceof BounceProxyBroadcaster ) { name = ( ( BounceProxyBroadcaster ) broadcaster ) . getName ( ) ; } else { name = broadcaster . getClass ( ) . getSimpleName ( ) ; } Integer cachedSize = null ; entries . add ( new ChannelInformation ( name , broadcaster . getAtmosphereResources ( ) . size ( ) , cachedSize ) ) ; } return entries ; }
|
Gets a list of all channel information .
| 152
| 9
|
151,924
|
public String createChannel ( String ccid , String atmosphereTrackingId ) { throwExceptionIfTrackingIdnotSet ( atmosphereTrackingId ) ; log . info ( "CREATE channel for cluster controller: {} trackingId: {} " , ccid , atmosphereTrackingId ) ; Broadcaster broadcaster = null ; // look for an existing broadcaster BroadcasterFactory defaultBroadcasterFactory = BroadcasterFactory . getDefault ( ) ; if ( defaultBroadcasterFactory == null ) { throw new JoynrHttpException ( 500 , 10009 , "broadcaster was null" ) ; } broadcaster = defaultBroadcasterFactory . lookup ( Broadcaster . class , ccid , false ) ; // create a new one if none already exists if ( broadcaster == null ) { broadcaster = defaultBroadcasterFactory . get ( BounceProxyBroadcaster . class , ccid ) ; } // avoids error where previous long poll from browser got message // destined for new long poll // especially as seen in js, where every second refresh caused a fail for ( AtmosphereResource resource : broadcaster . getAtmosphereResources ( ) ) { if ( resource . uuid ( ) != null && resource . uuid ( ) . equals ( atmosphereTrackingId ) ) { resource . resume ( ) ; } } UUIDBroadcasterCache broadcasterCache = ( UUIDBroadcasterCache ) broadcaster . getBroadcasterConfig ( ) . getBroadcasterCache ( ) ; broadcasterCache . activeClients ( ) . put ( atmosphereTrackingId , System . currentTimeMillis ( ) ) ; // BroadcasterCacheInspector is not implemented corrected in Atmosphere // 1.1.0RC4 // broadcasterCache.inspector(new MessageExpirationInspector()); return "/channels/" + ccid + "/" ; }
|
Creates a long polling channel .
| 368
| 7
|
151,925
|
public boolean deleteChannel ( String ccid ) { log . info ( "DELETE channel for cluster controller: " + ccid ) ; Broadcaster broadcaster = BroadcasterFactory . getDefault ( ) . lookup ( Broadcaster . class , ccid , false ) ; if ( broadcaster == null ) { return false ; } BroadcasterFactory . getDefault ( ) . remove ( ccid ) ; broadcaster . resumeAll ( ) ; broadcaster . destroy ( ) ; // broadcaster.getBroadcasterConfig().forceDestroy(); return true ; }
|
Deletes a channel from the broadcaster .
| 109
| 8
|
151,926
|
public String postMessage ( String ccid , byte [ ] serializedMessage ) { ImmutableMessage message ; try { message = new ImmutableMessage ( serializedMessage ) ; } catch ( EncodingException | UnsuppportedVersionException e ) { throw new JoynrHttpException ( Status . BAD_REQUEST , JOYNRMESSAGINGERROR_DESERIALIZATIONFAILED ) ; } if ( ccid == null ) { log . error ( "POST message {} to cluster controller: NULL. Dropped because: channel Id was not set." , message . getId ( ) ) ; throw new JoynrHttpException ( Status . BAD_REQUEST , JOYNRMESSAGINGERROR_CHANNELNOTSET ) ; } // send the message to the receiver. if ( message . getTtlMs ( ) == 0 ) { log . error ( "POST message {} to cluster controller: {} dropped because: expiry date not set" , ccid , message . getId ( ) ) ; throw new JoynrHttpException ( Status . BAD_REQUEST , JOYNRMESSAGINGERROR_EXPIRYDATENOTSET ) ; } // Relative TTLs are not supported yet. if ( ! message . isTtlAbsolute ( ) ) { throw new JoynrHttpException ( Status . BAD_REQUEST , JOYNRMESSAGINGERROR_RELATIVE_TTL_UNSPORTED ) ; } if ( message . getTtlMs ( ) < System . currentTimeMillis ( ) ) { log . warn ( "POST message {} to cluster controller: {} dropped because: TTL expired" , ccid , message . getId ( ) ) ; throw new JoynrHttpException ( Status . BAD_REQUEST , JOYNRMESSAGINGERROR_EXPIRYDATEEXPIRED ) ; } // look for an existing broadcaster Broadcaster ccBroadcaster = BroadcasterFactory . getDefault ( ) . lookup ( Broadcaster . class , ccid , false ) ; if ( ccBroadcaster == null ) { // if the receiver has never registered with the bounceproxy // (or his registration has expired) then return 204 no // content. log . error ( "POST message {} to cluster controller: {} dropped because: no channel found" , ccid , message . getId ( ) ) ; throw new JoynrHttpException ( Status . BAD_REQUEST , JOYNRMESSAGINGERROR_CHANNELNOTFOUND ) ; } if ( ccBroadcaster . getAtmosphereResources ( ) . size ( ) == 0 ) { log . debug ( "no poll currently waiting for channelId: {}" , ccid ) ; } ccBroadcaster . broadcast ( message ) ; return "messages/" + message . getId ( ) ; }
|
Posts a message to a long polling channel .
| 593
| 9
|
151,927
|
private void asyncGetGlobalCapabilitities ( final String [ ] domains , final String interfaceName , Collection < DiscoveryEntryWithMetaInfo > localDiscoveryEntries2 , long discoveryTimeout , final CapabilitiesCallback capabilitiesCallback ) { final Collection < DiscoveryEntryWithMetaInfo > localDiscoveryEntries = localDiscoveryEntries2 == null ? new LinkedList < DiscoveryEntryWithMetaInfo > ( ) : localDiscoveryEntries2 ; globalCapabilitiesDirectoryClient . lookup ( new Callback < List < GlobalDiscoveryEntry > > ( ) { @ Override public void onSuccess ( List < GlobalDiscoveryEntry > globalDiscoverEntries ) { if ( globalDiscoverEntries != null ) { registerIncomingEndpoints ( globalDiscoverEntries ) ; globalDiscoveryEntryCache . add ( globalDiscoverEntries ) ; Collection < DiscoveryEntryWithMetaInfo > allDisoveryEntries = new ArrayList < DiscoveryEntryWithMetaInfo > ( globalDiscoverEntries . size ( ) + localDiscoveryEntries . size ( ) ) ; allDisoveryEntries . addAll ( CapabilityUtils . convertToDiscoveryEntryWithMetaInfoList ( false , globalDiscoverEntries ) ) ; allDisoveryEntries . addAll ( localDiscoveryEntries ) ; capabilitiesCallback . processCapabilitiesReceived ( allDisoveryEntries ) ; } else { capabilitiesCallback . onError ( new NullPointerException ( "Received capabilities are null" ) ) ; } } @ Override public void onFailure ( JoynrRuntimeException exception ) { capabilitiesCallback . onError ( exception ) ; } } , domains , interfaceName , discoveryTimeout ) ; }
|
mixes in the localDiscoveryEntries to global capabilities found by participantId
| 347
| 16
|
151,928
|
public static boolean isSessionEncodedInUrl ( String encodedUrl , String sessionIdName ) { int sessionIdIndex = encodedUrl . indexOf ( getSessionIdSubstring ( sessionIdName ) ) ; return sessionIdIndex >= 0 ; }
|
Returns whether the session ID is encoded into the URL .
| 51
| 11
|
151,929
|
public static String getUrlWithoutSessionId ( String url , String sessionIdName ) { if ( isSessionEncodedInUrl ( url , sessionIdName ) ) { return url . substring ( 0 , url . indexOf ( getSessionIdSubstring ( sessionIdName ) ) ) ; } return url ; }
|
Returns the URL without the session encoded into the URL .
| 66
| 11
|
151,930
|
public static String getSessionEncodedUrl ( String url , String sessionIdName , String sessionId ) { return url + getSessionIdSubstring ( sessionIdName ) + sessionId ; }
|
Returns a url with the session encoded into the URL
| 40
| 10
|
151,931
|
private void stopPublicationByProviderId ( String providerParticipantId ) { for ( PublicationInformation publicationInformation : subscriptionId2PublicationInformation . values ( ) ) { if ( publicationInformation . getProviderParticipantId ( ) . equals ( providerParticipantId ) ) { removePublication ( publicationInformation . getSubscriptionId ( ) ) ; } } if ( providerParticipantId != null && queuedSubscriptionRequests . containsKey ( providerParticipantId ) ) { queuedSubscriptionRequests . removeAll ( providerParticipantId ) ; } }
|
Stops all publications for a provider
| 118
| 7
|
151,932
|
private void restoreQueuedSubscription ( String providerId , ProviderContainer providerContainer ) { Collection < PublicationInformation > queuedRequests = queuedSubscriptionRequests . get ( providerId ) ; Iterator < PublicationInformation > queuedRequestsIterator = queuedRequests . iterator ( ) ; while ( queuedRequestsIterator . hasNext ( ) ) { PublicationInformation publicationInformation = queuedRequestsIterator . next ( ) ; queuedRequestsIterator . remove ( ) ; if ( ! isExpired ( publicationInformation ) ) { addSubscriptionRequest ( publicationInformation . getProxyParticipantId ( ) , publicationInformation . getProviderParticipantId ( ) , publicationInformation . subscriptionRequest , providerContainer ) ; } } }
|
Called every time a provider is registered to check whether there are already subscriptionRequests waiting .
| 153
| 19
|
151,933
|
public static URI createChannelLocation ( ControlledBounceProxyInformation bpInfo , String ccid , URI location ) { return URI . create ( location . toString ( ) + ";jsessionid=." + bpInfo . getInstanceId ( ) ) ; }
|
Creates the channel location that is returned to the cluster controller . This includes tweaking of the URL for example to contain a session ID .
| 56
| 27
|
151,934
|
@ GET @ Produces ( "application/json" ) public GenericEntity < List < ChannelInformation > > listChannels ( ) { try { return new GenericEntity < List < ChannelInformation > > ( channelService . listChannels ( ) ) { } ; } catch ( Exception e ) { log . error ( "GET channels listChannels: error: {}" , e . getMessage ( ) , e ) ; throw new WebApplicationException ( Status . INTERNAL_SERVER_ERROR ) ; } }
|
A simple HTML list view of channels . A JSP is used for rendering .
| 107
| 16
|
151,935
|
@ GET @ Path ( "/{ccid: [A-Z,a-z,0-9,_,\\-,\\.]+}" ) @ Produces ( { MediaType . APPLICATION_JSON } ) @ Suspend ( resumeOnBroadcast = true , period = ChannelServiceConstants . EXPIRE_TIME_CONNECTION , timeUnit = TimeUnit . SECONDS , contentType = MediaType . APPLICATION_JSON ) public Broadcastable open ( @ PathParam ( "ccid" ) String ccid , @ HeaderParam ( "X-Cache-Index" ) Integer cacheIndex , @ HeaderParam ( ChannelServiceConstants . X_ATMOSPHERE_TRACKING_ID ) String atmosphereTrackingId ) { try { return channelService . openChannel ( ccid , cacheIndex , atmosphereTrackingId ) ; } catch ( WebApplicationException e ) { throw e ; } catch ( Exception e ) { log . error ( "GET Channels open long poll ccid: error: {}" , e . getMessage ( ) , e ) ; throw new WebApplicationException ( Status . INTERNAL_SERVER_ERROR ) ; } }
|
Open a long poll channel for the given cluster controller . The channel is closed automatically by the server at regular intervals to ensure liveliness .
| 248
| 27
|
151,936
|
@ POST @ Produces ( { MediaType . TEXT_PLAIN } ) public Response createChannel ( @ QueryParam ( "ccid" ) String ccid , @ HeaderParam ( ChannelServiceConstants . X_ATMOSPHERE_TRACKING_ID ) String atmosphereTrackingId ) { try { log . info ( "CREATE channel for channel ID: {}" , ccid ) ; if ( ccid == null || ccid . isEmpty ( ) ) throw new JoynrHttpException ( Status . BAD_REQUEST , JOYNRMESSAGINGERROR_CHANNELNOTSET ) ; Channel channel = channelService . getChannel ( ccid ) ; if ( channel != null ) { String encodedChannelLocation = response . encodeURL ( channel . getLocation ( ) . toString ( ) ) ; return Response . ok ( ) . entity ( encodedChannelLocation ) . header ( "Location" , encodedChannelLocation ) . header ( "bp" , channel . getBounceProxy ( ) . getId ( ) ) . build ( ) ; } // look for an existing bounce proxy handling the channel channel = channelService . createChannel ( ccid , atmosphereTrackingId ) ; String encodedChannelLocation = response . encodeURL ( channel . getLocation ( ) . toString ( ) ) ; log . debug ( "encoded channel URL " + channel . getLocation ( ) + " to " + encodedChannelLocation ) ; return Response . created ( URI . create ( encodedChannelLocation ) ) . entity ( encodedChannelLocation ) . header ( "bp" , channel . getBounceProxy ( ) . getId ( ) ) . build ( ) ; } catch ( WebApplicationException ex ) { throw ex ; } catch ( Exception e ) { throw new WebApplicationException ( e ) ; } }
|
HTTP POST to create a channel returns location to new resource which can then be long polled . Since the channel id may later change to be a UUID not using a PUT but rather POST with used id being returned
| 379
| 43
|
151,937
|
@ DELETE @ Path ( "/{ccid: [A-Z,a-z,0-9,_,\\-,\\.]+}" ) public Response deleteChannel ( @ PathParam ( "ccid" ) String ccid ) { try { log . info ( "DELETE channel for cluster controller: {}" , ccid ) ; if ( channelService . deleteChannel ( ccid ) ) { return Response . ok ( ) . build ( ) ; } return Response . noContent ( ) . build ( ) ; } catch ( WebApplicationException e ) { throw e ; } catch ( Exception e ) { log . error ( "DELETE channel for cluster controller: error: {}" , e . getMessage ( ) , e ) ; throw new WebApplicationException ( Status . INTERNAL_SERVER_ERROR ) ; } }
|
Remove the channel for the given cluster controller .
| 179
| 9
|
151,938
|
private synchronized boolean createChannel ( ) { final String url = settings . getBounceProxyUrl ( ) . buildCreateChannelUrl ( channelId ) ; HttpPost postCreateChannel = httpRequestFactory . createHttpPost ( URI . create ( url . trim ( ) ) ) ; postCreateChannel . setConfig ( defaultRequestConfig ) ; postCreateChannel . addHeader ( httpConstants . getHEADER_X_ATMOSPHERE_TRACKING_ID ( ) , receiverId ) ; postCreateChannel . addHeader ( httpConstants . getHEADER_CONTENT_TYPE ( ) , httpConstants . getAPPLICATION_JSON ( ) ) ; channelUrl = null ; CloseableHttpResponse response = null ; boolean created = false ; try { response = httpclient . execute ( postCreateChannel ) ; StatusLine statusLine = response . getStatusLine ( ) ; int statusCode = statusLine . getStatusCode ( ) ; String reasonPhrase = statusLine . getReasonPhrase ( ) ; switch ( statusCode ) { case HttpURLConnection . HTTP_OK : case HttpURLConnection . HTTP_CREATED : try { Header locationHeader = response . getFirstHeader ( httpConstants . getHEADER_LOCATION ( ) ) ; channelUrl = locationHeader != null ? locationHeader . getValue ( ) : null ; } catch ( Exception e ) { throw new JoynrChannelMissingException ( "channel url was null" ) ; } break ; default : logger . error ( "createChannel channelId: {} failed. status: {} reason: {}" , channelId , statusCode , reasonPhrase ) ; throw new JoynrChannelMissingException ( "channel url was null" ) ; } created = true ; logger . info ( "createChannel channelId: {} returned channelUrl {}" , channelId , channelUrl ) ; } catch ( ClientProtocolException e ) { logger . error ( "createChannel ERROR reason: {}" , e . getMessage ( ) ) ; } catch ( IOException e ) { logger . error ( "createChannel ERROR reason: {}" , e . getMessage ( ) ) ; } finally { if ( response != null ) { try { response . close ( ) ; } catch ( IOException e ) { logger . error ( "createChannel ERROR reason: {}" , e . getMessage ( ) ) ; } } } return created ; }
|
Create a new channel for the given cluster controller id . If a channel already exists it is returned instead .
| 504
| 21
|
151,939
|
public static List < List < Annotation > > findAndMergeParameterAnnotations ( Method method ) { List < List < Annotation >> res = new ArrayList < List < Annotation > > ( method . getParameterTypes ( ) . length ) ; for ( int i = 0 ; i < method . getParameterTypes ( ) . length ; i ++ ) { res . add ( new LinkedList < Annotation > ( ) ) ; } findAndMergeAnnotations ( method . getDeclaringClass ( ) , method , res ) ; return res ; }
|
Utility function to find all annotations on the parameters of the specified method and merge them with the same annotations on all base classes and interfaces .
| 118
| 28
|
151,940
|
private static boolean areMethodNameAndParameterTypesEqual ( Method methodA , Method methodB ) { if ( ! methodA . getName ( ) . equals ( methodB . getName ( ) ) ) { return false ; } Class < ? > [ ] methodAParameterTypes = methodA . getParameterTypes ( ) ; Class < ? > [ ] methodBParameterTypes = methodB . getParameterTypes ( ) ; if ( methodAParameterTypes . length != methodBParameterTypes . length ) { return false ; } for ( int i = 0 ; i < methodAParameterTypes . length ; i ++ ) { if ( ! methodAParameterTypes [ i ] . equals ( methodBParameterTypes [ i ] ) ) { return false ; } } return true ; }
|
Compares to methods for equality based on name and parameter types .
| 165
| 13
|
151,941
|
protected void arbitrationFinished ( ArbitrationStatus arbitrationStatus , ArbitrationResult arbitrationResult ) { this . arbitrationStatus = arbitrationStatus ; this . arbitrationResult = arbitrationResult ; // wait for arbitration listener to be registered if ( arbitrationListenerSemaphore . tryAcquire ( ) ) { arbitrationListener . onSuccess ( arbitrationResult ) ; arbitrationListenerSemaphore . release ( ) ; } }
|
Sets the arbitration result at the arbitrationListener if the listener is already registered
| 80
| 15
|
151,942
|
@ Override public Future < Void > registerProvider ( String domain , Object provider , ProviderQos providerQos , boolean awaitGlobalRegistration , final Class < ? > interfaceClass ) { if ( interfaceClass == null ) { throw new IllegalArgumentException ( "Cannot registerProvider: interfaceClass may not be NULL" ) ; } registerInterfaceClassTypes ( interfaceClass , "Cannot registerProvider" ) ; return capabilitiesRegistrar . registerProvider ( domain , provider , providerQos , awaitGlobalRegistration ) ; }
|
Registers a provider in the joynr framework by JEE
| 108
| 12
|
151,943
|
public void setStatus ( BounceProxyStatus status ) throws IllegalStateException { // this checks if the transition is valid if ( this . status . isValidTransition ( status ) ) { this . status = status ; } else { throw new IllegalStateException ( "Illegal status transition from " + this . status + " to " + status ) ; } }
|
Sets the status of the bounce proxy .
| 74
| 9
|
151,944
|
@ POST @ Produces ( { MediaType . APPLICATION_OCTET_STREAM } ) public Response postMessage ( @ PathParam ( "ccid" ) String ccid , byte [ ] serializedMessage ) { ImmutableMessage message ; try { message = new ImmutableMessage ( serializedMessage ) ; } catch ( EncodingException | UnsuppportedVersionException e ) { throw new JoynrHttpException ( Status . BAD_REQUEST , JOYNRMESSAGINGERROR_DESERIALIZATIONFAILED ) ; } try { log . debug ( "POST message to channel: {} message: {}" , ccid , message ) ; // TODO Can this happen at all with empty path parameter??? if ( ccid == null ) { log . error ( "POST message to channel: NULL. message: {} dropped because: channel Id was not set" , message ) ; throw new JoynrHttpException ( Status . BAD_REQUEST , JOYNRMESSAGINGERROR_CHANNELNOTSET ) ; } // send the message to the receiver. if ( message . getTtlMs ( ) == 0 ) { log . error ( "POST message to channel: {} message: {} dropped because: TTL not set" , ccid , message ) ; throw new JoynrHttpException ( Status . BAD_REQUEST , JOYNRMESSAGINGERROR_EXPIRYDATENOTSET ) ; } if ( message . getTtlMs ( ) < timestampProvider . getCurrentTime ( ) ) { log . warn ( "POST message {} to cluster controller: {} dropped because: TTL expired" , ccid , message . getId ( ) ) ; throw new JoynrHttpException ( Status . BAD_REQUEST , JOYNRMESSAGINGERROR_EXPIRYDATEEXPIRED , request . getRemoteHost ( ) ) ; } if ( ! messagingService . isAssignedForChannel ( ccid ) ) { // scalability extensions: in case that other component should handle this channel log . debug ( "POST message {}: Bounce Proxy not assigned for channel: {}" , message , ccid ) ; if ( messagingService . hasChannelAssignmentMoved ( ccid ) ) { // scalability extension: in case that this component was responsible before but isn't any more log . debug ( "POST message {}: Bounce Proxy assignment moved for channel: {}" , message , ccid ) ; return Response . status ( 410 /* Gone */ ) . build ( ) ; } else { log . debug ( "POST message {}: channel unknown: {}" , message , ccid ) ; return Response . status ( 404 /* Not Found */ ) . build ( ) ; } } // if the receiver has never registered with the bounceproxy // (or his registration has expired) then return 204 no // content. if ( ! messagingService . hasMessageReceiver ( ccid ) ) { log . debug ( "POST message {}: no receiver for channel: {}" , message , ccid ) ; return Response . noContent ( ) . build ( ) ; } messagingService . passMessageToReceiver ( ccid , serializedMessage ) ; // the location that can be queried to get the message // status // TODO REST URL for message status? URI location = ui . getBaseUriBuilder ( ) . path ( "messages/" + message . getId ( ) ) . build ( ) ; // encode URL in case we use sessions String encodeURL = response . encodeURL ( location . toString ( ) ) ; // return the message status location to the sender. return Response . created ( URI . create ( encodeURL ) ) . header ( "msgId" , message . getId ( ) ) . build ( ) ; } catch ( WebApplicationException e ) { throw e ; } catch ( Exception e ) { log . debug ( "POST message to channel: {} error: {}" , ccid , e . getMessage ( ) ) ; throw new WebApplicationException ( e , Status . INTERNAL_SERVER_ERROR ) ; } }
|
Send a message .
| 858
| 4
|
151,945
|
public static Arbitrator create ( final Set < String > domains , final String interfaceName , final Version interfaceVersion , final DiscoveryQos discoveryQos , DiscoveryAsync localDiscoveryAggregator ) throws DiscoveryException { ArbitrationStrategyFunction arbitrationStrategyFunction ; switch ( discoveryQos . getArbitrationStrategy ( ) ) { case FixedChannel : arbitrationStrategyFunction = new FixedParticipantArbitrationStrategyFunction ( ) ; break ; case Keyword : arbitrationStrategyFunction = new KeywordArbitrationStrategyFunction ( ) ; break ; case HighestPriority : arbitrationStrategyFunction = new HighestPriorityArbitrationStrategyFunction ( ) ; break ; case LastSeen : arbitrationStrategyFunction = new LastSeenArbitrationStrategyFunction ( ) ; break ; case Custom : arbitrationStrategyFunction = discoveryQos . getArbitrationStrategyFunction ( ) ; break ; default : throw new DiscoveryException ( "Arbitration failed: domain: " + domains + " interface: " + interfaceName + " qos: " + discoveryQos + ": unknown arbitration strategy or strategy not set!" ) ; } return new Arbitrator ( domains , interfaceName , interfaceVersion , discoveryQos , localDiscoveryAggregator , minimumArbitrationRetryDelay , arbitrationStrategyFunction , discoveryEntryVersionFilter ) ; }
|
Creates an arbitrator defined by the arbitrationStrategy set in the discoveryQos .
| 286
| 18
|
151,946
|
public static Properties loadProperties ( String fileName ) { LowerCaseProperties properties = new LowerCaseProperties ( ) ; ClassLoader classLoader = Thread . currentThread ( ) . getContextClassLoader ( ) ; URL url = classLoader . getResource ( fileName ) ; // try opening from classpath if ( url != null ) { InputStream urlStream = null ; try { urlStream = url . openStream ( ) ; properties . load ( urlStream ) ; logger . info ( "Properties from classpath loaded file: " + fileName ) ; } catch ( IOException e ) { logger . info ( "Properties from classpath not loaded because file not found: " + fileName ) ; } finally { if ( urlStream != null ) { try { urlStream . close ( ) ; } catch ( IOException e ) { } } } } // Override properties found on the classpath with any found in a file // of the same name LowerCaseProperties propertiesFromFileSystem = loadProperties ( new File ( fileName ) ) ; properties . putAll ( propertiesFromFileSystem ) ; return properties ; }
|
load properties from file
| 236
| 4
|
151,947
|
@ GET @ Produces ( { MediaType . APPLICATION_JSON } ) public GenericEntity < List < BounceProxyStatusInformation > > getBounceProxies ( ) { return new GenericEntity < List < BounceProxyStatusInformation > > ( monitoringService . getRegisteredBounceProxies ( ) ) { } ; }
|
Returns a list of bounce proxies that are registered with the bounceproxy controller .
| 68
| 15
|
151,948
|
public URI createChannel ( ControlledBounceProxyInformation bpInfo , String ccid , String trackingId ) throws JoynrProtocolException { try { // Try to create a channel on a bounce proxy with maximum number of // retries. return createChannelLoop ( bpInfo , ccid , trackingId , sendCreateChannelMaxRetries ) ; } catch ( JoynrProtocolException e ) { logger . error ( "Unexpected bounce proxy behaviour: message: {}" , e . getMessage ( ) ) ; throw e ; } catch ( JoynrRuntimeException e ) { logger . error ( "Channel creation on bounce proxy failed: message: {}" , e . getMessage ( ) ) ; throw e ; } catch ( Exception e ) { logger . error ( "Uncaught exception in channel creation: message: {}" , e . getMessage ( ) ) ; throw new JoynrRuntimeException ( "Unknown exception when creating channel '" + ccid + "' on bounce proxy '" + bpInfo . getId ( ) + "'" , e ) ; } }
|
Creates a channel on the remote bounce proxy .
| 224
| 10
|
151,949
|
private URI createChannelLoop ( ControlledBounceProxyInformation bpInfo , String ccid , String trackingId , int retries ) throws JoynrProtocolException { while ( retries > 0 ) { retries -- ; try { return sendCreateChannelHttpRequest ( bpInfo , ccid , trackingId ) ; } catch ( IOException e ) { // failed to establish communication with the bounce proxy logger . error ( "creating a channel on bounce proxy {} failed due to communication errors: message: {}" , bpInfo . getId ( ) , e . getMessage ( ) ) ; } // try again if creating the channel failed try { Thread . sleep ( sendCreateChannelRetryIntervalMs ) ; } catch ( InterruptedException e ) { throw new JoynrRuntimeException ( "creating a channel on bounce proxy " + bpInfo . getId ( ) + " was interrupted." ) ; } } // the maximum number of retries passed, so channel creation failed throw new JoynrRuntimeException ( "creating a channel on bounce proxy " + bpInfo . getId ( ) + " failed." ) ; }
|
Starts a loop to send createChannel requests to a bounce proxy with a maximum number of retries .
| 237
| 21
|
151,950
|
public void cancelReporting ( ) { if ( startupReportFuture != null ) { startupReportFuture . cancel ( true ) ; } if ( execService != null ) { // interrupt reporting loop execService . shutdownNow ( ) ; } }
|
Cancels startup reporting .
| 48
| 6
|
151,951
|
private void reportEventAsHttpRequest ( ) throws IOException { final String url = bounceProxyControllerUrl . buildReportStartupUrl ( controlledBounceProxyUrl ) ; logger . debug ( "Using monitoring service URL: {}" , url ) ; HttpPut putReportStartup = new HttpPut ( url . trim ( ) ) ; CloseableHttpResponse response = null ; try { response = httpclient . execute ( putReportStartup ) ; StatusLine statusLine = response . getStatusLine ( ) ; int statusCode = statusLine . getStatusCode ( ) ; switch ( statusCode ) { case HttpURLConnection . HTTP_NO_CONTENT : // bounce proxy instance was already known at the bounce proxy // controller // nothing else to do logger . info ( "Bounce proxy was already registered with the controller" ) ; break ; case HttpURLConnection . HTTP_CREATED : // bounce proxy instance was registered for the very first time // TODO maybe read URL logger . info ( "Registered bounce proxy with controller" ) ; break ; default : logger . error ( "Failed to send startup notification: {}" , response ) ; throw new JoynrHttpException ( statusCode , "Failed to send startup notification. Bounce Proxy won't get any channels assigned." ) ; } } finally { if ( response != null ) { response . close ( ) ; } } }
|
Reports the lifecycle event to the monitoring service as HTTP request .
| 288
| 13
|
151,952
|
private OnChangeSubscriptionQos setMinIntervalMsInternal ( final long minIntervalMs ) { if ( minIntervalMs < MIN_MIN_INTERVAL_MS ) { this . minIntervalMs = MIN_MIN_INTERVAL_MS ; logger . warn ( "minIntervalMs < MIN_MIN_INTERVAL_MS. Using MIN_MIN_INTERVAL_MS: {}" , MIN_MIN_INTERVAL_MS ) ; } else if ( minIntervalMs > MAX_MIN_INTERVAL_MS ) { this . minIntervalMs = MAX_MIN_INTERVAL_MS ; logger . warn ( "minIntervalMs > MAX_MIN_INTERVAL_MS. Using MAX_MIN_INTERVAL_MS: {}" , MAX_MIN_INTERVAL_MS ) ; } else { this . minIntervalMs = minIntervalMs ; } return this ; }
|
internal method required to prevent findbugs warning
| 194
| 8
|
151,953
|
private boolean hasRoleMaster ( String userId , String domain ) { DomainRoleEntry domainRole = domainAccessStore . getDomainRole ( userId , Role . MASTER ) ; if ( domainRole == null || ! Arrays . asList ( domainRole . getDomains ( ) ) . contains ( domain ) ) { return false ; } return true ; }
|
Indicates if the given user has master role for the given domain
| 75
| 13
|
151,954
|
public void put ( DelayableImmutableMessage delayableImmutableMessage ) { if ( messagePersister . persist ( messageQueueId , delayableImmutableMessage ) ) { logger . trace ( "Message {} was persisted for messageQueueId {}" , delayableImmutableMessage . getMessage ( ) , messageQueueId ) ; } else { logger . trace ( "Message {} was not persisted for messageQueueId {}" , delayableImmutableMessage . getMessage ( ) , messageQueueId ) ; } delayableImmutableMessages . put ( delayableImmutableMessage ) ; }
|
Add the passed in message to the queue of messages to be processed . Also offer the message for persisting .
| 122
| 22
|
151,955
|
public DelayableImmutableMessage poll ( long timeout , TimeUnit unit ) throws InterruptedException { DelayableImmutableMessage message = delayableImmutableMessages . poll ( timeout , unit ) ; if ( message != null ) { messagePersister . remove ( messageQueueId , message ) ; } return message ; }
|
Polls the message queue for a period no longer than the timeout specified for a new message .
| 66
| 19
|
151,956
|
public void startReporting ( ) { if ( executorService == null ) { throw new IllegalStateException ( "MonitoringServiceClient already shutdown" ) ; } if ( scheduledFuture != null ) { logger . error ( "only one performance reporting thread can be started" ) ; return ; } Runnable performanceReporterCallable = new Runnable ( ) { @ Override public void run ( ) { try { // only send a report if the bounce proxy is initialized if ( bounceProxyLifecycleMonitor . isInitialized ( ) ) { // Don't do any retries here. If we miss on performance // report, we'll just wait for the next loop. sendPerformanceReportAsHttpRequest ( ) ; } } catch ( Exception e ) { logger . error ( "Uncaught exception in reportPerformance." , e ) ; } } } ; scheduledFuture = executorService . scheduleWithFixedDelay ( performanceReporterCallable , performanceReportingFrequencyMs , performanceReportingFrequencyMs , TimeUnit . MILLISECONDS ) ; }
|
Starts a reporting loop that sends performance measures to the monitoring service in a certain frequency .
| 219
| 18
|
151,957
|
private void sendPerformanceReportAsHttpRequest ( ) throws IOException { final String url = bounceProxyControllerUrl . buildReportPerformanceUrl ( ) ; logger . debug ( "Using monitoring service URL: {}" , url ) ; Map < String , Integer > performanceMap = bounceProxyPerformanceMonitor . getAsKeyValuePairs ( ) ; String serializedMessage = objectMapper . writeValueAsString ( performanceMap ) ; HttpPost postReportPerformance = new HttpPost ( url . trim ( ) ) ; // using http apache constants here because JOYNr constants are in // libjoynr which should not be included here postReportPerformance . addHeader ( HttpHeaders . CONTENT_TYPE , "application/json" ) ; postReportPerformance . setEntity ( new StringEntity ( serializedMessage , "UTF-8" ) ) ; CloseableHttpResponse response = null ; try { response = httpclient . execute ( postReportPerformance ) ; StatusLine statusLine = response . getStatusLine ( ) ; int statusCode = statusLine . getStatusCode ( ) ; if ( statusCode != HttpURLConnection . HTTP_NO_CONTENT ) { logger . error ( "Failed to send performance report: {}" , response ) ; throw new JoynrHttpException ( statusCode , "Failed to send performance report." ) ; } } finally { if ( response != null ) { response . close ( ) ; } } }
|
Sends an HTTP request to the monitoring service to report performance measures of a bounce proxy instance .
| 302
| 19
|
151,958
|
public boolean stopReporting ( ) { // quit the bounce proxy heartbeat but let a possibly running request // finish if ( scheduledFuture != null ) { return scheduledFuture . cancel ( false ) ; } executorService . shutdown ( ) ; executorService = null ; return false ; }
|
Stops the performance reporting loop .
| 57
| 7
|
151,959
|
public void setArbitrationStrategy ( ArbitrationStrategy arbitrationStrategy ) { if ( arbitrationStrategy . equals ( ArbitrationStrategy . Custom ) ) { throw new IllegalStateException ( "A Custom strategy can only be set by passing an arbitration strategy function to the DiscoveryQos constructor" ) ; } this . arbitrationStrategy = arbitrationStrategy ; }
|
The discovery process outputs a list of matching providers . The arbitration strategy then chooses one or more of them to be used by the proxy .
| 76
| 27
|
151,960
|
public void onSuccess ( T result ) { try { statusLock . lock ( ) ; value = result ; status = new RequestStatus ( RequestStatusCode . OK ) ; statusLockChangedCondition . signalAll ( ) ; } catch ( Exception e ) { status = new RequestStatus ( RequestStatusCode . ERROR ) ; exception = new JoynrRuntimeException ( e ) ; } finally { statusLock . unlock ( ) ; } }
|
Resolves the future using the given result
| 88
| 8
|
151,961
|
public void onFailure ( JoynrException newException ) { exception = newException ; status = new RequestStatus ( RequestStatusCode . ERROR ) ; try { statusLock . lock ( ) ; statusLockChangedCondition . signalAll ( ) ; } finally { statusLock . unlock ( ) ; } }
|
Terminates the future in error
| 61
| 6
|
151,962
|
public Set < Version > getDiscoveredVersionsForDomain ( String domain ) { Set < Version > result = new HashSet <> ( ) ; if ( hasExceptionForDomain ( domain ) ) { result . addAll ( exceptionsByDomain . get ( domain ) . getDiscoveredVersions ( ) ) ; } return result ; }
|
Returns the set of versions which were discovered for a given domain .
| 68
| 13
|
151,963
|
@ CheckForNull public ConnectorInvocationHandler create ( final String fromParticipantId , final ArbitrationResult arbitrationResult , final MessagingQos qosSettings , String statelessAsyncParticipantId ) { // iterate through arbitrationResult.getDiscoveryEntries() // check if there is at least one Globally visible // set isGloballyVisible = true. otherwise = false boolean isGloballyVisible = false ; Set < DiscoveryEntryWithMetaInfo > entries = arbitrationResult . getDiscoveryEntries ( ) ; for ( DiscoveryEntryWithMetaInfo entry : entries ) { if ( entry . getQos ( ) . getScope ( ) == ProviderScope . GLOBAL ) { isGloballyVisible = true ; } messageRouter . setToKnown ( entry . getParticipantId ( ) ) ; } messageRouter . addNextHop ( fromParticipantId , libjoynrMessagingAddress , isGloballyVisible ) ; return joynrMessagingConnectorFactory . create ( fromParticipantId , arbitrationResult . getDiscoveryEntries ( ) , qosSettings , statelessAsyncParticipantId ) ; }
|
Creates a new connector object using concrete connector factories chosen by the endpointAddress which is passed in .
| 244
| 20
|
151,964
|
@ Override public void registerAttributeListener ( String attributeName , AttributeListener attributeListener ) { attributeListeners . putIfAbsent ( attributeName , new ArrayList < AttributeListener > ( ) ) ; List < AttributeListener > listeners = attributeListeners . get ( attributeName ) ; synchronized ( listeners ) { listeners . add ( attributeListener ) ; } }
|
Registers an attribute listener that gets notified in case the attribute changes . This is used for on change subscriptions .
| 77
| 22
|
151,965
|
@ Override public void unregisterAttributeListener ( String attributeName , AttributeListener attributeListener ) { List < AttributeListener > listeners = attributeListeners . get ( attributeName ) ; if ( listeners == null ) { LOG . error ( "trying to unregister an attribute listener for attribute \"" + attributeName + "\" that was never registered" ) ; return ; } synchronized ( listeners ) { boolean success = listeners . remove ( attributeListener ) ; if ( ! success ) { LOG . error ( "trying to unregister an attribute listener for attribute \"" + attributeName + "\" that was never registered" ) ; return ; } } }
|
Unregisters an attribute listener .
| 136
| 7
|
151,966
|
@ Override public void registerBroadcastListener ( String broadcastName , BroadcastListener broadcastListener ) { broadcastListeners . putIfAbsent ( broadcastName , new ArrayList < BroadcastListener > ( ) ) ; List < BroadcastListener > listeners = broadcastListeners . get ( broadcastName ) ; synchronized ( listeners ) { listeners . add ( broadcastListener ) ; } }
|
Registers a broadcast listener that gets notified in case the broadcast is fired .
| 75
| 15
|
151,967
|
@ Override public void unregisterBroadcastListener ( String broadcastName , BroadcastListener broadcastListener ) { List < BroadcastListener > listeners = broadcastListeners . get ( broadcastName ) ; if ( listeners == null ) { LOG . error ( "trying to unregister a listener for broadcast \"" + broadcastName + "\" that was never registered" ) ; return ; } synchronized ( listeners ) { boolean success = listeners . remove ( broadcastListener ) ; if ( ! success ) { LOG . error ( "trying to unregister a listener for broadcast \"" + broadcastName + "\" that was never registered" ) ; return ; } } }
|
Unregisters a broadcast listener .
| 133
| 7
|
151,968
|
@ Override public void addBroadcastFilter ( BroadcastFilterImpl filter ) { if ( broadcastFilters . containsKey ( filter . getName ( ) ) ) { broadcastFilters . get ( filter . getName ( ) ) . add ( filter ) ; } else { ArrayList < BroadcastFilter > list = new ArrayList < BroadcastFilter > ( ) ; list . add ( filter ) ; broadcastFilters . put ( filter . getName ( ) , list ) ; } }
|
Adds a broadcast filter to the provider . The filter is specific for a single broadcast as defined in the Franca model . It will be executed once for each subscribed client whenever the broadcast is fired . Clients set individual filter parameters to control filter behavior .
| 99
| 50
|
151,969
|
@ Override public void addBroadcastFilter ( BroadcastFilterImpl ... filters ) { List < BroadcastFilterImpl > filtersList = Arrays . asList ( filters ) ; for ( BroadcastFilterImpl filter : filtersList ) { addBroadcastFilter ( filter ) ; } }
|
Adds multiple broadcast filters to the provider .
| 56
| 8
|
151,970
|
@ CheckForNull public Object [ ] getValues ( long timeout ) throws InterruptedException { if ( ! isSettled ( ) ) { synchronized ( this ) { wait ( timeout ) ; } } if ( values == null ) { return null ; } return Arrays . copyOf ( values , values . length ) ; }
|
Get the resolved values of the promise . If the promise is not settled the call blocks until the promise is settled or timeout is reached .
| 68
| 27
|
151,971
|
private void getCapabilityEntry ( ImmutableMessage message , CapabilityCallback callback ) { long cacheMaxAge = Long . MAX_VALUE ; DiscoveryQos discoveryQos = new DiscoveryQos ( DiscoveryQos . NO_MAX_AGE , ArbitrationStrategy . NotSet , cacheMaxAge , DiscoveryScope . LOCAL_THEN_GLOBAL ) ; String participantId = message . getRecipient ( ) ; localCapabilitiesDirectory . lookup ( participantId , discoveryQos , callback ) ; }
|
Get the capability entry for the given message
| 107
| 8
|
151,972
|
public static void copyDirectory ( File sourceLocation , File targetLocation ) throws IOException { if ( sourceLocation . isDirectory ( ) ) { if ( ! targetLocation . exists ( ) ) { if ( targetLocation . mkdir ( ) == false ) { logger . debug ( "Creating target directory " + targetLocation + " failed." ) ; } } String [ ] children = sourceLocation . list ( ) ; if ( children == null ) { return ; } for ( int i = 0 ; i < children . length ; i ++ ) { copyDirectory ( new File ( sourceLocation , children [ i ] ) , new File ( targetLocation , children [ i ] ) ) ; } } else { FileInputStream in = null ; FileOutputStream out = null ; try { in = new FileInputStream ( sourceLocation ) ; out = new FileOutputStream ( targetLocation ) ; copyStream ( in , out ) ; } finally { if ( in != null ) { in . close ( ) ; } if ( out != null ) { out . close ( ) ; } } } }
|
If targetLocation does not exist it will be created .
| 224
| 11
|
151,973
|
public boolean check ( Version caller , Version provider ) { if ( caller == null || provider == null ) { throw new IllegalArgumentException ( format ( "Both caller (%s) and provider (%s) must be non-null." , caller , provider ) ) ; } if ( caller . getMajorVersion ( ) == null || caller . getMinorVersion ( ) == null || provider . getMajorVersion ( ) == null || provider . getMinorVersion ( ) == null ) { throw new IllegalArgumentException ( format ( "Neither major nor minor version values can be null in either caller %s or provider %s." , caller , provider ) ) ; } int callerMajor = caller . getMajorVersion ( ) ; int callerMinor = caller . getMinorVersion ( ) ; int providerMajor = provider . getMajorVersion ( ) ; int providerMinor = provider . getMinorVersion ( ) ; return callerMajor == providerMajor && callerMinor <= providerMinor ; }
|
Compatibility of two versions is defined as the caller and provider versions having the same major version and the provider having the same or a higher minor version as the caller .
| 198
| 33
|
151,974
|
public static GlobalDiscoveryEntry newGlobalDiscoveryEntry ( Version providerVesion , String domain , String interfaceName , String participantId , ProviderQos qos , Long lastSeenDateMs , Long expiryDateMs , String publicKeyId , Address address ) { // CHECKSTYLE ON return new GlobalDiscoveryEntry ( providerVesion , domain , interfaceName , participantId , qos , lastSeenDateMs , expiryDateMs , publicKeyId , serializeAddress ( address ) ) ; }
|
CHECKSTYLE IGNORE ParameterNumber FOR NEXT 1 LINES
| 111
| 14
|
151,975
|
@ Override public Object invoke ( Object proxy , Method method , Object [ ] args ) throws Throwable { if ( throwable != null ) { throw throwable ; } try { return invokeInternal ( proxy , method , args ) ; } catch ( Exception e ) { if ( this . throwable != null ) { logger . debug ( "exception caught: {} overridden by: {}" , e . getMessage ( ) , throwable . getMessage ( ) ) ; throw throwable ; } else { throw e ; } } }
|
The InvocationHandler invoke method is mapped to the ProxyInvocationHandler . invokeInternal
| 111
| 17
|
151,976
|
public B error ( String errorCode ) { ErrorEventDefinition errorEventDefinition = createErrorEventDefinition ( errorCode ) ; element . getEventDefinitions ( ) . add ( errorEventDefinition ) ; return myself ; }
|
Sets an error definition for the given error code . If already an error with this code exists it will be used otherwise a new error is created .
| 45
| 30
|
151,977
|
public B addExtensionElement ( BpmnModelElementInstance extensionElement ) { ExtensionElements extensionElements = getCreateSingleChild ( ExtensionElements . class ) ; extensionElements . addChildElement ( extensionElement ) ; return myself ; }
|
Add an extension element to the element .
| 52
| 8
|
151,978
|
public B camundaFailedJobRetryTimeCycle ( String retryTimeCycle ) { CamundaFailedJobRetryTimeCycle failedJobRetryTimeCycle = createInstance ( CamundaFailedJobRetryTimeCycle . class ) ; failedJobRetryTimeCycle . setTextContent ( retryTimeCycle ) ; addExtensionElement ( failedJobRetryTimeCycle ) ; return myself ; }
|
Sets the camunda failedJobRetryTimeCycle attribute for the build flow node .
| 93
| 19
|
151,979
|
public B message ( String messageName ) { Message message = findMessageForName ( messageName ) ; return message ( message ) ; }
|
Sets the message with the given message name . If already a message with this name exists it will be used otherwise a new message is created .
| 28
| 29
|
151,980
|
public B camundaOut ( String source , String target ) { CamundaOut param = modelInstance . newInstance ( CamundaOut . class ) ; param . setCamundaSource ( source ) ; param . setCamundaTarget ( target ) ; addExtensionElement ( param ) ; return myself ; }
|
Sets a camunda out parameter to pass a variable from a sub process instance to the super process instance
| 63
| 21
|
151,981
|
public B message ( String messageName ) { MessageEventDefinition messageEventDefinition = createMessageEventDefinition ( messageName ) ; element . getEventDefinitions ( ) . add ( messageEventDefinition ) ; return myself ; }
|
Sets an event definition for the given message name . If already a message with this name exists it will be used otherwise a new message is created .
| 45
| 30
|
151,982
|
public B signal ( String signalName ) { SignalEventDefinition signalEventDefinition = createSignalEventDefinition ( signalName ) ; element . getEventDefinitions ( ) . add ( signalEventDefinition ) ; return myself ; }
|
Sets an event definition for the given signal name . If already a signal with this name exists it will be used otherwise a new signal is created .
| 46
| 30
|
151,983
|
public B timerWithDate ( String timerDate ) { TimeDate timeDate = createInstance ( TimeDate . class ) ; timeDate . setTextContent ( timerDate ) ; TimerEventDefinition timerEventDefinition = createInstance ( TimerEventDefinition . class ) ; timerEventDefinition . setTimeDate ( timeDate ) ; element . getEventDefinitions ( ) . add ( timerEventDefinition ) ; return myself ; }
|
Sets an event definition for the timer with a time date .
| 87
| 13
|
151,984
|
public B timerWithDuration ( String timerDuration ) { TimeDuration timeDuration = createInstance ( TimeDuration . class ) ; timeDuration . setTextContent ( timerDuration ) ; TimerEventDefinition timerEventDefinition = createInstance ( TimerEventDefinition . class ) ; timerEventDefinition . setTimeDuration ( timeDuration ) ; element . getEventDefinitions ( ) . add ( timerEventDefinition ) ; return myself ; }
|
Sets an event definition for the timer with a time duration .
| 87
| 13
|
151,985
|
public B timerWithCycle ( String timerCycle ) { TimeCycle timeCycle = createInstance ( TimeCycle . class ) ; timeCycle . setTextContent ( timerCycle ) ; TimerEventDefinition timerEventDefinition = createInstance ( TimerEventDefinition . class ) ; timerEventDefinition . setTimeCycle ( timeCycle ) ; element . getEventDefinitions ( ) . add ( timerEventDefinition ) ; return myself ; }
|
Sets an event definition for the timer with a time cycle .
| 96
| 13
|
151,986
|
public SubProcessBuilder subProcessDone ( ) { BpmnModelElementInstance lastSubProcess = element . getScope ( ) ; if ( lastSubProcess != null && lastSubProcess instanceof SubProcess ) { return ( ( SubProcess ) lastSubProcess ) . builder ( ) ; } else { throw new BpmnModelException ( "Unable to find a parent subProcess." ) ; } }
|
Finishes the building of an embedded sub - process .
| 84
| 11
|
151,987
|
public B error ( ) { ErrorEventDefinition errorEventDefinition = createInstance ( ErrorEventDefinition . class ) ; element . getEventDefinitions ( ) . add ( errorEventDefinition ) ; return myself ; }
|
Sets a catch all error definition .
| 43
| 8
|
151,988
|
public ErrorEventDefinitionBuilder errorEventDefinition ( String id ) { ErrorEventDefinition errorEventDefinition = createEmptyErrorEventDefinition ( ) ; if ( id != null ) { errorEventDefinition . setId ( id ) ; } element . getEventDefinitions ( ) . add ( errorEventDefinition ) ; return new ErrorEventDefinitionBuilder ( modelInstance , errorEventDefinition ) ; }
|
Creates an error event definition with an unique id and returns a builder for the error event definition .
| 78
| 20
|
151,989
|
public ErrorEventDefinitionBuilder errorEventDefinition ( ) { ErrorEventDefinition errorEventDefinition = createEmptyErrorEventDefinition ( ) ; element . getEventDefinitions ( ) . add ( errorEventDefinition ) ; return new ErrorEventDefinitionBuilder ( modelInstance , errorEventDefinition ) ; }
|
Creates an error event definition and returns a builder for the error event definition .
| 58
| 16
|
151,990
|
public B escalation ( ) { EscalationEventDefinition escalationEventDefinition = createInstance ( EscalationEventDefinition . class ) ; element . getEventDefinitions ( ) . add ( escalationEventDefinition ) ; return myself ; }
|
Sets a catch all escalation definition .
| 47
| 8
|
151,991
|
public B escalation ( String escalationCode ) { EscalationEventDefinition escalationEventDefinition = createEscalationEventDefinition ( escalationCode ) ; element . getEventDefinitions ( ) . add ( escalationEventDefinition ) ; return myself ; }
|
Sets an escalation definition for the given escalation code . If already an escalation with this code exists it will be used otherwise a new escalation is created .
| 49
| 30
|
151,992
|
public CamundaUserTaskFormFieldBuilder camundaFormField ( ) { CamundaFormData camundaFormData = getCreateSingleExtensionElement ( CamundaFormData . class ) ; CamundaFormField camundaFormField = createChild ( camundaFormData , CamundaFormField . class ) ; return new CamundaUserTaskFormFieldBuilder ( modelInstance , element , camundaFormField ) ; }
|
Creates a new camunda form field extension element .
| 86
| 11
|
151,993
|
public B activationCondition ( String conditionExpression ) { ActivationCondition activationCondition = createInstance ( ActivationCondition . class ) ; activationCondition . setTextContent ( conditionExpression ) ; element . setActivationCondition ( activationCondition ) ; return myself ; }
|
Sets the activation condition expression for the build complex gateway
| 54
| 11
|
151,994
|
public B cardinality ( String expression ) { LoopCardinality cardinality = getCreateSingleChild ( LoopCardinality . class ) ; cardinality . setTextContent ( expression ) ; return myself ; }
|
Sets the cardinality expression .
| 43
| 7
|
151,995
|
public B completionCondition ( String expression ) { CompletionCondition condition = getCreateSingleChild ( CompletionCondition . class ) ; condition . setTextContent ( expression ) ; return myself ; }
|
Sets the completion condition expression .
| 39
| 7
|
151,996
|
@ SuppressWarnings ( { "rawtypes" , "unchecked" } ) public < T extends AbstractActivityBuilder > T multiInstanceDone ( ) { return ( T ) ( ( Activity ) element . getParentElement ( ) ) . builder ( ) ; }
|
Finishes the building of a multi instance loop characteristics .
| 56
| 11
|
151,997
|
public B condition ( String conditionText ) { Condition condition = createInstance ( Condition . class ) ; condition . setTextContent ( conditionText ) ; element . setCondition ( condition ) ; return myself ; }
|
Sets the condition of the conditional event definition .
| 42
| 10
|
151,998
|
@ SuppressWarnings ( { "rawtypes" , "unchecked" } ) public < T extends AbstractFlowNodeBuilder > T conditionalEventDefinitionDone ( ) { return ( T ) ( ( Event ) element . getParentElement ( ) ) . builder ( ) ; }
|
Finishes the building of a conditional event definition .
| 58
| 10
|
151,999
|
@ SuppressWarnings ( { "rawtypes" , "unchecked" } ) public < T extends AbstractFlowNodeBuilder > T errorEventDefinitionDone ( ) { return ( T ) ( ( Event ) element . getParentElement ( ) ) . builder ( ) ; }
|
Finishes the building of a error event definition .
| 58
| 10
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.