public static String getResourceVersion(HasMetadata entity) {
        if (entity != null) {
            ObjectMeta metadata = entity.getMetadata();
            if (metadata != null) {
                String resourceVersion = metadata.getResourceVersion();
                if (StringUtils.isNotBlank(resourceVersion)) {
                    return resourceVersion;
                }
            }
        }
        return null;
    }

public static String getResourceVersion ( HasMetadata entity ) { if ( entity != null ) { ObjectMeta metadata = entity . getMetadata ( ) ; if ( metadata != null ) { String resourceVersion = metadata . getResourceVersion ( ) ; if ( StringUtils . isNotBlank ( resourceVersion ) ) { return resourceVersion ; } } } return null ; }

Returns the resource version for the entity or null if it does not have one


public static boolean isPodReady(Pod pod) {
        if (!isPodRunning(pod)) {
            return false;
        }

        PodStatus podStatus = pod.getStatus();
        if (podStatus == null) {
            return true;
        }

        List<PodCondition> conditions = podStatus.getConditions();
        if (conditions == null || conditions.isEmpty()) {
            return true;
        }

        // Check "ready" condition
        for (PodCondition condition : conditions) {
            if ("ready".equalsIgnoreCase(condition.getType())) {
                return Boolean.parseBoolean(condition.getStatus());
            }
        }

        return true;
    }

public
static
boolean
isPodReady
(
Pod
pod
)
{
if
(
!
isPodRunning
(
pod
)
)
{
return
false
;
}
PodStatus
podStatus
=
pod
.
getStatus
(
)
;
if
(
podStatus
==
)
{
return
true
;
}
List
<
PodCondition
>
conditions
=
podStatus
.
getConditions
(
)
;
if
(
conditions
==
||
conditions
.
isEmpty
(
)
)
{
return
true
;
}
// Check "ready" condition
for
(
PodCondition
condition
:
conditions
)
{
if
(
"ready"
.
equalsIgnoreCase
(
condition
.
getType
(
)
)
)
{
return
Boolean
.
parseBoolean
(
condition
.
getStatus
(
)
)
;
}
}
return
true
;
}

Returns true if the pod is running and ready


private static Context getCurrentContext(Config config) {
        String contextName = config.getCurrentContext();
        if (contextName != null) {
            List<NamedContext> contexts = config.getContexts();
            if (contexts != null) {
                for (NamedContext context : contexts) {
                    if (Objects.equals(contextName, context.getName())) {
                        return context.getContext();
                    }
                }
            }
        }
        return null;
    }

private static Context getCurrentContext ( Config config ) { String contextName = config . getCurrentContext ( ) ; if ( contextName != null ) { List < NamedContext > contexts = config . getContexts ( ) ; if ( contexts != null ) { for ( NamedContext context : contexts ) { if ( Objects . equals ( contextName , context . getName ( ) ) ) { return context . getContext ( ) ; } } } } return null ; }

Returns the current context in the given config


private boolean hasRoute(final KubernetesListBuilder listBuilder, final String name) {
        final AtomicBoolean answer = new AtomicBoolean(false);
        listBuilder.accept(new TypedVisitor<RouteBuilder>() {

            @Override
            public void visit(RouteBuilder builder) {
                ObjectMeta metadata = builder.getMetadata();
                if (metadata != null && name.equals(metadata.getName())) {
                    answer.set(true);
                }
            }
        });
        return answer.get();
    }

private boolean hasRoute ( final KubernetesListBuilder listBuilder , final String name ) { final AtomicBoolean answer = new AtomicBoolean ( false ) ; listBuilder . accept ( new TypedVisitor < RouteBuilder > ( ) { @ Override public void visit ( RouteBuilder builder ) { ObjectMeta metadata = builder . getMetadata ( ) ; if ( metadata != null && name . equals ( metadata . getName ( ) ) ) { answer . set ( true ) ; } } } ) ; return answer . get ( ) ; }

Returns true if we already have a route created for the given name


public static boolean hasResource(MavenProject project, String... paths) {
        URLClassLoader compileClassLoader = getCompileClassLoader(project);
        for (String path : paths) {
            try {
                if (compileClassLoader.getResource(path) != null) {
                    return true;
                }
            } catch (Throwable e) {
                // ignore
            }
        }
        return false;
    }

public
static
boolean
hasResource
(
MavenProject
project
,
String
...
paths
)
{
URLClassLoader
compileClassLoader
=
getCompileClassLoader
(
project
)
;
for
(
String
path
:
paths
)
{
try
{
if
(
compileClassLoader
.
getResource
(
path
)
!=
)
{
return
true
;
}
}
catch
(
Throwable
e
)
{
// ignore
}
}
return
false
;
}

Returns true if any of the given resources could be found on the given class loader


private static Map<String, Object> readAndEnrichFragment(PlatformMode platformMode, ResourceVersioning apiVersions,
                                                             File file, String appName) throws IOException {
        Pattern pattern = Pattern.compile(FILENAME_PATTERN, Pattern.CASE_INSENSITIVE);
        Matcher matcher = pattern.matcher(file.getName());
        if (!matcher.matches()) {
            throw new IllegalArgumentException(
                String.format("Resource file name '%s' does not match pattern <name>-<type>.(yaml|yml|json)", file.getName()));
        }
        String name = matcher.group("name");
        String type = matcher.group("type");
        String ext = matcher.group("ext").toLowerCase();
        String kind;

        Map<String,Object> fragment = readFragment(file, ext);

        if (type != null) {
            kind = getAndValidateKindFromType(file, type);
        } else {
            // Try name as type
            kind = FILENAME_TO_KIND_MAPPER.get(name.toLowerCase());
            if (kind != null) {
                // Name is in fact the type, so lets erase the name.
                name = null;
            }
        }

        addKind(fragment, kind, file.getName());

        String apiVersion = apiVersions.getCoreVersion();
        if (Objects.equals(kind, "Ingress")) {
            apiVersion = apiVersions.getExtensionsVersion();
        } else if (Objects.equals(kind, "StatefulSet") || Objects.equals(kind, "Deployment")) {
            apiVersion = apiVersions.getAppsVersion();
        } else if (Objects.equals(kind, "Job")) {
            apiVersion = apiVersions.getJobVersion();
        } else if (Objects.equals(kind, "DeploymentConfig") && platformMode == PlatformMode.openshift) {
            apiVersion = apiVersions.getOpenshiftV1version();
        }
        addIfNotExistent(fragment, "apiVersion", apiVersion);

        Map<String, Object> metaMap = getMetadata(fragment);
        // No name means: generated app name should be taken as resource name
        addIfNotExistent(metaMap, "name", StringUtils.isNotBlank(name) ? name : appName);

        return fragment;
    }


public static List<EnvVar> convertToEnvVarList(Map<String, String> envVars) {
        List<EnvVar> envList = new LinkedList<>();
        for (Map.Entry<String, String> entry : envVars.entrySet()) {
            String name = entry.getKey();
            String value = entry.getValue();

            if (name != null) {
                EnvVar env = new EnvVarBuilder().withName(name).withValue(value).build();
                envList.add(env);
            }
        }
        return envList;
    }

public static List < EnvVar > convertToEnvVarList ( Map < String , String > envVars ) { List < EnvVar > envList = new LinkedList <> ( ) ; for ( Map . Entry < String , String > entry : envVars . entrySet ( ) ) { String name = entry . getKey ( ) ; String value = entry . getValue ( ) ; if ( name != null ) { EnvVar env = new EnvVarBuilder ( ) . withName ( name ) . withValue ( value ) . build ( ) ; envList . add ( env ) ; } } return envList ; }

Convert a map of env vars to a list of K8s EnvVar objects.
@param envVars the name-value map containing env vars which must not be null
@return list of converted env vars

Convert a map of env vars to a list of K8s EnvVar objects .


public static HasMetadata mergeResources(HasMetadata item1, HasMetadata item2, Logger log, boolean switchOnLocalCustomisation) {
        if (item1 instanceof Deployment && item2 instanceof Deployment) {
            return mergeDeployments((Deployment) item1, (Deployment) item2, log, switchOnLocalCustomisation);
        }
        if (item1 instanceof ConfigMap && item2 instanceof ConfigMap) {
            ConfigMap cm1 = (ConfigMap) item1;
            ConfigMap cm2 = (ConfigMap) item2;
            return mergeConfigMaps(cm1, cm2, log, switchOnLocalCustomisation);
        }
        mergeMetadata(item1, item2);
        return item1;
    }

public static HasMetadata mergeResources ( HasMetadata item1 , HasMetadata item2 , Logger log , boolean switchOnLocalCustomisation ) { if ( item1 instanceof Deployment && item2 instanceof Deployment ) { return mergeDeployments ( ( Deployment ) item1 , ( Deployment ) item2 , log , switchOnLocalCustomisation ) ; } if ( item1 instanceof ConfigMap && item2 instanceof ConfigMap ) { ConfigMap cm1 = ( ConfigMap ) item1 ; ConfigMap cm2 = ( ConfigMap ) item2 ; return mergeConfigMaps ( cm1 , cm2 , log , switchOnLocalCustomisation ) ; } mergeMetadata ( item1 , item2 ) ; return item1 ; }

Merges the given resources together into a single resource.

If switchOnLocalCustomisation is false then the overrides from item2 are merged into item1

@return the newly merged resources

Merges the given resources together into a single resource .


private static Map<String, String> mergeMapsAndRemoveEmptyStrings(Map<String, String> overrideMap, Map<String, String> originalMap) {
        Map<String, String> answer = MapUtil.mergeMaps(overrideMap, originalMap);
        Set<Map.Entry<String, String>> entries = overrideMap.entrySet();
        for (Map.Entry<String, String> entry : entries) {
            String value = entry.getValue();
            if (value == null || value.isEmpty()) {
                String key = entry.getKey();
                answer.remove(key);
            }
        }
        return answer;
    }

private static Map < String , String > mergeMapsAndRemoveEmptyStrings ( Map < String , String > overrideMap , Map < String , String > originalMap ) { Map < String , String > answer = MapUtil . mergeMaps ( overrideMap , originalMap ) ; Set < Map . Entry < String , String > > entries = overrideMap . entrySet ( ) ; for ( Map . Entry < String , String > entry : entries ) { String value = entry . getValue ( ) ; if ( value == null || value . isEmpty ( ) ) { String key = entry . getKey ( ) ; answer . remove ( key ) ; } } return answer ; }

