idx int64 0 41.2k | question stringlengths 74 4.21k | target stringlengths 5 888 |
|---|---|---|
20,700 | private String generateFileName ( ) { int checksum = 1 ; Set < TypeId < ? > > typesKeySet = types . keySet ( ) ; Iterator < TypeId < ? > > it = typesKeySet . iterator ( ) ; int [ ] checksums = new int [ typesKeySet . size ( ) ] ; int i = 0 ; while ( it . hasNext ( ) ) { TypeId < ? > typeId = it . next ( ) ; TypeDeclaration decl = getTypeDeclaration ( typeId ) ; Set < MethodId > methodSet = decl . methods . keySet ( ) ; if ( decl . supertype != null ) { int sum = 31 * decl . supertype . hashCode ( ) + decl . interfaces . hashCode ( ) ; checksums [ i ++ ] = 31 * sum + methodSet . hashCode ( ) ; } } Arrays . sort ( checksums ) ; for ( int sum : checksums ) { checksum *= 31 ; checksum += sum ; } return "Generated_" + checksum + ".jar" ; } | parent class types . |
20,701 | public ClassLoader generateAndLoad ( ClassLoader parent , File dexCache ) throws IOException { if ( dexCache == null ) { String property = System . getProperty ( "dexmaker.dexcache" ) ; if ( property != null ) { dexCache = new File ( property ) ; } else { dexCache = new AppDataDirGuesser ( ) . guess ( ) ; if ( dexCache == null ) { throw new IllegalArgumentException ( "dexcache == null (and no default could be" + " found; consider setting the 'dexmaker.dexcache' system property)" ) ; } } } File result = new File ( dexCache , generateFileName ( ) ) ; if ( result . exists ( ) ) { return generateClassLoader ( result , dexCache , parent ) ; } byte [ ] dex = generate ( ) ; result . createNewFile ( ) ; JarOutputStream jarOut = new JarOutputStream ( new FileOutputStream ( result ) ) ; JarEntry entry = new JarEntry ( DexFormat . DEX_IN_JAR_NAME ) ; entry . setSize ( dex . length ) ; jarOut . putNextEntry ( entry ) ; jarOut . write ( dex ) ; jarOut . closeEntry ( ) ; jarOut . close ( ) ; return generateClassLoader ( result , dexCache , parent ) ; } | Generates a dex file and loads its types into the current process . |
20,702 | public static MockMethodDispatcher get ( String identifier , Object instance ) { if ( instance == INSTANCE ) { return null ; } else { return INSTANCE . get ( identifier ) ; } } | Get the dispatcher for a identifier . |
20,703 | public static void set ( String identifier , Object advice ) { INSTANCE . putIfAbsent ( identifier , new MockMethodDispatcher ( advice ) ) ; } | Set up a new advice to receive calls for an identifier |
20,704 | public boolean isOverridden ( Object instance , Method origin ) { Class < ? > currentType = instance . getClass ( ) ; do { try { return ! origin . equals ( currentType . getDeclaredMethod ( origin . getName ( ) , origin . getParameterTypes ( ) ) ) ; } catch ( NoSuchMethodException ignored ) { currentType = currentType . getSuperclass ( ) ; } } while ( currentType != null ) ; return true ; } | Check if a method is overridden . |
20,705 | public < T > StaticMockitoSessionBuilder spyStatic ( Class < T > clazz ) { staticMockings . add ( new StaticMocking < > ( clazz , ( ) -> Mockito . mock ( clazz , withSettings ( ) . defaultAnswer ( CALLS_REAL_METHODS ) ) ) ) ; return this ; } | Sets up spying for static methods of a class . |
20,706 | static TypedConstant getConstant ( Object value ) { if ( value == null ) { return CstKnownNull . THE_ONE ; } else if ( value instanceof Boolean ) { return CstBoolean . make ( ( Boolean ) value ) ; } else if ( value instanceof Byte ) { return CstByte . make ( ( Byte ) value ) ; } else if ( value instanceof Character ) { return CstChar . make ( ( Character ) value ) ; } else if ( value instanceof Double ) { return CstDouble . make ( Double . doubleToLongBits ( ( Double ) value ) ) ; } else if ( value instanceof Float ) { return CstFloat . make ( Float . floatToIntBits ( ( Float ) value ) ) ; } else if ( value instanceof Integer ) { return CstInteger . make ( ( Integer ) value ) ; } else if ( value instanceof Long ) { return CstLong . make ( ( Long ) value ) ; } else if ( value instanceof Short ) { return CstShort . make ( ( Short ) value ) ; } else if ( value instanceof String ) { return new CstString ( ( String ) value ) ; } else if ( value instanceof Class ) { return new CstType ( TypeId . get ( ( Class < ? > ) value ) . ropType ) ; } else if ( value instanceof TypeId ) { return new CstType ( ( ( TypeId ) value ) . ropType ) ; } else { throw new UnsupportedOperationException ( "Not a constant: " + value ) ; } } | Returns a rop constant for the specified value . |
20,707 | public T build ( ) throws IOException { check ( handler != null , "handler == null" ) ; check ( constructorArgTypes . length == constructorArgValues . length , "constructorArgValues.length != constructorArgTypes.length" ) ; Class < ? extends T > proxyClass = buildProxyClass ( ) ; Constructor < ? extends T > constructor ; try { constructor = proxyClass . getConstructor ( constructorArgTypes ) ; } catch ( NoSuchMethodException e ) { throw new IllegalArgumentException ( "No constructor for " + baseClass . getName ( ) + " with parameter types " + Arrays . toString ( constructorArgTypes ) ) ; } T result ; try { result = constructor . newInstance ( constructorArgValues ) ; } catch ( InstantiationException e ) { throw new AssertionError ( e ) ; } catch ( IllegalAccessException e ) { throw new AssertionError ( e ) ; } catch ( InvocationTargetException e ) { throw launderCause ( e ) ; } setInvocationHandler ( result , handler ) ; return result ; } | Create a new instance of the class to proxy . |
20,708 | private static String superMethodName ( Method method ) { String returnType = method . getReturnType ( ) . getName ( ) ; return "super$" + method . getName ( ) + "$" + returnType . replace ( '.' , '_' ) . replace ( '[' , '_' ) . replace ( ';' , '_' ) ; } | The super method must include the return type otherwise its ambiguous for methods with covariant return types . |
20,709 | @ SuppressWarnings ( "unchecked" ) private static < T > Constructor < T > [ ] getConstructorsToOverwrite ( Class < T > clazz ) { return ( Constructor < T > [ ] ) clazz . getDeclaredConstructors ( ) ; } | hence this cast is safe . |
20,710 | @ SuppressWarnings ( { "rawtypes" , "unchecked" } ) private static void generateCodeForReturnStatement ( Code code , Class methodReturnType , Local localForResultOfInvoke , Local localOfMethodReturnType , Local aBoxedResult ) { if ( PRIMITIVE_TO_UNBOX_METHOD . containsKey ( methodReturnType ) ) { code . cast ( aBoxedResult , localForResultOfInvoke ) ; MethodId unboxingMethodFor = getUnboxMethodForPrimitive ( methodReturnType ) ; code . invokeVirtual ( unboxingMethodFor , localOfMethodReturnType , aBoxedResult ) ; code . returnValue ( localOfMethodReturnType ) ; } else if ( void . class . equals ( methodReturnType ) ) { code . returnVoid ( ) ; } else { code . cast ( localOfMethodReturnType , localForResultOfInvoke ) ; code . returnValue ( localOfMethodReturnType ) ; } } | This one is tricky to fix I gave up . |
20,711 | @ SuppressWarnings ( "unchecked" ) public static < T > T staticMockMarker ( Class < T > clazz ) { for ( StaticMockitoSession session : sessions ) { T marker = session . staticMockMarker ( clazz ) ; if ( marker != null ) { return marker ; } } return null ; } | Many methods of mockito take mock objects . To be able to call the same methods for static mocking this method gets a marker object that can be used instead . |
20,712 | @ SuppressWarnings ( "CheckReturnValue" ) public static void spyOn ( Object toSpy ) { if ( onSpyInProgressInstance . get ( ) != null ) { throw new IllegalStateException ( "Cannot set up spying on an existing object while " + "setting up spying for another existing object" ) ; } onSpyInProgressInstance . set ( toSpy ) ; try { spy ( toSpy ) ; } finally { onSpyInProgressInstance . remove ( ) ; } } | Make an existing object a spy . |
20,713 | @ SuppressWarnings ( { "CheckReturnValue" , "MockitoUsage" , "unchecked" } ) static void verifyInt ( MockedVoidMethod method , VerificationMode mode , InOrder instanceInOrder ) { if ( onMethodCallDuringVerification . get ( ) != null ) { throw new IllegalStateException ( "Verification is already in progress on this " + "thread." ) ; } ArrayList < Method > verifications = new ArrayList < > ( ) ; onMethodCallDuringVerification . set ( ( clazz , verifiedMethod ) -> { try { ArgumentMatcherStorageImpl argMatcherStorage = ( ArgumentMatcherStorageImpl ) mockingProgress ( ) . getArgumentMatcherStorage ( ) ; List < LocalizedMatcher > matchers ; Method resetStackMethod = argMatcherStorage . getClass ( ) . getDeclaredMethod ( "resetStack" ) ; resetStackMethod . setAccessible ( true ) ; matchers = ( List < LocalizedMatcher > ) resetStackMethod . invoke ( argMatcherStorage ) ; if ( instanceInOrder == null ) { verify ( staticMockMarker ( clazz ) , mode ) ; } else { instanceInOrder . verify ( staticMockMarker ( clazz ) , mode ) ; } Field matcherStackField = argMatcherStorage . getClass ( ) . getDeclaredField ( "matcherStack" ) ; matcherStackField . setAccessible ( true ) ; Method pushMethod = matcherStackField . getType ( ) . getDeclaredMethod ( "push" , Object . class ) ; for ( LocalizedMatcher matcher : matchers ) { pushMethod . invoke ( matcherStackField . get ( argMatcherStorage ) , matcher ) ; } } catch ( NoSuchFieldException | NoSuchMethodException | IllegalAccessException | InvocationTargetException | ClassCastException e ) { throw new Error ( "Reflection failed. Do you use a compatible version of " + "mockito?" , e ) ; } verifications . add ( verifiedMethod ) ; } ) ; try { try { method . run ( ) ; } catch ( Throwable t ) { if ( t instanceof RuntimeException ) { throw ( RuntimeException ) t ; } else if ( t instanceof Error ) { throw ( Error ) t ; } throw new RuntimeException ( t ) ; } if ( verifications . isEmpty ( ) ) { throw new IllegalArgumentException ( "Nothing was verified. Does the lambda call " + "a static method on a 'static' mock/spy ?" ) ; } else if ( verifications . size ( ) > 1 ) { throw new IllegalArgumentException ( "Multiple intercepted calls on methods " + verifications ) ; } } finally { onMethodCallDuringVerification . remove ( ) ; } } | Common implementation of verification of static method calls . |
20,714 | private < T > Method [ ] getMethodsToProxy ( MockCreationSettings < T > settings ) { Set < MethodSetEntry > abstractMethods = new HashSet < > ( ) ; Set < MethodSetEntry > nonAbstractMethods = new HashSet < > ( ) ; Class < ? > superClass = settings . getTypeToMock ( ) ; while ( superClass != null ) { for ( Method method : superClass . getDeclaredMethods ( ) ) { if ( Modifier . isAbstract ( method . getModifiers ( ) ) && ! nonAbstractMethods . contains ( new MethodSetEntry ( method ) ) ) { abstractMethods . add ( new MethodSetEntry ( method ) ) ; } else { nonAbstractMethods . add ( new MethodSetEntry ( method ) ) ; } } superClass = superClass . getSuperclass ( ) ; } for ( Class < ? > i : settings . getTypeToMock ( ) . getInterfaces ( ) ) { for ( Method method : i . getMethods ( ) ) { if ( ! nonAbstractMethods . contains ( new MethodSetEntry ( method ) ) ) { abstractMethods . add ( new MethodSetEntry ( method ) ) ; } } } for ( Class < ? > i : settings . getExtraInterfaces ( ) ) { for ( Method method : i . getMethods ( ) ) { if ( ! nonAbstractMethods . contains ( new MethodSetEntry ( method ) ) ) { abstractMethods . add ( new MethodSetEntry ( method ) ) ; } } } Method [ ] methodsToProxy = new Method [ abstractMethods . size ( ) ] ; int i = 0 ; for ( MethodSetEntry entry : abstractMethods ) { methodsToProxy [ i ++ ] = entry . originalMethod ; } return methodsToProxy ; } | Get methods to proxy . |
20,715 | public static < D , V > AnnotationId < D , V > get ( TypeId < D > declaringType , TypeId < V > type , ElementType annotatedElement ) { if ( annotatedElement != ElementType . TYPE && annotatedElement != ElementType . METHOD && annotatedElement != ElementType . FIELD && annotatedElement != ElementType . PARAMETER ) { throw new IllegalArgumentException ( "element type is not supported to annotate yet." ) ; } return new AnnotationId < > ( declaringType , type , annotatedElement ) ; } | Construct an instance . It initially contains no elements . |
20,716 | public void set ( Element element ) { if ( element == null ) { throw new NullPointerException ( "element == null" ) ; } CstString pairName = new CstString ( element . getName ( ) ) ; Constant pairValue = Element . toConstant ( element . getValue ( ) ) ; NameValuePair nameValuePair = new NameValuePair ( pairName , pairValue ) ; elements . put ( element . getName ( ) , nameValuePair ) ; } | Set an annotation element of this instance . If there is a preexisting element with the same name it will be replaced by this method . |
20,717 | public void addToMethod ( DexMaker dexMaker , MethodId < ? , ? > method ) { if ( annotatedElement != ElementType . METHOD ) { throw new IllegalStateException ( "This annotation is not for method" ) ; } if ( ! method . declaringType . equals ( declaringType ) ) { throw new IllegalArgumentException ( "Method" + method + "'s declaring type is inconsistent with" + this ) ; } ClassDefItem classDefItem = dexMaker . getTypeDeclaration ( declaringType ) . toClassDefItem ( ) ; if ( classDefItem == null ) { throw new NullPointerException ( "No class defined item is found" ) ; } else { CstMethodRef cstMethodRef = method . constant ; if ( cstMethodRef == null ) { throw new NullPointerException ( "Method reference is NULL" ) ; } else { CstType cstType = CstType . intern ( type . ropType ) ; Annotation annotation = new Annotation ( cstType , AnnotationVisibility . RUNTIME ) ; Annotations annotations = new Annotations ( ) ; for ( NameValuePair nvp : elements . values ( ) ) { annotation . add ( nvp ) ; } annotations . add ( annotation ) ; classDefItem . addMethodAnnotations ( cstMethodRef , annotations , dexMaker . getDexFile ( ) ) ; } } } | Add this annotation to a method . |
20,718 | int initialize ( int nextAvailableRegister ) { this . reg = nextAvailableRegister ; this . spec = RegisterSpec . make ( nextAvailableRegister , type . ropType ) ; return size ( ) ; } | Assigns registers to this local . |
20,719 | void appendToBootstrapClassLoaderSearch ( InputStream jarStream ) throws IOException { File jarFile = File . createTempFile ( "mockito-boot" , ".jar" ) ; jarFile . deleteOnExit ( ) ; byte [ ] buffer = new byte [ 64 * 1024 ] ; try ( OutputStream os = new FileOutputStream ( jarFile ) ) { while ( true ) { int numRead = jarStream . read ( buffer ) ; if ( numRead == - 1 ) { break ; } os . write ( buffer , 0 , numRead ) ; } } nativeAppendToBootstrapClassLoaderSearch ( jarFile . getAbsolutePath ( ) ) ; } | Append the jar to be bootstrap class load . This makes the classes in the jar behave as if they are loaded from the BCL . E . g . classes from java . lang can now call the classes in the jar . |
20,720 | < T > void mockStatic ( StaticMocking < T > mocking ) { if ( ExtendedMockito . staticMockMarker ( mocking . clazz ) != null ) { throw new IllegalArgumentException ( mocking . clazz + " is already mocked" ) ; } mockingInProgressClass . set ( mocking . clazz ) ; try { classToMarker . put ( mocking . clazz , mocking . markerSupplier . get ( ) ) ; } finally { mockingInProgressClass . remove ( ) ; } staticMocks . add ( mocking . clazz ) ; } | Init mocking for a class . |
20,721 | public void mark ( Label label ) { adopt ( label ) ; if ( label . marked ) { throw new IllegalStateException ( "already marked" ) ; } label . marked = true ; if ( currentLabel != null ) { jump ( label ) ; } currentLabel = label ; } | Start defining instructions for the named label . |
20,722 | private void splitCurrentLabel ( Label alternateSuccessor , List < Label > catchLabels ) { Label newLabel = new Label ( ) ; adopt ( newLabel ) ; currentLabel . primarySuccessor = newLabel ; currentLabel . alternateSuccessor = alternateSuccessor ; currentLabel . catchLabels = catchLabels ; currentLabel = newLabel ; currentLabel . marked = true ; } | Closes the current label and starts a new one . |
20,723 | public void cast ( Local < ? > target , Local < ? > source ) { if ( source . getType ( ) . ropType . isReference ( ) ) { addInstruction ( new ThrowingCstInsn ( Rops . CHECK_CAST , sourcePosition , RegisterSpecList . make ( source . spec ( ) ) , catches , target . type . constant ) ) ; moveResult ( target , true ) ; } else { addInstruction ( new PlainInsn ( getCastRop ( source . type . ropType , target . type . ropType ) , sourcePosition , target . spec ( ) , source . spec ( ) ) ) ; } } | Performs either a numeric cast or a type cast . |
20,724 | BasicBlockList toBasicBlocks ( ) { if ( ! localsInitialized ) { initializeLocals ( ) ; } cleanUpLabels ( ) ; BasicBlockList result = new BasicBlockList ( labels . size ( ) ) ; for ( int i = 0 ; i < labels . size ( ) ; i ++ ) { result . set ( i , labels . get ( i ) . toBasicBlock ( ) ) ; } return result ; } | produce BasicBlocks for dex |
20,725 | private void cleanUpLabels ( ) { int id = 0 ; for ( Iterator < Label > i = labels . iterator ( ) ; i . hasNext ( ) ; ) { Label label = i . next ( ) ; if ( label . isEmpty ( ) ) { i . remove ( ) ; } else { label . compact ( ) ; label . id = id ++ ; } } } | Removes empty labels and assigns IDs to non - empty labels . |
20,726 | @ SuppressWarnings ( "unchecked" ) private E wrappedException ( final Exception exp ) { E wrapped = new UncheckedFunc < > ( this . func ) . apply ( exp ) ; final int level = new InheritanceLevel ( exp . getClass ( ) , wrapped . getClass ( ) ) . value ( ) ; final String message = wrapped . getMessage ( ) . replaceFirst ( new UncheckedText ( new FormattedText ( "%s: " , exp . getClass ( ) . getName ( ) ) ) . asString ( ) , "" ) ; if ( level >= 0 && message . equals ( exp . getMessage ( ) ) ) { wrapped = ( E ) exp ; } return wrapped ; } | Wraps exception . Skips unnecessary wrapping of exceptions of the same type . Allows wrapping of exceptions of the same type if the error message has been changed . |
20,727 | private int copy ( final byte [ ] buffer , final byte [ ] response , final int read ) { System . arraycopy ( buffer , read - this . count , response , 0 , this . count ) ; return new MinOf ( this . count , read ) . intValue ( ) ; } | Copy full buffer to response . |
20,728 | private int copyPartial ( final byte [ ] buffer , final byte [ ] response , final int num , final int read ) { final int result ; if ( num > 0 ) { System . arraycopy ( response , read , response , 0 , this . count - read ) ; System . arraycopy ( buffer , 0 , response , this . count - read , read ) ; result = this . count ; } else { System . arraycopy ( buffer , 0 , response , 0 , read ) ; result = read ; } return result ; } | Copy buffer to response for read count smaller then buffer size . |
20,729 | @ SuppressWarnings ( "PMD.AvoidThrowingRawExceptionTypes" ) private T fallback ( final Throwable exp ) throws Exception { final Sorted < Map . Entry < FallbackFrom < T > , Integer > > candidates = new Sorted < > ( Comparator . comparing ( Map . Entry :: getValue ) , new Filtered < > ( entry -> new Not ( new Equals < > ( entry :: getValue , ( ) -> Integer . MIN_VALUE ) ) . value ( ) , new MapOf < > ( fbk -> fbk , fbk -> fbk . support ( exp . getClass ( ) ) , this . fallbacks ) . entrySet ( ) . iterator ( ) ) ) ; if ( candidates . hasNext ( ) ) { return candidates . next ( ) . getKey ( ) . apply ( exp ) ; } else { throw new Exception ( "No fallback found - throw the original exception" , exp ) ; } } | Finds the best fallback for the given exception type and apply it to the exception or throw the original error if no fallback found . |
20,730 | private int next ( final byte [ ] buffer , final int offset , final int length ) throws IOException { final int max = Math . min ( length , this . input . remaining ( ) ) ; this . input . put ( buffer , offset , max ) ; this . input . flip ( ) ; while ( true ) { final CoderResult result = this . decoder . decode ( this . input , this . output , false ) ; if ( result . isError ( ) ) { result . throwException ( ) ; } this . writer . write ( this . output . array ( ) , 0 , this . output . position ( ) ) ; this . writer . flush ( ) ; this . output . rewind ( ) ; if ( result . isUnderflow ( ) ) { break ; } } this . input . compact ( ) ; return max ; } | Write a portion from the buffer . |
20,731 | public Integer support ( final Class < ? extends Throwable > target ) { return new MinOf ( new Mapped < > ( supported -> new InheritanceLevel ( target , supported ) . value ( ) , this . exceptions ) ) . intValue ( ) ; } | Calculate level of support of the given exception type . |
20,732 | private int calculateLevel ( ) { int level = Integer . MIN_VALUE ; Class < ? > sclass = this . derived . getSuperclass ( ) ; int idx = 0 ; while ( ! sclass . equals ( Object . class ) ) { idx += 1 ; if ( sclass . equals ( this . base ) ) { level = idx ; break ; } sclass = sclass . getSuperclass ( ) ; } return level ; } | Calculates inheritance level . |
20,733 | public static String convertTcpToHttpUrl ( String connect ) { String protocol = connect . contains ( ":" + DOCKER_HTTPS_PORT ) ? "https:" : "http:" ; return connect . replaceFirst ( "^tcp:" , protocol ) ; } | Convert docker host URL to an http URL |
20,734 | public static boolean greaterOrEqualsVersion ( String versionA , String versionB ) { String largerVersion = extractLargerVersion ( versionA , versionB ) ; return largerVersion != null && largerVersion . equals ( versionA ) ; } | Check whether the first given API version is larger or equals the second given version |
20,735 | public static Map < String , String > extractFromPropertiesAsMap ( String prefix , Properties properties ) { Map < String , String > ret = new HashMap < > ( ) ; Enumeration names = properties . propertyNames ( ) ; String prefixP = prefix + "." ; while ( names . hasMoreElements ( ) ) { String propName = ( String ) names . nextElement ( ) ; if ( propMatchesPrefix ( prefixP , propName ) ) { String mapKey = propName . substring ( prefixP . length ( ) ) ; if ( PROPERTY_COMBINE_POLICY_SUFFIX . equals ( mapKey ) ) { continue ; } ret . put ( mapKey , properties . getProperty ( propName ) ) ; } } return ret . size ( ) > 0 ? ret : null ; } | Extract part of given properties as a map . The given prefix is used to find the properties the rest of the property name is used as key for the map . |
20,736 | public static String formatDurationTill ( long start ) { long duration = System . currentTimeMillis ( ) - start ; StringBuilder res = new StringBuilder ( ) ; TimeUnit current = HOURS ; while ( duration > 0 ) { long temp = current . convert ( duration , MILLISECONDS ) ; if ( temp > 0 ) { duration -= current . toMillis ( temp ) ; res . append ( temp ) . append ( " " ) . append ( current . name ( ) . toLowerCase ( ) ) ; if ( temp < 2 ) res . deleteCharAt ( res . length ( ) - 1 ) ; res . append ( ", " ) ; } if ( current == SECONDS ) { break ; } current = TimeUnit . values ( ) [ current . ordinal ( ) - 1 ] ; } if ( res . lastIndexOf ( ", " ) < 0 ) { return duration + " " + MILLISECONDS . name ( ) . toLowerCase ( ) ; } res . deleteCharAt ( res . length ( ) - 2 ) ; int i = res . lastIndexOf ( ", " ) ; if ( i > 0 ) { res . deleteCharAt ( i ) ; res . insert ( i , " and" ) ; } return res . toString ( ) ; } | Calculate the duration between now and the given time |
20,737 | public static String firstRegistryOf ( String ... checkFirst ) { for ( String registry : checkFirst ) { if ( registry != null ) { return registry ; } } return System . getenv ( "DOCKER_REGISTRY" ) ; } | Return the first non null registry given . Use the env var DOCKER_REGISTRY as final fallback |
20,738 | public static void storeTimestamp ( File tsFile , Date buildDate ) throws MojoExecutionException { try { if ( tsFile . exists ( ) ) { tsFile . delete ( ) ; } File dir = tsFile . getParentFile ( ) ; if ( ! dir . exists ( ) ) { if ( ! dir . mkdirs ( ) ) { throw new MojoExecutionException ( "Cannot create directory " + dir ) ; } } FileUtils . fileWrite ( tsFile , StandardCharsets . US_ASCII . name ( ) , Long . toString ( buildDate . getTime ( ) ) ) ; } catch ( IOException e ) { throw new MojoExecutionException ( "Cannot create " + tsFile + " for storing time " + buildDate . getTime ( ) , e ) ; } } | create a timestamp file holding time in epoch seconds |
20,739 | public static KeyStore createDockerKeyStore ( String certPath ) throws IOException , GeneralSecurityException { PrivateKey privKey = loadPrivateKey ( certPath + "/key.pem" ) ; Certificate [ ] certs = loadCertificates ( certPath + "/cert.pem" ) ; KeyStore keyStore = KeyStore . getInstance ( KeyStore . getDefaultType ( ) ) ; keyStore . load ( null ) ; keyStore . setKeyEntry ( "docker" , privKey , "docker" . toCharArray ( ) , certs ) ; addCA ( keyStore , certPath + "/ca.pem" ) ; return keyStore ; } | Create a key stored holding certificates and secret keys from the given Docker key cert |
20,740 | public AuthConfig extendedAuth ( AuthConfig localCredentials ) throws IOException , MojoExecutionException { JsonObject jo = getAuthorizationToken ( localCredentials ) ; JsonArray authorizationDatas = jo . getAsJsonArray ( "authorizationData" ) ; JsonObject authorizationData = authorizationDatas . get ( 0 ) . getAsJsonObject ( ) ; String authorizationToken = authorizationData . get ( "authorizationToken" ) . getAsString ( ) ; return new AuthConfig ( authorizationToken , "none" ) ; } | Perform extended authentication . Use the provided credentials as IAM credentials and get a temporary ECR token . |
20,741 | public void progressStart ( ) { if ( ! batchMode && log . isInfoEnabled ( ) ) { imageLines . remove ( ) ; updateCount . remove ( ) ; imageLines . set ( new HashMap < String , Integer > ( ) ) ; updateCount . set ( new AtomicInteger ( ) ) ; } } | Start a progress bar |
20,742 | public void progressUpdate ( String layerId , String status , String progressMessage ) { if ( ! batchMode && log . isInfoEnabled ( ) && StringUtils . isNotEmpty ( layerId ) ) { if ( useAnsi ) { updateAnsiProgress ( layerId , status , progressMessage ) ; } else { updateNonAnsiProgress ( layerId ) ; } flush ( ) ; } } | Update the progress |
20,743 | private String format ( String message , Object [ ] params ) { if ( params . length == 0 ) { return message ; } else if ( params . length == 1 && params [ 0 ] instanceof Throwable ) { return message + ": " + params [ 0 ] . toString ( ) ; } else { return String . format ( message , params ) ; } } | Use parameters when given otherwise we use the string directly |
20,744 | public synchronized void registerContainer ( String containerId , ImageConfiguration imageConfig , GavLabel gavLabel ) { ContainerShutdownDescriptor descriptor = new ContainerShutdownDescriptor ( imageConfig , containerId ) ; shutdownDescriptorPerContainerMap . put ( containerId , descriptor ) ; updatePomLabelMap ( gavLabel , descriptor ) ; updateImageToContainerMapping ( imageConfig , containerId ) ; } | Register a started container to this tracker |
20,745 | public synchronized String lookupContainer ( String lookup ) { if ( aliasToContainerMap . containsKey ( lookup ) ) { return aliasToContainerMap . get ( lookup ) ; } return imageToContainerMap . get ( lookup ) ; } | Lookup a container by name or alias from the tracked containers |
20,746 | public synchronized Collection < ContainerShutdownDescriptor > removeShutdownDescriptors ( GavLabel gavLabel ) { List < ContainerShutdownDescriptor > descriptors ; if ( gavLabel != null ) { descriptors = removeFromPomLabelMap ( gavLabel ) ; removeFromPerContainerMap ( descriptors ) ; } else { descriptors = new ArrayList < > ( shutdownDescriptorPerContainerMap . values ( ) ) ; clearAllMaps ( ) ; } Collections . reverse ( descriptors ) ; return descriptors ; } | Get all shutdown descriptors for a given pom label and remove it from the tracker . The descriptors are returned in reverse order of their registration . |
20,747 | protected synchronized Date getBuildTimestamp ( ) throws IOException { Date now = ( Date ) getPluginContext ( ) . get ( CONTEXT_KEY_BUILD_TIMESTAMP ) ; if ( now == null ) { now = getReferenceDate ( ) ; getPluginContext ( ) . put ( CONTEXT_KEY_BUILD_TIMESTAMP , now ) ; } return now ; } | Get the current build timestamp . this has either already been created by a previous call or a new current date is created |
20,748 | protected Date getReferenceDate ( ) throws IOException { Date referenceDate = EnvUtil . loadTimestamp ( getBuildTimestampFile ( ) ) ; return referenceDate != null ? referenceDate : new Date ( ) ; } | from an existing build date file . If this does not exist the current date is used . |
20,749 | private String initImageConfiguration ( Date buildTimeStamp ) { resolvedImages = ConfigHelper . resolveImages ( log , images , new ConfigHelper . Resolver ( ) { public List < ImageConfiguration > resolve ( ImageConfiguration image ) { return imageConfigResolver . resolve ( image , project , session ) ; } } , filter , this ) ; File topDockerfile = new File ( project . getBasedir ( ) , "Dockerfile" ) ; if ( topDockerfile . exists ( ) ) { if ( resolvedImages . isEmpty ( ) ) { resolvedImages . add ( createSimpleDockerfileConfig ( topDockerfile ) ) ; } else if ( resolvedImages . size ( ) == 1 && resolvedImages . get ( 0 ) . getBuildConfiguration ( ) == null ) { resolvedImages . set ( 0 , addSimpleDockerfileConfig ( resolvedImages . get ( 0 ) , topDockerfile ) ) ; } } return ConfigHelper . initAndValidate ( resolvedImages , apiVersion , new ImageNameFormatter ( project , buildTimeStamp ) , log ) ; } | Resolve and customize image configuration |
20,750 | private List < DockerConnectionDetector . DockerHostProvider > getDefaultDockerHostProviders ( DockerAccessContext dockerAccessContext , Logger log ) { DockerMachineConfiguration config = dockerAccessContext . getMachine ( ) ; if ( dockerAccessContext . isSkipMachine ( ) ) { config = null ; } else if ( config == null ) { Properties projectProps = dockerAccessContext . getProjectProperties ( ) ; if ( projectProps . containsKey ( DockerMachineConfiguration . DOCKER_MACHINE_NAME_PROP ) ) { config = new DockerMachineConfiguration ( projectProps . getProperty ( DockerMachineConfiguration . DOCKER_MACHINE_NAME_PROP ) , projectProps . getProperty ( DockerMachineConfiguration . DOCKER_MACHINE_AUTO_CREATE_PROP ) , projectProps . getProperty ( DockerMachineConfiguration . DOCKER_MACHINE_REGENERATE_CERTS_AFTER_START_PROP ) ) ; } } List < DockerConnectionDetector . DockerHostProvider > ret = new ArrayList < > ( ) ; ret . add ( new DockerMachine ( log , config ) ) ; return ret ; } | Return a list of providers which could delive connection parameters from calling external commands . For this plugin this is docker - machine but can be overridden to add other config options too . |
20,751 | private void setDockerHostAddressProperty ( DockerAccessContext dockerAccessContext , String dockerUrl ) throws MojoFailureException { Properties props = dockerAccessContext . getProjectProperties ( ) ; if ( props . getProperty ( "docker.host.address" ) == null ) { final String host ; try { URI uri = new URI ( dockerUrl ) ; if ( uri . getHost ( ) == null && ( uri . getScheme ( ) . equals ( "unix" ) || uri . getScheme ( ) . equals ( "npipe" ) ) ) { host = "localhost" ; } else { host = uri . getHost ( ) ; } } catch ( URISyntaxException e ) { throw new MojoFailureException ( "Cannot parse " + dockerUrl + " as URI: " + e . getMessage ( ) , e ) ; } props . setProperty ( "docker.host.address" , host == null ? "" : host ) ; } } | Registry for managed containers |
20,752 | public static List < ImageConfiguration > resolveImages ( Logger logger , List < ImageConfiguration > images , Resolver imageResolver , String imageNameFilter , Customizer imageCustomizer ) { List < ImageConfiguration > ret = resolveConfiguration ( imageResolver , images ) ; ret = imageCustomizer . customizeConfig ( ret ) ; List < ImageConfiguration > filtered = filterImages ( imageNameFilter , ret ) ; if ( ret . size ( ) > 0 && filtered . size ( ) == 0 && imageNameFilter != null ) { List < String > imageNames = new ArrayList < > ( ) ; for ( ImageConfiguration image : ret ) { imageNames . add ( image . getName ( ) ) ; } logger . warn ( "None of the resolved images [%s] match the configured filter '%s'" , StringUtils . join ( imageNames . iterator ( ) , "," ) , imageNameFilter ) ; } return filtered ; } | Resolve image with an external image resolver |
20,753 | public static String initAndValidate ( List < ImageConfiguration > images , String apiVersion , NameFormatter nameFormatter , Logger log ) { for ( ImageConfiguration imageConfiguration : images ) { apiVersion = EnvUtil . extractLargerVersion ( apiVersion , imageConfiguration . initAndValidate ( nameFormatter , log ) ) ; } return apiVersion ; } | Initialize and validate the configuration . |
20,754 | public static boolean matchesConfiguredImages ( String imageList , ImageConfiguration imageConfig ) { if ( imageList == null ) { return true ; } Set < String > imagesAllowed = new HashSet < > ( Arrays . asList ( imageList . split ( "\\s*,\\s*" ) ) ) ; return imagesAllowed . contains ( imageConfig . getName ( ) ) || imagesAllowed . contains ( imageConfig . getAlias ( ) ) ; } | Check if the provided image configuration matches the given |
20,755 | private static List < ImageConfiguration > filterImages ( String nameFilter , List < ImageConfiguration > imagesToFilter ) { List < ImageConfiguration > ret = new ArrayList < > ( ) ; for ( ImageConfiguration imageConfig : imagesToFilter ) { if ( matchesConfiguredImages ( nameFilter , imageConfig ) ) { ret . add ( imageConfig ) ; } } return ret ; } | list of image names which should be used |
20,756 | private static List < ImageConfiguration > resolveConfiguration ( Resolver imageResolver , List < ImageConfiguration > unresolvedImages ) { List < ImageConfiguration > ret = new ArrayList < > ( ) ; if ( unresolvedImages != null ) { for ( ImageConfiguration image : unresolvedImages ) { ret . addAll ( imageResolver . resolve ( image ) ) ; } verifyImageNames ( ret ) ; } return ret ; } | Resolve and initialize external configuration |
20,757 | private static void verifyImageNames ( List < ImageConfiguration > ret ) { for ( ImageConfiguration config : ret ) { if ( config . getName ( ) == null ) { throw new IllegalArgumentException ( "Configuration error: <image> must have a non-null <name>" ) ; } } } | Extract authentication information |
20,758 | public void callPluginGoal ( String fullGoal ) throws MojoFailureException , MojoExecutionException { String [ ] parts = splitGoalSpec ( fullGoal ) ; Plugin plugin = project . getPlugin ( parts [ 0 ] ) ; String goal = parts [ 1 ] ; if ( plugin == null ) { throw new MojoFailureException ( "No goal " + fullGoal + " found in pom.xml" ) ; } try { String executionId = null ; if ( goal != null && goal . length ( ) > 0 && goal . indexOf ( '#' ) > - 1 ) { int pos = goal . indexOf ( '#' ) ; executionId = goal . substring ( pos + 1 ) ; goal = goal . substring ( 0 , pos ) ; } PluginDescriptor pluginDescriptor = getPluginDescriptor ( project , plugin ) ; MojoDescriptor mojoDescriptor = pluginDescriptor . getMojo ( goal ) ; if ( mojoDescriptor == null ) { throw new MojoExecutionException ( "Could not find goal '" + goal + "' in plugin " + plugin . getGroupId ( ) + ":" + plugin . getArtifactId ( ) + ":" + plugin . getVersion ( ) ) ; } MojoExecution exec = getMojoExecution ( executionId , mojoDescriptor ) ; pluginManager . executeMojo ( session , exec ) ; } catch ( Exception e ) { throw new MojoExecutionException ( "Unable to execute mojo" , e ) ; } } | Call another goal after restart has finished |
20,759 | public File write ( File destDir ) throws IOException { File target = new File ( destDir , "Dockerfile" ) ; FileUtils . fileWrite ( target , content ( ) ) ; return target ; } | Create a DockerFile in the given directory |
20,760 | private String createKeyValue ( String key , String value ) { StringBuilder sb = new StringBuilder ( ) ; sb . append ( key ) . append ( '=' ) ; if ( value == null || value . isEmpty ( ) ) { return sb . append ( "\"\"" ) . toString ( ) ; } StringBuilder valBuf = new StringBuilder ( ) ; boolean toBeQuoted = false ; for ( int i = 0 ; i < value . length ( ) ; ++ i ) { char c = value . charAt ( i ) ; switch ( c ) { case '"' : case '\n' : case '\\' : valBuf . append ( '\\' ) ; case ' ' : toBeQuoted = true ; default : valBuf . append ( c ) ; } } if ( toBeQuoted ) { sb . append ( '"' ) . append ( valBuf . toString ( ) ) . append ( '"' ) ; } else { sb . append ( value ) ; } return sb . toString ( ) ; } | Escape any slashes quotes and newlines int the value . If any escaping occurred quote the value . |
20,761 | public DockerFileBuilder run ( List < String > runCmds ) { if ( runCmds != null ) { for ( String cmd : runCmds ) { if ( ! StringUtils . isEmpty ( cmd ) ) { this . runCmds . add ( cmd ) ; } } } return this ; } | Adds the RUN Commands within the build image section |
20,762 | public static Collection < Container > getContainersToStop ( final ImageConfiguration image , final String defaultContainerNamePattern , final Date buildTimestamp , final Collection < Container > containers ) { String containerNamePattern = extractContainerNamePattern ( image , defaultContainerNamePattern ) ; if ( ! containerNamePattern . contains ( INDEX_PLACEHOLDER ) ) { return containers ; } final String partiallyApplied = replacePlaceholders ( containerNamePattern , image . getName ( ) , image . getAlias ( ) , buildTimestamp ) ; return keepOnlyLastIndexedContainer ( containers , partiallyApplied ) ; } | Keep only the entry with the higest index if an indexed naming scheme for container has been chosen . |
20,763 | public void pushImages ( Collection < ImageConfiguration > imageConfigs , int retries , RegistryConfig registryConfig , boolean skipTag ) throws DockerAccessException , MojoExecutionException { for ( ImageConfiguration imageConfig : imageConfigs ) { BuildImageConfiguration buildConfig = imageConfig . getBuildConfiguration ( ) ; String name = imageConfig . getName ( ) ; if ( buildConfig != null ) { String configuredRegistry = EnvUtil . firstRegistryOf ( new ImageName ( imageConfig . getName ( ) ) . getRegistry ( ) , imageConfig . getRegistry ( ) , registryConfig . getRegistry ( ) ) ; AuthConfig authConfig = createAuthConfig ( true , new ImageName ( name ) . getUser ( ) , configuredRegistry , registryConfig ) ; long start = System . currentTimeMillis ( ) ; docker . pushImage ( name , authConfig , configuredRegistry , retries ) ; log . info ( "Pushed %s in %s" , name , EnvUtil . formatDurationTill ( start ) ) ; if ( ! skipTag ) { for ( String tag : imageConfig . getBuildConfiguration ( ) . getTags ( ) ) { if ( tag != null ) { docker . pushImage ( new ImageName ( name , tag ) . getFullName ( ) , authConfig , configuredRegistry , retries ) ; } } } } } } | Push a set of images to a registry |
20,764 | private void initDockerFileFile ( Logger log ) { if ( ( dockerFile != null || dockerFileDir != null ) && dockerArchive != null ) { throw new IllegalArgumentException ( "Both <dockerFile> (<dockerFileDir>) and <dockerArchive> are set. " + "Only one of them can be specified." ) ; } dockerFileFile = findDockerFileFile ( log ) ; if ( dockerArchive != null ) { dockerArchiveFile = new File ( dockerArchive ) ; } } | Initialize the dockerfile location and the build mode |
20,765 | private File createBuildTarBall ( BuildDirs buildDirs , List < ArchiverCustomizer > archiverCustomizers , AssemblyConfiguration assemblyConfig , ArchiveCompression compression ) throws MojoExecutionException { File archive = new File ( buildDirs . getTemporaryRootDirectory ( ) , "docker-build." + compression . getFileSuffix ( ) ) ; try { TarArchiver archiver = createBuildArchiver ( buildDirs . getOutputDirectory ( ) , archive , assemblyConfig ) ; for ( ArchiverCustomizer customizer : archiverCustomizers ) { if ( customizer != null ) { archiver = customizer . customize ( archiver ) ; } } archiver . setCompression ( compression . getTarCompressionMethod ( ) ) ; archiver . createArchive ( ) ; return archive ; } catch ( NoSuchArchiverException e ) { throw new MojoExecutionException ( "No archiver for type 'tar' found" , e ) ; } catch ( IOException e ) { throw new MojoExecutionException ( "Cannot create archive " + archive , e ) ; } } | Create final tar - ball to be used for building the archive to send to the Docker daemon |
20,766 | private File ensureThatArtifactFileIsSet ( MavenProject project ) { Artifact artifact = project . getArtifact ( ) ; if ( artifact == null ) { return null ; } File oldFile = artifact . getFile ( ) ; if ( oldFile != null ) { return oldFile ; } Build build = project . getBuild ( ) ; if ( build == null ) { return null ; } String finalName = build . getFinalName ( ) ; String target = build . getDirectory ( ) ; if ( finalName == null || target == null ) { return null ; } File artifactFile = new File ( target , finalName + "." + project . getPackaging ( ) ) ; if ( artifactFile . exists ( ) && artifactFile . isFile ( ) ) { setArtifactFile ( project , artifactFile ) ; } return null ; } | warning with an error following . |
20,767 | public void addEntry ( File srcFile , File destFile ) { entries . add ( new Entry ( srcFile , destFile ) ) ; } | Add a entry to the list of assembly files which possible should be monitored |
20,768 | private List < Resolvable > resolve ( List < Resolvable > images ) { List < Resolvable > resolved = new ArrayList < > ( ) ; for ( Resolvable config : images ) { List < String > volumesOrLinks = extractDependentImagesFor ( config ) ; if ( volumesOrLinks == null ) { updateProcessedImages ( config ) ; resolved . add ( config ) ; } else { secondPass . add ( config ) ; } } return secondPass . size ( ) > 0 ? resolveRemaining ( resolved ) : resolved ; } | an appropriate container which can be linked into the image |
20,769 | public File createChangedFilesArchive ( List < AssemblyFiles . Entry > entries , File assemblyDir , String imageName , MojoParameters mojoParameters ) throws MojoExecutionException { return dockerAssemblyManager . createChangedFilesArchive ( entries , assemblyDir , imageName , mojoParameters ) ; } | Create an tar archive from a set of assembly files . Only files which changed since the last call are included . |
20,770 | public ContainerNetworkingConfig aliases ( NetworkConfig config ) { JsonObject endPoints = new JsonObject ( ) ; endPoints . add ( "Aliases" , JsonFactory . newJsonArray ( config . getAliases ( ) ) ) ; JsonObject endpointConfigMap = new JsonObject ( ) ; endpointConfigMap . add ( config . getCustomNetwork ( ) , endPoints ) ; networkingConfig . add ( "EndpointsConfig" , endpointConfigMap ) ; return this ; } | Add networking aliases to a custom network |
20,771 | public void buildImage ( ImageConfiguration imageConfig , ImagePullManager imagePullManager , BuildContext buildContext ) throws DockerAccessException , MojoExecutionException { if ( imagePullManager != null ) { autoPullBaseImage ( imageConfig , imagePullManager , buildContext ) ; } buildImage ( imageConfig , buildContext . getMojoParameters ( ) , checkForNocache ( imageConfig ) , addBuildArgs ( buildContext ) ) ; } | Pull the base image if needed and run the build . |
20,772 | protected void buildImage ( ImageConfiguration imageConfig , MojoParameters params , boolean noCache , Map < String , String > buildArgs ) throws DockerAccessException , MojoExecutionException { String imageName = imageConfig . getName ( ) ; ImageName . validate ( imageName ) ; BuildImageConfiguration buildConfig = imageConfig . getBuildConfiguration ( ) ; String oldImageId = null ; CleanupMode cleanupMode = buildConfig . cleanupMode ( ) ; if ( cleanupMode . isRemove ( ) ) { oldImageId = queryService . getImageId ( imageName ) ; } if ( buildConfig . getDockerArchive ( ) != null ) { File tarArchive = buildConfig . getAbsoluteDockerTarPath ( params ) ; String archiveImageName = getArchiveImageName ( buildConfig , tarArchive ) ; long time = System . currentTimeMillis ( ) ; docker . loadImage ( imageName , tarArchive ) ; log . info ( "%s: Loaded tarball in %s" , buildConfig . getDockerArchive ( ) , EnvUtil . formatDurationTill ( time ) ) ; if ( archiveImageName != null && ! archiveImageName . equals ( imageName ) ) { docker . tag ( archiveImageName , imageName , true ) ; } return ; } long time = System . currentTimeMillis ( ) ; File dockerArchive = archiveService . createArchive ( imageName , buildConfig , params , log ) ; log . info ( "%s: Created %s in %s" , imageConfig . getDescription ( ) , dockerArchive . getName ( ) , EnvUtil . formatDurationTill ( time ) ) ; Map < String , String > mergedBuildMap = prepareBuildArgs ( buildArgs , buildConfig ) ; BuildOptions opts = new BuildOptions ( buildConfig . getBuildOptions ( ) ) . dockerfile ( getDockerfileName ( buildConfig ) ) . forceRemove ( cleanupMode . isRemove ( ) ) . noCache ( noCache ) . cacheFrom ( buildConfig . getCacheFrom ( ) ) . buildArgs ( mergedBuildMap ) ; String newImageId = doBuildImage ( imageName , dockerArchive , opts ) ; log . info ( "%s: Built image %s" , imageConfig . getDescription ( ) , newImageId ) ; if ( oldImageId != null && ! oldImageId . equals ( newImageId ) ) { try { docker . removeImage ( oldImageId , true ) ; log . info ( "%s: Removed old image %s" , imageConfig . getDescription ( ) , oldImageId ) ; } catch ( DockerAccessException exp ) { if ( cleanupMode == CleanupMode . TRY_TO_REMOVE ) { log . warn ( "%s: %s (old image)%s" , imageConfig . getDescription ( ) , exp . getMessage ( ) , ( exp . getCause ( ) != null ? " [" + exp . getCause ( ) . getMessage ( ) + "]" : "" ) ) ; } else { throw exp ; } } } } | Build an image |
20,773 | public void stopContainer ( String containerId , ImageConfiguration imageConfig , boolean keepContainer , boolean removeVolumes ) throws DockerAccessException , ExecException { ContainerTracker . ContainerShutdownDescriptor descriptor = new ContainerTracker . ContainerShutdownDescriptor ( imageConfig , containerId ) ; shutdown ( descriptor , keepContainer , removeVolumes ) ; } | Stop a container immediately by id . |
20,774 | public void stopPreviouslyStartedContainer ( String containerId , boolean keepContainer , boolean removeVolumes ) throws DockerAccessException , ExecException { ContainerTracker . ContainerShutdownDescriptor descriptor = tracker . removeContainer ( containerId ) ; if ( descriptor != null ) { shutdown ( descriptor , keepContainer , removeVolumes ) ; } } | Lookup up whether a certain has been already started and registered . If so stop it |
20,775 | public void stopStartedContainers ( boolean keepContainer , boolean removeVolumes , boolean removeCustomNetworks , GavLabel gavLabel ) throws DockerAccessException , ExecException { Set < Network > networksToRemove = new HashSet < > ( ) ; for ( ContainerTracker . ContainerShutdownDescriptor descriptor : tracker . removeShutdownDescriptors ( gavLabel ) ) { collectCustomNetworks ( networksToRemove , descriptor , removeCustomNetworks ) ; shutdown ( descriptor , keepContainer , removeVolumes ) ; } removeCustomNetworks ( networksToRemove ) ; } | Stop all registered container |
20,776 | public List < StartOrderResolver . Resolvable > getImagesConfigsInOrder ( QueryService queryService , List < ImageConfiguration > images ) { return StartOrderResolver . resolve ( queryService , convertToResolvables ( images ) ) ; } | Get the proper order for images to start |
20,777 | public PortMapping createPortMapping ( RunImageConfiguration runConfig , Properties properties ) { try { return new PortMapping ( runConfig . getPorts ( ) , properties ) ; } catch ( IllegalArgumentException exp ) { throw new IllegalArgumentException ( "Cannot parse port mapping" , exp ) ; } } | Create port mapping for a specific configuration as it can be used when creating containers |
20,778 | public void addShutdownHookForStoppingContainers ( final boolean keepContainer , final boolean removeVolumes , final boolean removeCustomNetworks ) { Runtime . getRuntime ( ) . addShutdownHook ( new Thread ( ) { public void run ( ) { try { stopStartedContainers ( keepContainer , removeVolumes , removeCustomNetworks , null ) ; } catch ( DockerAccessException | ExecException e ) { log . error ( "Error while stopping containers: %s" , e . getMessage ( ) ) ; } } } ) ; } | Add a shutdown hook in order to stop all registered containers |
20,779 | public List < String > createVolumesAsPerVolumeBinds ( ServiceHub hub , List < String > binds , List < VolumeConfiguration > volumes ) throws DockerAccessException { Map < String , Integer > indexMap = new HashMap < > ( ) ; List < String > volumesCreated = new ArrayList < > ( ) ; for ( int index = 0 ; index < volumes . size ( ) ; index ++ ) { indexMap . put ( volumes . get ( index ) . getName ( ) , index ) ; } for ( String bind : binds ) { if ( bind . contains ( ":" ) ) { String name = bind . substring ( 0 , bind . indexOf ( ':' ) ) ; Integer volumeConfigIndex = indexMap . get ( name ) ; if ( volumeConfigIndex != null ) { VolumeConfiguration volumeConfig = volumes . get ( volumeConfigIndex ) ; hub . getVolumeService ( ) . createVolume ( volumeConfig ) ; volumesCreated . add ( volumeConfig . getName ( ) ) ; } } } return volumesCreated ; } | Creates a Volume if a volume is referred to during startup in bind mount mapping and a VolumeConfiguration exists |
20,780 | public static boolean canConnectUnixSocket ( File path ) { try ( UnixSocketChannel channel = UnixSocketChannel . open ( ) ) { return channel . connect ( new UnixSocketAddress ( path ) ) ; } catch ( IOException e ) { return false ; } } | Check whether we can connect to a local Unix socket |
20,781 | private static Map < String , String > getOrderedHeadersToSign ( Header [ ] headers ) { Map < String , String > unique = new TreeMap < > ( ) ; for ( Header header : headers ) { String key = header . getName ( ) . toLowerCase ( Locale . US ) . trim ( ) ; if ( key . equals ( "connection" ) ) { continue ; } String value = header . getValue ( ) ; if ( value == null ) { value = "" ; } else { value = value . trim ( ) . replaceAll ( "\\s+" , " " ) ; } String prior = unique . get ( key ) ; if ( prior != null ) { if ( prior . length ( ) > 0 ) { value = prior + ',' + value ; } unique . put ( key , value ) ; } else { unique . put ( key , value ) ; } } return unique ; } | Get the ordered map of headers to sign . |
20,782 | private static String canonicalHeaders ( Map < String , String > headers ) { StringBuilder canonical = new StringBuilder ( ) ; for ( Map . Entry < String , String > header : headers . entrySet ( ) ) { canonical . append ( header . getKey ( ) ) . append ( ':' ) . append ( header . getValue ( ) ) . append ( '\n' ) ; } return canonical . toString ( ) ; } | Create canonical header set . The headers are ordered by name . |
20,783 | public void updateProperties ( Map < String , Container . PortBinding > dockerObtainedDynamicBindings ) { for ( Map . Entry < String , Container . PortBinding > entry : dockerObtainedDynamicBindings . entrySet ( ) ) { String variable = entry . getKey ( ) ; Container . PortBinding portBinding = entry . getValue ( ) ; if ( portBinding != null ) { update ( hostPortVariableMap , specToHostPortVariableMap . get ( variable ) , portBinding . getHostPort ( ) ) ; String hostIp = portBinding . getHostIp ( ) ; if ( "0.0.0.0" . equals ( hostIp ) ) { hostIp = projProperties . getProperty ( "docker.host.address" ) ; } update ( hostIpVariableMap , specToHostIpVariableMap . get ( variable ) , hostIp ) ; } } updateDynamicProperties ( hostPortVariableMap ) ; updateDynamicProperties ( hostIpVariableMap ) ; } | Update variable - to - port mappings with dynamically obtained ports and host ips . This should only be called once after this dynamically allocated parts has been be obtained . |
20,784 | JsonObject toDockerPortBindingsJson ( ) { Map < String , Integer > portMap = getContainerPortToHostPortMap ( ) ; if ( ! portMap . isEmpty ( ) ) { JsonObject portBindings = new JsonObject ( ) ; Map < String , String > bindToMap = getBindToHostMap ( ) ; for ( Map . Entry < String , Integer > entry : portMap . entrySet ( ) ) { String containerPortSpec = entry . getKey ( ) ; Integer hostPort = entry . getValue ( ) ; JsonObject o = new JsonObject ( ) ; o . addProperty ( "HostPort" , hostPort != null ? hostPort . toString ( ) : "" ) ; if ( bindToMap . containsKey ( containerPortSpec ) ) { o . addProperty ( "HostIp" , bindToMap . get ( containerPortSpec ) ) ; } JsonArray array = new JsonArray ( ) ; array . add ( o ) ; portBindings . add ( containerPortSpec , array ) ; } return portBindings ; } else { return null ; } } | Create a JSON specification which can be used to in a Docker API request as the PortBindings part for creating container . |
20,785 | public JsonArray toJson ( ) { Map < String , Integer > portMap = getContainerPortToHostPortMap ( ) ; if ( portMap . isEmpty ( ) ) { return null ; } JsonArray ret = new JsonArray ( ) ; Map < String , String > bindToMap = getBindToHostMap ( ) ; for ( Map . Entry < String , Integer > entry : portMap . entrySet ( ) ) { JsonObject mapping = new JsonObject ( ) ; String containerPortSpec = entry . getKey ( ) ; Matcher matcher = PROTOCOL_SPLIT_PATTERN . matcher ( entry . getKey ( ) ) ; if ( ! matcher . matches ( ) ) { throw new IllegalStateException ( "Internal error: " + entry . getKey ( ) + " doesn't contain protocol part and doesn't match " + PROTOCOL_SPLIT_PATTERN ) ; } mapping . addProperty ( "containerPort" , Integer . parseInt ( matcher . group ( 1 ) ) ) ; if ( matcher . group ( 2 ) != null ) { mapping . addProperty ( "protocol" , matcher . group ( 2 ) ) ; } Integer hostPort = entry . getValue ( ) ; if ( hostPort != null ) { mapping . addProperty ( "hostPort" , hostPort ) ; } if ( bindToMap . containsKey ( containerPortSpec ) ) { mapping . addProperty ( "hostIP" , bindToMap . get ( containerPortSpec ) ) ; } ret . add ( mapping ) ; } return ret ; } | Return the content of the mapping as an array with all specifications as given |
20,786 | private Integer getPortFromProjectOrSystemProperty ( String var ) { String sysProp = System . getProperty ( var ) ; if ( sysProp != null ) { return getAsIntOrNull ( sysProp ) ; } if ( projProperties . containsKey ( var ) ) { return getAsIntOrNull ( projProperties . getProperty ( var ) ) ; } return null ; } | First check system properties then the variables given |
20,787 | public AssemblyFiles getAssemblyFiles ( MavenSession session ) { AssemblyFiles ret = new AssemblyFiles ( new File ( getDestFile ( ) . getParentFile ( ) , assemblyName ) ) ; for ( Addition addition : added ) { Object resource = addition . resource ; File target = new File ( ret . getAssemblyDirectory ( ) , addition . destination ) ; if ( resource instanceof File && addition . destination != null ) { addFileEntry ( ret , session , ( File ) resource , target ) ; } else if ( resource instanceof PlexusIoFileResource ) { addFileEntry ( ret , session , ( ( PlexusIoFileResource ) resource ) . getFile ( ) , target ) ; } else if ( resource instanceof FileSet ) { FileSet fs = ( FileSet ) resource ; DirectoryScanner ds = new DirectoryScanner ( ) ; File base = addition . directory ; ds . setBasedir ( base ) ; ds . setIncludes ( fs . getIncludes ( ) ) ; ds . setExcludes ( fs . getExcludes ( ) ) ; ds . setCaseSensitive ( fs . isCaseSensitive ( ) ) ; ds . scan ( ) ; for ( String f : ds . getIncludedFiles ( ) ) { File source = new File ( base , f ) ; File subTarget = new File ( target , f ) ; addFileEntry ( ret , session , source , subTarget ) ; } } else { throw new IllegalStateException ( "Unknown resource type " + resource . getClass ( ) + ": " + resource ) ; } } return ret ; } | Get all files depicted by this assembly . |
20,788 | private Artifact getArtifactFromJar ( File jar ) { String type = extractFileType ( jar ) ; if ( type != null ) { try { ArrayList < Properties > options = new ArrayList < Properties > ( ) ; try ( ZipInputStream in = new ZipInputStream ( new FileInputStream ( jar ) ) ) { ZipEntry entry ; while ( ( entry = in . getNextEntry ( ) ) != null ) { if ( entry . getName ( ) . startsWith ( "META-INF/maven/" ) && entry . getName ( ) . endsWith ( "pom.properties" ) ) { byte [ ] buf = new byte [ 1024 ] ; int len ; ByteArrayOutputStream out = new ByteArrayOutputStream ( ) ; while ( ( len = in . read ( buf ) ) > 0 ) { out . write ( buf , 0 , len ) ; } Properties properties = new Properties ( ) ; properties . load ( new ByteArrayInputStream ( out . toByteArray ( ) ) ) ; options . add ( properties ) ; } } } if ( options . size ( ) == 1 ) { return getArtifactFromPomProperties ( type , options . get ( 0 ) ) ; } else { log . warn ( "Found %d pom.properties in %s" , options . size ( ) , jar ) ; } } catch ( IOException e ) { log . warn ( "IO Exception while examining %s for maven coordinates: %s. Ignoring for watching ..." , jar , e . getMessage ( ) ) ; } } return null ; } | look into a jar file and check for pom . properties . The first pom . properties found are returned . |
20,789 | private void logRemoveResponse ( JsonArray logElements ) { for ( int i = 0 ; i < logElements . size ( ) ; i ++ ) { JsonObject entry = logElements . get ( i ) . getAsJsonObject ( ) ; for ( Object key : entry . keySet ( ) ) { log . debug ( "%s: %s" , key , entry . get ( key . toString ( ) ) ) ; } } } | Callback for processing response chunks |
20,790 | private AuthConfig extendedAuthentication ( AuthConfig standardAuthConfig , String registry ) throws IOException , MojoExecutionException { EcrExtendedAuth ecr = new EcrExtendedAuth ( log , registry ) ; if ( ecr . isAwsRegistry ( ) ) { return ecr . extendedAuth ( standardAuthConfig ) ; } return standardAuthConfig ; } | Try various extended authentication method . Currently only supports amazon ECR |
20,791 | private AuthConfig parseOpenShiftConfig ( ) { Map kubeConfig = DockerFileUtil . readKubeConfig ( ) ; if ( kubeConfig == null ) { return null ; } String currentContextName = ( String ) kubeConfig . get ( "current-context" ) ; if ( currentContextName == null ) { return null ; } for ( Map contextMap : ( List < Map > ) kubeConfig . get ( "contexts" ) ) { if ( currentContextName . equals ( contextMap . get ( "name" ) ) ) { return parseContext ( kubeConfig , ( Map ) contextMap . get ( "context" ) ) ; } } return null ; } | Parse OpenShift config to get credentials but return null if not found |
20,792 | public Container getMandatoryContainer ( String containerIdOrName ) throws DockerAccessException { Container container = getContainer ( containerIdOrName ) ; if ( container == null ) { throw new DockerAccessException ( "Cannot find container %s" , containerIdOrName ) ; } return container ; } | Get container by id |
20,793 | public Network getNetworkByName ( final String networkName ) throws DockerAccessException { for ( Network el : docker . listNetworks ( ) ) { if ( networkName . equals ( el . getName ( ) ) ) { return el ; } } return null ; } | Get a network for a given network name . |
20,794 | public List < Container > getContainersForImage ( final String image , final boolean all ) throws DockerAccessException { return docker . getContainersForImage ( image , all ) ; } | Get all containers which are build from an image . By default only the last containers are considered but this can be tuned with a global parameters . |
20,795 | public void fetchLogs ( ) { try { callback . open ( ) ; this . request = getLogRequest ( false ) ; final HttpResponse response = client . execute ( request ) ; parseResponse ( response ) ; } catch ( LogCallback . DoneException e ) { } catch ( IOException exp ) { callback . error ( exp . getMessage ( ) ) ; } finally { callback . close ( ) ; } } | Get logs and feed a callback with the content |
20,796 | public void run ( ) { try { callback . open ( ) ; this . request = getLogRequest ( true ) ; final HttpResponse response = client . execute ( request ) ; parseResponse ( response ) ; } catch ( LogCallback . DoneException e ) { } catch ( IOException e ) { callback . error ( "IO Error while requesting logs: " + e + " " + Thread . currentThread ( ) . getName ( ) ) ; } finally { callback . close ( ) ; } } | Fetch log asynchronously as stream and follow stream |
20,797 | private FixedStringSearchInterpolator mainProjectInterpolator ( MavenProject mainProject ) { if ( mainProject != null ) { return FixedStringSearchInterpolator . create ( new org . codehaus . plexus . interpolation . fixed . PrefixedObjectValueSource ( InterpolationConstants . PROJECT_PREFIXES , mainProject , true ) , new org . codehaus . plexus . interpolation . fixed . PrefixedPropertiesValueSource ( InterpolationConstants . PROJECT_PROPERTIES_PREFIXES , mainProject . getProperties ( ) , true ) ) ; } else { return FixedStringSearchInterpolator . empty ( ) ; } } | Taken from AbstractAssemblyMojo |
20,798 | public static String convertImageNamePattern ( String pattern ) { final String REGEX_PREFIX = "%regex[" , ANT_PREFIX = "%ant[" , PATTERN_SUFFIX = "]" ; if ( pattern . startsWith ( REGEX_PREFIX ) && pattern . endsWith ( PATTERN_SUFFIX ) ) { return pattern . substring ( REGEX_PREFIX . length ( ) , pattern . length ( ) - PATTERN_SUFFIX . length ( ) ) ; } if ( pattern . startsWith ( ANT_PREFIX ) && pattern . endsWith ( PATTERN_SUFFIX ) ) { pattern = pattern . substring ( ANT_PREFIX . length ( ) , pattern . length ( ) - PATTERN_SUFFIX . length ( ) ) ; } String [ ] parts = pattern . split ( "((?=[/:?*])|(?<=[/:?*]))" ) ; Matcher matcher = Pattern . compile ( "[A-Za-z0-9-]+" ) . matcher ( "" ) ; StringBuilder builder = new StringBuilder ( "^" ) ; for ( int i = 0 ; i < parts . length ; ++ i ) { if ( "?" . equals ( parts [ i ] ) ) { builder . append ( "[^/:]" ) ; } else if ( "*" . equals ( parts [ i ] ) ) { if ( i + 1 < parts . length && "*" . equals ( parts [ i + 1 ] ) ) { builder . append ( "([^:]|:(?=.*:))*" ) ; ++ i ; if ( i + 1 < parts . length && "/" . equals ( parts [ i + 1 ] ) ) { builder . append ( "(?<![^/])" ) ; ++ i ; } } else { builder . append ( "([^/:]|:(?=.*:))*" ) ; } } else if ( "/" . equals ( parts [ i ] ) || ":" . equals ( parts [ i ] ) || matcher . reset ( parts [ i ] ) . matches ( ) ) { builder . append ( parts [ i ] ) ; } else if ( parts [ i ] . length ( ) > 0 ) { builder . append ( Pattern . quote ( parts [ i ] ) ) ; } } builder . append ( "$" ) ; return builder . toString ( ) ; } | Accepts an Ant - ish or regular expression pattern and compiles to a regular expression . |
20,799 | void sign ( HttpRequest request , AuthConfig credentials , Date signingTime ) { AwsSigner4Request sr = new AwsSigner4Request ( region , service , request , signingTime ) ; if ( ! request . containsHeader ( "X-Amz-Date" ) ) { request . addHeader ( "X-Amz-Date" , sr . getSigningDateTime ( ) ) ; } request . addHeader ( "Authorization" , task4 ( sr , credentials ) ) ; final String securityToken = credentials . getAuth ( ) ; if ( StringUtils . isNotEmpty ( securityToken ) ) { request . addHeader ( "X-Amz-Security-Token" , securityToken ) ; } } | Sign a request . Add the headers that authenticate the request . |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.