idx
int64
0
41.2k
question
stringlengths
74
4.04k
target
stringlengths
7
750
24,600
public Observable < ServerTableAuditingPolicyInner > createOrUpdateAsync ( String resourceGroupName , String serverName , ServerTableAuditingPolicyInner parameters ) { return createOrUpdateWithServiceResponseAsync ( resourceGroupName , serverName , parameters ) . map ( new Func1 < ServiceResponse < ServerTableAuditingPolicyInner > , ServerTableAuditingPolicyInner > ( ) { public ServerTableAuditingPolicyInner call ( ServiceResponse < ServerTableAuditingPolicyInner > response ) { return response . body ( ) ; } } ) ; }
Creates or updates a servers s table auditing policy . Table auditing is deprecated use blob auditing instead .
24,601
public Observable < ServerTableAuditingPolicyListResultInner > listByServerAsync ( String resourceGroupName , String serverName ) { return listByServerWithServiceResponseAsync ( resourceGroupName , serverName ) . map ( new Func1 < ServiceResponse < ServerTableAuditingPolicyListResultInner > , ServerTableAuditingPolicyListResultInner > ( ) { public ServerTableAuditingPolicyListResultInner call ( ServiceResponse < ServerTableAuditingPolicyListResultInner > response ) { return response . body ( ) ; } } ) ; }
Lists a servers s table auditing policies . Table auditing is deprecated use blob auditing instead .
24,602
public void register ( Builder . Registry registry ) { registry . add ( new AzureAdTokenFactory ( ) ) ; registry . add ( MediaContract . class , MediaExceptionProcessor . class ) ; registry . add ( MediaRestProxy . class ) ; registry . add ( OAuthFilter . class ) ; registry . add ( ResourceLocationManager . class ) ; registry . add ( RedirectFilter . class ) ; registry . add ( VersionHeadersFilter . class ) ; registry . add ( UserAgentFilter . class ) ; registry . alter ( MediaContract . class , ClientConfig . class , new Builder . Alteration < ClientConfig > ( ) { @ SuppressWarnings ( "rawtypes" ) public ClientConfig alter ( String profile , ClientConfig instance , Builder builder , Map < String , Object > properties ) { instance . getProperties ( ) . put ( JSONConfiguration . FEATURE_POJO_MAPPING , true ) ; instance . getProperties ( ) . put ( ClientConfig . PROPERTY_FOLLOW_REDIRECTS , false ) ; try { instance . getSingletons ( ) . add ( new ODataEntityProvider ( ) ) ; instance . getSingletons ( ) . add ( new ODataEntityCollectionProvider ( ) ) ; instance . getSingletons ( ) . add ( new MediaContentProvider ( ) ) ; instance . getSingletons ( ) . add ( new BatchMimeMultipartBodyWritter ( ) ) ; } catch ( JAXBException e ) { throw new RuntimeException ( e ) ; } catch ( ParserConfigurationException e ) { throw new RuntimeException ( e ) ; } return instance ; } } ) ; }
register the Media services .
24,603
public void run ( ) { try { ReceivePump . this . receiveAndProcess ( ) ; } catch ( final Exception exception ) { if ( TRACE_LOGGER . isErrorEnabled ( ) ) { TRACE_LOGGER . error ( String . format ( Locale . US , "Receive pump for eventHub (%s), consumerGroup (%s), partition (%s) " + "encountered unrecoverable error and exited with exception %s." , this . eventHubName , this . consumerGroupName , this . receiver . getPartitionId ( ) , exception . toString ( ) ) ) ; } throw exception ; } }
entry - point - for runnable
24,604
public void receiveAndProcess ( ) { if ( this . shouldContinue ( ) ) { this . receiver . receive ( this . onReceiveHandler . getMaxEventCount ( ) ) . handleAsync ( this . processAndReschedule , this . executor ) ; } else { if ( TRACE_LOGGER . isInfoEnabled ( ) ) { TRACE_LOGGER . info ( String . format ( Locale . US , "Stopping receive pump for eventHub (%s), consumerGroup (%s), partition (%s) as %s" , this . eventHubName , this . consumerGroupName , this . receiver . getPartitionId ( ) , this . stopPumpRaised . get ( ) ? "per the request." : "pump ran into errors." ) ) ; } this . stopPump . complete ( null ) ; } }
receives and invokes user - callback if success or stops pump if fails
24,605
public static Authenticated authenticate ( AzureTokenCredentials credentials ) { return new AuthenticatedImpl ( new RestClient . Builder ( ) . withBaseUrl ( credentials . environment ( ) , AzureEnvironment . Endpoint . RESOURCE_MANAGER ) . withCredentials ( credentials ) . withSerializerAdapter ( new AzureJacksonAdapter ( ) ) . withResponseBuilderFactory ( new AzureResponseBuilder . Factory ( ) ) . build ( ) ) ; }
Creates an instance of Azure . Authenticated that exposes subscription tenant and authorization API entry points .
24,606
public Observable < DataMaskingPolicyInner > getAsync ( String resourceGroupName , String serverName , String databaseName ) { return getWithServiceResponseAsync ( resourceGroupName , serverName , databaseName ) . map ( new Func1 < ServiceResponse < DataMaskingPolicyInner > , DataMaskingPolicyInner > ( ) { public DataMaskingPolicyInner call ( ServiceResponse < DataMaskingPolicyInner > response ) { return response . body ( ) ; } } ) ; }
Gets a database data masking policy .
24,607
public Observable < Page < DscNodeConfigurationInner > > listByAutomationAccountNextAsync ( final String nextPageLink ) { return listByAutomationAccountNextWithServiceResponseAsync ( nextPageLink ) . map ( new Func1 < ServiceResponse < Page < DscNodeConfigurationInner > > , Page < DscNodeConfigurationInner > > ( ) { public Page < DscNodeConfigurationInner > call ( ServiceResponse < Page < DscNodeConfigurationInner > > response ) { return response . body ( ) ; } } ) ; }
Retrieve a list of dsc node configurations .
24,608
public Observable < List < AssemblyDefinitionInner > > listAsync ( String resourceGroupName , String integrationAccountName ) { return listWithServiceResponseAsync ( resourceGroupName , integrationAccountName ) . map ( new Func1 < ServiceResponse < List < AssemblyDefinitionInner > > , List < AssemblyDefinitionInner > > ( ) { public List < AssemblyDefinitionInner > call ( ServiceResponse < List < AssemblyDefinitionInner > > response ) { return response . body ( ) ; } } ) ; }
List the assemblies for an integration account .
24,609
static String parseRoleIdentifier ( final String trackingId ) { if ( StringUtil . isNullOrWhiteSpace ( trackingId ) || ! trackingId . contains ( TRACKING_ID_TOKEN_SEPARATOR ) ) { return null ; } return trackingId . substring ( trackingId . indexOf ( TRACKING_ID_TOKEN_SEPARATOR ) ) ; }
parses ServiceBus role identifiers from trackingId
24,610
public static MySQLManager authenticate ( AzureTokenCredentials credentials , String subscriptionId ) { return new MySQLManager ( new RestClient . Builder ( ) . withBaseUrl ( credentials . environment ( ) , AzureEnvironment . Endpoint . RESOURCE_MANAGER ) . withCredentials ( credentials ) . withSerializerAdapter ( new AzureJacksonAdapter ( ) ) . withResponseBuilderFactory ( new AzureResponseBuilder . Factory ( ) ) . build ( ) , subscriptionId ) ; }
Creates an instance of MySQLManager that exposes DBforMySQL resource management API entry points .
24,611
public void delete ( String resourceGroupName , String automationAccountName , UUID jobScheduleId ) { deleteWithServiceResponseAsync ( resourceGroupName , automationAccountName , jobScheduleId ) . toBlocking ( ) . single ( ) . body ( ) ; }
Delete the job schedule identified by job schedule name .
24,612
public Observable < ApplicationInsightsComponentInner > getByResourceGroupAsync ( String resourceGroupName , String resourceName ) { return getByResourceGroupWithServiceResponseAsync ( resourceGroupName , resourceName ) . map ( new Func1 < ServiceResponse < ApplicationInsightsComponentInner > , ApplicationInsightsComponentInner > ( ) { public ApplicationInsightsComponentInner call ( ServiceResponse < ApplicationInsightsComponentInner > response ) { return response . body ( ) ; } } ) ; }
Returns an Application Insights component .
24,613
public static void validate ( Object parameter ) { if ( parameter == null ) { return ; } Class < ? > type = parameter . getClass ( ) ; if ( type == Double . class || type == Float . class || type == Long . class || type == Integer . class || type == Short . class || type == Character . class || type == Byte . class || type == Boolean . class ) { type = wrapperToPrimitive ( type ) ; } if ( type . isPrimitive ( ) || type . isEnum ( ) || type . isAssignableFrom ( Class . class ) || type . isAssignableFrom ( LocalDate . class ) || type . isAssignableFrom ( OffsetDateTime . class ) || type . isAssignableFrom ( String . class ) || type . isAssignableFrom ( DateTimeRfc1123 . class ) || type . isAssignableFrom ( Duration . class ) ) { return ; } Annotation skipParentAnnotation = type . getAnnotation ( SkipParentValidation . class ) ; if ( skipParentAnnotation == null ) { for ( Class < ? > c : TypeUtil . getAllClasses ( type ) ) { validateClass ( c , parameter ) ; } } else { validateClass ( type , parameter ) ; } }
Validates a user provided required parameter to be not null .
24,614
public Observable < DatabaseInner > getAsync ( String resourceGroupName , String serverName , String databaseName , String expand ) { return getWithServiceResponseAsync ( resourceGroupName , serverName , databaseName , expand ) . map ( new Func1 < ServiceResponse < DatabaseInner > , DatabaseInner > ( ) { public DatabaseInner call ( ServiceResponse < DatabaseInner > response ) { return response . body ( ) ; } } ) ; }
Gets a database .
24,615
public List < DatabaseInner > listByServer ( String resourceGroupName , String serverName , String expand , String filter ) { return listByServerWithServiceResponseAsync ( resourceGroupName , serverName , expand , filter ) . toBlocking ( ) . single ( ) . body ( ) ; }
Returns a list of databases in a server .
24,616
public JobExecutionInner get ( String resourceGroupName , String serverName , String jobAgentName , String jobName , UUID jobExecutionId ) { return getWithServiceResponseAsync ( resourceGroupName , serverName , jobAgentName , jobName , jobExecutionId ) . toBlocking ( ) . single ( ) . body ( ) ; }
Gets a job execution .
24,617
public Observable < VirtualNetworkRuleInner > getAsync ( String resourceGroupName , String accountName , String virtualNetworkRuleName ) { return getWithServiceResponseAsync ( resourceGroupName , accountName , virtualNetworkRuleName ) . map ( new Func1 < ServiceResponse < VirtualNetworkRuleInner > , VirtualNetworkRuleInner > ( ) { public VirtualNetworkRuleInner call ( ServiceResponse < VirtualNetworkRuleInner > response ) { return response . body ( ) ; } } ) ; }
Gets the specified Data Lake Store virtual network rule .
24,618
public Observable < Void > cancelAsync ( String resourceGroupName , String registryName , String buildId ) { return cancelWithServiceResponseAsync ( resourceGroupName , registryName , buildId ) . map ( new Func1 < ServiceResponse < Void > , Void > ( ) { public Void call ( ServiceResponse < Void > response ) { return response . body ( ) ; } } ) ; }
Cancel an existing build .
24,619
public void loadNextPage ( ) { this . currentPage = cachedPage ; cachedPage = null ; this . items . addAll ( currentPage . items ( ) ) ; cachePage ( currentPage . nextPageLink ( ) ) ; }
Loads a page from next page link . The exceptions are wrapped into Java Runtime exceptions .
24,620
protected void setCurrentPage ( Page < E > currentPage ) { this . currentPage = currentPage ; List < E > retrievedItems = currentPage . items ( ) ; if ( retrievedItems != null ) { items . addAll ( retrievedItems ) ; } cachePage ( currentPage . nextPageLink ( ) ) ; }
Sets the current page .
24,621
public void putCustomEventMapping ( final String eventType , final Type eventDataType ) { if ( eventType == null || eventType . isEmpty ( ) ) { throw new IllegalArgumentException ( "eventType parameter is required and cannot be null or empty" ) ; } if ( eventDataType == null ) { throw new IllegalArgumentException ( "eventDataType parameter is required and cannot be null" ) ; } this . eventTypeToEventDataMapping . put ( canonicalizeEventType ( eventType ) , eventDataType ) ; }
Add a custom event mapping . If a mapping with same eventType exists then the old eventDataType is replaced by the specified eventDataType .
24,622
public Type getCustomEventMapping ( final String eventType ) { if ( ! containsCustomEventMappingFor ( eventType ) ) { return null ; } else { return this . eventTypeToEventDataMapping . get ( canonicalizeEventType ( eventType ) ) ; } }
Get type of the Java model that is mapped to the given eventType .
24,623
public boolean removeCustomEventMapping ( final String eventType ) { if ( ! containsCustomEventMappingFor ( eventType ) ) { return false ; } else { this . eventTypeToEventDataMapping . remove ( canonicalizeEventType ( eventType ) ) ; return true ; } }
Removes the mapping with the given eventType .
24,624
public boolean containsCustomEventMappingFor ( final String eventType ) { if ( eventType == null || eventType . isEmpty ( ) ) { return false ; } else { return this . eventTypeToEventDataMapping . containsKey ( canonicalizeEventType ( eventType ) ) ; } }
Checks if an event mapping with the given eventType exists .
24,625
public EventGridEvent [ ] deserializeEventGridEvents ( final String requestContent , final SerializerAdapter < ObjectMapper > serializerAdapter ) throws IOException { EventGridEvent [ ] eventGridEvents = serializerAdapter . < EventGridEvent [ ] > deserialize ( requestContent , EventGridEvent [ ] . class ) ; for ( EventGridEvent receivedEvent : eventGridEvents ) { if ( receivedEvent . data ( ) == null ) { continue ; } else { final String eventType = receivedEvent . eventType ( ) ; final Type eventDataType ; if ( SystemEventTypeMappings . containsMappingFor ( eventType ) ) { eventDataType = SystemEventTypeMappings . getMapping ( eventType ) ; } else if ( containsCustomEventMappingFor ( eventType ) ) { eventDataType = getCustomEventMapping ( eventType ) ; } else { eventDataType = null ; } if ( eventDataType != null ) { final String eventDataAsString = serializerAdapter . serializeRaw ( receivedEvent . data ( ) ) ; final Object eventData = serializerAdapter . < Object > deserialize ( eventDataAsString , eventDataType ) ; setEventData ( receivedEvent , eventData ) ; } } } return eventGridEvents ; }
De - serialize the events in the given requested content using the provided de - serializer .
24,626
public Observable < ApplicationInsightsComponentAvailableFeaturesInner > getAsync ( String resourceGroupName , String resourceName ) { return getWithServiceResponseAsync ( resourceGroupName , resourceName ) . map ( new Func1 < ServiceResponse < ApplicationInsightsComponentAvailableFeaturesInner > , ApplicationInsightsComponentAvailableFeaturesInner > ( ) { public ApplicationInsightsComponentAvailableFeaturesInner call ( ServiceResponse < ApplicationInsightsComponentAvailableFeaturesInner > response ) { return response . body ( ) ; } } ) ; }
Returns all available features of the application insights component .
24,627
public Observable < List < RestorableDroppedDatabaseInner > > listByServerAsync ( String resourceGroupName , String serverName ) { return listByServerWithServiceResponseAsync ( resourceGroupName , serverName ) . map ( new Func1 < ServiceResponse < List < RestorableDroppedDatabaseInner > > , List < RestorableDroppedDatabaseInner > > ( ) { public List < RestorableDroppedDatabaseInner > call ( ServiceResponse < List < RestorableDroppedDatabaseInner > > response ) { return response . body ( ) ; } } ) ; }
Gets a list of deleted databases that can be restored .
24,628
public static ComputerVisionClient authenticate ( ServiceClientCredentials credentials , String endpoint ) { return authenticate ( "https://{endpoint}/vision/v2.0/" , credentials ) . withEndpoint ( endpoint ) ; }
Initializes an instance of Computer Vision API client .
24,629
public Observable < OperationStatus > deleteAsync ( UUID appId , String versionId , int exampleId ) { return deleteWithServiceResponseAsync ( appId , versionId , exampleId ) . map ( new Func1 < ServiceResponse < OperationStatus > , OperationStatus > ( ) { public OperationStatus call ( ServiceResponse < OperationStatus > response ) { return response . body ( ) ; } } ) ; }
Deletes the labeled example with the specified ID .
24,630
public static byte [ ] encodeURLWithoutPadding ( byte [ ] src ) { return src == null ? null : Base64 . getUrlEncoder ( ) . withoutPadding ( ) . encode ( src ) ; }
Encodes a byte array to base64 URL format .
24,631
public static String encodeToString ( byte [ ] src ) { return src == null ? null : Base64 . getEncoder ( ) . encodeToString ( src ) ; }
Encodes a byte array to a base 64 string .
24,632
public static byte [ ] decodeString ( String encoded ) { return encoded == null ? null : Base64 . getDecoder ( ) . decode ( encoded ) ; }
Decodes a base64 encoded string .
24,633
public Observable < DatabaseSecurityAlertPolicyInner > getAsync ( String resourceGroupName , String serverName , String databaseName ) { return getWithServiceResponseAsync ( resourceGroupName , serverName , databaseName ) . map ( new Func1 < ServiceResponse < DatabaseSecurityAlertPolicyInner > , DatabaseSecurityAlertPolicyInner > ( ) { public DatabaseSecurityAlertPolicyInner call ( ServiceResponse < DatabaseSecurityAlertPolicyInner > response ) { return response . body ( ) ; } } ) ; }
Gets a database s threat detection policy .
24,634
public Observable < DatabaseSecurityAlertPolicyInner > createOrUpdateAsync ( String resourceGroupName , String serverName , String databaseName , DatabaseSecurityAlertPolicyInner parameters ) { return createOrUpdateWithServiceResponseAsync ( resourceGroupName , serverName , databaseName , parameters ) . map ( new Func1 < ServiceResponse < DatabaseSecurityAlertPolicyInner > , DatabaseSecurityAlertPolicyInner > ( ) { public DatabaseSecurityAlertPolicyInner call ( ServiceResponse < DatabaseSecurityAlertPolicyInner > response ) { return response . body ( ) ; } } ) ; }
Creates or updates a database s threat detection policy .
24,635
public static List < Class < ? > > getAllClasses ( Class < ? > clazz ) { List < Class < ? > > types = new ArrayList < > ( ) ; while ( clazz != null ) { types . add ( clazz ) ; clazz = clazz . getSuperclass ( ) ; } return types ; }
Find all super classes including provided class .
24,636
public static Type [ ] getTypeArguments ( Type type ) { if ( ! ( type instanceof ParameterizedType ) ) { return new Type [ 0 ] ; } return ( ( ParameterizedType ) type ) . getActualTypeArguments ( ) ; }
Get the generic arguments for a type .
24,637
public static Type getTypeArgument ( Type type ) { if ( ! ( type instanceof ParameterizedType ) ) { return null ; } return ( ( ParameterizedType ) type ) . getActualTypeArguments ( ) [ 0 ] ; }
Get the generic argument or the first if the type has more than one .
24,638
public static Type getSuperType ( Type type ) { if ( type instanceof ParameterizedType ) { ParameterizedType parameterizedType = ( ParameterizedType ) type ; Type genericSuperClass = ( ( Class < ? > ) parameterizedType . getRawType ( ) ) . getGenericSuperclass ( ) ; if ( genericSuperClass instanceof ParameterizedType ) { Type [ ] superTypeArguments = getTypeArguments ( genericSuperClass ) ; List < Type > typeParameters = Arrays . asList ( ( ( Class < ? > ) parameterizedType . getRawType ( ) ) . getTypeParameters ( ) ) ; int j = 0 ; for ( int i = 0 ; i != superTypeArguments . length ; i ++ ) { if ( typeParameters . contains ( superTypeArguments [ i ] ) ) { superTypeArguments [ i ] = parameterizedType . getActualTypeArguments ( ) [ j ++ ] ; } } return new ParameterizedType ( ) { public Type [ ] getActualTypeArguments ( ) { return superTypeArguments ; } public Type getRawType ( ) { return ( ( ParameterizedType ) genericSuperClass ) . getRawType ( ) ; } public Type getOwnerType ( ) { return null ; } } ; } else { return genericSuperClass ; } } else { return ( ( Class < ? > ) type ) . getGenericSuperclass ( ) ; } }
Get the super type for a given type .
24,639
public static Type getSuperType ( Type subType , Class < ? > rawSuperType ) { while ( subType != null && getRawClass ( subType ) != rawSuperType ) { subType = getSuperType ( subType ) ; } return subType ; }
Get the super type for a type in its super type chain which has a raw class that matches the specified class .
24,640
public static boolean isTypeOrSubTypeOf ( Type subType , Type superType ) { Class < ? > sub = getRawClass ( subType ) ; Class < ? > sup = getRawClass ( superType ) ; return sup . isAssignableFrom ( sub ) ; }
Determines if a type is the same or a subtype for another type .
24,641
public static ParameterizedType createParameterizedType ( Class < ? > rawClass , Type ... genericTypes ) { return new ParameterizedType ( ) { public Type [ ] getActualTypeArguments ( ) { return genericTypes ; } public Type getRawType ( ) { return rawClass ; } public Type getOwnerType ( ) { return null ; } } ; }
Create a parameterized type from a raw class and its type arguments .
24,642
public static Type getRestResponseBodyType ( Type restResponseReturnType ) { final Type [ ] restResponseTypeArguments = TypeUtil . getTypeArguments ( restResponseReturnType ) ; if ( restResponseTypeArguments != null && restResponseTypeArguments . length > 0 ) { return restResponseTypeArguments [ restResponseTypeArguments . length - 1 ] ; } else { return getRestResponseBodyType ( TypeUtil . getSuperType ( restResponseReturnType ) ) ; } }
Returns the body type expected in the rest response .
24,643
int calculateCode ( byte [ ] key , long tm ) { byte [ ] data = new byte [ 8 ] ; long value = tm ; for ( int i = 8 ; i -- > 0 ; value >>>= 8 ) { data [ i ] = ( byte ) value ; } SecretKeySpec signKey = new SecretKeySpec ( key , config . getHmacHashFunction ( ) . toString ( ) ) ; try { Mac mac = Mac . getInstance ( config . getHmacHashFunction ( ) . toString ( ) ) ; mac . init ( signKey ) ; byte [ ] hash = mac . doFinal ( data ) ; int offset = hash [ hash . length - 1 ] & 0xF ; long truncatedHash = 0 ; for ( int i = 0 ; i < 4 ; ++ i ) { truncatedHash <<= 8 ; truncatedHash |= ( hash [ offset + i ] & 0xFF ) ; } truncatedHash &= 0x7FFFFFFF ; truncatedHash %= config . getKeyModulus ( ) ; return ( int ) truncatedHash ; } catch ( NoSuchAlgorithmException | InvalidKeyException ex ) { LOGGER . log ( Level . SEVERE , ex . getMessage ( ) , ex ) ; throw new GoogleAuthenticatorException ( "The operation cannot be performed now." ) ; } }
Calculates the verification code of the provided key at the specified instant of time using the algorithm specified in RFC 6238 .
24,644
private boolean checkCode ( String secret , long code , long timestamp , int window ) { byte [ ] decodedKey = decodeSecret ( secret ) ; final long timeWindow = getTimeWindowFromTime ( timestamp ) ; for ( int i = - ( ( window - 1 ) / 2 ) ; i <= window / 2 ; ++ i ) { long hash = calculateCode ( decodedKey , timeWindow + i ) ; if ( hash == code ) { return true ; } } return false ; }
This method implements the algorithm specified in RFC 6238 to check if a validation code is valid in a given instant of time for the given secret key .
24,645
private int generateScratchCode ( ) { while ( true ) { byte [ ] scratchCodeBuffer = new byte [ BYTES_PER_SCRATCH_CODE ] ; secureRandom . nextBytes ( scratchCodeBuffer ) ; int scratchCode = calculateScratchCode ( scratchCodeBuffer ) ; if ( scratchCode != SCRATCH_CODE_INVALID ) { return scratchCode ; } } }
This method creates a new random byte buffer from which a new scratch code is generated . This function is invoked if a scratch code generated from the main buffer is invalid because it does not satisfy the scratch code restrictions .
24,646
private String calculateSecretKey ( byte [ ] secretKey ) { switch ( config . getKeyRepresentation ( ) ) { case BASE32 : return new Base32 ( ) . encodeToString ( secretKey ) ; case BASE64 : return new Base64 ( ) . encodeToString ( secretKey ) ; default : throw new IllegalArgumentException ( "Unknown key representation type." ) ; } }
This method calculates the secret key given a random byte buffer .
24,647
private ICredentialRepository getValidCredentialRepository ( ) { ICredentialRepository repository = getCredentialRepository ( ) ; if ( repository == null ) { throw new UnsupportedOperationException ( String . format ( "An instance of the %s service must be " + "configured in order to use this feature." , ICredentialRepository . class . getName ( ) ) ) ; } return repository ; }
This method loads the first available and valid ICredentialRepository registered using the Java service loader API .
24,648
public ICredentialRepository getCredentialRepository ( ) { if ( this . credentialRepositorySearched ) return this . credentialRepository ; this . credentialRepositorySearched = true ; ServiceLoader < ICredentialRepository > loader = ServiceLoader . load ( ICredentialRepository . class ) ; for ( ICredentialRepository repository : loader ) { this . credentialRepository = repository ; break ; } return this . credentialRepository ; }
This method loads the first available ICredentialRepository registered using the Java service loader API .
24,649
public static void buildMeta ( Writer writer , String indexType , String indexName , Object params , String action , ClientOptions clientOption , boolean upper7 ) throws IOException { if ( params instanceof Map ) { buildMapMeta ( writer , indexType , indexName , ( Map ) params , action , clientOption , upper7 ) ; return ; } Object id = null ; Object parentId = null ; Object routing = null ; Object esRetryOnConflict = null ; Object version = null ; Object versionType = null ; if ( clientOption != null ) { ClassUtil . ClassInfo beanClassInfo = ClassUtil . getClassInfo ( params . getClass ( ) ) ; id = clientOption . getIdField ( ) != null ? BuildTool . getId ( params , beanClassInfo , clientOption . getIdField ( ) ) : null ; parentId = clientOption . getParentIdField ( ) != null ? BuildTool . getParentId ( params , beanClassInfo , clientOption . getParentIdField ( ) ) : null ; routing = clientOption . getRountField ( ) != null ? BuildTool . getRouting ( params , beanClassInfo , clientOption . getRountField ( ) ) : null ; esRetryOnConflict = clientOption . getEsRetryOnConflictField ( ) != null ? BuildTool . getEsRetryOnConflict ( params , beanClassInfo , clientOption . getEsRetryOnConflictField ( ) ) : null ; version = clientOption . getVersionField ( ) != null ? BuildTool . getEsRetryOnConflict ( params , beanClassInfo , clientOption . getVersionField ( ) ) : null ; versionType = clientOption . getVersionTypeField ( ) != null ? BuildTool . getEsRetryOnConflict ( params , beanClassInfo , clientOption . getVersionTypeField ( ) ) : null ; } buildMeta ( writer , indexType , indexName , params , action , id , parentId , routing , esRetryOnConflict , version , versionType , upper7 ) ; }
String docIdKey String parentIdKey String routingKey
24,650
public boolean process ( ) throws ResourceNotFoundException , ParseErrorException { if ( processed ) return true ; synchronized ( this ) { if ( processed ) return true ; data = null ; errorCondition = null ; Reader is = null ; try { is = new BBossStringReader ( template ) ; } catch ( ResourceNotFoundException rnfe ) { errorCondition = rnfe ; processed = true ; throw rnfe ; } if ( is != null ) { try { BufferedReader br = new BufferedReader ( is ) ; data = rsvc . parse ( br , name ) ; initDocument ( ) ; processed = true ; try { rechecksqlistpl ( ) ; } catch ( Exception e ) { } return true ; } catch ( ParseException pex ) { errorCondition = new ParseErrorException ( pex , name ) ; processed = true ; throw errorCondition ; } catch ( TemplateInitException pex ) { errorCondition = new ParseErrorException ( pex , name ) ; processed = true ; throw errorCondition ; } catch ( RuntimeException e ) { errorCondition = new VelocityException ( "Exception thrown processing Template " + getName ( ) , e ) ; processed = true ; throw errorCondition ; } finally { processed = true ; try { is . close ( ) ; } catch ( IOException e ) { if ( errorCondition == null ) { throw new VelocityException ( e ) ; } } } } else { errorCondition = new ResourceNotFoundException ( "Unknown resource error for resource " + name ) ; processed = true ; throw errorCondition ; } } }
gets the named resource as a stream parses and inits
24,651
public String addDateDocumentsNew ( String indexName , String addTemplate , List < ? > beans , String refreshOption ) throws ElasticSearchException { return addDateDocuments ( indexName , _doc , addTemplate , beans , refreshOption ) ; }
For Elasticsearch 7 and 7 +
24,652
public static Map < String , String > getEscapeMapping ( String in , Map < String , String > headers ) { return getEscapeMapping ( in , headers , false , 0 , 0 ) ; }
Instead of replacing escape sequences in a string this method returns a mapping of an attribute name to the value based on the escape sequence found in the argument string .
24,653
private void openClient ( String clusterName ) { logger . info ( "Using ElasticSearch hostnames: {} " , Arrays . toString ( serverAddresses ) ) ; Settings settings = null ; Settings . Builder builder = Settings . builder ( ) ; if ( this . elasticUser != null && ! this . elasticUser . equals ( "" ) ) { builder . put ( "cluster.name" , clusterName ) . put ( "xpack.security.user" , this . elasticUser + ":" + this . elasticPassword ) ; } else { builder . put ( "cluster.name" , clusterName ) ; } if ( this . extendElasticsearchPropes != null && extendElasticsearchPropes . size ( ) > 0 ) { Iterator < Entry < Object , Object > > iterator = extendElasticsearchPropes . entrySet ( ) . iterator ( ) ; while ( iterator . hasNext ( ) ) { Entry < Object , Object > entry = iterator . next ( ) ; builder . put ( ( String ) entry . getKey ( ) , String . valueOf ( entry . getValue ( ) ) ) ; } } settings = builder . build ( ) ; try { TransportClient transportClient = this . elasticUser != null && ! this . elasticUser . equals ( "" ) ? new PreBuiltXPackTransportClient ( settings ) : new PreBuiltTransportClient ( settings ) ; for ( TransportAddress host : serverAddresses ) { transportClient . addTransportAddress ( host ) ; } if ( client != null ) { client . close ( ) ; } client = transportClient ; } catch ( RuntimeException e ) { e . printStackTrace ( ) ; } catch ( Throwable e ) { e . printStackTrace ( ) ; } }
Open client to elaticsearch cluster
24,654
public ClientInterface getRestClient ( ) { if ( restClient == null ) { synchronized ( this ) { if ( restClient == null ) { restClient = ElasticSearchHelper . getRestClientUtil ( ) ; } } } return restClient ; }
Get default elasticsearch server ClientInterface
24,655
public ClientInterface getConfigRestClient ( String elasticsearchName , String configFile ) { return ElasticSearchHelper . getConfigRestClientUtil ( elasticsearchName , configFile ) ; }
Get Special elasticsearch server ConfigFile ClientInterface
24,656
public void setStyleClass ( int from , int to , String styleClass ) { setStyle ( from , to , Collections . singletonList ( styleClass ) ) ; }
Convenient method to assign a single style class .
24,657
TwoDimensional . Position currentLine ( ) { int parIdx = getCurrentParagraph ( ) ; Cell < Paragraph < PS , SEG , S > , ParagraphBox < PS , SEG , S > > cell = virtualFlow . getCell ( parIdx ) ; int lineIdx = cell . getNode ( ) . getCurrentLineIndex ( caretSelectionBind . getUnderlyingCaret ( ) ) ; return paragraphLineNavigator . position ( parIdx , lineIdx ) ; }
Returns the current line as a two - level index . The major number is the paragraph index the minor number is the line number within the paragraph .
24,658
final ParagraphBox . CaretOffsetX getCaretOffsetX ( CaretNode caret ) { return getCell ( caret . getParagraphIndex ( ) ) . getCaretOffsetX ( caret ) ; }
Returns x coordinate of the caret in the current paragraph .
24,659
public Paragraph < PS , SEG , S > restyle ( S style ) { return new Paragraph < > ( paragraphStyle , segmentOps , segments , StyleSpans . singleton ( style , length ( ) ) ) ; }
Restyles every segment in the paragraph to have the given style .
24,660
public Paragraph < PS , SEG , S > setParagraphStyle ( PS paragraphStyle ) { return new Paragraph < > ( paragraphStyle , segmentOps , segments , styles ) ; }
Creates a new Paragraph which has the same contents as the current Paragraph but the given paragraph style .
24,661
public String getText ( ) { if ( text == null ) { StringBuilder sb = new StringBuilder ( length ( ) ) ; for ( SEG seg : segments ) sb . append ( segmentOps . getText ( seg ) ) ; text = sb . toString ( ) ; } return text ; }
Returns the plain text content of this paragraph not including the line terminator .
24,662
public Tuple2 < ReadOnlyStyledDocument < PS , SEG , S > , ReadOnlyStyledDocument < PS , SEG , S > > split ( int position ) { return tree . locate ( NAVIGATE , position ) . map ( this :: split ) ; }
Splits this document into two at the given position and returns both halves .
24,663
public Tuple2 < ReadOnlyStyledDocument < PS , SEG , S > , ReadOnlyStyledDocument < PS , SEG , S > > split ( int paragraphIndex , int columnPosition ) { return tree . splitAt ( paragraphIndex ) . map ( ( l , p , r ) -> { Paragraph < PS , SEG , S > p1 = p . trim ( columnPosition ) ; Paragraph < PS , SEG , S > p2 = p . subSequence ( columnPosition ) ; ReadOnlyStyledDocument < PS , SEG , S > doc1 = new ReadOnlyStyledDocument < > ( l . append ( p1 ) ) ; ReadOnlyStyledDocument < PS , SEG , S > doc2 = new ReadOnlyStyledDocument < > ( r . prepend ( p2 ) ) ; return t ( doc1 , doc2 ) ; } ) ; }
Splits this document into two at the given paragraph s column position and returns both halves .
24,664
public static < PS , SEG , S > ReadOnlyStyledDocument < PS , SEG , S > constructDocument ( SegmentOps < SEG , S > segmentOps , PS defaultParagraphStyle , Consumer < ReadOnlyStyledDocumentBuilder < PS , SEG , S > > configuration ) { ReadOnlyStyledDocumentBuilder < PS , SEG , S > builder = new ReadOnlyStyledDocumentBuilder < > ( segmentOps , defaultParagraphStyle ) ; configuration . accept ( builder ) ; return builder . build ( ) ; }
Constructs a list of paragraphs
24,665
public ReadOnlyStyledDocumentBuilder < PS , SEG , S > addParagraph ( List < SEG > segments , StyleSpans < S > styles ) { return addParagraph ( segments , styles , null ) ; }
Adds to the list a paragraph that has multiple segments with multiple styles throughout those segments
24,666
public ReadOnlyStyledDocumentBuilder < PS , SEG , S > addParagraphs0 ( List < Tuple2 < PS , List < SEG > > > paragraphArgList , StyleSpans < S > entireDocumentStyleSpans ) { return addParagraphList ( paragraphArgList , entireDocumentStyleSpans , Tuple2 :: get1 , Tuple2 :: get2 ) ; }
Adds multiple paragraphs to the list allowing one to specify each paragraph s paragraph style .
24,667
private void moveContentBreaks ( int numOfBreaks , BreakIterator breakIterator , boolean followingNotPreceding ) { if ( area . getLength ( ) == 0 ) { return ; } breakIterator . setText ( area . getText ( ) ) ; if ( followingNotPreceding ) { breakIterator . following ( getPosition ( ) ) ; } else { breakIterator . preceding ( getPosition ( ) ) ; } for ( int i = 1 ; i < numOfBreaks ; i ++ ) { breakIterator . next ( ) ; } moveTo ( breakIterator . current ( ) ) ; }
Helper method for reducing duplicate code
24,668
private void insertImage ( ) { String initialDir = System . getProperty ( "user.dir" ) ; FileChooser fileChooser = new FileChooser ( ) ; fileChooser . setTitle ( "Insert image" ) ; fileChooser . setInitialDirectory ( new File ( initialDir ) ) ; File selectedFile = fileChooser . showOpenDialog ( mainStage ) ; if ( selectedFile != null ) { String imagePath = selectedFile . getAbsolutePath ( ) ; imagePath = imagePath . replace ( '\\' , '/' ) ; ReadOnlyStyledDocument < ParStyle , Either < String , LinkedImage > , TextStyle > ros = ReadOnlyStyledDocument . fromSegment ( Either . right ( new RealLinkedImage ( imagePath ) ) , ParStyle . EMPTY , TextStyle . EMPTY , area . getSegOps ( ) ) ; area . replaceSelection ( ros ) ; } }
Action listener which inserts a new image at the current caret position .
24,669
CharacterHit hitTextLine ( CaretOffsetX x , int line ) { return text . hitLine ( x . value , line ) ; }
Hits the embedded TextFlow at the given line and x offset .
24,670
CharacterHit hitText ( CaretOffsetX x , double y ) { return text . hit ( x . value , y ) ; }
Hits the embedded TextFlow at the given x and y offset .
24,671
public void selectRangeExpl ( int anchorParagraph , int anchorColumn , int caretParagraph , int caretColumn ) { selectRangeExpl ( textPosition ( anchorParagraph , anchorColumn ) , textPosition ( caretParagraph , caretColumn ) ) ; }
caret selection bind
24,672
public static LogMonitor logMonitor ( ) { return new LogMonitor ( ) { public void corruption ( long bytes , String reason ) { System . out . println ( String . format ( "corruption of %s bytes: %s" , bytes , reason ) ) ; } public void corruption ( long bytes , Throwable reason ) { System . out . println ( String . format ( "corruption of %s bytes" , bytes ) ) ; reason . printStackTrace ( ) ; } } ; }
todo implement real logging
24,673
public void seek ( Slice targetKey ) { if ( restartCount == 0 ) { return ; } int left = 0 ; int right = restartCount - 1 ; while ( left < right ) { int mid = ( left + right + 1 ) / 2 ; seekToRestartPosition ( mid ) ; if ( comparator . compare ( nextEntry . getKey ( ) , targetKey ) < 0 ) { left = mid ; } else { right = mid - 1 ; } } for ( seekToRestartPosition ( left ) ; nextEntry != null ; next ( ) ) { if ( comparator . compare ( peek ( ) . getKey ( ) , targetKey ) >= 0 ) { break ; } } }
Repositions the iterator so the key of the next BlockElement returned greater than or equal to the specified targetKey .
24,674
private static BlockEntry readEntry ( SliceInput data , BlockEntry previousEntry ) { requireNonNull ( data , "data is null" ) ; int sharedKeyLength = VariableLengthQuantity . readVariableLengthInt ( data ) ; int nonSharedKeyLength = VariableLengthQuantity . readVariableLengthInt ( data ) ; int valueLength = VariableLengthQuantity . readVariableLengthInt ( data ) ; Slice key = Slices . allocate ( sharedKeyLength + nonSharedKeyLength ) ; SliceOutput sliceOutput = key . output ( ) ; if ( sharedKeyLength > 0 ) { checkState ( previousEntry != null , "Entry has a shared key but no previous entry was provided" ) ; sliceOutput . writeBytes ( previousEntry . getKey ( ) , 0 , sharedKeyLength ) ; } sliceOutput . writeBytes ( data , nonSharedKeyLength ) ; Slice value = data . readSlice ( valueLength ) ; return new BlockEntry ( key , value ) ; }
Reads the entry at the current data readIndex . After this method data readIndex is positioned at the beginning of the next entry or at the end of data if there was not a next entry .
24,675
public static boolean setCurrentFile ( File databaseDir , long descriptorNumber ) throws IOException { String manifest = descriptorFileName ( descriptorNumber ) ; String temp = tempFileName ( descriptorNumber ) ; File tempFile = new File ( databaseDir , temp ) ; writeStringToFileSync ( manifest + "\n" , tempFile ) ; File to = new File ( databaseDir , currentFileName ( ) ) ; boolean ok = tempFile . renameTo ( to ) ; if ( ! ok ) { tempFile . delete ( ) ; writeStringToFileSync ( manifest + "\n" , to ) ; } return ok ; }
Make the CURRENT file point to the descriptor file with the specified number .
24,676
public boolean isBaseLevelForKey ( Slice userKey ) { UserComparator userComparator = inputVersion . getInternalKeyComparator ( ) . getUserComparator ( ) ; for ( int level = this . level + 2 ; level < NUM_LEVELS ; level ++ ) { List < FileMetaData > files = inputVersion . getFiles ( level ) ; while ( levelPointers [ level ] < files . size ( ) ) { FileMetaData f = files . get ( levelPointers [ level ] ) ; if ( userComparator . compare ( userKey , f . getLargest ( ) . getUserKey ( ) ) <= 0 ) { if ( userComparator . compare ( userKey , f . getSmallest ( ) . getUserKey ( ) ) >= 0 ) { return false ; } break ; } levelPointers [ level ] ++ ; } } return true ; }
in levels greater than level + 1 .
24,677
public boolean shouldStopBefore ( InternalKey internalKey ) { InternalKeyComparator internalKeyComparator = inputVersion . getInternalKeyComparator ( ) ; while ( grandparentIndex < grandparents . size ( ) && internalKeyComparator . compare ( internalKey , grandparents . get ( grandparentIndex ) . getLargest ( ) ) > 0 ) { if ( seenKey ) { overlappedBytes += grandparents . get ( grandparentIndex ) . getFileSize ( ) ; } grandparentIndex ++ ; } seenKey = true ; if ( overlappedBytes > MAX_GRAND_PARENT_OVERLAP_BYTES ) { overlappedBytes = 0 ; return true ; } else { return false ; } }
before processing internal_key .
24,678
public Slice copySlice ( int index , int length ) { checkPositionIndexes ( index , index + length , this . length ) ; index += offset ; byte [ ] copiedArray = new byte [ length ] ; System . arraycopy ( data , index , copiedArray , 0 , length ) ; return new Slice ( copiedArray ) ; }
Returns a copy of this buffer s sub - region . Modifying the content of the returned buffer or this buffer does not affect each other at all .
24,679
public Slice slice ( int index , int length ) { if ( index == 0 && length == this . length ) { return this ; } checkPositionIndexes ( index , index + length , this . length ) ; if ( index >= 0 && length == 0 ) { return Slices . EMPTY_SLICE ; } return new Slice ( data , offset + index , length ) ; }
Returns a slice of this buffer s sub - region . Modifying the content of the returned buffer or this buffer affects each other s content while they maintain separate indexes and marks .
24,680
public ByteBuffer toByteBuffer ( int index , int length ) { checkPositionIndexes ( index , index + length , this . length ) ; index += offset ; return ByteBuffer . wrap ( data , index , length ) . order ( LITTLE_ENDIAN ) ; }
Converts this buffer s sub - region into a NIO buffer . The returned buffer shares the content with this buffer .
24,681
private LogChunkType readNextChunk ( ) { currentChunk = Slices . EMPTY_SLICE ; if ( currentBlock . available ( ) < HEADER_SIZE ) { if ( ! readNextBlock ( ) ) { if ( eof ) { return EOF ; } } } int expectedChecksum = currentBlock . readInt ( ) ; int length = currentBlock . readUnsignedByte ( ) ; length = length | currentBlock . readUnsignedByte ( ) << 8 ; byte chunkTypeId = currentBlock . readByte ( ) ; LogChunkType chunkType = getLogChunkTypeByPersistentId ( chunkTypeId ) ; if ( length > currentBlock . available ( ) ) { int dropSize = currentBlock . available ( ) + HEADER_SIZE ; reportCorruption ( dropSize , "Invalid chunk length" ) ; currentBlock = Slices . EMPTY_SLICE . input ( ) ; return BAD_CHUNK ; } if ( chunkType == ZERO_TYPE && length == 0 ) { currentBlock = Slices . EMPTY_SLICE . input ( ) ; return BAD_CHUNK ; } if ( endOfBufferOffset - HEADER_SIZE - length < initialOffset ) { currentBlock . skipBytes ( length ) ; return BAD_CHUNK ; } currentChunk = currentBlock . readBytes ( length ) ; if ( verifyChecksums ) { int actualChecksum = getChunkChecksum ( chunkTypeId , currentChunk ) ; if ( actualChecksum != expectedChecksum ) { int dropSize = currentBlock . available ( ) + HEADER_SIZE ; currentBlock = Slices . EMPTY_SLICE . input ( ) ; reportCorruption ( dropSize , "Invalid chunk checksum" ) ; return BAD_CHUNK ; } } if ( chunkType == UNKNOWN ) { reportCorruption ( length , String . format ( "Unknown chunk type %d" , chunkType . getPersistentId ( ) ) ) ; return BAD_CHUNK ; } return chunkType ; }
Return type or one of the preceding special values
24,682
private void reportCorruption ( long bytes , String reason ) { if ( monitor != null ) { monitor . corruption ( bytes , reason ) ; } }
Reports corruption to the monitor . The buffer must be updated to remove the dropped bytes prior to invocation .
24,683
private void reportDrop ( long bytes , Throwable reason ) { if ( monitor != null ) { monitor . corruption ( bytes , reason ) ; } }
Reports dropped bytes to the monitor . The buffer must be updated to remove the dropped bytes prior to invocation .
24,684
public T get ( ) throws InterruptedException { if ( ! valueReady . await ( ( long ) ( timeout * 1000 ) , TimeUnit . MILLISECONDS ) ) { String msg = String . format ( "BlockingVariable.get() timed out after %1.2f seconds" , timeout ) ; throw new SpockTimeoutError ( timeout , msg ) ; } return value ; }
Blocks until a value has been set for this variable or a timeout expires .
24,685
private void handleWhereBlock ( Method method ) { Block block = method . getLastBlock ( ) ; if ( ! ( block instanceof WhereBlock ) ) return ; new DeepBlockRewriter ( this ) . visit ( block ) ; WhereBlockRewriter . rewrite ( ( WhereBlock ) block , this ) ; }
will then be used by DeepBlockRewriter
24,686
private void handleFeatureIncludes ( SpecInfo spec , IncludeExcludeCriteria criteria ) { if ( criteria . isEmpty ( ) ) return ; for ( FeatureInfo feature : spec . getAllFeatures ( ) ) if ( hasAnyAnnotation ( feature . getFeatureMethod ( ) , criteria . annotations ) ) feature . setExcluded ( false ) ; }
in contrast to the three other handleXXX methods this one includes nodes
24,687
public void visitField ( FieldNode gField ) { PropertyNode owner = spec . getAst ( ) . getProperty ( gField . getName ( ) ) ; if ( gField . isStatic ( ) ) return ; Field field = new Field ( spec , gField , fieldCount ++ ) ; field . setShared ( AstUtil . hasAnnotation ( gField , Shared . class ) ) ; field . setOwner ( owner ) ; spec . getFields ( ) . add ( field ) ; }
although it IS related to a user - provided definition
24,688
private boolean constructorMayHaveBeenAddedByCompiler ( ConstructorNode constructor ) { Parameter [ ] params = constructor . getParameters ( ) ; Statement firstStat = constructor . getFirstStatement ( ) ; return AstUtil . isJointCompiled ( spec . getAst ( ) ) && constructor . isPublic ( ) && params != null && params . length == 0 && firstStat == null ; }
to add special logic to detect this case .
24,689
public ExpressionStatement rewrite ( ExpressionStatement stat ) { try { if ( ! isInteraction ( stat ) ) return null ; createBuilder ( ) ; setCount ( ) ; setCall ( ) ; addResponses ( ) ; build ( ) ; return register ( ) ; } catch ( InvalidSpecCompileException e ) { resources . getErrorReporter ( ) . error ( e ) ; return null ; } }
If the given statement is a valid interaction definition returns the rewritten statement . If the given statement is not an interaction definition returns null . If the given statement is an invalid interaction definition records a compile error and returns null .
24,690
private Object createEmptyWrapper ( Class < ? > type ) { if ( Number . class . isAssignableFrom ( type ) ) { Method method = ReflectionUtil . getDeclaredMethodBySignature ( type , "valueOf" , String . class ) ; if ( method != null && method . getReturnType ( ) == type ) { return ReflectionUtil . invokeMethod ( type , method , "0" ) ; } if ( type == BigInteger . class ) return BigInteger . ZERO ; if ( type == BigDecimal . class ) return BigDecimal . ZERO ; return null ; } if ( type == Boolean . class ) return false ; if ( type == Character . class ) return ( char ) 0 ; return null ; }
also handles some numeric types which aren t primitive wrapper types
24,691
public void await ( int value , TimeUnit unit ) throws Throwable { await ( TimeUtil . toSeconds ( value , unit ) ) ; }
Waits until all evaluate blocks have completed or the specified timeout expires . If one of the evaluate blocks throws an exception it is rethrown from this method .
24,692
private static RunContext createBottomContext ( ) { File spockUserHome = SpockUserHomeUtil . getSpockUserHome ( ) ; DelegatingScript script = new ConfigurationScriptLoader ( spockUserHome ) . loadAutoDetectedScript ( ) ; List < Class < ? > > classes = new ExtensionClassesLoader ( ) . loadClassesFromDefaultLocation ( ) ; return new RunContext ( "default" , spockUserHome , script , classes ) ; }
this shouldn t be much of a problem in practice .
24,693
public static void closeQuietly ( final Socket ... sockets ) { if ( sockets == null ) return ; for ( Socket socket : sockets ) { if ( socket == null ) return ; try { socket . close ( ) ; } catch ( IOException ignored ) { } } }
In JDK 1 . 6 java . net . Socket doesn t implement Closeable so we have this overload .
24,694
public static String getText ( Reader reader ) throws IOException { try { StringBuilder source = new StringBuilder ( ) ; BufferedReader buffered = new BufferedReader ( reader ) ; String line = buffered . readLine ( ) ; while ( line != null ) { source . append ( line ) ; source . append ( '\n' ) ; line = buffered . readLine ( ) ; } return source . toString ( ) ; } finally { closeQuietly ( reader ) ; } }
Returns the text read from the given reader as a String . Closes the given reader upon return .
24,695
public static OperatingSystem getCurrent ( ) { String name = System . getProperty ( "os.name" ) ; String version = System . getProperty ( "os.version" ) ; String lowerName = name . toLowerCase ( ) ; if ( lowerName . contains ( "linux" ) ) return new OperatingSystem ( name , version , Family . LINUX ) ; if ( lowerName . contains ( "mac os" ) || lowerName . contains ( "darwin" ) ) return new OperatingSystem ( name , version , Family . MAC_OS ) ; if ( lowerName . contains ( "windows" ) ) return new OperatingSystem ( name , version , Family . WINDOWS ) ; if ( lowerName . contains ( "sunos" ) ) return new OperatingSystem ( name , version , Family . SOLARIS ) ; return new OperatingSystem ( name , version , Family . OTHER ) ; }
Returns the current operating system .
24,696
private boolean forbidUseOfSuperInFixtureMethod ( MethodCallExpression expr ) { Method currMethod = resources . getCurrentMethod ( ) ; Expression target = expr . getObjectExpression ( ) ; if ( currMethod instanceof FixtureMethod && target instanceof VariableExpression && ( ( VariableExpression ) target ) . isSuperExpression ( ) && currMethod . getName ( ) . equals ( expr . getMethodAsString ( ) ) ) { resources . getErrorReporter ( ) . error ( expr , "A base class fixture method should not be called explicitly " + "because it is always invoked automatically by the framework" ) ; return true ; } return false ; }
the base method and doesn t know that it will be run automatically )
24,697
public static Throwable getRootCause ( Throwable exception ) { Assert . notNull ( exception ) ; return exception . getCause ( ) == null ? exception : getRootCause ( exception . getCause ( ) ) ; }
Returns the innermost cause of the specified exception . If the specified exception has no cause the exception itself is returned .
24,698
public static List < Throwable > getCauseChain ( Throwable exception ) { Assert . notNull ( exception ) ; List < Throwable > result = new ArrayList < > ( ) ; collectCauseChain ( exception , result ) ; return result ; }
Returns a list of all causes of the specified exception . The first element of the returned list is the specified exception itself ; the last element is its root cause .
24,699
public static Type getArrayComponentType ( Type type ) { if ( type instanceof Class ) { Class < ? > clazz = ( Class < ? > ) type ; return clazz . getComponentType ( ) ; } else if ( type instanceof GenericArrayType ) { GenericArrayType aType = ( GenericArrayType ) type ; return aType . getGenericComponentType ( ) ; } else { return null ; } }
If type is an array type returns the type of the component of the array . Otherwise returns null .