Input: To use embedded icons provided by the fabric8 - console [CODESPLIT] protected String embeddedIconsInConsole ( String iconRef , String prefix ) { 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 ; }


Input: Returns the spring boot configuration ( supports application . properties and application . yml ) or an empty properties object if not found [CODESPLIT] public static Properties getSpringBootApplicationProperties ( URLClassLoader compileClassLoader ) { URL ymlResource = compileClassLoader . findResource ( "application.yml" ) ; URL propertiesResource = compileClassLoader . findResource ( "application.properties" ) ; Properties props = YamlUtil . getPropertiesFromYamlResource ( ymlResource ) ; props . putAll ( getPropertiesResource ( propertiesResource ) ) ; return props ; }


Input: Returns the given properties resource on the project classpath if found or an empty properties object if not [CODESPLIT] protected static Properties getPropertiesResource ( URL resource ) { Properties answer = new Properties ( ) ; if ( resource != null ) { try ( InputStream stream = resource . openStream ( ) ) { answer . load ( stream ) ; } catch ( IOException e ) { throw new IllegalStateException ( "Error while reading resource from URL " + resource , e ) ; } } return answer ; }


Input: Determine the spring - boot major version for the current project [CODESPLIT] public static Optional < String > getSpringBootVersion ( MavenProject mavenProject ) { return Optional . ofNullable ( MavenUtil . getDependencyVersion ( mavenProject , SpringBootConfigurationHelper . SPRING_BOOT_GROUP_ID , SpringBootConfigurationHelper . SPRING_BOOT_ARTIFACT_ID ) ) ; }


Input: 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 . [CODESPLIT] public < T > List < T > createServiceObjects ( String ... descriptorPaths ) { try { ServiceEntry . initDefaultOrder ( ) ; TreeMap < ServiceEntry , T > serviceMap = new TreeMap < ServiceEntry , T > ( ) ; for ( String descriptor : descriptorPaths ) { readServiceDefinitions ( serviceMap , descriptor ) ; } ArrayList < T > ret = new ArrayList < T > ( ) ; for ( T service : serviceMap . values ( ) ) { ret . add ( service ) ; } return ret ; } finally { ServiceEntry . removeDefaultOrder ( ) ; } }


Input: Allow enricher to add Metadata to the resources . [CODESPLIT] private void enrich ( PlatformMode platformMode , final ProcessorConfig enricherConfig , final KubernetesListBuilder builder , final List < Enricher > enricherList ) { loop ( enricherConfig , enricher -> { enricher . enrich ( platformMode , builder ) ; return null ; } ) ; }


Input: ============================================================================================= [CODESPLIT] private void logEnrichers ( List < Enricher > enrichers ) { log . verbose ( "Enrichers:" ) ; for ( Enricher enricher : enrichers ) { log . verbose ( "- %s" , enricher . getName ( ) ) ; } }


Input: Returns the thorntail configuration ( supports project - defaults . yml ) or an empty properties object if not found [CODESPLIT] public static Properties getThorntailProperties ( URLClassLoader compileClassLoader ) { URL ymlResource = compileClassLoader . findResource ( "project-defaults.yml" ) ; Properties props = YamlUtil . getPropertiesFromYamlResource ( ymlResource ) ; return props ; }


Input: Get the raw untyped configuration or an empty map [CODESPLIT] public Map < String , String > getRawConfig ( ) { return configuration . getProcessorConfig ( ) . orElse ( ProcessorConfig . EMPTY ) . getConfigMap ( name ) ; }


Input: Get a config value with a default . If no value is given as a last resort project properties are looked up . [CODESPLIT] public String get ( Configs . Key key , String defaultVal ) { 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 ; }


Input: / * 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 . [CODESPLIT] private void setupIgnoreRules ( ResourceClassifier target ) { ignoreValidationRules . add ( new IgnorePortValidationRule ( IgnorePortValidationRule . TYPE ) ) ; ignoreValidationRules . add ( new IgnoreResourceMemoryLimitRule ( IgnoreResourceMemoryLimitRule . TYPE ) ) ; }


Input: Validates the resource descriptors as per JSON schema . If any resource is invalid it throws @ { @link ConstraintViolationException } with all violated constraints [CODESPLIT] public int validate ( ) throws ConstraintViolationException , IOException { 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 ; }


Input: Build a flattened representation of the Yaml tree . The conversion is compliant with the thorntail spring - boot rules . [CODESPLIT] private static Map < String , Object > getFlattenedMap ( Map < String , Object > source ) { Map < String , Object > result = new LinkedHashMap <> ( ) ; buildFlattenedMap ( result , source , null ) ; return result ; }


Input: 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 . [CODESPLIT] public String getSanitizedArtifactId ( ) { if ( this . artifactId != null && ! this . artifactId . isEmpty ( ) && Character . isDigit ( this . artifactId . charAt ( 0 ) ) ) { return PREFIX + this . artifactId ; } return this . artifactId ; }


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


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


Input: ================================================================================== [CODESPLIT] private List < ImageConfiguration > getResolvedImages ( List < ImageConfiguration > images , final Logger log ) throws MojoExecutionException { 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 ; }


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


Input: This method detects if the user has changed the configuration of an entity . <p / > It compares the <b > user< / b > configuration of 2 object trees ignoring any runtime status or timestamp information . [CODESPLIT] public static boolean configEqual ( Object entity1 , Object entity2 ) { 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 ) ; } }


Input: Compares 2 instances of the given Kubernetes DTO class to see if the user has changed their configuration . <p / > This method will ignore properties { [CODESPLIT] protected static boolean configEqualKubernetesDTO ( @ NotNull Object entity1 , @ NotNull Object entity2 , @ NotNull Class < ? > clazz ) { // 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 ; } }


Input: ============================================================================================= [CODESPLIT] private static void combineParameters ( List < Parameter > parameters , List < Parameter > otherParameters ) { 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 ( ) ) ; } } } } }


Input: Get a config value with a default [CODESPLIT] public String get ( Configs . Key key , String defaultVal ) { String keyVal = key != null ? key . name ( ) : "" ; String val = config != null ? config . getConfig ( name , key . name ( ) ) : null ; if ( val == null ) { String fullKey = GENERATOR_PROP_PREFIX + "." + name + "." + key ; val = Configs . getSystemPropertyWithMavenPropertyAsFallback ( properties , fullKey ) ; } return val != null ? val : defaultVal ; }


Input: Get a config value with a default . If no value is given as a last resort project properties are looked up . [CODESPLIT] public String get ( Configs . Key key , String defaultVal ) { 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 ; }


Input: Return full configuration as raw string - string values [CODESPLIT] public Map < String , String > getConfigMap ( String name ) { return config . containsKey ( name ) ? Collections . unmodifiableMap ( config . get ( name ) ) : Collections . < String , String > emptyMap ( ) ; }


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


