signature:
public class KubernetesResourceUtil { /** * we could also use an annotation ? */
private static boolean isLocalCustomisation ( PodSpec podSpec ) { } }

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


signature:
public class AbstractPortsExtractor { /** * Reads the configuration from the file .
 * @ param f
 * @ return
 * @ throws IOException */
private Map < String , String > readConfig ( File f ) throws IOException { } }

implementation: 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 ;


signature:
public class AbstractPortsExtractor { /** * Flattens a nested map into a Map < String , String > .
 * @ param map The target map .
 * @ return The flattened map . */
private Map < String , String > flatten ( Map map ) { } }

implementation: Map < String , String > flat = new HashMap < > ( ) ; for ( Object key : map . keySet ( ) ) { String stringKey = String . valueOf ( key ) ; Object value = map . get ( key ) ; if ( value instanceof String ) { flat . put ( stringKey , ( String ) value ) ; } else if ( value instanceof Map ) { for ( Map . Entry < String , String > entry : flatten ( ( Map ) value ) . entrySet ( ) ) { flat . put ( new StringBuilder ( stringKey ) . append ( DOT ) . append ( entry . getKey ( ) ) . toString ( ) , entry . getValue ( ) ) ; } } else { flat . put ( stringKey , String . valueOf ( value ) ) ; } } return flat ;


signature:
public class AbstractPortsExtractor { /** * Converts a { @ link Properties } object to a { @ link Map } .
 * @ param properties The properties object .
 * @ return The map . */
private Map < String , String > propertiesToMap ( Properties properties ) { } }

implementation: Map < String , String > map = new HashMap < > ( ) ; for ( Map . Entry < Object , Object > entry : properties . entrySet ( ) ) { map . put ( String . valueOf ( entry . getKey ( ) ) , String . valueOf ( entry . getValue ( ) ) ) ; } return map ;


signature:
public class AbstractPortsExtractor { /** * Adds a port to the list .
 * @ param map The list .
 * @ param key The key .
 * @ param port The candidate port . */
private void addPortIfValid ( Map < String , Integer > map , String key , String port ) { } }

implementation: if ( StringUtils . isNotBlank ( port ) ) { String t = port . trim ( ) ; if ( t . matches ( NUMBER_REGEX ) ) { map . put ( key , Integer . parseInt ( t ) ) ; } }


signature: public class ProbeHandler { private HTTPGetAction getHTTPGetAction ( String getUrl ) { } }

implementation:
if ( getUrl == null || ! getUrl . subSequence ( 0 , 4 ) . toString ( ) . equalsIgnoreCase ( "http" ) ) { return null ; } try { URL url = new URL ( getUrl ) ; return new HTTPGetAction ( url . getHost ( ) , null /* headers */
, url . getPath ( ) , new IntOrString ( url . getPort ( ) ) , url . getProtocol ( ) . toUpperCase ( ) ) ; } catch ( MalformedURLException e ) { throw new IllegalArgumentException ( "Invalid URL " + getUrl + " given for HTTP GET readiness check" ) ; }


signature:
public class MavenEnricherContext { /** * Method used in MOJO */
public String getDockerJsonConfigString ( final Settings settings , final String serverId ) { } }

implementation: 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 ( ) ;


signature:
public class Configuration { /** * 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 */
public Optional < Map < String , Object > > getPluginConfiguration ( String system , String id ) { } }

implementation: return pluginConfigLookup . apply ( system , id ) ;


signature:
public class Configuration { /** * 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 */
public Optional < Map < String , Object > > getSecretConfiguration ( String id ) { } }

implementation: return secretConfigLookup . apply ( id ) ;


signature:
public class IoUtil { /** * 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 void download ( Logger log , URL downloadUrl , File target ) throws MojoExecutionException { } }

implementation: 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 ( ) ; }


signature:
public class IoUtil { /** * Find a free ( on localhost ) random port in the specified range after the given number of attempts . */
public static int getFreeRandomPort ( int min , int max , int attempts ) { } }

implementation: Random random = new Random ( ) ; for ( int i = 0 ; i < attempts ; i ++ ) { int port = min + random . nextInt ( max - min + 1 ) ; try ( Socket socket = new Socket ( "localhost" , port ) ) { } catch ( ConnectException e ) { return port ; } catch ( IOException e ) { throw new IllegalStateException ( "Error while trying to check open ports" , e ) ; } } throw new IllegalStateException ( "Cannot find a free random port in the range [" + min + ", " + max + "] after " + attempts + " attempts" ) ;


signature:
public class VersionUtil { /** * Compares two version strings such that " 1.10.1 " > " 1.4 " etc */
public static int compareVersions ( String v1 , String v2 ) { } }

implementation:
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 ;


signature:
public class ProfileUtil { /** * Find a profile . Profiles are looked up at various locations :
 * < ul >
 * < li > A given directory with the name profiles . yml ( and variations , { @ link # findProfile ( String , File ) } < / li >
 * < / ul >
 * @ param profileArg the profile ' s name
 * @ param resourceDir a directory to check for profiles .
 * @ return the profile found or the default profile if none of this name is given
 * @ throws IOException */
public static Profile findProfile ( String profileArg , File resourceDir ) throws IOException { } }

implementation: try { String profile = profileArg == null ? DEFAULT_PROFILE : profileArg ; Profile profileFound = lookup ( profile , resourceDir ) ; if ( profileFound != null ) { if ( profileFound . getParentProfile ( ) != null ) { profileFound = inheritFromParentProfile ( profileFound , resourceDir ) ; log . info ( profileFound + " inheriting resources from " + profileFound . getParentProfile ( ) ) ; } return profileFound ; } else { throw new IllegalArgumentException ( "No profile '" + profile + "' defined" ) ; } } catch ( IOException e ) { throw new IOException ( "Error while looking up profile " + profileArg + ": " + e . getMessage ( ) , e ) ; }


signature:
public class ProfileUtil { /** * 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 */
public static ProcessorConfig blendProfileWithConfiguration ( ProcessorConfigurationExtractor configExtractor , String profile , File resourceDir , ProcessorConfig config ) throws IOException { } }

implementation:
// Get specified profile or the default profile
ProcessorConfig profileConfig = extractProcesssorConfiguration ( configExtractor , profile , resourceDir ) ; return ProcessorConfig . mergeProcessorConfigs ( config , profileConfig ) ;


signature:
public class ProfileUtil { /** * 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 */
public static Profile lookup ( String name , File directory ) throws IOException { } }

implementation:
// 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 ) ;


signature:
public class ProfileUtil { /** * Read all default profiles first , then merge in custom profiles found on the classpath */
private static List < Profile > readProfileFromClasspath ( String name ) throws IOException { } }

implementation: List < Profile > ret = new ArrayList < > ( ) ; ret . addAll ( readAllFromClasspath ( name , "default" ) ) ; ret . addAll ( readAllFromClasspath ( name , "" ) ) ; return ret ;


signature:
public class ProfileUtil { /** * 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 */
public static List < Profile > readAllFromClasspath ( String name , String ext ) throws IOException { } }

implementation: 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 ;


signature:
public class ProfileUtil { /** * check for various variations of profile files */
private static File findProfileYaml ( File directory ) { } }

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


signature:
public class ProfileUtil { /** * prepend meta - inf location */
private static List < String > getMetaInfProfilePaths ( String ext ) { } }

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


signature:
public class ProfileUtil { /** * 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 */
public static List < Profile > fromYaml ( InputStream is ) throws IOException { } }

implementation: TypeReference < List < Profile > > typeRef = new TypeReference < List < Profile > > ( ) { } ; return mapper . readValue ( is , typeRef ) ;


signature:
public class ClassUtil { /** * Find all classes below a certain directory which contain
 * main ( ) classes
 * @ param rootDir the directory to start from
 * @ return List of classes with " public void static main ( String [ ] args ) " methods . Can be empty , but not null .
 * @ exception IOException if something goes wrong */
public static List < String > findMainClasses ( File rootDir ) throws IOException { } }

implementation: List < String > ret = new ArrayList < > ( ) ; if ( ! rootDir . exists ( ) ) { return ret ; } if ( ! rootDir . isDirectory ( ) ) { throw new IllegalArgumentException ( String . format ( "Path %s is not a directory" , rootDir . getPath ( ) ) ) ; } findClasses ( ret , rootDir , rootDir . getAbsolutePath ( ) + "/" ) ; return ret ;


