idx
int64
0
165k
question
stringlengths
73
4.15k
target
stringlengths
5
918
len_question
int64
21
890
len_target
int64
3
255
148,800
public static boolean reconnect ( final Jedis jedis , final int reconAttempts , final long reconnectSleepTime ) { int i = 1 ; do { try { jedis . disconnect ( ) ; try { Thread . sleep ( reconnectSleepTime ) ; } catch ( Exception e2 ) { } jedis . connect ( ) ; } catch ( JedisConnectionException jce ) { } // Ignore bad connection attempts catch ( Exception e3 ) { LOG . error ( "Unknown Exception while trying to reconnect to Redis" , e3 ) ; } } while ( ++ i <= reconAttempts && ! testJedisConnection ( jedis ) ) ; return testJedisConnection ( jedis ) ; }
Attempt to reconnect to Redis .
149
7
148,801
public static boolean isRegularQueue ( final Jedis jedis , final String key ) { return LIST . equalsIgnoreCase ( jedis . type ( key ) ) ; }
Determines if the queue identified by the given key is a regular queue .
38
16
148,802
public static boolean isDelayedQueue ( final Jedis jedis , final String key ) { return ZSET . equalsIgnoreCase ( jedis . type ( key ) ) ; }
Determines if the queue identified by the given key is a delayed queue .
40
16
148,803
public static boolean isKeyUsed ( final Jedis jedis , final String key ) { return ! NONE . equalsIgnoreCase ( jedis . type ( key ) ) ; }
Determines if the queue identified by the given key is used .
40
14
148,804
public static boolean canUseAsDelayedQueue ( final Jedis jedis , final String key ) { final String type = jedis . type ( key ) ; return ( ZSET . equalsIgnoreCase ( type ) || NONE . equalsIgnoreCase ( type ) ) ; }
Determines if the queue identified by the given key can be used as a delayed queue .
61
19
148,805
public void createNamespace ( ) { Map < String , String > namespaceAnnotations = annotationProvider . create ( session . getId ( ) , Constants . RUNNING_STATUS ) ; if ( namespaceService . exists ( session . getNamespace ( ) ) ) { //namespace exists } else if ( configuration . isNamespaceLazyCreateEnabled ( ) ) { namespaceService . create ( session . getNamespace ( ) , namespaceAnnotations ) ; } else { throw new IllegalStateException ( "Namespace [" + session . getNamespace ( ) + "] doesn't exist and lazily creation of namespaces is disabled. " + "Either use an existing one, or set `namespace.lazy.enabled` to true." ) ; } }
Creates a namespace if needed .
160
7
148,806
private static int getPort ( Service service , Annotation ... qualifiers ) { for ( Annotation q : qualifiers ) { if ( q instanceof Port ) { Port port = ( Port ) q ; if ( port . value ( ) > 0 ) { return port . value ( ) ; } } } ServicePort servicePort = findQualifiedServicePort ( service , qualifiers ) ; if ( servicePort != null ) { return servicePort . getPort ( ) ; } return 0 ; }
Find the the qualified container port of the target service Uses java annotations first or returns the container port .
99
20
148,807
private static int getContainerPort ( Service service , Annotation ... qualifiers ) { for ( Annotation q : qualifiers ) { if ( q instanceof Port ) { Port port = ( Port ) q ; if ( port . value ( ) > 0 ) { return port . value ( ) ; } } } ServicePort servicePort = findQualifiedServicePort ( service , qualifiers ) ; if ( servicePort != null ) { return servicePort . getTargetPort ( ) . getIntVal ( ) ; } return 0 ; }
Find the the qualfied container port of the target service Uses java annotations first or returns the container port .
107
22
148,808
private static String getScheme ( Service service , Annotation ... qualifiers ) { for ( Annotation q : qualifiers ) { if ( q instanceof Scheme ) { return ( ( Scheme ) q ) . value ( ) ; } } if ( service . getMetadata ( ) != null && service . getMetadata ( ) . getAnnotations ( ) != null ) { String s = service . getMetadata ( ) . getAnnotations ( ) . get ( SERVICE_SCHEME ) ; if ( s != null && s . isEmpty ( ) ) { return s ; } } return DEFAULT_SCHEME ; }
Find the scheme to use to connect to the service . Uses java annotations first and if not found uses kubernetes annotations on the service object .
132
30
148,809
private static String getPath ( Service service , Annotation ... qualifiers ) { for ( Annotation q : qualifiers ) { if ( q instanceof Scheme ) { return ( ( Scheme ) q ) . value ( ) ; } } if ( service . getMetadata ( ) != null && service . getMetadata ( ) . getAnnotations ( ) != null ) { String s = service . getMetadata ( ) . getAnnotations ( ) . get ( SERVICE_SCHEME ) ; if ( s != null && s . isEmpty ( ) ) { return s ; } } return DEFAULT_PATH ; }
Find the path to use . Uses java annotations first and if not found uses kubernetes annotations on the service object .
128
25
148,810
private static Pod getRandomPod ( KubernetesClient client , String name , String namespace ) { Endpoints endpoints = client . endpoints ( ) . inNamespace ( namespace ) . withName ( name ) . get ( ) ; List < String > pods = new ArrayList <> ( ) ; if ( endpoints != null ) { for ( EndpointSubset subset : endpoints . getSubsets ( ) ) { for ( EndpointAddress address : subset . getAddresses ( ) ) { if ( address . getTargetRef ( ) != null && POD . equals ( address . getTargetRef ( ) . getKind ( ) ) ) { String pod = address . getTargetRef ( ) . getName ( ) ; if ( pod != null && ! pod . isEmpty ( ) ) { pods . add ( pod ) ; } } } } } if ( pods . isEmpty ( ) ) { return null ; } else { String chosen = pods . get ( RANDOM . nextInt ( pods . size ( ) ) ) ; return client . pods ( ) . inNamespace ( namespace ) . withName ( chosen ) . get ( ) ; } }
Get a random pod that provides the specified service in the specified namespace .
244
14
148,811
public static URL classFileUrl ( Class < ? > clazz ) throws IOException { ClassLoader cl = clazz . getClassLoader ( ) ; if ( cl == null ) { cl = ClassLoader . getSystemClassLoader ( ) ; } URL res = cl . getResource ( clazz . getName ( ) . replace ( ' ' , ' ' ) + ".class" ) ; if ( res == null ) { throw new IllegalArgumentException ( "Unable to locate class file for " + clazz ) ; } return res ; }
Returns the URL of the class file where the given class has been loaded from .
114
16
148,812
private static String decode ( String s ) { ByteArrayOutputStream baos = new ByteArrayOutputStream ( ) ; for ( int i = 0 ; i < s . length ( ) ; i ++ ) { char ch = s . charAt ( i ) ; if ( ch == ' ' ) { baos . write ( hexToInt ( s . charAt ( i + 1 ) ) * 16 + hexToInt ( s . charAt ( i + 2 ) ) ) ; i += 2 ; continue ; } baos . write ( ch ) ; } try { return new String ( baos . toByteArray ( ) , "UTF-8" ) ; } catch ( UnsupportedEncodingException e ) { throw new Error ( e ) ; // impossible } }
Decode %HH .
160
5
148,813
public List < ? super OpenShiftResource > processTemplateResources ( ) { List < ? extends OpenShiftResource > resources ; final List < ? super OpenShiftResource > processedResources = new ArrayList <> ( ) ; templates = OpenShiftResourceFactory . getTemplates ( getType ( ) ) ; boolean sync_instantiation = OpenShiftResourceFactory . syncInstantiation ( getType ( ) ) ; /* Instantiate templates */ for ( Template template : templates ) { resources = processTemplate ( template ) ; if ( resources != null ) { if ( sync_instantiation ) { /* synchronous template instantiation */ processedResources . addAll ( resources ) ; } else { /* asynchronous template instantiation */ try { delay ( openShiftAdapter , resources ) ; } catch ( Throwable t ) { throw new IllegalArgumentException ( asynchronousDelayErrorMessage ( ) , t ) ; } } } } return processedResources ; }
Instantiates the templates specified by
192
7
148,814
public ExecInspection execStartVerbose ( String containerId , String ... commands ) { this . readWriteLock . readLock ( ) . lock ( ) ; try { String id = execCreate ( containerId , commands ) ; CubeOutput output = execStartOutput ( id ) ; return new ExecInspection ( output , inspectExec ( id ) ) ; } finally { this . readWriteLock . readLock ( ) . unlock ( ) ; } }
EXecutes command to given container returning the inspection object as well . This method does 3 calls to dockerhost . Create Start and Inspect .
94
28
148,815
private static String createImageStreamRequest ( String name , String version , String image , boolean insecure ) { JSONObject imageStream = new JSONObject ( ) ; JSONObject metadata = new JSONObject ( ) ; JSONObject annotations = new JSONObject ( ) ; metadata . put ( "name" , name ) ; annotations . put ( "openshift.io/image.insecureRepository" , insecure ) ; metadata . put ( "annotations" , annotations ) ; // Definition of the image JSONObject from = new JSONObject ( ) ; from . put ( "kind" , "DockerImage" ) ; from . put ( "name" , image ) ; JSONObject importPolicy = new JSONObject ( ) ; importPolicy . put ( "insecure" , insecure ) ; JSONObject tag = new JSONObject ( ) ; tag . put ( "name" , version ) ; tag . put ( "from" , from ) ; tag . put ( "importPolicy" , importPolicy ) ; JSONObject tagAnnotations = new JSONObject ( ) ; tagAnnotations . put ( "version" , version ) ; tag . put ( "annotations" , tagAnnotations ) ; JSONArray tags = new JSONArray ( ) ; tags . add ( tag ) ; // Add image definition to image stream JSONObject spec = new JSONObject ( ) ; spec . put ( "tags" , tags ) ; imageStream . put ( "kind" , "ImageStream" ) ; imageStream . put ( "apiVersion" , "v1" ) ; imageStream . put ( "metadata" , metadata ) ; imageStream . put ( "spec" , spec ) ; return imageStream . toJSONString ( ) ; }
Creates image stream request and returns it in JSON formatted string .
356
13
148,816
static < T > List < Template > getTemplates ( T objectType ) { try { List < Template > templates = new ArrayList <> ( ) ; TEMP_FINDER . findAnnotations ( templates , objectType ) ; return templates ; } catch ( Exception e ) { throw new IllegalStateException ( e ) ; } }
Aggregates a list of templates specified by
71
9
148,817
static < T > boolean syncInstantiation ( T objectType ) { List < Template > templates = new ArrayList <> ( ) ; Templates tr = TEMP_FINDER . findAnnotations ( templates , objectType ) ; if ( tr == null ) { /* Default to synchronous instantiation */ return true ; } else { return tr . syncInstantiation ( ) ; } }
Returns true if templates are to be instantiated synchronously and false if asynchronously .
81
18
148,818
public void deployApplication ( String applicationName , String ... classpathLocations ) throws IOException { final List < URL > classpathElements = Arrays . stream ( classpathLocations ) . map ( classpath -> Thread . currentThread ( ) . getContextClassLoader ( ) . getResource ( classpath ) ) . collect ( Collectors . toList ( ) ) ; deployApplication ( applicationName , classpathElements . toArray ( new URL [ classpathElements . size ( ) ] ) ) ; }
Deploys application reading resources from specified classpath location
109
10
148,819
public void deployApplication ( String applicationName , URL ... urls ) throws IOException { this . applicationName = applicationName ; for ( URL url : urls ) { try ( InputStream inputStream = url . openStream ( ) ) { deploy ( inputStream ) ; } } }
Deploys application reading resources from specified URLs
59
8
148,820
public void deploy ( InputStream inputStream ) throws IOException { final List < ? extends HasMetadata > entities = deploy ( "application" , inputStream ) ; if ( this . applicationName == null ) { Optional < String > deployment = entities . stream ( ) . filter ( hm -> hm instanceof Deployment ) . map ( hm -> ( Deployment ) hm ) . map ( rc -> rc . getMetadata ( ) . getName ( ) ) . findFirst ( ) ; deployment . ifPresent ( name -> this . applicationName = name ) ; } }
Deploys application reading resources from specified InputStream
122
9
148,821
public Optional < URL > getServiceUrl ( String name ) { Service service = client . services ( ) . inNamespace ( namespace ) . withName ( name ) . get ( ) ; return service != null ? createUrlForService ( service ) : Optional . empty ( ) ; }
Gets the URL of the service with the given name that has been created during the current session .
59
20
148,822
public Optional < URL > getServiceUrl ( ) { Optional < Service > optionalService = client . services ( ) . inNamespace ( namespace ) . list ( ) . getItems ( ) . stream ( ) . findFirst ( ) ; return optionalService . map ( this :: createUrlForService ) . orElse ( Optional . empty ( ) ) ; }
Gets the URL of the first service that have been created during the current session .
74
17
148,823
public void cleanup ( ) { List < String > keys = new ArrayList <> ( created . keySet ( ) ) ; keys . sort ( String :: compareTo ) ; for ( String key : keys ) { created . remove ( key ) . stream ( ) . sorted ( Comparator . comparing ( HasMetadata :: getKind ) ) . forEach ( metadata -> { log . info ( String . format ( "Deleting %s : %s" , key , metadata . getKind ( ) ) ) ; deleteWithRetries ( metadata ) ; } ) ; } }
Removes all resources deployed using this class .
120
9
148,824
public void awaitPodReadinessOrFail ( Predicate < Pod > filter ) { await ( ) . atMost ( 5 , TimeUnit . MINUTES ) . until ( ( ) -> { List < Pod > list = client . pods ( ) . inNamespace ( namespace ) . list ( ) . getItems ( ) ; return list . stream ( ) . filter ( filter ) . filter ( Readiness :: isPodReady ) . collect ( Collectors . toList ( ) ) . size ( ) >= 1 ; } ) ; }
Awaits at most 5 minutes until all pods meets the given predicate .
111
15
148,825
private static Version getDockerVersion ( String serverUrl ) { try { DockerClient client = DockerClientBuilder . getInstance ( serverUrl ) . build ( ) ; return client . versionCmd ( ) . exec ( ) ; } catch ( Exception e ) { return null ; } }
Returns the docker version .
58
5
148,826
public void configure ( @ Observes ( precedence = - 10 ) ArquillianDescriptor arquillianDescriptor ) { Map < String , String > config = arquillianDescriptor . extension ( EXTENSION_NAME ) . getExtensionProperties ( ) ; CubeConfiguration cubeConfiguration = CubeConfiguration . fromMap ( config ) ; configurationProducer . set ( cubeConfiguration ) ; }
Add precedence - 10 because we need that ContainerRegistry is available in the Arquillian scope .
84
20
148,827
public void configure ( @ Observes ( precedence = - 200 ) ArquillianDescriptor arquillianDescriptor ) { restAssuredConfigurationInstanceProducer . set ( RestAssuredConfiguration . fromMap ( arquillianDescriptor . extension ( "restassured" ) . getExtensionProperties ( ) ) ) ; }
required for rest assured base URI configuration .
72
8
148,828
public Map < String , String > resolve ( Map < String , String > config ) { config = resolveSystemEnvironmentVariables ( config ) ; config = resolveSystemDefaultSetup ( config ) ; config = resolveDockerInsideDocker ( config ) ; config = resolveDownloadDockerMachine ( config ) ; config = resolveAutoStartDockerMachine ( config ) ; config = resolveDefaultDockerMachine ( config ) ; config = resolveServerUriByOperativeSystem ( config ) ; config = resolveServerIp ( config ) ; config = resolveTlsVerification ( config ) ; return config ; }
Resolves the configuration .
124
5
148,829
public static String fromClassPath ( ) { Set < String > versions = new HashSet <> ( ) ; try { ClassLoader classLoader = Thread . currentThread ( ) . getContextClassLoader ( ) ; Enumeration < URL > manifests = classLoader . getResources ( "META-INF/MANIFEST.MF" ) ; while ( manifests . hasMoreElements ( ) ) { URL manifestURL = manifests . nextElement ( ) ; try ( InputStream is = manifestURL . openStream ( ) ) { Manifest manifest = new Manifest ( ) ; manifest . read ( is ) ; Attributes buildInfo = manifest . getAttributes ( "Build-Info" ) ; if ( buildInfo != null ) { if ( buildInfo . getValue ( "Selenium-Version" ) != null ) { versions . add ( buildInfo . getValue ( "Selenium-Version" ) ) ; } else { // might be in build-info part if ( manifest . getEntries ( ) != null ) { if ( manifest . getEntries ( ) . containsKey ( "Build-Info" ) ) { final Attributes attributes = manifest . getEntries ( ) . get ( "Build-Info" ) ; if ( attributes . getValue ( "Selenium-Version" ) != null ) { versions . add ( attributes . getValue ( "Selenium-Version" ) ) ; } } } } } } } } catch ( Exception e ) { logger . log ( Level . WARNING , "Exception {0} occurred while resolving selenium version and latest image is going to be used." , e . getMessage ( ) ) ; return SELENIUM_VERSION ; } if ( versions . isEmpty ( ) ) { logger . log ( Level . INFO , "No version of Selenium found in classpath. Using latest image." ) ; return SELENIUM_VERSION ; } String foundVersion = versions . iterator ( ) . next ( ) ; if ( versions . size ( ) > 1 ) { logger . log ( Level . WARNING , "Multiple versions of Selenium found in classpath. Using the first one found {0}." , foundVersion ) ; } return foundVersion ; }
Returns current selenium version from JAR set in classpath .
459
14
148,830
public static URL getKubernetesConfigurationUrl ( Map < String , String > map ) throws MalformedURLException { if ( Strings . isNotNullOrEmpty ( Utils . getSystemPropertyOrEnvVar ( ENVIRONMENT_CONFIG_URL , "" ) ) ) { return new URL ( Utils . getSystemPropertyOrEnvVar ( ENVIRONMENT_CONFIG_URL , "" ) ) ; } else if ( Strings . isNotNullOrEmpty ( Utils . getSystemPropertyOrEnvVar ( ENVIRONMENT_CONFIG_RESOURCE_NAME , "" ) ) ) { String resourceName = Utils . getSystemPropertyOrEnvVar ( ENVIRONMENT_CONFIG_RESOURCE_NAME , "" ) ; return findConfigResource ( resourceName ) ; } else if ( map . containsKey ( ENVIRONMENT_CONFIG_URL ) ) { return new URL ( map . get ( ENVIRONMENT_CONFIG_URL ) ) ; } else if ( map . containsKey ( ENVIRONMENT_CONFIG_RESOURCE_NAME ) ) { String resourceName = map . get ( ENVIRONMENT_CONFIG_RESOURCE_NAME ) ; return findConfigResource ( resourceName ) ; } else { // Let the resource locator find the resource return null ; } }
Applies the kubernetes json url to the configuration .
296
13
148,831
public static URL findConfigResource ( String resourceName ) { if ( Strings . isNullOrEmpty ( resourceName ) ) { return null ; } final URL url = resourceName . startsWith ( ROOT ) ? DefaultConfiguration . class . getResource ( resourceName ) : DefaultConfiguration . class . getResource ( ROOT + resourceName ) ; if ( url != null ) { return url ; } // This is useful to get resource under META-INF directory String [ ] resourceNamePrefix = new String [ ] { "META-INF/fabric8/" , "META-INF/fabric8/" } ; for ( String resource : resourceNamePrefix ) { String fullResourceName = resource + resourceName ; URL candidate = KubernetesResourceLocator . class . getResource ( fullResourceName . startsWith ( ROOT ) ? fullResourceName : ROOT + fullResourceName ) ; if ( candidate != null ) { return candidate ; } } return null ; }
Returns the URL of a classpath resource .
211
9
148,832
public static URL asUrlOrResource ( String s ) { if ( Strings . isNullOrEmpty ( s ) ) { return null ; } try { return new URL ( s ) ; } catch ( MalformedURLException e ) { //If its not a valid URL try to treat it as a local resource. return findConfigResource ( s ) ; } }
Convert a string to a URL and fallback to classpath resource if not convertible .
77
18
148,833
@ Override public void deploy ( InputStream inputStream ) throws IOException { final List < ? extends HasMetadata > entities = deploy ( "application" , inputStream ) ; if ( this . applicationName == null ) { Optional < String > deploymentConfig = entities . stream ( ) . filter ( hm -> hm instanceof DeploymentConfig ) . map ( hm -> ( DeploymentConfig ) hm ) . map ( dc -> dc . getMetadata ( ) . getName ( ) ) . findFirst ( ) ; deploymentConfig . ifPresent ( name -> this . applicationName = name ) ; } }
Deploys application reading resources from specified InputStream .
129
10
148,834
public Optional < URL > getRoute ( String routeName ) { Route route = getClient ( ) . routes ( ) . inNamespace ( namespace ) . withName ( routeName ) . get ( ) ; return route != null ? Optional . ofNullable ( createUrlFromRoute ( route ) ) : Optional . empty ( ) ; }
Gets the URL of the route with given name .
70
11
148,835
public Optional < URL > getRoute ( ) { Optional < Route > optionalRoute = getClient ( ) . routes ( ) . inNamespace ( namespace ) . list ( ) . getItems ( ) . stream ( ) . findFirst ( ) ; return optionalRoute . map ( OpenShiftRouteLocator :: createUrlFromRoute ) ; }
Returns the URL of the first route .
70
8
148,836
public boolean projectExists ( String name ) throws IllegalArgumentException { if ( name == null || name . isEmpty ( ) ) { throw new IllegalArgumentException ( "Project name cannot be empty" ) ; } return listProjects ( ) . stream ( ) . map ( p -> p . getMetadata ( ) . getName ( ) ) . anyMatch ( Predicate . isEqual ( name ) ) ; }
Checks if the given project exists or not .
90
10
148,837
public Optional < Project > findProject ( String name ) throws IllegalArgumentException { if ( name == null || name . isEmpty ( ) ) { throw new IllegalArgumentException ( "Project name cannot be empty" ) ; } return getProject ( name ) ; }
Finds for the given project .
56
7
148,838
private static Constraint loadConstraint ( Annotation context ) { Constraint constraint = null ; final ServiceLoader < Constraint > constraints = ServiceLoader . load ( Constraint . class ) ; for ( Constraint aConstraint : constraints ) { try { aConstraint . getClass ( ) . getDeclaredMethod ( "check" , context . annotationType ( ) ) ; constraint = aConstraint ; break ; } catch ( NoSuchMethodException e ) { // Look for next implementation if method not found with required signature. } } if ( constraint == null ) { throw new IllegalStateException ( "Couldn't found any implementation of " + Constraint . class . getName ( ) ) ; } return constraint ; }
we have only one implementation on classpath .
160
9
148,839
public void createEnvironment ( @ Observes ( precedence = 10 ) BeforeClass event , OpenShiftAdapter client , CubeOpenShiftConfiguration cubeOpenShiftConfiguration ) { final TestClass testClass = event . getTestClass ( ) ; log . info ( String . format ( "Creating environment for %s" , testClass . getName ( ) ) ) ; OpenShiftResourceFactory . createResources ( testClass . getName ( ) , client , testClass . getJavaClass ( ) , cubeOpenShiftConfiguration . getProperties ( ) ) ; classTemplateProcessor = new ClassTemplateProcessor ( client , cubeOpenShiftConfiguration , testClass ) ; final List < ? extends OpenShiftResource > templateResources = classTemplateProcessor . processTemplateResources ( ) ; templateDetailsProducer . set ( ( ) -> templateResources ) ; }
Create the environment as specified by
171
6
148,840
public DockerContainerObjectBuilder < T > withContainerObjectClass ( Class < T > containerObjectClass ) { if ( containerObjectClass == null ) { throw new IllegalArgumentException ( "container object class cannot be null" ) ; } this . containerObjectClass = containerObjectClass ; //First we check if this ContainerObject is defining a @CubeDockerFile in static method final List < Method > methodsWithCubeDockerFile = ReflectionUtil . getMethodsWithAnnotation ( containerObjectClass , CubeDockerFile . class ) ; if ( methodsWithCubeDockerFile . size ( ) > 1 ) { throw new IllegalArgumentException ( String . format ( "More than one %s annotation found and only one was expected. Methods where annotation was found are: %s" , CubeDockerFile . class . getSimpleName ( ) , methodsWithCubeDockerFile ) ) ; } classHasMethodWithCubeDockerFile = ! methodsWithCubeDockerFile . isEmpty ( ) ; classDefinesCubeDockerFile = containerObjectClass . isAnnotationPresent ( CubeDockerFile . class ) ; classDefinesImage = containerObjectClass . isAnnotationPresent ( Image . class ) ; if ( classHasMethodWithCubeDockerFile ) { methodWithCubeDockerFile = methodsWithCubeDockerFile . get ( 0 ) ; boolean isMethodStatic = Modifier . isStatic ( methodWithCubeDockerFile . getModifiers ( ) ) ; boolean methodHasNoArguments = methodWithCubeDockerFile . getParameterCount ( ) == 0 ; boolean methodReturnsAnArchive = Archive . class . isAssignableFrom ( methodWithCubeDockerFile . getReturnType ( ) ) ; if ( ! isMethodStatic || ! methodHasNoArguments || ! methodReturnsAnArchive ) { throw new IllegalArgumentException ( String . format ( "Method %s annotated with %s is expected to be static, no args and return %s." , methodWithCubeDockerFile , CubeDockerFile . class . getSimpleName ( ) , Archive . class . getSimpleName ( ) ) ) ; } } // User has defined @CubeDockerfile on the class and a method if ( classHasMethodWithCubeDockerFile && classDefinesCubeDockerFile ) { throw new IllegalArgumentException ( String . format ( "More than one %s annotation found and only one was expected. Both class and method %s has the annotation." , CubeDockerFile . class . getSimpleName ( ) , methodWithCubeDockerFile ) ) ; } // User has defined @CubeDockerfile and @Image if ( ( classHasMethodWithCubeDockerFile || classDefinesCubeDockerFile ) && classDefinesImage ) { throw new IllegalArgumentException ( String . format ( "Container Object %s has defined %s annotation and %s annotation together." , containerObjectClass . getSimpleName ( ) , Image . class . getSimpleName ( ) , CubeDockerFile . class . getSimpleName ( ) ) ) ; } // User has not defined either @CubeDockerfile or @Image if ( ! classDefinesCubeDockerFile && ! classDefinesImage && ! classHasMethodWithCubeDockerFile ) { throw new IllegalArgumentException ( String . format ( "Container Object %s is not annotated with either %s or %s annotations." , containerObjectClass . getName ( ) , CubeDockerFile . class . getSimpleName ( ) , Image . class . getSimpleName ( ) ) ) ; } return this ; }
Specifies the container object class to be instantiated
761
10
148,841
public DockerContainerObjectBuilder < T > withEnrichers ( Collection < TestEnricher > enrichers ) { if ( enrichers == null ) { throw new IllegalArgumentException ( "enrichers cannot be null" ) ; } this . enrichers = enrichers ; return this ; }
Specifies the list of enrichers that will be used to enrich the container object .
66
18
148,842
public T build ( ) throws IllegalAccessException , IOException , InvocationTargetException { generatedConfigutation = new CubeContainer ( ) ; findContainerName ( ) ; // if needed, prepare prepare resources required to build a docker image prepareImageBuild ( ) ; // instantiate container object instantiateContainerObject ( ) ; // enrich container object (without cube instance) enrichContainerObjectBeforeCube ( ) ; // extract configuration from container object class extractConfigurationFromContainerObject ( ) ; // merge received configuration with extracted configuration mergeContainerObjectConfiguration ( ) ; // create/start/register associated cube initializeCube ( ) ; // enrich container object (with cube instance) enrichContainerObjectWithCube ( ) ; // return created container object return containerObjectInstance ; }
Triggers the building process builds creates and starts the docker container associated with the requested container object creates the container object and returns it
152
26
148,843
private static Path resolveDockerDefinition ( Path fullpath ) { final Path ymlPath = fullpath . resolveSibling ( fullpath . getFileName ( ) + ".yml" ) ; if ( Files . exists ( ymlPath ) ) { return ymlPath ; } else { final Path yamlPath = fullpath . resolveSibling ( fullpath . getFileName ( ) + ".yaml" ) ; if ( Files . exists ( yamlPath ) ) { return yamlPath ; } } return null ; }
Resolves current full path with . yml and . yaml extensions
112
14
148,844
public static void awaitRoute ( URL routeUrl , int timeout , TimeUnit timeoutUnit , int repetitions , int ... statusCodes ) { AtomicInteger successfulAwaitsInARow = new AtomicInteger ( 0 ) ; await ( ) . atMost ( timeout , timeoutUnit ) . until ( ( ) -> { if ( tryConnect ( routeUrl , statusCodes ) ) { successfulAwaitsInARow . incrementAndGet ( ) ; } else { successfulAwaitsInARow . set ( 0 ) ; } return successfulAwaitsInARow . get ( ) >= repetitions ; } ) ; }
Waits for the timeout duration until the url responds with correct status code
130
14
148,845
public static Constructor < ? > getConstructor ( final Class < ? > clazz , final Class < ? > ... argumentTypes ) throws NoSuchMethodException { try { return AccessController . doPrivileged ( new PrivilegedExceptionAction < Constructor < ? > > ( ) { public Constructor < ? > run ( ) throws NoSuchMethodException { return clazz . getConstructor ( argumentTypes ) ; } } ) ; } // Unwrap catch ( final PrivilegedActionException pae ) { final Throwable t = pae . getCause ( ) ; // Rethrow if ( t instanceof NoSuchMethodException ) { throw ( NoSuchMethodException ) t ; } else { // No other checked Exception thrown by Class.getConstructor try { throw ( RuntimeException ) t ; } // Just in case we've really messed up catch ( final ClassCastException cce ) { throw new RuntimeException ( "Obtained unchecked Exception; this code should never be reached" , t ) ; } } } }
Obtains the Constructor specified from the given Class and argument types
212
13
148,846
public static String getStringProperty ( String name , Map < String , String > map , String defaultValue ) { if ( map . containsKey ( name ) && Strings . isNotNullOrEmpty ( map . get ( name ) ) ) { defaultValue = map . get ( name ) ; } return getPropertyOrEnvironmentVariable ( name , defaultValue ) ; }
Gets a property from system environment or an external map . The lookup order is system > env > map > defaultValue .
76
25
148,847
public OpenShiftAssistantTemplate parameter ( String name , String value ) { parameterValues . put ( name , value ) ; return this ; }
Stores template parameters for OpenShiftAssistantTemplate .
28
10
148,848
public static Timespan create ( Timespan ... timespans ) { if ( timespans == null ) { return null ; } if ( timespans . length == 0 ) { return ZERO_MILLISECONDS ; } Timespan res = timespans [ 0 ] ; for ( int i = 1 ; i < timespans . length ; i ++ ) { Timespan timespan = timespans [ i ] ; res = res . add ( timespan ) ; } return res ; }
Creates a timespan from a list of other timespans .
107
14
148,849
public void install ( @ Observes ( precedence = 90 ) CubeDockerConfiguration configuration , ArquillianDescriptor arquillianDescriptor ) { DockerCompositions cubes = configuration . getDockerContainersContent ( ) ; final SeleniumContainers seleniumContainers = SeleniumContainers . create ( getBrowser ( arquillianDescriptor ) , cubeDroneConfigurationInstance . get ( ) ) ; cubes . add ( seleniumContainers . getSeleniumContainerName ( ) , seleniumContainers . getSeleniumContainer ( ) ) ; final boolean recording = cubeDroneConfigurationInstance . get ( ) . isRecording ( ) ; if ( recording ) { cubes . add ( seleniumContainers . getVncContainerName ( ) , seleniumContainers . getVncContainer ( ) ) ; cubes . add ( seleniumContainers . getVideoConverterContainerName ( ) , seleniumContainers . getVideoConverterContainer ( ) ) ; } seleniumContainersInstanceProducer . set ( seleniumContainers ) ; System . out . println ( "SELENIUM INSTALLED" ) ; System . out . println ( ConfigUtil . dump ( cubes ) ) ; }
ten less than Cube Q
267
5
148,850
public void startDockerMachine ( String cliPathExec , String machineName ) { commandLineExecutor . execCommand ( createDockerMachineCommand ( cliPathExec ) , "start" , machineName ) ; this . manuallyStarted = true ; }
Starts given docker machine .
55
6
148,851
public boolean isDockerMachineInstalled ( String cliPathExec ) { try { commandLineExecutor . execCommand ( createDockerMachineCommand ( cliPathExec ) ) ; return true ; } catch ( Exception e ) { return false ; } }
Checks if Docker Machine is installed by running docker - machine and inspect the result .
54
17
148,852
public void overrideCubeProperties ( DockerCompositions overrideDockerCompositions ) { final Set < String > containerIds = overrideDockerCompositions . getContainerIds ( ) ; for ( String containerId : containerIds ) { // main definition of containers contains a container that must be overrode if ( containers . containsKey ( containerId ) ) { final CubeContainer cubeContainer = containers . get ( containerId ) ; final CubeContainer overrideCubeContainer = overrideDockerCompositions . get ( containerId ) ; cubeContainer . setRemoveVolumes ( overrideCubeContainer . getRemoveVolumes ( ) ) ; cubeContainer . setAlwaysPull ( overrideCubeContainer . getAlwaysPull ( ) ) ; if ( overrideCubeContainer . hasAwait ( ) ) { cubeContainer . setAwait ( overrideCubeContainer . getAwait ( ) ) ; } if ( overrideCubeContainer . hasBeforeStop ( ) ) { cubeContainer . setBeforeStop ( overrideCubeContainer . getBeforeStop ( ) ) ; } if ( overrideCubeContainer . isManual ( ) ) { cubeContainer . setManual ( overrideCubeContainer . isManual ( ) ) ; } if ( overrideCubeContainer . isKillContainer ( ) ) { cubeContainer . setKillContainer ( overrideCubeContainer . isKillContainer ( ) ) ; } } else { logger . warning ( String . format ( "Overriding Container %s are not defined in main definition of containers." , containerId ) ) ; } } }
This method only overrides properties that are specific from Cube like await strategy or before stop events .
315
19
148,853
public static String replaceParameters ( final InputStream stream ) { String content = IOUtil . asStringPreservingNewLines ( stream ) ; return resolvePlaceholders ( content ) ; }
Method that takes an inputstream read it preserving the end lines and subtitute using commons - lang - 3 calls the variables first searching as system properties vars and then in environment var list . In case of missing the property is replaced by white space .
39
50
148,854
public static String join ( final Collection < ? > collection , final String separator ) { StringBuffer buffer = new StringBuffer ( ) ; boolean first = true ; Iterator < ? > iter = collection . iterator ( ) ; while ( iter . hasNext ( ) ) { Object next = iter . next ( ) ; if ( first ) { first = false ; } else { buffer . append ( separator ) ; } buffer . append ( next ) ; } return buffer . toString ( ) ; }
joins a collection of objects together as a String using a separator
103
14
148,855
public static List < String > splitAsList ( String text , String delimiter ) { List < String > answer = new ArrayList < String > ( ) ; if ( text != null && text . length ( ) > 0 ) { answer . addAll ( Arrays . asList ( text . split ( delimiter ) ) ) ; } return answer ; }
splits a string into a list of strings ignoring the empty string
74
13
148,856
public static List < String > splitAndTrimAsList ( String text , String sep ) { ArrayList < String > answer = new ArrayList <> ( ) ; if ( text != null && text . length ( ) > 0 ) { for ( String v : text . split ( sep ) ) { String trim = v . trim ( ) ; if ( trim . length ( ) > 0 ) { answer . add ( trim ) ; } } } return answer ; }
splits a string into a list of strings . Trims the results and ignores empty strings
97
18
148,857
public void waitForDeployments ( @ Observes ( precedence = - 100 ) AfterStart event , OpenShiftAdapter client , CEEnvironmentProcessor . TemplateDetails details , TestClass testClass , CubeOpenShiftConfiguration configuration , OpenShiftClient openshiftClient ) throws Exception { if ( testClass == null ) { // nothing to do, since we're not in ClassScoped context return ; } if ( details == null ) { log . warning ( String . format ( "No environment for %s" , testClass . getName ( ) ) ) ; return ; } log . info ( String . format ( "Waiting for environment for %s" , testClass . getName ( ) ) ) ; try { delay ( client , details . getResources ( ) ) ; } catch ( Throwable t ) { throw new IllegalArgumentException ( "Error waiting for template resources to deploy: " + testClass . getName ( ) , t ) ; } }
Wait for the template resources to come up after the test container has been started . This allows the test container and the template resources to come up in parallel .
197
31
148,858
public static boolean validate ( final String ip ) { Matcher matcher = pattern . matcher ( ip ) ; return matcher . matches ( ) ; }
Validate ipv4 address with regular expression
32
9
148,859
@ Override protected AbstractFilePickerFragment < File > getFragment ( final String startPath , final int mode , final boolean allowMultiple , final boolean allowDirCreate , final boolean allowExistingFile , final boolean singleClick ) { // startPath is allowed to be null. // In that case, default folder should be SD-card and not "/" String path = ( startPath != null ? startPath : Environment . getExternalStorageDirectory ( ) . getPath ( ) ) ; currentFragment = new BackHandlingFilePickerFragment ( ) ; currentFragment . setArgs ( path , mode , allowMultiple , allowDirCreate , allowExistingFile , singleClick ) ; return currentFragment ; }
Return a copy of the new fragment and set the variable above .
151
13
148,860
@ NonNull @ Override public File getParent ( @ NonNull final File from ) { if ( from . getPath ( ) . equals ( getRoot ( ) . getPath ( ) ) ) { // Already at root, we can't go higher return from ; } else if ( from . getParentFile ( ) != null ) { return from . getParentFile ( ) ; } else { return from ; } }
Return the path to the parent directory . Should return the root if from is root .
87
17
148,861
@ NonNull @ Override public Loader < SortedList < File > > getLoader ( ) { return new AsyncTaskLoader < SortedList < File > > ( getActivity ( ) ) { FileObserver fileObserver ; @ Override public SortedList < File > loadInBackground ( ) { File [ ] listFiles = mCurrentPath . listFiles ( ) ; final int initCap = listFiles == null ? 0 : listFiles . length ; SortedList < File > files = new SortedList <> ( File . class , new SortedListAdapterCallback < File > ( getDummyAdapter ( ) ) { @ Override public int compare ( File lhs , File rhs ) { return compareFiles ( lhs , rhs ) ; } @ Override public boolean areContentsTheSame ( File file , File file2 ) { return file . getAbsolutePath ( ) . equals ( file2 . getAbsolutePath ( ) ) && ( file . isFile ( ) == file2 . isFile ( ) ) ; } @ Override public boolean areItemsTheSame ( File file , File file2 ) { return areContentsTheSame ( file , file2 ) ; } } , initCap ) ; files . beginBatchedUpdates ( ) ; if ( listFiles != null ) { for ( java . io . File f : listFiles ) { if ( isItemVisible ( f ) ) { files . add ( f ) ; } } } files . endBatchedUpdates ( ) ; return files ; } /** * Handles a request to start the Loader. */ @ Override protected void onStartLoading ( ) { super . onStartLoading ( ) ; // handle if directory does not exist. Fall back to root. if ( mCurrentPath == null || ! mCurrentPath . isDirectory ( ) ) { mCurrentPath = getRoot ( ) ; } // Start watching for changes fileObserver = new FileObserver ( mCurrentPath . getPath ( ) , FileObserver . CREATE | FileObserver . DELETE | FileObserver . MOVED_FROM | FileObserver . MOVED_TO ) { @ Override public void onEvent ( int event , String path ) { // Reload onContentChanged ( ) ; } } ; fileObserver . startWatching ( ) ; forceLoad ( ) ; } /** * Handles a request to completely reset the Loader. */ @ Override protected void onReset ( ) { super . onReset ( ) ; // Stop watching if ( fileObserver != null ) { fileObserver . stopWatching ( ) ; fileObserver = null ; } } } ; }
Get a loader that lists the Files in the current path and monitors changes .
565
15
148,862
@ Override public void onLoadFinished ( final Loader < SortedList < T > > loader , final SortedList < T > data ) { isLoading = false ; mCheckedItems . clear ( ) ; mCheckedVisibleViewHolders . clear ( ) ; mFiles = data ; mAdapter . setList ( data ) ; if ( mCurrentDirView != null ) { mCurrentDirView . setText ( getFullPath ( mCurrentPath ) ) ; } // Stop loading now to avoid a refresh clearing the user's selections getLoaderManager ( ) . destroyLoader ( 0 ) ; }
Called when a previously created loader has finished its load .
129
12
148,863
public void clearSelections ( ) { for ( CheckableViewHolder vh : mCheckedVisibleViewHolders ) { vh . checkbox . setChecked ( false ) ; } mCheckedVisibleViewHolders . clear ( ) ; mCheckedItems . clear ( ) ; }
Animate de - selection of visible views and clear selected set .
65
13
148,864
protected boolean isMultimedia ( File file ) { //noinspection SimplifiableIfStatement if ( isDir ( file ) ) { return false ; } String path = file . getPath ( ) . toLowerCase ( ) ; for ( String ext : MULTIMEDIA_EXTENSIONS ) { if ( path . endsWith ( ext ) ) { return true ; } } return false ; }
An extremely simple method for identifying multimedia . This could be improved but it s good enough for this example .
83
21
148,865
@ NonNull @ Override public Loader < SortedList < FtpFile > > getLoader ( ) { return new AsyncTaskLoader < SortedList < FtpFile > > ( getContext ( ) ) { @ Override public SortedList < FtpFile > loadInBackground ( ) { SortedList < FtpFile > sortedList = new SortedList <> ( FtpFile . class , new SortedListAdapterCallback < FtpFile > ( getDummyAdapter ( ) ) { @ Override public int compare ( FtpFile lhs , FtpFile rhs ) { if ( lhs . isDirectory ( ) && ! rhs . isDirectory ( ) ) { return - 1 ; } else if ( rhs . isDirectory ( ) && ! lhs . isDirectory ( ) ) { return 1 ; } else { return lhs . getName ( ) . compareToIgnoreCase ( rhs . getName ( ) ) ; } } @ Override public boolean areContentsTheSame ( FtpFile oldItem , FtpFile newItem ) { return oldItem . getName ( ) . equals ( newItem . getName ( ) ) ; } @ Override public boolean areItemsTheSame ( FtpFile item1 , FtpFile item2 ) { return item1 . getName ( ) . equals ( item2 . getName ( ) ) ; } } ) ; if ( ! ftp . isConnected ( ) ) { // Connect try { ftp . connect ( server , port ) ; ftp . setFileType ( FTP . ASCII_FILE_TYPE ) ; ftp . enterLocalPassiveMode ( ) ; ftp . setUseEPSVwithIPv4 ( false ) ; if ( ! ( loggedIn = ftp . login ( username , password ) ) ) { ftp . logout ( ) ; Log . e ( TAG , "Login failed" ) ; } } catch ( IOException e ) { if ( ftp . isConnected ( ) ) { try { ftp . disconnect ( ) ; } catch ( IOException ignored ) { } } Log . e ( TAG , "Could not connect to server." ) ; } } if ( loggedIn ) { try { // handle if directory does not exist. Fall back to root. if ( mCurrentPath == null || ! mCurrentPath . isDirectory ( ) ) { mCurrentPath = getRoot ( ) ; } sortedList . beginBatchedUpdates ( ) ; for ( FTPFile f : ftp . listFiles ( mCurrentPath . getPath ( ) ) ) { FtpFile file ; if ( f . isDirectory ( ) ) { file = new FtpDir ( mCurrentPath , f . getName ( ) ) ; } else { file = new FtpFile ( mCurrentPath , f . getName ( ) ) ; } if ( isItemVisible ( file ) ) { sortedList . add ( file ) ; } } sortedList . endBatchedUpdates ( ) ; } catch ( IOException e ) { Log . e ( TAG , "IOException: " + e . getMessage ( ) ) ; } } return sortedList ; } /** * Handles a request to start the Loader. */ @ Override protected void onStartLoading ( ) { super . onStartLoading ( ) ; // handle if directory does not exist. Fall back to root. if ( mCurrentPath == null || ! mCurrentPath . isDirectory ( ) ) { mCurrentPath = getRoot ( ) ; } forceLoad ( ) ; } } ; }
Get a loader that lists the files in the current path and monitors changes .
755
15
148,866
@ JsonProperty public String timestamp ( ) { if ( timestampAsText == null ) { timestampAsText = DateTimeFormatter . ISO_INSTANT . format ( timestamp ) ; } return timestampAsText ; }
Returns a date and time string which is formatted as ISO - 8601 .
45
15
148,867
public static CentralDogma forConfig ( File configFile ) throws IOException { requireNonNull ( configFile , "configFile" ) ; return new CentralDogma ( Jackson . readValue ( configFile , CentralDogmaConfig . class ) ) ; }
Creates a new instance from the given configuration file .
53
11
148,868
public Optional < ServerPort > activePort ( ) { final Server server = this . server ; return server != null ? server . activePort ( ) : Optional . empty ( ) ; }
Returns the primary port of the server .
38
8
148,869
public Map < InetSocketAddress , ServerPort > activePorts ( ) { final Server server = this . server ; if ( server != null ) { return server . activePorts ( ) ; } else { return Collections . emptyMap ( ) ; } }
Returns the ports of the server .
54
7
148,870
public CompletableFuture < Void > stop ( ) { numPendingStopRequests . incrementAndGet ( ) ; return startStop . stop ( ) . thenRun ( numPendingStopRequests :: decrementAndGet ) ; }
Stops the server . This method does nothing if the server is stopped already .
50
16
148,871
public static void initializeInternalProject ( CommandExecutor executor ) { final long creationTimeMillis = System . currentTimeMillis ( ) ; try { executor . execute ( createProject ( creationTimeMillis , Author . SYSTEM , INTERNAL_PROJ ) ) . get ( ) ; } catch ( Throwable cause ) { cause = Exceptions . peel ( cause ) ; if ( ! ( cause instanceof ProjectExistsException ) ) { throw new Error ( "failed to initialize an internal project" , cause ) ; } } // These repositories might be created when creating an internal project, but we try to create them // again here in order to make sure them exist because sometimes their names are changed. for ( final String repo : ImmutableList . of ( Project . REPO_META , Project . REPO_DOGMA ) ) { try { executor . execute ( createRepository ( creationTimeMillis , Author . SYSTEM , INTERNAL_PROJ , repo ) ) . get ( ) ; } catch ( Throwable cause ) { cause = Exceptions . peel ( cause ) ; if ( ! ( cause instanceof RepositoryExistsException ) ) { throw new Error ( cause ) ; } } } }
Creates an internal project and repositories such as a token storage .
257
13
148,872
@ Override protected < T > CompletableFuture < T > doExecute ( Command < T > command ) throws Exception { final CompletableFuture < T > future = new CompletableFuture <> ( ) ; executor . execute ( ( ) -> { try { future . complete ( blockingExecute ( command ) ) ; } catch ( Throwable t ) { future . completeExceptionally ( t ) ; } } ) ; return future ; }
Ensure that all logs are replayed any other logs can not be added before end of this function .
95
21
148,873
public static long makeReasonable ( long expectedTimeoutMillis , long bufferMillis ) { checkArgument ( expectedTimeoutMillis > 0 , "expectedTimeoutMillis: %s (expected: > 0)" , expectedTimeoutMillis ) ; checkArgument ( bufferMillis >= 0 , "bufferMillis: %s (expected: > 0)" , bufferMillis ) ; final long timeout = Math . min ( expectedTimeoutMillis , MAX_MILLIS ) ; if ( bufferMillis == 0 ) { return timeout ; } if ( timeout > MAX_MILLIS - bufferMillis ) { return MAX_MILLIS ; } else { return bufferMillis + timeout ; } }
Returns a reasonable timeout duration for a watch request .
147
10
148,874
public CentralDogmaBuilder port ( InetSocketAddress localAddress , SessionProtocol protocol ) { return port ( new ServerPort ( localAddress , protocol ) ) ; }
Adds a port that serves the HTTP requests . If unspecified cleartext HTTP on port 36462 is used .
35
22
148,875
void close ( Supplier < CentralDogmaException > failureCauseSupplier ) { requireNonNull ( failureCauseSupplier , "failureCauseSupplier" ) ; if ( closePending . compareAndSet ( null , failureCauseSupplier ) ) { repositoryWorker . execute ( ( ) -> { rwLock . writeLock ( ) . lock ( ) ; try { if ( commitIdDatabase != null ) { try { commitIdDatabase . close ( ) ; } catch ( Exception e ) { logger . warn ( "Failed to close a commitId database:" , e ) ; } } if ( jGitRepository != null ) { try { jGitRepository . close ( ) ; } catch ( Exception e ) { logger . warn ( "Failed to close a Git repository: {}" , jGitRepository . getDirectory ( ) , e ) ; } } } finally { rwLock . writeLock ( ) . unlock ( ) ; commitWatchers . close ( failureCauseSupplier ) ; closeFuture . complete ( null ) ; } } ) ; } closeFuture . join ( ) ; }
Waits until all pending operations are complete and closes this repository .
237
13
148,876
@ Override public CompletableFuture < Map < String , Change < ? > > > diff ( Revision from , Revision to , String pathPattern ) { final ServiceRequestContext ctx = context ( ) ; return CompletableFuture . supplyAsync ( ( ) -> { requireNonNull ( from , "from" ) ; requireNonNull ( to , "to" ) ; requireNonNull ( pathPattern , "pathPattern" ) ; failFastIfTimedOut ( this , logger , ctx , "diff" , from , to , pathPattern ) ; final RevisionRange range = normalizeNow ( from , to ) . toAscending ( ) ; readLock ( ) ; try ( RevWalk rw = new RevWalk ( jGitRepository ) ) { final RevTree treeA = rw . parseTree ( commitIdDatabase . get ( range . from ( ) ) ) ; final RevTree treeB = rw . parseTree ( commitIdDatabase . get ( range . to ( ) ) ) ; // Compare the two Git trees. // Note that we do not cache here because CachingRepository caches the final result already. return toChangeMap ( blockingCompareTreesUncached ( treeA , treeB , pathPatternFilterOrTreeFilter ( pathPattern ) ) ) ; } catch ( StorageException e ) { throw e ; } catch ( Exception e ) { throw new StorageException ( "failed to parse two trees: range=" + range , e ) ; } finally { readUnlock ( ) ; } } , repositoryWorker ) ; }
Get the diff between any two valid revisions .
328
9
148,877
private Revision uncachedHeadRevision ( ) { try ( RevWalk revWalk = new RevWalk ( jGitRepository ) ) { final ObjectId headRevisionId = jGitRepository . resolve ( R_HEADS_MASTER ) ; if ( headRevisionId != null ) { final RevCommit revCommit = revWalk . parseCommit ( headRevisionId ) ; return CommitUtil . extractRevision ( revCommit . getFullMessage ( ) ) ; } } catch ( CentralDogmaException e ) { throw e ; } catch ( Exception e ) { throw new StorageException ( "failed to get the current revision" , e ) ; } throw new StorageException ( "failed to determine the HEAD: " + jGitRepository . getDirectory ( ) ) ; }
Returns the current revision .
171
5
148,878
public static String simpleTypeName ( Object obj ) { if ( obj == null ) { return "null" ; } return simpleTypeName ( obj . getClass ( ) , false ) ; }
Returns the simplified name of the type of the specified object .
40
12
148,879
public final B accessToken ( String accessToken ) { requireNonNull ( accessToken , "accessToken" ) ; checkArgument ( ! accessToken . isEmpty ( ) , "accessToken is empty." ) ; this . accessToken = accessToken ; return self ( ) ; }
Sets the access token to use when authenticating a client .
59
13
148,880
public static JsonPatch fromJson ( final JsonNode node ) throws IOException { requireNonNull ( node , "node" ) ; try { return Jackson . treeToValue ( node , JsonPatch . class ) ; } catch ( JsonMappingException e ) { throw new JsonPatchException ( "invalid JSON patch" , e ) ; } }
Static factory method to build a JSON Patch out of a JSON representation .
78
14
148,881
public static JsonPatch generate ( final JsonNode source , final JsonNode target , ReplaceMode replaceMode ) { requireNonNull ( source , "source" ) ; requireNonNull ( target , "target" ) ; final DiffProcessor processor = new DiffProcessor ( replaceMode , ( ) -> unchangedValues ( source , target ) ) ; generateDiffs ( processor , EMPTY_JSON_POINTER , source , target ) ; return processor . getPatch ( ) ; }
Generates a JSON patch for transforming the source node into the target node .
101
15
148,882
public JsonNode apply ( final JsonNode node ) { requireNonNull ( node , "node" ) ; JsonNode ret = node . deepCopy ( ) ; for ( final JsonPatchOperation operation : operations ) { ret = operation . apply ( ret ) ; } return ret ; }
Applies this patch to a JSON value .
62
9
148,883
static Project convert ( String name , com . linecorp . centraldogma . server . storage . project . Project project ) { return new Project ( name ) ; }
The parameter project is not used at the moment but will be used once schema and plugin support lands .
35
20
148,884
@ Override public List < Revision > getMatrixHistory ( final int start , final int limit ) throws StoreException { return delegate . getMatrixHistory ( start , limit ) ; }
caching is not supported for this method
37
8
148,885
private static File getUserDirectory ( final String prefix , final String suffix , final File parent ) { final String dirname = formatDirName ( prefix , suffix ) ; return new File ( parent , dirname ) ; }
Returns a File object whose path is the expected user directory . Does not create or check for existence .
45
20
148,886
private static String formatDirName ( final String prefix , final String suffix ) { // Replace all invalid characters with '-' final CharMatcher invalidCharacters = VALID_SUFFIX_CHARS . negate ( ) ; return String . format ( "%s-%s" , prefix , invalidCharacters . trimAndCollapseFrom ( suffix . toLowerCase ( ) , ' ' ) ) ; }
Returns the expected name of a workspace for a given suffix
82
11
148,887
private static void deleteUserDirectories ( final File root , final FileFilter filter ) { final File [ ] dirs = root . listFiles ( filter ) ; LOGGER . info ( "Identified (" + dirs . length + ") directories to delete" ) ; for ( final File dir : dirs ) { LOGGER . info ( "Deleting " + dir ) ; if ( ! FileUtils . deleteQuietly ( dir ) ) { LOGGER . info ( "Failed to delete directory " + dir ) ; } } }
Deletes all of the Directories in root that match the FileFilter
115
14
148,888
@ Nonnull public static Proctor construct ( @ Nonnull final TestMatrixArtifact matrix , ProctorLoadResult loadResult , FunctionMapper functionMapper ) { final ExpressionFactory expressionFactory = RuleEvaluator . EXPRESSION_FACTORY ; final Map < String , TestChooser < ? > > testChoosers = Maps . newLinkedHashMap ( ) ; final Map < String , String > versions = Maps . newLinkedHashMap ( ) ; for ( final Entry < String , ConsumableTestDefinition > entry : matrix . getTests ( ) . entrySet ( ) ) { final String testName = entry . getKey ( ) ; final ConsumableTestDefinition testDefinition = entry . getValue ( ) ; final TestType testType = testDefinition . getTestType ( ) ; final TestChooser < ? > testChooser ; if ( TestType . RANDOM . equals ( testType ) ) { testChooser = new RandomTestChooser ( expressionFactory , functionMapper , testName , testDefinition ) ; } else { testChooser = new StandardTestChooser ( expressionFactory , functionMapper , testName , testDefinition ) ; } testChoosers . put ( testName , testChooser ) ; versions . put ( testName , testDefinition . getVersion ( ) ) ; } return new Proctor ( matrix , loadResult , testChoosers ) ; }
Factory method to do the setup and transformation of inputs
299
10
148,889
public static ProctorLoadResult verifyWithoutSpecification ( @ Nonnull final TestMatrixArtifact testMatrix , final String matrixSource ) { final ProctorLoadResult . Builder resultBuilder = ProctorLoadResult . newBuilder ( ) ; for ( final Entry < String , ConsumableTestDefinition > entry : testMatrix . getTests ( ) . entrySet ( ) ) { final String testName = entry . getKey ( ) ; final ConsumableTestDefinition testDefinition = entry . getValue ( ) ; try { verifyInternallyConsistentDefinition ( testName , matrixSource , testDefinition ) ; } catch ( IncompatibleTestMatrixException e ) { LOGGER . info ( String . format ( "Unable to load test matrix for %s" , testName ) , e ) ; resultBuilder . recordError ( testName , e ) ; } } return resultBuilder . build ( ) ; }
Verifies that the TestMatrix is correct and sane without using a specification . The Proctor API doesn t use a test specification so that it can serve all tests in the matrix without restriction . Does a limited set of sanity checks that are applicable when there is no specification and thus no required tests or provided context .
187
62
148,890
public static ProctorLoadResult verify ( @ Nonnull final TestMatrixArtifact testMatrix , final String matrixSource , @ Nonnull final Map < String , TestSpecification > requiredTests , @ Nonnull final FunctionMapper functionMapper , final ProvidedContext providedContext , @ Nonnull final Set < String > dynamicTests ) { final ProctorLoadResult . Builder resultBuilder = ProctorLoadResult . newBuilder ( ) ; final Map < String , Map < Integer , String > > allTestsKnownBuckets = Maps . newHashMapWithExpectedSize ( requiredTests . size ( ) ) ; for ( final Entry < String , TestSpecification > entry : requiredTests . entrySet ( ) ) { final Map < Integer , String > bucketValueToName = Maps . newHashMap ( ) ; for ( final Entry < String , Integer > bucket : entry . getValue ( ) . getBuckets ( ) . entrySet ( ) ) { bucketValueToName . put ( bucket . getValue ( ) , bucket . getKey ( ) ) ; } allTestsKnownBuckets . put ( entry . getKey ( ) , bucketValueToName ) ; } final Map < String , ConsumableTestDefinition > definedTests = testMatrix . getTests ( ) ; final SetView < String > missingTests = Sets . difference ( requiredTests . keySet ( ) , definedTests . keySet ( ) ) ; resultBuilder . recordAllMissing ( missingTests ) ; for ( final Entry < String , ConsumableTestDefinition > entry : definedTests . entrySet ( ) ) { final String testName = entry . getKey ( ) ; final Map < Integer , String > knownBuckets ; final TestSpecification specification ; final boolean isRequired ; if ( allTestsKnownBuckets . containsKey ( testName ) ) { // required in specification isRequired = true ; knownBuckets = allTestsKnownBuckets . remove ( testName ) ; specification = requiredTests . get ( testName ) ; } else if ( dynamicTests . contains ( testName ) ) { // resolved by dynamic filter isRequired = false ; knownBuckets = Collections . emptyMap ( ) ; specification = new TestSpecification ( ) ; } else { // we don't care about this test continue ; } final ConsumableTestDefinition testDefinition = entry . getValue ( ) ; try { verifyTest ( testName , testDefinition , specification , knownBuckets , matrixSource , functionMapper , providedContext ) ; } catch ( IncompatibleTestMatrixException e ) { if ( isRequired ) { LOGGER . error ( String . format ( "Unable to load test matrix for a required test %s" , testName ) , e ) ; resultBuilder . recordError ( testName , e ) ; } else { LOGGER . info ( String . format ( "Unable to load test matrix for a dynamic test %s" , testName ) , e ) ; resultBuilder . recordIncompatibleDynamicTest ( testName , e ) ; } } } // TODO mjs - is this check additive? resultBuilder . recordAllMissing ( allTestsKnownBuckets . keySet ( ) ) ; resultBuilder . recordVerifiedRules ( providedContext . shouldEvaluate ( ) ) ; final ProctorLoadResult loadResult = resultBuilder . build ( ) ; return loadResult ; }
Does not mutate the TestMatrix . Verifies that the test matrix contains all the required tests and that each required test is valid .
725
27
148,891
static boolean isEmptyWhitespace ( @ Nullable final String s ) { if ( s == null ) { return true ; } return CharMatcher . WHITESPACE . matchesAllOf ( s ) ; }
Returns flag whose value indicates if the string is null empty or only contains whitespace characters
46
17
148,892
public static TestSpecification generateSpecification ( @ Nonnull final TestDefinition testDefinition ) { final TestSpecification testSpecification = new TestSpecification ( ) ; // Sort buckets by value ascending final Map < String , Integer > buckets = Maps . newLinkedHashMap ( ) ; final List < TestBucket > testDefinitionBuckets = Ordering . from ( new Comparator < TestBucket > ( ) { @ Override public int compare ( final TestBucket lhs , final TestBucket rhs ) { return Ints . compare ( lhs . getValue ( ) , rhs . getValue ( ) ) ; } } ) . immutableSortedCopy ( testDefinition . getBuckets ( ) ) ; int fallbackValue = - 1 ; if ( testDefinitionBuckets . size ( ) > 0 ) { final TestBucket firstBucket = testDefinitionBuckets . get ( 0 ) ; fallbackValue = firstBucket . getValue ( ) ; // buckets are sorted, choose smallest value as the fallback value final PayloadSpecification payloadSpecification = new PayloadSpecification ( ) ; if ( firstBucket . getPayload ( ) != null && ! firstBucket . getPayload ( ) . equals ( Payload . EMPTY_PAYLOAD ) ) { final PayloadType payloadType = PayloadType . payloadTypeForName ( firstBucket . getPayload ( ) . fetchType ( ) ) ; payloadSpecification . setType ( payloadType . payloadTypeName ) ; if ( payloadType == PayloadType . MAP ) { final Map < String , String > payloadSpecificationSchema = new HashMap < String , String > ( ) ; for ( Map . Entry < String , Object > entry : firstBucket . getPayload ( ) . getMap ( ) . entrySet ( ) ) { payloadSpecificationSchema . put ( entry . getKey ( ) , PayloadType . payloadTypeForValue ( entry . getValue ( ) ) . payloadTypeName ) ; } payloadSpecification . setSchema ( payloadSpecificationSchema ) ; } testSpecification . setPayload ( payloadSpecification ) ; } for ( int i = 0 ; i < testDefinitionBuckets . size ( ) ; i ++ ) { final TestBucket bucket = testDefinitionBuckets . get ( i ) ; buckets . put ( bucket . getName ( ) , bucket . getValue ( ) ) ; } } testSpecification . setBuckets ( buckets ) ; testSpecification . setDescription ( testDefinition . getDescription ( ) ) ; testSpecification . setFallbackValue ( fallbackValue ) ; return testSpecification ; }
Generates a usable test specification for a given test definition Uses the first bucket as the fallback value
570
20
148,893
@ Nonnull protected Payload getPayload ( final String testName ) { // Get the current bucket. final TestBucket testBucket = buckets . get ( testName ) ; // Lookup Payloads for this test if ( testBucket != null ) { final Payload payload = testBucket . getPayload ( ) ; if ( null != payload ) { return payload ; } } return Payload . EMPTY_PAYLOAD ; }
Return the Payload attached to the current active bucket for |test| . Always returns a payload so the client doesn t crash on a malformed test definition .
94
32
148,894
@ Nonnull public static Map < String , Integer > parseForcedGroups ( @ Nonnull final HttpServletRequest request ) { final String forceGroupsList = getForceGroupsStringFromRequest ( request ) ; return parseForceGroupsList ( forceGroupsList ) ; }
Consumer is required to do any privilege checks before getting here
61
11
148,895
private void precheckStateAllNull ( ) throws IllegalStateException { if ( ( doubleValue != null ) || ( doubleArray != null ) || ( longValue != null ) || ( longArray != null ) || ( stringValue != null ) || ( stringArray != null ) || ( map != null ) ) { throw new IllegalStateException ( "Expected all properties to be empty: " + this ) ; } }
Sanity check precondition for above setters
87
10
148,896
private Map < String , Integer > runSampling ( final ProctorContext proctorContext , final Set < String > targetTestNames , final TestType testType , final int determinationsToRun ) { final Set < String > targetTestGroups = getTargetTestGroups ( targetTestNames ) ; final Map < String , Integer > testGroupToOccurrences = Maps . newTreeMap ( ) ; for ( final String testGroup : targetTestGroups ) { testGroupToOccurrences . put ( testGroup , 0 ) ; } for ( int i = 0 ; i < determinationsToRun ; ++ i ) { final Identifiers identifiers = TestType . RANDOM . equals ( testType ) ? new Identifiers ( Collections . < TestType , String > emptyMap ( ) , /* randomEnabled */ true ) : Identifiers . of ( testType , Long . toString ( random . nextLong ( ) ) ) ; final AbstractGroups groups = supplier . getRandomGroups ( proctorContext , identifiers ) ; for ( final Entry < String , TestBucket > e : groups . getProctorResult ( ) . getBuckets ( ) . entrySet ( ) ) { final String testName = e . getKey ( ) ; if ( targetTestNames . contains ( testName ) ) { final int group = e . getValue ( ) . getValue ( ) ; final String testGroup = testName + group ; testGroupToOccurrences . put ( testGroup , testGroupToOccurrences . get ( testGroup ) + 1 ) ; } } } return testGroupToOccurrences ; }
test how many times the group was present in the list of groups .
341
14
148,897
private Proctor getProctorNotNull ( ) { final Proctor proctor = proctorLoader . get ( ) ; if ( proctor == null ) { throw new IllegalStateException ( "Proctor specification and/or text matrix has not been loaded" ) ; } return proctor ; }
return currently - loaded Proctor instance throwing IllegalStateException if not loaded
61
14
148,898
@ SafeVarargs public static void registerFilterTypes ( final Class < ? extends DynamicFilter > ... types ) { FILTER_TYPES . addAll ( Arrays . asList ( types ) ) ; }
Register custom filter types especially for serializer of specification json file
44
12
148,899
private ProctorContext getProctorContext ( final HttpServletRequest request ) throws IllegalAccessException , InstantiationException { final ProctorContext proctorContext = contextClass . newInstance ( ) ; final BeanWrapper beanWrapper = new BeanWrapperImpl ( proctorContext ) ; for ( final PropertyDescriptor descriptor : beanWrapper . getPropertyDescriptors ( ) ) { final String propertyName = descriptor . getName ( ) ; if ( ! "class" . equals ( propertyName ) ) { // ignore class property which every object has final String parameterValue = request . getParameter ( propertyName ) ; if ( parameterValue != null ) { beanWrapper . setPropertyValue ( propertyName , parameterValue ) ; } } } return proctorContext ; }
Do some magic to turn request parameters into a context object
163
11