id
int32
0
165k
repo
stringlengths
7
58
path
stringlengths
12
218
func_name
stringlengths
3
140
original_string
stringlengths
73
34.1k
language
stringclasses
1 value
code
stringlengths
73
34.1k
code_tokens
list
docstring
stringlengths
3
16k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
105
339
28,100
apache/incubator-heron
heron/spi/src/java/org/apache/heron/spi/packing/PackingPlan.java
PackingPlan.getComponentCounts
public Map<String, Integer> getComponentCounts() { Map<String, Integer> componentCounts = new HashMap<>(); for (ContainerPlan containerPlan : getContainers()) { for (InstancePlan instancePlan : containerPlan.getInstances()) { Integer count = 0; if (componentCounts.containsKey(instancePlan.getComponentName())) { count = componentCounts.get(instancePlan.getComponentName()); } componentCounts.put(instancePlan.getComponentName(), ++count); } } return componentCounts; }
java
public Map<String, Integer> getComponentCounts() { Map<String, Integer> componentCounts = new HashMap<>(); for (ContainerPlan containerPlan : getContainers()) { for (InstancePlan instancePlan : containerPlan.getInstances()) { Integer count = 0; if (componentCounts.containsKey(instancePlan.getComponentName())) { count = componentCounts.get(instancePlan.getComponentName()); } componentCounts.put(instancePlan.getComponentName(), ++count); } } return componentCounts; }
[ "public", "Map", "<", "String", ",", "Integer", ">", "getComponentCounts", "(", ")", "{", "Map", "<", "String", ",", "Integer", ">", "componentCounts", "=", "new", "HashMap", "<>", "(", ")", ";", "for", "(", "ContainerPlan", "containerPlan", ":", "getContainers", "(", ")", ")", "{", "for", "(", "InstancePlan", "instancePlan", ":", "containerPlan", ".", "getInstances", "(", ")", ")", "{", "Integer", "count", "=", "0", ";", "if", "(", "componentCounts", ".", "containsKey", "(", "instancePlan", ".", "getComponentName", "(", ")", ")", ")", "{", "count", "=", "componentCounts", ".", "get", "(", "instancePlan", ".", "getComponentName", "(", ")", ")", ";", "}", "componentCounts", ".", "put", "(", "instancePlan", ".", "getComponentName", "(", ")", ",", "++", "count", ")", ";", "}", "}", "return", "componentCounts", ";", "}" ]
Return a map containing the count of all of the components, keyed by name
[ "Return", "a", "map", "containing", "the", "count", "of", "all", "of", "the", "components", "keyed", "by", "name" ]
776abe2b5a45b93a0eb957fd65cbc149d901a92a
https://github.com/apache/incubator-heron/blob/776abe2b5a45b93a0eb957fd65cbc149d901a92a/heron/spi/src/java/org/apache/heron/spi/packing/PackingPlan.java#L110-L122
28,101
apache/incubator-heron
heron/spi/src/java/org/apache/heron/spi/packing/PackingPlan.java
PackingPlan.getComponentRamDistribution
public String getComponentRamDistribution() { // Generate a map with the minimal RAM size for each component Map<String, ByteAmount> ramMap = new HashMap<>(); for (ContainerPlan containerPlan : this.getContainers()) { for (InstancePlan instancePlan : containerPlan.getInstances()) { ByteAmount newRam = instancePlan.getResource().getRam(); ByteAmount currentRam = ramMap.get(instancePlan.getComponentName()); if (currentRam == null || currentRam.asBytes() > newRam.asBytes()) { ramMap.put(instancePlan.getComponentName(), newRam); } } } // Convert it into a formatted String StringBuilder ramMapBuilder = new StringBuilder(); for (String component : ramMap.keySet()) { ramMapBuilder.append(String.format("%s:%d,", component, ramMap.get(component).asBytes())); } // Remove the duplicated "," at the end ramMapBuilder.deleteCharAt(ramMapBuilder.length() - 1); return ramMapBuilder.toString(); }
java
public String getComponentRamDistribution() { // Generate a map with the minimal RAM size for each component Map<String, ByteAmount> ramMap = new HashMap<>(); for (ContainerPlan containerPlan : this.getContainers()) { for (InstancePlan instancePlan : containerPlan.getInstances()) { ByteAmount newRam = instancePlan.getResource().getRam(); ByteAmount currentRam = ramMap.get(instancePlan.getComponentName()); if (currentRam == null || currentRam.asBytes() > newRam.asBytes()) { ramMap.put(instancePlan.getComponentName(), newRam); } } } // Convert it into a formatted String StringBuilder ramMapBuilder = new StringBuilder(); for (String component : ramMap.keySet()) { ramMapBuilder.append(String.format("%s:%d,", component, ramMap.get(component).asBytes())); } // Remove the duplicated "," at the end ramMapBuilder.deleteCharAt(ramMapBuilder.length() - 1); return ramMapBuilder.toString(); }
[ "public", "String", "getComponentRamDistribution", "(", ")", "{", "// Generate a map with the minimal RAM size for each component", "Map", "<", "String", ",", "ByteAmount", ">", "ramMap", "=", "new", "HashMap", "<>", "(", ")", ";", "for", "(", "ContainerPlan", "containerPlan", ":", "this", ".", "getContainers", "(", ")", ")", "{", "for", "(", "InstancePlan", "instancePlan", ":", "containerPlan", ".", "getInstances", "(", ")", ")", "{", "ByteAmount", "newRam", "=", "instancePlan", ".", "getResource", "(", ")", ".", "getRam", "(", ")", ";", "ByteAmount", "currentRam", "=", "ramMap", ".", "get", "(", "instancePlan", ".", "getComponentName", "(", ")", ")", ";", "if", "(", "currentRam", "==", "null", "||", "currentRam", ".", "asBytes", "(", ")", ">", "newRam", ".", "asBytes", "(", ")", ")", "{", "ramMap", ".", "put", "(", "instancePlan", ".", "getComponentName", "(", ")", ",", "newRam", ")", ";", "}", "}", "}", "// Convert it into a formatted String", "StringBuilder", "ramMapBuilder", "=", "new", "StringBuilder", "(", ")", ";", "for", "(", "String", "component", ":", "ramMap", ".", "keySet", "(", ")", ")", "{", "ramMapBuilder", ".", "append", "(", "String", ".", "format", "(", "\"%s:%d,\"", ",", "component", ",", "ramMap", ".", "get", "(", "component", ")", ".", "asBytes", "(", ")", ")", ")", ";", "}", "// Remove the duplicated \",\" at the end", "ramMapBuilder", ".", "deleteCharAt", "(", "ramMapBuilder", ".", "length", "(", ")", "-", "1", ")", ";", "return", "ramMapBuilder", ".", "toString", "(", ")", ";", "}" ]
Get the formatted String describing component RAM distribution from PackingPlan, used by executor @return String describing component RAM distribution
[ "Get", "the", "formatted", "String", "describing", "component", "RAM", "distribution", "from", "PackingPlan", "used", "by", "executor" ]
776abe2b5a45b93a0eb957fd65cbc149d901a92a
https://github.com/apache/incubator-heron/blob/776abe2b5a45b93a0eb957fd65cbc149d901a92a/heron/spi/src/java/org/apache/heron/spi/packing/PackingPlan.java#L130-L152
28,102
linkedin/dexmaker
dexmaker/src/main/java/com/android/dx/DexMaker.java
DexMaker.declare
public Code declare(MethodId<?, ?> method, int flags) { TypeDeclaration typeDeclaration = getTypeDeclaration(method.declaringType); if (typeDeclaration.methods.containsKey(method)) { throw new IllegalStateException("already declared: " + method); } int supportedFlags = Modifier.PUBLIC | Modifier.PRIVATE | Modifier.PROTECTED | Modifier.STATIC | Modifier.FINAL | Modifier.SYNCHRONIZED | AccessFlags.ACC_SYNTHETIC | AccessFlags.ACC_BRIDGE; if ((flags & ~supportedFlags) != 0) { throw new IllegalArgumentException("Unexpected flag: " + Integer.toHexString(flags)); } // replace the SYNCHRONIZED flag with the DECLARED_SYNCHRONIZED flag if ((flags & Modifier.SYNCHRONIZED) != 0) { flags = (flags & ~Modifier.SYNCHRONIZED) | AccessFlags.ACC_DECLARED_SYNCHRONIZED; } if (method.isConstructor() || method.isStaticInitializer()) { flags |= ACC_CONSTRUCTOR; } MethodDeclaration methodDeclaration = new MethodDeclaration(method, flags); typeDeclaration.methods.put(method, methodDeclaration); return methodDeclaration.code; }
java
public Code declare(MethodId<?, ?> method, int flags) { TypeDeclaration typeDeclaration = getTypeDeclaration(method.declaringType); if (typeDeclaration.methods.containsKey(method)) { throw new IllegalStateException("already declared: " + method); } int supportedFlags = Modifier.PUBLIC | Modifier.PRIVATE | Modifier.PROTECTED | Modifier.STATIC | Modifier.FINAL | Modifier.SYNCHRONIZED | AccessFlags.ACC_SYNTHETIC | AccessFlags.ACC_BRIDGE; if ((flags & ~supportedFlags) != 0) { throw new IllegalArgumentException("Unexpected flag: " + Integer.toHexString(flags)); } // replace the SYNCHRONIZED flag with the DECLARED_SYNCHRONIZED flag if ((flags & Modifier.SYNCHRONIZED) != 0) { flags = (flags & ~Modifier.SYNCHRONIZED) | AccessFlags.ACC_DECLARED_SYNCHRONIZED; } if (method.isConstructor() || method.isStaticInitializer()) { flags |= ACC_CONSTRUCTOR; } MethodDeclaration methodDeclaration = new MethodDeclaration(method, flags); typeDeclaration.methods.put(method, methodDeclaration); return methodDeclaration.code; }
[ "public", "Code", "declare", "(", "MethodId", "<", "?", ",", "?", ">", "method", ",", "int", "flags", ")", "{", "TypeDeclaration", "typeDeclaration", "=", "getTypeDeclaration", "(", "method", ".", "declaringType", ")", ";", "if", "(", "typeDeclaration", ".", "methods", ".", "containsKey", "(", "method", ")", ")", "{", "throw", "new", "IllegalStateException", "(", "\"already declared: \"", "+", "method", ")", ";", "}", "int", "supportedFlags", "=", "Modifier", ".", "PUBLIC", "|", "Modifier", ".", "PRIVATE", "|", "Modifier", ".", "PROTECTED", "|", "Modifier", ".", "STATIC", "|", "Modifier", ".", "FINAL", "|", "Modifier", ".", "SYNCHRONIZED", "|", "AccessFlags", ".", "ACC_SYNTHETIC", "|", "AccessFlags", ".", "ACC_BRIDGE", ";", "if", "(", "(", "flags", "&", "~", "supportedFlags", ")", "!=", "0", ")", "{", "throw", "new", "IllegalArgumentException", "(", "\"Unexpected flag: \"", "+", "Integer", ".", "toHexString", "(", "flags", ")", ")", ";", "}", "// replace the SYNCHRONIZED flag with the DECLARED_SYNCHRONIZED flag", "if", "(", "(", "flags", "&", "Modifier", ".", "SYNCHRONIZED", ")", "!=", "0", ")", "{", "flags", "=", "(", "flags", "&", "~", "Modifier", ".", "SYNCHRONIZED", ")", "|", "AccessFlags", ".", "ACC_DECLARED_SYNCHRONIZED", ";", "}", "if", "(", "method", ".", "isConstructor", "(", ")", "||", "method", ".", "isStaticInitializer", "(", ")", ")", "{", "flags", "|=", "ACC_CONSTRUCTOR", ";", "}", "MethodDeclaration", "methodDeclaration", "=", "new", "MethodDeclaration", "(", "method", ",", "flags", ")", ";", "typeDeclaration", ".", "methods", ".", "put", "(", "method", ",", "methodDeclaration", ")", ";", "return", "methodDeclaration", ".", "code", ";", "}" ]
Declares a method or constructor. @param flags a bitwise combination of {@link Modifier#PUBLIC}, {@link Modifier#PRIVATE}, {@link Modifier#PROTECTED}, {@link Modifier#STATIC}, {@link Modifier#FINAL} and {@link Modifier#SYNCHRONIZED}. <p><strong>Warning:</strong> the {@link Modifier#SYNCHRONIZED} flag is insufficient to generate a synchronized method. You must also use {@link Code#monitorEnter} and {@link Code#monitorExit} to acquire a monitor.
[ "Declares", "a", "method", "or", "constructor", "." ]
c58ffebcbb2564c7d1fa6fb58b48f351c330296d
https://github.com/linkedin/dexmaker/blob/c58ffebcbb2564c7d1fa6fb58b48f351c330296d/dexmaker/src/main/java/com/android/dx/DexMaker.java#L262-L288
28,103
linkedin/dexmaker
dexmaker/src/main/java/com/android/dx/DexMaker.java
DexMaker.declare
public void declare(FieldId<?, ?> fieldId, int flags, Object staticValue) { TypeDeclaration typeDeclaration = getTypeDeclaration(fieldId.declaringType); if (typeDeclaration.fields.containsKey(fieldId)) { throw new IllegalStateException("already declared: " + fieldId); } int supportedFlags = Modifier.PUBLIC | Modifier.PRIVATE | Modifier.PROTECTED | Modifier.STATIC | Modifier.FINAL | Modifier.VOLATILE | Modifier.TRANSIENT | AccessFlags.ACC_SYNTHETIC; if ((flags & ~supportedFlags) != 0) { throw new IllegalArgumentException("Unexpected flag: " + Integer.toHexString(flags)); } if ((flags & Modifier.STATIC) == 0 && staticValue != null) { throw new IllegalArgumentException("staticValue is non-null, but field is not static"); } FieldDeclaration fieldDeclaration = new FieldDeclaration(fieldId, flags, staticValue); typeDeclaration.fields.put(fieldId, fieldDeclaration); }
java
public void declare(FieldId<?, ?> fieldId, int flags, Object staticValue) { TypeDeclaration typeDeclaration = getTypeDeclaration(fieldId.declaringType); if (typeDeclaration.fields.containsKey(fieldId)) { throw new IllegalStateException("already declared: " + fieldId); } int supportedFlags = Modifier.PUBLIC | Modifier.PRIVATE | Modifier.PROTECTED | Modifier.STATIC | Modifier.FINAL | Modifier.VOLATILE | Modifier.TRANSIENT | AccessFlags.ACC_SYNTHETIC; if ((flags & ~supportedFlags) != 0) { throw new IllegalArgumentException("Unexpected flag: " + Integer.toHexString(flags)); } if ((flags & Modifier.STATIC) == 0 && staticValue != null) { throw new IllegalArgumentException("staticValue is non-null, but field is not static"); } FieldDeclaration fieldDeclaration = new FieldDeclaration(fieldId, flags, staticValue); typeDeclaration.fields.put(fieldId, fieldDeclaration); }
[ "public", "void", "declare", "(", "FieldId", "<", "?", ",", "?", ">", "fieldId", ",", "int", "flags", ",", "Object", "staticValue", ")", "{", "TypeDeclaration", "typeDeclaration", "=", "getTypeDeclaration", "(", "fieldId", ".", "declaringType", ")", ";", "if", "(", "typeDeclaration", ".", "fields", ".", "containsKey", "(", "fieldId", ")", ")", "{", "throw", "new", "IllegalStateException", "(", "\"already declared: \"", "+", "fieldId", ")", ";", "}", "int", "supportedFlags", "=", "Modifier", ".", "PUBLIC", "|", "Modifier", ".", "PRIVATE", "|", "Modifier", ".", "PROTECTED", "|", "Modifier", ".", "STATIC", "|", "Modifier", ".", "FINAL", "|", "Modifier", ".", "VOLATILE", "|", "Modifier", ".", "TRANSIENT", "|", "AccessFlags", ".", "ACC_SYNTHETIC", ";", "if", "(", "(", "flags", "&", "~", "supportedFlags", ")", "!=", "0", ")", "{", "throw", "new", "IllegalArgumentException", "(", "\"Unexpected flag: \"", "+", "Integer", ".", "toHexString", "(", "flags", ")", ")", ";", "}", "if", "(", "(", "flags", "&", "Modifier", ".", "STATIC", ")", "==", "0", "&&", "staticValue", "!=", "null", ")", "{", "throw", "new", "IllegalArgumentException", "(", "\"staticValue is non-null, but field is not static\"", ")", ";", "}", "FieldDeclaration", "fieldDeclaration", "=", "new", "FieldDeclaration", "(", "fieldId", ",", "flags", ",", "staticValue", ")", ";", "typeDeclaration", ".", "fields", ".", "put", "(", "fieldId", ",", "fieldDeclaration", ")", ";", "}" ]
Declares a field. @param flags a bitwise combination of {@link Modifier#PUBLIC}, {@link Modifier#PRIVATE}, {@link Modifier#PROTECTED}, {@link Modifier#STATIC}, {@link Modifier#FINAL}, {@link Modifier#VOLATILE}, and {@link Modifier#TRANSIENT}. @param staticValue a constant representing the initial value for the static field, possibly null. This must be null if this field is non-static.
[ "Declares", "a", "field", "." ]
c58ffebcbb2564c7d1fa6fb58b48f351c330296d
https://github.com/linkedin/dexmaker/blob/c58ffebcbb2564c7d1fa6fb58b48f351c330296d/dexmaker/src/main/java/com/android/dx/DexMaker.java#L301-L321
28,104
linkedin/dexmaker
dexmaker/src/main/java/com/android/dx/DexMaker.java
DexMaker.generate
public byte[] generate() { if (outputDex == null) { DexOptions options = new DexOptions(); options.minSdkVersion = DexFormat.API_NO_EXTENDED_OPCODES; outputDex = new DexFile(options); } for (TypeDeclaration typeDeclaration : types.values()) { outputDex.add(typeDeclaration.toClassDefItem()); } try { return outputDex.toDex(null, false); } catch (IOException e) { throw new RuntimeException(e); } }
java
public byte[] generate() { if (outputDex == null) { DexOptions options = new DexOptions(); options.minSdkVersion = DexFormat.API_NO_EXTENDED_OPCODES; outputDex = new DexFile(options); } for (TypeDeclaration typeDeclaration : types.values()) { outputDex.add(typeDeclaration.toClassDefItem()); } try { return outputDex.toDex(null, false); } catch (IOException e) { throw new RuntimeException(e); } }
[ "public", "byte", "[", "]", "generate", "(", ")", "{", "if", "(", "outputDex", "==", "null", ")", "{", "DexOptions", "options", "=", "new", "DexOptions", "(", ")", ";", "options", ".", "minSdkVersion", "=", "DexFormat", ".", "API_NO_EXTENDED_OPCODES", ";", "outputDex", "=", "new", "DexFile", "(", "options", ")", ";", "}", "for", "(", "TypeDeclaration", "typeDeclaration", ":", "types", ".", "values", "(", ")", ")", "{", "outputDex", ".", "add", "(", "typeDeclaration", ".", "toClassDefItem", "(", ")", ")", ";", "}", "try", "{", "return", "outputDex", ".", "toDex", "(", "null", ",", "false", ")", ";", "}", "catch", "(", "IOException", "e", ")", "{", "throw", "new", "RuntimeException", "(", "e", ")", ";", "}", "}" ]
Generates a dex file and returns its bytes.
[ "Generates", "a", "dex", "file", "and", "returns", "its", "bytes", "." ]
c58ffebcbb2564c7d1fa6fb58b48f351c330296d
https://github.com/linkedin/dexmaker/blob/c58ffebcbb2564c7d1fa6fb58b48f351c330296d/dexmaker/src/main/java/com/android/dx/DexMaker.java#L326-L342
28,105
linkedin/dexmaker
dexmaker/src/main/java/com/android/dx/DexMaker.java
DexMaker.generateFileName
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"; }
java
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"; }
[ "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.
[ "parent", "class", "types", "." ]
c58ffebcbb2564c7d1fa6fb58b48f351c330296d
https://github.com/linkedin/dexmaker/blob/c58ffebcbb2564c7d1fa6fb58b48f351c330296d/dexmaker/src/main/java/com/android/dx/DexMaker.java#L346-L371
28,106
linkedin/dexmaker
dexmaker/src/main/java/com/android/dx/DexMaker.java
DexMaker.generateAndLoad
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()); // Check that the file exists. If it does, return a DexClassLoader and skip all // the dex bytecode generation. if (result.exists()) { return generateClassLoader(result, dexCache, parent); } byte[] dex = generate(); /* * This implementation currently dumps the dex to the filesystem. It * jars the emitted .dex for the benefit of Gingerbread and earlier * devices, which can't load .dex files directly. * * TODO: load the dex from memory where supported. */ 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); }
java
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()); // Check that the file exists. If it does, return a DexClassLoader and skip all // the dex bytecode generation. if (result.exists()) { return generateClassLoader(result, dexCache, parent); } byte[] dex = generate(); /* * This implementation currently dumps the dex to the filesystem. It * jars the emitted .dex for the benefit of Gingerbread and earlier * devices, which can't load .dex files directly. * * TODO: load the dex from memory where supported. */ 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); }
[ "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", "(", ")", ")", ";", "// Check that the file exists. If it does, return a DexClassLoader and skip all", "// the dex bytecode generation.", "if", "(", "result", ".", "exists", "(", ")", ")", "{", "return", "generateClassLoader", "(", "result", ",", "dexCache", ",", "parent", ")", ";", "}", "byte", "[", "]", "dex", "=", "generate", "(", ")", ";", "/*\n * This implementation currently dumps the dex to the filesystem. It\n * jars the emitted .dex for the benefit of Gingerbread and earlier\n * devices, which can't load .dex files directly.\n *\n * TODO: load the dex from memory where supported.\n */", "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. <h3>Picking a dex cache directory</h3> The {@code dexCache} should be an application-private directory. If you pass a world-writable directory like {@code /sdcard} a malicious app could inject code into your process. Most applications should use this: <pre> {@code File dexCache = getApplicationContext().getDir("dx", Context.MODE_PRIVATE); }</pre> If the {@code dexCache} is null, this method will consult the {@code dexmaker.dexcache} system property. If that exists, it will be used for the dex cache. If it doesn't exist, this method will attempt to guess the application's private data directory as a last resort. If that fails, this method will fail with an unchecked exception. You can avoid the exception by either providing a non-null value or setting the system property. @param parent the parent ClassLoader to be used when loading our generated types (if set, overrides {@link #setSharedClassLoader(ClassLoader) shared class loader}. @param dexCache the destination directory where generated and optimized dex files will be written. If null, this class will try to guess the application's private data dir.
[ "Generates", "a", "dex", "file", "and", "loads", "its", "types", "into", "the", "current", "process", "." ]
c58ffebcbb2564c7d1fa6fb58b48f351c330296d
https://github.com/linkedin/dexmaker/blob/c58ffebcbb2564c7d1fa6fb58b48f351c330296d/dexmaker/src/main/java/com/android/dx/DexMaker.java#L500-L539
28,107
linkedin/dexmaker
dexmaker-mockito-inline-dispatcher/src/main/java/com/android/dx/mockito/inline/MockMethodDispatcher.java
MockMethodDispatcher.get
public static MockMethodDispatcher get(String identifier, Object instance) { if (instance == INSTANCE) { // Avoid endless loop if ConcurrentHashMap was redefined to check for being a mock. return null; } else { return INSTANCE.get(identifier); } }
java
public static MockMethodDispatcher get(String identifier, Object instance) { if (instance == INSTANCE) { // Avoid endless loop if ConcurrentHashMap was redefined to check for being a mock. return null; } else { return INSTANCE.get(identifier); } }
[ "public", "static", "MockMethodDispatcher", "get", "(", "String", "identifier", ",", "Object", "instance", ")", "{", "if", "(", "instance", "==", "INSTANCE", ")", "{", "// Avoid endless loop if ConcurrentHashMap was redefined to check for being a mock.", "return", "null", ";", "}", "else", "{", "return", "INSTANCE", ".", "get", "(", "identifier", ")", ";", "}", "}" ]
Get the dispatcher for a identifier. @param identifier identifier of the dispatcher @param instance instance that might be mocked @return dispatcher for the identifier
[ "Get", "the", "dispatcher", "for", "a", "identifier", "." ]
c58ffebcbb2564c7d1fa6fb58b48f351c330296d
https://github.com/linkedin/dexmaker/blob/c58ffebcbb2564c7d1fa6fb58b48f351c330296d/dexmaker-mockito-inline-dispatcher/src/main/java/com/android/dx/mockito/inline/MockMethodDispatcher.java#L45-L52
28,108
linkedin/dexmaker
dexmaker-mockito-inline-dispatcher/src/main/java/com/android/dx/mockito/inline/MockMethodDispatcher.java
MockMethodDispatcher.set
public static void set(String identifier, Object advice) { INSTANCE.putIfAbsent(identifier, new MockMethodDispatcher(advice)); }
java
public static void set(String identifier, Object advice) { INSTANCE.putIfAbsent(identifier, new MockMethodDispatcher(advice)); }
[ "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 @param identifier a unique identifier @param advice advice the dispatcher should call
[ "Set", "up", "a", "new", "advice", "to", "receive", "calls", "for", "an", "identifier" ]
c58ffebcbb2564c7d1fa6fb58b48f351c330296d
https://github.com/linkedin/dexmaker/blob/c58ffebcbb2564c7d1fa6fb58b48f351c330296d/dexmaker-mockito-inline-dispatcher/src/main/java/com/android/dx/mockito/inline/MockMethodDispatcher.java#L69-L71
28,109
linkedin/dexmaker
dexmaker-mockito-inline/src/main/java/com/android/dx/mockito/inline/MockMethodAdvice.java
MockMethodAdvice.isOverridden
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; }
java
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; }
[ "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. @param instance mocked instance @param origin method that might be overridden @return {@code true} iff the method is overridden
[ "Check", "if", "a", "method", "is", "overridden", "." ]
c58ffebcbb2564c7d1fa6fb58b48f351c330296d
https://github.com/linkedin/dexmaker/blob/c58ffebcbb2564c7d1fa6fb58b48f351c330296d/dexmaker-mockito-inline/src/main/java/com/android/dx/mockito/inline/MockMethodAdvice.java#L239-L252
28,110
linkedin/dexmaker
dexmaker-mockito-inline-extended/src/main/java/com/android/dx/mockito/inline/extended/StaticMockitoSessionBuilder.java
StaticMockitoSessionBuilder.spyStatic
@UnstableApi public <T> StaticMockitoSessionBuilder spyStatic(Class<T> clazz) { staticMockings.add(new StaticMocking<>(clazz, () -> Mockito.mock(clazz, withSettings() .defaultAnswer(CALLS_REAL_METHODS)))); return this; }
java
@UnstableApi public <T> StaticMockitoSessionBuilder spyStatic(Class<T> clazz) { staticMockings.add(new StaticMocking<>(clazz, () -> Mockito.mock(clazz, withSettings() .defaultAnswer(CALLS_REAL_METHODS)))); return this; }
[ "@", "UnstableApi", "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. @param clazz The class to set up static spying for @return This builder
[ "Sets", "up", "spying", "for", "static", "methods", "of", "a", "class", "." ]
c58ffebcbb2564c7d1fa6fb58b48f351c330296d
https://github.com/linkedin/dexmaker/blob/c58ffebcbb2564c7d1fa6fb58b48f351c330296d/dexmaker-mockito-inline-extended/src/main/java/com/android/dx/mockito/inline/extended/StaticMockitoSessionBuilder.java#L101-L106
28,111
linkedin/dexmaker
dexmaker/src/main/java/com/android/dx/Constants.java
Constants.getConstant
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); } }
java
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); } }
[ "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. @param value null, a boxed primitive, String, Class, or TypeId.
[ "Returns", "a", "rop", "constant", "for", "the", "specified", "value", "." ]
c58ffebcbb2564c7d1fa6fb58b48f351c330296d
https://github.com/linkedin/dexmaker/blob/c58ffebcbb2564c7d1fa6fb58b48f351c330296d/dexmaker/src/main/java/com/android/dx/Constants.java#L43-L71
28,112
linkedin/dexmaker
dexmaker/src/main/java/com/android/dx/stock/ProxyBuilder.java
ProxyBuilder.build
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) { // Should not be thrown, generated class is not abstract. throw new AssertionError(e); } catch (IllegalAccessException e) { // Should not be thrown, the generated constructor is accessible. throw new AssertionError(e); } catch (InvocationTargetException e) { // Thrown when the base class constructor throws an exception. throw launderCause(e); } setInvocationHandler(result, handler); return result; }
java
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) { // Should not be thrown, generated class is not abstract. throw new AssertionError(e); } catch (IllegalAccessException e) { // Should not be thrown, the generated constructor is accessible. throw new AssertionError(e); } catch (InvocationTargetException e) { // Thrown when the base class constructor throws an exception. throw launderCause(e); } setInvocationHandler(result, handler); return result; }
[ "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", ")", "{", "// Should not be thrown, generated class is not abstract.", "throw", "new", "AssertionError", "(", "e", ")", ";", "}", "catch", "(", "IllegalAccessException", "e", ")", "{", "// Should not be thrown, the generated constructor is accessible.", "throw", "new", "AssertionError", "(", "e", ")", ";", "}", "catch", "(", "InvocationTargetException", "e", ")", "{", "// Thrown when the base class constructor throws an exception.", "throw", "launderCause", "(", "e", ")", ";", "}", "setInvocationHandler", "(", "result", ",", "handler", ")", ";", "return", "result", ";", "}" ]
Create a new instance of the class to proxy. @throws UnsupportedOperationException if the class we are trying to create a proxy for is not accessible. @throws IOException if an exception occurred writing to the {@code dexCache} directory. @throws UndeclaredThrowableException if the constructor for the base class to proxy throws a declared exception during construction. @throws IllegalArgumentException if the handler is null, if the constructor argument types do not match the constructor argument values, or if no such constructor exists.
[ "Create", "a", "new", "instance", "of", "the", "class", "to", "proxy", "." ]
c58ffebcbb2564c7d1fa6fb58b48f351c330296d
https://github.com/linkedin/dexmaker/blob/c58ffebcbb2564c7d1fa6fb58b48f351c330296d/dexmaker/src/main/java/com/android/dx/stock/ProxyBuilder.java#L232-L259
28,113
linkedin/dexmaker
dexmaker/src/main/java/com/android/dx/stock/ProxyBuilder.java
ProxyBuilder.superMethodName
private static String superMethodName(Method method) { String returnType = method.getReturnType().getName(); return "super$" + method.getName() + "$" + returnType.replace('.', '_').replace('[', '_').replace(';', '_'); }
java
private static String superMethodName(Method method) { String returnType = method.getReturnType().getName(); return "super$" + method.getName() + "$" + returnType.replace('.', '_').replace('[', '_').replace(';', '_'); }
[ "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.
[ "The", "super", "method", "must", "include", "the", "return", "type", "otherwise", "its", "ambiguous", "for", "methods", "with", "covariant", "return", "types", "." ]
c58ffebcbb2564c7d1fa6fb58b48f351c330296d
https://github.com/linkedin/dexmaker/blob/c58ffebcbb2564c7d1fa6fb58b48f351c330296d/dexmaker/src/main/java/com/android/dx/stock/ProxyBuilder.java#L674-L678
28,114
linkedin/dexmaker
dexmaker/src/main/java/com/android/dx/stock/ProxyBuilder.java
ProxyBuilder.getConstructorsToOverwrite
@SuppressWarnings("unchecked") private static <T> Constructor<T>[] getConstructorsToOverwrite(Class<T> clazz) { return (Constructor<T>[]) clazz.getDeclaredConstructors(); }
java
@SuppressWarnings("unchecked") private static <T> Constructor<T>[] getConstructorsToOverwrite(Class<T> clazz) { return (Constructor<T>[]) clazz.getDeclaredConstructors(); }
[ "@", "SuppressWarnings", "(", "\"unchecked\"", ")", "private", "static", "<", "T", ">", "Constructor", "<", "T", ">", "[", "]", "getConstructorsToOverwrite", "(", "Class", "<", "T", ">", "clazz", ")", "{", "return", "(", "Constructor", "<", "T", ">", "[", "]", ")", "clazz", ".", "getDeclaredConstructors", "(", ")", ";", "}" ]
hence this cast is safe.
[ "hence", "this", "cast", "is", "safe", "." ]
c58ffebcbb2564c7d1fa6fb58b48f351c330296d
https://github.com/linkedin/dexmaker/blob/c58ffebcbb2564c7d1fa6fb58b48f351c330296d/dexmaker/src/main/java/com/android/dx/stock/ProxyBuilder.java#L717-L720
28,115
linkedin/dexmaker
dexmaker/src/main/java/com/android/dx/stock/ProxyBuilder.java
ProxyBuilder.generateCodeForReturnStatement
@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); } }
java
@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); } }
[ "@", "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.
[ "This", "one", "is", "tricky", "to", "fix", "I", "gave", "up", "." ]
c58ffebcbb2564c7d1fa6fb58b48f351c330296d
https://github.com/linkedin/dexmaker/blob/c58ffebcbb2564c7d1fa6fb58b48f351c330296d/dexmaker/src/main/java/com/android/dx/stock/ProxyBuilder.java#L839-L853
28,116
linkedin/dexmaker
dexmaker-mockito-inline-extended/src/main/java/com/android/dx/mockito/inline/extended/ExtendedMockito.java
ExtendedMockito.staticMockMarker
@UnstableApi @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; }
java
@UnstableApi @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; }
[ "@", "UnstableApi", "@", "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. @param clazz The class object the marker should be crated for @return A marker object. This should not be used directly. It can only be passed into other ExtendedMockito methods. @see #inOrder(Object...) @see #clearInvocations(Object...) @see #ignoreStubs(Object...) @see #mockingDetails(Object) @see #reset(Object[]) @see #verifyNoMoreInteractions(Object...) @see #verifyZeroInteractions(Object...)
[ "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", "." ]
c58ffebcbb2564c7d1fa6fb58b48f351c330296d
https://github.com/linkedin/dexmaker/blob/c58ffebcbb2564c7d1fa6fb58b48f351c330296d/dexmaker-mockito-inline-extended/src/main/java/com/android/dx/mockito/inline/extended/ExtendedMockito.java#L161-L172
28,117
linkedin/dexmaker
dexmaker-mockito-inline-extended/src/main/java/com/android/dx/mockito/inline/extended/ExtendedMockito.java
ExtendedMockito.spyOn
@UnstableApi @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(); } }
java
@UnstableApi @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(); } }
[ "@", "UnstableApi", "@", "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. <p>This does <u>not</u> clone the existing objects. If a method is stubbed on a spy converted by this method all references to the already existing object will be affected by the stubbing. @param toSpy The existing object to convert into a spy
[ "Make", "an", "existing", "object", "a", "spy", "." ]
c58ffebcbb2564c7d1fa6fb58b48f351c330296d
https://github.com/linkedin/dexmaker/blob/c58ffebcbb2564c7d1fa6fb58b48f351c330296d/dexmaker-mockito-inline-extended/src/main/java/com/android/dx/mockito/inline/extended/ExtendedMockito.java#L207-L221
28,118
linkedin/dexmaker
dexmaker-mockito-inline-extended/src/main/java/com/android/dx/mockito/inline/extended/ExtendedMockito.java
ExtendedMockito.verifyInt
@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<>(); /* Set up callback that is triggered when the next static method is called on this thread. * * This is necessary as we don't know which class the method will be called on. Once the * call is intercepted this will * 1. Remove all matchers (e.g. eq(), any()) from the matcher stack * 2. Call verify on the marker for the class * 3. Add the markers back to the stack */ onMethodCallDuringVerification.set((clazz, verifiedMethod) -> { // TODO: O holy reflection! Let's hope we can integrate this better. try { ArgumentMatcherStorageImpl argMatcherStorage = (ArgumentMatcherStorageImpl) mockingProgress().getArgumentMatcherStorage(); List<LocalizedMatcher> matchers; // Matcher are called before verify, hence remove the from the storage 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); } // Add the matchers back after verify is called 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 { // Trigger the method call. This call will be intercepted and trigger the // onMethodCallDuringVerification callback. 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()) { // Make sure something was intercepted throw new IllegalArgumentException("Nothing was verified. Does the lambda call " + "a static method on a 'static' mock/spy ?"); } else if (verifications.size() > 1) { // A lambda might call several methods. In this case it is not clear what should // be verified. Hence throw an error. throw new IllegalArgumentException("Multiple intercepted calls on methods " + verifications); } } finally { onMethodCallDuringVerification.remove(); } }
java
@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<>(); /* Set up callback that is triggered when the next static method is called on this thread. * * This is necessary as we don't know which class the method will be called on. Once the * call is intercepted this will * 1. Remove all matchers (e.g. eq(), any()) from the matcher stack * 2. Call verify on the marker for the class * 3. Add the markers back to the stack */ onMethodCallDuringVerification.set((clazz, verifiedMethod) -> { // TODO: O holy reflection! Let's hope we can integrate this better. try { ArgumentMatcherStorageImpl argMatcherStorage = (ArgumentMatcherStorageImpl) mockingProgress().getArgumentMatcherStorage(); List<LocalizedMatcher> matchers; // Matcher are called before verify, hence remove the from the storage 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); } // Add the matchers back after verify is called 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 { // Trigger the method call. This call will be intercepted and trigger the // onMethodCallDuringVerification callback. 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()) { // Make sure something was intercepted throw new IllegalArgumentException("Nothing was verified. Does the lambda call " + "a static method on a 'static' mock/spy ?"); } else if (verifications.size() > 1) { // A lambda might call several methods. In this case it is not clear what should // be verified. Hence throw an error. throw new IllegalArgumentException("Multiple intercepted calls on methods " + verifications); } } finally { onMethodCallDuringVerification.remove(); } }
[ "@", "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", "<>", "(", ")", ";", "/* Set up callback that is triggered when the next static method is called on this thread.\n *\n * This is necessary as we don't know which class the method will be called on. Once the\n * call is intercepted this will\n * 1. Remove all matchers (e.g. eq(), any()) from the matcher stack\n * 2. Call verify on the marker for the class\n * 3. Add the markers back to the stack\n */", "onMethodCallDuringVerification", ".", "set", "(", "(", "clazz", ",", "verifiedMethod", ")", "->", "{", "// TODO: O holy reflection! Let's hope we can integrate this better.", "try", "{", "ArgumentMatcherStorageImpl", "argMatcherStorage", "=", "(", "ArgumentMatcherStorageImpl", ")", "mockingProgress", "(", ")", ".", "getArgumentMatcherStorage", "(", ")", ";", "List", "<", "LocalizedMatcher", ">", "matchers", ";", "// Matcher are called before verify, hence remove the from the storage", "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", ")", ";", "}", "// Add the matchers back after verify is called", "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", "{", "// Trigger the method call. This call will be intercepted and trigger the", "// onMethodCallDuringVerification callback.", "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", "(", ")", ")", "{", "// Make sure something was intercepted", "throw", "new", "IllegalArgumentException", "(", "\"Nothing was verified. Does the lambda call \"", "+", "\"a static method on a 'static' mock/spy ?\"", ")", ";", "}", "else", "if", "(", "verifications", ".", "size", "(", ")", ">", "1", ")", "{", "// A lambda might call several methods. In this case it is not clear what should", "// be verified. Hence throw an error.", "throw", "new", "IllegalArgumentException", "(", "\"Multiple intercepted calls on methods \"", "+", "verifications", ")", ";", "}", "}", "finally", "{", "onMethodCallDuringVerification", ".", "remove", "(", ")", ";", "}", "}" ]
Common implementation of verification of static method calls. @param method The static method call to be verified @param mode The verification mode @param instanceInOrder If set, the {@link StaticInOrder} object
[ "Common", "implementation", "of", "verification", "of", "static", "method", "calls", "." ]
c58ffebcbb2564c7d1fa6fb58b48f351c330296d
https://github.com/linkedin/dexmaker/blob/c58ffebcbb2564c7d1fa6fb58b48f351c330296d/dexmaker-mockito-inline-extended/src/main/java/com/android/dx/mockito/inline/extended/ExtendedMockito.java#L341-L425
28,119
linkedin/dexmaker
dexmaker-mockito-inline/src/main/java/com/android/dx/mockito/inline/InlineDexmakerMockMaker.java
InlineDexmakerMockMaker.getMethodsToProxy
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; }
java
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; }
[ "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. <p>Only abstract methods will need to get proxied as all other methods will get an entry hook. @param settings description of the current mocking process. @return methods to proxy.
[ "Get", "methods", "to", "proxy", "." ]
c58ffebcbb2564c7d1fa6fb58b48f351c330296d
https://github.com/linkedin/dexmaker/blob/c58ffebcbb2564c7d1fa6fb58b48f351c330296d/dexmaker-mockito-inline/src/main/java/com/android/dx/mockito/inline/InlineDexmakerMockMaker.java#L201-L242
28,120
linkedin/dexmaker
dexmaker/src/main/java/com/android/dx/AnnotationId.java
AnnotationId.get
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); }
java
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); }
[ "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. @param declaringType the type declaring the program element. @param type the annotation type. @param annotatedElement the program element type to be annotated. @return an annotation {@code AnnotationId<D,V>} instance.
[ "Construct", "an", "instance", ".", "It", "initially", "contains", "no", "elements", "." ]
c58ffebcbb2564c7d1fa6fb58b48f351c330296d
https://github.com/linkedin/dexmaker/blob/c58ffebcbb2564c7d1fa6fb58b48f351c330296d/dexmaker/src/main/java/com/android/dx/AnnotationId.java#L92-L102
28,121
linkedin/dexmaker
dexmaker/src/main/java/com/android/dx/AnnotationId.java
AnnotationId.set
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); }
java
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); }
[ "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. @param element {@code non-null;} the annotation element to be set.
[ "Set", "an", "annotation", "element", "of", "this", "instance", ".", "If", "there", "is", "a", "preexisting", "element", "with", "the", "same", "name", "it", "will", "be", "replaced", "by", "this", "method", "." ]
c58ffebcbb2564c7d1fa6fb58b48f351c330296d
https://github.com/linkedin/dexmaker/blob/c58ffebcbb2564c7d1fa6fb58b48f351c330296d/dexmaker/src/main/java/com/android/dx/AnnotationId.java#L111-L120
28,122
linkedin/dexmaker
dexmaker/src/main/java/com/android/dx/AnnotationId.java
AnnotationId.addToMethod
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 { // Generate CstType CstType cstType = CstType.intern(type.ropType); // Generate Annotation Annotation annotation = new Annotation(cstType, AnnotationVisibility.RUNTIME); // Add generated annotation Annotations annotations = new Annotations(); for (NameValuePair nvp : elements.values()) { annotation.add(nvp); } annotations.add(annotation); classDefItem.addMethodAnnotations(cstMethodRef, annotations, dexMaker.getDexFile()); } } }
java
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 { // Generate CstType CstType cstType = CstType.intern(type.ropType); // Generate Annotation Annotation annotation = new Annotation(cstType, AnnotationVisibility.RUNTIME); // Add generated annotation Annotations annotations = new Annotations(); for (NameValuePair nvp : elements.values()) { annotation.add(nvp); } annotations.add(annotation); classDefItem.addMethodAnnotations(cstMethodRef, annotations, dexMaker.getDexFile()); } } }
[ "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", "{", "// Generate CstType", "CstType", "cstType", "=", "CstType", ".", "intern", "(", "type", ".", "ropType", ")", ";", "// Generate Annotation", "Annotation", "annotation", "=", "new", "Annotation", "(", "cstType", ",", "AnnotationVisibility", ".", "RUNTIME", ")", ";", "// Add generated annotation", "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. @param dexMaker DexMaker instance. @param method Method to be added to.
[ "Add", "this", "annotation", "to", "a", "method", "." ]
c58ffebcbb2564c7d1fa6fb58b48f351c330296d
https://github.com/linkedin/dexmaker/blob/c58ffebcbb2564c7d1fa6fb58b48f351c330296d/dexmaker/src/main/java/com/android/dx/AnnotationId.java#L128-L162
28,123
linkedin/dexmaker
dexmaker/src/main/java/com/android/dx/Local.java
Local.initialize
int initialize(int nextAvailableRegister) { this.reg = nextAvailableRegister; this.spec = RegisterSpec.make(nextAvailableRegister, type.ropType); return size(); }
java
int initialize(int nextAvailableRegister) { this.reg = nextAvailableRegister; this.spec = RegisterSpec.make(nextAvailableRegister, type.ropType); return size(); }
[ "int", "initialize", "(", "int", "nextAvailableRegister", ")", "{", "this", ".", "reg", "=", "nextAvailableRegister", ";", "this", ".", "spec", "=", "RegisterSpec", ".", "make", "(", "nextAvailableRegister", ",", "type", ".", "ropType", ")", ";", "return", "size", "(", ")", ";", "}" ]
Assigns registers to this local. @return the number of registers required.
[ "Assigns", "registers", "to", "this", "local", "." ]
c58ffebcbb2564c7d1fa6fb58b48f351c330296d
https://github.com/linkedin/dexmaker/blob/c58ffebcbb2564c7d1fa6fb58b48f351c330296d/dexmaker/src/main/java/com/android/dx/Local.java#L44-L48
28,124
linkedin/dexmaker
dexmaker-mockito-inline/src/main/java/com/android/dx/mockito/inline/JvmtiAgent.java
JvmtiAgent.appendToBootstrapClassLoaderSearch
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()); }
java
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()); }
[ "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. @param jarStream stream of jar to be added
[ "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", "." ]
c58ffebcbb2564c7d1fa6fb58b48f351c330296d
https://github.com/linkedin/dexmaker/blob/c58ffebcbb2564c7d1fa6fb58b48f351c330296d/dexmaker-mockito-inline/src/main/java/com/android/dx/mockito/inline/JvmtiAgent.java#L85-L102
28,125
linkedin/dexmaker
dexmaker-mockito-inline-extended/src/main/java/com/android/dx/mockito/inline/extended/StaticMockitoSession.java
StaticMockitoSession.mockStatic
<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); }
java
<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); }
[ "<", "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. @param mocking Description and settings of the mocking @param <T> The class to mock
[ "Init", "mocking", "for", "a", "class", "." ]
c58ffebcbb2564c7d1fa6fb58b48f351c330296d
https://github.com/linkedin/dexmaker/blob/c58ffebcbb2564c7d1fa6fb58b48f351c330296d/dexmaker-mockito-inline-extended/src/main/java/com/android/dx/mockito/inline/extended/StaticMockitoSession.java#L91-L104
28,126
linkedin/dexmaker
dexmaker/src/main/java/com/android/dx/Code.java
Code.mark
public void mark(Label label) { adopt(label); if (label.marked) { throw new IllegalStateException("already marked"); } label.marked = true; if (currentLabel != null) { jump(label); // blocks must end with a branch, return or throw } currentLabel = label; }
java
public void mark(Label label) { adopt(label); if (label.marked) { throw new IllegalStateException("already marked"); } label.marked = true; if (currentLabel != null) { jump(label); // blocks must end with a branch, return or throw } currentLabel = label; }
[ "public", "void", "mark", "(", "Label", "label", ")", "{", "adopt", "(", "label", ")", ";", "if", "(", "label", ".", "marked", ")", "{", "throw", "new", "IllegalStateException", "(", "\"already marked\"", ")", ";", "}", "label", ".", "marked", "=", "true", ";", "if", "(", "currentLabel", "!=", "null", ")", "{", "jump", "(", "label", ")", ";", "// blocks must end with a branch, return or throw", "}", "currentLabel", "=", "label", ";", "}" ]
Start defining instructions for the named label.
[ "Start", "defining", "instructions", "for", "the", "named", "label", "." ]
c58ffebcbb2564c7d1fa6fb58b48f351c330296d
https://github.com/linkedin/dexmaker/blob/c58ffebcbb2564c7d1fa6fb58b48f351c330296d/dexmaker/src/main/java/com/android/dx/Code.java#L333-L343
28,127
linkedin/dexmaker
dexmaker/src/main/java/com/android/dx/Code.java
Code.splitCurrentLabel
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; }
java
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; }
[ "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. @param catchLabels an immutable list of catch labels
[ "Closes", "the", "current", "label", "and", "starts", "a", "new", "one", "." ]
c58ffebcbb2564c7d1fa6fb58b48f351c330296d
https://github.com/linkedin/dexmaker/blob/c58ffebcbb2564c7d1fa6fb58b48f351c330296d/dexmaker/src/main/java/com/android/dx/Code.java#L462-L470
28,128
linkedin/dexmaker
dexmaker/src/main/java/com/android/dx/Code.java
Code.cast
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())); } }
java
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())); } }
[ "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. <h3>Numeric Casts</h3> Converts a primitive to a different representation. Numeric casts may be lossy. For example, converting the double {@code 1.8d} to an integer yields {@code 1}, losing the fractional part. Converting the integer {@code 0x12345678} to a short yields {@code 0x5678}, losing the high bytes. The following numeric casts are supported: <p><table border="1" summary="Supported Numeric Casts"> <tr><th>From</th><th>To</th></tr> <tr><td>int</td><td>byte, char, short, long, float, double</td></tr> <tr><td>long</td><td>int, float, double</td></tr> <tr><td>float</td><td>int, long, double</td></tr> <tr><td>double</td><td>int, long, float</td></tr> </table> <p>For some primitive conversions it will be necessary to chain multiple cast operations. For example, to go from float to short one would first cast float to int and then int to short. <p>Numeric casts never throw {@link ClassCastException}. <h3>Type Casts</h3> Checks that a reference value is assignable to the target type. If it is assignable it is copied to the target local. If it is not assignable a {@link ClassCastException} is thrown.
[ "Performs", "either", "a", "numeric", "cast", "or", "a", "type", "cast", "." ]
c58ffebcbb2564c7d1fa6fb58b48f351c330296d
https://github.com/linkedin/dexmaker/blob/c58ffebcbb2564c7d1fa6fb58b48f351c330296d/dexmaker/src/main/java/com/android/dx/Code.java#L753-L762
28,129
linkedin/dexmaker
dexmaker/src/main/java/com/android/dx/Code.java
Code.toBasicBlocks
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; }
java
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; }
[ "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
[ "produce", "BasicBlocks", "for", "dex" ]
c58ffebcbb2564c7d1fa6fb58b48f351c330296d
https://github.com/linkedin/dexmaker/blob/c58ffebcbb2564c7d1fa6fb58b48f351c330296d/dexmaker/src/main/java/com/android/dx/Code.java#L875-L887
28,130
linkedin/dexmaker
dexmaker/src/main/java/com/android/dx/Code.java
Code.cleanUpLabels
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++; } } }
java
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++; } } }
[ "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.
[ "Removes", "empty", "labels", "and", "assigns", "IDs", "to", "non", "-", "empty", "labels", "." ]
c58ffebcbb2564c7d1fa6fb58b48f351c330296d
https://github.com/linkedin/dexmaker/blob/c58ffebcbb2564c7d1fa6fb58b48f351c330296d/dexmaker/src/main/java/com/android/dx/Code.java#L892-L903
28,131
yegor256/cactoos
src/main/java/org/cactoos/scalar/Checked.java
Checked.wrappedException
@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; }
java
@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; }
[ "@", "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. @param exp Exception @return E Wrapped exception
[ "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", "." ]
7d2366be99f8d93eecfca2941ac23d4337dc224e
https://github.com/yegor256/cactoos/blob/7d2366be99f8d93eecfca2941ac23d4337dc224e/src/main/java/org/cactoos/scalar/Checked.java#L98-L118
28,132
yegor256/cactoos
src/main/java/org/cactoos/io/TailOf.java
TailOf.copy
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(); }
java
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(); }
[ "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. @param buffer The buffer array @param response The response array @param read Number of bytes read in buffer @return Number of bytes in the response buffer
[ "Copy", "full", "buffer", "to", "response", "." ]
7d2366be99f8d93eecfca2941ac23d4337dc224e
https://github.com/yegor256/cactoos/blob/7d2366be99f8d93eecfca2941ac23d4337dc224e/src/main/java/org/cactoos/io/TailOf.java#L109-L115
28,133
yegor256/cactoos
src/main/java/org/cactoos/io/TailOf.java
TailOf.copyPartial
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; }
java
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; }
[ "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. @param buffer The buffer array @param response The response array @param num Number of bytes in response array from previous read @param read Number of bytes read in the buffer @return New count of bytes in the response array @checkstyle ParameterNumberCheck (3 lines)
[ "Copy", "buffer", "to", "response", "for", "read", "count", "smaller", "then", "buffer", "size", "." ]
7d2366be99f8d93eecfca2941ac23d4337dc224e
https://github.com/yegor256/cactoos/blob/7d2366be99f8d93eecfca2941ac23d4337dc224e/src/main/java/org/cactoos/io/TailOf.java#L126-L140
28,134
yegor256/cactoos
src/main/java/org/cactoos/scalar/ScalarWithFallback.java
ScalarWithFallback.fallback
@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 ); } }
java
@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 ); } }
[ "@", "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. @param exp The original exception @return Result of the most suitable fallback @throws Exception The original exception if no fallback found
[ "Finds", "the", "best", "fallback", "for", "the", "given", "exception", "type", "and", "apply", "it", "to", "the", "exception", "or", "throw", "the", "original", "error", "if", "no", "fallback", "found", "." ]
7d2366be99f8d93eecfca2941ac23d4337dc224e
https://github.com/yegor256/cactoos/blob/7d2366be99f8d93eecfca2941ac23d4337dc224e/src/main/java/org/cactoos/scalar/ScalarWithFallback.java#L89-L116
28,135
yegor256/cactoos
src/main/java/org/cactoos/io/WriterAsOutputStream.java
WriterAsOutputStream.next
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; }
java
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; }
[ "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. @param buffer The buffer @param offset Offset in the buffer @param length Maximum possible amount to take @return How much was taken @throws IOException If fails
[ "Write", "a", "portion", "from", "the", "buffer", "." ]
7d2366be99f8d93eecfca2941ac23d4337dc224e
https://github.com/yegor256/cactoos/blob/7d2366be99f8d93eecfca2941ac23d4337dc224e/src/main/java/org/cactoos/io/WriterAsOutputStream.java#L185-L208
28,136
yegor256/cactoos
src/main/java/org/cactoos/scalar/FallbackFrom.java
FallbackFrom.support
public Integer support(final Class<? extends Throwable> target) { return new MinOf( new Mapped<>( supported -> new InheritanceLevel(target, supported).value(), this.exceptions ) ).intValue(); }
java
public Integer support(final Class<? extends Throwable> target) { return new MinOf( new Mapped<>( supported -> new InheritanceLevel(target, supported).value(), this.exceptions ) ).intValue(); }
[ "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. @param target Exception type @return Level of support: greater or equals to 0 if the target is supported and {@link Integer#MIN_VALUE} otherwise @see InheritanceLevel
[ "Calculate", "level", "of", "support", "of", "the", "given", "exception", "type", "." ]
7d2366be99f8d93eecfca2941ac23d4337dc224e
https://github.com/yegor256/cactoos/blob/7d2366be99f8d93eecfca2941ac23d4337dc224e/src/main/java/org/cactoos/scalar/FallbackFrom.java#L85-L92
28,137
yegor256/cactoos
src/main/java/org/cactoos/scalar/InheritanceLevel.java
InheritanceLevel.calculateLevel
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; }
java
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; }
[ "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. @return Integer Level
[ "Calculates", "inheritance", "level", "." ]
7d2366be99f8d93eecfca2941ac23d4337dc224e
https://github.com/yegor256/cactoos/blob/7d2366be99f8d93eecfca2941ac23d4337dc224e/src/main/java/org/cactoos/scalar/InheritanceLevel.java#L84-L97
28,138
fabric8io/docker-maven-plugin
src/main/java/io/fabric8/maven/docker/util/EnvUtil.java
EnvUtil.convertTcpToHttpUrl
public static String convertTcpToHttpUrl(String connect) { String protocol = connect.contains(":" + DOCKER_HTTPS_PORT) ? "https:" : "http:"; return connect.replaceFirst("^tcp:", protocol); }
java
public static String convertTcpToHttpUrl(String connect) { String protocol = connect.contains(":" + DOCKER_HTTPS_PORT) ? "https:" : "http:"; return connect.replaceFirst("^tcp:", protocol); }
[ "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
[ "Convert", "docker", "host", "URL", "to", "an", "http", "URL" ]
70ce4f56125d8efb8ddcf2ad4dbb5d6e2c7642b3
https://github.com/fabric8io/docker-maven-plugin/blob/70ce4f56125d8efb8ddcf2ad4dbb5d6e2c7642b3/src/main/java/io/fabric8/maven/docker/util/EnvUtil.java#L43-L46
28,139
fabric8io/docker-maven-plugin
src/main/java/io/fabric8/maven/docker/util/EnvUtil.java
EnvUtil.greaterOrEqualsVersion
public static boolean greaterOrEqualsVersion(String versionA, String versionB) { String largerVersion = extractLargerVersion(versionA, versionB); return largerVersion != null && largerVersion.equals(versionA); }
java
public static boolean greaterOrEqualsVersion(String versionA, String versionB) { String largerVersion = extractLargerVersion(versionA, versionB); return largerVersion != null && largerVersion.equals(versionA); }
[ "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 @param versionA first version to check against @param versionB the second version @return true if versionA is greater or equals versionB, false otherwise
[ "Check", "whether", "the", "first", "given", "API", "version", "is", "larger", "or", "equals", "the", "second", "given", "version" ]
70ce4f56125d8efb8ddcf2ad4dbb5d6e2c7642b3
https://github.com/fabric8io/docker-maven-plugin/blob/70ce4f56125d8efb8ddcf2ad4dbb5d6e2c7642b3/src/main/java/io/fabric8/maven/docker/util/EnvUtil.java#L85-L88
28,140
fabric8io/docker-maven-plugin
src/main/java/io/fabric8/maven/docker/util/EnvUtil.java
EnvUtil.extractFromPropertiesAsMap
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; }
java
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; }
[ "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. NOTE: If key is "._combine" ({@link #PROPERTY_COMBINE_POLICY_SUFFIX)} it is ignored! This is reserved for combine policy tweaking. @param prefix prefix which specifies the part which should be extracted as map @param properties properties to extract from @return the extracted map or null if no such map exists
[ "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", "." ]
70ce4f56125d8efb8ddcf2ad4dbb5d6e2c7642b3
https://github.com/fabric8io/docker-maven-plugin/blob/70ce4f56125d8efb8ddcf2ad4dbb5d6e2c7642b3/src/main/java/io/fabric8/maven/docker/util/EnvUtil.java#L224-L240
28,141
fabric8io/docker-maven-plugin
src/main/java/io/fabric8/maven/docker/util/EnvUtil.java
EnvUtil.formatDurationTill
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(); }
java
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(); }
[ "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 Taken mostly from http://stackoverflow.com/a/5062810/207604 . Kudos to @dblevins @param start starting time (in milliseconds) @return time in seconds
[ "Calculate", "the", "duration", "between", "now", "and", "the", "given", "time" ]
70ce4f56125d8efb8ddcf2ad4dbb5d6e2c7642b3
https://github.com/fabric8io/docker-maven-plugin/blob/70ce4f56125d8efb8ddcf2ad4dbb5d6e2c7642b3/src/main/java/io/fabric8/maven/docker/util/EnvUtil.java#L324-L355
28,142
fabric8io/docker-maven-plugin
src/main/java/io/fabric8/maven/docker/util/EnvUtil.java
EnvUtil.firstRegistryOf
public static String firstRegistryOf(String ... checkFirst) { for (String registry : checkFirst) { if (registry != null) { return registry; } } // Check environment as last resort return System.getenv("DOCKER_REGISTRY"); }
java
public static String firstRegistryOf(String ... checkFirst) { for (String registry : checkFirst) { if (registry != null) { return registry; } } // Check environment as last resort return System.getenv("DOCKER_REGISTRY"); }
[ "public", "static", "String", "firstRegistryOf", "(", "String", "...", "checkFirst", ")", "{", "for", "(", "String", "registry", ":", "checkFirst", ")", "{", "if", "(", "registry", "!=", "null", ")", "{", "return", "registry", ";", "}", "}", "// Check environment as last resort", "return", "System", ".", "getenv", "(", "\"DOCKER_REGISTRY\"", ")", ";", "}" ]
Return the first non null registry given. Use the env var DOCKER_REGISTRY as final fallback @param checkFirst list of registries to check @return registry found or null if none.
[ "Return", "the", "first", "non", "null", "registry", "given", ".", "Use", "the", "env", "var", "DOCKER_REGISTRY", "as", "final", "fallback" ]
70ce4f56125d8efb8ddcf2ad4dbb5d6e2c7642b3
https://github.com/fabric8io/docker-maven-plugin/blob/70ce4f56125d8efb8ddcf2ad4dbb5d6e2c7642b3/src/main/java/io/fabric8/maven/docker/util/EnvUtil.java#L368-L376
28,143
fabric8io/docker-maven-plugin
src/main/java/io/fabric8/maven/docker/util/EnvUtil.java
EnvUtil.storeTimestamp
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); } }
java
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); } }
[ "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
[ "create", "a", "timestamp", "file", "holding", "time", "in", "epoch", "seconds" ]
70ce4f56125d8efb8ddcf2ad4dbb5d6e2c7642b3
https://github.com/fabric8io/docker-maven-plugin/blob/70ce4f56125d8efb8ddcf2ad4dbb5d6e2c7642b3/src/main/java/io/fabric8/maven/docker/util/EnvUtil.java#L404-L419
28,144
fabric8io/docker-maven-plugin
src/main/java/io/fabric8/maven/docker/access/KeyStoreUtil.java
KeyStoreUtil.createDockerKeyStore
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; }
java
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; }
[ "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 @param certPath directory holding the keys (key.pem) and certs (ca.pem, cert.pem) @return a keystore where the private key is secured with "docker" @throws IOException is reading of the the PEMs failed @throws GeneralSecurityException when the files in a wrong format
[ "Create", "a", "key", "stored", "holding", "certificates", "and", "secret", "keys", "from", "the", "given", "Docker", "key", "cert" ]
70ce4f56125d8efb8ddcf2ad4dbb5d6e2c7642b3
https://github.com/fabric8io/docker-maven-plugin/blob/70ce4f56125d8efb8ddcf2ad4dbb5d6e2c7642b3/src/main/java/io/fabric8/maven/docker/access/KeyStoreUtil.java#L39-L49
28,145
fabric8io/docker-maven-plugin
src/main/java/io/fabric8/maven/docker/access/ecr/EcrExtendedAuth.java
EcrExtendedAuth.extendedAuth
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"); }
java
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"); }
[ "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. @param localCredentials IAM id/secret @return ECR base64 encoded username:password @throws IOException @throws MojoExecutionException
[ "Perform", "extended", "authentication", ".", "Use", "the", "provided", "credentials", "as", "IAM", "credentials", "and", "get", "a", "temporary", "ECR", "token", "." ]
70ce4f56125d8efb8ddcf2ad4dbb5d6e2c7642b3
https://github.com/fabric8io/docker-maven-plugin/blob/70ce4f56125d8efb8ddcf2ad4dbb5d6e2c7642b3/src/main/java/io/fabric8/maven/docker/access/ecr/EcrExtendedAuth.java#L89-L97
28,146
fabric8io/docker-maven-plugin
src/main/java/io/fabric8/maven/docker/util/AnsiLogger.java
AnsiLogger.progressStart
public void progressStart() { // A progress indicator is always written out to standard out if a tty is enabled. if (!batchMode && log.isInfoEnabled()) { imageLines.remove(); updateCount.remove(); imageLines.set(new HashMap<String, Integer>()); updateCount.set(new AtomicInteger()); } }
java
public void progressStart() { // A progress indicator is always written out to standard out if a tty is enabled. if (!batchMode && log.isInfoEnabled()) { imageLines.remove(); updateCount.remove(); imageLines.set(new HashMap<String, Integer>()); updateCount.set(new AtomicInteger()); } }
[ "public", "void", "progressStart", "(", ")", "{", "// A progress indicator is always written out to standard out if a tty is enabled.", "if", "(", "!", "batchMode", "&&", "log", ".", "isInfoEnabled", "(", ")", ")", "{", "imageLines", ".", "remove", "(", ")", ";", "updateCount", ".", "remove", "(", ")", ";", "imageLines", ".", "set", "(", "new", "HashMap", "<", "String", ",", "Integer", ">", "(", ")", ")", ";", "updateCount", ".", "set", "(", "new", "AtomicInteger", "(", ")", ")", ";", "}", "}" ]
Start a progress bar
[ "Start", "a", "progress", "bar" ]
70ce4f56125d8efb8ddcf2ad4dbb5d6e2c7642b3
https://github.com/fabric8io/docker-maven-plugin/blob/70ce4f56125d8efb8ddcf2ad4dbb5d6e2c7642b3/src/main/java/io/fabric8/maven/docker/util/AnsiLogger.java#L121-L129
28,147
fabric8io/docker-maven-plugin
src/main/java/io/fabric8/maven/docker/util/AnsiLogger.java
AnsiLogger.progressUpdate
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(); } }
java
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(); } }
[ "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
[ "Update", "the", "progress" ]
70ce4f56125d8efb8ddcf2ad4dbb5d6e2c7642b3
https://github.com/fabric8io/docker-maven-plugin/blob/70ce4f56125d8efb8ddcf2ad4dbb5d6e2c7642b3/src/main/java/io/fabric8/maven/docker/util/AnsiLogger.java#L134-L143
28,148
fabric8io/docker-maven-plugin
src/main/java/io/fabric8/maven/docker/util/AnsiLogger.java
AnsiLogger.format
private String format(String message, Object[] params) { if (params.length == 0) { return message; } else if (params.length == 1 && params[0] instanceof Throwable) { // We print only the message here since breaking exception will bubble up // anyway return message + ": " + params[0].toString(); } else { return String.format(message, params); } }
java
private String format(String message, Object[] params) { if (params.length == 0) { return message; } else if (params.length == 1 && params[0] instanceof Throwable) { // We print only the message here since breaking exception will bubble up // anyway return message + ": " + params[0].toString(); } else { return String.format(message, params); } }
[ "private", "String", "format", "(", "String", "message", ",", "Object", "[", "]", "params", ")", "{", "if", "(", "params", ".", "length", "==", "0", ")", "{", "return", "message", ";", "}", "else", "if", "(", "params", ".", "length", "==", "1", "&&", "params", "[", "0", "]", "instanceof", "Throwable", ")", "{", "// We print only the message here since breaking exception will bubble up", "// anyway", "return", "message", "+", "\": \"", "+", "params", "[", "0", "]", ".", "toString", "(", ")", ";", "}", "else", "{", "return", "String", ".", "format", "(", "message", ",", "params", ")", ";", "}", "}" ]
Use parameters when given, otherwise we use the string directly
[ "Use", "parameters", "when", "given", "otherwise", "we", "use", "the", "string", "directly" ]
70ce4f56125d8efb8ddcf2ad4dbb5d6e2c7642b3
https://github.com/fabric8io/docker-maven-plugin/blob/70ce4f56125d8efb8ddcf2ad4dbb5d6e2c7642b3/src/main/java/io/fabric8/maven/docker/util/AnsiLogger.java#L232-L242
28,149
fabric8io/docker-maven-plugin
src/main/java/io/fabric8/maven/docker/service/ContainerTracker.java
ContainerTracker.registerContainer
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); }
java
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); }
[ "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 @param containerId container id to register @param imageConfig configuration of associated image @param gavLabel pom label to identifying the reactor project where the container was created
[ "Register", "a", "started", "container", "to", "this", "tracker" ]
70ce4f56125d8efb8ddcf2ad4dbb5d6e2c7642b3
https://github.com/fabric8io/docker-maven-plugin/blob/70ce4f56125d8efb8ddcf2ad4dbb5d6e2c7642b3/src/main/java/io/fabric8/maven/docker/service/ContainerTracker.java#L34-L41
28,150
fabric8io/docker-maven-plugin
src/main/java/io/fabric8/maven/docker/service/ContainerTracker.java
ContainerTracker.lookupContainer
public synchronized String lookupContainer(String lookup) { if (aliasToContainerMap.containsKey(lookup)) { return aliasToContainerMap.get(lookup); } return imageToContainerMap.get(lookup); }
java
public synchronized String lookupContainer(String lookup) { if (aliasToContainerMap.containsKey(lookup)) { return aliasToContainerMap.get(lookup); } return imageToContainerMap.get(lookup); }
[ "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 @param lookup name or alias of the container to lookup @return container id found or <code>null</code>
[ "Lookup", "a", "container", "by", "name", "or", "alias", "from", "the", "tracked", "containers" ]
70ce4f56125d8efb8ddcf2ad4dbb5d6e2c7642b3
https://github.com/fabric8io/docker-maven-plugin/blob/70ce4f56125d8efb8ddcf2ad4dbb5d6e2c7642b3/src/main/java/io/fabric8/maven/docker/service/ContainerTracker.java#L64-L69
28,151
fabric8io/docker-maven-plugin
src/main/java/io/fabric8/maven/docker/service/ContainerTracker.java
ContainerTracker.removeShutdownDescriptors
public synchronized Collection<ContainerShutdownDescriptor> removeShutdownDescriptors(GavLabel gavLabel) { List<ContainerShutdownDescriptor> descriptors; if (gavLabel != null) { descriptors = removeFromPomLabelMap(gavLabel); removeFromPerContainerMap(descriptors); } else { // All entries are requested descriptors = new ArrayList<>(shutdownDescriptorPerContainerMap.values()); clearAllMaps(); } Collections.reverse(descriptors); return descriptors; }
java
public synchronized Collection<ContainerShutdownDescriptor> removeShutdownDescriptors(GavLabel gavLabel) { List<ContainerShutdownDescriptor> descriptors; if (gavLabel != null) { descriptors = removeFromPomLabelMap(gavLabel); removeFromPerContainerMap(descriptors); } else { // All entries are requested descriptors = new ArrayList<>(shutdownDescriptorPerContainerMap.values()); clearAllMaps(); } Collections.reverse(descriptors); return descriptors; }
[ "public", "synchronized", "Collection", "<", "ContainerShutdownDescriptor", ">", "removeShutdownDescriptors", "(", "GavLabel", "gavLabel", ")", "{", "List", "<", "ContainerShutdownDescriptor", ">", "descriptors", ";", "if", "(", "gavLabel", "!=", "null", ")", "{", "descriptors", "=", "removeFromPomLabelMap", "(", "gavLabel", ")", ";", "removeFromPerContainerMap", "(", "descriptors", ")", ";", "}", "else", "{", "// All entries are requested", "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. If no pom label is given, then all descriptors are returned. @param gavLabel the label for which to get the descriptors or <code>null</code> for all descriptors @return the descriptors for the given label or an empty collection
[ "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", "." ]
70ce4f56125d8efb8ddcf2ad4dbb5d6e2c7642b3
https://github.com/fabric8io/docker-maven-plugin/blob/70ce4f56125d8efb8ddcf2ad4dbb5d6e2c7642b3/src/main/java/io/fabric8/maven/docker/service/ContainerTracker.java#L80-L93
28,152
fabric8io/docker-maven-plugin
src/main/java/io/fabric8/maven/docker/AbstractDockerMojo.java
AbstractDockerMojo.getBuildTimestamp
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; }
java
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; }
[ "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 @return timestamp to use
[ "Get", "the", "current", "build", "timestamp", ".", "this", "has", "either", "already", "been", "created", "by", "a", "previous", "call", "or", "a", "new", "current", "date", "is", "created" ]
70ce4f56125d8efb8ddcf2ad4dbb5d6e2c7642b3
https://github.com/fabric8io/docker-maven-plugin/blob/70ce4f56125d8efb8ddcf2ad4dbb5d6e2c7642b3/src/main/java/io/fabric8/maven/docker/AbstractDockerMojo.java#L284-L291
28,153
fabric8io/docker-maven-plugin
src/main/java/io/fabric8/maven/docker/AbstractDockerMojo.java
AbstractDockerMojo.getReferenceDate
protected Date getReferenceDate() throws IOException { Date referenceDate = EnvUtil.loadTimestamp(getBuildTimestampFile()); return referenceDate != null ? referenceDate : new Date(); }
java
protected Date getReferenceDate() throws IOException { Date referenceDate = EnvUtil.loadTimestamp(getBuildTimestampFile()); return referenceDate != null ? referenceDate : new Date(); }
[ "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.
[ "from", "an", "existing", "build", "date", "file", ".", "If", "this", "does", "not", "exist", "the", "current", "date", "is", "used", "." ]
70ce4f56125d8efb8ddcf2ad4dbb5d6e2c7642b3
https://github.com/fabric8io/docker-maven-plugin/blob/70ce4f56125d8efb8ddcf2ad4dbb5d6e2c7642b3/src/main/java/io/fabric8/maven/docker/AbstractDockerMojo.java#L295-L298
28,154
fabric8io/docker-maven-plugin
src/main/java/io/fabric8/maven/docker/AbstractDockerMojo.java
AbstractDockerMojo.initImageConfiguration
private String initImageConfiguration(Date buildTimeStamp) { // Resolve images resolvedImages = ConfigHelper.resolveImages( log, images, // Unresolved images new ConfigHelper.Resolver() { @Override public List<ImageConfiguration> resolve(ImageConfiguration image) { return imageConfigResolver.resolve(image, project, session); } }, filter, // A filter which image to process this); // customizer (can be overwritten by a subclass) // Check for simple Dockerfile mode 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)); } } // Initialize configuration and detect minimal API version return ConfigHelper.initAndValidate(resolvedImages, apiVersion, new ImageNameFormatter(project, buildTimeStamp), log); }
java
private String initImageConfiguration(Date buildTimeStamp) { // Resolve images resolvedImages = ConfigHelper.resolveImages( log, images, // Unresolved images new ConfigHelper.Resolver() { @Override public List<ImageConfiguration> resolve(ImageConfiguration image) { return imageConfigResolver.resolve(image, project, session); } }, filter, // A filter which image to process this); // customizer (can be overwritten by a subclass) // Check for simple Dockerfile mode 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)); } } // Initialize configuration and detect minimal API version return ConfigHelper.initAndValidate(resolvedImages, apiVersion, new ImageNameFormatter(project, buildTimeStamp), log); }
[ "private", "String", "initImageConfiguration", "(", "Date", "buildTimeStamp", ")", "{", "// Resolve images", "resolvedImages", "=", "ConfigHelper", ".", "resolveImages", "(", "log", ",", "images", ",", "// Unresolved images", "new", "ConfigHelper", ".", "Resolver", "(", ")", "{", "@", "Override", "public", "List", "<", "ImageConfiguration", ">", "resolve", "(", "ImageConfiguration", "image", ")", "{", "return", "imageConfigResolver", ".", "resolve", "(", "image", ",", "project", ",", "session", ")", ";", "}", "}", ",", "filter", ",", "// A filter which image to process", "this", ")", ";", "// customizer (can be overwritten by a subclass)", "// Check for simple Dockerfile mode", "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", ")", ")", ";", "}", "}", "// Initialize configuration and detect minimal API version", "return", "ConfigHelper", ".", "initAndValidate", "(", "resolvedImages", ",", "apiVersion", ",", "new", "ImageNameFormatter", "(", "project", ",", "buildTimeStamp", ")", ",", "log", ")", ";", "}" ]
Resolve and customize image configuration
[ "Resolve", "and", "customize", "image", "configuration" ]
70ce4f56125d8efb8ddcf2ad4dbb5d6e2c7642b3
https://github.com/fabric8io/docker-maven-plugin/blob/70ce4f56125d8efb8ddcf2ad4dbb5d6e2c7642b3/src/main/java/io/fabric8/maven/docker/AbstractDockerMojo.java#L323-L349
28,155
fabric8io/docker-maven-plugin
src/main/java/io/fabric8/maven/docker/service/DockerAccessFactory.java
DockerAccessFactory.getDefaultDockerHostProviders
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; }
java
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; }
[ "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. @return list of providers or <code>null</code> if none are applicable
[ "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", "." ]
70ce4f56125d8efb8ddcf2ad4dbb5d6e2c7642b3
https://github.com/fabric8io/docker-maven-plugin/blob/70ce4f56125d8efb8ddcf2ad4dbb5d6e2c7642b3/src/main/java/io/fabric8/maven/docker/service/DockerAccessFactory.java#L67-L85
28,156
fabric8io/docker-maven-plugin
src/main/java/io/fabric8/maven/docker/service/DockerAccessFactory.java
DockerAccessFactory.setDockerHostAddressProperty
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); } }
java
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); } }
[ "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
[ "Registry", "for", "managed", "containers" ]
70ce4f56125d8efb8ddcf2ad4dbb5d6e2c7642b3
https://github.com/fabric8io/docker-maven-plugin/blob/70ce4f56125d8efb8ddcf2ad4dbb5d6e2c7642b3/src/main/java/io/fabric8/maven/docker/service/DockerAccessFactory.java#L88-L104
28,157
fabric8io/docker-maven-plugin
src/main/java/io/fabric8/maven/docker/config/ConfigHelper.java
ConfigHelper.resolveImages
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; }
java
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; }
[ "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 @param images the original image config list (can be null) @param imageResolver the resolver used to extend on an image configuration @param imageNameFilter filter to select only certain image configurations with the given name @param imageCustomizer final customization hook for mangling the configuration @return a list of resolved and customized image configuration.
[ "Resolve", "image", "with", "an", "external", "image", "resolver" ]
70ce4f56125d8efb8ddcf2ad4dbb5d6e2c7642b3
https://github.com/fabric8io/docker-maven-plugin/blob/70ce4f56125d8efb8ddcf2ad4dbb5d6e2c7642b3/src/main/java/io/fabric8/maven/docker/config/ConfigHelper.java#L52-L69
28,158
fabric8io/docker-maven-plugin
src/main/java/io/fabric8/maven/docker/config/ConfigHelper.java
ConfigHelper.initAndValidate
public static String initAndValidate(List<ImageConfiguration> images, String apiVersion, NameFormatter nameFormatter, Logger log) { // Init and validate configs. After this step, getResolvedImages() contains the valid configuration. for (ImageConfiguration imageConfiguration : images) { apiVersion = EnvUtil.extractLargerVersion(apiVersion, imageConfiguration.initAndValidate(nameFormatter, log)); } return apiVersion; }
java
public static String initAndValidate(List<ImageConfiguration> images, String apiVersion, NameFormatter nameFormatter, Logger log) { // Init and validate configs. After this step, getResolvedImages() contains the valid configuration. for (ImageConfiguration imageConfiguration : images) { apiVersion = EnvUtil.extractLargerVersion(apiVersion, imageConfiguration.initAndValidate(nameFormatter, log)); } return apiVersion; }
[ "public", "static", "String", "initAndValidate", "(", "List", "<", "ImageConfiguration", ">", "images", ",", "String", "apiVersion", ",", "NameFormatter", "nameFormatter", ",", "Logger", "log", ")", "{", "// Init and validate configs. After this step, getResolvedImages() contains the valid configuration.", "for", "(", "ImageConfiguration", "imageConfiguration", ":", "images", ")", "{", "apiVersion", "=", "EnvUtil", ".", "extractLargerVersion", "(", "apiVersion", ",", "imageConfiguration", ".", "initAndValidate", "(", "nameFormatter", ",", "log", ")", ")", ";", "}", "return", "apiVersion", ";", "}" ]
Initialize and validate the configuration. @param images the images to check @param apiVersion the original API version intended to use @param nameFormatter formatter for image names @param log a logger for printing out diagnostic messages @return the minimal API Docker API required to be used for the given configuration.
[ "Initialize", "and", "validate", "the", "configuration", "." ]
70ce4f56125d8efb8ddcf2ad4dbb5d6e2c7642b3
https://github.com/fabric8io/docker-maven-plugin/blob/70ce4f56125d8efb8ddcf2ad4dbb5d6e2c7642b3/src/main/java/io/fabric8/maven/docker/config/ConfigHelper.java#L121-L128
28,159
fabric8io/docker-maven-plugin
src/main/java/io/fabric8/maven/docker/config/ConfigHelper.java
ConfigHelper.matchesConfiguredImages
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()); }
java
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()); }
[ "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
[ "Check", "if", "the", "provided", "image", "configuration", "matches", "the", "given" ]
70ce4f56125d8efb8ddcf2ad4dbb5d6e2c7642b3
https://github.com/fabric8io/docker-maven-plugin/blob/70ce4f56125d8efb8ddcf2ad4dbb5d6e2c7642b3/src/main/java/io/fabric8/maven/docker/config/ConfigHelper.java#L131-L137
28,160
fabric8io/docker-maven-plugin
src/main/java/io/fabric8/maven/docker/config/ConfigHelper.java
ConfigHelper.filterImages
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; }
java
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; }
[ "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
[ "list", "of", "image", "names", "which", "should", "be", "used" ]
70ce4f56125d8efb8ddcf2ad4dbb5d6e2c7642b3
https://github.com/fabric8io/docker-maven-plugin/blob/70ce4f56125d8efb8ddcf2ad4dbb5d6e2c7642b3/src/main/java/io/fabric8/maven/docker/config/ConfigHelper.java#L143-L151
28,161
fabric8io/docker-maven-plugin
src/main/java/io/fabric8/maven/docker/config/ConfigHelper.java
ConfigHelper.resolveConfiguration
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; }
java
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; }
[ "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
[ "Resolve", "and", "initialize", "external", "configuration" ]
70ce4f56125d8efb8ddcf2ad4dbb5d6e2c7642b3
https://github.com/fabric8io/docker-maven-plugin/blob/70ce4f56125d8efb8ddcf2ad4dbb5d6e2c7642b3/src/main/java/io/fabric8/maven/docker/config/ConfigHelper.java#L154-L164
28,162
fabric8io/docker-maven-plugin
src/main/java/io/fabric8/maven/docker/config/ConfigHelper.java
ConfigHelper.verifyImageNames
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>"); } } }
java
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>"); } } }
[ "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
[ "Extract", "authentication", "information" ]
70ce4f56125d8efb8ddcf2ad4dbb5d6e2c7642b3
https://github.com/fabric8io/docker-maven-plugin/blob/70ce4f56125d8efb8ddcf2ad4dbb5d6e2c7642b3/src/main/java/io/fabric8/maven/docker/config/ConfigHelper.java#L168-L174
28,163
fabric8io/docker-maven-plugin
src/main/java/io/fabric8/maven/docker/service/MojoExecutionService.java
MojoExecutionService.callPluginGoal
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); } }
java
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); } }
[ "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
[ "Call", "another", "goal", "after", "restart", "has", "finished" ]
70ce4f56125d8efb8ddcf2ad4dbb5d6e2c7642b3
https://github.com/fabric8io/docker-maven-plugin/blob/70ce4f56125d8efb8ddcf2ad4dbb5d6e2c7642b3/src/main/java/io/fabric8/maven/docker/service/MojoExecutionService.java#L58-L88
28,164
fabric8io/docker-maven-plugin
src/main/java/io/fabric8/maven/docker/assembly/DockerFileBuilder.java
DockerFileBuilder.write
public File write(File destDir) throws IOException { File target = new File(destDir,"Dockerfile"); FileUtils.fileWrite(target, content()); return target; }
java
public File write(File destDir) throws IOException { File target = new File(destDir,"Dockerfile"); FileUtils.fileWrite(target, content()); return target; }
[ "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 @param destDir directory where to store the dockerfile @return the full path to the docker file @throws IOException if writing fails
[ "Create", "a", "DockerFile", "in", "the", "given", "directory" ]
70ce4f56125d8efb8ddcf2ad4dbb5d6e2c7642b3
https://github.com/fabric8io/docker-maven-plugin/blob/70ce4f56125d8efb8ddcf2ad4dbb5d6e2c7642b3/src/main/java/io/fabric8/maven/docker/assembly/DockerFileBuilder.java#L83-L87
28,165
fabric8io/docker-maven-plugin
src/main/java/io/fabric8/maven/docker/assembly/DockerFileBuilder.java
DockerFileBuilder.createKeyValue
private String createKeyValue(String key, String value) { StringBuilder sb = new StringBuilder(); // no quoting the key; "Keys are alphanumeric strings which may contain periods (.) and hyphens (-)" 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 '\\': // escape the character valBuf.append('\\'); case ' ': // space needs quotes, too toBeQuoted = true; default: // always append valBuf.append(c); } } if (toBeQuoted) { // need to keep quotes sb.append('"').append(valBuf.toString()).append('"'); } else { sb.append(value); } return sb.toString(); }
java
private String createKeyValue(String key, String value) { StringBuilder sb = new StringBuilder(); // no quoting the key; "Keys are alphanumeric strings which may contain periods (.) and hyphens (-)" 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 '\\': // escape the character valBuf.append('\\'); case ' ': // space needs quotes, too toBeQuoted = true; default: // always append valBuf.append(c); } } if (toBeQuoted) { // need to keep quotes sb.append('"').append(valBuf.toString()).append('"'); } else { sb.append(value); } return sb.toString(); }
[ "private", "String", "createKeyValue", "(", "String", "key", ",", "String", "value", ")", "{", "StringBuilder", "sb", "=", "new", "StringBuilder", "(", ")", ";", "// no quoting the key; \"Keys are alphanumeric strings which may contain periods (.) and hyphens (-)\"", "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", "'", "'", ":", "case", "'", "'", ":", "// escape the character", "valBuf", ".", "append", "(", "'", "'", ")", ";", "case", "'", "'", ":", "// space needs quotes, too", "toBeQuoted", "=", "true", ";", "default", ":", "// always append", "valBuf", ".", "append", "(", "c", ")", ";", "}", "}", "if", "(", "toBeQuoted", ")", "{", "// need to keep quotes", "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. @param key The key @param value The value @return Escaped and quoted key="value"
[ "Escape", "any", "slashes", "quotes", "and", "newlines", "int", "the", "value", ".", "If", "any", "escaping", "occurred", "quote", "the", "value", "." ]
70ce4f56125d8efb8ddcf2ad4dbb5d6e2c7642b3
https://github.com/fabric8io/docker-maven-plugin/blob/70ce4f56125d8efb8ddcf2ad4dbb5d6e2c7642b3/src/main/java/io/fabric8/maven/docker/assembly/DockerFileBuilder.java#L250-L282
28,166
fabric8io/docker-maven-plugin
src/main/java/io/fabric8/maven/docker/assembly/DockerFileBuilder.java
DockerFileBuilder.run
public DockerFileBuilder run(List<String> runCmds) { if (runCmds != null) { for (String cmd : runCmds) { if (!StringUtils.isEmpty(cmd)) { this.runCmds.add(cmd); } } } return this; }
java
public DockerFileBuilder run(List<String> runCmds) { if (runCmds != null) { for (String cmd : runCmds) { if (!StringUtils.isEmpty(cmd)) { this.runCmds.add(cmd); } } } return this; }
[ "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 @param runCmds @return
[ "Adds", "the", "RUN", "Commands", "within", "the", "build", "image", "section" ]
70ce4f56125d8efb8ddcf2ad4dbb5d6e2c7642b3
https://github.com/fabric8io/docker-maven-plugin/blob/70ce4f56125d8efb8ddcf2ad4dbb5d6e2c7642b3/src/main/java/io/fabric8/maven/docker/assembly/DockerFileBuilder.java#L434-L443
28,167
fabric8io/docker-maven-plugin
src/main/java/io/fabric8/maven/docker/util/ContainerNamingUtil.java
ContainerNamingUtil.getContainersToStop
public static Collection<Container> getContainersToStop(final ImageConfiguration image, final String defaultContainerNamePattern, final Date buildTimestamp, final Collection<Container> containers) { String containerNamePattern = extractContainerNamePattern(image, defaultContainerNamePattern); // Only special treatment for indexed container names if (!containerNamePattern.contains(INDEX_PLACEHOLDER)) { return containers; } final String partiallyApplied = replacePlaceholders( containerNamePattern, image.getName(), image.getAlias(), buildTimestamp); return keepOnlyLastIndexedContainer(containers, partiallyApplied); }
java
public static Collection<Container> getContainersToStop(final ImageConfiguration image, final String defaultContainerNamePattern, final Date buildTimestamp, final Collection<Container> containers) { String containerNamePattern = extractContainerNamePattern(image, defaultContainerNamePattern); // Only special treatment for indexed container names if (!containerNamePattern.contains(INDEX_PLACEHOLDER)) { return containers; } final String partiallyApplied = replacePlaceholders( containerNamePattern, image.getName(), image.getAlias(), buildTimestamp); return keepOnlyLastIndexedContainer(containers, partiallyApplied); }
[ "public", "static", "Collection", "<", "Container", ">", "getContainersToStop", "(", "final", "ImageConfiguration", "image", ",", "final", "String", "defaultContainerNamePattern", ",", "final", "Date", "buildTimestamp", ",", "final", "Collection", "<", "Container", ">", "containers", ")", "{", "String", "containerNamePattern", "=", "extractContainerNamePattern", "(", "image", ",", "defaultContainerNamePattern", ")", ";", "// Only special treatment for indexed container names", "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. @param image the image from which to the the container pattern @param buildTimestamp the timestamp for the build @param containers the list of existing containers @return a list with potentially lower indexed entries removed
[ "Keep", "only", "the", "entry", "with", "the", "higest", "index", "if", "an", "indexed", "naming", "scheme", "for", "container", "has", "been", "chosen", "." ]
70ce4f56125d8efb8ddcf2ad4dbb5d6e2c7642b3
https://github.com/fabric8io/docker-maven-plugin/blob/70ce4f56125d8efb8ddcf2ad4dbb5d6e2c7642b3/src/main/java/io/fabric8/maven/docker/util/ContainerNamingUtil.java#L66-L87
28,168
fabric8io/docker-maven-plugin
src/main/java/io/fabric8/maven/docker/service/RegistryService.java
RegistryService.pushImages
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); } } } } } }
java
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); } } } } } }
[ "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 @param imageConfigs images to push (but only if they have a build configuration) @param retries how often to retry @param registryConfig a global registry configuration @param skipTag flag to skip pushing tagged images @throws DockerAccessException @throws MojoExecutionException
[ "Push", "a", "set", "of", "images", "to", "a", "registry" ]
70ce4f56125d8efb8ddcf2ad4dbb5d6e2c7642b3
https://github.com/fabric8io/docker-maven-plugin/blob/70ce4f56125d8efb8ddcf2ad4dbb5d6e2c7642b3/src/main/java/io/fabric8/maven/docker/service/RegistryService.java#L44-L71
28,169
fabric8io/docker-maven-plugin
src/main/java/io/fabric8/maven/docker/config/BuildImageConfiguration.java
BuildImageConfiguration.initDockerFileFile
private void initDockerFileFile(Logger log) { // can't have dockerFile/dockerFileDir and dockerArchive 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); } }
java
private void initDockerFileFile(Logger log) { // can't have dockerFile/dockerFileDir and dockerArchive 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); } }
[ "private", "void", "initDockerFileFile", "(", "Logger", "log", ")", "{", "// can't have dockerFile/dockerFileDir and dockerArchive", "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
[ "Initialize", "the", "dockerfile", "location", "and", "the", "build", "mode" ]
70ce4f56125d8efb8ddcf2ad4dbb5d6e2c7642b3
https://github.com/fabric8io/docker-maven-plugin/blob/70ce4f56125d8efb8ddcf2ad4dbb5d6e2c7642b3/src/main/java/io/fabric8/maven/docker/config/BuildImageConfiguration.java#L628-L639
28,170
fabric8io/docker-maven-plugin
src/main/java/io/fabric8/maven/docker/assembly/DockerAssemblyManager.java
DockerAssemblyManager.createBuildTarBall
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); } }
java
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); } }
[ "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
[ "Create", "final", "tar", "-", "ball", "to", "be", "used", "for", "building", "the", "archive", "to", "send", "to", "the", "Docker", "daemon" ]
70ce4f56125d8efb8ddcf2ad4dbb5d6e2c7642b3
https://github.com/fabric8io/docker-maven-plugin/blob/70ce4f56125d8efb8ddcf2ad4dbb5d6e2c7642b3/src/main/java/io/fabric8/maven/docker/assembly/DockerAssemblyManager.java#L305-L323
28,171
fabric8io/docker-maven-plugin
src/main/java/io/fabric8/maven/docker/assembly/DockerAssemblyManager.java
DockerAssemblyManager.ensureThatArtifactFileIsSet
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; }
java
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; }
[ "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.
[ "warning", "with", "an", "error", "following", "." ]
70ce4f56125d8efb8ddcf2ad4dbb5d6e2c7642b3
https://github.com/fabric8io/docker-maven-plugin/blob/70ce4f56125d8efb8ddcf2ad4dbb5d6e2c7642b3/src/main/java/io/fabric8/maven/docker/assembly/DockerAssemblyManager.java#L494-L517
28,172
fabric8io/docker-maven-plugin
src/main/java/io/fabric8/maven/docker/assembly/AssemblyFiles.java
AssemblyFiles.addEntry
public void addEntry(File srcFile, File destFile) { entries.add(new Entry(srcFile,destFile)); }
java
public void addEntry(File srcFile, File destFile) { entries.add(new Entry(srcFile,destFile)); }
[ "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 @param srcFile source file to monitor. The source file must exist. @param destFile the destination to which it is eventually copied. The destination file must be relative.
[ "Add", "a", "entry", "to", "the", "list", "of", "assembly", "files", "which", "possible", "should", "be", "monitored" ]
70ce4f56125d8efb8ddcf2ad4dbb5d6e2c7642b3
https://github.com/fabric8io/docker-maven-plugin/blob/70ce4f56125d8efb8ddcf2ad4dbb5d6e2c7642b3/src/main/java/io/fabric8/maven/docker/assembly/AssemblyFiles.java#L49-L51
28,173
fabric8io/docker-maven-plugin
src/main/java/io/fabric8/maven/docker/util/StartOrderResolver.java
StartOrderResolver.resolve
private List<Resolvable> resolve(List<Resolvable> images) { List<Resolvable> resolved = new ArrayList<>(); // First pass: Pick all data images and all without dependencies for (Resolvable config : images) { List<String> volumesOrLinks = extractDependentImagesFor(config); if (volumesOrLinks == null) { // A data image only or no dependency. Add it to the list of data image which can be always // created first. updateProcessedImages(config); resolved.add(config); } else { secondPass.add(config); } } // Next passes: Those with dependencies are checked whether they already have been visited. return secondPass.size() > 0 ? resolveRemaining(resolved) : resolved; }
java
private List<Resolvable> resolve(List<Resolvable> images) { List<Resolvable> resolved = new ArrayList<>(); // First pass: Pick all data images and all without dependencies for (Resolvable config : images) { List<String> volumesOrLinks = extractDependentImagesFor(config); if (volumesOrLinks == null) { // A data image only or no dependency. Add it to the list of data image which can be always // created first. updateProcessedImages(config); resolved.add(config); } else { secondPass.add(config); } } // Next passes: Those with dependencies are checked whether they already have been visited. return secondPass.size() > 0 ? resolveRemaining(resolved) : resolved; }
[ "private", "List", "<", "Resolvable", ">", "resolve", "(", "List", "<", "Resolvable", ">", "images", ")", "{", "List", "<", "Resolvable", ">", "resolved", "=", "new", "ArrayList", "<>", "(", ")", ";", "// First pass: Pick all data images and all without dependencies", "for", "(", "Resolvable", "config", ":", "images", ")", "{", "List", "<", "String", ">", "volumesOrLinks", "=", "extractDependentImagesFor", "(", "config", ")", ";", "if", "(", "volumesOrLinks", "==", "null", ")", "{", "// A data image only or no dependency. Add it to the list of data image which can be always", "// created first.", "updateProcessedImages", "(", "config", ")", ";", "resolved", ".", "add", "(", "config", ")", ";", "}", "else", "{", "secondPass", ".", "add", "(", "config", ")", ";", "}", "}", "// Next passes: Those with dependencies are checked whether they already have been visited.", "return", "secondPass", ".", "size", "(", ")", ">", "0", "?", "resolveRemaining", "(", "resolved", ")", ":", "resolved", ";", "}" ]
an appropriate container which can be linked into the image
[ "an", "appropriate", "container", "which", "can", "be", "linked", "into", "the", "image" ]
70ce4f56125d8efb8ddcf2ad4dbb5d6e2c7642b3
https://github.com/fabric8io/docker-maven-plugin/blob/70ce4f56125d8efb8ddcf2ad4dbb5d6e2c7642b3/src/main/java/io/fabric8/maven/docker/util/StartOrderResolver.java#L38-L55
28,174
fabric8io/docker-maven-plugin
src/main/java/io/fabric8/maven/docker/service/ArchiveService.java
ArchiveService.createChangedFilesArchive
public File createChangedFilesArchive(List<AssemblyFiles.Entry> entries, File assemblyDir, String imageName, MojoParameters mojoParameters) throws MojoExecutionException { return dockerAssemblyManager.createChangedFilesArchive(entries, assemblyDir, imageName, mojoParameters); }
java
public File createChangedFilesArchive(List<AssemblyFiles.Entry> entries, File assemblyDir, String imageName, MojoParameters mojoParameters) throws MojoExecutionException { return dockerAssemblyManager.createChangedFilesArchive(entries, assemblyDir, imageName, mojoParameters); }
[ "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. @param entries changed files. List must not be empty or null @param imageName image's name @param mojoParameters @return created archive
[ "Create", "an", "tar", "archive", "from", "a", "set", "of", "assembly", "files", ".", "Only", "files", "which", "changed", "since", "the", "last", "call", "are", "included", "." ]
70ce4f56125d8efb8ddcf2ad4dbb5d6e2c7642b3
https://github.com/fabric8io/docker-maven-plugin/blob/70ce4f56125d8efb8ddcf2ad4dbb5d6e2c7642b3/src/main/java/io/fabric8/maven/docker/service/ArchiveService.java#L109-L112
28,175
fabric8io/docker-maven-plugin
src/main/java/io/fabric8/maven/docker/access/ContainerNetworkingConfig.java
ContainerNetworkingConfig.aliases
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; }
java
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; }
[ "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 @param config network config as configured in the pom.xml @return this configuration
[ "Add", "networking", "aliases", "to", "a", "custom", "network" ]
70ce4f56125d8efb8ddcf2ad4dbb5d6e2c7642b3
https://github.com/fabric8io/docker-maven-plugin/blob/70ce4f56125d8efb8ddcf2ad4dbb5d6e2c7642b3/src/main/java/io/fabric8/maven/docker/access/ContainerNetworkingConfig.java#L18-L27
28,176
fabric8io/docker-maven-plugin
src/main/java/io/fabric8/maven/docker/service/BuildService.java
BuildService.buildImage
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)); }
java
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)); }
[ "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. @param imageConfig the image configuration @param buildContext the build context @throws DockerAccessException @throws MojoExecutionException
[ "Pull", "the", "base", "image", "if", "needed", "and", "run", "the", "build", "." ]
70ce4f56125d8efb8ddcf2ad4dbb5d6e2c7642b3
https://github.com/fabric8io/docker-maven-plugin/blob/70ce4f56125d8efb8ddcf2ad4dbb5d6e2c7642b3/src/main/java/io/fabric8/maven/docker/service/BuildService.java#L63-L71
28,177
fabric8io/docker-maven-plugin
src/main/java/io/fabric8/maven/docker/service/BuildService.java
BuildService.buildImage
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); // auto is now supported by docker, consider switching? 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; } } } }
java
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); // auto is now supported by docker, consider switching? 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; } } } }
[ "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", ")", ";", "// auto is now supported by docker, consider switching?", "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 @param imageConfig the image configuration @param params mojo params for the project @param noCache if not null, dictate the caching behaviour. Otherwise its taken from the build configuration @param buildArgs @throws DockerAccessException @throws MojoExecutionException
[ "Build", "an", "image" ]
70ce4f56125d8efb8ddcf2ad4dbb5d6e2c7642b3
https://github.com/fabric8io/docker-maven-plugin/blob/70ce4f56125d8efb8ddcf2ad4dbb5d6e2c7642b3/src/main/java/io/fabric8/maven/docker/service/BuildService.java#L99-L161
28,178
fabric8io/docker-maven-plugin
src/main/java/io/fabric8/maven/docker/service/RunService.java
RunService.stopContainer
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); }
java
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); }
[ "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. @param containerId the container to stop @param imageConfig image configuration for this container @param keepContainer whether to keep container or to remove them after stoppings @param removeVolumes whether to remove volumes after stopping
[ "Stop", "a", "container", "immediately", "by", "id", "." ]
70ce4f56125d8efb8ddcf2ad4dbb5d6e2c7642b3
https://github.com/fabric8io/docker-maven-plugin/blob/70ce4f56125d8efb8ddcf2ad4dbb5d6e2c7642b3/src/main/java/io/fabric8/maven/docker/service/RunService.java#L169-L177
28,179
fabric8io/docker-maven-plugin
src/main/java/io/fabric8/maven/docker/service/RunService.java
RunService.stopPreviouslyStartedContainer
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); } }
java
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); } }
[ "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 @param containerId the container to stop @param keepContainer whether to keep container or to remove them after stoppings @param removeVolumes whether to remove volumes after stopping @throws DockerAccessException
[ "Lookup", "up", "whether", "a", "certain", "has", "been", "already", "started", "and", "registered", ".", "If", "so", "stop", "it" ]
70ce4f56125d8efb8ddcf2ad4dbb5d6e2c7642b3
https://github.com/fabric8io/docker-maven-plugin/blob/70ce4f56125d8efb8ddcf2ad4dbb5d6e2c7642b3/src/main/java/io/fabric8/maven/docker/service/RunService.java#L188-L196
28,180
fabric8io/docker-maven-plugin
src/main/java/io/fabric8/maven/docker/service/RunService.java
RunService.stopStartedContainers
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); }
java
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); }
[ "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 @param keepContainer whether to keep container or to remove them after stopping @param removeVolumes whether to remove volumes after stopping @throws DockerAccessException if during stopping of a container sth fails
[ "Stop", "all", "registered", "container" ]
70ce4f56125d8efb8ddcf2ad4dbb5d6e2c7642b3
https://github.com/fabric8io/docker-maven-plugin/blob/70ce4f56125d8efb8ddcf2ad4dbb5d6e2c7642b3/src/main/java/io/fabric8/maven/docker/service/RunService.java#L204-L215
28,181
fabric8io/docker-maven-plugin
src/main/java/io/fabric8/maven/docker/service/RunService.java
RunService.getImagesConfigsInOrder
public List<StartOrderResolver.Resolvable> getImagesConfigsInOrder(QueryService queryService, List<ImageConfiguration> images) { return StartOrderResolver.resolve(queryService, convertToResolvables(images)); }
java
public List<StartOrderResolver.Resolvable> getImagesConfigsInOrder(QueryService queryService, List<ImageConfiguration> images) { return StartOrderResolver.resolve(queryService, convertToResolvables(images)); }
[ "public", "List", "<", "StartOrderResolver", ".", "Resolvable", ">", "getImagesConfigsInOrder", "(", "QueryService", "queryService", ",", "List", "<", "ImageConfiguration", ">", "images", ")", "{", "return", "StartOrderResolver", ".", "resolve", "(", "queryService", ",", "convertToResolvables", "(", "images", ")", ")", ";", "}" ]
Get the proper order for images to start @param images list of images for which the order should be created @return list of images in the right startup order
[ "Get", "the", "proper", "order", "for", "images", "to", "start" ]
70ce4f56125d8efb8ddcf2ad4dbb5d6e2c7642b3
https://github.com/fabric8io/docker-maven-plugin/blob/70ce4f56125d8efb8ddcf2ad4dbb5d6e2c7642b3/src/main/java/io/fabric8/maven/docker/service/RunService.java#L239-L241
28,182
fabric8io/docker-maven-plugin
src/main/java/io/fabric8/maven/docker/service/RunService.java
RunService.createPortMapping
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); } }
java
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); } }
[ "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 @param runConfig the cun configuration @param properties properties to lookup variables @return the portmapping
[ "Create", "port", "mapping", "for", "a", "specific", "configuration", "as", "it", "can", "be", "used", "when", "creating", "containers" ]
70ce4f56125d8efb8ddcf2ad4dbb5d6e2c7642b3
https://github.com/fabric8io/docker-maven-plugin/blob/70ce4f56125d8efb8ddcf2ad4dbb5d6e2c7642b3/src/main/java/io/fabric8/maven/docker/service/RunService.java#L250-L256
28,183
fabric8io/docker-maven-plugin
src/main/java/io/fabric8/maven/docker/service/RunService.java
RunService.addShutdownHookForStoppingContainers
public void addShutdownHookForStoppingContainers(final boolean keepContainer, final boolean removeVolumes, final boolean removeCustomNetworks) { Runtime.getRuntime().addShutdownHook(new Thread() { @Override public void run() { try { stopStartedContainers(keepContainer, removeVolumes, removeCustomNetworks, null); } catch (DockerAccessException | ExecException e) { log.error("Error while stopping containers: %s", e.getMessage()); } } }); }
java
public void addShutdownHookForStoppingContainers(final boolean keepContainer, final boolean removeVolumes, final boolean removeCustomNetworks) { Runtime.getRuntime().addShutdownHook(new Thread() { @Override public void run() { try { stopStartedContainers(keepContainer, removeVolumes, removeCustomNetworks, null); } catch (DockerAccessException | ExecException e) { log.error("Error while stopping containers: %s", e.getMessage()); } } }); }
[ "public", "void", "addShutdownHookForStoppingContainers", "(", "final", "boolean", "keepContainer", ",", "final", "boolean", "removeVolumes", ",", "final", "boolean", "removeCustomNetworks", ")", "{", "Runtime", ".", "getRuntime", "(", ")", ".", "addShutdownHook", "(", "new", "Thread", "(", ")", "{", "@", "Override", "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
[ "Add", "a", "shutdown", "hook", "in", "order", "to", "stop", "all", "registered", "containers" ]
70ce4f56125d8efb8ddcf2ad4dbb5d6e2c7642b3
https://github.com/fabric8io/docker-maven-plugin/blob/70ce4f56125d8efb8ddcf2ad4dbb5d6e2c7642b3/src/main/java/io/fabric8/maven/docker/service/RunService.java#L261-L272
28,184
fabric8io/docker-maven-plugin
src/main/java/io/fabric8/maven/docker/service/RunService.java
RunService.createVolumesAsPerVolumeBinds
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; }
java
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; }
[ "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 @param hub Service hub @param binds volume binds present in ImageConfiguration @param volumes VolumeConfigs present @return List of volumes created @throws DockerAccessException
[ "Creates", "a", "Volume", "if", "a", "volume", "is", "referred", "to", "during", "startup", "in", "bind", "mount", "mapping", "and", "a", "VolumeConfiguration", "exists" ]
70ce4f56125d8efb8ddcf2ad4dbb5d6e2c7642b3
https://github.com/fabric8io/docker-maven-plugin/blob/70ce4f56125d8efb8ddcf2ad4dbb5d6e2c7642b3/src/main/java/io/fabric8/maven/docker/service/RunService.java#L558-L581
28,185
fabric8io/docker-maven-plugin
src/main/java/io/fabric8/maven/docker/access/util/LocalSocketUtil.java
LocalSocketUtil.canConnectUnixSocket
public static boolean canConnectUnixSocket(File path) { try (UnixSocketChannel channel = UnixSocketChannel.open()) { return channel.connect(new UnixSocketAddress(path)); } catch (IOException e) { return false; } }
java
public static boolean canConnectUnixSocket(File path) { try (UnixSocketChannel channel = UnixSocketChannel.open()) { return channel.connect(new UnixSocketAddress(path)); } catch (IOException e) { return false; } }
[ "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
[ "Check", "whether", "we", "can", "connect", "to", "a", "local", "Unix", "socket" ]
70ce4f56125d8efb8ddcf2ad4dbb5d6e2c7642b3
https://github.com/fabric8io/docker-maven-plugin/blob/70ce4f56125d8efb8ddcf2ad4dbb5d6e2c7642b3/src/main/java/io/fabric8/maven/docker/access/util/LocalSocketUtil.java#L37-L43
28,186
fabric8io/docker-maven-plugin
src/main/java/io/fabric8/maven/docker/access/ecr/AwsSigner4Request.java
AwsSigner4Request.getOrderedHeadersToSign
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")) { // do not sign 'connection' header, it is very likely to be changed en-route. continue; } String value = header.getValue(); if (value == null) { value = ""; } else { // minimize white space value = value.trim().replaceAll("\\s+", " "); } // merge all values with same header name 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; }
java
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")) { // do not sign 'connection' header, it is very likely to be changed en-route. continue; } String value = header.getValue(); if (value == null) { value = ""; } else { // minimize white space value = value.trim().replaceAll("\\s+", " "); } // merge all values with same header name 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; }
[ "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\"", ")", ")", "{", "// do not sign 'connection' header, it is very likely to be changed en-route.", "continue", ";", "}", "String", "value", "=", "header", ".", "getValue", "(", ")", ";", "if", "(", "value", "==", "null", ")", "{", "value", "=", "\"\"", ";", "}", "else", "{", "// minimize white space", "value", "=", "value", ".", "trim", "(", ")", ".", "replaceAll", "(", "\"\\\\s+\"", ",", "\" \"", ")", ";", "}", "// merge all values with same header name", "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. @param headers the possible headers to sign @return A &lt;String, StringBuilder&gt; map of headers to sign. Key is the name of the header, Value is the comma separated values with minimized space
[ "Get", "the", "ordered", "map", "of", "headers", "to", "sign", "." ]
70ce4f56125d8efb8ddcf2ad4dbb5d6e2c7642b3
https://github.com/fabric8io/docker-maven-plugin/blob/70ce4f56125d8efb8ddcf2ad4dbb5d6e2c7642b3/src/main/java/io/fabric8/maven/docker/access/ecr/AwsSigner4Request.java#L157-L184
28,187
fabric8io/docker-maven-plugin
src/main/java/io/fabric8/maven/docker/access/ecr/AwsSigner4Request.java
AwsSigner4Request.canonicalHeaders
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(); }
java
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(); }
[ "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", "(", "'", "'", ")", ";", "}", "return", "canonical", ".", "toString", "(", ")", ";", "}" ]
Create canonical header set. The headers are ordered by name. @param headers The set of headers to sign @return The signing value from headers. Headers are separated with newline. Each header is formatted name:value with each header value whitespace trimmed and minimized
[ "Create", "canonical", "header", "set", ".", "The", "headers", "are", "ordered", "by", "name", "." ]
70ce4f56125d8efb8ddcf2ad4dbb5d6e2c7642b3
https://github.com/fabric8io/docker-maven-plugin/blob/70ce4f56125d8efb8ddcf2ad4dbb5d6e2c7642b3/src/main/java/io/fabric8/maven/docker/access/ecr/AwsSigner4Request.java#L193-L199
28,188
fabric8io/docker-maven-plugin
src/main/java/io/fabric8/maven/docker/access/PortMapping.java
PortMapping.updateProperties
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(); // Use the docker host if binding is on all interfaces if ("0.0.0.0".equals(hostIp)) { hostIp = projProperties.getProperty("docker.host.address"); } update(hostIpVariableMap, specToHostIpVariableMap.get(variable), hostIp); } } updateDynamicProperties(hostPortVariableMap); updateDynamicProperties(hostIpVariableMap); }
java
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(); // Use the docker host if binding is on all interfaces if ("0.0.0.0".equals(hostIp)) { hostIp = projProperties.getProperty("docker.host.address"); } update(hostIpVariableMap, specToHostIpVariableMap.get(variable), hostIp); } } updateDynamicProperties(hostPortVariableMap); updateDynamicProperties(hostIpVariableMap); }
[ "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", "(", ")", ";", "// Use the docker host if binding is on all interfaces", "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. @param dockerObtainedDynamicBindings keys are the container ports, values are the dynamically mapped host ports and host ips.
[ "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", "." ]
70ce4f56125d8efb8ddcf2ad4dbb5d6e2c7642b3
https://github.com/fabric8io/docker-maven-plugin/blob/70ce4f56125d8efb8ddcf2ad4dbb5d6e2c7642b3/src/main/java/io/fabric8/maven/docker/access/PortMapping.java#L104-L125
28,189
fabric8io/docker-maven-plugin
src/main/java/io/fabric8/maven/docker/access/PortMapping.java
PortMapping.toDockerPortBindingsJson
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; } }
java
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; } }
[ "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. @return 'PortBindings' object or null if no port mappings are used.
[ "Create", "a", "JSON", "specification", "which", "can", "be", "used", "to", "in", "a", "Docker", "API", "request", "as", "the", "PortBindings", "part", "for", "creating", "container", "." ]
70ce4f56125d8efb8ddcf2ad4dbb5d6e2c7642b3
https://github.com/fabric8io/docker-maven-plugin/blob/70ce4f56125d8efb8ddcf2ad4dbb5d6e2c7642b3/src/main/java/io/fabric8/maven/docker/access/PortMapping.java#L133-L159
28,190
fabric8io/docker-maven-plugin
src/main/java/io/fabric8/maven/docker/access/PortMapping.java
PortMapping.toJson
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; }
java
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; }
[ "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 @return port mappings as JSON array or null if no mappings exist
[ "Return", "the", "content", "of", "the", "mapping", "as", "an", "array", "with", "all", "specifications", "as", "given" ]
70ce4f56125d8efb8ddcf2ad4dbb5d6e2c7642b3
https://github.com/fabric8io/docker-maven-plugin/blob/70ce4f56125d8efb8ddcf2ad4dbb5d6e2c7642b3/src/main/java/io/fabric8/maven/docker/access/PortMapping.java#L166-L203
28,191
fabric8io/docker-maven-plugin
src/main/java/io/fabric8/maven/docker/access/PortMapping.java
PortMapping.getPortFromProjectOrSystemProperty
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; }
java
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; }
[ "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
[ "First", "check", "system", "properties", "then", "the", "variables", "given" ]
70ce4f56125d8efb8ddcf2ad4dbb5d6e2c7642b3
https://github.com/fabric8io/docker-maven-plugin/blob/70ce4f56125d8efb8ddcf2ad4dbb5d6e2c7642b3/src/main/java/io/fabric8/maven/docker/access/PortMapping.java#L262-L271
28,192
fabric8io/docker-maven-plugin
src/main/java/io/fabric8/maven/docker/assembly/MappingTrackArchiver.java
MappingTrackArchiver.getAssemblyFiles
public AssemblyFiles getAssemblyFiles(MavenSession session) { AssemblyFiles ret = new AssemblyFiles(new File(getDestFile().getParentFile(), assemblyName)); // Where the 'real' files are copied to 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; }
java
public AssemblyFiles getAssemblyFiles(MavenSession session) { AssemblyFiles ret = new AssemblyFiles(new File(getDestFile().getParentFile(), assemblyName)); // Where the 'real' files are copied to 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; }
[ "public", "AssemblyFiles", "getAssemblyFiles", "(", "MavenSession", "session", ")", "{", "AssemblyFiles", "ret", "=", "new", "AssemblyFiles", "(", "new", "File", "(", "getDestFile", "(", ")", ".", "getParentFile", "(", ")", ",", "assemblyName", ")", ")", ";", "// Where the 'real' files are copied to", "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. @return assembled files
[ "Get", "all", "files", "depicted", "by", "this", "assembly", "." ]
70ce4f56125d8efb8ddcf2ad4dbb5d6e2c7642b3
https://github.com/fabric8io/docker-maven-plugin/blob/70ce4f56125d8efb8ddcf2ad4dbb5d6e2c7642b3/src/main/java/io/fabric8/maven/docker/assembly/MappingTrackArchiver.java#L59-L88
28,193
fabric8io/docker-maven-plugin
src/main/java/io/fabric8/maven/docker/assembly/MappingTrackArchiver.java
MappingTrackArchiver.getArtifactFromJar
private Artifact getArtifactFromJar(File jar) { // Lets figure the real mvn source of file. 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(); //change ouptut stream as required 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; }
java
private Artifact getArtifactFromJar(File jar) { // Lets figure the real mvn source of file. 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(); //change ouptut stream as required 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; }
[ "private", "Artifact", "getArtifactFromJar", "(", "File", "jar", ")", "{", "// Lets figure the real mvn source of file.", "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", "(", ")", ";", "//change ouptut stream as required", "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.
[ "look", "into", "a", "jar", "file", "and", "check", "for", "pom", ".", "properties", ".", "The", "first", "pom", ".", "properties", "found", "are", "returned", "." ]
70ce4f56125d8efb8ddcf2ad4dbb5d6e2c7642b3
https://github.com/fabric8io/docker-maven-plugin/blob/70ce4f56125d8efb8ddcf2ad4dbb5d6e2c7642b3/src/main/java/io/fabric8/maven/docker/assembly/MappingTrackArchiver.java#L127-L160
28,194
fabric8io/docker-maven-plugin
src/main/java/io/fabric8/maven/docker/access/hc/DockerAccessWithHcClient.java
DockerAccessWithHcClient.logRemoveResponse
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())); } } }
java
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())); } } }
[ "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
[ "Callback", "for", "processing", "response", "chunks" ]
70ce4f56125d8efb8ddcf2ad4dbb5d6e2c7642b3
https://github.com/fabric8io/docker-maven-plugin/blob/70ce4f56125d8efb8ddcf2ad4dbb5d6e2c7642b3/src/main/java/io/fabric8/maven/docker/access/hc/DockerAccessWithHcClient.java#L703-L710
28,195
fabric8io/docker-maven-plugin
src/main/java/io/fabric8/maven/docker/util/AuthConfigFactory.java
AuthConfigFactory.extendedAuthentication
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; }
java
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; }
[ "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 @param standardAuthConfig The locally stored credentials. @param registry The registry to authenticated against. @return The given credentials, if registry does not need extended authentication; else, the credentials after authentication. @throws IOException @throws MojoExecutionException
[ "Try", "various", "extended", "authentication", "method", ".", "Currently", "only", "supports", "amazon", "ECR" ]
70ce4f56125d8efb8ddcf2ad4dbb5d6e2c7642b3
https://github.com/fabric8io/docker-maven-plugin/blob/70ce4f56125d8efb8ddcf2ad4dbb5d6e2c7642b3/src/main/java/io/fabric8/maven/docker/util/AuthConfigFactory.java#L157-L163
28,196
fabric8io/docker-maven-plugin
src/main/java/io/fabric8/maven/docker/util/AuthConfigFactory.java
AuthConfigFactory.parseOpenShiftConfig
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; }
java
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; }
[ "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
[ "Parse", "OpenShift", "config", "to", "get", "credentials", "but", "return", "null", "if", "not", "found" ]
70ce4f56125d8efb8ddcf2ad4dbb5d6e2c7642b3
https://github.com/fabric8io/docker-maven-plugin/blob/70ce4f56125d8efb8ddcf2ad4dbb5d6e2c7642b3/src/main/java/io/fabric8/maven/docker/util/AuthConfigFactory.java#L458-L476
28,197
fabric8io/docker-maven-plugin
src/main/java/io/fabric8/maven/docker/service/QueryService.java
QueryService.getMandatoryContainer
public Container getMandatoryContainer(String containerIdOrName) throws DockerAccessException { Container container = getContainer(containerIdOrName); if (container == null) { throw new DockerAccessException("Cannot find container %s", containerIdOrName); } return container; }
java
public Container getMandatoryContainer(String containerIdOrName) throws DockerAccessException { Container container = getContainer(containerIdOrName); if (container == null) { throw new DockerAccessException("Cannot find container %s", containerIdOrName); } return container; }
[ "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 @param containerIdOrName container id or name @return container found @throws DockerAccessException if an error occurs or no container with this id or name exists
[ "Get", "container", "by", "id" ]
70ce4f56125d8efb8ddcf2ad4dbb5d6e2c7642b3
https://github.com/fabric8io/docker-maven-plugin/blob/70ce4f56125d8efb8ddcf2ad4dbb5d6e2c7642b3/src/main/java/io/fabric8/maven/docker/service/QueryService.java#L36-L42
28,198
fabric8io/docker-maven-plugin
src/main/java/io/fabric8/maven/docker/service/QueryService.java
QueryService.getNetworkByName
public Network getNetworkByName(final String networkName) throws DockerAccessException { for (Network el : docker.listNetworks()) { if (networkName.equals(el.getName())) { return el; } } return null; }
java
public Network getNetworkByName(final String networkName) throws DockerAccessException { for (Network el : docker.listNetworks()) { if (networkName.equals(el.getName())) { return el; } } return null; }
[ "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. @param networkName name of network to lookup @return the network found or <code>null</code> if no network is available. @throws DockerAccessException in case of an remote error
[ "Get", "a", "network", "for", "a", "given", "network", "name", "." ]
70ce4f56125d8efb8ddcf2ad4dbb5d6e2c7642b3
https://github.com/fabric8io/docker-maven-plugin/blob/70ce4f56125d8efb8ddcf2ad4dbb5d6e2c7642b3/src/main/java/io/fabric8/maven/docker/service/QueryService.java#L60-L67
28,199
fabric8io/docker-maven-plugin
src/main/java/io/fabric8/maven/docker/service/QueryService.java
QueryService.getContainersForImage
public List<Container> getContainersForImage(final String image, final boolean all) throws DockerAccessException { return docker.getContainersForImage(image, all); }
java
public List<Container> getContainersForImage(final String image, final boolean all) throws DockerAccessException { return docker.getContainersForImage(image, all); }
[ "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. @param image for which its container are looked up @param all whether to fetch all containers @return list of <code>Container</code> objects @throws DockerAccessException if the request fails
[ "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", "." ]
70ce4f56125d8efb8ddcf2ad4dbb5d6e2c7642b3
https://github.com/fabric8io/docker-maven-plugin/blob/70ce4f56125d8efb8ddcf2ad4dbb5d6e2c7642b3/src/main/java/io/fabric8/maven/docker/service/QueryService.java#L98-L100