signature: public class CdEnricher { private void addGitServiceUrl ( Map < String , String > annotations , String repoName , String gitCommitId ) { } }

implementation:
String username = getGitUserName ( ) ; // this requires online access to kubernetes so we should silently fail if no connection
String gogsUrl = getExternalServiceURL ( getConfig ( Config . gitService ) , "http" ) ; String rootGitUrl = String . format ( "%s/%s/%s" , gogsUrl , username , repoName ) ; rootGitUrl = String . format ( "%s/%s/%s" , rootGitUrl , "commit" , gitCommitId ) ; if ( StringUtils . isNotBlank ( rootGitUrl ) ) { annotations . put ( Fabric8Annotations . GIT_URL . value ( ) , rootGitUrl ) ; }


signature:
public class DefaultControllerEnricher { /** * This method overrides the ImagePullPolicy value by the value provided in
 * XML config .
 * @ param resourceConfig
 * @ param defaultValue
 * @ return */
private String getImagePullPolicy ( ResourceConfig resourceConfig , String defaultValue ) { } }

implementation: if ( resourceConfig != null ) { return resourceConfig . getImagePullPolicy ( ) != null ? resourceConfig . getImagePullPolicy ( ) : defaultValue ; } return defaultValue ;


signature:
public class BaseEnricher { /** * Returns true if we are in OpenShift S2I binary building mode */
protected boolean isOpenShiftMode ( ) { } }

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


signature:
public class BaseEnricher { /** * 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 */
protected int getReplicaCount ( KubernetesListBuilder builder , ResourceConfig xmlResourceConfig , int defaultValue ) { } }

implementation: 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 ;


signature:
public class XmlUtils { /** * Returns the first child element for the given name */
public static Element firstChild ( Element element , String name ) { } }

implementation: 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 ;


signature: public class XmlUtils { private static String getTextContent ( final Node node ) { } }

implementation: switch ( node . getNodeType ( ) ) { case Node . ELEMENT_NODE : case Node . ATTRIBUTE_NODE : case Node . ENTITY_NODE : case Node . ENTITY_REFERENCE_NODE : case Node . DOCUMENT_FRAGMENT_NODE : return mergeTextContent ( node . getChildNodes ( ) ) ; case Node . TEXT_NODE : case Node . CDATA_SECTION_NODE : case Node . COMMENT_NODE : case Node . PROCESSING_INSTRUCTION_NODE : return node . getNodeValue ( ) ; case Node . DOCUMENT_NODE : case Node . DOCUMENT_TYPE_NODE : case Node . NOTATION_NODE : default : return null ; }


signature:
public class ApplyService { /** * Applies the given DTOs onto the Kubernetes master */
public void apply ( Object dto , String sourceName ) throws Exception { } }

implementation: if ( dto instanceof List ) { List list = ( List ) dto ; for ( Object element : list ) { if ( dto == element ) { log . warn ( "Found recursive nested object for " + dto + " of class: " + dto . getClass ( ) . getName ( ) ) ; continue ; } apply ( element , sourceName ) ; } } else if ( dto instanceof KubernetesList ) { applyList ( ( KubernetesList ) dto , sourceName ) ; } else if ( dto != null ) { applyEntity ( dto , sourceName ) ; }


signature:
public class ApplyService { /** * Applies the given DTOs onto the Kubernetes master */
private void applyEntity ( Object dto , String sourceName ) throws Exception { } }

implementation: if ( dto instanceof Pod ) { applyPod ( ( Pod ) dto , sourceName ) ; } else if ( dto instanceof ReplicationController ) { applyReplicationController ( ( ReplicationController ) dto , sourceName ) ; } else if ( dto instanceof Service ) { applyService ( ( Service ) dto , sourceName ) ; } else if ( dto instanceof Route ) { applyRoute ( ( Route ) dto , sourceName ) ; } else if ( dto instanceof BuildConfig ) { applyBuildConfig ( ( BuildConfig ) dto , sourceName ) ; } else if ( dto instanceof DeploymentConfig ) { DeploymentConfig resource = ( DeploymentConfig ) dto ; OpenShiftClient openShiftClient = getOpenShiftClient ( ) ; if ( openShiftClient != null ) { applyResource ( resource , sourceName , openShiftClient . deploymentConfigs ( ) ) ; } else { log . warn ( "Not connected to OpenShift cluster so cannot apply entity " + dto ) ; } } else if ( dto instanceof RoleBinding ) { applyRoleBinding ( ( RoleBinding ) dto , sourceName ) ; } else if ( dto instanceof Role ) { Role resource = ( Role ) dto ; OpenShiftClient openShiftClient = getOpenShiftClient ( ) ; if ( openShiftClient != null ) { applyResource ( resource , sourceName , openShiftClient . rbac ( ) . roles ( ) ) ; } else { log . warn ( "Not connected to OpenShift cluster so cannot apply entity " + dto ) ; } } else if ( dto instanceof ImageStream ) { applyImageStream ( ( ImageStream ) dto , sourceName ) ; } else if ( dto instanceof OAuthClient ) { applyOAuthClient ( ( OAuthClient ) dto , sourceName ) ; } else if ( dto instanceof Template ) { applyTemplate ( ( Template ) dto , sourceName ) ; } else if ( dto instanceof ServiceAccount ) { applyServiceAccount ( ( ServiceAccount ) dto , sourceName ) ; } else if ( dto instanceof Secret ) { applySecret ( ( Secret ) dto , sourceName ) ; } else if ( dto instanceof ConfigMap ) { applyResource ( ( ConfigMap ) dto , sourceName , kubernetesClient . configMaps ( ) ) ; } else if ( dto instanceof DaemonSet ) { applyResource ( ( DaemonSet ) dto , sourceName , kubernetesClient . extensions ( ) . daemonSets ( ) ) ; } else if ( dto instanceof Deployment ) { applyResource ( ( Deployment ) dto , sourceName , kubernetesClient . extensions ( ) . deployments ( ) ) ; } else if ( dto instanceof ReplicaSet ) { applyResource ( ( ReplicaSet ) dto , sourceName , kubernetesClient . extensions ( ) . replicaSets ( ) ) ; } else if ( dto instanceof StatefulSet ) { applyResource ( ( StatefulSet ) dto , sourceName , kubernetesClient . apps ( ) . statefulSets ( ) ) ; } else if ( dto instanceof Ingress ) { applyResource ( ( Ingress ) dto , sourceName , kubernetesClient . extensions ( ) . ingresses ( ) ) ; } else if ( dto instanceof PersistentVolumeClaim ) { applyPersistentVolumeClaim ( ( PersistentVolumeClaim ) dto , sourceName ) ; } else if ( dto instanceof HasMetadata ) { HasMetadata entity = ( HasMetadata ) dto ; try { log . info ( "Applying " + getKind ( entity ) + " " + getName ( entity ) + " from " + sourceName ) ; kubernetesClient . resource ( entity ) . inNamespace ( getNamespace ( ) ) . createOrReplace ( ) ; } catch ( Exception e ) { onApplyError ( "Failed to create " + getKind ( entity ) + " from " + sourceName + ". " + e , e ) ; } } else { throw new IllegalArgumentException ( "Unknown entity type " + dto ) ; }


signature:
public class ApplyService { /** * Creates / updates the template and processes it returning the processed DTOs */
public Object applyTemplate ( Template entity , String sourceName ) throws Exception { } }

implementation: installTemplate ( entity , sourceName ) ; return processTemplate ( entity , sourceName ) ;


signature:
public class ApplyService { /** * Installs the template into the namespace without processing it */
public void installTemplate ( Template entity , String sourceName ) { } }

implementation:
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 ) ; } } }


signature:
public class ApplyService { /** * Creates / updates a service account and processes it returning the processed DTOs */
public void applyServiceAccount ( ServiceAccount serviceAccount , String sourceName ) throws Exception { } }

