idx int64 0 165k | question stringlengths 73 4.15k | target stringlengths 5 918 | len_question int64 21 890 | len_target int64 3 255 |
|---|---|---|---|---|
145,300 | public static boolean hasAnnotation ( AnnotatedNode node , String name ) { return AstUtil . getAnnotation ( node , name ) != null ; } | Return true only if the node has the named annotation | 34 | 10 |
145,301 | public static boolean hasAnyAnnotation ( AnnotatedNode node , String ... names ) { for ( String name : names ) { if ( hasAnnotation ( node , name ) ) { return true ; } } return false ; } | Return true only if the node has any of the named annotations | 48 | 12 |
145,302 | public static List < Expression > getVariableExpressions ( DeclarationExpression declarationExpression ) { Expression leftExpression = declarationExpression . getLeftExpression ( ) ; // !important: performance enhancement if ( leftExpression instanceof ArrayExpression ) { List < Expression > expressions = ( ( ArrayExpression ) leftExpression ) . getExpressions ( ) ; return expressions . isEmpty ( ) ? Arrays . asList ( leftExpression ) : expressions ; } else if ( leftExpression instanceof ListExpression ) { List < Expression > expressions = ( ( ListExpression ) leftExpression ) . getExpressions ( ) ; return expressions . isEmpty ( ) ? Arrays . asList ( leftExpression ) : expressions ; } else if ( leftExpression instanceof TupleExpression ) { List < Expression > expressions = ( ( TupleExpression ) leftExpression ) . getExpressions ( ) ; return expressions . isEmpty ( ) ? Arrays . asList ( leftExpression ) : expressions ; } else if ( leftExpression instanceof VariableExpression ) { return Arrays . asList ( leftExpression ) ; } // todo: write warning return Collections . emptyList ( ) ; } | Return the List of VariableExpression objects referenced by the specified DeclarationExpression . | 257 | 16 |
145,303 | public static boolean isFinalVariable ( DeclarationExpression declarationExpression , SourceCode sourceCode ) { if ( isFromGeneratedSourceCode ( declarationExpression ) ) { return false ; } List < Expression > variableExpressions = getVariableExpressions ( declarationExpression ) ; if ( ! variableExpressions . isEmpty ( ) ) { Expression variableExpression = variableExpressions . get ( 0 ) ; int startOfDeclaration = declarationExpression . getColumnNumber ( ) ; int startOfVariableName = variableExpression . getColumnNumber ( ) ; int sourceLineNumber = findFirstNonAnnotationLine ( declarationExpression , sourceCode ) ; String sourceLine = sourceCode . getLines ( ) . get ( sourceLineNumber - 1 ) ; String modifiers = ( startOfDeclaration >= 0 && startOfVariableName >= 0 && sourceLine . length ( ) >= startOfVariableName ) ? sourceLine . substring ( startOfDeclaration - 1 , startOfVariableName - 1 ) : "" ; return modifiers . contains ( "final" ) ; } return false ; } | Return true if the DeclarationExpression represents a final variable declaration . | 227 | 13 |
145,304 | public static boolean isTrue ( Expression expression ) { if ( expression == null ) { return false ; } if ( expression instanceof PropertyExpression && classNodeImplementsType ( ( ( PropertyExpression ) expression ) . getObjectExpression ( ) . getType ( ) , Boolean . class ) ) { if ( ( ( PropertyExpression ) expression ) . getProperty ( ) instanceof ConstantExpression && "TRUE" . equals ( ( ( ConstantExpression ) ( ( PropertyExpression ) expression ) . getProperty ( ) ) . getValue ( ) ) ) { return true ; } } return ( ( expression instanceof ConstantExpression ) && ( ( ConstantExpression ) expression ) . isTrueExpression ( ) ) || "Boolean.TRUE" . equals ( expression . getText ( ) ) ; } | Tells you if the expression is true which can be true or Boolean . TRUE . | 172 | 17 |
145,305 | public static boolean isFalse ( Expression expression ) { if ( expression == null ) { return false ; } if ( expression instanceof PropertyExpression && classNodeImplementsType ( ( ( PropertyExpression ) expression ) . getObjectExpression ( ) . getType ( ) , Boolean . class ) ) { if ( ( ( PropertyExpression ) expression ) . getProperty ( ) instanceof ConstantExpression && "FALSE" . equals ( ( ( ConstantExpression ) ( ( PropertyExpression ) expression ) . getProperty ( ) ) . getValue ( ) ) ) { return true ; } } return ( ( expression instanceof ConstantExpression ) && ( ( ConstantExpression ) expression ) . isFalseExpression ( ) ) || "Boolean.FALSE" . equals ( expression . getText ( ) ) ; } | Tells you if the expression is the false expression either literal or constant . | 172 | 15 |
145,306 | public static boolean respondsTo ( Object object , String methodName ) { MetaClass metaClass = DefaultGroovyMethods . getMetaClass ( object ) ; if ( ! metaClass . respondsTo ( object , methodName ) . isEmpty ( ) ) { return true ; } Map properties = DefaultGroovyMethods . getProperties ( object ) ; return properties . containsKey ( methodName ) ; } | Return true only if the specified object responds to the named method | 82 | 12 |
145,307 | public static boolean classNodeImplementsType ( ClassNode node , Class target ) { ClassNode targetNode = ClassHelper . make ( target ) ; if ( node . implementsInterface ( targetNode ) ) { return true ; } if ( node . isDerivedFrom ( targetNode ) ) { return true ; } if ( node . getName ( ) . equals ( target . getName ( ) ) ) { return true ; } if ( node . getName ( ) . equals ( target . getSimpleName ( ) ) ) { return true ; } if ( node . getSuperClass ( ) != null && node . getSuperClass ( ) . getName ( ) . equals ( target . getName ( ) ) ) { return true ; } if ( node . getSuperClass ( ) != null && node . getSuperClass ( ) . getName ( ) . equals ( target . getSimpleName ( ) ) ) { return true ; } if ( node . getInterfaces ( ) != null ) { for ( ClassNode declaredInterface : node . getInterfaces ( ) ) { if ( classNodeImplementsType ( declaredInterface , target ) ) { return true ; } } } return false ; } | This method tells you if a ClassNode implements or extends a certain class . | 250 | 15 |
145,308 | public static boolean isClosureDeclaration ( ASTNode expression ) { if ( expression instanceof DeclarationExpression ) { if ( ( ( DeclarationExpression ) expression ) . getRightExpression ( ) instanceof ClosureExpression ) { return true ; } } if ( expression instanceof FieldNode ) { ClassNode type = ( ( FieldNode ) expression ) . getType ( ) ; if ( AstUtil . classNodeImplementsType ( type , Closure . class ) ) { return true ; } else if ( ( ( FieldNode ) expression ) . getInitialValueExpression ( ) instanceof ClosureExpression ) { return true ; } } return false ; } | Returns true if the ASTNode is a declaration of a closure either as a declaration or a field . | 140 | 20 |
145,309 | public static List < String > getParameterNames ( MethodNode node ) { ArrayList < String > result = new ArrayList < String > ( ) ; if ( node . getParameters ( ) != null ) { for ( Parameter parameter : node . getParameters ( ) ) { result . add ( parameter . getName ( ) ) ; } } return result ; } | Gets the parameter names of a method node . | 75 | 10 |
145,310 | public static List < String > getArgumentNames ( MethodCallExpression methodCall ) { ArrayList < String > result = new ArrayList < String > ( ) ; Expression arguments = methodCall . getArguments ( ) ; List < Expression > argExpressions = null ; if ( arguments instanceof ArrayExpression ) { argExpressions = ( ( ArrayExpression ) arguments ) . getExpressions ( ) ; } else if ( arguments instanceof ListExpression ) { argExpressions = ( ( ListExpression ) arguments ) . getExpressions ( ) ; } else if ( arguments instanceof TupleExpression ) { argExpressions = ( ( TupleExpression ) arguments ) . getExpressions ( ) ; } else { LOG . warn ( "getArgumentNames arguments is not an expected type" ) ; } if ( argExpressions != null ) { for ( Expression exp : argExpressions ) { if ( exp instanceof VariableExpression ) { result . add ( ( ( VariableExpression ) exp ) . getName ( ) ) ; } } } return result ; } | Gets the argument names of a method call . If the arguments are not VariableExpressions then a null will be returned . | 227 | 25 |
145,311 | public static boolean isSafe ( Expression expression ) { if ( expression instanceof MethodCallExpression ) { return ( ( MethodCallExpression ) expression ) . isSafe ( ) ; } if ( expression instanceof PropertyExpression ) { return ( ( PropertyExpression ) expression ) . isSafe ( ) ; } return false ; } | Tells you if the expression is a null safe dereference . | 68 | 13 |
145,312 | public static boolean isSpreadSafe ( Expression expression ) { if ( expression instanceof MethodCallExpression ) { return ( ( MethodCallExpression ) expression ) . isSpreadSafe ( ) ; } if ( expression instanceof PropertyExpression ) { return ( ( PropertyExpression ) expression ) . isSpreadSafe ( ) ; } return false ; } | Tells you if the expression is a spread operator call | 71 | 11 |
145,313 | public static boolean isMethodNode ( ASTNode node , String methodNamePattern , Integer numArguments , Class returnType ) { if ( ! ( node instanceof MethodNode ) ) { return false ; } if ( ! ( ( ( MethodNode ) node ) . getName ( ) . matches ( methodNamePattern ) ) ) { return false ; } if ( numArguments != null && ( ( MethodNode ) node ) . getParameters ( ) != null && ( ( MethodNode ) node ) . getParameters ( ) . length != numArguments ) { return false ; } if ( returnType != null && ! AstUtil . classNodeImplementsType ( ( ( MethodNode ) node ) . getReturnType ( ) , returnType ) ) { return false ; } return true ; } | Tells you if the ASTNode is a method node for the given name arity and return type . | 165 | 21 |
145,314 | public static boolean isVariable ( ASTNode expression , String pattern ) { return ( expression instanceof VariableExpression && ( ( VariableExpression ) expression ) . getName ( ) . matches ( pattern ) ) ; } | Tells you if the given ASTNode is a VariableExpression with the given name . | 44 | 18 |
145,315 | private static Class getClassForClassNode ( ClassNode type ) { // todo hamlet - move to a different "InferenceUtil" object Class primitiveType = getPrimitiveType ( type ) ; if ( primitiveType != null ) { return primitiveType ; } else if ( classNodeImplementsType ( type , String . class ) ) { return String . class ; } else if ( classNodeImplementsType ( type , ReentrantLock . class ) ) { return ReentrantLock . class ; } else if ( type . getName ( ) != null && type . getName ( ) . endsWith ( "[]" ) ) { return Object [ ] . class ; // better type inference could be done, but oh well } return null ; } | This is private . It is a helper function for the utils . | 160 | 14 |
145,316 | public static int findFirstNonAnnotationLine ( ASTNode node , SourceCode sourceCode ) { if ( node instanceof AnnotatedNode && ! ( ( AnnotatedNode ) node ) . getAnnotations ( ) . isEmpty ( ) ) { // HACK: Groovy line numbers are broken when annotations have a parameter :( // so we must look at the lineNumber, not the lastLineNumber AnnotationNode lastAnnotation = null ; for ( AnnotationNode annotation : ( ( AnnotatedNode ) node ) . getAnnotations ( ) ) { if ( lastAnnotation == null ) lastAnnotation = annotation ; else if ( lastAnnotation . getLineNumber ( ) < annotation . getLineNumber ( ) ) lastAnnotation = annotation ; } String rawLine = getRawLine ( sourceCode , lastAnnotation . getLastLineNumber ( ) - 1 ) ; if ( rawLine == null ) { return node . getLineNumber ( ) ; } // is the annotation the last thing on the line? if ( rawLine . length ( ) > lastAnnotation . getLastColumnNumber ( ) ) { // no it is not return lastAnnotation . getLastLineNumber ( ) ; } // yes it is the last thing, return the next thing return lastAnnotation . getLastLineNumber ( ) + 1 ; } return node . getLineNumber ( ) ; } | gets the first non annotation line number of a node taking into account annotations . | 289 | 15 |
145,317 | protected boolean isFirstVisit ( Object expression ) { if ( visited . contains ( expression ) ) { return false ; } visited . add ( expression ) ; return true ; } | Return true if the AST expression has not already been visited . If it is the first visit register the expression so that the next visit will return false . | 35 | 30 |
145,318 | protected String sourceLineTrimmed ( ASTNode node ) { return sourceCode . line ( AstUtil . findFirstNonAnnotationLine ( node , sourceCode ) - 1 ) ; } | Return the trimmed source line corresponding to the specified AST node | 40 | 11 |
145,319 | protected String sourceLine ( ASTNode node ) { return sourceCode . getLines ( ) . get ( AstUtil . findFirstNonAnnotationLine ( node , sourceCode ) - 1 ) ; } | Return the raw source line corresponding to the specified AST node | 43 | 11 |
145,320 | @ Deprecated public static < T > T buildJsonResponse ( Response response , Class < T > clazz ) throws IOException , SlackApiException { if ( response . code ( ) == 200 ) { String body = response . body ( ) . string ( ) ; DETAILED_LOGGER . accept ( new HttpResponseListener . State ( SlackConfig . DEFAULT , response , body ) ) ; return GsonFactory . createSnakeCase ( ) . fromJson ( body , clazz ) ; } else { String body = response . body ( ) . string ( ) ; throw new SlackApiException ( response , body ) ; } } | use parseJsonResponse instead | 138 | 6 |
145,321 | public WebhookResponse send ( String url , Payload payload ) throws IOException { SlackHttpClient httpClient = getHttpClient ( ) ; Response httpResponse = httpClient . postJsonPostRequest ( url , payload ) ; String body = httpResponse . body ( ) . string ( ) ; httpClient . runHttpResponseListeners ( httpResponse , body ) ; return WebhookResponse . builder ( ) . code ( httpResponse . code ( ) ) . message ( httpResponse . message ( ) ) . body ( body ) . build ( ) ; } | Send a data to Incoming Webhook endpoint . | 115 | 10 |
145,322 | private void updateSession ( Session newSession ) { if ( this . currentSession == null ) { this . currentSession = newSession ; } else { synchronized ( this . currentSession ) { this . currentSession = newSession ; } } } | Overwrites the underlying WebSocket session . | 50 | 9 |
145,323 | public Class < E > getEventClass ( ) { if ( cachedClazz != null ) { return cachedClazz ; } Class < ? > clazz = this . getClass ( ) ; while ( clazz != Object . class ) { try { Type mySuperclass = clazz . getGenericSuperclass ( ) ; Type tType = ( ( ParameterizedType ) mySuperclass ) . getActualTypeArguments ( ) [ 0 ] ; cachedClazz = ( Class < E > ) Class . forName ( tType . getTypeName ( ) ) ; return cachedClazz ; } catch ( Exception e ) { } clazz = clazz . getSuperclass ( ) ; } throw new IllegalStateException ( "Failed to load event class - " + this . getClass ( ) . getCanonicalName ( ) ) ; } | Returns the Class object of the Event implementation . | 179 | 9 |
145,324 | protected final String computeId ( final ITemplateContext context , final IProcessableElementTag tag , final String name , final boolean sequence ) { String id = tag . getAttributeValue ( this . idAttributeDefinition . getAttributeName ( ) ) ; if ( ! org . thymeleaf . util . StringUtils . isEmptyOrWhitespace ( id ) ) { return ( StringUtils . hasText ( id ) ? id : null ) ; } id = FieldUtils . idFromName ( name ) ; if ( sequence ) { final Integer count = context . getIdentifierSequences ( ) . getAndIncrementIDSeq ( id ) ; return id + count . toString ( ) ; } return id ; } | This method is designed to be called from the diverse subclasses | 154 | 12 |
145,325 | public String code ( final String code ) { if ( this . theme == null ) { throw new TemplateProcessingException ( "Theme cannot be resolved because RequestContext was not found. " + "Are you using a Context object without a RequestContext variable?" ) ; } return this . theme . getMessageSource ( ) . getMessage ( code , null , "" , this . locale ) ; } | Looks up and returns the value of the given key in the properties file of the currently - selected theme . | 81 | 21 |
145,326 | private static DirectoryGrouping resolveDirectoryGrouping ( final ModelNode model , final ExpressionResolver expressionResolver ) { try { return DirectoryGrouping . forName ( HostResourceDefinition . DIRECTORY_GROUPING . resolveModelAttribute ( expressionResolver , model ) . asString ( ) ) ; } catch ( OperationFailedException e ) { throw new IllegalStateException ( e ) ; } } | Returns the value of found in the model . | 82 | 9 |
145,327 | private String addPathProperty ( final List < String > command , final String typeName , final String propertyName , final Map < String , String > properties , final DirectoryGrouping directoryGrouping , final File typeDir , File serverDir ) { final String result ; final String value = properties . get ( propertyName ) ; if ( value == null ) { switch ( directoryGrouping ) { case BY_TYPE : result = getAbsolutePath ( typeDir , "servers" , serverName ) ; break ; case BY_SERVER : default : result = getAbsolutePath ( serverDir , typeName ) ; break ; } properties . put ( propertyName , result ) ; } else { final File dir = new File ( value ) ; switch ( directoryGrouping ) { case BY_TYPE : result = getAbsolutePath ( dir , "servers" , serverName ) ; break ; case BY_SERVER : default : result = getAbsolutePath ( dir , serverName ) ; break ; } } command . add ( String . format ( "-D%s=%s" , propertyName , result ) ) ; return result ; } | Adds the absolute path to command . | 239 | 7 |
145,328 | private String findLoggingProfile ( final ResourceRoot resourceRoot ) { final Manifest manifest = resourceRoot . getAttachment ( Attachments . MANIFEST ) ; if ( manifest != null ) { final String loggingProfile = manifest . getMainAttributes ( ) . getValue ( LOGGING_PROFILE ) ; if ( loggingProfile != null ) { LoggingLogger . ROOT_LOGGER . debugf ( "Logging profile '%s' found in '%s'." , loggingProfile , resourceRoot ) ; return loggingProfile ; } } return null ; } | Find the logging profile attached to any resource . | 119 | 9 |
145,329 | public static int getBytesToken ( ParsingContext ctx ) { String input = ctx . getInput ( ) . substring ( ctx . getLocation ( ) ) ; int tokenOffset = 0 ; int i = 0 ; char [ ] inputChars = input . toCharArray ( ) ; for ( ; i < input . length ( ) ; i += 1 ) { char c = inputChars [ i ] ; if ( c == ' ' ) { continue ; } if ( c != BYTES_TOKEN_CHARS [ tokenOffset ] ) { return - 1 ; } else { tokenOffset += 1 ; if ( tokenOffset == BYTES_TOKEN_CHARS . length ) { // Found the token. return i ; } } } return - 1 ; } | handle white spaces . | 165 | 4 |
145,330 | public static void addOperation ( final OperationContext context ) { RbacSanityCheckOperation added = context . getAttachment ( KEY ) ; if ( added == null ) { // TODO support managed domain if ( ! context . isNormalServer ( ) ) return ; context . addStep ( createOperation ( ) , INSTANCE , Stage . MODEL ) ; context . attach ( KEY , INSTANCE ) ; } } | Add the operation at the end of Stage MODEL if this operation has not already been registered . | 87 | 19 |
145,331 | public static ModelNode getFailureDescription ( final ModelNode result ) { if ( isSuccessfulOutcome ( result ) ) { throw ControllerClientLogger . ROOT_LOGGER . noFailureDescription ( ) ; } if ( result . hasDefined ( FAILURE_DESCRIPTION ) ) { return result . get ( FAILURE_DESCRIPTION ) ; } return new ModelNode ( ) ; } | Parses the result and returns the failure description . | 84 | 11 |
145,332 | public static ModelNode getOperationAddress ( final ModelNode op ) { return op . hasDefined ( OP_ADDR ) ? op . get ( OP_ADDR ) : new ModelNode ( ) ; } | Returns the address for the operation . | 44 | 7 |
145,333 | public static String getOperationName ( final ModelNode op ) { if ( op . hasDefined ( OP ) ) { return op . get ( OP ) . asString ( ) ; } throw ControllerClientLogger . ROOT_LOGGER . operationNameNotFound ( ) ; } | Returns the name of the operation . | 59 | 7 |
145,334 | public static ModelNode createReadResourceOperation ( final ModelNode address , final boolean recursive ) { final ModelNode op = createOperation ( READ_RESOURCE_OPERATION , address ) ; op . get ( RECURSIVE ) . set ( recursive ) ; return op ; } | Creates an operation to read a resource . | 57 | 9 |
145,335 | public ModelNode buildRequest ( ) throws OperationFormatException { ModelNode address = request . get ( Util . ADDRESS ) ; if ( prefix . isEmpty ( ) ) { address . setEmptyList ( ) ; } else { Iterator < Node > iterator = prefix . iterator ( ) ; while ( iterator . hasNext ( ) ) { OperationRequestAddress . Node node = iterator . next ( ) ; if ( node . getName ( ) != null ) { address . add ( node . getType ( ) , node . getName ( ) ) ; } else if ( iterator . hasNext ( ) ) { throw new OperationFormatException ( "The node name is not specified for type '" + node . getType ( ) + "'" ) ; } } } if ( ! request . hasDefined ( Util . OPERATION ) ) { throw new OperationFormatException ( "The operation name is missing or the format of the operation request is wrong." ) ; } return request ; } | Makes sure that the operation name and the address have been set and returns a ModelNode representing the operation request . | 206 | 23 |
145,336 | private void parseUsersAuthentication ( final XMLExtendedStreamReader reader , final ModelNode realmAddress , final List < ModelNode > list ) throws XMLStreamException { final ModelNode usersAddress = realmAddress . clone ( ) . add ( AUTHENTICATION , USERS ) ; list . add ( Util . getEmptyOperation ( ADD , usersAddress ) ) ; while ( reader . hasNext ( ) && reader . nextTag ( ) != END_ELEMENT ) { requireNamespace ( reader , namespace ) ; final Element element = Element . forName ( reader . getLocalName ( ) ) ; switch ( element ) { case USER : { parseUser ( reader , usersAddress , list ) ; break ; } default : { throw unexpectedElement ( reader ) ; } } } } | The users element defines users within the domain model it is a simple authentication for some out of the box users . | 166 | 22 |
145,337 | public Set < Action . ActionEffect > getActionEffects ( ) { switch ( getImpact ( ) ) { case CLASSLOADING : case WRITE : return WRITES ; case READ_ONLY : return READS ; default : throw new IllegalStateException ( ) ; } } | Gets the effects of this action . | 60 | 8 |
145,338 | private ModelNode addLocalHost ( final ModelNode address , final List < ModelNode > operationList , final String hostName ) { String resolvedHost = hostName != null ? hostName : defaultHostControllerName ; // All further operations should modify the newly added host so the address passed in is updated. address . add ( HOST , resolvedHost ) ; // Add a step to setup the ManagementResourceRegistrations for the root host resource final ModelNode hostAddOp = new ModelNode ( ) ; hostAddOp . get ( OP ) . set ( HostAddHandler . OPERATION_NAME ) ; hostAddOp . get ( OP_ADDR ) . set ( address ) ; operationList . add ( hostAddOp ) ; // Add a step to store the HC name ModelNode nameValue = hostName == null ? new ModelNode ( ) : new ModelNode ( hostName ) ; final ModelNode writeName = Util . getWriteAttributeOperation ( address , NAME , nameValue ) ; operationList . add ( writeName ) ; return hostAddOp ; } | Add the operation to add the local host definition . | 221 | 10 |
145,339 | public static byte [ ] hashPath ( MessageDigest messageDigest , Path path ) throws IOException { try ( InputStream in = getRecursiveContentStream ( path ) ) { return hashContent ( messageDigest , in ) ; } } | Hashes a path if the path points to a directory then hashes the contents recursively . | 51 | 19 |
145,340 | public synchronized ModelNode doCommand ( String command ) throws CommandFormatException , IOException { ModelNode request = cmdCtx . buildRequest ( command ) ; return execute ( request , isSlowCommand ( command ) ) . getResponseNode ( ) ; } | Submit a command to the server . | 52 | 7 |
145,341 | public synchronized Response doCommandFullResponse ( String command ) throws CommandFormatException , IOException { ModelNode request = cmdCtx . buildRequest ( command ) ; boolean replacedBytes = replaceFilePathsWithBytes ( request ) ; OperationResponse response = execute ( request , isSlowCommand ( command ) || replacedBytes ) ; return new Response ( command , request , response ) ; } | User - initiated commands use this method . | 78 | 8 |
145,342 | private File [ ] getFilesFromProperty ( final String name , final Properties props ) { String sep = WildFlySecurityManager . getPropertyPrivileged ( "path.separator" , null ) ; String value = props . getProperty ( name , null ) ; if ( value != null ) { final String [ ] paths = value . split ( Pattern . quote ( sep ) ) ; final int len = paths . length ; final File [ ] files = new File [ len ] ; for ( int i = 0 ; i < len ; i ++ ) { files [ i ] = new File ( paths [ i ] ) ; } return files ; } return NO_FILES ; } | Get a File path list from configuration . | 140 | 8 |
145,343 | public boolean putAtomic ( C instance , K key , V value , Map < K , V > snapshot ) { Assert . checkNotNullParam ( "key" , key ) ; final Map < K , V > newMap ; final int oldSize = snapshot . size ( ) ; if ( oldSize == 0 ) { newMap = Collections . singletonMap ( key , value ) ; } else if ( oldSize == 1 ) { final Map . Entry < K , V > entry = snapshot . entrySet ( ) . iterator ( ) . next ( ) ; final K oldKey = entry . getKey ( ) ; if ( oldKey . equals ( key ) ) { return false ; } else { newMap = new FastCopyHashMap < K , V > ( snapshot ) ; newMap . put ( key , value ) ; } } else { newMap = new FastCopyHashMap < K , V > ( snapshot ) ; newMap . put ( key , value ) ; } return updater . compareAndSet ( instance , snapshot , newMap ) ; } | Put a value if and only if the map has not changed since the given snapshot was taken . If the put fails it is the caller s responsibility to retry . | 223 | 33 |
145,344 | @ Deprecated public void parseAndSetParameter ( String value , ModelNode operation , XMLStreamReader reader ) throws XMLStreamException { //we use manual parsing here, and not #getParser().. to preserve backward compatibility. if ( value != null ) { for ( String element : value . split ( "," ) ) { parseAndAddParameterElement ( element . trim ( ) , operation , reader ) ; } } } | Parses whole value as list attribute | 87 | 8 |
145,345 | boolean lock ( final Integer permit , final long timeout , final TimeUnit unit ) { boolean result = false ; try { result = lockInterruptibly ( permit , timeout , unit ) ; } catch ( InterruptedException e ) { Thread . currentThread ( ) . interrupt ( ) ; } return result ; } | Attempts exclusive acquisition with a max wait time . | 64 | 9 |
145,346 | boolean lockShared ( final Integer permit , final long timeout , final TimeUnit unit ) { boolean result = false ; try { result = lockSharedInterruptibly ( permit , timeout , unit ) ; } catch ( InterruptedException e ) { Thread . currentThread ( ) . interrupt ( ) ; } return result ; } | Attempts shared acquisition with a max wait time . | 68 | 9 |
145,347 | void lockInterruptibly ( final Integer permit ) throws InterruptedException { if ( permit == null ) { throw new IllegalArgumentException ( ) ; } sync . acquireInterruptibly ( permit ) ; } | Acquire the exclusive lock allowing the acquisition to be interrupted . | 43 | 12 |
145,348 | void lockSharedInterruptibly ( final Integer permit ) throws InterruptedException { if ( permit == null ) { throw new IllegalArgumentException ( ) ; } sync . acquireSharedInterruptibly ( permit ) ; } | Acquire the shared lock allowing the acquisition to be interrupted . | 47 | 12 |
145,349 | boolean lockInterruptibly ( final Integer permit , final long timeout , final TimeUnit unit ) throws InterruptedException { if ( permit == null ) { throw new IllegalArgumentException ( ) ; } return sync . tryAcquireNanos ( permit , unit . toNanos ( timeout ) ) ; } | Acquire the exclusive lock with a max wait timeout to acquire . | 64 | 13 |
145,350 | boolean lockSharedInterruptibly ( final Integer permit , final long timeout , final TimeUnit unit ) throws InterruptedException { if ( permit == null ) { throw new IllegalArgumentException ( ) ; } return sync . tryAcquireSharedNanos ( permit , unit . toNanos ( timeout ) ) ; } | Acquire the shared lock with a max wait timeout to acquire . | 68 | 13 |
145,351 | CapabilityRegistry createShadowCopy ( ) { CapabilityRegistry result = new CapabilityRegistry ( forServer , this ) ; readLock . lock ( ) ; try { try { result . writeLock . lock ( ) ; copy ( this , result ) ; } finally { result . writeLock . unlock ( ) ; } } finally { readLock . unlock ( ) ; } return result ; } | Creates updateable version of capability registry that on publish pushes all changes to main registry this is used to create context local registry that only on completion commits changes to main registry | 83 | 34 |
145,352 | private void registerRequirement ( RuntimeRequirementRegistration requirement ) { assert writeLock . isHeldByCurrentThread ( ) ; CapabilityId dependentId = requirement . getDependentId ( ) ; if ( ! capabilities . containsKey ( dependentId ) ) { throw ControllerLogger . MGMT_OP_LOGGER . unknownCapabilityInContext ( dependentId . getName ( ) , dependentId . getScope ( ) . getName ( ) ) ; } Map < CapabilityId , Map < String , RuntimeRequirementRegistration > > requirementMap = requirement . isRuntimeOnly ( ) ? runtimeOnlyRequirements : requirements ; Map < String , RuntimeRequirementRegistration > dependents = requirementMap . get ( dependentId ) ; if ( dependents == null ) { dependents = new HashMap <> ( ) ; requirementMap . put ( dependentId , dependents ) ; } RuntimeRequirementRegistration existing = dependents . get ( requirement . getRequiredName ( ) ) ; if ( existing == null ) { dependents . put ( requirement . getRequiredName ( ) , requirement ) ; } else { existing . addRegistrationPoint ( requirement . getOldestRegistrationPoint ( ) ) ; } modified = true ; } | This must be called with the write lock held . | 251 | 10 |
145,353 | @ Override public void removeCapabilityRequirement ( RuntimeRequirementRegistration requirementRegistration ) { // We don't know if this got registered as an runtime-only requirement or a hard one // so clean it from both maps writeLock . lock ( ) ; try { removeRequirement ( requirementRegistration , false ) ; removeRequirement ( requirementRegistration , true ) ; } finally { writeLock . unlock ( ) ; } } | Remove a previously registered requirement for a capability . | 86 | 9 |
145,354 | void publish ( ) { assert publishedFullRegistry != null : "Cannot write directly to main registry" ; writeLock . lock ( ) ; try { if ( ! modified ) { return ; } publishedFullRegistry . writeLock . lock ( ) ; try { publishedFullRegistry . clear ( true ) ; copy ( this , publishedFullRegistry ) ; pendingRemoveCapabilities . clear ( ) ; pendingRemoveRequirements . clear ( ) ; modified = false ; } finally { publishedFullRegistry . writeLock . unlock ( ) ; } } finally { writeLock . unlock ( ) ; } } | Publish the changes to main registry | 124 | 7 |
145,355 | void rollback ( ) { if ( publishedFullRegistry == null ) { return ; } writeLock . lock ( ) ; try { publishedFullRegistry . readLock . lock ( ) ; try { clear ( true ) ; copy ( publishedFullRegistry , this ) ; modified = false ; } finally { publishedFullRegistry . readLock . unlock ( ) ; } } finally { writeLock . unlock ( ) ; } } | Discard the changes . | 89 | 5 |
145,356 | static void addOperationAddress ( final ModelNode operation , final PathAddress base , final String key , final String value ) { operation . get ( OP_ADDR ) . set ( base . append ( key , value ) . toModelNode ( ) ) ; } | Appends the key and value to the address and sets the address on the operation . | 54 | 17 |
145,357 | void bootTimeScan ( final DeploymentOperations deploymentOperations ) { // WFCORE-1579: skip the scan if deployment dir is not available if ( ! checkDeploymentDir ( this . deploymentDir ) ) { DeploymentScannerLogger . ROOT_LOGGER . bootTimeScanFailed ( deploymentDir . getAbsolutePath ( ) ) ; return ; } this . establishDeployedContentList ( this . deploymentDir , deploymentOperations ) ; deployedContentEstablished = true ; if ( acquireScanLock ( ) ) { try { scan ( true , deploymentOperations ) ; } finally { releaseScanLock ( ) ; } } } | Perform a one - off scan during boot to establish deployment tasks to execute during boot | 137 | 17 |
145,358 | void scan ( ) { if ( acquireScanLock ( ) ) { boolean scheduleRescan = false ; try { scheduleRescan = scan ( false , deploymentOperations ) ; } finally { try { if ( scheduleRescan ) { synchronized ( this ) { if ( scanEnabled ) { rescanIncompleteTask = scheduledExecutor . schedule ( scanRunnable , 200 , TimeUnit . MILLISECONDS ) ; } } } } finally { releaseScanLock ( ) ; } } } } | Perform a normal scan | 107 | 5 |
145,359 | void forcedUndeployScan ( ) { if ( acquireScanLock ( ) ) { try { ROOT_LOGGER . tracef ( "Performing a post-boot forced undeploy scan for scan directory %s" , deploymentDir . getAbsolutePath ( ) ) ; ScanContext scanContext = new ScanContext ( deploymentOperations ) ; // Add remove actions to the plan for anything we count as // deployed that we didn't find on the scan for ( Map . Entry < String , DeploymentMarker > missing : scanContext . toRemove . entrySet ( ) ) { // remove successful deployment and left will be removed if ( scanContext . registeredDeployments . containsKey ( missing . getKey ( ) ) ) { scanContext . registeredDeployments . remove ( missing . getKey ( ) ) ; } } Set < String > scannedDeployments = new HashSet < String > ( scanContext . registeredDeployments . keySet ( ) ) ; scannedDeployments . removeAll ( scanContext . persistentDeployments ) ; List < ScannerTask > scannerTasks = scanContext . scannerTasks ; for ( String toUndeploy : scannedDeployments ) { scannerTasks . add ( new UndeployTask ( toUndeploy , deploymentDir , scanContext . scanStartTime , true ) ) ; } try { executeScannerTasks ( scannerTasks , deploymentOperations , true ) ; } catch ( InterruptedException e ) { Thread . currentThread ( ) . interrupt ( ) ; } ROOT_LOGGER . tracef ( "Forced undeploy scan complete" ) ; } catch ( Exception e ) { ROOT_LOGGER . scanException ( e , deploymentDir . getAbsolutePath ( ) ) ; } finally { releaseScanLock ( ) ; } } } | Perform a post - boot scan to remove any deployments added during boot that failed to deploy properly . This method isn t private solely to allow a unit test in the same package to call it . | 375 | 39 |
145,360 | private boolean checkDeploymentDir ( File directory ) { if ( ! directory . exists ( ) ) { if ( deploymentDirAccessible ) { deploymentDirAccessible = false ; ROOT_LOGGER . directoryIsNonexistent ( deploymentDir . getAbsolutePath ( ) ) ; } } else if ( ! directory . isDirectory ( ) ) { if ( deploymentDirAccessible ) { deploymentDirAccessible = false ; ROOT_LOGGER . isNotADirectory ( deploymentDir . getAbsolutePath ( ) ) ; } } else if ( ! directory . canRead ( ) ) { if ( deploymentDirAccessible ) { deploymentDirAccessible = false ; ROOT_LOGGER . directoryIsNotReadable ( deploymentDir . getAbsolutePath ( ) ) ; } } else if ( ! directory . canWrite ( ) ) { if ( deploymentDirAccessible ) { deploymentDirAccessible = false ; ROOT_LOGGER . directoryIsNotWritable ( deploymentDir . getAbsolutePath ( ) ) ; } } else { deploymentDirAccessible = true ; } return deploymentDirAccessible ; } | Checks that given directory if readable & writable and prints a warning if the check fails . Warning is only printed once and is not repeated until the condition is fixed and broken again . | 234 | 37 |
145,361 | private static ModelNode createOperation ( final ModelNode operationToValidate ) { PathAddress pa = PathAddress . pathAddress ( operationToValidate . require ( OP_ADDR ) ) ; PathAddress validationAddress = pa . subAddress ( 0 , pa . size ( ) - 1 ) ; return Util . getEmptyOperation ( "validate-cache" , validationAddress . toModelNode ( ) ) ; } | Creates an operations that targets the valiadating handler . | 87 | 13 |
145,362 | public synchronized RegistrationPoint getOldestRegistrationPoint ( ) { return registrationPoints . size ( ) == 0 ? null : registrationPoints . values ( ) . iterator ( ) . next ( ) . get ( 0 ) ; } | Gets the registration point that been associated with the registration for the longest period . | 45 | 16 |
145,363 | public synchronized Set < RegistrationPoint > getRegistrationPoints ( ) { Set < RegistrationPoint > result = new HashSet <> ( ) ; for ( List < RegistrationPoint > registrationPoints : registrationPoints . values ( ) ) { result . addAll ( registrationPoints ) ; } return Collections . unmodifiableSet ( result ) ; } | Get all registration points associated with this registration . | 68 | 9 |
145,364 | public static boolean hasValidContentAdditionParameterDefined ( ModelNode operation ) { for ( String s : DeploymentAttributes . MANAGED_CONTENT_ATTRIBUTES . keySet ( ) ) { if ( operation . hasDefined ( s ) ) { return true ; } } return false ; } | Checks to see if a valid deployment parameter has been defined . | 66 | 13 |
145,365 | static InstalledIdentity load ( final InstalledImage image , final ProductConfig productConfig , final List < File > moduleRoots , final List < File > bundleRoots ) throws IOException { // build the identity information final String productVersion = productConfig . resolveVersion ( ) ; final String productName = productConfig . resolveName ( ) ; final Identity identity = new AbstractLazyIdentity ( ) { @ Override public String getName ( ) { return productName ; } @ Override public String getVersion ( ) { return productVersion ; } @ Override public InstalledImage getInstalledImage ( ) { return image ; } } ; final Properties properties = PatchUtils . loadProperties ( identity . getDirectoryStructure ( ) . getInstallationInfo ( ) ) ; final List < String > allPatches = PatchUtils . readRefs ( properties , Constants . ALL_PATCHES ) ; // Step 1 - gather the installed layers data final InstalledConfiguration conf = createInstalledConfig ( image ) ; // Step 2 - process the actual module and bundle roots final ProcessedLayers processedLayers = process ( conf , moduleRoots , bundleRoots ) ; final InstalledConfiguration config = processedLayers . getConf ( ) ; // Step 3 - create the actual config objects // Process layers final InstalledIdentityImpl installedIdentity = new InstalledIdentityImpl ( identity , allPatches , image ) ; for ( final LayerPathConfig layer : processedLayers . getLayers ( ) . values ( ) ) { final String name = layer . name ; installedIdentity . putLayer ( name , createPatchableTarget ( name , layer , config . getLayerMetadataDir ( name ) , image ) ) ; } // Process add-ons for ( final LayerPathConfig addOn : processedLayers . getAddOns ( ) . values ( ) ) { final String name = addOn . name ; installedIdentity . putAddOn ( name , createPatchableTarget ( name , addOn , config . getAddOnMetadataDir ( name ) , image ) ) ; } return installedIdentity ; } | Load the available layers . | 448 | 5 |
145,366 | static ProcessedLayers process ( final InstalledConfiguration conf , final List < File > moduleRoots , final List < File > bundleRoots ) throws IOException { final ProcessedLayers layers = new ProcessedLayers ( conf ) ; // Process module roots final LayerPathSetter moduleSetter = new LayerPathSetter ( ) { @ Override public boolean setPath ( final LayerPathConfig pending , final File root ) { if ( pending . modulePath == null ) { pending . modulePath = root ; return true ; } return false ; } } ; for ( final File moduleRoot : moduleRoots ) { processRoot ( moduleRoot , layers , moduleSetter ) ; } // Process bundle root final LayerPathSetter bundleSetter = new LayerPathSetter ( ) { @ Override public boolean setPath ( LayerPathConfig pending , File root ) { if ( pending . bundlePath == null ) { pending . bundlePath = root ; return true ; } return false ; } } ; for ( final File bundleRoot : bundleRoots ) { processRoot ( bundleRoot , layers , bundleSetter ) ; } // if (conf.getInstalledLayers().size() != layers.getLayers().size()) { // throw processingError("processed layers don't match expected %s, but was %s", conf.getInstalledLayers(), layers.getLayers().keySet()); // } // if (conf.getInstalledAddOns().size() != layers.getAddOns().size()) { // throw processingError("processed add-ons don't match expected %s, but was %s", conf.getInstalledAddOns(), layers.getAddOns().keySet()); // } return layers ; } | Process the module and bundle roots and cross check with the installed information . | 369 | 14 |
145,367 | static void processRoot ( final File root , final ProcessedLayers layers , final LayerPathSetter setter ) throws IOException { final LayersConfig layersConfig = LayersConfig . getLayersConfig ( root ) ; // Process layers final File layersDir = new File ( root , layersConfig . getLayersPath ( ) ) ; if ( ! layersDir . exists ( ) ) { if ( layersConfig . isConfigured ( ) ) { // Bad config from user throw PatchLogger . ROOT_LOGGER . installationNoLayersConfigFound ( layersDir . getAbsolutePath ( ) ) ; } // else this isn't a root that has layers and add-ons } else { // check for a valid layer configuration for ( final String layer : layersConfig . getLayers ( ) ) { File layerDir = new File ( layersDir , layer ) ; if ( ! layerDir . exists ( ) ) { if ( layersConfig . isConfigured ( ) ) { // Bad config from user throw PatchLogger . ROOT_LOGGER . installationMissingLayer ( layer , layersDir . getAbsolutePath ( ) ) ; } // else this isn't a standard layers and add-ons structure return ; } layers . addLayer ( layer , layerDir , setter ) ; } } // Finally process the add-ons final File addOnsDir = new File ( root , layersConfig . getAddOnsPath ( ) ) ; final File [ ] addOnsList = addOnsDir . listFiles ( ) ; if ( addOnsList != null ) { for ( final File addOn : addOnsList ) { layers . addAddOn ( addOn . getName ( ) , addOn , setter ) ; } } } | Process a module or bundle root . | 368 | 7 |
145,368 | static AbstractLazyPatchableTarget createPatchableTarget ( final String name , final LayerPathConfig layer , final File metadata , final InstalledImage image ) throws IOException { // patchable target return new AbstractLazyPatchableTarget ( ) { @ Override public InstalledImage getInstalledImage ( ) { return image ; } @ Override public File getModuleRoot ( ) { return layer . modulePath ; } @ Override public File getBundleRepositoryRoot ( ) { return layer . bundlePath ; } public File getPatchesMetadata ( ) { return metadata ; } @ Override public String getName ( ) { return name ; } } ; } | Create the actual patchable target . | 139 | 7 |
145,369 | public List < ModelNode > getAllowedValues ( ) { if ( allowedValues == null ) { return Collections . emptyList ( ) ; } return Arrays . asList ( this . allowedValues ) ; } | returns array with all allowed values | 44 | 7 |
145,370 | protected void addAllowedValuesToDescription ( ModelNode result , ParameterValidator validator ) { if ( allowedValues != null ) { for ( ModelNode allowedValue : allowedValues ) { result . get ( ModelDescriptionConstants . ALLOWED ) . add ( allowedValue ) ; } } else if ( validator instanceof AllowedValuesValidator ) { AllowedValuesValidator avv = ( AllowedValuesValidator ) validator ; List < ModelNode > allowed = avv . getAllowedValues ( ) ; if ( allowed != null ) { for ( ModelNode ok : allowed ) { result . get ( ModelDescriptionConstants . ALLOWED ) . add ( ok ) ; } } } } | Adds the allowed values . Override for attributes who should not use the allowed values . | 150 | 17 |
145,371 | public static ModelNode validateRequest ( CommandContext ctx , ModelNode request ) throws CommandFormatException { final Set < String > keys = request . keys ( ) ; if ( keys . size ( ) == 2 ) { // no props return null ; } ModelNode outcome = ( ModelNode ) ctx . get ( Scope . REQUEST , DESCRIPTION_RESPONSE ) ; if ( outcome == null ) { outcome = retrieveDescription ( ctx , request , true ) ; if ( outcome == null ) { return null ; } else { ctx . set ( Scope . REQUEST , DESCRIPTION_RESPONSE , outcome ) ; } } if ( ! outcome . has ( Util . RESULT ) ) { throw new CommandFormatException ( "Failed to perform " + Util . READ_OPERATION_DESCRIPTION + " to validate the request: result is not available." ) ; } final String operationName = request . get ( Util . OPERATION ) . asString ( ) ; final ModelNode result = outcome . get ( Util . RESULT ) ; final Set < String > definedProps = result . hasDefined ( Util . REQUEST_PROPERTIES ) ? result . get ( Util . REQUEST_PROPERTIES ) . keys ( ) : Collections . emptySet ( ) ; if ( definedProps . isEmpty ( ) ) { if ( ! ( keys . size ( ) == 3 && keys . contains ( Util . OPERATION_HEADERS ) ) ) { throw new CommandFormatException ( "Operation '" + operationName + "' does not expect any property." ) ; } } else { int skipped = 0 ; for ( String prop : keys ) { if ( skipped < 2 && ( prop . equals ( Util . ADDRESS ) || prop . equals ( Util . OPERATION ) ) ) { ++ skipped ; continue ; } if ( ! definedProps . contains ( prop ) ) { if ( ! Util . OPERATION_HEADERS . equals ( prop ) ) { throw new CommandFormatException ( "'" + prop + "' is not found among the supported properties: " + definedProps ) ; } } } } return outcome ; } | return null if the operation has no params to validate | 463 | 10 |
145,372 | public static boolean reconnectContext ( RedirectException re , CommandContext ctx ) { boolean reconnected = false ; try { ConnectionInfo info = ctx . getConnectionInfo ( ) ; ControllerAddress address = null ; if ( info != null ) { address = info . getControllerAddress ( ) ; } if ( address != null && isHttpsRedirect ( re , address . getProtocol ( ) ) ) { LOG . debug ( "Trying to reconnect an http to http upgrade" ) ; try { ctx . connectController ( ) ; reconnected = true ; } catch ( Exception ex ) { LOG . warn ( "Exception reconnecting" , ex ) ; // Proper https redirect but error. // Ignoring it. } } } catch ( URISyntaxException ex ) { LOG . warn ( "Invalid URI: " , ex ) ; // OK, invalid redirect. } return reconnected ; } | Reconnect the context if the RedirectException is valid . | 189 | 13 |
145,373 | public static String compactToString ( ModelNode node ) { Objects . requireNonNull ( node ) ; final StringWriter stringWriter = new StringWriter ( ) ; final PrintWriter writer = new PrintWriter ( stringWriter , true ) ; node . writeString ( writer , true ) ; return stringWriter . toString ( ) ; } | Build a compact representation of the ModelNode . | 68 | 9 |
145,374 | private void init ( ) { validatePreSignedUrls ( ) ; try { conn = new AWSAuthConnection ( access_key , secret_access_key ) ; // Determine the bucket name if prefix is set or if pre-signed URLs are being used if ( prefix != null && prefix . length ( ) > 0 ) { ListAllMyBucketsResponse bucket_list = conn . listAllMyBuckets ( null ) ; List buckets = bucket_list . entries ; if ( buckets != null ) { boolean found = false ; for ( Object tmp : buckets ) { if ( tmp instanceof Bucket ) { Bucket bucket = ( Bucket ) tmp ; if ( bucket . name . startsWith ( prefix ) ) { location = bucket . name ; found = true ; } } } if ( ! found ) { location = prefix + "-" + java . util . UUID . randomUUID ( ) . toString ( ) ; } } } if ( usingPreSignedUrls ( ) ) { PreSignedUrlParser parsedPut = new PreSignedUrlParser ( pre_signed_put_url ) ; location = parsedPut . getBucket ( ) ; } if ( ! conn . checkBucketExists ( location ) ) { conn . createBucket ( location , AWSAuthConnection . LOCATION_DEFAULT , null ) . connection . getResponseMessage ( ) ; } } catch ( Exception e ) { throw HostControllerLogger . ROOT_LOGGER . cannotAccessS3Bucket ( location , e . getLocalizedMessage ( ) ) ; } } | Do the set - up that s needed to access Amazon S3 . | 332 | 14 |
145,375 | private List < DomainControllerData > readFromFile ( String directoryName ) { List < DomainControllerData > data = new ArrayList < DomainControllerData > ( ) ; if ( directoryName == null ) { return data ; } if ( conn == null ) { init ( ) ; } try { if ( usingPreSignedUrls ( ) ) { PreSignedUrlParser parsedPut = new PreSignedUrlParser ( pre_signed_put_url ) ; directoryName = parsedPut . getPrefix ( ) ; } String key = S3Util . sanitize ( directoryName ) + "/" + S3Util . sanitize ( DC_FILE_NAME ) ; GetResponse val = conn . get ( location , key , null ) ; if ( val . object != null ) { byte [ ] buf = val . object . data ; if ( buf != null && buf . length > 0 ) { try { data = S3Util . domainControllerDataFromByteBuffer ( buf ) ; } catch ( Exception e ) { throw HostControllerLogger . ROOT_LOGGER . failedMarshallingDomainControllerData ( ) ; } } } return data ; } catch ( IOException e ) { throw HostControllerLogger . ROOT_LOGGER . cannotAccessS3File ( e . getLocalizedMessage ( ) ) ; } } | Read the domain controller data from an S3 file . | 284 | 11 |
145,376 | private void writeToFile ( List < DomainControllerData > data , String domainName ) throws IOException { if ( domainName == null || data == null ) { return ; } if ( conn == null ) { init ( ) ; } try { String key = S3Util . sanitize ( domainName ) + "/" + S3Util . sanitize ( DC_FILE_NAME ) ; byte [ ] buf = S3Util . domainControllerDataToByteBuffer ( data ) ; S3Object val = new S3Object ( buf , null ) ; if ( usingPreSignedUrls ( ) ) { Map headers = new TreeMap ( ) ; headers . put ( "x-amz-acl" , Arrays . asList ( "public-read" ) ) ; conn . put ( pre_signed_put_url , val , headers ) . connection . getResponseMessage ( ) ; } else { Map headers = new TreeMap ( ) ; headers . put ( "Content-Type" , Arrays . asList ( "text/plain" ) ) ; conn . put ( location , key , val , headers ) . connection . getResponseMessage ( ) ; } } catch ( Exception e ) { throw HostControllerLogger . ROOT_LOGGER . cannotWriteToS3File ( e . getLocalizedMessage ( ) ) ; } } | Write the domain controller data to an S3 file . | 290 | 11 |
145,377 | private void remove ( String directoryName ) { if ( ( directoryName == null ) || ( conn == null ) ) return ; String key = S3Util . sanitize ( directoryName ) + "/" + S3Util . sanitize ( DC_FILE_NAME ) ; try { Map headers = new TreeMap ( ) ; headers . put ( "Content-Type" , Arrays . asList ( "text/plain" ) ) ; if ( usingPreSignedUrls ( ) ) { conn . delete ( pre_signed_delete_url ) . connection . getResponseMessage ( ) ; } else { conn . delete ( location , key , headers ) . connection . getResponseMessage ( ) ; } } catch ( Exception e ) { ROOT_LOGGER . cannotRemoveS3File ( e ) ; } } | Remove the S3 file that contains the domain controller data . | 176 | 12 |
145,378 | public void mergeSubtree ( final OperationTransformerRegistry targetRegistry , final Map < PathAddress , ModelVersion > subTree ) { for ( Map . Entry < PathAddress , ModelVersion > entry : subTree . entrySet ( ) ) { mergeSubtree ( targetRegistry , entry . getKey ( ) , entry . getValue ( ) ) ; } } | Merge a subtree . | 77 | 6 |
145,379 | private static boolean isDisabledHandler ( final LogContext logContext , final String handlerName ) { final Map < String , String > disableHandlers = logContext . getAttachment ( CommonAttributes . ROOT_LOGGER_NAME , DISABLED_HANDLERS_KEY ) ; return disableHandlers != null && disableHandlers . containsKey ( handlerName ) ; } | Checks to see if a handler is disabled | 80 | 9 |
145,380 | static PathAddress toPathAddress ( String domain , ImmutableManagementResourceRegistration registry , ObjectName name ) { if ( ! name . getDomain ( ) . equals ( domain ) ) { return PathAddress . EMPTY_ADDRESS ; } if ( name . equals ( ModelControllerMBeanHelper . createRootObjectName ( domain ) ) ) { return PathAddress . EMPTY_ADDRESS ; } final Hashtable < String , String > properties = name . getKeyPropertyList ( ) ; return searchPathAddress ( PathAddress . EMPTY_ADDRESS , registry , properties ) ; } | Straight conversion from an ObjectName to a PathAddress . | 125 | 12 |
145,381 | private void stopDone ( ) { synchronized ( stopLock ) { final StopContext stopContext = this . stopContext ; this . stopContext = null ; if ( stopContext != null ) { stopContext . complete ( ) ; } stopLock . notifyAll ( ) ; } } | Callback from the worker when it terminates | 57 | 8 |
145,382 | public String getRejectionLogMessageId ( ) { String id = logMessageId ; if ( id == null ) { id = getRejectionLogMessage ( Collections . < String , ModelNode > emptyMap ( ) ) ; } logMessageId = id ; return logMessageId ; } | Returns the log message id used by this checker . This is used to group it so that all attributes failing a type of rejction end up in the same error message . This default implementation uses the formatted log message with an empty attribute map as the id . | 60 | 53 |
145,383 | @ Override public synchronized void stop ( final StopContext context ) { final boolean shutdownServers = runningModeControl . getRestartMode ( ) == RestartMode . SERVERS ; if ( shutdownServers ) { Runnable task = new Runnable ( ) { @ Override public void run ( ) { try { serverInventory . shutdown ( true , - 1 , true ) ; // TODO graceful shutdown serverInventory = null ; // client.getValue().setServerInventory(null); } finally { serverCallback . getValue ( ) . setCallbackHandler ( null ) ; context . complete ( ) ; } } } ; try { executorService . getValue ( ) . execute ( task ) ; } catch ( RejectedExecutionException e ) { task . run ( ) ; } finally { context . asynchronous ( ) ; } } else { // We have to set the shutdown flag in any case serverInventory . shutdown ( false , - 1 , true ) ; serverInventory = null ; } } | Stops all servers . | 213 | 5 |
145,384 | public boolean isResourceExcluded ( final PathAddress address ) { if ( ! localHostControllerInfo . isMasterDomainController ( ) && address . size ( ) > 0 ) { IgnoredDomainResourceRoot root = this . rootResource ; PathElement firstElement = address . getElement ( 0 ) ; IgnoreDomainResourceTypeResource typeResource = root == null ? null : root . getChildInternal ( firstElement . getKey ( ) ) ; if ( typeResource != null ) { if ( typeResource . hasName ( firstElement . getValue ( ) ) ) { return true ; } } } return false ; } | Returns whether this host should ignore operations from the master domain controller that target the given address . | 127 | 18 |
145,385 | VersionExcludeData getVersionIgnoreData ( int major , int minor , int micro ) { VersionExcludeData result = registry . get ( new VersionKey ( major , minor , micro ) ) ; if ( result == null ) { result = registry . get ( new VersionKey ( major , minor , null ) ) ; } return result ; } | Gets the host - ignore data for a slave host running the given version . | 72 | 16 |
145,386 | public static void copyRecursively ( final Path source , final Path target , boolean overwrite ) throws IOException { final CopyOption [ ] options ; if ( overwrite ) { options = new CopyOption [ ] { StandardCopyOption . COPY_ATTRIBUTES , StandardCopyOption . REPLACE_EXISTING } ; } else { options = new CopyOption [ ] { StandardCopyOption . COPY_ATTRIBUTES } ; } Files . walkFileTree ( source , new FileVisitor < Path > ( ) { @ Override public FileVisitResult preVisitDirectory ( Path dir , BasicFileAttributes attrs ) throws IOException { Files . copy ( dir , target . resolve ( source . relativize ( dir ) ) , options ) ; return FileVisitResult . CONTINUE ; } @ Override public FileVisitResult visitFile ( Path file , BasicFileAttributes attrs ) throws IOException { Files . copy ( file , target . resolve ( source . relativize ( file ) ) , options ) ; return FileVisitResult . CONTINUE ; } @ Override public FileVisitResult visitFileFailed ( Path file , IOException exc ) throws IOException { DeploymentRepositoryLogger . ROOT_LOGGER . cannotCopyFile ( exc , file ) ; return FileVisitResult . CONTINUE ; } @ Override public FileVisitResult postVisitDirectory ( Path dir , IOException exc ) throws IOException { return FileVisitResult . CONTINUE ; } } ) ; } | Copy a path recursively . | 312 | 7 |
145,387 | public static void deleteSilentlyRecursively ( final Path path ) { if ( path != null ) { try { deleteRecursively ( path ) ; } catch ( IOException ioex ) { DeploymentRepositoryLogger . ROOT_LOGGER . cannotDeleteFile ( ioex , path ) ; } } } | Delete a path recursively not throwing Exception if it fails or if the path is null . | 67 | 19 |
145,388 | public static void deleteRecursively ( final Path path ) throws IOException { DeploymentRepositoryLogger . ROOT_LOGGER . debugf ( "Deleting %s recursively" , path ) ; if ( Files . exists ( path ) ) { Files . walkFileTree ( path , new FileVisitor < Path > ( ) { @ Override public FileVisitResult preVisitDirectory ( Path dir , BasicFileAttributes attrs ) throws IOException { return FileVisitResult . CONTINUE ; } @ Override public FileVisitResult visitFile ( Path file , BasicFileAttributes attrs ) throws IOException { Files . delete ( file ) ; return FileVisitResult . CONTINUE ; } @ Override public FileVisitResult visitFileFailed ( Path file , IOException exc ) throws IOException { DeploymentRepositoryLogger . ROOT_LOGGER . cannotDeleteFile ( exc , path ) ; throw exc ; } @ Override public FileVisitResult postVisitDirectory ( Path dir , IOException exc ) throws IOException { Files . delete ( dir ) ; return FileVisitResult . CONTINUE ; } } ) ; } } | Delete a path recursively . | 238 | 7 |
145,389 | public static final Path resolveSecurely ( Path rootPath , String path ) { Path resolvedPath ; if ( path == null || path . isEmpty ( ) ) { resolvedPath = rootPath . normalize ( ) ; } else { String relativePath = removeSuperflousSlashes ( path ) ; resolvedPath = rootPath . resolve ( relativePath ) . normalize ( ) ; } if ( ! resolvedPath . startsWith ( rootPath ) ) { throw DeploymentRepositoryLogger . ROOT_LOGGER . forbiddenPath ( path ) ; } return resolvedPath ; } | Resolve a path from the rootPath checking that it doesn t go out of the rootPath . | 120 | 20 |
145,390 | public static List < ContentRepositoryElement > listFiles ( final Path rootPath , Path tempDir , final ContentFilter filter ) throws IOException { List < ContentRepositoryElement > result = new ArrayList <> ( ) ; if ( Files . exists ( rootPath ) ) { if ( isArchive ( rootPath ) ) { return listZipContent ( rootPath , filter ) ; } Files . walkFileTree ( rootPath , new FileVisitor < Path > ( ) { @ Override public FileVisitResult preVisitDirectory ( Path dir , BasicFileAttributes attrs ) throws IOException { return FileVisitResult . CONTINUE ; } @ Override public FileVisitResult visitFile ( Path file , BasicFileAttributes attrs ) throws IOException { if ( filter . acceptFile ( rootPath , file ) ) { result . add ( ContentRepositoryElement . createFile ( formatPath ( rootPath . relativize ( file ) ) , Files . size ( file ) ) ) ; } return FileVisitResult . CONTINUE ; } @ Override public FileVisitResult visitFileFailed ( Path file , IOException exc ) throws IOException { return FileVisitResult . CONTINUE ; } @ Override public FileVisitResult postVisitDirectory ( Path dir , IOException exc ) throws IOException { if ( filter . acceptDirectory ( rootPath , dir ) ) { String directoryPath = formatDirectoryPath ( rootPath . relativize ( dir ) ) ; if ( ! "/" . equals ( directoryPath ) ) { result . add ( ContentRepositoryElement . createFolder ( directoryPath ) ) ; } } return FileVisitResult . CONTINUE ; } private String formatDirectoryPath ( Path path ) { return formatPath ( path ) + ' ' ; } private String formatPath ( Path path ) { return path . toString ( ) . replace ( File . separatorChar , ' ' ) ; } } ) ; } else { Path file = getFile ( rootPath ) ; if ( isArchive ( file ) ) { Path relativePath = file . relativize ( rootPath ) ; Path target = createTempDirectory ( tempDir , "unarchive" ) ; unzip ( file , target ) ; return listFiles ( target . resolve ( relativePath ) , tempDir , filter ) ; } else { throw new FileNotFoundException ( rootPath . toString ( ) ) ; } } return result ; } | List files in a path according to the specified filter . | 501 | 11 |
145,391 | public static Path createTempDirectory ( Path dir , String prefix ) throws IOException { try { return Files . createTempDirectory ( dir , prefix ) ; } catch ( UnsupportedOperationException ex ) { } return Files . createTempDirectory ( dir , prefix ) ; } | Create a temporary directory with the same attributes as its parent directory . | 55 | 13 |
145,392 | public static void unzip ( Path zip , Path target ) throws IOException { try ( final ZipFile zipFile = new ZipFile ( zip . toFile ( ) ) ) { unzip ( zipFile , target ) ; } } | Unzip a file to a target directory . | 48 | 9 |
145,393 | public static ServiceController < String > addService ( final ServiceName name , final String path , boolean possiblyAbsolute , final String relativeTo , final ServiceTarget serviceTarget ) { if ( possiblyAbsolute && isAbsoluteUnixOrWindowsPath ( path ) ) { return AbsolutePathService . addService ( name , path , serviceTarget ) ; } RelativePathService service = new RelativePathService ( path ) ; ServiceBuilder < String > builder = serviceTarget . addService ( name , service ) . addDependency ( pathNameOf ( relativeTo ) , String . class , service . injectedPath ) ; ServiceController < String > svc = builder . install ( ) ; return svc ; } | Installs a path service . | 144 | 6 |
145,394 | public List < File > getInactiveHistory ( ) throws PatchingException { if ( validHistory == null ) { walk ( ) ; } final File [ ] inactiveDirs = installedIdentity . getInstalledImage ( ) . getPatchesDir ( ) . listFiles ( new FileFilter ( ) { @ Override public boolean accept ( File pathname ) { return pathname . isDirectory ( ) && ! validHistory . contains ( pathname . getName ( ) ) ; } } ) ; return inactiveDirs == null ? Collections . < File > emptyList ( ) : Arrays . asList ( inactiveDirs ) ; } | Get the inactive history directories . | 133 | 6 |
145,395 | public List < File > getInactiveOverlays ( ) throws PatchingException { if ( referencedOverlayDirectories == null ) { walk ( ) ; } List < File > inactiveDirs = null ; for ( Layer layer : installedIdentity . getLayers ( ) ) { final File overlaysDir = new File ( layer . getDirectoryStructure ( ) . getModuleRoot ( ) , Constants . OVERLAYS ) ; final File [ ] inactiveLayerDirs = overlaysDir . listFiles ( new FileFilter ( ) { @ Override public boolean accept ( File pathname ) { return pathname . isDirectory ( ) && ! referencedOverlayDirectories . contains ( pathname ) ; } } ) ; if ( inactiveLayerDirs != null && inactiveLayerDirs . length > 0 ) { if ( inactiveDirs == null ) { inactiveDirs = new ArrayList < File > ( ) ; } inactiveDirs . addAll ( Arrays . asList ( inactiveLayerDirs ) ) ; } } return inactiveDirs == null ? Collections . < File > emptyList ( ) : inactiveDirs ; } | Get the inactive overlay directories . | 239 | 6 |
145,396 | public void deleteInactiveContent ( ) throws PatchingException { List < File > dirs = getInactiveHistory ( ) ; if ( ! dirs . isEmpty ( ) ) { for ( File dir : dirs ) { deleteDir ( dir , ALL ) ; } } dirs = getInactiveOverlays ( ) ; if ( ! dirs . isEmpty ( ) ) { for ( File dir : dirs ) { deleteDir ( dir , ALL ) ; } } } | Delete inactive contents . | 102 | 4 |
145,397 | public void bootstrap ( ) throws Exception { final HostRunningModeControl runningModeControl = environment . getRunningModeControl ( ) ; final ControlledProcessState processState = new ControlledProcessState ( true ) ; shutdownHook . setControlledProcessState ( processState ) ; ServiceTarget target = serviceContainer . subTarget ( ) ; ControlledProcessStateService controlledProcessStateService = ControlledProcessStateService . addService ( target , processState ) . getValue ( ) ; RunningStateJmx . registerMBean ( controlledProcessStateService , null , runningModeControl , false ) ; final HostControllerService hcs = new HostControllerService ( environment , runningModeControl , authCode , processState ) ; target . addService ( HostControllerService . HC_SERVICE_NAME , hcs ) . install ( ) ; } | Start the host controller services . | 170 | 6 |
145,398 | private void persistDecorator ( XMLExtendedStreamWriter writer , ModelNode model ) throws XMLStreamException { if ( shouldWriteDecoratorAndElements ( model ) ) { writer . writeStartElement ( decoratorElement ) ; persistChildren ( writer , model ) ; writer . writeEndElement ( ) ; } } | persist decorator and than continue to children without touching the model | 69 | 13 |
145,399 | @ Deprecated public static PersistentResourceXMLBuilder decorator ( final String elementName ) { return new PersistentResourceXMLBuilder ( PathElement . pathElement ( elementName ) , null ) . setDecoratorGroup ( elementName ) ; } | Creates builder for passed path element | 53 | 7 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.