Input: 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 : [CODESPLIT] public static ProcessorConfig mergeProcessorConfigs ( ProcessorConfig ... processorConfigs ) { // 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 ) ; }


Input: Only good for small list ( that s what we expect for enrichers and generators ) [CODESPLIT] private static List < String > removeDups ( List < String > list ) { List < String > ret = new ArrayList <> ( ) ; for ( String el : list ) { if ( ! ret . contains ( el ) ) { ret . add ( el ) ; } } return ret ; }


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


Input: Use istag as default for redhat versions of this plugin [CODESPLIT] private String getFromModeDefault ( RuntimeMode mode ) { if ( mode == RuntimeMode . openshift && fromSelector != null && fromSelector . isRedHat ( ) ) { return "istag" ; } else { return "docker" ; } }


Input: Get Image name with a standard default [CODESPLIT] protected String getImageName ( ) { if ( RuntimeMode . isOpenShiftMode ( getProject ( ) . getProperties ( ) ) ) { return getConfigWithFallback ( Config . name , "fabric8.generator.name" , "%a:%l" ) ; } else { return getConfigWithFallback ( Config . name , "fabric8.generator.name" , "%g/%a:%l" ) ; } }


Input: Get the docker registry where the image should be located . It returns null in Openshift mode . [CODESPLIT] protected String getRegistry ( ) { if ( ! RuntimeMode . isOpenShiftMode ( getProject ( ) . getProperties ( ) ) ) { return getConfigWithFallback ( Config . registry , "fabric8.generator.registry" , null ) ; } return null ; }


Input: Returns the absolute path to a resource addressed by the given <code > url< / code > [CODESPLIT] public static String getAbsolutePath ( URL url ) { try { return url != null ? Paths . get ( url . toURI ( ) ) . toAbsolutePath ( ) . toString ( ) : null ; } catch ( URISyntaxException e ) { throw new RuntimeException ( e ) ; } }


Input: Returns true if in offline mode false if not speciied . Can be overriden by [CODESPLIT] boolean isOnline ( ) { String isOnline = getConfig ( Config . online ) ; if ( isOnline != null ) { return Configs . asBoolean ( isOnline ) ; } Boolean ret = asBooleanFromGlobalProp ( "fabric8.online" ) ; return ret != null ? ret : getDefaultOnline ( ) ; }


Input: Returns the external access to the given service name [CODESPLIT] protected String getExternalServiceURL ( String serviceName , String protocol ) { if ( ! isOnline ( ) ) { getLog ( ) . info ( "Not looking for service " + serviceName + " as we are in offline mode" ) ; return null ; } else { try { KubernetesClient kubernetes = getKubernetes ( ) ; String ns = kubernetes . getNamespace ( ) ; if ( StringUtils . isBlank ( ns ) ) { ns = getNamespace ( ) ; } Service service = kubernetes . services ( ) . inNamespace ( ns ) . withName ( serviceName ) . get ( ) ; return service != null ? ServiceUrlUtil . getServiceURL ( kubernetes , serviceName , ns , protocol , true ) : null ; } catch ( Throwable e ) { Throwable cause = e ; boolean notFound = false ; boolean connectError = false ; Stack < Throwable > stack = unfoldExceptions ( e ) ; while ( ! stack . isEmpty ( ) ) { Throwable t = stack . pop ( ) ; if ( t instanceof ConnectException || "No route to host" . equals ( t . getMessage ( ) ) ) { getLog ( ) . warn ( "Cannot connect to Kubernetes to find URL for service %s : %s" , serviceName , cause . getMessage ( ) ) ; return null ; } else if ( t instanceof IllegalArgumentException || t . getMessage ( ) != null && t . getMessage ( ) . matches ( "^No.*found.*$" ) ) { getLog ( ) . warn ( "%s" , cause . getMessage ( ) ) ; return null ; } ; } getLog ( ) . warn ( "Cannot find URL for service %s : %s" , serviceName , cause . getMessage ( ) ) ; return null ; } } }


Input: Creates an Iterable to walk the exception from the bottom up ( the last caused by going upwards to the root exception ) . [CODESPLIT] protected Stack < Throwable > unfoldExceptions ( Throwable exception ) { 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 ; }


Input: Check a global prop from the project or system props [CODESPLIT] protected Boolean asBooleanFromGlobalProp ( String prop ) { String value = getContext ( ) . getConfiguration ( ) . getProperty ( prop ) ; if ( value == null ) { value = System . getProperty ( prop ) ; } return value != null ? Boolean . valueOf ( value ) : null ; }


Input: - default [CODESPLIT] private String getNamespace ( ) { 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 ( ) ; }


Input: Create Jest client with URI [CODESPLIT] private JestClient createJestClient ( String uri ) { HttpClientConfig . Builder builder = new HttpClientConfig . Builder ( uri ) . maxTotalConnection ( properties . getMaxTotalConnection ( ) ) . defaultMaxTotalConnectionPerRoute ( properties . getDefaultMaxTotalConnectionPerRoute ( ) ) . maxConnectionIdleTime ( properties . getMaxConnectionIdleTime ( ) , TimeUnit . MILLISECONDS ) . readTimeout ( properties . getReadTimeout ( ) ) . multiThreaded ( properties . getMultiThreaded ( ) ) ; if ( StringUtils . hasText ( this . properties . getUsername ( ) ) ) { builder . defaultCredentials ( this . properties . getUsername ( ) , this . properties . getPassword ( ) ) ; } String proxyHost = this . properties . getProxy ( ) . getHost ( ) ; if ( StringUtils . hasText ( proxyHost ) ) { Integer proxyPort = this . properties . getProxy ( ) . getPort ( ) ; Assert . notNull ( proxyPort , "Proxy port must not be null" ) ; builder . proxy ( new HttpHost ( proxyHost , proxyPort ) ) ; } List < HttpClientConfigBuilderCustomizer > configBuilderCustomizers = builderCustomizers != null ? builderCustomizers . getIfAvailable ( ) : new ArrayList <> ( ) ; if ( ! CollectionUtils . isEmpty ( configBuilderCustomizers ) ) { logger . info ( "Custom HttpClientConfigBuilderCustomizers detected. Applying these to the HttpClientConfig builder." ) ; configBuilderCustomizers . stream ( ) . forEach ( customizer -> customizer . customize ( builder ) ) ; logger . info ( "Custom HttpClientConfigBuilderCustomizers applied." ) ; } JestClientFactory factory = jestClientFactory != null ? jestClientFactory : new JestClientFactory ( ) ; factory . setHttpClientConfig ( builder . build ( ) ) ; return factory . getObject ( ) ; }


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


Input: List all official ES plugins available on ClassPath . [CODESPLIT] @ SuppressWarnings ( "unchecked" ) private static Collection < Class < ? extends Plugin > > scanPlugins ( ) { ClassPathScanningCandidateComponentProvider componentProvider = new ClassPathScanningCandidateComponentProvider ( false ) ; componentProvider . addIncludeFilter ( new AssignableTypeFilter ( Plugin . class ) ) ; return componentProvider . findCandidateComponents ( "org.elasticsearch.plugin" ) . stream ( ) . map ( BeanDefinition :: getBeanClassName ) . map ( name -> { try { return ( Class < ? extends Plugin > ) Class . forName ( name ) ; } catch ( ClassNotFoundException e ) { logger . warn ( "Cannot load class on plugin detection" , e ) ; return null ; } } ) . collect ( Collectors . toSet ( ) ) ; }


Input: extract the distance string from a { @link org . springframework . data . geo . Distance } object . [CODESPLIT] private void extractDistanceString ( Distance distance , StringBuilder sb ) { // 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 ; } }


Input: Add mapping for @Field annotation [CODESPLIT] private static void addSingleFieldMapping ( XContentBuilder builder , java . lang . reflect . Field field , Field annotation , boolean nestedOrObjectField ) throws IOException { builder . startObject ( field . getName ( ) ) ; addFieldMappingParameters ( builder , annotation , nestedOrObjectField ) ; builder . endObject ( ) ; }


Input: Add mapping for @MultiField annotation [CODESPLIT] private static void addMultiFieldMapping ( XContentBuilder builder , java . lang . reflect . Field field , MultiField annotation , boolean nestedOrObjectField ) throws IOException { // 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 ( ) ; }


Input: Parse a { @link GraphQLConfiguration } from json . [CODESPLIT] public static GraphQLConfiguration fromJson ( JSONObject json ) { 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 ; }


Input: 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 . [CODESPLIT] @ MainThread public static String getClientMetadataId ( Context context ) { PayPalDataCollectorRequest request = new PayPalDataCollectorRequest ( ) . setApplicationGuid ( InstallationIdentifier . getInstallationGUID ( context ) ) ; return getClientMetadataId ( context , request ) ; }


Input: 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 . [CODESPLIT] @ MainThread public static String getClientMetadataId ( Context context , PayPalDataCollectorRequest request ) { 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 ( ) ; }


Input: Used to parse a response from the Braintree Gateway to be used for American Express rewards balance . [CODESPLIT] public static AmericanExpressRewardsBalance fromJson ( String jsonString ) throws JSONException { JSONObject json = new JSONObject ( jsonString ) ; AmericanExpressRewardsBalance rewardsBalance = new AmericanExpressRewardsBalance ( ) ; if ( json . has ( ERROR_KEY ) ) { JSONObject errorJson = json . getJSONObject ( ERROR_KEY ) ; rewardsBalance . mErrorMessage = errorJson . getString ( ERROR_MESSAGE_KEY ) ; rewardsBalance . mErrorCode = errorJson . getString ( ERROR_CODE_KEY ) ; } rewardsBalance . mConversionRate = Json . optString ( json , CONVERSION_RATE_KEY , null ) ; rewardsBalance . mCurrencyAmount = Json . optString ( json , CURRENCY_AMOUNT_KEY , null ) ; rewardsBalance . mCurrencyIsoCode = Json . optString ( json , CURRENCY_ISO_CODE_KEY , null ) ; rewardsBalance . mRequestId = Json . optString ( json , REQUEST_ID_KEY , null ) ; rewardsBalance . mRewardsAmount = Json . optString ( json , REWARDS_AMOUNT_KEY , null ) ; rewardsBalance . mRewardsUnit = Json . optString ( json , REWARDS_UNIT_KEY , null ) ; return rewardsBalance ; }


Input: Convert an API response to an { @link VenmoAccountNonce } . [CODESPLIT] public static VenmoAccountNonce fromJson ( String json ) throws JSONException { VenmoAccountNonce venmoAccountNonce = new VenmoAccountNonce ( ) ; venmoAccountNonce . fromJson ( VenmoAccountNonce . getJsonObjectForType ( API_RESOURCE_KEY , new JSONObject ( json ) ) ) ; return venmoAccountNonce ; }


Input: Fetches the capabilities of a card . If the card needs to be enrolled use { @link UnionPay#enroll ( BraintreeFragment UnionPayCardBuilder ) } . <p / > On completion returns the { @link UnionPayCapabilities } to { @link com . braintreepayments . api . interfaces . UnionPayListener#onCapabilitiesFetched ( UnionPayCapabilities ) } <p / > On error an exception will be passed back to { @link com . braintreepayments . api . interfaces . BraintreeErrorListener#onError ( Exception ) } [CODESPLIT] public static void fetchCapabilities ( final BraintreeFragment fragment , final String cardNumber ) { 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" ) ; } } ) ; } } ) ; }


Input: 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 . <p / > 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 ) } <p / > On error an exception will be passed back to { @link com . braintreepayments . api . interfaces . BraintreeErrorListener#onError ( Exception ) } [CODESPLIT] public static void enroll ( final BraintreeFragment fragment , final UnionPayCardBuilder unionPayCardBuilder ) { 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 ) ; } } } ) ; }


Input: 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 . <p / > On completion returns the { @link com . braintreepayments . api . models . PaymentMethodNonce } to { @link com . braintreepayments . api . interfaces . PaymentMethodNonceCreatedListener } . <p / > If creation fails validation { @link com . braintreepayments . api . interfaces . BraintreeErrorListener#onError ( Exception ) } will be called with the resulting { @link com . braintreepayments . api . exceptions . ErrorWithResponse } . <p / > 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 . [CODESPLIT] public static void tokenize ( final BraintreeFragment fragment , final UnionPayCardBuilder unionPayCardBuilder ) { 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" ) ; } } ) ; }


Input: Convert an API response to a { @link LocalPaymentResult } . [CODESPLIT] public static LocalPaymentResult fromJson ( String json ) throws JSONException { LocalPaymentResult localPaymentResult = new LocalPaymentResult ( ) ; localPaymentResult . fromJson ( LocalPaymentResult . getJsonObjectForType ( API_RESOURCE_KEY , new JSONObject ( json ) ) ) ; return localPaymentResult ; }


Input: Generates a { @link LocalPaymentResult } from the { @link JSONObject } . [CODESPLIT] protected void fromJson ( JSONObject json ) throws JSONException { 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 ( ) ; } }


Input: Launches an { @link Intent } pointing to the Venmo app on the Google Play Store [CODESPLIT] public static void openVenmoAppPageInGooglePlay ( BraintreeFragment fragment ) { fragment . sendAnalyticsEvent ( "android.pay-with-venmo.app-store.invoked" ) ; Intent intent = new Intent ( Intent . ACTION_VIEW ) ; intent . setData ( Uri . parse ( "https://play.google.com/store/apps/details?id=" + PACKAGE_NAME ) ) ; fragment . startActivity ( intent ) ; }


Input: Start the Pay With Venmo flow . This will app switch to the Venmo app . <p / > If the Venmo app is not available { @link AppSwitchNotAvailableException } will be sent to { @link com . braintreepayments . api . interfaces . BraintreeErrorListener#onError ( Exception ) } . [CODESPLIT] public static void authorizeAccount ( final BraintreeFragment fragment , final boolean vault , final String profileId ) { fragment . waitForConfiguration ( new ConfigurationListener ( ) { @ Override public void onConfigurationFetched ( Configuration configuration ) { fragment . sendAnalyticsEvent ( "pay-with-venmo.selected" ) ; String venmoProfileId = profileId ; if ( TextUtils . isEmpty ( venmoProfileId ) ) { venmoProfileId = configuration . getPayWithVenmo ( ) . getMerchantId ( ) ; } String exceptionMessage = "" ; if ( ! configuration . getPayWithVenmo ( ) . isAccessTokenValid ( ) ) { exceptionMessage = "Venmo is not enabled" ; } else if ( ! Venmo . isVenmoInstalled ( fragment . getApplicationContext ( ) ) ) { exceptionMessage = "Venmo is not installed" ; } if ( ! TextUtils . isEmpty ( exceptionMessage ) ) { fragment . postCallback ( new AppSwitchNotAvailableException ( exceptionMessage ) ) ; fragment . sendAnalyticsEvent ( "pay-with-venmo.app-switch.failed" ) ; } else { persistVenmoVaultOption ( vault && fragment . getAuthorization ( ) instanceof ClientToken , fragment . getApplicationContext ( ) ) ; fragment . startActivityForResult ( getLaunchIntent ( configuration . getPayWithVenmo ( ) , venmoProfileId , fragment ) , BraintreeRequestCodes . VENMO ) ; fragment . sendAnalyticsEvent ( "pay-with-venmo.app-switch.started" ) ; } } } ) ; }


Input: Parse a { @link CardConfiguration } from json . [CODESPLIT] public static CardConfiguration fromJson ( JSONObject json ) { if ( json == null ) { json = new JSONObject ( ) ; } CardConfiguration cardConfiguration = new CardConfiguration ( ) ; JSONArray jsonArray = json . optJSONArray ( SUPPORTED_CARD_TYPES_KEY ) ; if ( jsonArray != null ) { for ( int i = 0 ; i < jsonArray . length ( ) ; i ++ ) { cardConfiguration . mSupportedCardTypes . add ( jsonArray . optString ( i , "" ) ) ; } } cardConfiguration . mCollectFraudData = json . optBoolean ( COLLECT_DEVICE_DATA_KEY , false ) ; return cardConfiguration ; }


Input: Gets the rewards balance associated with a Braintree nonce . Only for American Express cards . [CODESPLIT] public static void getRewardsBalance ( final BraintreeFragment fragment , final String nonce , final String currencyIsoCode ) { fragment . waitForConfiguration ( new ConfigurationListener ( ) { @ Override public void onConfigurationFetched ( Configuration configuration ) { String getRewardsBalanceUrl = Uri . parse ( AMEX_REWARDS_BALANCE_PATH ) . buildUpon ( ) . appendQueryParameter ( "paymentMethodNonce" , nonce ) . appendQueryParameter ( "currencyIsoCode" , currencyIsoCode ) . build ( ) . toString ( ) ; fragment . sendAnalyticsEvent ( "amex.rewards-balance.start" ) ; fragment . getHttpClient ( ) . get ( getRewardsBalanceUrl , new HttpResponseCallback ( ) { @ Override public void success ( String responseBody ) { fragment . sendAnalyticsEvent ( "amex.rewards-balance.success" ) ; try { fragment . postAmericanExpressCallback ( AmericanExpressRewardsBalance . fromJson ( responseBody ) ) ; } catch ( JSONException e ) { fragment . sendAnalyticsEvent ( "amex.rewards-balance.parse.failed" ) ; fragment . postCallback ( e ) ; } } @ Override public void failure ( Exception exception ) { fragment . postCallback ( exception ) ; fragment . sendAnalyticsEvent ( "amex.rewards-balance.error" ) ; } } ) ; } } ) ; }


Input: Create a PayPalPaymentResource from a jsonString . Checks for keys associated with Single Payment and Billing Agreement flows . [CODESPLIT] public static PayPalPaymentResource fromJson ( String jsonString ) throws JSONException { JSONObject json = new JSONObject ( jsonString ) ; PayPalPaymentResource payPalPaymentResource = new PayPalPaymentResource ( ) ; JSONObject redirectJson = json . optJSONObject ( PAYMENT_RESOURCE_KEY ) ; if ( redirectJson != null ) { payPalPaymentResource . redirectUrl ( Json . optString ( redirectJson , REDIRECT_URL_KEY , "" ) ) ; } else { redirectJson = json . optJSONObject ( AGREEMENT_SETUP_KEY ) ; payPalPaymentResource . redirectUrl ( Json . optString ( redirectJson , APPROVAL_URL_KEY , "" ) ) ; } return payPalPaymentResource ; }


Input: Make a HTTP GET request to Braintree using the base url path and authorization provided . If the path is a full url it will be used instead of the previously provided url . [CODESPLIT] @ Override public void get ( String path , HttpResponseCallback callback ) { if ( path == null ) { postCallbackOnMainThread ( callback , new IllegalArgumentException ( "Path cannot be null" ) ) ; return ; } Uri uri ; if ( path . startsWith ( "http" ) ) { uri = Uri . parse ( path ) ; } else { uri = Uri . parse ( mBaseUrl + path ) ; } if ( mAuthorization instanceof ClientToken ) { uri = uri . buildUpon ( ) . appendQueryParameter ( AUTHORIZATION_FINGERPRINT_KEY , ( ( ClientToken ) mAuthorization ) . getAuthorizationFingerprint ( ) ) . build ( ) ; } super . get ( uri . toString ( ) , callback ) ; }


Input: Make a HTTP POST request to Braintree using the base url path and authorization provided . If the path is a full url it will be used instead of the previously provided url . [CODESPLIT] @ Override public void post ( String path , String data , HttpResponseCallback callback ) { try { if ( mAuthorization instanceof ClientToken ) { data = new JSONObject ( data ) . put ( AUTHORIZATION_FINGERPRINT_KEY , ( ( ClientToken ) mAuthorization ) . getAuthorizationFingerprint ( ) ) . toString ( ) ; } super . post ( path , data , callback ) ; } catch ( JSONException e ) { postCallbackOnMainThread ( callback , e ) ; } }


Input: Makes a synchronous HTTP POST request to Braintree using the base url path and authorization provided . @see BraintreeHttpClient#post ( String String HttpResponseCallback ) [CODESPLIT] public String post ( String path , String data ) throws Exception { if ( mAuthorization instanceof ClientToken ) { data = new JSONObject ( data ) . put ( AUTHORIZATION_FINGERPRINT_KEY , ( ( ClientToken ) mAuthorization ) . getAuthorizationFingerprint ( ) ) . toString ( ) ; } return super . post ( path , data ) ; }


Input: Parses the Venmo configuration from json . [CODESPLIT] static VenmoConfiguration fromJson ( JSONObject json ) { if ( json == null ) { json = new JSONObject ( ) ; } VenmoConfiguration venmoConfiguration = new VenmoConfiguration ( ) ; venmoConfiguration . mAccessToken = Json . optString ( json , ACCESS_TOKEN_KEY , "" ) ; venmoConfiguration . mEnvironment = Json . optString ( json , ENVIRONMENT_KEY , "" ) ; venmoConfiguration . mMerchantId = Json . optString ( json , MERCHANT_ID_KEY , "" ) ; return venmoConfiguration ; }


Input: Used to parse a response from the Braintree Gateway to be used for 3D Secure . [CODESPLIT] public static ThreeDSecureAuthenticationResponse fromJson ( String jsonString ) { ThreeDSecureAuthenticationResponse authenticationResponse = new ThreeDSecureAuthenticationResponse ( ) ; try { JSONObject json = new JSONObject ( jsonString ) ; JSONObject cardJson = json . optJSONObject ( PAYMENT_METHOD_KEY ) ; if ( cardJson != null ) { CardNonce cardNonce = new CardNonce ( ) ; cardNonce . fromJson ( cardJson ) ; authenticationResponse . mCardNonce = cardNonce ; } authenticationResponse . mSuccess = json . getBoolean ( SUCCESS_KEY ) ; if ( ! authenticationResponse . mSuccess ) { authenticationResponse . mErrors = jsonString ; } } catch ( JSONException e ) { authenticationResponse . mSuccess = false ; } return authenticationResponse ; }


Input: Collect device information for fraud identification purposes . [CODESPLIT] public static void collectDeviceData ( BraintreeFragment fragment , BraintreeResponseListener < String > listener ) { collectDeviceData ( fragment , null , listener ) ; }


Input: Collect device information for fraud identification purposes . This should be used in conjunction with a non - aggregate fraud id . [CODESPLIT] public static void collectDeviceData ( final BraintreeFragment fragment , final String merchantId , final BraintreeResponseListener < String > listener ) { fragment . waitForConfiguration ( new ConfigurationListener ( ) { @ Override public void onConfigurationFetched ( Configuration configuration ) { final JSONObject deviceData = new JSONObject ( ) ; try { String clientMetadataId = getPayPalClientMetadataId ( fragment . getApplicationContext ( ) ) ; if ( ! TextUtils . isEmpty ( clientMetadataId ) ) { deviceData . put ( CORRELATION_ID_KEY , clientMetadataId ) ; } } catch ( JSONException ignored ) { } if ( configuration . getKount ( ) . isEnabled ( ) ) { final String id ; if ( merchantId != null ) { id = merchantId ; } else { id = configuration . getKount ( ) . getKountMerchantId ( ) ; } try { final String deviceSessionId = UUIDHelper . getFormattedUUID ( ) ; startDeviceCollector ( fragment , id , deviceSessionId , new BraintreeResponseListener < String > ( ) { @ Override public void onResponse ( String sessionId ) { try { deviceData . put ( DEVICE_SESSION_ID_KEY , deviceSessionId ) ; deviceData . put ( FRAUD_MERCHANT_ID_KEY , id ) ; } catch ( JSONException ignored ) { } listener . onResponse ( deviceData . toString ( ) ) ; } } ) ; } catch ( ClassNotFoundException | NoClassDefFoundError | NumberFormatException ignored ) { listener . onResponse ( deviceData . toString ( ) ) ; } } else { listener . onResponse ( deviceData . toString ( ) ) ; } } } ) ; }


Input: Collect PayPal device information for fraud identification purposes . [CODESPLIT] public static void collectPayPalDeviceData ( final BraintreeFragment fragment , final BraintreeResponseListener < String > listener ) { final JSONObject deviceData = new JSONObject ( ) ; try { String clientMetadataId = getPayPalClientMetadataId ( fragment . getApplicationContext ( ) ) ; if ( ! TextUtils . isEmpty ( clientMetadataId ) ) { deviceData . put ( CORRELATION_ID_KEY , clientMetadataId ) ; } } catch ( JSONException ignored ) { } listener . onResponse ( deviceData . toString ( ) ) ; }


Input: Collect device information for fraud identification purposes from PayPal only . [CODESPLIT] public static String getPayPalClientMetadataId ( Context context ) { try { return PayPalOneTouchCore . getClientMetadataId ( context ) ; } catch ( NoClassDefFoundError ignored ) { } try { return PayPalDataCollector . getClientMetadataId ( context ) ; } catch ( NoClassDefFoundError ignored ) { } return "" ; }


Input: Check if an app has the correct matching signature . Used to prevent malicious apps from impersonating other apps . [CODESPLIT] @ SuppressLint ( "PackageManagerGetSignatures" ) public static boolean isSignatureValid ( Context context , String packageName , String certificateSubject , String certificateIssuer , int publicKeyHashCode ) { if ( ! sEnableSignatureVerification ) { return true ; } PackageManager packageManager = context . getPackageManager ( ) ; Signature [ ] signatures ; try { signatures = packageManager . getPackageInfo ( packageName , PackageManager . GET_SIGNATURES ) . signatures ; } catch ( NameNotFoundException e ) { return false ; } InputStream certStream = null ; boolean validated = ( signatures . length != 0 ) ; for ( Signature signature : signatures ) { try { certStream = new ByteArrayInputStream ( signature . toByteArray ( ) ) ; X509Certificate x509Cert = ( X509Certificate ) CertificateFactory . getInstance ( "X509" ) . generateCertificate ( certStream ) ; String subject = x509Cert . getSubjectX500Principal ( ) . getName ( ) ; String issuer = x509Cert . getIssuerX500Principal ( ) . getName ( ) ; int actualPublicKeyHashCode = x509Cert . getPublicKey ( ) . hashCode ( ) ; validated &= ( certificateSubject . equals ( subject ) && certificateIssuer . equals ( issuer ) && publicKeyHashCode == actualPublicKeyHashCode ) ; if ( ! validated ) { return false ; } } catch ( CertificateException e ) { return false ; } finally { try { if ( certStream != null ) { certStream . close ( ) ; } } catch ( IOException ignored ) { } } } return validated ; }


Input: Retrieves the current list of { @link PaymentMethodNonce } s for the current customer . <p / > When finished the { @link java . util . List } of { @link PaymentMethodNonce } s will be sent to { @link PaymentMethodNoncesUpdatedListener#onPaymentMethodNoncesUpdated ( List ) } . [CODESPLIT] public static void getPaymentMethodNonces ( final BraintreeFragment fragment , boolean defaultFirst ) { final Uri uri = Uri . parse ( TokenizationClient . versionedPath ( TokenizationClient . PAYMENT_METHOD_ENDPOINT ) ) . buildUpon ( ) . appendQueryParameter ( "default_first" , String . valueOf ( defaultFirst ) ) . appendQueryParameter ( "session_id" , fragment . getSessionId ( ) ) . build ( ) ; fragment . waitForConfiguration ( new ConfigurationListener ( ) { @ Override public void onConfigurationFetched ( Configuration configuration ) { fragment . getHttpClient ( ) . get ( uri . toString ( ) , new HttpResponseCallback ( ) { @ Override public void success ( String responseBody ) { try { fragment . postCallback ( PaymentMethodNonce . parsePaymentMethodNonces ( responseBody ) ) ; fragment . sendAnalyticsEvent ( "get-payment-methods.succeeded" ) ; } catch ( JSONException e ) { fragment . postCallback ( e ) ; fragment . sendAnalyticsEvent ( "get-payment-methods.failed" ) ; } } @ Override public void failure ( Exception exception ) { fragment . postCallback ( exception ) ; fragment . sendAnalyticsEvent ( "get-payment-methods.failed" ) ; } } ) ; } } ) ; }


Input: Deletes a payment method owned by the customer whose id was used to generate the { @link ClientToken } used to create the { @link BraintreeFragment } . <p / > Note : This method only works with Android Lollipop ( > = 21 ) and above . This will invoke { @link com . braintreepayments . api . interfaces . BraintreeErrorListener#onError ( Exception ) } when <ul > <li > A { @link com . braintreepayments . api . models . TokenizationKey } is used . < / li > <li > The device is below Lollipop . < / li > <li > If the request fails . < / li > <ul / > [CODESPLIT] public static void deletePaymentMethod ( final BraintreeFragment fragment , final PaymentMethodNonce paymentMethodNonce ) { boolean usesClientToken = fragment . getAuthorization ( ) instanceof ClientToken ; if ( ! usesClientToken ) { fragment . postCallback ( new BraintreeException ( "A client token with a customer id must be used to delete a payment method nonce." ) ) ; return ; } JSONObject base = new JSONObject ( ) ; JSONObject variables = new JSONObject ( ) ; JSONObject input = new JSONObject ( ) ; try { base . put ( CLIENT_SDK_META_DATA , new MetadataBuilder ( ) . sessionId ( fragment . getSessionId ( ) ) . source ( "client" ) . integration ( fragment . getIntegrationType ( ) ) . build ( ) ) ; base . put ( GraphQLConstants . Keys . QUERY , GraphQLQueryHelper . getQuery ( fragment . getApplicationContext ( ) , R . raw . delete_payment_method_mutation ) ) ; input . put ( SINGLE_USE_TOKEN_ID , paymentMethodNonce . getNonce ( ) ) ; variables . put ( INPUT , input ) ; base . put ( VARIABLES , variables ) ; base . put ( GraphQLConstants . Keys . OPERATION_NAME , "DeletePaymentMethodFromSingleUseToken" ) ; } catch ( Resources . NotFoundException | IOException | JSONException e ) { fragment . postCallback ( new BraintreeException ( "Unable to read GraphQL query" ) ) ; } fragment . getGraphQLHttpClient ( ) . post ( base . toString ( ) , new HttpResponseCallback ( ) { @ Override public void success ( String responseBody ) { fragment . postPaymentMethodDeletedCallback ( paymentMethodNonce ) ; fragment . sendAnalyticsEvent ( "delete-payment-methods.succeeded" ) ; } @ Override public void failure ( Exception exception ) { fragment . postCallback ( new PaymentMethodDeleteException ( paymentMethodNonce , exception ) ) ; fragment . sendAnalyticsEvent ( "delete-payment-methods.failed" ) ; } } ) ; }


Input: Get a { @link PendingRequest } containing an { @link Intent } used to start a PayPal authentication request using the best possible authentication mechanism : wallet or browser . [CODESPLIT] public static PendingRequest getStartIntent ( Context context , Request request ) { initService ( context ) ; // calling this method functionally does nothing, but ensures that we send off FPTI data about wallet installs. isWalletAppInstalled ( context ) ; Recipe recipe = request . getRecipeToExecute ( context , sConfigManager . getConfig ( ) ) ; if ( recipe == null ) { return new PendingRequest ( false , null , null , null ) ; } if ( RequestTarget . wallet == recipe . getTarget ( ) ) { request . trackFpti ( context , TrackingPoint . SwitchToWallet , recipe . getProtocol ( ) ) ; return new PendingRequest ( true , RequestTarget . wallet , request . getClientMetadataId ( ) , AppSwitchHelper . getAppSwitchIntent ( sContextInspector , sConfigManager , request , recipe ) ) ; } else { Intent intent = BrowserSwitchHelper . getBrowserSwitchIntent ( sContextInspector , sConfigManager , request ) ; if ( intent != null ) { return new PendingRequest ( true , RequestTarget . browser , request . getClientMetadataId ( ) , intent ) ; } else { return new PendingRequest ( false , RequestTarget . browser , request . getClientMetadataId ( ) , null ) ; } } }


Input: Gets a { @link Result } from an { @link Intent } returned by either the PayPal Wallet app or the browser . [CODESPLIT] public static Result parseResponse ( Context context , Request request , Intent data ) { initService ( context ) ; if ( data != null && data . getData ( ) != null ) { return BrowserSwitchHelper . parseBrowserSwitchResponse ( sContextInspector , request , data . getData ( ) ) ; } else if ( data != null && data . getExtras ( ) != null && ! data . getExtras ( ) . isEmpty ( ) ) { return AppSwitchHelper . parseAppSwitchResponse ( sContextInspector , request , data ) ; } else { request . trackFpti ( context , TrackingPoint . Cancel , null ) ; return new Result ( ) ; } }


Input: 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 . [CODESPLIT] @ MainThread public static String getClientMetadataId ( Context context , String pairingId ) { return PayPalDataCollector . getClientMetadataId ( context , pairingId ) ; }


Input: Verification is associated with a transaction amount and your merchant account . To specify a different merchant account ( or in turn currency ) you will need to specify the merchant account id when <a href = https : // developers . braintreepayments . com / android / sdk / overview / generate - client - token > generating a client token< / a > [CODESPLIT] public static void performVerification ( final BraintreeFragment fragment , final CardBuilder cardBuilder , final String amount ) { TokenizationClient . tokenize ( fragment , cardBuilder , new PaymentMethodNonceCallback ( ) { @ Override public void success ( PaymentMethodNonce paymentMethodNonce ) { performVerification ( fragment , paymentMethodNonce . getNonce ( ) , amount ) ; } @ Override public void failure ( Exception exception ) { fragment . postCallback ( exception ) ; } } ) ; }


Input: Verification is associated with a transaction amount and your merchant account . To specify a different merchant account ( or in turn currency ) you will need to specify the merchant account id when <a href = https : // developers . braintreepayments . com / android / sdk / overview / generate - client - token > generating a client token< / a > [CODESPLIT] public static void performVerification ( final BraintreeFragment fragment , final String nonce , final String amount ) { ThreeDSecureRequest request = new ThreeDSecureRequest ( ) . nonce ( nonce ) . amount ( amount ) ; performVerification ( fragment , request ) ; }


Input: Verification is associated with a transaction amount and your merchant account . To specify a different merchant account ( or in turn currency ) you will need to specify the merchant account id when <a href = https : // developers . braintreepayments . com / android / sdk / overview / generate - client - token > generating a client token< / a > [CODESPLIT] public static void performVerification ( final BraintreeFragment fragment , final ThreeDSecureRequest request ) { if ( request . getAmount ( ) == null || request . getNonce ( ) == null ) { fragment . postCallback ( new InvalidArgumentException ( "The ThreeDSecureRequest nonce and amount cannot be null" ) ) ; return ; } fragment . waitForConfiguration ( new ConfigurationListener ( ) { @ Override public void onConfigurationFetched ( Configuration configuration ) { if ( ! configuration . isThreeDSecureEnabled ( ) ) { fragment . postCallback ( new BraintreeException ( "Three D Secure is not enabled in the control panel" ) ) ; return ; } final boolean supportsBrowserSwitch = ManifestValidator . isUrlSchemeDeclaredInAndroidManifest ( fragment . getApplicationContext ( ) , fragment . getReturnUrlScheme ( ) , BraintreeBrowserSwitchActivity . class ) ; if ( ! supportsBrowserSwitch ) { fragment . sendAnalyticsEvent ( "three-d-secure.invalid-manifest" ) ; fragment . postCallback ( new BraintreeException ( "BraintreeBrowserSwitchActivity missing, " + "incorrectly configured in AndroidManifest.xml or another app defines the same browser " + "switch url as this app. See " + "https://developers.braintreepayments.com/guides/client-sdk/android/v2#browser-switch " + "for the correct configuration" ) ) ; return ; } fragment . getHttpClient ( ) . post ( TokenizationClient . versionedPath ( TokenizationClient . PAYMENT_METHOD_ENDPOINT + "/" + request . getNonce ( ) + "/three_d_secure/lookup" ) , request . build ( ) , new HttpResponseCallback ( ) { @ Override public void success ( String responseBody ) { try { ThreeDSecureLookup threeDSecureLookup = ThreeDSecureLookup . fromJson ( responseBody ) ; if ( threeDSecureLookup . getAcsUrl ( ) != null ) { launchBrowserSwitch ( fragment , threeDSecureLookup ) ; } else { fragment . postCallback ( threeDSecureLookup . getCardNonce ( ) ) ; } } catch ( JSONException e ) { fragment . postCallback ( e ) ; } } @ Override public void failure ( Exception exception ) { fragment . postCallback ( exception ) ; } } ) ; } } ) ; }


Input: Parse a { @link KountConfiguration } from json . [CODESPLIT] public static KountConfiguration fromJson ( JSONObject json ) { if ( json == null ) { json = new JSONObject ( ) ; } KountConfiguration kountConfiguration = new KountConfiguration ( ) ; kountConfiguration . mKountMerchantId = Json . optString ( json , KOUNT_MERCHANT_ID_KEY , "" ) ; return kountConfiguration ; }


Input: Create a { @link com . braintreepayments . api . models . CardNonce } . <p / > On completion returns the { @link com . braintreepayments . api . models . PaymentMethodNonce } to { @link com . braintreepayments . api . interfaces . PaymentMethodNonceCreatedListener } . <p / > If creation fails validation { @link com . braintreepayments . api . interfaces . BraintreeErrorListener#onError ( Exception ) } will be called with the resulting { @link com . braintreepayments . api . exceptions . ErrorWithResponse } . <p / > 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 . [CODESPLIT] public static void tokenize ( final BraintreeFragment fragment , final CardBuilder cardBuilder ) { TokenizationClient . tokenize ( fragment , cardBuilder , new PaymentMethodNonceCallback ( ) { @ Override public void success ( PaymentMethodNonce paymentMethodNonce ) { DataCollector . collectRiskData ( fragment , paymentMethodNonce ) ; fragment . postCallback ( paymentMethodNonce ) ; fragment . sendAnalyticsEvent ( "card.nonce-received" ) ; } @ Override public void failure ( Exception exception ) { fragment . postCallback ( exception ) ; fragment . sendAnalyticsEvent ( "card.nonce-failed" ) ; } } ) ; }


Input: Returns the value mapped by name if it exists coercing it if necessary or fallback if no such mapping exists . [CODESPLIT] public static String optString ( JSONObject json , String name , String fallback ) { if ( json . isNull ( name ) ) { return fallback ; } else { return json . optString ( name , fallback ) ; } }


Input: Parses a response from the Braintree gateway for a list of payment method nonces . [CODESPLIT] public static List < PaymentMethodNonce > parsePaymentMethodNonces ( String jsonBody ) throws JSONException { JSONArray paymentMethods = new JSONObject ( jsonBody ) . getJSONArray ( PAYMENT_METHOD_NONCE_COLLECTION_KEY ) ; if ( paymentMethods == null ) { return Collections . emptyList ( ) ; } List < PaymentMethodNonce > paymentMethodsNonces = new ArrayList <> ( ) ; JSONObject json ; PaymentMethodNonce paymentMethodNonce ; for ( int i = 0 ; i < paymentMethods . length ( ) ; i ++ ) { json = paymentMethods . getJSONObject ( i ) ; paymentMethodNonce = parsePaymentMethodNonces ( json , json . getString ( PAYMENT_METHOD_TYPE_KEY ) ) ; if ( paymentMethodNonce != null ) { paymentMethodsNonces . add ( paymentMethodNonce ) ; } } return paymentMethodsNonces ; }


Input: Parses a { @link PaymentMethodNonce } from json . [CODESPLIT] @ Nullable public static PaymentMethodNonce parsePaymentMethodNonces ( String json , String type ) throws JSONException { return parsePaymentMethodNonces ( new JSONObject ( json ) , type ) ; }


Input: Parses a { @link PaymentMethodNonce } from json . [CODESPLIT] @ Nullable public static PaymentMethodNonce parsePaymentMethodNonces ( JSONObject json , String type ) throws JSONException { switch ( type ) { case CardNonce . TYPE : if ( json . has ( CardNonce . API_RESOURCE_KEY ) || json . has ( CardNonce . DATA_KEY ) ) { return CardNonce . fromJson ( json . toString ( ) ) ; } else { CardNonce cardNonce = new CardNonce ( ) ; cardNonce . fromJson ( json ) ; return cardNonce ; } case PayPalAccountNonce . TYPE : if ( json . has ( PayPalAccountNonce . API_RESOURCE_KEY ) ) { return PayPalAccountNonce . fromJson ( json . toString ( ) ) ; } else { PayPalAccountNonce payPalAccountNonce = new PayPalAccountNonce ( ) ; payPalAccountNonce . fromJson ( json ) ; return payPalAccountNonce ; } case VenmoAccountNonce . TYPE : if ( json . has ( VenmoAccountNonce . API_RESOURCE_KEY ) ) { return VenmoAccountNonce . fromJson ( json . toString ( ) ) ; } else { VenmoAccountNonce venmoAccountNonce = new VenmoAccountNonce ( ) ; venmoAccountNonce . fromJson ( json ) ; return venmoAccountNonce ; } case VisaCheckoutNonce . TYPE : if ( json . has ( VisaCheckoutNonce . API_RESOURCE_KEY ) ) { return VisaCheckoutNonce . fromJson ( json . toString ( ) ) ; } else { VisaCheckoutNonce visaCheckoutNonce = new VisaCheckoutNonce ( ) ; visaCheckoutNonce . fromJson ( json ) ; return visaCheckoutNonce ; } default : return null ; } }


Input: 1 . Look for exact match of environment . ( Could be mock live or a particular host : port . ) 2 . If environment is anything other than mock or live then look for develop . 3 . Look for live . ( There should always be a live endpoint specified in any v3 browser - switch recipe . ) [CODESPLIT] public ConfigEndpoint getEndpoint ( String environment ) { ConfigEndpoint configEndpoint ; if ( mEndpoints . containsKey ( environment ) ) { configEndpoint = mEndpoints . get ( environment ) ; } else if ( mEndpoints . containsKey ( DEVELOP ) ) { configEndpoint = mEndpoints . get ( DEVELOP ) ; } else { // default to live as fallback configEndpoint = mEndpoints . get ( EnvironmentManager . LIVE ) ; } return configEndpoint ; }


Input: Defines the host to be used in the cancellation url for browser switch ( the package name will be used as the scheme ) [CODESPLIT] @ SuppressWarnings ( "unchecked" ) public T cancelUrl ( String scheme , String host ) { mCancelUrl = scheme + "://" + redirectURLHostAndPath ( ) + host ; return ( T ) this ; }


Input: Defines the host to be used in the success url for browser switch ( the package name will be used as the scheme ) [CODESPLIT] @ SuppressWarnings ( "unchecked" ) public T successUrl ( String scheme , String host ) { mSuccessUrl = scheme + "://" + redirectURLHostAndPath ( ) + host ; return ( T ) this ; }


Input: Returns the browser recipe that can handle checkout or null if there is none . [CODESPLIT] public CheckoutRecipe getBrowserCheckoutConfig ( ) { for ( CheckoutRecipe recipe : mCheckoutRecipesInDecreasingPriorityOrder ) { if ( recipe . getTarget ( ) == RequestTarget . browser ) { return recipe ; } } return null ; }


Input: Returns the browser recipe that can handle billing agreement or null if there is none . [CODESPLIT] public BillingAgreementRecipe getBrowserBillingAgreementConfig ( ) { for ( BillingAgreementRecipe recipe : mBillingAgreementRecipesInDecreasingPriorityOrder ) { if ( recipe . getTarget ( ) == RequestTarget . browser ) { return recipe ; } } return null ; }


Input: Convert an API response to a { @link CardNonce } . [CODESPLIT] public static CardNonce fromJson ( String json ) throws JSONException { CardNonce cardNonce = new CardNonce ( ) ; JSONObject jsonObject = new JSONObject ( json ) ; if ( jsonObject . has ( DATA_KEY ) ) { cardNonce . fromGraphQLJson ( jsonObject ) ; } else { cardNonce . fromJson ( CardNonce . getJsonObjectForType ( API_RESOURCE_KEY , jsonObject ) ) ; } return cardNonce ; }


Input: Populate properties with values from a { @link JSONObject } . [CODESPLIT] protected void fromJson ( JSONObject json ) throws JSONException { super . fromJson ( json ) ; JSONObject details = json . getJSONObject ( CARD_DETAILS_KEY ) ; mLastTwo = details . getString ( LAST_TWO_KEY ) ; mLastFour = details . getString ( LAST_FOUR_KEY ) ; mCardType = details . getString ( CARD_TYPE_KEY ) ; mThreeDSecureInfo = ThreeDSecureInfo . fromJson ( json . optJSONObject ( THREE_D_SECURE_INFO_KEY ) ) ; mBinData = BinData . fromJson ( json . optJSONObject ( BIN_DATA_KEY ) ) ; }


Input: Parse an { @link AnalyticsConfiguration } from json . [CODESPLIT] public static AnalyticsConfiguration fromJson ( JSONObject json ) { if ( json == null ) { json = new JSONObject ( ) ; } AnalyticsConfiguration analyticsConfiguration = new AnalyticsConfiguration ( ) ; analyticsConfiguration . mUrl = Json . optString ( json , URL_KEY , null ) ; return analyticsConfiguration ; }


Input: Create a { @link PaymentMethodNonce } in the Braintree Gateway . <p / > On completion returns the { @link PaymentMethodNonce } to { @link PaymentMethodNonceCallback } . <p / > If creation fails validation { @link com . braintreepayments . api . interfaces . BraintreeErrorListener#onError ( Exception ) } will be called with the resulting { @link ErrorWithResponse } . <p / > If an error not due to validation ( server error network issue etc . ) occurs { @link com . braintreepayments . api . interfaces . BraintreeErrorListener#onError ( Exception ) } ( Throwable ) } will be called with the { @link Exception } that occurred . [CODESPLIT] static void tokenize ( final BraintreeFragment fragment , final PaymentMethodBuilder paymentMethodBuilder , final PaymentMethodNonceCallback callback ) { paymentMethodBuilder . setSessionId ( fragment . getSessionId ( ) ) ; fragment . waitForConfiguration ( new ConfigurationListener ( ) { @ Override public void onConfigurationFetched ( Configuration configuration ) { if ( paymentMethodBuilder instanceof CardBuilder && configuration . getGraphQL ( ) . isFeatureEnabled ( Features . TOKENIZE_CREDIT_CARDS ) ) { tokenizeGraphQL ( fragment , ( CardBuilder ) paymentMethodBuilder , callback ) ; } else { tokenizeRest ( fragment , paymentMethodBuilder , callback ) ; } } } ) ; }


Input: Make a HTTP GET request to using the base url and path provided . If the path is a full url it will be used instead of the previously provided base url . [CODESPLIT] public void get ( final String path , final HttpResponseCallback callback ) { if ( path == null ) { postCallbackOnMainThread ( callback , new IllegalArgumentException ( "Path cannot be null" ) ) ; return ; } final String url ; if ( path . startsWith ( "http" ) ) { url = path ; } else { url = mBaseUrl + path ; } mThreadPool . submit ( new Runnable ( ) { @ Override public void run ( ) { HttpURLConnection connection = null ; try { connection = init ( url ) ; connection . setRequestMethod ( METHOD_GET ) ; postCallbackOnMainThread ( callback , parseResponse ( connection ) ) ; } catch ( Exception e ) { postCallbackOnMainThread ( callback , e ) ; } finally { if ( connection != null ) { connection . disconnect ( ) ; } } } } ) ; }


Input: Make a HTTP POST request using the base url and path provided . If the path is a full url it will be used instead of the previously provided url . [CODESPLIT] public void post ( final String path , final String data , final HttpResponseCallback callback ) { if ( path == null ) { postCallbackOnMainThread ( callback , new IllegalArgumentException ( "Path cannot be null" ) ) ; return ; } mThreadPool . submit ( new Runnable ( ) { @ Override public void run ( ) { try { postCallbackOnMainThread ( callback , post ( path , data ) ) ; } catch ( Exception e ) { postCallbackOnMainThread ( callback , e ) ; } } } ) ; }


Input: Performs a synchronous post request . [CODESPLIT] public String post ( String path , String data ) throws Exception { HttpURLConnection connection = null ; try { if ( path . startsWith ( "http" ) ) { connection = init ( path ) ; } else { connection = init ( mBaseUrl + path ) ; } connection . setRequestProperty ( "Content-Type" , "application/json" ) ; connection . setRequestMethod ( METHOD_POST ) ; connection . setDoOutput ( true ) ; writeOutputStream ( connection . getOutputStream ( ) , data ) ; return parseResponse ( connection ) ; } finally { if ( connection != null ) { connection . disconnect ( ) ; } } }


Input: Convert an API response to a { @link VisaCheckoutNonce } . [CODESPLIT] public static VisaCheckoutNonce fromJson ( String json ) throws JSONException { VisaCheckoutNonce visaCheckoutNonce = new VisaCheckoutNonce ( ) ; visaCheckoutNonce . fromJson ( PaymentMethodNonce . getJsonObjectForType ( API_RESOURCE_KEY , new JSONObject ( json ) ) ) ; return visaCheckoutNonce ; }


Input: Prepares the payment flow for a specific type of local payment . [CODESPLIT] public static void startPayment ( final BraintreeFragment fragment , final LocalPaymentRequest request , final BraintreeResponseListener < LocalPaymentRequest > listener ) { if ( request == null ) { fragment . postCallback ( new BraintreeException ( "A LocalPaymentRequest is required." ) ) ; return ; } else if ( request . getApprovalUrl ( ) != null || request . getPaymentId ( ) != null ) { fragment . postCallback ( new BraintreeException ( "LocalPaymentRequest is invalid, " + "appovalUrl and paymentId should not be set." ) ) ; return ; } else if ( request . getPaymentType ( ) == null || request . getAmount ( ) == null ) { fragment . postCallback ( new BraintreeException ( "LocalPaymentRequest is invalid, " + "paymentType and amount are required." ) ) ; return ; } else if ( listener == null ) { fragment . postCallback ( new BraintreeException ( "BraintreeResponseListener<LocalPaymentRequest> " + "is required." ) ) ; return ; } fragment . waitForConfiguration ( new ConfigurationListener ( ) { @ Override public void onConfigurationFetched ( Configuration configuration ) { if ( ! configuration . getPayPal ( ) . isEnabled ( ) ) { fragment . postCallback ( new ConfigurationException ( "Local payments are not enabled for this merchant." ) ) ; return ; } sMerchantAccountId = request . getMerchantAccountId ( ) ; sPaymentType = request . getPaymentType ( ) ; String returnUrl = fragment . getReturnUrlScheme ( ) + "://" + LOCAL_PAYMENT_SUCCESSS ; String cancel = fragment . getReturnUrlScheme ( ) + "://" + LOCAL_PAYMENT_CANCEL ; fragment . sendAnalyticsEvent ( paymentTypeForAnalytics ( ) + ".local-payment.start-payment.selected" ) ; fragment . getHttpClient ( ) . post ( "/v1/paypal_hermes/create_payment_resource" , request . build ( returnUrl , cancel ) , new HttpResponseCallback ( ) { @ Override public void success ( String responseBody ) { try { JSONObject responseJson = new JSONObject ( responseBody ) ; request . approvalUrl ( responseJson . getJSONObject ( "paymentResource" ) . getString ( "redirectUrl" ) ) ; request . paymentId ( responseJson . getJSONObject ( "paymentResource" ) . getString ( "paymentToken" ) ) ; fragment . sendAnalyticsEvent ( paymentTypeForAnalytics ( ) + ".local-payment.create.succeeded" ) ; listener . onResponse ( request ) ; } catch ( JSONException jsonException ) { failure ( jsonException ) ; } } @ Override public void failure ( Exception exception ) { fragment . sendAnalyticsEvent ( paymentTypeForAnalytics ( ) + ".local-payment.webswitch.initiate.failed" ) ; fragment . postCallback ( exception ) ; } } ) ; } } ) ; }


Input: Initiates the browser switch for a payment flow by opening a browser where the customer can authenticate with their bank . [CODESPLIT] public static void approvePayment ( BraintreeFragment fragment , LocalPaymentRequest request ) { fragment . browserSwitch ( BraintreeRequestCodes . LOCAL_PAYMENT , request . getApprovalUrl ( ) ) ; fragment . sendAnalyticsEvent ( paymentTypeForAnalytics ( ) + ".local-payment.webswitch.initiate.succeeded" ) ; }


Input: Returns an { @link Authorization } of the correct type for a given { @link String } . [CODESPLIT] public static Authorization fromString ( @ Nullable String authorizationString ) throws InvalidArgumentException { if ( isTokenizationKey ( authorizationString ) ) { return new TokenizationKey ( authorizationString ) ; } else { return new ClientToken ( authorizationString ) ; } }


Input: Method to extract an error for an individual field e . g . creditCard customer etc . [CODESPLIT] @ Nullable public BraintreeError errorFor ( String field ) { BraintreeError returnError ; if ( mFieldErrors != null ) { for ( BraintreeError error : mFieldErrors ) { if ( error . getField ( ) . equals ( field ) ) { return error ; } else if ( error . getFieldErrors ( ) != null ) { returnError = error . errorFor ( field ) ; if ( returnError != null ) { return returnError ; } } } } return null ; }


Input: Convert an API response to a { @link PayPalAccountNonce } . [CODESPLIT] public static PayPalAccountNonce fromJson ( String jsonString ) throws JSONException { JSONObject jsonObj = new JSONObject ( jsonString ) ; PayPalAccountNonce payPalAccountNonce = new PayPalAccountNonce ( ) ; if ( jsonObj . has ( PayPalAccountNonce . API_RESOURCE_KEY ) ) { payPalAccountNonce . fromJson ( PayPalAccountNonce . getJsonObjectForType ( API_RESOURCE_KEY , jsonObj ) ) ; } else if ( jsonObj . has ( PayPalAccountNonce . PAYMENT_METHOD_DATA_KEY ) ) { JSONObject tokenObj = new JSONObject ( new JSONObject ( jsonString ) . getJSONObject ( PayPalAccountNonce . PAYMENT_METHOD_DATA_KEY ) . getJSONObject ( PayPalAccountNonce . TOKENIZATION_DATA_KEY ) . getString ( PayPalAccountNonce . TOKEN_KEY ) ) ; payPalAccountNonce . fromJson ( PayPalAccountNonce . getJsonObjectForType ( API_RESOURCE_KEY , tokenObj ) ) ; JSONObject shippingAddress = jsonObj . optJSONObject ( SHIPPING_ADDRESS_KEY ) ; if ( shippingAddress != null ) { payPalAccountNonce . mShippingAddress = PostalAddressParser . fromJson ( shippingAddress ) ; } } else { throw new JSONException ( "Could not parse JSON for a payment method nonce" ) ; } return payPalAccountNonce ; }


Input: Generates a { @link PayPalAccountNonce } from the { @link JSONObject } . [CODESPLIT] protected void fromJson ( JSONObject json ) throws JSONException { 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 ) ; try { if ( details . has ( CREDIT_FINANCING_KEY ) ) { JSONObject creditFinancing = details . getJSONObject ( CREDIT_FINANCING_KEY ) ; mCreditFinancing = PayPalCreditFinancing . fromJson ( creditFinancing ) ; } JSONObject payerInfo = details . getJSONObject ( PAYER_INFO_KEY ) ; JSONObject billingAddress = payerInfo . optJSONObject ( BILLING_ADDRESS_KEY ) ; if ( payerInfo . has ( ACCOUNT_ADDRESS_KEY ) ) { billingAddress = payerInfo . optJSONObject ( ACCOUNT_ADDRESS_KEY ) ; } mShippingAddress = PostalAddressParser . fromJson ( payerInfo . optJSONObject ( SHIPPING_ADDRESS_KEY ) ) ; mBillingAddress = PostalAddressParser . fromJson ( billingAddress ) ; mFirstName = Json . optString ( payerInfo , FIRST_NAME_KEY , "" ) ; mLastName = 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 ( ) ; } }


Input: Create a new instance of { @link BraintreeFragment } using the client token and add it to the { @link AppCompatActivity } s { @link FragmentManager } . [CODESPLIT] public static BraintreeFragment newInstance ( AppCompatActivity activity , String authorization ) throws InvalidArgumentException { if ( activity == null ) { throw new InvalidArgumentException ( "Activity is null" ) ; } FragmentManager fm = activity . getSupportFragmentManager ( ) ; BraintreeFragment braintreeFragment = ( BraintreeFragment ) fm . findFragmentByTag ( TAG ) ; if ( braintreeFragment == null ) { braintreeFragment = new BraintreeFragment ( ) ; Bundle bundle = new Bundle ( ) ; try { Authorization auth = Authorization . fromString ( authorization ) ; bundle . putParcelable ( EXTRA_AUTHORIZATION_TOKEN , auth ) ; } catch ( InvalidArgumentException e ) { throw new InvalidArgumentException ( "Tokenization Key or client token was invalid." ) ; } bundle . putString ( EXTRA_SESSION_ID , UUIDHelper . getFormattedUUID ( ) ) ; bundle . putString ( EXTRA_INTEGRATION_TYPE , IntegrationType . get ( activity ) ) ; braintreeFragment . setArguments ( bundle ) ; try { if ( VERSION . SDK_INT >= VERSION_CODES . N ) { try { fm . beginTransaction ( ) . add ( braintreeFragment , TAG ) . commitNow ( ) ; } catch ( IllegalStateException | NullPointerException e ) { fm . beginTransaction ( ) . add ( braintreeFragment , TAG ) . commit ( ) ; try { fm . executePendingTransactions ( ) ; } catch ( IllegalStateException ignored ) { } } } else { fm . beginTransaction ( ) . add ( braintreeFragment , TAG ) . commit ( ) ; try { fm . executePendingTransactions ( ) ; } catch ( IllegalStateException ignored ) { } } } catch ( IllegalStateException e ) { throw new InvalidArgumentException ( e . getMessage ( ) ) ; } } braintreeFragment . mContext = activity . getApplicationContext ( ) ; return braintreeFragment ; }


Input: Adds a listener . [CODESPLIT] public < T extends BraintreeListener > void addListener ( T listener ) { if ( listener instanceof ConfigurationListener ) { mConfigurationListener = ( ConfigurationListener ) listener ; } if ( listener instanceof BraintreeCancelListener ) { mCancelListener = ( BraintreeCancelListener ) listener ; } if ( listener instanceof PaymentMethodNoncesUpdatedListener ) { mPaymentMethodNoncesUpdatedListener = ( PaymentMethodNoncesUpdatedListener ) listener ; } if ( listener instanceof PaymentMethodNonceCreatedListener ) { mPaymentMethodNonceCreatedListener = ( PaymentMethodNonceCreatedListener ) listener ; } if ( listener instanceof PaymentMethodNonceDeletedListener ) { mPaymentMethodNonceDeletedListener = ( PaymentMethodNonceDeletedListener ) listener ; } if ( listener instanceof BraintreePaymentResultListener ) { mBraintreePaymentResultListener = ( BraintreePaymentResultListener ) listener ; } if ( listener instanceof BraintreeErrorListener ) { mErrorListener = ( BraintreeErrorListener ) listener ; } if ( listener instanceof UnionPayListener ) { mUnionPayListener = ( UnionPayListener ) listener ; } if ( listener instanceof AmericanExpressListener ) { mAmericanExpressListener = ( AmericanExpressListener ) listener ; } flushCallbacks ( ) ; }


Input: Removes a previously added listener . [CODESPLIT] public < T extends BraintreeListener > void removeListener ( T listener ) { if ( listener instanceof ConfigurationListener ) { mConfigurationListener = null ; } if ( listener instanceof BraintreeCancelListener ) { mCancelListener = null ; } if ( listener instanceof PaymentMethodNoncesUpdatedListener ) { mPaymentMethodNoncesUpdatedListener = null ; } if ( listener instanceof PaymentMethodNonceCreatedListener ) { mPaymentMethodNonceCreatedListener = null ; } if ( listener instanceof PaymentMethodNonceDeletedListener ) { mPaymentMethodNonceDeletedListener = null ; } if ( listener instanceof BraintreePaymentResultListener ) { mBraintreePaymentResultListener = null ; } if ( listener instanceof BraintreeErrorListener ) { mErrorListener = null ; } if ( listener instanceof UnionPayListener ) { mUnionPayListener = null ; } if ( listener instanceof AmericanExpressListener ) { mAmericanExpressListener = null ; } }


Input: Obtain an instance of a { @link GoogleApiClient } that is connected or connecting to be used for Android Pay . This instance will be automatically disconnected in { @link BraintreeFragment#onStop () } and automatically connected in { @link BraintreeFragment#onResume () } . <p / > Connection failed and connection suspended errors will be sent to { @link BraintreeErrorListener#onError ( Exception ) } . [CODESPLIT] public void getGoogleApiClient ( final BraintreeResponseListener < GoogleApiClient > listener ) { waitForConfiguration ( new ConfigurationListener ( ) { @ Override public void onConfigurationFetched ( Configuration configuration ) { GoogleApiClient googleApiClient = getGoogleApiClient ( ) ; if ( googleApiClient != null ) { listener . onResponse ( googleApiClient ) ; } } } ) ; }


Input: Parse an { @link GooglePaymentConfiguration } from json . [CODESPLIT] public static GooglePaymentConfiguration fromJson ( JSONObject json ) { if ( json == null ) { json = new JSONObject ( ) ; } GooglePaymentConfiguration googlePaymentConfiguration = new GooglePaymentConfiguration ( ) ; googlePaymentConfiguration . mEnabled = json . optBoolean ( ENABLED_KEY , false ) ; googlePaymentConfiguration . mGoogleAuthorizationFingerprint = Json . optString ( json , GOOGLE_AUTHORIZATION_FINGERPRINT_KEY , null ) ; googlePaymentConfiguration . mEnvironment = Json . optString ( json , ENVIRONMENT_KEY , null ) ; googlePaymentConfiguration . mDisplayName = Json . optString ( json , DISPLAY_NAME_KEY , "" ) ; JSONArray supportedNetworks = json . optJSONArray ( SUPPORTED_NETWORKS_KEY ) ; if ( supportedNetworks != null ) { googlePaymentConfiguration . mSupportedNetworks = new String [ supportedNetworks . length ( ) ] ; for ( int i = 0 ; i < supportedNetworks . length ( ) ; i ++ ) { try { googlePaymentConfiguration . mSupportedNetworks [ i ] = supportedNetworks . getString ( i ) ; } catch ( JSONException ignored ) { } } } else { googlePaymentConfiguration . mSupportedNetworks = new String [ 0 ] ; } return googlePaymentConfiguration ; }


Input: Starts the Billing Agreement flow for PayPal with custom PayPal approval handler . [CODESPLIT] public static void requestBillingAgreement ( BraintreeFragment fragment , PayPalRequest request , PayPalApprovalHandler handler ) { if ( request . getAmount ( ) == null ) { fragment . sendAnalyticsEvent ( "paypal.billing-agreement.selected" ) ; if ( request . shouldOfferCredit ( ) ) { fragment . sendAnalyticsEvent ( "paypal.billing-agreement.credit.offered" ) ; } requestOneTimePayment ( fragment , request , true , handler ) ; } else { fragment . postCallback ( new BraintreeException ( "There must be no amount specified for the Billing Agreement flow" ) ) ; } }


Input: Create a PayPalPaymentResource on behalf of the merchant . To be used in the PayPal Checkout flows for Single Payment and Billing Agreement . [CODESPLIT] private static void createPaymentResource ( BraintreeFragment fragment , PayPalRequest request , boolean isBillingAgreement , HttpResponseCallback callback ) throws JSONException , ErrorWithResponse , BraintreeException { String currencyCode = request . getCurrencyCode ( ) ; if ( currencyCode == null ) { currencyCode = fragment . getConfiguration ( ) . getPayPal ( ) . getCurrencyIsoCode ( ) ; } CheckoutRequest checkoutRequest = getCheckoutRequest ( fragment , null ) ; JSONObject parameters = new JSONObject ( ) . put ( RETURN_URL_KEY , checkoutRequest . getSuccessUrl ( ) ) . put ( CANCEL_URL_KEY , checkoutRequest . getCancelUrl ( ) ) . put ( OFFER_CREDIT_KEY , request . shouldOfferCredit ( ) ) ; if ( fragment . getAuthorization ( ) instanceof ClientToken ) { parameters . put ( AUTHORIZATION_FINGERPRINT_KEY , fragment . getAuthorization ( ) . getBearer ( ) ) ; } else { parameters . put ( TOKENIZATION_KEY , fragment . getAuthorization ( ) . getBearer ( ) ) ; } if ( ! isBillingAgreement ) { parameters . put ( AMOUNT_KEY , request . getAmount ( ) ) . put ( CURRENCY_ISO_CODE_KEY , currencyCode ) . put ( INTENT_KEY , request . getIntent ( ) ) ; } else { if ( ! TextUtils . isEmpty ( request . getBillingAgreementDescription ( ) ) ) { parameters . put ( DESCRIPTION_KEY , request . getBillingAgreementDescription ( ) ) ; } } JSONObject experienceProfile = new JSONObject ( ) ; experienceProfile . put ( NO_SHIPPING_KEY , ! request . isShippingAddressRequired ( ) ) ; experienceProfile . put ( LANDING_PAGE_TYPE_KEY , request . getLandingPageType ( ) ) ; String displayName = request . getDisplayName ( ) ; if ( TextUtils . isEmpty ( displayName ) ) { displayName = fragment . getConfiguration ( ) . getPayPal ( ) . getDisplayName ( ) ; } experienceProfile . put ( DISPLAY_NAME_KEY , displayName ) ; if ( request . getLocaleCode ( ) != null ) { experienceProfile . put ( LOCALE_CODE_KEY , request . getLocaleCode ( ) ) ; } if ( request . getShippingAddressOverride ( ) != null ) { experienceProfile . put ( ADDRESS_OVERRIDE_KEY , ! request . isShippingAddressEditable ( ) ) ; JSONObject shippingAddressJson ; if ( isBillingAgreement ) { shippingAddressJson = new JSONObject ( ) ; parameters . put ( SHIPPING_ADDRESS_KEY , shippingAddressJson ) ; } else { shippingAddressJson = parameters ; } PostalAddress shippingAddress = request . getShippingAddressOverride ( ) ; shippingAddressJson . put ( PostalAddressParser . LINE_1_KEY , shippingAddress . getStreetAddress ( ) ) ; shippingAddressJson . put ( PostalAddressParser . LINE_2_KEY , shippingAddress . getExtendedAddress ( ) ) ; shippingAddressJson . put ( PostalAddressParser . LOCALITY_KEY , shippingAddress . getLocality ( ) ) ; shippingAddressJson . put ( PostalAddressParser . REGION_KEY , shippingAddress . getRegion ( ) ) ; shippingAddressJson . put ( PostalAddressParser . POSTAL_CODE_UNDERSCORE_KEY , shippingAddress . getPostalCode ( ) ) ; shippingAddressJson . put ( PostalAddressParser . COUNTRY_CODE_UNDERSCORE_KEY , shippingAddress . getCountryCodeAlpha2 ( ) ) ; shippingAddressJson . put ( PostalAddressParser . RECIPIENT_NAME_UNDERSCORE_KEY , shippingAddress . getRecipientName ( ) ) ; } else { experienceProfile . put ( ADDRESS_OVERRIDE_KEY , false ) ; } if ( request . getMerchantAccountId ( ) != null ) { parameters . put ( MERCHANT_ACCOUNT_ID , request . getMerchantAccountId ( ) ) ; } parameters . put ( EXPERIENCE_PROFILE_KEY , experienceProfile ) ; String apiUrl = isBillingAgreement ? SETUP_BILLING_AGREEMENT_ENDPOINT : CREATE_SINGLE_PAYMENT_ENDPOINT ; String versionedPath = "/v1/" + apiUrl ; fragment . getHttpClient ( ) . post ( versionedPath , parameters . toString ( ) , callback ) ; }


Input: The result from PayPal s request . [CODESPLIT] protected static void onActivityResult ( final BraintreeFragment fragment , int resultCode , Intent data ) { Request request = getPersistedRequest ( fragment . getApplicationContext ( ) ) ; String paymentType = paymentTypeForRequest ( request ) ; String switchType = switchTypeForIntent ( data ) ; String eventPrefix = paymentType + "." + switchType ; if ( resultCode == AppCompatActivity . RESULT_OK && data != null && request != null ) { Result result = PayPalOneTouchCore . parseResponse ( fragment . getApplicationContext ( ) , request , data ) ; switch ( result . getResultType ( ) ) { case Error : fragment . postCallback ( new BrowserSwitchException ( result . getError ( ) . getMessage ( ) ) ) ; fragment . sendAnalyticsEvent ( eventPrefix + ".failed" ) ; break ; case Cancel : fragment . postCancelCallback ( BraintreeRequestCodes . PAYPAL ) ; fragment . sendAnalyticsEvent ( eventPrefix + ".canceled" ) ; break ; case Success : onSuccess ( fragment , data , request , result ) ; fragment . sendAnalyticsEvent ( eventPrefix + ".succeeded" ) ; break ; } } else { fragment . sendAnalyticsEvent ( eventPrefix + ".canceled" ) ; if ( resultCode != AppCompatActivity . RESULT_CANCELED ) { fragment . postCancelCallback ( BraintreeRequestCodes . PAYPAL ) ; } } }


Input: Parse the PayPal response URL using OneTouchCore . [CODESPLIT] private static PayPalAccountBuilder parseResponse ( PayPalRequest paypalRequest , Request request , Result result , Intent intent ) { PayPalAccountBuilder paypalAccountBuilder = new PayPalAccountBuilder ( ) . clientMetadataId ( request . getClientMetadataId ( ) ) ; if ( paypalRequest != null && paypalRequest . getMerchantAccountId ( ) != null ) { paypalAccountBuilder . merchantAccountId ( paypalRequest . getMerchantAccountId ( ) ) ; } if ( request instanceof CheckoutRequest && paypalRequest != null ) { paypalAccountBuilder . intent ( paypalRequest . getIntent ( ) ) ; } if ( isAppSwitch ( intent ) ) { paypalAccountBuilder . source ( "paypal-app" ) ; } else { paypalAccountBuilder . source ( "paypal-browser" ) ; } paypalAccountBuilder . oneTouchCoreData ( result . getResponse ( ) ) ; return paypalAccountBuilder ; }


Input: Used to parse a response from the Braintree Gateway to be used for 3D Secure . [CODESPLIT] public static ThreeDSecureLookup fromJson ( String jsonString ) throws JSONException { JSONObject json = new JSONObject ( jsonString ) ; ThreeDSecureLookup lookup = new ThreeDSecureLookup ( ) ; CardNonce cardNonce = new CardNonce ( ) ; cardNonce . fromJson ( json . getJSONObject ( CARD_NONCE_KEY ) ) ; lookup . mCardNonce = cardNonce ; JSONObject lookupJson = json . getJSONObject ( LOOKUP_KEY ) ; if ( lookupJson . isNull ( ACS_URL_KEY ) ) { lookup . mAcsUrl = null ; } else { lookup . mAcsUrl = lookupJson . getString ( ACS_URL_KEY ) ; } lookup . mMd = lookupJson . getString ( MD_KEY ) ; lookup . mTermUrl = lookupJson . getString ( TERM_URL_KEY ) ; lookup . mPareq = lookupJson . getString ( PA_REQ_KEY ) ; return lookup ; }


Input: Parse an { @link PayPalConfiguration } from json . [CODESPLIT] public static PayPalConfiguration fromJson ( JSONObject json ) { if ( json == null ) { json = new JSONObject ( ) ; } PayPalConfiguration payPalConfiguration = new PayPalConfiguration ( ) ; payPalConfiguration . mDisplayName = Json . optString ( json , DISPLAY_NAME_KEY , null ) ; payPalConfiguration . mClientId = Json . optString ( json , CLIENT_ID_KEY , null ) ; payPalConfiguration . mPrivacyUrl = Json . optString ( json , PRIVACY_URL_KEY , null ) ; payPalConfiguration . mUserAgreementUrl = Json . optString ( json , USER_AGREEMENT_URL_KEY , null ) ; payPalConfiguration . mDirectBaseUrl = Json . optString ( json , DIRECT_BASE_URL_KEY , null ) ; payPalConfiguration . mEnvironment = Json . optString ( json , ENVIRONMENT_KEY , null ) ; payPalConfiguration . mTouchDisabled = json . optBoolean ( TOUCH_DISABLED_KEY , true ) ; payPalConfiguration . mCurrencyIsoCode = Json . optString ( json , CURRENCY_ISO_CODE_KEY , null ) ; return payPalConfiguration ; }


Input: Add user - defined words to the noun dictionary . Spaced words are ignored . [CODESPLIT] public static void addNounsToDictionary ( List < String > words ) { OpenKoreanTextProcessor . addNounsToDictionary ( JavaConverters . asScalaBufferConverter ( words ) . asScala ( ) ) ; }