implementation: String namespace = getNamespace ( ) ; String id = getName ( serviceAccount ) ; Objects . requireNonNull ( id , "No name for " + serviceAccount + " " + sourceName ) ; if ( isServicesOnlyMode ( ) ) { log . debug ( "Only processing Services right now so ignoring ServiceAccount: " + id ) ; return ; } ServiceAccount old = kubernetesClient . serviceAccounts ( ) . inNamespace ( namespace ) . withName ( id ) . get ( ) ; if ( isRunning ( old ) ) { if ( UserConfigurationCompare . configEqual ( serviceAccount , old ) ) { log . info ( "ServiceAccount has not changed so not doing anything" ) ; } else { if ( isRecreateMode ( ) ) { kubernetesClient . serviceAccounts ( ) . inNamespace ( namespace ) . withName ( id ) . delete ( ) ; doCreateServiceAccount ( serviceAccount , namespace , sourceName ) ; } else { log . info ( "Updating a ServiceAccount from " + sourceName ) ; try { Object answer = kubernetesClient . serviceAccounts ( ) . inNamespace ( namespace ) . withName ( id ) . replace ( serviceAccount ) ; logGeneratedEntity ( "Updated ServiceAccount: " , namespace , serviceAccount , answer ) ; } catch ( Exception e ) { onApplyError ( "Failed to update ServiceAccount from " + sourceName + ". " + e + ". " + serviceAccount , e ) ; } } } } else { if ( ! isAllowCreate ( ) ) { log . warn ( "Creation disabled so not creating a ServiceAccount from " + sourceName + " namespace " + namespace + " name " + getName ( serviceAccount ) ) ; } else { doCreateServiceAccount ( serviceAccount , namespace , sourceName ) ; } }


signature:
public class ApplyService { /** * Removes all the tags with the given name
 * @ return the number of tags removed */
private int removeTagByName ( List < TagReference > tags , String tagName ) { } }

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


signature:
public class ApplyService { /** * Returns true if the namespace is created */
public boolean applyNamespace ( Namespace entity ) { } }

implementation: 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 ;


signature:
public class ApplyService { /** * Creates and return a project in openshift
 * @ param project
 * @ return */
public boolean applyProject ( Project project ) { } }

implementation: return applyProjectRequest ( new ProjectRequestBuilder ( ) . withDisplayName ( project . getMetadata ( ) . getName ( ) ) . withMetadata ( project . getMetadata ( ) ) . build ( ) ) ;


signature:
public class ApplyService { /** * Returns true if the ProjectRequest is created */
public boolean applyProjectRequest ( ProjectRequest entity ) { } }

implementation:
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 ;


signature:
public class ApplyService { /** * Returns the namespace defined in the entity or the configured namespace */
protected String getNamespace ( HasMetadata entity ) { } }

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


signature:
public class ApplyService { /** * Logs an error applying some JSON to Kubernetes and optionally throws an exception */
protected void onApplyError ( String message , Exception e ) { } }

implementation: log . error ( message , e ) ; throw new RuntimeException ( message , e ) ;


signature: public class PengEndpoint { @ GET @ Produces ( "text/plain" ) public String peng ( @ PathParam ( "id" ) String id ) { } }

implementation: Stroke stroke = Stroke . play ( strength ) ; return pengId + " " + stroke . toString ( ) ;


signature: public class SpringBootGenerator { private void ensureSpringDevToolSecretToken ( ) throws MojoExecutionException { } }

implementation: Properties properties = SpringBootUtil . getSpringBootApplicationProperties ( MavenUtil . getCompileClassLoader ( getProject ( ) ) ) ; String remoteSecret = properties . getProperty ( DEV_TOOLS_REMOTE_SECRET ) ; if ( Strings . isNullOrEmpty ( remoteSecret ) ) { addSecretTokenToApplicationProperties ( ) ; throw new MojoExecutionException ( "No spring.devtools.remote.secret found in application.properties. Plugin has added it, please re-run goals" ) ; }


signature:
public class DefaultNamespaceEnricher { /** * 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 */
@ Override public void create ( PlatformMode platformMode , KubernetesListBuilder builder ) { } }

implementation: 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 ) ; } } }


signature:
public class DefaultNamespaceEnricher { /** * This method will annotate all the items in the KubernetesListBuilder with the
 * created new namespace or project .
 * @ param platformMode
 * @ param builder */
@ Override public void enrich ( PlatformMode platformMode , KubernetesListBuilder builder ) { } }

implementation:
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 ( ) ; } } ) ;


signature:
public class MavenConfigurationExtractor { /** * Transforms the Dom object into a Map .
 * This Map can contain pairs key / value where value can be a simple type , another Map ( Inner objects )
 * and a list of simple types .
 * Currently it is NOT supported List of complex objects .
 * @ param root object .
 * @ return Map of DOM structure . */
public static Map < String , Object > extract ( Xpp3Dom root ) { } }

implementation: if ( root == null ) { return new HashMap < > ( ) ; } return getElement ( root ) ;


signature:
public class JavaExecGenerator { /** * Hook for adding extra environment vars
 * @ return map with environment variables to use
 * @ param prePackagePhase */
protected Map < String , String > getEnv ( boolean prePackagePhase ) throws MojoExecutionException { } }

implementation: 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 ;


signature:
public class GoTimeUtil { /** * Parses a duration string anr returns its value in seconds . */
public static Integer durationSeconds ( String duration ) { } }

implementation: 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 ( ) ;


signature:
public class GoTimeUtil { /** * Parses a duration string anr returns its value in nanoseconds . */
public static BigDecimal durationNs ( String durationP ) { } }

implementation: 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 ;


signature:
public class AbstractAppServerHandler { /** * 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 */
protected String [ ] scanFiles ( String ... patterns ) { } }

implementation: 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 ] ; }


signature:
public class ApplyMojo { /** * Should we try to create an external URL for the given service ?
 * By default lets ignore the kubernetes services and any service which does not expose ports 80 and 443
 * @ return true if we should create an OpenShift Route for this service . */
private boolean shouldCreateExternalURLForService ( Service service , String id ) { } }

implementation: if ( "kubernetes" . equals ( id ) || "kubernetes-ro" . equals ( id ) ) { return false ; } Set < Integer > ports = getPorts ( service ) ; log . debug ( "Service " + id + " has ports: " + ports ) ; if ( ports . size ( ) == 1 ) { String type = null ; ServiceSpec spec = service . getSpec ( ) ; if ( spec != null ) { type = spec . getType ( ) ; if ( Objects . equals ( type , "LoadBalancer" ) ) { return true ; } } log . info ( "Not generating route for service " + id + " type is not LoadBalancer: " + type ) ; return false ; } else { log . info ( "Not generating route for service " + id + " as only single port services are supported. Has ports: " + ports ) ; return false ; }


signature:
public class ApplyMojo { /** * Lets disable OpenShift - only features if we are not running on OpenShift */
protected void disableOpenShiftFeatures ( ApplyService applyService ) { } }

implementation:
// 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 ) ;


signature:
public class ApplyMojo { /** * Returns true if there is an existing ingress rule for the given service */
private boolean serviceHasIngressRule ( List < Ingress > ingresses , Service service ) { } }

implementation: 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 ;


signature:
public class ApplyMojo { /** * Returns the root project folder */
protected File getRootProjectFolder ( ) { } }

implementation: File answer = null ; MavenProject project = getProject ( ) ; while ( project != null ) { File basedir = project . getBasedir ( ) ; if ( basedir != null ) { answer = basedir ; } project = project . getParent ( ) ; } return answer ;


signature:
public class ApplyMojo { /** * Returns the root project folder */
protected MavenProject getRootProject ( ) { } }

implementation: MavenProject project = getProject ( ) ; while ( project != null ) { MavenProject parent = project . getParent ( ) ; if ( parent == null ) { break ; } project = parent ; } return project ;


signature:
public class PushMojo { /** * Customization hook called by the base plugin .
 * @ param configs configuration to customize
 * @ return the configuration customized by our generators . */
@ Override public List < ImageConfiguration > customizeConfig ( List < ImageConfiguration > configs ) { } }

implementation: try { ProcessorConfig generatorConfig = ProfileUtil . blendProfileWithConfiguration ( ProfileUtil . GENERATOR_CONFIG , profile , ResourceDirCreator . getFinalResourceDir ( resourceDir , environment ) , generator ) ; GeneratorContext ctx = new GeneratorContext . Builder ( ) . config ( generatorConfig ) . project ( project ) . logger ( log ) . runtimeMode ( mode ) . strategy ( buildStrategy ) . useProjectClasspath ( false ) . build ( ) ; return GeneratorManager . generate ( configs , ctx , true ) ; } catch ( Exception e ) { throw new IllegalArgumentException ( "Cannot extract generator config: " + e , e ) ; }


