idx
int64
0
41.2k
question
stringlengths
83
4.15k
target
stringlengths
5
715
28,500
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 ) ; } 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
28,501
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
28,502
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 .
28,503
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 .
28,504
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
28,505
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
28,506
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 ) { _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
28,507
void completeUploading ( ) throws IOException { LOGGER . debug ( "name: {}, currentSize: {}, Threshold: {}," + " fileCount: {}, fileBucketSize: {}" , _file . getAbsolutePath ( ) , _currentSize , this . _csvFileSize , _fileCount , this . _csvFileBucketSize ) ; _outstream . flush ( ) ; _outstream . close ( ) ; if ( _currentSize > 0 ) { FileUploader fu = new FileUploader ( _loader , _location , _file ) ; fu . upload ( ) ; _uploaders . add ( fu ) ; } else { _file . delete ( ) ; } for ( FileUploader fu : _uploaders ) { fu . join ( ) ; } _directory . deleteOnExit ( ) ; if ( this . _rowCount == 0 ) { setState ( State . EMPTY ) ; } }
Wait for all files to finish uploading and schedule stage for processing
28,508
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 .
28,509
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 ( ) { 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 .
28,510
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 .
28,511
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 .
28,512
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 .
28,513
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
28,514
@ Produces ( { MediaType . TEXT_PLAIN } ) public String getTime ( ) { return String . valueOf ( System . currentTimeMillis ( ) ) ; }
get server time in ms
28,515
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
28,516
@ Path ( "/clusters/{clusterid: ([A-Z,a-z,0-9,_,\\-]+)}" ) public Response migrateCluster ( @ PathParam ( "clusterid" ) final String clusterId ) { migrationService . startClusterMigration ( clusterId ) ; return Response . status ( 202 ) . build ( ) ; }
Migrates all bounce proxies of one cluster to a different cluster .
28,517
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 .
28,518
@ 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" ) ; String path = longPollingDelegate . postMessage ( ccid , serializedMessage ) ; URI location = ui . getBaseUriBuilder ( ) . path ( path ) . build ( ) ; 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
28,519
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 .
28,520
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 .
28,521
public String createChannel ( String ccid , String atmosphereTrackingId ) { throwExceptionIfTrackingIdnotSet ( atmosphereTrackingId ) ; log . info ( "CREATE channel for cluster controller: {} trackingId: {} " , ccid , atmosphereTrackingId ) ; Broadcaster broadcaster = null ; BroadcasterFactory defaultBroadcasterFactory = BroadcasterFactory . getDefault ( ) ; if ( defaultBroadcasterFactory == null ) { throw new JoynrHttpException ( 500 , 10009 , "broadcaster was null" ) ; } broadcaster = defaultBroadcasterFactory . lookup ( Broadcaster . class , ccid , false ) ; if ( broadcaster == null ) { broadcaster = defaultBroadcasterFactory . get ( BounceProxyBroadcaster . class , ccid ) ; } 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 ( ) ) ; return "/channels/" + ccid + "/" ; }
Creates a long polling channel .
28,522
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 ( ) ; return true ; }
Deletes a channel from the broadcaster .
28,523
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 ) ; } 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 ) ; } 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 ) ; } Broadcaster ccBroadcaster = BroadcasterFactory . getDefault ( ) . lookup ( Broadcaster . class , ccid , false ) ; if ( ccBroadcaster == null ) { 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 .
28,524
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 > > ( ) { 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" ) ) ; } } public void onFailure ( JoynrRuntimeException exception ) { capabilitiesCallback . onError ( exception ) ; } } , domains , interfaceName , discoveryTimeout ) ; }
mixes in the localDiscoveryEntries to global capabilities found by participantId
28,525
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 .
28,526
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 .
28,527
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
28,528
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
28,529
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 .
28,530
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 .
28,531
@ 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 .
28,532
@ 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 .
28,533
@ 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 ( ) ; } 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
28,534
@ 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 .
28,535
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 .
28,536
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 .
28,537
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 .
28,538
protected void arbitrationFinished ( ArbitrationStatus arbitrationStatus , ArbitrationResult arbitrationResult ) { this . arbitrationStatus = arbitrationStatus ; this . arbitrationResult = arbitrationResult ; if ( arbitrationListenerSemaphore . tryAcquire ( ) ) { arbitrationListener . onSuccess ( arbitrationResult ) ; arbitrationListenerSemaphore . release ( ) ; } }
Sets the arbitration result at the arbitrationListener if the listener is already registered
28,539
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
28,540
public void setStatus ( BounceProxyStatus status ) throws IllegalStateException { 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 .
28,541
@ 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 ) ; 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 ) ; } 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 ) ) { log . debug ( "POST message {}: Bounce Proxy not assigned for channel: {}" , message , ccid ) ; if ( messagingService . hasChannelAssignmentMoved ( ccid ) ) { log . debug ( "POST message {}: Bounce Proxy assignment moved for channel: {}" , message , ccid ) ; return Response . status ( 410 ) . build ( ) ; } else { log . debug ( "POST message {}: channel unknown: {}" , message , ccid ) ; return Response . status ( 404 ) . build ( ) ; } } if ( ! messagingService . hasMessageReceiver ( ccid ) ) { log . debug ( "POST message {}: no receiver for channel: {}" , message , ccid ) ; return Response . noContent ( ) . build ( ) ; } messagingService . passMessageToReceiver ( ccid , serializedMessage ) ; URI location = ui . getBaseUriBuilder ( ) . path ( "messages/" + message . getId ( ) ) . build ( ) ; String encodeURL = response . encodeURL ( location . toString ( ) ) ; 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 .
28,542
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 .
28,543
public static Properties loadProperties ( String fileName ) { LowerCaseProperties properties = new LowerCaseProperties ( ) ; ClassLoader classLoader = Thread . currentThread ( ) . getContextClassLoader ( ) ; URL url = classLoader . getResource ( fileName ) ; 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 ) { } } } } LowerCaseProperties propertiesFromFileSystem = loadProperties ( new File ( fileName ) ) ; properties . putAll ( propertiesFromFileSystem ) ; return properties ; }
load properties from file
28,544
@ 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 .
28,545
public URI createChannel ( ControlledBounceProxyInformation bpInfo , String ccid , String trackingId ) throws JoynrProtocolException { try { 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 .
28,546
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 ) { logger . error ( "creating a channel on bounce proxy {} failed due to communication errors: message: {}" , bpInfo . getId ( ) , e . getMessage ( ) ) ; } try { Thread . sleep ( sendCreateChannelRetryIntervalMs ) ; } catch ( InterruptedException e ) { throw new JoynrRuntimeException ( "creating a channel on bounce proxy " + bpInfo . getId ( ) + " was interrupted." ) ; } } 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 .
28,547
public void cancelReporting ( ) { if ( startupReportFuture != null ) { startupReportFuture . cancel ( true ) ; } if ( execService != null ) { execService . shutdownNow ( ) ; } }
Cancels startup reporting .
28,548
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 : logger . info ( "Bounce proxy was already registered with the controller" ) ; break ; case HttpURLConnection . HTTP_CREATED : 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 .
28,549
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
28,550
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
28,551
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 .
28,552
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 .
28,553
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 ( ) { public void run ( ) { try { if ( bounceProxyLifecycleMonitor . isInitialized ( ) ) { 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 .
28,554
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 ( ) ) ; 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 .
28,555
public boolean stopReporting ( ) { if ( scheduledFuture != null ) { return scheduledFuture . cancel ( false ) ; } executorService . shutdown ( ) ; executorService = null ; return false ; }
Stops the performance reporting loop .
28,556
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 .
28,557
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
28,558
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
28,559
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 .
28,560
public ConnectorInvocationHandler create ( final String fromParticipantId , final ArbitrationResult arbitrationResult , final MessagingQos qosSettings , String statelessAsyncParticipantId ) { 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 .
28,561
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 .
28,562
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 .
28,563
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 .
28,564
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 .
28,565
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 .
28,566
public void addBroadcastFilter ( BroadcastFilterImpl ... filters ) { List < BroadcastFilterImpl > filtersList = Arrays . asList ( filters ) ; for ( BroadcastFilterImpl filter : filtersList ) { addBroadcastFilter ( filter ) ; } }
Adds multiple broadcast filters to the provider .
28,567
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 .
28,568
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
28,569
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 .
28,570
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 .
28,571
public static GlobalDiscoveryEntry newGlobalDiscoveryEntry ( Version providerVesion , String domain , String interfaceName , String participantId , ProviderQos qos , Long lastSeenDateMs , Long expiryDateMs , String publicKeyId , Address address ) { return new GlobalDiscoveryEntry ( providerVesion , domain , interfaceName , participantId , qos , lastSeenDateMs , expiryDateMs , publicKeyId , serializeAddress ( address ) ) ; }
CHECKSTYLE IGNORE ParameterNumber FOR NEXT 1 LINES
28,572
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
28,573
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 .
28,574
public B addExtensionElement ( BpmnModelElementInstance extensionElement ) { ExtensionElements extensionElements = getCreateSingleChild ( ExtensionElements . class ) ; extensionElements . addChildElement ( extensionElement ) ; return myself ; }
Add an extension element to the element .
28,575
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 .
28,576
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,577
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
28,578
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 .
28,579
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 .
28,580
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 .
28,581
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 .
28,582
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 .
28,583
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 .
28,584
public B error ( ) { ErrorEventDefinition errorEventDefinition = createInstance ( ErrorEventDefinition . class ) ; element . getEventDefinitions ( ) . add ( errorEventDefinition ) ; return myself ; }
Sets a catch all error definition .
28,585
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 .
28,586
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 .
28,587
public B escalation ( ) { EscalationEventDefinition escalationEventDefinition = createInstance ( EscalationEventDefinition . class ) ; element . getEventDefinitions ( ) . add ( escalationEventDefinition ) ; return myself ; }
Sets a catch all escalation definition .
28,588
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 .
28,589
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 .
28,590
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
28,591
public B cardinality ( String expression ) { LoopCardinality cardinality = getCreateSingleChild ( LoopCardinality . class ) ; cardinality . setTextContent ( expression ) ; return myself ; }
Sets the cardinality expression .
28,592
public B completionCondition ( String expression ) { CompletionCondition condition = getCreateSingleChild ( CompletionCondition . class ) ; condition . setTextContent ( expression ) ; return myself ; }
Sets the completion condition expression .
28,593
@ SuppressWarnings ( { "rawtypes" , "unchecked" } ) public < T extends AbstractActivityBuilder > T multiInstanceDone ( ) { return ( T ) ( ( Activity ) element . getParentElement ( ) ) . builder ( ) ; }
Finishes the building of a multi instance loop characteristics .
28,594
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 .
28,595
@ SuppressWarnings ( { "rawtypes" , "unchecked" } ) public < T extends AbstractFlowNodeBuilder > T conditionalEventDefinitionDone ( ) { return ( T ) ( ( Event ) element . getParentElement ( ) ) . builder ( ) ; }
Finishes the building of a conditional event definition .
28,596
@ SuppressWarnings ( { "rawtypes" , "unchecked" } ) public < T extends AbstractFlowNodeBuilder > T errorEventDefinitionDone ( ) { return ( T ) ( ( Event ) element . getParentElement ( ) ) . builder ( ) ; }
Finishes the building of a error event definition .
28,597
public B camundaInputParameter ( String name , String value ) { CamundaInputOutput camundaInputOutput = getCreateSingleExtensionElement ( CamundaInputOutput . class ) ; CamundaInputParameter camundaInputParameter = createChild ( camundaInputOutput , CamundaInputParameter . class ) ; camundaInputParameter . setCamundaName ( name ) ; camundaInputParameter . setTextContent ( value ) ; return myself ; }
Creates a new camunda input parameter extension element with the given name and value .
28,598
public B camundaOutputParameter ( String name , String value ) { CamundaInputOutput camundaInputOutput = getCreateSingleExtensionElement ( CamundaInputOutput . class ) ; CamundaOutputParameter camundaOutputParameter = createChild ( camundaInputOutput , CamundaOutputParameter . class ) ; camundaOutputParameter . setCamundaName ( name ) ; camundaOutputParameter . setTextContent ( value ) ; return myself ; }
Creates a new camunda output parameter extension element with the given name and value .
28,599
public MessageEventDefinitionBuilder messageEventDefinition ( String id ) { MessageEventDefinition messageEventDefinition = createEmptyMessageEventDefinition ( ) ; if ( id != null ) { messageEventDefinition . setId ( id ) ; } element . getEventDefinitions ( ) . add ( messageEventDefinition ) ; return new MessageEventDefinitionBuilder ( modelInstance , messageEventDefinition ) ; }
Creates an empty message event definition with the given id and returns a builder for the message event definition .