Returns a merge of the given maps and then removes any resulting empty string values (which is the way to remove, say, a label or annotation
when overriding

Returns a merge of the given maps and then removes any resulting empty string values ( which is the way to remove say a label or annotation when overriding


private static boolean isLocalCustomisation(PodSpec podSpec) {
        List<Container> containers = podSpec.getContainers() != null ? podSpec.getContainers() : Collections.<Container>emptyList();
        for (Container container : containers) {
            if (StringUtils.isNotBlank(container.getImage())) {
                return false;
            }
        }
        return true;
    }

private static boolean isLocalCustomisation ( PodSpec podSpec ) { List < Container > containers = podSpec . getContainers ( ) != null ? podSpec . getContainers ( ) : Collections . < Container > emptyList ( ) ; for ( Container container : containers ) { if ( StringUtils . isNotBlank ( container . getImage ( ) ) ) { return false ; } } return true ; }


private Map<String, String> readConfig(File f) throws IOException {
        Map<String, String> map;
        if (f.getName().endsWith(JSON_EXTENSION)) {
            map = flatten(JSON_MAPPER.readValue(f, Map.class));
        } else if (f.getName().endsWith(YAML_EXTENSION) || f.getName().endsWith(YML_EXTENSION)) {
            map = flatten(YAML_MAPPER.readValue(f, Map.class));
        } else if (f.getName().endsWith(PROPERTIES_EXTENSION)) {
            Properties properties = new Properties();
            properties.load(new FileInputStream(f));
            map = propertiesToMap(properties);
        } else {
            throw new IllegalArgumentException("Can't read configuration from: [" + f.getName() + "]. Unknown file extension.");
        }
        return map;
    }

private
Map
<
String
,
String
>
readConfig
(
File
f
)
throws
IOException
{
Map
<
String
,
String
>
map
;
if
(
f
.
getName
(
)
.
endsWith
(
JSON_EXTENSION
)
)
{
map
=
flatten
(
JSON_MAPPER
.
readValue
(
f
,
Map
.
class
)
)
;
}
else
if
(
f
.
getName
(
)
.
endsWith
(
YAML_EXTENSION
)
||
f
.
getName
(
)
.
endsWith
(
YML_EXTENSION
)
)
{
map
=
flatten
(
YAML_MAPPER
.
readValue
(
f
,
Map
.
class
)
)
;
}
else
if
(
f
.
getName
(
)
.
endsWith
(
PROPERTIES_EXTENSION
)
)
{
Properties
properties
=
new
Properties
(
)
;
properties
.
load
(
new
FileInputStream
(
f
)
)
;
map
=
propertiesToMap
(
properties
)
;
}
else
{
throw
new
IllegalArgumentException
(
"Can't read configuration from: ["
+
f
.
getName
(
)
+
"]. Unknown file extension."
)
;
}
return
map
;
}

Reads the configuration from the file.
@param f
@return
@throws IOException


private void addPortIfValid(Map<String, Integer> map, String key, String port) {
        if (StringUtils.isNotBlank(port)) {
            String t = port.trim();
            if (t.matches(NUMBER_REGEX)) {
                map.put(key, Integer.parseInt(t));
            }
        }
    }

private void addPortIfValid ( Map < String , Integer > map , String key , String port ) { if ( StringUtils . isNotBlank ( port ) ) { String t = port . trim ( ) ; if ( t . matches ( NUMBER_REGEX ) ) { map . put ( key , Integer . parseInt ( t ) ) ; } } }

Adds a port to the list.
@param map   The list.
@param key   The key.
@param port  The candidate port.


public String getDockerJsonConfigString(final Settings settings, final String serverId) {
        Server server = getServer(settings, serverId);
        if (server == null) {
            return "";
        }

        JsonObject auth = new JsonObject();
        auth.add("username", new JsonPrimitive(server.getUsername()));
        auth.add("password", new JsonPrimitive(server.getPassword()));

        String mail = getConfigurationValue(server, "email");
        if (!StringUtils.isBlank(mail)) {
            auth.add("email", new JsonPrimitive(mail));
        }

        JsonObject json = new JsonObject();
        json.add(serverId, auth);
        return json.toString();
    }

public String getDockerJsonConfigString ( final Settings settings , final String serverId ) { Server server = getServer ( settings , serverId ) ; if ( server == null ) { return "" ; } JsonObject auth = new JsonObject ( ) ; auth . add ( "username" , new JsonPrimitive ( server . getUsername ( ) ) ) ; auth . add ( "password" , new JsonPrimitive ( server . getPassword ( ) ) ) ; String mail = getConfigurationValue ( server , "email" ) ; if ( ! StringUtils . isBlank ( mail ) ) { auth . add ( "email" , new JsonPrimitive ( mail ) ) ; } JsonObject json = new JsonObject ( ) ; json . add ( serverId , auth ) ; return json . toString ( ) ; }


public Optional<Map<String, Object>> getPluginConfiguration(String system, String id) {
        return pluginConfigLookup.apply(system, id);
    }

public Optional < Map < String , Object > > getPluginConfiguration ( String system , String id ) { return pluginConfigLookup . apply ( system , id ) ; }

Gets plugin configuration values. Since there can be inner values,
it returns a Map of Objects where an Object can be a
simple type, List or another Map.

@param system the underlying build platform (e.g. "maven")
@param id which plugin configuration to pick
@return configuration map specific to this id

Gets plugin configuration values . Since there can be inner values it returns a Map of Objects where an Object can be a simple type List or another Map .


public Optional<Map<String, Object>> getSecretConfiguration(String id) {
        return secretConfigLookup.apply(id);
    }

public Optional < Map < String , Object > > getSecretConfiguration ( String id ) { return secretConfigLookup . apply ( id ) ; }

Gets configuration values. Since there can be inner values,
it returns a Map of Objects where an Object can be a
simple type, List or another Map.

@param id id specific to the secret store
@return configuration map specific to this id

Gets configuration values . Since there can be inner values it returns a Map of Objects where an Object can be a simple type List or another Map .


public static void download(Logger log, URL downloadUrl, File target) throws MojoExecutionException {
        log.progressStart();
        try {
            OkHttpClient client =
                new OkHttpClient.Builder()
                    .readTimeout(30, TimeUnit.MINUTES).build();
            Request request = new Request.Builder()
                .url(downloadUrl)
                .build();
            Response response = client.newCall(request).execute();

            try (OutputStream out = new FileOutputStream(target);
                 InputStream im = response.body().byteStream()) {

                long length = response.body().contentLength();
                InputStream in = response.body().byteStream();
                byte[] buffer = new byte[8192];

                long readBytes = 0;
                while (true) {
                    int len = in.read(buffer);
                    readBytes += len;
                    log.progressUpdate(target.getName(), "Downloading", getProgressBar(readBytes, length));
                    if (len <= 0) {
                        out.flush();
                        break;
                    }
                    out.write(buffer, 0, len);
                }
            }
        } catch (IOException e) {
            throw new MojoExecutionException("Failed to download URL " + downloadUrl + " to  " + target + ": " + e, e);
        } finally {
            log.progressFinished();
        }

    }

public
static
void
download
(
Logger
log
,
URL
downloadUrl
,
File
target
)
throws
MojoExecutionException
{
log
.
progressStart
(
)
;
try
{
OkHttpClient
client
=
new
OkHttpClient
.
Builder
(
)
.
readTimeout
(
30
,
TimeUnit
.
MINUTES
)
.
build
(
)
;
Request
request
=
new
Request
.
Builder
(
)
.
url
(
downloadUrl
)
.
build
(
)
;
Response
response
=
client
.
newCall
(
request
)
.
execute
(
)
;
try
(
OutputStream
out
=
new
FileOutputStream
(
target
)
;
InputStream
im
=
response
.
body
(
)
.
byteStream
(
)
)
{
long
length
=
response
.
body
(
)
.
contentLength
(
)
;
InputStream
in
=
response
.
body
(
)
.
byteStream
(
)
;
byte
[
]
buffer
=
new
byte
[
8192
]
;
long
readBytes
=
0
;
while
(
true
)
{
int
len
=
in
.
read
(
buffer
)
;
readBytes
+=
len
;
log
.
progressUpdate
(
target
.
getName
(
)
,
"Downloading"
,
getProgressBar
(
readBytes
,
length
)
)
;
if
(
len
<=
0
)
{
out
.
flush
(
)
;
break
;
}
out
.
write
(
buffer
,
0
,
len
)
;
}
}
}
catch
(
IOException
e
)
{
throw
new
MojoExecutionException
(
"Failed to download URL "
+
downloadUrl
+
" to  "
+
target
+
": "
+
e
,
e
)
;
}
finally
{
log
.
progressFinished
(
)
;
}
}

Download with showing the progress a given URL and store it in a file
@param log logger used to track progress
@param downloadUrl url to download
@param target target file where to store the downloaded data
@throws MojoExecutionException


public static int compareVersions(String v1, String v2) {
        String[] components1 = split(v1);
        String[] components2 = split(v2);
        int diff;
        int length = Math.min(components1.length, components2.length);
        for (int i = 0; i < length; i++) {
            String s1 = components1[i];
            String s2 = components2[i];
            Integer i1 = tryParseInteger(s1);
            Integer i2 = tryParseInteger(s2);
            if (i1 != null && i2 != null) {
                diff = i1.compareTo(i2);
            } else {
                // lets assume strings instead
                diff = s1.compareTo(s2);
            }
            if (diff != 0) {
                return diff;
            }
        }
        diff = Integer.compare(components1.length, components2.length);
        if (diff == 0) {
            if (v1 == v2) {
                return 0;
            }
            /* if v1 == null then v2 can't be null here (see 'if' above).
               So for v1 == null its always smaller than v2 */;
            return v1 != null ? v1.compareTo(v2) : -1;
        }
        return diff;
    }

Compares two version strings such that "1.10.1" > "1.4" etc

Compares two version strings such that 1 . 10 . 1 > 1 . 4 etc


public static ProcessorConfig blendProfileWithConfiguration(ProcessorConfigurationExtractor configExtractor,
                                                                String profile,
                                                                File resourceDir,
                                                                ProcessorConfig config) throws IOException {
        // Get specified profile or the default profile
        ProcessorConfig profileConfig = extractProcesssorConfiguration(configExtractor, profile, resourceDir);

        return ProcessorConfig.mergeProcessorConfigs(config, profileConfig);
    }

Find an enricher or generator config, possibly via a profile and merge it with a given configuration.

@param configExtractor how to extract the config from a profile when found
@param profile the profile name (can be null, then no profile is used)
@param resourceDir resource directory where to lookup the profile (in addition to a classpath lookup)
@return the merged configuration which can be empty if no profile is given
@param config the provided configuration
@throws IOException

Find an enricher or generator config possibly via a profile and merge it with a given configuration .


public static Profile lookup(String name, File directory) throws IOException {
        // First check from the classpath, these profiles are used as a basis
        List<Profile> profiles = readProfileFromClasspath(name);

        File profileFile = findProfileYaml(directory);
        if (profileFile != null) {
            List<Profile> fileProfiles = fromYaml(new FileInputStream(profileFile));
            for (Profile profile : fileProfiles) {
                if (profile.getName().equals(name)) {
                    profiles.add(profile);
                    break;
                }
            }
        }
        // "larger" orders are "earlier" in the list
        Collections.sort(profiles, Collections.<Profile>reverseOrder());
        return mergeProfiles(profiles);
    }

Lookup profiles from a given directory and merge it with a profile of the
same name found in the classpath

@param name name of the profile to lookup
@param directory directory to lookup
@return Profile found or null
@throws IOException if somethings fails during lookup


private static List<Profile> readProfileFromClasspath(String name) throws IOException {
        List<Profile> ret = new ArrayList<>();
        ret.addAll(readAllFromClasspath(name, "default"));
        ret.addAll(readAllFromClasspath(name, ""));
        return ret;
    }

private static List < Profile > readProfileFromClasspath ( String name ) throws IOException { List < Profile > ret = new ArrayList <> ( ) ; ret . addAll ( readAllFromClasspath ( name , "default" ) ) ; ret . addAll ( readAllFromClasspath ( name , "" ) ) ; return ret ; }

Read all default profiles first, then merge in custom profiles found on the classpath

Read all default profiles first then merge in custom profiles found on the classpath


public static List<Profile> readAllFromClasspath(String name, String ext) throws IOException {
        List<Profile > ret = new ArrayList<>();
        for (String location : getMetaInfProfilePaths(ext)) {
            for (String url : ClassUtil.getResources(location)) {
                for (Profile profile : fromYaml(new URL(url).openStream())) {
                    if (name.equals(profile.getName())) {
                        ret.add(profile);
                    }
                }
            }
        }
        return ret;
    }

public static List < Profile > readAllFromClasspath ( String name , String ext ) throws IOException { List < Profile > ret = new ArrayList <> ( ) ; for ( String location : getMetaInfProfilePaths ( ext ) ) { for ( String url : ClassUtil . getResources ( location ) ) { for ( Profile profile : fromYaml ( new URL ( url ) . openStream ( ) ) ) { if ( name . equals ( profile . getName ( ) ) ) { ret . add ( profile ) ; } } } } return ret ; }

Read all profiles found in the classpath.

@param name name of the profile to lookup
@param ext to use (e.g. 'default' for checking 'profile-default.yml'. Can also be null or empty.
@return all profiles with this name stored in files with this extension

@throws IOException if reading of a profile fails

Read all profiles found in the classpath .


private static File findProfileYaml(File directory) {
        for (String profileFile : PROFILE_FILENAMES) {
            File ret = new File(directory, String.format(profileFile, ""));
            if (ret.exists()) {
                return ret;
            }
        }
        return null;
    }

private static File findProfileYaml ( File directory ) { for ( String profileFile : PROFILE_FILENAMES ) { File ret = new File ( directory , String . format ( profileFile , "" ) ) ; if ( ret . exists ( ) ) { return ret ; } } return null ; }

check for various variations of profile files


private static List<String> getMetaInfProfilePaths(String ext) {
        List<String> ret = new ArrayList<>(PROFILE_FILENAMES.length);
        for (String p : PROFILE_FILENAMES) {
            ret.add("META-INF/fabric8/" + getProfileFileName(p,ext));
        }
        return ret;
    }

private static List < String > getMetaInfProfilePaths ( String ext ) { List < String > ret = new ArrayList <> ( PROFILE_FILENAMES . length ) ; for ( String p : PROFILE_FILENAMES ) { ret . add ( "META-INF/fabric8/" + getProfileFileName ( p , ext ) ) ; } return ret ; }


public static List<Profile> fromYaml(InputStream is) throws IOException {
        TypeReference<List<Profile>> typeRef = new TypeReference<List<Profile>>() {};
        return mapper.readValue(is, typeRef);
    }

public static List < Profile > fromYaml ( InputStream is ) throws IOException { TypeReference < List < Profile >> typeRef = new TypeReference < List < Profile > > ( ) { } ; return mapper . readValue ( is , typeRef ) ; }

Load a profile from an input stream. This must be in YAML format

@param is inputstream to read the profile from
@return the de-serialized profile
@throws IOException if deserialization fails

Load a profile from an input stream . This must be in YAML format


private String getImagePullPolicy(ResourceConfig resourceConfig, String defaultValue) {
        if(resourceConfig != null) {
            return resourceConfig.getImagePullPolicy() != null ? resourceConfig.getImagePullPolicy() : defaultValue;
        }
        return defaultValue;
    }

private String getImagePullPolicy ( ResourceConfig resourceConfig , String defaultValue ) { if ( resourceConfig != null ) { return resourceConfig . getImagePullPolicy ( ) != null ? resourceConfig . getImagePullPolicy ( ) : defaultValue ; } return defaultValue ; }

This method overrides the ImagePullPolicy value by the value provided in
XML config.

@param resourceConfig
@param defaultValue
@return

This method overrides the ImagePullPolicy value by the value provided in XML config .


protected boolean isOpenShiftMode() {
        Properties properties = getContext().getConfiguration().getProperties();
        if (properties != null) {
            return RuntimeMode.isOpenShiftMode(properties);
        }
        return false;
    }

protected boolean isOpenShiftMode ( ) { Properties properties = getContext ( ) . getConfiguration ( ) . getProperties ( ) ; if ( properties != null ) { return RuntimeMode . isOpenShiftMode ( properties ) ; } return false ; }

Returns true if we are in OpenShift S2I binary building mode


protected int getReplicaCount(KubernetesListBuilder builder, ResourceConfig xmlResourceConfig, int defaultValue) {
        if (xmlResourceConfig != null) {
            List<HasMetadata> items = builder.buildItems();
            for (HasMetadata item : items) {
                if (item instanceof Deployment) {
                    if(((Deployment)item).getSpec().getReplicas() != null) {
                        return ((Deployment)item).getSpec().getReplicas();
                    }
                }
                if (item instanceof DeploymentConfig) {
                    if(((DeploymentConfig)item).getSpec().getReplicas() != null) {
                        return ((DeploymentConfig)item).getSpec().getReplicas();
                    }
                }
            }
            return xmlResourceConfig.getReplicas() > 0 ? xmlResourceConfig.getReplicas() : defaultValue;
        }
        return defaultValue;
    }

protected int getReplicaCount ( KubernetesListBuilder builder , ResourceConfig xmlResourceConfig , int defaultValue ) { if ( xmlResourceConfig != null ) { List < HasMetadata > items = builder . buildItems ( ) ; for ( HasMetadata item : items ) { if ( item instanceof Deployment ) { if ( ( ( Deployment ) item ) . getSpec ( ) . getReplicas ( ) != null ) { return ( ( Deployment ) item ) . getSpec ( ) . getReplicas ( ) ; } } if ( item instanceof DeploymentConfig ) { if ( ( ( DeploymentConfig ) item ) . getSpec ( ) . getReplicas ( ) != null ) { return ( ( DeploymentConfig ) item ) . getSpec ( ) . getReplicas ( ) ; } } } return xmlResourceConfig . getReplicas ( ) > 0 ? xmlResourceConfig . getReplicas ( ) : defaultValue ; } return defaultValue ; }

This method just makes sure that the replica count provided in XML config
overrides the default option; and resource fragments are always given
topmost priority.

@param builder
@param xmlResourceConfig
@param defaultValue
@return resolved replica count

This method just makes sure that the replica count provided in XML config overrides the default option ; and resource fragments are always given topmost priority .


public static Element firstChild(Element element, String name) {
        NodeList nodes = element.getChildNodes();
        if (nodes != null) {
            for (int i = 0, size = nodes.getLength(); i < size; i++) {
                Node item = nodes.item(i);
                if (item instanceof Element) {
                    Element childElement = (Element) item;

                    if (name.equals(childElement.getTagName())) {
                        return childElement;
                    }
                }
            }
        }
        return null;
    }

public static Element firstChild ( Element element , String name ) { NodeList nodes = element . getChildNodes ( ) ; if ( nodes != null ) { for ( int i = 0 , size = nodes . getLength ( ) ; i < size ; i ++ ) { Node item = nodes . item ( i ) ; if ( item instanceof Element ) { Element childElement = ( Element ) item ; if ( name . equals ( childElement . getTagName ( ) ) ) { return childElement ; } } } } return null ; }

Returns the first child element for the given name


public void installTemplate(Template entity, String sourceName) {
        OpenShiftClient openShiftClient = getOpenShiftClient();
        if (openShiftClient == null) {
            // lets not install the template on Kubernetes!
            return;
        }
        if (!isProcessTemplatesLocally()) {
            String namespace = getNamespace();
            String id = getName(entity);
            Objects.requireNonNull(id, "No name for " + entity + " " + sourceName);
            Template old = openShiftClient.templates().inNamespace(namespace).withName(id).get();
            if (isRunning(old)) {
                if (UserConfigurationCompare.configEqual(entity, old)) {
                    log.info("Template has not changed so not doing anything");
                } else {
                    boolean recreateMode = isRecreateMode();
                    // TODO seems you can't update templates right now
                    recreateMode = true;
                    if (recreateMode) {
                        openShiftClient.templates().inNamespace(namespace).withName(id).delete();
                        doCreateTemplate(entity, namespace, sourceName);
                    } else {
                        log.info("Updating a Template from " + sourceName);
                        try {
                            Object answer = openShiftClient.templates().inNamespace(namespace).withName(id).replace(entity);
                            log.info("Updated Template: " + answer);
                        } catch (Exception e) {
                            onApplyError("Failed to update Template from " + sourceName + ". " + e + ". " + entity, e);
                        }
                    }
                }
            } else {
                if (!isAllowCreate()) {
                    log.warn("Creation disabled so not creating a Template from " + sourceName + " namespace " + namespace + " name " + getName(entity));
                } else {
                    doCreateTemplate(entity, namespace, sourceName);
                }
            }
        }
    }

Installs the template into the namespace without processing it


private int removeTagByName(List<TagReference> tags, String tagName) {
        List<TagReference> removeTags = new ArrayList<>();
        for (TagReference tag : tags) {
            if (Objects.equals(tagName, tag.getName())) {
                removeTags.add(tag);
            }
        }
        tags.removeAll(removeTags);
        return removeTags.size();
    }

private int removeTagByName ( List < TagReference > tags , String tagName ) { List < TagReference > removeTags = new ArrayList <> ( ) ; for ( TagReference tag : tags ) { if ( Objects . equals ( tagName , tag . getName ( ) ) ) { removeTags . add ( tag ) ; } } tags . removeAll ( removeTags ) ; return removeTags . size ( ) ; }

Removes all the tags with the given name
@return the number of tags removed


public boolean applyNamespace(Namespace entity) {
        String namespace = getOrCreateMetadata(entity).getName();
        log.info("Using namespace: " + namespace);
        String name = getName(entity);
        Objects.requireNonNull(name, "No name for " + entity );
        Namespace old = kubernetesClient.namespaces().withName(name).get();
        if (!isRunning(old)) {
            try {
                Object answer = kubernetesClient.namespaces().create(entity);
                logGeneratedEntity("Created namespace: ", namespace, entity, answer);
                return true;
            } catch (Exception e) {
                onApplyError("Failed to create namespace: " + name + " due " + e.getMessage(), e);
            }
        }
        return false;
    }

public
boolean
applyNamespace
(
Namespace
entity
)
{
String
namespace
=
getOrCreateMetadata
(
entity
)
.
getName
(
)
;
log
.
info
(
"Using namespace: "
+
namespace
)
;
String
name
=
getName
(
entity
)
;
Objects
.
requireNonNull
(
name
,
"No name for "
+
entity
)
;
Namespace
old
=
kubernetesClient
.
namespaces
(
)
.
withName
(
name
)
.
get
(
)
;
if
(
!
isRunning
(
old
)
)
{
try
{
Object
answer
=
kubernetesClient
.
namespaces
(
)
.
create
(
entity
)
;
logGeneratedEntity
(
"Created namespace: "
,
namespace
,
entity
,
answer
)
;
return
true
;
}
catch
(
Exception
e
)
{
onApplyError
(
"Failed to create namespace: "
+
name
+
" due "
+
e
.
getMessage
(
)
,
e
)
;
}
}
return
false
;
}

Returns true if the namespace is created


public boolean applyProject(Project project) {
        return applyProjectRequest(new ProjectRequestBuilder()
                .withDisplayName(project.getMetadata().getName())
                .withMetadata(project.getMetadata()).build());
    }

public boolean applyProject ( Project project ) { return applyProjectRequest ( new ProjectRequestBuilder ( ) . withDisplayName ( project . getMetadata ( ) . getName ( ) ) . withMetadata ( project . getMetadata ( ) ) . build ( ) ) ; }

Creates and return a project in openshift
@param project
@return


public boolean applyProjectRequest(ProjectRequest entity) {
        String namespace = getOrCreateMetadata(entity).getName();
        log.info("Using project: " + namespace);
        String name = getName(entity);
        Objects.requireNonNull(name, "No name for " + entity);
        OpenShiftClient openshiftClient = getOpenShiftClient();
        if (openshiftClient == null) {
            log.warn("Cannot check for Project " + namespace + " as not running against OpenShift!");
            return false;
        }
        boolean exists = checkNamespace(name);
        // We may want to be more fine-grained on the phase of the project
        if (!exists) {
            try {
                Object answer = openshiftClient.projectrequests().create(entity);
                logGeneratedEntity("Created ProjectRequest: ", namespace, entity, answer);
                return true;
            } catch (Exception e) {
                onApplyError("Failed to create ProjectRequest: " + name + " due " + e.getMessage(), e);
            }
        }
        return false;
    }

Returns true if the ProjectRequest is created


protected String getNamespace(HasMetadata entity) {
        String answer = KubernetesHelper.getNamespace(entity);
        if (StringUtils.isBlank(answer)) {
            answer = getNamespace();
        }
        // lest make sure the namespace exists
        applyNamespace(answer);
        return answer;
    }

protected
String
getNamespace
(
HasMetadata
entity
)
{
String
answer
=
KubernetesHelper
.
getNamespace
(
entity
)
;
if
(
StringUtils
.
isBlank
(
answer
)
)
{
answer
=
getNamespace
(
)
;
}
// lest make sure the namespace exists
applyNamespace
(
answer
)
;
return
answer
;
}

Returns the namespace defined in the entity or the configured namespace


protected void onApplyError(String message, Exception e) {
        log.error(message, e);
        throw new RuntimeException(message, e);
    }

protected void onApplyError ( String message , Exception e ) { log . error ( message , e ) ; throw new RuntimeException ( message , e ) ; }

Logs an error applying some JSON to Kubernetes and optionally throws an exception


@Override
    public void create(PlatformMode platformMode, KubernetesListBuilder builder) {

        final String name = config.getNamespace();

        if (name == null || name.isEmpty()) {
            return;
        }

        if (!KubernetesResourceUtil.checkForKind(builder, NAMESPACE_KINDS)) {
            String type = getConfig(Config.type);
            if ("project".equalsIgnoreCase(type) || "namespace".equalsIgnoreCase(type)) {
                if (platformMode == PlatformMode.kubernetes) {

                    log.info("Adding a default Namespace:" + config.getNamespace());
                    Namespace namespace = handlerHub.getNamespaceHandler().getNamespace(config.getNamespace());
                    builder.addToNamespaceItems(namespace);
                } else {

                    log.info("Adding a default Project" + config.getNamespace());
                    Project project = handlerHub.getProjectHandler().getProject(config.getNamespace());
                    builder.addToProjectItems(project);
                }
            }
        }
    }

@
Override
public
void
create
(
PlatformMode
platformMode
,
KubernetesListBuilder
builder
)
{
final
String
name
=
config
.
getNamespace
(
)
;
if
(
name
==
||
name
.
isEmpty
(
)
)
{
return
;
}
if
(
!
KubernetesResourceUtil
.
checkForKind
(
builder
,
NAMESPACE_KINDS
)
)
{
String
type
=
getConfig
(
Config
.
type
)
;
if
(
"project"
.
equalsIgnoreCase
(
type
)
||
"namespace"
.
equalsIgnoreCase
(
type
)
)
{
if
(
platformMode
==
PlatformMode
.
kubernetes
)
{
log
.
info
(
"Adding a default Namespace:"
+
config
.
getNamespace
(
)
)
;
Namespace
namespace
=
handlerHub
.
getNamespaceHandler
(
)
.
getNamespace
(
config
.
getNamespace
(
)
)
;
builder
.
addToNamespaceItems
(
namespace
)
;
}
else
{
log
.
info
(
"Adding a default Project"
+
config
.
getNamespace
(
)
)
;
Project
project
=
handlerHub
.
getProjectHandler
(
)
.
getProject
(
config
.
getNamespace
(
)
)
;
builder
.
addToProjectItems
(
project
)
;
}
}
}
}

This method will create a default Namespace or Project if a namespace property is
specified in the xml resourceConfig or as a parameter to a mojo.
@param platformMode
@param builder

This method will create a default Namespace or Project if a namespace property is specified in the xml resourceConfig or as a parameter to a mojo .


@Override
    public void enrich(PlatformMode platformMode, KubernetesListBuilder builder) {

        builder.accept(new TypedVisitor<ObjectMetaBuilder>() {
            private String getNamespaceName() {
                String name = null;
                if (config.getNamespace() != null && !config.getNamespace().isEmpty()) {
                    name = config.getNamespace();
                }

                name = builder.getItems().stream()
                        .filter(item -> Arrays.asList(NAMESPACE_KINDS).contains(item.getKind()))
                        .findFirst().get().getMetadata().getName();

                return name;
            }

            @Override
            public void visit(ObjectMetaBuilder metaBuilder) {
                if (!KubernetesResourceUtil.checkForKind(builder, NAMESPACE_KINDS)) {
                    return;
                }

                String name = getNamespaceName();
                if (name == null || name.isEmpty()) {
                    return;
                }

                metaBuilder.withNamespace(name).build();
            }
        });

        // Removing namespace annotation from the namespace and project objects being generated.
        // to avoid unncessary trouble while applying these resources.
        builder.accept(new TypedVisitor<NamespaceBuilder>() {
            @Override
            public void visit(NamespaceBuilder builder) {
                builder.withNewStatus("active").editMetadata().withNamespace(null).endMetadata().build();
            }
        });

        builder.accept(new TypedVisitor<ProjectBuilder>() {
            @Override
            public void visit(ProjectBuilder builder) {
                builder.withNewStatus("active").editMetadata().withNamespace(null).endMetadata().build();
            }
        });
    }

This method will annotate all the items in the KubernetesListBuilder with the
created new namespace or project.
@param platformMode
@param builder

This method will annotate all the items in the KubernetesListBuilder with the created new namespace or project .


protected Map<String, String> getEnv(boolean prePackagePhase) throws MojoExecutionException {
        Map<String, String> ret = new HashMap<>();
        if (!isFatJar()) {
            String mainClass = getConfig(Config.mainClass);
            if (mainClass == null) {
                mainClass = mainClassDetector.getMainClass();
                if (mainClass == null) {
                    if (!prePackagePhase) {
                        throw new MojoExecutionException("Cannot extract main class to startup");
                    }
                }
            }
            if (mainClass != null) {
                log.verbose("Detected main class %s", mainClass);
                ret.put(JAVA_MAIN_CLASS_ENV_VAR, mainClass);
            }
        }
        List<String> javaOptions = getExtraJavaOptions();
        if (javaOptions.size() > 0) {
            ret.put(JAVA_OPTIONS, StringUtils.join(javaOptions.iterator(), " "));
        }
        return ret;
    }

protected
Map
<
String
,
String
>
getEnv
(
boolean
prePackagePhase
)
throws
MojoExecutionException
{
Map
<
String
,
String
>
ret
=
new
HashMap
<>
(
)
;
if
(
!
isFatJar
(
)
)
{
String
mainClass
=
getConfig
(
Config
.
mainClass
)
;
if
(
mainClass
==
)
{
mainClass
=
mainClassDetector
.
getMainClass
(
)
;
if
(
mainClass
==
)
{
if
(
!
prePackagePhase
)
{
throw
new
MojoExecutionException
(
"Cannot extract main class to startup"
)
;
}
}
}
if
(
mainClass
!=
)
{
log
.
verbose
(
"Detected main class %s"
,
mainClass
)
;
ret
.
put
(
JAVA_MAIN_CLASS_ENV_VAR
,
mainClass
)
;
}
}
List
<
String
>
javaOptions
=
getExtraJavaOptions
(
)
;
if
(
javaOptions
.
size
(
)
>
0
)
{
ret
.
put
(
JAVA_OPTIONS
,
StringUtils
.
join
(
javaOptions
.
iterator
(
)
,
" "
)
)
;
}
return
ret
;
}

Hook for adding extra environment vars

@return map with environment variables to use
@param prePackagePhase


public static Integer durationSeconds(String duration) {
        BigDecimal ns = durationNs(duration);
        if (ns == null) {
            return null;
        }

        BigDecimal sec = ns.divide(new BigDecimal(1_000_000_000));
        if (sec.compareTo(new BigDecimal(Integer.MAX_VALUE)) > 0) {
            throw new IllegalArgumentException("Integer Overflow");
        }
        return sec.intValue();
    }

public
static
Integer
durationSeconds
(
String
duration
)
{
BigDecimal
ns
=
durationNs
(
duration
)
;
if
(
ns
==
)
{
return
;
}
BigDecimal
sec
=
ns
.
divide
(
new
BigDecimal
(
1_000_000_000
)
)
;
if
(
sec
.
compareTo
(
new
BigDecimal
(
Integer
.
MAX_VALUE
)
)
>
0
)
{
throw
new
IllegalArgumentException
(
"Integer Overflow"
)
;
}
return
sec
.
intValue
(
)
;
}

Parses a duration string anr returns its value in seconds.

Parses a duration string anr returns its value in seconds .


public static BigDecimal durationNs(String durationP) {
        if (durationP == null) {
            return null;
        }
        String duration = durationP.trim();
        if (duration.length() == 0) {
            return null;
        }

        int unitPos = 1;
        while (unitPos < duration.length() && (Character.isDigit(duration.charAt(unitPos)) || duration.charAt(unitPos) == '.')) {
            unitPos++;
        }

        if (unitPos >= duration.length()) {
            throw new IllegalArgumentException("Time unit not found in string: " + duration);
        }

        String tail = duration.substring(unitPos);

        Long multiplier = null;
        Integer unitEnd = null;
        for(int i=0; i<TIME_UNITS.length; i++) {
            if (tail.startsWith(TIME_UNITS[i])) {
                multiplier = UNIT_MULTIPLIERS[i];
                unitEnd = unitPos + TIME_UNITS[i].length();
                break;
            }
        }

        if (multiplier == null) {
            throw new IllegalArgumentException("Unknown time unit in string: " + duration);
        }

        BigDecimal value = new BigDecimal(duration.substring(0, unitPos));
        value = value.multiply(BigDecimal.valueOf(multiplier));

        String remaining = duration.substring(unitEnd);
        BigDecimal remainingValue = durationNs(remaining);
        if (remainingValue != null) {
            value = value.add(remainingValue);
        }

        return value;
    }

public
static
BigDecimal
durationNs
(
String
durationP
)
{
if
(
durationP
==
)
{
return
;
}
String
duration
=
durationP
.
trim
(
)
;
if
(
duration
.
length
(
)
==
0
)
{
return
;
}
int
unitPos
=
1
;
while
(
unitPos
<
duration
.
length
(
)
&&
(
Character
.
isDigit
(
duration
.
charAt
(
unitPos
)
)
||
duration
.
charAt
(
unitPos
)
==
'
'
)
)
{
unitPos
++
;
}
if
(
unitPos
>=
duration
.
length
(
)
)
{
throw
new
IllegalArgumentException
(
"Time unit not found in string: "
+
duration
)
;
}
String
tail
=
duration
.
substring
(
unitPos
)
;
Long
multiplier
=
;
Integer
unitEnd
=
;
for
(
int
i
=
0
;
i
<
TIME_UNITS
.
length
;
i
++
)
{
if
(
tail
.
startsWith
(
TIME_UNITS
[
i
]
)
)
{
multiplier
=
UNIT_MULTIPLIERS
[
i
]
;
unitEnd
=
unitPos
+
TIME_UNITS
[
i
]
.
length
(
)
;
break
;
}
}
if
(
multiplier
==
)
{
throw
new
IllegalArgumentException
(
"Unknown time unit in string: "
+
duration
)
;
}
BigDecimal
value
=
new
BigDecimal
(
duration
.
substring
(
0
,
unitPos
)
)
;
value
=
value
.
multiply
(
BigDecimal
.
valueOf
(
multiplier
)
)
;
String
remaining
=
duration
.
substring
(
unitEnd
)
;
BigDecimal
remainingValue
=
durationNs
(
remaining
)
;
if
(
remainingValue
!=
)
{
value
=
value
.
add
(
remainingValue
)
;
}
return
value
;
}

Parses a duration string anr returns its value in nanoseconds.

Parses a duration string anr returns its value in nanoseconds .


protected String[] scanFiles(String... patterns) {
        String buildOutputDir = project.getBuild().getDirectory();
        if (buildOutputDir != null && new File(buildOutputDir).exists()) {
            DirectoryScanner directoryScanner = new DirectoryScanner();
            directoryScanner.setBasedir(buildOutputDir);
            directoryScanner.setIncludes(patterns);
            directoryScanner.scan();
            return directoryScanner.getIncludedFiles();
        } else {
            return new String[0];
        }

    }

protected String [ ] scanFiles ( String ... patterns ) { String buildOutputDir = project . getBuild ( ) . getDirectory ( ) ; if ( buildOutputDir != null && new File ( buildOutputDir ) . exists ( ) ) { DirectoryScanner directoryScanner = new DirectoryScanner ( ) ; directoryScanner . setBasedir ( buildOutputDir ) ; directoryScanner . setIncludes ( patterns ) ; directoryScanner . scan ( ) ; return directoryScanner . getIncludedFiles ( ) ; } else { return new String [ 0 ] ; } }

Scan the project's output directory for certain files.

@param patterns one or more patterns which fit to Maven's include syntax
@return list of files found

Scan the project s output directory for certain files .


protected void disableOpenShiftFeatures(ApplyService applyService) {
        // TODO we could check if the Templates service is running and if so we could still support templates?
        this.processTemplatesLocally = true;
        applyService.setSupportOAuthClients(false);
        applyService.setProcessTemplatesLocally(true);
    }

Lets disable OpenShift-only features if we are not running on OpenShift

Lets disable OpenShift - only features if we are not running on OpenShift


private boolean serviceHasIngressRule(List<Ingress> ingresses, Service service) {
        String serviceName = KubernetesHelper.getName(service);
        for (Ingress ingress : ingresses) {
            IngressSpec spec = ingress.getSpec();
            if (spec == null) {
                break;
            }
            List<IngressRule> rules = spec.getRules();
            if (rules == null) {
                break;
            }
            for (IngressRule rule : rules) {
                HTTPIngressRuleValue http = rule.getHttp();
                if (http == null) {
                    break;
                }
                List<HTTPIngressPath> paths = http.getPaths();
                if (paths == null) {
                    break;
                }
                for (HTTPIngressPath path : paths) {
                    IngressBackend backend = path.getBackend();
                    if (backend == null) {
                        break;
                    }
                    if (Objects.equals(serviceName, backend.getServiceName())) {
                        return true;
                    }
                }
            }
        }
        return false;
    }

private boolean serviceHasIngressRule ( List < Ingress > ingresses , Service service ) { String serviceName = KubernetesHelper . getName ( service ) ; for ( Ingress ingress : ingresses ) { IngressSpec spec = ingress . getSpec ( ) ; if ( spec == null ) { break ; } List < IngressRule > rules = spec . getRules ( ) ; if ( rules == null ) { break ; } for ( IngressRule rule : rules ) { HTTPIngressRuleValue http = rule . getHttp ( ) ; if ( http == null ) { break ; } List < HTTPIngressPath > paths = http . getPaths ( ) ; if ( paths == null ) { break ; } for ( HTTPIngressPath path : paths ) { IngressBackend backend = path . getBackend ( ) ; if ( backend == null ) { break ; } if ( Objects . equals ( serviceName , backend . getServiceName ( ) ) ) { return true ; } } } } return false ; }

Returns true if there is an existing ingress rule for the given service


public Map<String, List<String>> parse(final InputStream mapping) {

        final Properties mappingProperties = new Properties();
        try {
            mappingProperties.load(mapping);

            final Map<String, List<String>> serializedContent = new HashMap<>();

            final Set<String> kinds = mappingProperties.stringPropertyNames();

            for (String kind : kinds) {
                final String filenames = mappingProperties.getProperty(kind);
                final String[] filenameTypes = filenames.split(",");
                final List<String> scannedFiletypes = new ArrayList<>();
                for (final String filenameType : filenameTypes) {
                    scannedFiletypes.add(filenameType.trim());
                }
                serializedContent.put(kind, scannedFiletypes);
            }

            return serializedContent;
        } catch (IOException e) {
            throw new IllegalStateException(e);
        }
    }

public Map < String , List < String > > parse ( final InputStream mapping ) { final Properties mappingProperties = new Properties ( ) ; try { mappingProperties . load ( mapping ) ; final Map < String , List < String > > serializedContent = new HashMap <> ( ) ; final Set < String > kinds = mappingProperties . stringPropertyNames ( ) ; for ( String kind : kinds ) { final String filenames = mappingProperties . getProperty ( kind ) ; final String [ ] filenameTypes = filenames . split ( "," ) ; final List < String > scannedFiletypes = new ArrayList <> ( ) ; for ( final String filenameType : filenameTypes ) { scannedFiletypes . add ( filenameType . trim ( ) ) ; } serializedContent . put ( kind , scannedFiletypes ) ; } return serializedContent ; } catch ( IOException e ) { throw new IllegalStateException ( e ) ; } }

This method reads properties file to load custom mapping between kinds and filenames.

<pre>
ConfigMap=cm, configmap
Service=service
</pre>

@param mapping
stream of a properties file setting mappings between kinds and filenames.

@return Serialization of all elements as a map

This method reads properties file to load custom mapping between kinds and filenames .


private GeneratorContext getGeneratorContext() {
        return new GeneratorContext.Builder()
                .config(extractGeneratorConfig())
                .project(project)
                .logger(log)
                .runtimeMode(runtimeMode)
                .strategy(buildStrategy)
                .useProjectClasspath(useProjectClasspath)
                .artifactResolver(getFabric8ServiceHub().getArtifactResolverService())
                .build();
    }

private GeneratorContext getGeneratorContext ( ) { return new GeneratorContext . Builder ( ) . config ( extractGeneratorConfig ( ) ) . project ( project ) . logger ( log ) . runtimeMode ( runtimeMode ) . strategy ( buildStrategy ) . useProjectClasspath ( useProjectClasspath ) . artifactResolver ( getFabric8ServiceHub ( ) . getArtifactResolverService ( ) ) . build ( ) ; }


private ProcessorConfig extractGeneratorConfig() {
        try {
            return ProfileUtil.blendProfileWithConfiguration(ProfileUtil.GENERATOR_CONFIG, profile, ResourceDirCreator.getFinalResourceDir(resourceDir, environment), generator);
        } catch (IOException e) {
            throw new IllegalArgumentException("Cannot extract generator config: " + e,e);
        }
    }

private
ProcessorConfig
extractGeneratorConfig
(
)
{
try
{
return
ProfileUtil
.
blendProfileWithConfiguration
(
ProfileUtil
.
GENERATOR_CONFIG
,
profile
,
ResourceDirCreator
.
getFinalResourceDir
(
resourceDir
,
environment
)
,
generator
)
;
}
catch
(
IOException
e
)
{
throw
new
IllegalArgumentException
(
"Cannot extract generator config: "
+
e
,
e
)
;
}
}


public EnricherContext getEnricherContext() {
        return new MavenEnricherContext.Builder()
                .project(project)
                .properties(project.getProperties())
                .session(session)
                .config(extractEnricherConfig())
                .images(getResolvedImages())
                .resources(resources)
                .log(log)
                .build();
    }

public EnricherContext getEnricherContext ( ) { return new MavenEnricherContext . Builder ( ) . project ( project ) . properties ( project . getProperties ( ) ) . session ( session ) . config ( extractEnricherConfig ( ) ) . images ( getResolvedImages ( ) ) . resources ( resources ) . log ( log ) . build ( ) ; }


private ProcessorConfig extractEnricherConfig() {
        try {
            return ProfileUtil.blendProfileWithConfiguration(ProfileUtil.ENRICHER_CONFIG, profile, ResourceDirCreator.getFinalResourceDir(resourceDir, environment), enricher);
        } catch (IOException e) {
            throw new IllegalArgumentException("Cannot extract enricher config: " + e,e);
        }
    }

private
ProcessorConfig
extractEnricherConfig
(
)
{
try
{
return
ProfileUtil
.
blendProfileWithConfiguration
(
ProfileUtil
.
ENRICHER_CONFIG
,
profile
,
ResourceDirCreator
.
getFinalResourceDir
(
resourceDir
,
environment
)
,
enricher
)
;
}
catch
(
IOException
e
)
{
throw
new
IllegalArgumentException
(
"Cannot extract enricher config: "
+
e
,
e
)
;
}
}


private String getDefaultIconRef() {
        ProjectClassLoaders cls = getContext().getProjectClassLoaders();
        if (cls.isClassInCompileClasspath(false, "io.fabric8.funktion.runtime.Main") ||
            getContext().hasDependency( "io.fabric8.funktion", null)) {
            return "funktion";
        }
        if (cls.isClassInCompileClasspath(false, "org.apache.camel.CamelContext")) {
            return "camel";
        }
        if (getContext().hasPlugin(null, SpringBootConfigurationHelper.SPRING_BOOT_MAVEN_PLUGIN_ARTIFACT_ID)  ||
            cls.isClassInCompileClasspath(false, "org.springframework.boot.SpringApplication")) {
            return "spring-boot";
        }
        if (cls.isClassInCompileClasspath(false, "org.springframework.core.Constants")) {
            return "spring";
        }
        if (cls.isClassInCompileClasspath(false, "org.vertx.java.core.Handler", "io.vertx.core.Handler")) {
            return "vertx";
        }

        if (getContext().hasPlugin("org.wildfly.swarm", "wildfly-swarm-plugin") ||
            getContext().hasDependency( "org.wildfly.swarm", null)) {
            return "wildfly-swarm";
        }
        if (getContext().hasPlugin( "io.thorntail", "thorntail-maven-plugin") ||
            getContext().hasDependency( "io.thorntail", null)) {
            // use the WildFly Swarm icon until there's a dedicated Thorntail icon
            // Thorntail is a new name of WildFly Swarm
            return "wildfly-swarm";
        }

        return null;
    }

Lets use the project and its classpath to try figure out what default icon to use

@return the icon ref if we can detect one or return null


private void copyAppConfigFiles(File appBuildDir, File appConfigDir) throws IOException {
        File[] files = appConfigDir.listFiles();
        if (files != null) {
            appBuildDir.mkdirs();
            for (File file : files) {
                File outFile = new File(appBuildDir, file.getName());
                if (file.isDirectory()) {
                    copyAppConfigFiles(outFile, file);
                } else {
                    Files.copy(file, outFile);
                }
            }
        }
    }

private void copyAppConfigFiles ( File appBuildDir , File appConfigDir ) throws IOException { File [ ] files = appConfigDir . listFiles ( ) ; if ( files != null ) { appBuildDir . mkdirs ( ) ; for ( File file : files ) { File outFile = new File ( appBuildDir , file . getName ( ) ) ; if ( file . isDirectory ( ) ) { copyAppConfigFiles ( outFile , file ) ; } else { Files . copy ( file , outFile ) ; } } } }

Copies any local configuration files into the app directory


protected static Properties getPropertiesResource(URL resource) {
        Properties answer = new Properties();
        if (resource != null) {
            try(InputStream stream = resource.openStream()) {
                answer.load(stream);
            } catch (IOException e) {
                throw new IllegalStateException("Error while reading resource from URL " + resource, e);
            }
        }
        return answer;
    }

Returns the given properties resource on the project classpath if found or an empty properties object if not


public static Optional<String> getSpringBootVersion(MavenProject mavenProject) {
        return Optional.ofNullable(MavenUtil.getDependencyVersion(mavenProject, SpringBootConfigurationHelper.SPRING_BOOT_GROUP_ID, SpringBootConfigurationHelper.SPRING_BOOT_ARTIFACT_ID));
    }

public static Optional < String > getSpringBootVersion ( MavenProject mavenProject ) { return Optional . ofNullable ( MavenUtil . getDependencyVersion ( mavenProject , SpringBootConfigurationHelper . SPRING_BOOT_GROUP_ID , SpringBootConfigurationHelper . SPRING_BOOT_ARTIFACT_ID ) ) ; }

Determine the spring-boot major version for the current project

Determine the spring - boot major version for the current project


public <T> List<T> createServiceObjects(String... descriptorPaths) {
        try {
            ServiceEntry.initDefaultOrder();
            TreeMap<ServiceEntry,T> serviceMap = new TreeMap<ServiceEntry,T>();
            for (String descriptor : descriptorPaths) {
                readServiceDefinitions(serviceMap, descriptor);
            }
            ArrayList<T> ret = new ArrayList<T>();
            for (T service : serviceMap.values()) {
                ret.add(service);
            }
            return ret;
        } finally {
            ServiceEntry.removeDefaultOrder();
        }
    }

public < T > List < T > createServiceObjects ( String ... descriptorPaths ) { try { ServiceEntry . initDefaultOrder ( ) ; TreeMap < ServiceEntry , T > serviceMap = new TreeMap < ServiceEntry , T > ( ) ; for ( String descriptor : descriptorPaths ) { readServiceDefinitions ( serviceMap , descriptor ) ; } ArrayList < T > ret = new ArrayList < T > ( ) ; for ( T service : serviceMap . values ( ) ) { ret . add ( service ) ; } return ret ; } finally { ServiceEntry . removeDefaultOrder ( ) ; } }

Create a list of services ordered according to the ordering given in the
service descriptor files. Note, that the descriptor will be looked up
in the whole classpath space, which can result in reading in multiple
descriptors with a single path. Note, that the reading order for multiple
resources with the same name is not defined.

@param descriptorPaths a list of resource paths which are handle in the given order.
Normally, default service should be given as first parameter so that custom
descriptors have a chance to remove a default service.
@param <T> type of the service objects to create
@return a ordered list of created services or an empty list.

Create a list of services ordered according to the ordering given in the service descriptor files . Note that the descriptor will be looked up in the whole classpath space which can result in reading in multiple descriptors with a single path . Note that the reading order for multiple resources with the same name is not defined .


private void enrich(PlatformMode platformMode, final ProcessorConfig enricherConfig, final KubernetesListBuilder builder, final List<Enricher> enricherList) {
        loop(enricherConfig, enricher -> {
                enricher.enrich(platformMode, builder);
                return null;
            });
    }

private void enrich ( PlatformMode platformMode , final ProcessorConfig enricherConfig , final KubernetesListBuilder builder , final List < Enricher > enricherList ) { loop ( enricherConfig , enricher -> { enricher . enrich ( platformMode , builder ) ; return null ; } ) ; }

Allow enricher to add Metadata to the resources.

@param builder builder to customize
@param enricherList list of enrichers

Allow enricher to add Metadata to the resources .


public Map<String, String> getRawConfig() {
        return configuration.getProcessorConfig().orElse(ProcessorConfig.EMPTY).getConfigMap(name);
    }

public Map < String , String > getRawConfig ( ) { return configuration . getProcessorConfig ( ) . orElse ( ProcessorConfig . EMPTY ) . getConfigMap ( name ) ; }

Get the raw, untyped configuration or an empty map
@return raw configuration.

Get the raw untyped configuration or an empty map


private static Map<String, Object> getFlattenedMap(Map<String, Object> source) {
        Map<String, Object> result = new LinkedHashMap<>();
        buildFlattenedMap(result, source, null);
        return result;
    }

private static Map < String , Object > getFlattenedMap ( Map < String , Object > source ) { Map < String , Object > result = new LinkedHashMap <> ( ) ; buildFlattenedMap ( result , source , null ) ; return result ; }

Build a flattened representation of the Yaml tree. The conversion is compliant with the thorntail spring-boot rules.

Build a flattened representation of the Yaml tree . The conversion is compliant with the thorntail spring - boot rules .


private ProcessorConfig extractWatcherConfig() {
        try {
            return ProfileUtil.blendProfileWithConfiguration(ProfileUtil.WATCHER_CONFIG, profile, ResourceDirCreator.getFinalResourceDir(resourceDir, environment), watcher);
        } catch (IOException e) {
            throw new IllegalArgumentException("Cannot extract watcher config: " + e, e);
        }
    }

private
ProcessorConfig
extractWatcherConfig
(
)
{
try
{
return
ProfileUtil
.
blendProfileWithConfiguration
(
ProfileUtil
.
WATCHER_CONFIG
,
profile
,
ResourceDirCreator
.
getFinalResourceDir
(
resourceDir
,
environment
)
,
watcher
)
;
}
catch
(
IOException
e
)
{
throw
new
IllegalArgumentException
(
"Cannot extract watcher config: "
+
e
,
e
)
;
}
}


protected static Template getSingletonTemplate(KubernetesList resources) {
        // if the list contains a single Template lets unwrap it
        if (resources != null) {
            List<HasMetadata> items = resources.getItems();
            if (items != null && items.size() == 1) {
                HasMetadata singleEntity = items.get(0);
                if (singleEntity instanceof Template) {
                    return (Template) singleEntity;
                }
            }
        }
        return null;
    }

Returns the Template if the list contains a single Template only otherwise returns null


private Date getBuildReferenceDate() throws MojoExecutionException {
        // Pick up an existing build date created by fabric8:build previously
        File tsFile = new File(project.getBuild().getDirectory(), AbstractDockerMojo.DOCKER_BUILD_TIMESTAMP);
        if (!tsFile.exists()) {
            return new Date();
        }
        try {
            return EnvUtil.loadTimestamp(tsFile);
        } catch (IOException e) {
            throw new MojoExecutionException("Cannot read timestamp from " + tsFile, e);
        }
    }


public String get(Configs.Key key, String defaultVal) {
        String keyVal = key != null ? key.name() : "";
        String val = config != null ? config.getConfig(name, key.name()) : null;
        if (val == null) {
            String fullKey = GENERATOR_PROP_PREFIX + "." + name + "." + key;
            val = Configs.getSystemPropertyWithMavenPropertyAsFallback(properties, fullKey);
        }
        return val != null ? val : defaultVal;
    }

Get a config value with a default
@param key key part to lookup. The whole key is build up from prefix + "." + key. If key is null,
then only the prefix is used for the lookup (this is suitable for enrichers having only one config option)
@param defaultVal the default value to use when the no config is set
@return the value looked up or the default value.


public Map<String, String> getConfigMap(String name) {
        return config.containsKey(name) ?
            Collections.unmodifiableMap(config.get(name)) :
            Collections.<String, String>emptyMap();
    }

public Map < String , String > getConfigMap ( String name ) { return config . containsKey ( name ) ? Collections . unmodifiableMap ( config . get ( name ) ) : Collections . < String , String > emptyMap ( ) ; }

Return full configuration as raw string-string values

@param name name of the enricher / generator
@return unmodifiable map of the original config

Return full configuration as raw string - string values


public <T extends Named> List<T> prepareProcessors(List<T> namedList, String type) {
        List<T> ret = new ArrayList<>();
        Map<String, T> lookup = new HashMap<>();
        for (T named : namedList) {
            lookup.put(named.getName(), named);
        }
        for (String inc : includes) {
            if (use(inc)) {
                T named = lookup.get(inc);
                if (named == null) {
                    List<String> keys = new ArrayList<>(lookup.keySet());
                    Collections.sort(keys);
                    throw new IllegalArgumentException(
                        "No " + type + " with name '" + inc +
                        "' found to include. " +
                        "Please check spelling in your profile / config and your project dependencies. Included " + type + "s: " +
                        StringUtils.join(keys,", "));
                }
                ret.add(named);
            }
        }
        return ret;
    }

Order elements according to the order provided by the include statements.
If no includes has been configured, return the given list unaltered.
Otherwise arrange the elements from the list in to the include order and return a new
list.

If an include specifies an element which does not exist, an exception is thrown.

@param namedList the list to order
@param type a description used in an error message (like 'generator' or 'enricher')
@param <T> the concrete type
@return the ordered list according to the algorithm described above
@throws IllegalArgumentException if the includes reference an non existing element

Order elements according to the order provided by the include statements . If no includes has been configured return the given list unaltered . Otherwise arrange the elements from the list in to the include order and return a new list .


protected void addFrom(BuildImageConfiguration.Builder builder) {
        String fromMode = getConfigWithFallback(Config.fromMode, "fabric8.generator.fromMode", getFromModeDefault(context.getRuntimeMode()));
        String from = getConfigWithFallback(Config.from, "fabric8.generator.from", null);
        if ("docker".equalsIgnoreCase(fromMode)) {
            String fromImage = from;
            if (fromImage == null) {
                fromImage = fromSelector != null ? fromSelector.getFrom() : null;
            }
            builder.from(fromImage);
            log.info("Using Docker image %s as base / builder", fromImage);
        } else if ("istag".equalsIgnoreCase(fromMode)) {
            Map<String, String> fromExt = new HashMap<>();
            if (from != null) {
                ImageName iName = new ImageName(from);
                // user/project is considered to be the namespace
                String tag = iName.getTag();
                if (StringUtils.isBlank(tag)) {
                    tag = "latest";
                }
                fromExt.put(OpenShiftBuildStrategy.SourceStrategy.name.key(), iName.getSimpleName() + ":" + tag);
                if (iName.getUser() != null) {
                    fromExt.put(OpenShiftBuildStrategy.SourceStrategy.namespace.key(), iName.getUser());
                }
                fromExt.put(OpenShiftBuildStrategy.SourceStrategy.kind.key(), "ImageStreamTag");
            } else {
                fromExt = fromSelector != null ? fromSelector.getImageStreamTagFromExt() : null;
            }
            if (fromExt != null) {
                String namespace = fromExt.get(OpenShiftBuildStrategy.SourceStrategy.namespace.key());
                if (namespace != null) {
                    log.info("Using ImageStreamTag '%s' from namespace '%s' as builder image",
                             fromExt.get(OpenShiftBuildStrategy.SourceStrategy.name.key()), namespace);
                } else {
                    log.info("Using ImageStreamTag '%s' as builder image",
                             fromExt.get(OpenShiftBuildStrategy.SourceStrategy.name.key()));
                }
                builder.fromExt(fromExt);
            }
        } else {
            throw new IllegalArgumentException(String.format("Invalid 'fromMode' in generator configuration for '%s'", getName()));
        }
    }

Add the base image either from configuration or from a given selector

@param builder for the build image configuration to add the from to.


private String getFromModeDefault(RuntimeMode mode) {
        if (mode == RuntimeMode.openshift && fromSelector != null && fromSelector.isRedHat()) {
            return "istag";
        } else {
            return "docker";
        }
    }

private String getFromModeDefault ( RuntimeMode mode ) { if ( mode == RuntimeMode . openshift && fromSelector != null && fromSelector . isRedHat ( ) ) { return "istag" ; } else { return "docker" ; } }

Use "istag" as default for "redhat" versions of this plugin

Use istag as default for redhat versions of this plugin


protected String getImageName() {
        if (RuntimeMode.isOpenShiftMode(getProject().getProperties())) {
            return getConfigWithFallback(Config.name, "fabric8.generator.name", "%a:%l");
        } else {
            return getConfigWithFallback(Config.name, "fabric8.generator.name", "%g/%a:%l");
        }
    }

protected String getImageName ( ) { if ( RuntimeMode . isOpenShiftMode ( getProject ( ) . getProperties ( ) ) ) { return getConfigWithFallback ( Config . name , "fabric8.generator.name" , "%a:%l" ) ; } else { return getConfigWithFallback ( Config . name , "fabric8.generator.name" , "%g/%a:%l" ) ; } }

Get Image name with a standard default

@return Docker image name which is never null


protected String getRegistry() {
        if (!RuntimeMode.isOpenShiftMode(getProject().getProperties())) {
            return getConfigWithFallback(Config.registry, "fabric8.generator.registry", null);
        }

        return null;
    }

protected String getRegistry ( ) { if ( ! RuntimeMode . isOpenShiftMode ( getProject ( ) . getProperties ( ) ) ) { return getConfigWithFallback ( Config . registry , "fabric8.generator.registry" , null ) ; } return null ; }

Get the docker registry where the image should be located.
It returns null in Openshift mode.

@return The docker registry if configured

Get the docker registry where the image should be located . It returns null in Openshift mode .


boolean isOnline() {
        String isOnline = getConfig(Config.online);
        if (isOnline != null) {
            return Configs.asBoolean(isOnline);
        }
        Boolean ret = asBooleanFromGlobalProp("fabric8.online");
        return ret != null ? ret : getDefaultOnline();
    }

boolean isOnline ( ) { String isOnline = getConfig ( Config . online ) ; if ( isOnline != null ) { return Configs . asBoolean ( isOnline ) ; } Boolean ret = asBooleanFromGlobalProp ( "fabric8.online" ) ; return ret != null ? ret : getDefaultOnline ( ) ; }

Returns true if in offline mode, "false" if not speciied.
Can be overriden by

Returns true if in offline mode false if not speciied . Can be overriden by


protected String getExternalServiceURL(String serviceName, String protocol) {
        if (!isOnline()) {
            getLog().info("Not looking for service " + serviceName + " as we are in offline mode");
            return null;
        } else {
            try {
                KubernetesClient kubernetes = getKubernetes();
                String ns = kubernetes.getNamespace();
                if (StringUtils.isBlank(ns)) {
                    ns = getNamespace();
                }
                Service service = kubernetes.services().inNamespace(ns).withName(serviceName).get();
                return service != null ?
                    ServiceUrlUtil.getServiceURL(kubernetes, serviceName, ns, protocol, true) :
                    null;
            } catch (Throwable e) {
                Throwable cause = e;

                boolean notFound = false;
                boolean connectError = false;
                Stack<Throwable> stack = unfoldExceptions(e);
                while (!stack.isEmpty()) {
                    Throwable t = stack.pop();
                    if (t instanceof ConnectException || "No route to host".equals(t.getMessage())) {
                        getLog().warn("Cannot connect to Kubernetes to find URL for service %s : %s",
                                      serviceName, cause.getMessage());
                        return null;
                    } else if (t instanceof IllegalArgumentException ||
                               t.getMessage() != null && t.getMessage().matches("^No.*found.*$")) {
                        getLog().warn("%s", cause.getMessage());
                        return null;
                    };
                }
                getLog().warn("Cannot find URL for service %s : %s", serviceName, cause.getMessage());
                return null;
            }
        }
    }

Returns the external access to the given service name

@param serviceName name of the service
@param protocol URL protocol such as http


protected Boolean asBooleanFromGlobalProp(String prop) {
        String value = getContext().getConfiguration().getProperty(prop);
        if (value == null) {
            value = System.getProperty(prop);
        }
        return value != null ? Boolean.valueOf(value) : null;
    }

protected Boolean asBooleanFromGlobalProp ( String prop ) { String value = getContext ( ) . getConfiguration ( ) . getProperty ( prop ) ; if ( value == null ) { value = System . getProperty ( prop ) ; } return value != null ? Boolean . valueOf ( value ) : null ; }

Check a global prop from the project or system props


private JestClient createJestClient(String uri) {

		HttpClientConfig.Builder builder = new HttpClientConfig.Builder(uri)
			.maxTotalConnection(properties.getMaxTotalConnection())
			.defaultMaxTotalConnectionPerRoute(properties.getDefaultMaxTotalConnectionPerRoute())
			.maxConnectionIdleTime(properties.getMaxConnectionIdleTime(), TimeUnit.MILLISECONDS)
			.readTimeout(properties.getReadTimeout())
			.multiThreaded(properties.getMultiThreaded());

		if (StringUtils.hasText(this.properties.getUsername())) {
			builder.defaultCredentials(this.properties.getUsername(), this.properties.getPassword());
		}

		String proxyHost = this.properties.getProxy().getHost();
		if (StringUtils.hasText(proxyHost)) {
			Integer proxyPort = this.properties.getProxy().getPort();
			Assert.notNull(proxyPort, "Proxy port must not be null");
			builder.proxy(new HttpHost(proxyHost, proxyPort));
		}

		List<HttpClientConfigBuilderCustomizer> configBuilderCustomizers = builderCustomizers != null ? builderCustomizers.getIfAvailable() : new ArrayList<>();
		if (!CollectionUtils.isEmpty(configBuilderCustomizers)) {
			logger.info("Custom HttpClientConfigBuilderCustomizers detected. Applying these to the HttpClientConfig builder.");
			configBuilderCustomizers.stream().forEach(customizer -> customizer.customize(builder));
			logger.info("Custom HttpClientConfigBuilderCustomizers applied.");
		}

		JestClientFactory factory = jestClientFactory != null ? jestClientFactory : new JestClientFactory();
		factory.setHttpClientConfig(builder.build());
		return factory.getObject();
	}

Create Jest client with URI
@param uri URI of Elasticsearch
@return JestClient


private int createInternalNode() throws NodeValidationException {

		if (logger.isInfoEnabled()) {
			logger.info("Create test ES node");
		}

		int port = SocketUtils.findAvailableTcpPort();
		String clusterName = INTERNAL_TEST_CLUSTER_NAME + UUID.randomUUID();

		Settings.Builder settingsBuilder = Settings.builder()
				.put("cluster.name", clusterName)
				.put("http.type", "netty4")
				.put("http.port", String.valueOf(port));

		if (this.esNodeproperties != null) {
			this.esNodeproperties.getProperties().forEach(settingsBuilder::put);
		}

		Collection<Class<? extends Plugin>> plugins = scanPlugins();
		plugins.add(Netty4Plugin.class);

		this.node = new InternalNode(settingsBuilder.build(), plugins).start();

		return Integer.parseInt(settingsBuilder.get("http.port"));
	}

private
int
createInternalNode
(
)
throws
NodeValidationException
{
if
(
logger
.
isInfoEnabled
(
)
)
{
logger
.
info
(
"Create test ES node"
)
;
}
int
port
=
SocketUtils
.
findAvailableTcpPort
(
)
;
String
clusterName
=
INTERNAL_TEST_CLUSTER_NAME
+
UUID
.
randomUUID
(
)
;
Settings
.
Builder
settingsBuilder
=
Settings
.
builder
(
)
.
put
(
"cluster.name"
,
clusterName
)
.
put
(
"http.type"
,
"netty4"
)
.
put
(
"http.port"
,
String
.
valueOf
(
port
)
)
;
if
(
this
.
esNodeproperties
!=
)
{
this
.
esNodeproperties
.
getProperties
(
)
.
forEach
(
settingsBuilder
::
put
)
;
}
Collection
<
Class
<
extends
Plugin
>
>
plugins
=
scanPlugins
(
)
;
plugins
.
add
(
Netty4Plugin
.
class
)
;
this
.
node
=
new
InternalNode
(
settingsBuilder
.
build
(
)
,
plugins
)
.
start
(
)
;
return
Integer
.
parseInt
(
settingsBuilder
.
get
(
"http.port"
)
)
;
}

Create internal Elasticsearch node.
@return HTTP port of node


@SuppressWarnings("unchecked")
	private static Collection<Class<? extends Plugin>> scanPlugins() {
		ClassPathScanningCandidateComponentProvider componentProvider = new ClassPathScanningCandidateComponentProvider(false);
		componentProvider.addIncludeFilter(new AssignableTypeFilter(Plugin.class));

		return componentProvider.findCandidateComponents("org.elasticsearch.plugin").stream()
				.map(BeanDefinition::getBeanClassName)
				.map(name -> {
					try {
						return (Class<? extends Plugin>) Class.forName(name);
					} catch (ClassNotFoundException e) {
						logger.warn("Cannot load class on plugin detection", e);
						return null;
					}
				})
				.collect(Collectors.toSet());
	}

List all official ES plugins available on ClassPath.
@return List of plugins class

List all official ES plugins available on ClassPath .


public static AmericanExpressRewardsBalance fromJson(String jsonString) throws JSONException {
        JSONObject json = new JSONObject(jsonString);

        AmericanExpressRewardsBalance rewardsBalance = new AmericanExpressRewardsBalance();

        if (json.has(ERROR_KEY)) {
            JSONObject errorJson = json.getJSONObject(ERROR_KEY);
            rewardsBalance.mErrorMessage = errorJson.getString(ERROR_MESSAGE_KEY);
            rewardsBalance.mErrorCode = errorJson.getString(ERROR_CODE_KEY);
        }

        rewardsBalance.mConversionRate = Json.optString(json, CONVERSION_RATE_KEY, null);
        rewardsBalance.mCurrencyAmount = Json.optString(json, CURRENCY_AMOUNT_KEY, null);
        rewardsBalance.mCurrencyIsoCode = Json.optString(json, CURRENCY_ISO_CODE_KEY, null);
        rewardsBalance.mRequestId = Json.optString(json, REQUEST_ID_KEY, null);
        rewardsBalance.mRewardsAmount = Json.optString(json, REWARDS_AMOUNT_KEY, null);
        rewardsBalance.mRewardsUnit = Json.optString(json, REWARDS_UNIT_KEY, null);

        return rewardsBalance;
    }

public static AmericanExpressRewardsBalance fromJson ( String jsonString ) throws JSONException { JSONObject json = new JSONObject ( jsonString ) ; AmericanExpressRewardsBalance rewardsBalance = new AmericanExpressRewardsBalance ( ) ; if ( json . has ( ERROR_KEY ) ) { JSONObject errorJson = json . getJSONObject ( ERROR_KEY ) ; rewardsBalance . mErrorMessage = errorJson . getString ( ERROR_MESSAGE_KEY ) ; rewardsBalance . mErrorCode = errorJson . getString ( ERROR_CODE_KEY ) ; } rewardsBalance . mConversionRate = Json . optString ( json , CONVERSION_RATE_KEY , null ) ; rewardsBalance . mCurrencyAmount = Json . optString ( json , CURRENCY_AMOUNT_KEY , null ) ; rewardsBalance . mCurrencyIsoCode = Json . optString ( json , CURRENCY_ISO_CODE_KEY , null ) ; rewardsBalance . mRequestId = Json . optString ( json , REQUEST_ID_KEY , null ) ; rewardsBalance . mRewardsAmount = Json . optString ( json , REWARDS_AMOUNT_KEY , null ) ; rewardsBalance . mRewardsUnit = Json . optString ( json , REWARDS_UNIT_KEY , null ) ; return rewardsBalance ; }

Used to parse a response from the Braintree Gateway to be used for American Express rewards balance.

@param jsonString The json response from the Braintree Gateway American Express rewards balance route.
@return The {@link com.braintreepayments.api.models.AmericanExpressRewardsBalance} with rewards balance data.
@throws JSONException when parsing fails.

Used to parse a response from the Braintree Gateway to be used for American Express rewards balance .


public static void getRewardsBalance(final BraintreeFragment fragment, final String nonce,
            final String currencyIsoCode) {
        fragment.waitForConfiguration(new ConfigurationListener() {
            @Override
            public void onConfigurationFetched(Configuration configuration) {
                String getRewardsBalanceUrl = Uri.parse(AMEX_REWARDS_BALANCE_PATH)
                        .buildUpon()
                        .appendQueryParameter("paymentMethodNonce", nonce)
                        .appendQueryParameter("currencyIsoCode", currencyIsoCode)
                        .build()
                        .toString();

                fragment.sendAnalyticsEvent("amex.rewards-balance.start");
                fragment.getHttpClient().get(getRewardsBalanceUrl, new HttpResponseCallback() {
                    @Override
                    public void success(String responseBody) {
                        fragment.sendAnalyticsEvent("amex.rewards-balance.success");
                        try {
                            fragment.postAmericanExpressCallback(AmericanExpressRewardsBalance.fromJson(responseBody));
                        } catch (JSONException e) {
                            fragment.sendAnalyticsEvent("amex.rewards-balance.parse.failed");
                            fragment.postCallback(e);
                        }
                    }

                    @Override
                    public void failure(Exception exception) {
                        fragment.postCallback(exception);
                        fragment.sendAnalyticsEvent("amex.rewards-balance.error");
                    }
                });
            }
        });
    }

public static void getRewardsBalance ( final BraintreeFragment fragment , final String nonce , final String currencyIsoCode ) { fragment . waitForConfiguration ( new ConfigurationListener ( ) { @ Override public void onConfigurationFetched ( Configuration configuration ) { String getRewardsBalanceUrl = Uri . parse ( AMEX_REWARDS_BALANCE_PATH ) . buildUpon ( ) . appendQueryParameter ( "paymentMethodNonce" , nonce ) . appendQueryParameter ( "currencyIsoCode" , currencyIsoCode ) . build ( ) . toString ( ) ; fragment . sendAnalyticsEvent ( "amex.rewards-balance.start" ) ; fragment . getHttpClient ( ) . get ( getRewardsBalanceUrl , new HttpResponseCallback ( ) { @ Override public void success ( String responseBody ) { fragment . sendAnalyticsEvent ( "amex.rewards-balance.success" ) ; try { fragment . postAmericanExpressCallback ( AmericanExpressRewardsBalance . fromJson ( responseBody ) ) ; } catch ( JSONException e ) { fragment . sendAnalyticsEvent ( "amex.rewards-balance.parse.failed" ) ; fragment . postCallback ( e ) ; } } @ Override public void failure ( Exception exception ) { fragment . postCallback ( exception ) ; fragment . sendAnalyticsEvent ( "amex.rewards-balance.error" ) ; } } ) ; } } ) ; }

Gets the rewards balance associated with a Braintree nonce. Only for American Express cards.

@param fragment the {@link BraintreeFragment} This fragment will also be responsible
for handling callbacks to it's listeners
@param nonce A nonce representing a card that will be used to look up the rewards balance
@param currencyIsoCode The currencyIsoCode to use. Example: 'USD'

Gets the rewards balance associated with a Braintree nonce . Only for American Express cards .


public static PayPalPaymentResource fromJson(String jsonString) throws JSONException {
        JSONObject json = new JSONObject(jsonString);

        PayPalPaymentResource payPalPaymentResource = new PayPalPaymentResource();
        JSONObject redirectJson = json.optJSONObject(PAYMENT_RESOURCE_KEY);
        if(redirectJson != null) {
            payPalPaymentResource.redirectUrl(Json.optString(redirectJson, REDIRECT_URL_KEY, ""));
        } else {
            redirectJson = json.optJSONObject(AGREEMENT_SETUP_KEY);
            payPalPaymentResource.redirectUrl(Json.optString(redirectJson, APPROVAL_URL_KEY, ""));
        }
        return payPalPaymentResource;
    }

public static PayPalPaymentResource fromJson ( String jsonString ) throws JSONException { JSONObject json = new JSONObject ( jsonString ) ; PayPalPaymentResource payPalPaymentResource = new PayPalPaymentResource ( ) ; JSONObject redirectJson = json . optJSONObject ( PAYMENT_RESOURCE_KEY ) ; if ( redirectJson != null ) { payPalPaymentResource . redirectUrl ( Json . optString ( redirectJson , REDIRECT_URL_KEY , "" ) ) ; } else { redirectJson = json . optJSONObject ( AGREEMENT_SETUP_KEY ) ; payPalPaymentResource . redirectUrl ( Json . optString ( redirectJson , APPROVAL_URL_KEY , "" ) ) ; } return payPalPaymentResource ; }

Create a PayPalPaymentResource from a jsonString. Checks for keys associated with
Single Payment and Billing Agreement flows.

@param jsonString a valid JSON string representing the payment resource
@return a PayPal payment resource
@throws JSONException

Create a PayPalPaymentResource from a jsonString . Checks for keys associated with Single Payment and Billing Agreement flows .


@Override
    public void get(String path, HttpResponseCallback callback) {
        if (path == null) {
            postCallbackOnMainThread(callback, new IllegalArgumentException("Path cannot be null"));
            return;
        }

        Uri uri;
        if (path.startsWith("http")) {
            uri = Uri.parse(path);
        } else {
            uri = Uri.parse(mBaseUrl + path);
        }

        if (mAuthorization instanceof ClientToken) {
            uri = uri.buildUpon()
                    .appendQueryParameter(AUTHORIZATION_FINGERPRINT_KEY,
                            ((ClientToken) mAuthorization).getAuthorizationFingerprint())
                    .build();
        }

        super.get(uri.toString(), callback);
    }

@
Override
public
void
get
(
String
path
,
HttpResponseCallback
callback
)
{
if
(
path
==
)
{
postCallbackOnMainThread
(
callback
,
new
IllegalArgumentException
(
"Path cannot be null"
)
)
;
return
;
}
Uri
uri
;
if
(
path
.
startsWith
(
"http"
)
)
{
uri
=
Uri
.
parse
(
path
)
;
}
else
{
uri
=
Uri
.
parse
(
mBaseUrl
+
path
)
;
}
if
(
mAuthorization
instanceof
ClientToken
)
{
uri
=
uri
.
buildUpon
(
)
.
appendQueryParameter
(
AUTHORIZATION_FINGERPRINT_KEY
,
(
(
ClientToken
)
mAuthorization
)
.
getAuthorizationFingerprint
(
)
)
.
build
(
)
;
}
super
.
get
(
uri
.
toString
(
)
,
callback
)
;
}

Make a HTTP GET request to Braintree using the base url, path and authorization provided.
If the path is a full url, it will be used instead of the previously provided url.

@param path The path or url to request from the server via GET
@param callback The {@link HttpResponseCallback} to receive the response or error.

Make a HTTP GET request to Braintree using the base url path and authorization provided . If the path is a full url it will be used instead of the previously provided url .


@Override
    public void post(String path, String data, HttpResponseCallback callback) {
        try {
            if (mAuthorization instanceof ClientToken) {
                data = new JSONObject(data)
                        .put(AUTHORIZATION_FINGERPRINT_KEY,
                                ((ClientToken) mAuthorization).getAuthorizationFingerprint())
                        .toString();
            }

            super.post(path, data, callback);
        } catch (JSONException e) {
            postCallbackOnMainThread(callback, e);
        }
    }

@ Override public void post ( String path , String data , HttpResponseCallback callback ) { try { if ( mAuthorization instanceof ClientToken ) { data = new JSONObject ( data ) . put ( AUTHORIZATION_FINGERPRINT_KEY , ( ( ClientToken ) mAuthorization ) . getAuthorizationFingerprint ( ) ) . toString ( ) ; } super . post ( path , data , callback ) ; } catch ( JSONException e ) { postCallbackOnMainThread ( callback , e ) ; } }

Make a HTTP POST request to Braintree using the base url, path and authorization provided.
If the path is a full url, it will be used instead of the previously provided url.

@param path The path or url to request from the server via HTTP POST
@param data The body of the POST request
@param callback The {@link HttpResponseCallback} to receive the response or error.

Make a HTTP POST request to Braintree using the base url path and authorization provided . If the path is a full url it will be used instead of the previously provided url .


static VenmoConfiguration fromJson(JSONObject json) {
        if (json == null) {
            json = new JSONObject();
        }

        VenmoConfiguration venmoConfiguration = new VenmoConfiguration();
        venmoConfiguration.mAccessToken = Json.optString(json, ACCESS_TOKEN_KEY, "");
        venmoConfiguration.mEnvironment = Json.optString(json, ENVIRONMENT_KEY, "");
        venmoConfiguration.mMerchantId = Json.optString(json, MERCHANT_ID_KEY, "");

        return venmoConfiguration;
    }

static VenmoConfiguration fromJson ( JSONObject json ) { if ( json == null ) { json = new JSONObject ( ) ; } VenmoConfiguration venmoConfiguration = new VenmoConfiguration ( ) ; venmoConfiguration . mAccessToken = Json . optString ( json , ACCESS_TOKEN_KEY , "" ) ; venmoConfiguration . mEnvironment = Json . optString ( json , ENVIRONMENT_KEY , "" ) ; venmoConfiguration . mMerchantId = Json . optString ( json , MERCHANT_ID_KEY , "" ) ; return venmoConfiguration ; }

Parses the Venmo configuration from json.

@param json The json to parse.
@return A {@link VenmoConfiguration} instance with data that was able to be parsed from the
{@link JSONObject}.

Parses the Venmo configuration from json .


public static void collectDeviceData(BraintreeFragment fragment, BraintreeResponseListener<String> listener) {
        collectDeviceData(fragment, null, listener);
    }

public static void collectDeviceData ( BraintreeFragment fragment , BraintreeResponseListener < String > listener ) { collectDeviceData ( fragment , null , listener ) ; }

Collect device information for fraud identification purposes.

@param fragment {@link BraintreeFragment}
@param listener to be called with the device data String to send to Braintree.

Collect device information for fraud identification purposes .


public static void collectDeviceData(final BraintreeFragment fragment, final String merchantId,
            final BraintreeResponseListener<String> listener) {
        fragment.waitForConfiguration(new ConfigurationListener() {
            @Override
            public void onConfigurationFetched(Configuration configuration) {
                final JSONObject deviceData = new JSONObject();

                try {
                    String clientMetadataId = getPayPalClientMetadataId(fragment.getApplicationContext());
                    if (!TextUtils.isEmpty(clientMetadataId)) {
                        deviceData.put(CORRELATION_ID_KEY, clientMetadataId);
                    }
                } catch (JSONException ignored) {}

                if (configuration.getKount().isEnabled()) {
                    final String id;
                    if (merchantId != null) {
                        id = merchantId;
                    } else {
                        id = configuration.getKount().getKountMerchantId();
                    }

                    try {
                        final String deviceSessionId = UUIDHelper.getFormattedUUID();
                        startDeviceCollector(fragment, id, deviceSessionId, new BraintreeResponseListener<String>() {
                            @Override
                            public void onResponse(String sessionId) {
                                try {
                                    deviceData.put(DEVICE_SESSION_ID_KEY, deviceSessionId);
                                    deviceData.put(FRAUD_MERCHANT_ID_KEY, id);
                                } catch (JSONException ignored) {}

                                listener.onResponse(deviceData.toString());
                            }
                        });
                    } catch (ClassNotFoundException | NoClassDefFoundError | NumberFormatException ignored) {
                        listener.onResponse(deviceData.toString());
                    }
                } else {
                    listener.onResponse(deviceData.toString());
                }
            }
        });
    }

public static void collectDeviceData ( final BraintreeFragment fragment , final String merchantId , final BraintreeResponseListener < String > listener ) { fragment . waitForConfiguration ( new ConfigurationListener ( ) { @ Override public void onConfigurationFetched ( Configuration configuration ) { final JSONObject deviceData = new JSONObject ( ) ; try { String clientMetadataId = getPayPalClientMetadataId ( fragment . getApplicationContext ( ) ) ; if ( ! TextUtils . isEmpty ( clientMetadataId ) ) { deviceData . put ( CORRELATION_ID_KEY , clientMetadataId ) ; } } catch ( JSONException ignored ) { } if ( configuration . getKount ( ) . isEnabled ( ) ) { final String id ; if ( merchantId != null ) { id = merchantId ; } else { id = configuration . getKount ( ) . getKountMerchantId ( ) ; } try { final String deviceSessionId = UUIDHelper . getFormattedUUID ( ) ; startDeviceCollector ( fragment , id , deviceSessionId , new BraintreeResponseListener < String > ( ) { @ Override public void onResponse ( String sessionId ) { try { deviceData . put ( DEVICE_SESSION_ID_KEY , deviceSessionId ) ; deviceData . put ( FRAUD_MERCHANT_ID_KEY , id ) ; } catch ( JSONException ignored ) { } listener . onResponse ( deviceData . toString ( ) ) ; } } ) ; } catch ( ClassNotFoundException | NoClassDefFoundError | NumberFormatException ignored ) { listener . onResponse ( deviceData . toString ( ) ) ; } } else { listener . onResponse ( deviceData . toString ( ) ) ; } } } ) ; }

Collect device information for fraud identification purposes. This should be used in conjunction
with a non-aggregate fraud id.

@param fragment {@link BraintreeFragment}
@param merchantId The fraud merchant id from Braintree.
@param listener listener to be called with the device data String to send to Braintree.

Collect device information for fraud identification purposes . This should be used in conjunction with a non - aggregate fraud id .