signature:
public class PropertiesMappingParser { /** * 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 */
public Map < String , List < String > > parse ( final InputStream mapping ) { } }

implementation: 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 ) ; }


signature:
public class BuildMojo { /** * Customization hook called by the base plugin .
 * @ param configs configuration to customize
 * @ return the configuration customized by our generators . */
@ Override public List < ImageConfiguration > customizeConfig ( List < ImageConfiguration > configs ) { } }

implementation: runtimeMode = clusterAccess . resolveRuntimeMode ( mode , log ) ; log . info ( "Running in [[B]]%s[[B]] mode" , runtimeMode . getLabel ( ) ) ; if ( runtimeMode == RuntimeMode . openshift ) { log . info ( "Using [[B]]OpenShift[[B]] build with strategy [[B]]%s[[B]]" , buildStrategy . getLabel ( ) ) ; } else { log . info ( "Building Docker image in [[B]]Kubernetes[[B]] mode" ) ; } if ( runtimeMode . equals ( PlatformMode . openshift ) ) { Properties properties = project . getProperties ( ) ; if ( ! properties . contains ( RuntimeMode . FABRIC8_EFFECTIVE_PLATFORM_MODE ) ) { properties . setProperty ( RuntimeMode . FABRIC8_EFFECTIVE_PLATFORM_MODE , runtimeMode . toString ( ) ) ; } } try { return GeneratorManager . generate ( configs , getGeneratorContext ( ) , false ) ; } catch ( MojoExecutionException e ) { throw new IllegalArgumentException ( "Cannot extract generator config: " + e , e ) ; }


signature:
public class BuildMojo { /** * Get generator context */
private GeneratorContext getGeneratorContext ( ) { } }

implementation: return new GeneratorContext . Builder ( ) . config ( extractGeneratorConfig ( ) ) . project ( project ) . logger ( log ) . runtimeMode ( runtimeMode ) . strategy ( buildStrategy ) . useProjectClasspath ( useProjectClasspath ) . artifactResolver ( getFabric8ServiceHub ( ) . getArtifactResolverService ( ) ) . build ( ) ;


signature:
public class BuildMojo { /** * Get generator config */
private ProcessorConfig extractGeneratorConfig ( ) { } }

implementation: 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 ) ; }


signature:
public class BuildMojo { /** * Get enricher context */
public EnricherContext getEnricherContext ( ) { } }

implementation: return new MavenEnricherContext . Builder ( ) . project ( project ) . properties ( project . getProperties ( ) ) . session ( session ) . config ( extractEnricherConfig ( ) ) . images ( getResolvedImages ( ) ) . resources ( resources ) . log ( log ) . build ( ) ;


signature:
public class BuildMojo { /** * Get enricher config */
private ProcessorConfig extractEnricherConfig ( ) { } }

implementation: 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 ) ; }


signature: public class IconEnricher { private String extractIconRef ( ) { } }

implementation: String iconRef = getConfig ( Config . ref ) ; if ( StringUtils . isBlank ( iconRef ) ) { iconRef = getDefaultIconRef ( ) ; } return iconRef ;


signature:
public class IconEnricher { /** * 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 String getDefaultIconRef ( ) { } }

implementation:
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 ;


signature:
public class IconEnricher { /** * Copies any local configuration files into the app directory */
private void copyAppConfigFiles ( File appBuildDir , File appConfigDir ) throws IOException { } }

implementation: 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 ) ; } } }


signature:
public class IconEnricher { /** * To use embedded icons provided by the fabric8 - console
 * @ param iconRef name of icon file
 * @ param prefix prefix location for the icons in the fabric8 - console
 * @ return the embedded icon ref , or < tt > null < / tt > if no embedded icon found to be used */
protected String embeddedIconsInConsole ( String iconRef , String prefix ) { } }

implementation:
if ( iconRef == null ) { return null ; } if ( iconRef . startsWith ( "icons/" ) ) { iconRef = iconRef . substring ( 6 ) ; } // special for fabric8 as its in a different dir
if ( iconRef . contains ( "META-INF/fabric8" ) ) { return "img/fabric8_icon.svg" ; } if ( iconRef . contains ( "activemq" ) ) { return prefix + "activemq.svg" ; } else if ( iconRef . contains ( "apiman" ) ) { return prefix + "apiman.png" ; } else if ( iconRef . contains ( "api-registry" ) ) { return prefix + "api-registry.svg" ; } else if ( iconRef . contains ( "brackets" ) ) { return prefix + "brackets.svg" ; } else if ( iconRef . contains ( "camel" ) ) { return prefix + "camel.svg" ; } else if ( iconRef . contains ( "chaos-monkey" ) ) { return prefix + "chaos-monkey.png" ; } else if ( iconRef . contains ( "docker-registry" ) ) { return prefix + "docker-registry.png" ; } else if ( iconRef . contains ( "elasticsearch" ) ) { return prefix + "elasticsearch.png" ; } else if ( iconRef . contains ( "fluentd" ) ) { return prefix + "fluentd.png" ; } else if ( iconRef . contains ( "forge" ) ) { return prefix + "forge.svg" ; } else if ( iconRef . contains ( "funktion" ) ) { return prefix + "funktion.png" ; } else if ( iconRef . contains ( "gerrit" ) ) { return prefix + "gerrit.png" ; } else if ( iconRef . contains ( "gitlab" ) ) { return prefix + "gitlab.svg" ; } else if ( iconRef . contains ( "gogs" ) ) { return prefix + "gogs.png" ; } else if ( iconRef . contains ( "grafana" ) ) { return prefix + "grafana.png" ; } else if ( iconRef . contains ( "hubot-irc" ) ) { return prefix + "hubot-irc.png" ; } else if ( iconRef . contains ( "hubot-letschat" ) ) { return prefix + "hubot-letschat.png" ; } else if ( iconRef . contains ( "hubot-notifier" ) ) { return prefix + "hubot-notifier.png" ; } else if ( iconRef . contains ( "hubot-slack" ) ) { return prefix + "hubot-slack.png" ; } else if ( iconRef . contains ( "image-linker" ) ) { return prefix + "image-linker.svg" ; } else if ( iconRef . contains ( "javascript" ) ) { return prefix + "javascript.png" ; } else if ( iconRef . contains ( "java" ) ) { return prefix + "java.svg" ; } else if ( iconRef . contains ( "jenkins" ) ) { return prefix + "jenkins.svg" ; } else if ( iconRef . contains ( "jetty" ) ) { return prefix + "jetty.svg" ; } else if ( iconRef . contains ( "karaf" ) ) { return prefix + "karaf.svg" ; } else if ( iconRef . contains ( "keycloak" ) ) { return prefix + "keycloak.svg" ; } else if ( iconRef . contains ( "kibana" ) ) { return prefix + "kibana.svg" ; } else if ( iconRef . contains ( "kiwiirc" ) ) { return prefix + "kiwiirc.png" ; } else if ( iconRef . contains ( "letschat" ) ) { return prefix + "letschat.png" ; } else if ( iconRef . contains ( "mule" ) ) { return prefix + "mule.svg" ; } else if ( iconRef . contains ( "nexus" ) ) { return prefix + "nexus.png" ; } else if ( iconRef . contains ( "node" ) ) { return prefix + "node.svg" ; } else if ( iconRef . contains ( "orion" ) ) { return prefix + "orion.png" ; } else if ( iconRef . contains ( "prometheus" ) ) { return prefix + "prometheus.png" ; } else if ( iconRef . contains ( "django" ) || iconRef . contains ( "python" ) ) { return prefix + "python.png" ; } else if ( iconRef . contains ( "spring-boot" ) ) { return prefix + "spring-boot.svg" ; } else if ( iconRef . contains ( "taiga" ) ) { return prefix + "taiga.png" ; } else if ( iconRef . contains ( "tomcat" ) ) { return prefix + "tomcat.svg" ; } else if ( iconRef . contains ( "tomee" ) ) { return prefix + "tomee.svg" ; } else if ( iconRef . contains ( "vertx" ) ) { return prefix + "vertx.svg" ; } else if ( iconRef . contains ( "wildfly" ) ) { return prefix + "wildfly.svg" ; } else if ( iconRef . contains ( "wildfly-swarm" ) ) { return prefix + "wildfly-swarm.png" ; } else if ( iconRef . contains ( "weld" ) ) { return prefix + "weld.svg" ; } else if ( iconRef . contains ( "zipkin" ) ) { return prefix + "zipkin.png" ; } return null ;


signature:
public class SpringBootUtil { /** * Returns the spring boot configuration ( supports ` application . properties ` and ` application . yml ` )
 * or an empty properties object if not found */
public static Properties getSpringBootApplicationProperties ( URLClassLoader compileClassLoader ) { } }

implementation: URL ymlResource = compileClassLoader . findResource ( "application.yml" ) ; URL propertiesResource = compileClassLoader . findResource ( "application.properties" ) ; Properties props = YamlUtil . getPropertiesFromYamlResource ( ymlResource ) ; props . putAll ( getPropertiesResource ( propertiesResource ) ) ; return props ;


signature:
public class SpringBootUtil { /** * Returns the given properties resource on the project classpath if found or an empty properties object if not */
protected static Properties getPropertiesResource ( URL resource ) { } }

implementation: 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 ;


signature:
public class SpringBootUtil { /** * Determine the spring - boot major version for the current project */
public static Optional < String > getSpringBootVersion ( MavenProject mavenProject ) { } }

implementation: return Optional . ofNullable ( MavenUtil . getDependencyVersion ( mavenProject , SpringBootConfigurationHelper . SPRING_BOOT_GROUP_ID , SpringBootConfigurationHelper . SPRING_BOOT_ARTIFACT_ID ) ) ;


signature:
public class PluginServiceFactory { /** * 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 . */
public < T > List < T > createServiceObjects ( String ... descriptorPaths ) { } }

implementation: 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 ( ) ; }


signature:
public class EnricherManager { /** * Allow enricher to add Metadata to the resources .
 * @ param builder builder to customize
 * @ param enricherList list of enrichers */
private void enrich ( PlatformMode platformMode , final ProcessorConfig enricherConfig , final KubernetesListBuilder builder , final List < Enricher > enricherList ) { } }

implementation: loop ( enricherConfig , enricher -> { enricher . enrich ( platformMode , builder ) ; return null ; } ) ;


signature: public class EnricherManager { private void logEnrichers ( List < Enricher > enrichers ) { } }

implementation: log . verbose ( "Enrichers:" ) ; for ( Enricher enricher : enrichers ) { log . verbose ( "- %s" , enricher . getName ( ) ) ; }


signature:
public class ThorntailUtil { /** * Returns the thorntail configuration ( supports ` project - defaults . yml ` )
 * or an empty properties object if not found */
public static Properties getThorntailProperties ( URLClassLoader compileClassLoader ) { } }

implementation: URL ymlResource = compileClassLoader . findResource ( "project-defaults.yml" ) ; Properties props = YamlUtil . getPropertiesFromYamlResource ( ymlResource ) ; return props ;


signature:
public class EnricherConfig { /** * Get the raw , untyped configuration or an empty map
 * @ return raw configuration . */
public Map < String , String > getRawConfig ( ) { } }

implementation: return configuration . getProcessorConfig ( ) . orElse ( ProcessorConfig . EMPTY ) . getConfigMap ( name ) ;


signature:
public class EnricherConfig { /** * Get a config value with a default . If no value is given , as a last resort , project properties are looked up .
 * @ param key key part to lookup . The whole key is build up from < code > prefix + " . " + key < / code > . 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 String get ( Configs . Key key , String defaultVal ) { } }

implementation: String val = configuration . getProcessorConfig ( ) . orElse ( ProcessorConfig . EMPTY ) . getConfig ( name , key . name ( ) ) ; if ( val == null ) { String fullKey = ENRICHER_PROP_PREFIX + "." + name + "." + key ; val = configuration . getPropertyWithSystemOverride ( fullKey ) ; } return val != null ? val : defaultVal ;


signature:
public class ResourceValidator { /** * Add exception rules to ignore validation constraint from JSON schema for OpenShift / Kubernetes resources . Some fields in JSON schema which are marked as required
 * but in reality it ' s not required to provide values for those fields while creating the resources .
 * e . g . In DeploymentConfig ( https : / / docs . openshift . com / container - platform / 3.6 / rest _ api / openshift _ v1 . html # v1 - deploymentconfig ) model ' status ' field is marked as
 * required . */
private void setupIgnoreRules ( ResourceClassifier target ) { } }

implementation: ignoreValidationRules . add ( new IgnorePortValidationRule ( IgnorePortValidationRule . TYPE ) ) ; ignoreValidationRules . add ( new IgnoreResourceMemoryLimitRule ( IgnoreResourceMemoryLimitRule . TYPE ) ) ;


signature:
public class ResourceValidator { /** * Validates the resource descriptors as per JSON schema . If any resource is invalid it throws @ { @ link ConstraintViolationException } with
 * all violated constraints
 * @ return number of resources processed
 * @ throws ConstraintViolationException
 * @ throws IOException */
public int validate ( ) throws ConstraintViolationException , IOException { } }

implementation: for ( File resource : resources ) { if ( resource . isFile ( ) && resource . exists ( ) ) { try { log . info ( "validating %s resource" , resource . toString ( ) ) ; JsonNode inputSpecNode = geFileContent ( resource ) ; String kind = inputSpecNode . get ( "kind" ) . toString ( ) ; JsonSchema schema = getJsonSchema ( prepareSchemaUrl ( SCHEMA_JSON ) , kind ) ; Set < ValidationMessage > errors = schema . validate ( inputSpecNode ) ; processErrors ( errors , resource ) ; } catch ( URISyntaxException e ) { throw new IOException ( e ) ; } } } return resources . length ;


signature:
public class YamlUtil { /** * Build a flattened representation of the Yaml tree . The conversion is compliant with the thorntail spring - boot rules . */
private static Map < String , Object > getFlattenedMap ( Map < String , Object > source ) { } }

implementation: Map < String , Object > result = new LinkedHashMap < > ( ) ; buildFlattenedMap ( result , source , null ) ; return result ;


signature:
public class GroupArtifactVersion { /** * ArtifactId is used for setting a resource name ( service , pod , . . . ) in Kubernetes resource .
 * The problem is that a Kubernetes resource name must start by a char .
 * This method returns a valid string to be used as Kubernetes name .
 * @ return Sanitized Kubernetes name . */
public String getSanitizedArtifactId ( ) { } }

implementation: if ( this . artifactId != null && ! this . artifactId . isEmpty ( ) && Character . isDigit ( this . artifactId . charAt ( 0 ) ) ) { return PREFIX + this . artifactId ; } return this . artifactId ;


signature:
public class WatchMojo { /** * Get watcher config */
private ProcessorConfig extractWatcherConfig ( ) { } }

implementation: 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 ) ; }


signature:
public class ResourceMojo { /** * Returns the Template if the list contains a single Template only otherwise returns null */
protected static Template getSingletonTemplate ( KubernetesList resources ) { } }

implementation:
// 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 ;


signature: public class ResourceMojo { private List < ImageConfiguration > getResolvedImages ( List < ImageConfiguration > images , final Logger log ) throws MojoExecutionException { } }

implementation:
List < ImageConfiguration > ret ; ret = ConfigHelper . resolveImages ( log , images , ( ImageConfiguration image ) -> imageConfigResolver . resolve ( image , project , session ) , null , // no filter on image name yet ( TODO : Maybe add this , too ? )
( List < ImageConfiguration > configs ) -> { try { GeneratorContext ctx = new GeneratorContext . Builder ( ) . config ( extractGeneratorConfig ( ) ) . project ( project ) . runtimeMode ( runtimeMode ) . logger ( log ) . strategy ( buildStrategy ) . useProjectClasspath ( useProjectClasspath ) . build ( ) ; return GeneratorManager . generate ( configs , ctx , true ) ; } catch ( Exception e ) { throw new IllegalArgumentException ( "Cannot extract generator: " + e , e ) ; } } ) ; Date now = getBuildReferenceDate ( ) ; storeReferenceDateInPluginContext ( now ) ; String minimalApiVersion = ConfigHelper . initAndValidate ( ret , null /* no minimal api version */
, new ImageNameFormatter ( project , now ) , log ) ; return ret ;


signature:
public class ResourceMojo { /** * get a reference date */
private Date getBuildReferenceDate ( ) throws MojoExecutionException { } }

implementation:
// 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 ) ; }


signature:
public class UserConfigurationCompare { /** * This method detects if the user has changed the configuration of an entity .
 * It compares the < b > user < / b > configuration of 2 object trees ignoring any
 * runtime status or timestamp information .
 * @ return true if the configurations are equal . */
public static boolean configEqual ( Object entity1 , Object entity2 ) { } }

implementation: if ( entity1 == entity2 ) { return true ; } else if ( entity1 == null || entity2 == null ) { return false ; } else if ( entity1 instanceof Map ) { return configEqualMap ( ( Map ) entity1 , castTo ( Map . class , entity2 ) ) ; } else if ( entity2 instanceof Map ) { return configEqualMap ( ( Map ) entity1 , castTo ( Map . class , entity2 ) ) ; } else if ( entity2 instanceof ObjectMeta ) { return configEqualObjectMeta ( ( ObjectMeta ) entity1 , castTo ( ObjectMeta . class , entity2 ) ) ; } else if ( entity1 instanceof Collection && entity2 instanceof Collection ) { return collectionsEqual ( ( Collection ) entity1 , ( Collection ) entity2 ) ; } else { Class < ? > aClass = getCommonDenominator ( entity1 . getClass ( ) , entity2 . getClass ( ) ) ; if ( aClass != null ) { Object castEntity2 = castTo ( aClass , entity2 ) ; if ( castEntity2 == null ) { return false ; } else if ( aClass . getPackage ( ) . getName ( ) . startsWith ( "io.fabric8" ) ) { return configEqualKubernetesDTO ( entity1 , entity2 , aClass ) ; } } return java . util . Objects . equals ( entity1 , entity2 ) ; }


signature:
public class UserConfigurationCompare { /** * Compares 2 instances of the given Kubernetes DTO class to see if the user has changed their configuration .
 * This method will ignore properties { @ link # ignoredProperties } such as status or timestamp properties */
protected static boolean configEqualKubernetesDTO ( @ NotNull Object entity1 , @ NotNull Object entity2 , @ NotNull Class < ? > clazz ) { } }

implementation:
// lets iterate through the objects making sure we ' ve not
BeanInfo beanInfo = null ; try { beanInfo = Introspector . getBeanInfo ( clazz ) ; } catch ( IntrospectionException e ) { LOG . warn ( "Failed to get beanInfo for " + clazz . getName ( ) + ". " + e , e ) ; return false ; } try { PropertyDescriptor [ ] propertyDescriptors = beanInfo . getPropertyDescriptors ( ) ; for ( PropertyDescriptor propertyDescriptor : propertyDescriptors ) { String name = propertyDescriptor . getName ( ) ; if ( ignoredProperties . contains ( name ) ) { continue ; } Method readMethod = propertyDescriptor . getReadMethod ( ) ; if ( readMethod != null ) { Object value1 = invokeMethod ( entity1 , readMethod ) ; Object value2 = invokeMethod ( entity2 , readMethod ) ; if ( value1 != null && value2 != null && ! configEqual ( value1 , value2 ) ) { return false ; } } } return true ; } catch ( Exception e ) { return false ; }


signature: public class OpenshiftHelper { private static void combineParameters ( List < Parameter > parameters , List < Parameter > otherParameters ) { } }

implementation: if ( otherParameters != null && otherParameters . size ( ) > 0 ) { Map < String , Parameter > map = new HashMap < > ( ) ; for ( Parameter parameter : parameters ) { map . put ( parameter . getName ( ) , parameter ) ; } for ( Parameter otherParameter : otherParameters ) { String name = otherParameter . getName ( ) ; Parameter original = map . get ( name ) ; if ( original == null ) { parameters . add ( otherParameter ) ; } else { if ( StringUtils . isNotBlank ( original . getValue ( ) ) ) { original . setValue ( otherParameter . getValue ( ) ) ; } } } }


signature:
public class GeneratorConfig { /** * Get a config value with a default
 * @ param key key part to lookup . The whole key is build up from < code > prefix + " . " + key < / code > . 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 String get ( Configs . Key key , String defaultVal ) { } }

implementation: 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 ;


signature:
public class WatcherConfig { /** * Get a config value with a default . If no value is given , as a last resort , project properties are looked up .
 * @ param key key part to lookup . The whole key is build up from < code > prefix + " . " + key < / code > . 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 String get ( Configs . Key key , String defaultVal ) { } }

implementation: String val = config != null ? config . getConfig ( name , key . name ( ) ) : null ; if ( val == null ) { String fullKey = WATCHER_PROP_PREFIX + "." + name + "." + key ; val = Configs . getSystemPropertyWithMavenPropertyAsFallback ( projectProperties , fullKey ) ; } return val != null ? val : defaultVal ;


signature:
public class ProcessorConfig { /** * Return full configuration as raw string - string values
 * @ param name name of the enricher / generator
 * @ return unmodifiable map of the original config */
public Map < String , String > getConfigMap ( String name ) { } }

implementation: return config . containsKey ( name ) ? Collections . unmodifiableMap ( config . get ( name ) ) : Collections . < String , String > emptyMap ( ) ;


signature:
public class ProcessorConfig { /** * 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 */
public < T extends Named > List < T > prepareProcessors ( List < T > namedList , String type ) { } }

implementation: 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 ;


signature:
public class ProcessorConfig { /** * Merge in another processor configuration , with a lower priority . I . e . the latter a config is
 * in the argument list , the less priority it has . This means :
 * < ul >
 * < li > A configuration earlier in the list overrides configuration later < / li >
 * < li > Includes and exclude earlier in the list take precedence of the includes / excludes later in the list < / li >
 * < / ul >
 * @ param processorConfigs configs to merge into the current config
 * @ return a merged configuration for convenience of chaining and returning . This is a new object and can e . g . */
public static ProcessorConfig mergeProcessorConfigs ( ProcessorConfig ... processorConfigs ) { } }

implementation:
// Merge the configuration
Map < String , TreeMap > configs = mergeConfig ( processorConfigs ) ; // Get all includes
Set < String > excludes = mergeExcludes ( processorConfigs ) ; // Find the set of includes , which are the ones from the profile + the ones configured
List < String > includes = mergeIncludes ( processorConfigs ) ; return new ProcessorConfig ( includes , excludes , configs ) ;


signature:
public class ProcessorConfig { /** * Only good for small list ( that ' s what we expect for enrichers and generators ) */
private static List < String > removeDups ( List < String > list ) { } }

implementation: List < String > ret = new ArrayList < > ( ) ; for ( String el : list ) { if ( ! ret . contains ( el ) ) { ret . add ( el ) ; } } return ret ;


signature:
public class BaseGenerator { /** * Add the base image either from configuration or from a given selector
 * @ param builder for the build image configuration to add the from to . */
protected void addFrom ( BuildImageConfiguration . Builder builder ) { } }

implementation:
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 ( ) ) ) ; }


signature:
public class BaseGenerator { /** * Use " istag " as default for " redhat " versions of this plugin */
private String getFromModeDefault ( RuntimeMode mode ) { } }

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


signature:
public class BaseGenerator { /** * Get Image name with a standard default
 * @ return Docker image name which is never null */
protected String getImageName ( ) { } }

implementation: 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" ) ; }


signature:
public class BaseGenerator { /** * Get the docker registry where the image should be located .
 * It returns null in Openshift mode .
 * @ return The docker registry if configured */
protected String getRegistry ( ) { } }

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


signature:
public class FileUtil { /** * Returns the absolute path to a resource addressed by the given < code > url < / code >
 * @ param url resource URL
 * @ return absolute path to the resource */
public static String getAbsolutePath ( URL url ) { } }

implementation: try { return url != null ? Paths . get ( url . toURI ( ) ) . toAbsolutePath ( ) . toString ( ) : null ; } catch ( URISyntaxException e ) { throw new RuntimeException ( e ) ; }


signature:
public class AbstractLiveEnricher { /** * Returns true if in offline mode , " false " if not speciied .
 * Can be overriden by */
boolean isOnline ( ) { } }

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


signature:
public class AbstractLiveEnricher { /** * Returns the external access to the given service name
 * @ param serviceName name of the service
 * @ param protocol URL protocol such as < code > http < / code > */
protected String getExternalServiceURL ( String serviceName , String protocol ) { } }

implementation: 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 ; } }


signature:
public class AbstractLiveEnricher { /** * Creates an Iterable to walk the exception from the bottom up
 * ( the last caused by going upwards to the root exception ) .
 * @ param exception the exception
 * @ return the Iterable
 * @ see java . lang . Iterable */
protected Stack < Throwable > unfoldExceptions ( Throwable exception ) { } }

implementation:
Stack < Throwable > throwables = new Stack < > ( ) ; Throwable current = exception ; // spool to the bottom of the caused by tree
while ( current != null ) { throwables . push ( current ) ; current = current . getCause ( ) ; } return throwables ;


signature:
public class AbstractLiveEnricher { /** * Check a global prop from the project or system props */
protected Boolean asBooleanFromGlobalProp ( String prop ) { } }

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


signature:
public class AbstractLiveEnricher { /** * - " default " */
private String getNamespace ( ) { } }

implementation: String namespace = getConfig ( Config . namespace ) ; if ( StringUtils . isNotBlank ( namespace ) ) { return namespace ; } namespace = getContext ( ) . getConfiguration ( ) . getProperty ( "fabric8.namespace" ) ; if ( StringUtils . isNotBlank ( namespace ) ) { return namespace ; } namespace = System . getProperty ( "fabric8.namespace" ) ; if ( StringUtils . isNotBlank ( namespace ) ) { return namespace ; } return KubernetesHelper . getDefaultNamespace ( ) ;


signature:
public class ElasticsearchJestAutoConfiguration { /** * Create Jest client with URI
 * @ param uri URI of Elasticsearch
 * @ return JestClient */
private JestClient createJestClient ( String uri ) { } }

implementation: 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 ( ) ;


signature:
public class ElasticsearchJestAutoConfiguration { /** * Create internal Elasticsearch node .
 * @ return HTTP port of node */
private int createInternalNode ( ) throws NodeValidationException { } }

implementation: 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" ) ) ;


signature:
public class ElasticsearchJestAutoConfiguration { /** * List all official ES plugins available on ClassPath .
 * @ return List of plugins class */
@ SuppressWarnings ( "unchecked" ) private static Collection < Class < ? extends Plugin > > scanPlugins ( ) { } }

implementation: 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 ( ) ) ;


signature:
public class CriteriaFilterProcessor { /** * extract the distance string from a { @ link org . springframework . data . geo . Distance } object .
 * @ param distance distance object to extract string from
 * @ param sb StringBuilder to build the distance string */
private void extractDistanceString ( Distance distance , StringBuilder sb ) { } }

implementation:
// handle Distance object
sb . append ( ( int ) distance . getValue ( ) ) ; Metrics metric = ( Metrics ) distance . getMetric ( ) ; switch ( metric ) { case KILOMETERS : sb . append ( "km" ) ; break ; case MILES : sb . append ( "mi" ) ; break ; }


signature:
public class MappingBuilder { /** * Add mapping for @ Field annotation
 * @ throws IOException */
private static void addSingleFieldMapping ( XContentBuilder builder , java . lang . reflect . Field field , Field annotation , boolean nestedOrObjectField ) throws IOException { } }

implementation: builder . startObject ( field . getName ( ) ) ; addFieldMappingParameters ( builder , annotation , nestedOrObjectField ) ; builder . endObject ( ) ;


signature:
public class MappingBuilder { /** * Add mapping for @ MultiField annotation
 * @ throws IOException */
private static void addMultiFieldMapping ( XContentBuilder builder , java . lang . reflect . Field field , MultiField annotation , boolean nestedOrObjectField ) throws IOException { } }

implementation:
// main field
builder . startObject ( field . getName ( ) ) ; addFieldMappingParameters ( builder , annotation . mainField ( ) , nestedOrObjectField ) ; // inner fields
builder . startObject ( "fields" ) ; for ( InnerField innerField : annotation . otherFields ( ) ) { builder . startObject ( innerField . suffix ( ) ) ; addFieldMappingParameters ( builder , innerField , false ) ; builder . endObject ( ) ; } builder . endObject ( ) ; builder . endObject ( ) ;


signature:
public class GraphQLConfiguration { /** * Parse a { @ link GraphQLConfiguration } from json .
 * @ param json The { @ link JSONObject } to parse .
 * @ return a { @ link GraphQLConfiguration } instance with the data that was able to be parsed from the { @ link
 * JSONObject } . */
public static GraphQLConfiguration fromJson ( JSONObject json ) { } }

implementation: if ( json == null ) { json = new JSONObject ( ) ; } GraphQLConfiguration graphQLConfiguration = new GraphQLConfiguration ( ) ; graphQLConfiguration . mUrl = Json . optString ( json , Keys . URL , "" ) ; graphQLConfiguration . mFeatures = parseJsonFeatures ( json . optJSONArray ( Keys . FEATURES ) ) ; return graphQLConfiguration ;


signature:
public class PayPalDataCollector { /** * Gets a Client Metadata ID at the time of payment activity . Once a user initiates a PayPal payment
 * from their device , PayPal uses the Client Metadata ID to verify that the payment is
 * originating from a valid , user - consented device and application . This helps reduce fraud and
 * decrease declines . This method MUST be called prior to initiating a pre - consented payment ( a
 * " future payment " ) from a mobile device . Pass the result to your server , to include in the
 * payment request sent to PayPal . Do not otherwise cache or store this value .
 * @ param context
 * @ return clientMetadataId Your server will send this to PayPal */
@ MainThread public static String getClientMetadataId ( Context context ) { } }

implementation: PayPalDataCollectorRequest request = new PayPalDataCollectorRequest ( ) . setApplicationGuid ( InstallationIdentifier . getInstallationGUID ( context ) ) ; return getClientMetadataId ( context , request ) ;


signature:
public class PayPalDataCollector { /** * Gets a Client Metadata ID at the time of payment activity . Once a user initiates a PayPal payment
 * from their device , PayPal uses the Client Metadata ID to verify that the payment is
 * originating from a valid , user - consented device and application . This helps reduce fraud and
 * decrease declines . This method MUST be called prior to initiating a pre - consented payment ( a
 * " future payment " ) from a mobile device . Pass the result to your server , to include in the
 * payment request sent to PayPal . Do not otherwise cache or store this value .
 * @ param context An Android context .
 * @ param request configures what data to collect .
 * @ return */
@ MainThread public static String getClientMetadataId ( Context context , PayPalDataCollectorRequest request ) { } }

implementation: if ( context == null ) { return "" ; } MagnesSDK magnesInstance = MagnesSDK . getInstance ( ) ; MagnesSettings . Builder magnesSettingsBuilder = new MagnesSettings . Builder ( context ) . setMagnesSource ( MagnesSource . BRAINTREE ) . disableBeacon ( request . isDisableBeacon ( ) ) . setMagnesEnvironment ( Environment . LIVE ) . setAppGuid ( request . getApplicationGuid ( ) ) ; magnesInstance . setUp ( magnesSettingsBuilder . build ( ) ) ; MagnesResult result = magnesInstance . collectAndSubmit ( context , request . getClientMetadataId ( ) , request . getAdditionalData ( ) ) ; return result . getPaypalClientMetaDataId ( ) ;


signature:
public class AmericanExpressRewardsBalance { /** * 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 . */
public static AmericanExpressRewardsBalance fromJson ( String jsonString ) throws JSONException { } }

implementation: 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 ;


signature:
public class VenmoAccountNonce { /** * Convert an API response to an { @ link VenmoAccountNonce } .
 * @ param json Raw JSON response from Braintree of a { @ link VenmoAccountNonce } .
 * @ return { @ link VenmoAccountNonce } .
 * @ throws JSONException when parsing the response fails . */
public static VenmoAccountNonce fromJson ( String json ) throws JSONException { } }

implementation: VenmoAccountNonce venmoAccountNonce = new VenmoAccountNonce ( ) ; venmoAccountNonce . fromJson ( VenmoAccountNonce . getJsonObjectForType ( API_RESOURCE_KEY , new JSONObject ( json ) ) ) ; return venmoAccountNonce ;


signature:
public class UnionPay { /** * Fetches the capabilities of a card . If the card needs to be enrolled use { @ link
 * UnionPay # enroll ( BraintreeFragment , UnionPayCardBuilder ) } .
 * On completion , returns the { @ link UnionPayCapabilities } to
 * { @ link com . braintreepayments . api . interfaces . UnionPayListener # onCapabilitiesFetched ( UnionPayCapabilities ) }
 * On error , an exception will be passed back to
 * { @ link com . braintreepayments . api . interfaces . BraintreeErrorListener # onError ( Exception ) }
 * @ param fragment { @ link BraintreeFragment }
 * @ param cardNumber The card number to check for Union Pay capabilities . */
public static void fetchCapabilities ( final BraintreeFragment fragment , final String cardNumber ) { } }

implementation: fragment . waitForConfiguration ( new ConfigurationListener ( ) { @ Override public void onConfigurationFetched ( Configuration configuration ) { if ( ! configuration . getUnionPay ( ) . isEnabled ( ) ) { fragment . postCallback ( new ConfigurationException ( "UnionPay is not enabled" ) ) ; return ; } String fetchCapabilitiesUrl = Uri . parse ( UNIONPAY_CAPABILITIES_PATH ) . buildUpon ( ) . appendQueryParameter ( "creditCard[number]" , cardNumber ) . build ( ) . toString ( ) ; fragment . getHttpClient ( ) . get ( fetchCapabilitiesUrl , new HttpResponseCallback ( ) { @ Override public void success ( String responseBody ) { fragment . postCallback ( UnionPayCapabilities . fromJson ( responseBody ) ) ; fragment . sendAnalyticsEvent ( "union-pay.capabilities-received" ) ; } @ Override public void failure ( Exception exception ) { fragment . postCallback ( exception ) ; fragment . sendAnalyticsEvent ( "union-pay.capabilities-failed" ) ; } } ) ; } } ) ;


signature:
public class UnionPay { /** * Enrolls a Union Pay card . Only call this method if the card needs to be enrolled . Check { @ link
 * UnionPay # fetchCapabilities ( BraintreeFragment , String ) } if your card needs to be enrolled .
 * On completion , returns a enrollmentId to
 * { @ link com . braintreepayments . api . interfaces . UnionPayListener # onSmsCodeSent ( String , boolean ) }
 * This enrollmentId needs to be applied to { @ link UnionPayCardBuilder } along with the SMS code
 * collected from the merchant before invoking { @ link UnionPay # tokenize ( BraintreeFragment , UnionPayCardBuilder ) }
 * On error , an exception will be passed back to
 * { @ link com . braintreepayments . api . interfaces . BraintreeErrorListener # onError ( Exception ) }
 * @ param fragment { @ link BraintreeFragment }
 * @ param unionPayCardBuilder { @ link UnionPayCardBuilder } */
public static void enroll ( final BraintreeFragment fragment , final UnionPayCardBuilder unionPayCardBuilder ) { } }

implementation: fragment . waitForConfiguration ( new ConfigurationListener ( ) { @ Override public void onConfigurationFetched ( Configuration configuration ) { UnionPayConfiguration unionPayConfiguration = configuration . getUnionPay ( ) ; if ( ! unionPayConfiguration . isEnabled ( ) ) { fragment . postCallback ( new ConfigurationException ( "UnionPay is not enabled" ) ) ; return ; } try { JSONObject enrollmentPayloadJson = unionPayCardBuilder . buildEnrollment ( ) ; fragment . getHttpClient ( ) . post ( UNIONPAY_ENROLLMENT_PATH , enrollmentPayloadJson . toString ( ) , new HttpResponseCallback ( ) { @ Override public void success ( String responseBody ) { try { JSONObject response = new JSONObject ( responseBody ) ; String enrollmentId = response . getString ( UNIONPAY_ENROLLMENT_ID_KEY ) ; boolean smsCodeRequired = response . getBoolean ( UNIONPAY_SMS_REQUIRED_KEY ) ; fragment . postUnionPayCallback ( enrollmentId , smsCodeRequired ) ; fragment . sendAnalyticsEvent ( "union-pay.enrollment-succeeded" ) ; } catch ( JSONException e ) { failure ( e ) ; } } @ Override public void failure ( Exception exception ) { fragment . postCallback ( exception ) ; fragment . sendAnalyticsEvent ( "union-pay.enrollment-failed" ) ; } } ) ; } catch ( JSONException exception ) { fragment . postCallback ( exception ) ; } } } ) ;


signature:
public class UnionPay { /** * Create a { @ link com . braintreepayments . api . models . CardNonce } . Note that if the card is a UnionPay card ,
 * { @ link UnionPayCardBuilder # enrollmentId ( String ) } and { @ link UnionPayCardBuilder # smsCode ( String ) }
 * need to be set for tokenization to succeed .
 * On completion , returns the { @ link com . braintreepayments . api . models . PaymentMethodNonce } to { @ link
 * com . braintreepayments . api . interfaces . PaymentMethodNonceCreatedListener } .
 * If creation fails validation , { @ link com . braintreepayments . api . interfaces . BraintreeErrorListener # onError ( Exception ) }
 * will be called with the resulting { @ link com . braintreepayments . api . exceptions . ErrorWithResponse } .
 * If an error not due to validation ( server error , network issue , etc . ) occurs , { @ link
 * com . braintreepayments . api . interfaces . BraintreeErrorListener # onError ( Exception ) } will be called with the { @ link
 * Exception } that occurred .
 * @ param fragment { @ link BraintreeFragment }
 * @ param unionPayCardBuilder { @ link UnionPayCardBuilder } */
public static void tokenize ( final BraintreeFragment fragment , final UnionPayCardBuilder unionPayCardBuilder ) { } }

implementation: TokenizationClient . tokenize ( fragment , unionPayCardBuilder , new PaymentMethodNonceCallback ( ) { @ Override public void success ( PaymentMethodNonce paymentMethodNonce ) { fragment . postCallback ( paymentMethodNonce ) ; fragment . sendAnalyticsEvent ( "union-pay.nonce-received" ) ; } @ Override public void failure ( Exception exception ) { fragment . postCallback ( exception ) ; fragment . sendAnalyticsEvent ( "union-pay.nonce-failed" ) ; } } ) ;


signature:
public class LocalPaymentResult { /** * Convert an API response to a { @ link LocalPaymentResult } .
 * @ param json Raw JSON representation of a { @ link LocalPaymentResult } .
 * @ return { @ link LocalPaymentResult } for use in payment method selection UIs . */
public static LocalPaymentResult fromJson ( String json ) throws JSONException { } }

implementation: LocalPaymentResult localPaymentResult = new LocalPaymentResult ( ) ; localPaymentResult . fromJson ( LocalPaymentResult . getJsonObjectForType ( API_RESOURCE_KEY , new JSONObject ( json ) ) ) ; return localPaymentResult ;


signature:
public class LocalPaymentResult { /** * Generates a { @ link LocalPaymentResult } from the { @ link JSONObject } .
 * @ param json { @ link JSONObject } that holds properties for { @ link LocalPaymentResult } .
 * @ throws JSONException */
protected void fromJson ( JSONObject json ) throws JSONException { } }

implementation: super . fromJson ( json ) ; JSONObject details = json . getJSONObject ( DETAILS_KEY ) ; mEmail = Json . optString ( details , EMAIL_KEY , null ) ; mClientMetadataId = Json . optString ( details , CLIENT_METADATA_ID_KEY , null ) ; mType = Json . optString ( json , TYPE_KEY , "PayPalAccount" ) ; try { JSONObject payerInfo = details . getJSONObject ( PAYER_INFO_KEY ) ; JSONObject billingAddress ; if ( payerInfo . has ( ACCOUNT_ADDRESS_KEY ) ) { billingAddress = payerInfo . optJSONObject ( ACCOUNT_ADDRESS_KEY ) ; } else { billingAddress = payerInfo . optJSONObject ( BILLING_ADDRESS_KEY ) ; } JSONObject shippingAddress = payerInfo . optJSONObject ( SHIPPING_ADDRESS_KEY ) ; mBillingAddress = PostalAddressParser . fromJson ( billingAddress ) ; mShippingAddress = PostalAddressParser . fromJson ( shippingAddress ) ; mGivenName = Json . optString ( payerInfo , FIRST_NAME_KEY , "" ) ; mSurname = Json . optString ( payerInfo , LAST_NAME_KEY , "" ) ; mPhone = Json . optString ( payerInfo , PHONE_KEY , "" ) ; mPayerId = Json . optString ( payerInfo , PAYER_ID_KEY , "" ) ; if ( mEmail == null ) { mEmail = Json . optString ( payerInfo , EMAIL_KEY , null ) ; } } catch ( JSONException e ) { mBillingAddress = new PostalAddress ( ) ; mShippingAddress = new PostalAddress ( ) ; }