_id
stringlengths
2
7
title
stringlengths
3
140
partition
stringclasses
3 values
text
stringlengths
73
34.1k
language
stringclasses
1 value
meta_information
dict
q173600
KubernetesHelper.getCurrentContext
test
private static Context getCurrentContext(Config config) { String contextName = config.getCurrentContext(); if (contextName != null) { List<NamedContext> contexts = config.getContexts(); if (contexts != null) { for (NamedContext context : contexts) { if (Objects.equals(contextName, context.getName())) { return context.getContext(); } } } } return null; }
java
{ "resource": "" }
q173601
RouteEnricher.hasRoute
test
private boolean hasRoute(final KubernetesListBuilder listBuilder, final String name) { final AtomicBoolean answer = new AtomicBoolean(false); listBuilder.accept(new TypedVisitor<RouteBuilder>() { @Override public void visit(RouteBuilder builder) { ObjectMeta metadata = builder.getMetadata(); if (metadata != null && name.equals(metadata.getName())) { answer.set(true); } } }); return answer.get(); }
java
{ "resource": "" }
q173602
MavenUtil.hasResource
test
public static boolean hasResource(MavenProject project, String... paths) { URLClassLoader compileClassLoader = getCompileClassLoader(project); for (String path : paths) { try { if (compileClassLoader.getResource(path) != null) { return true; } } catch (Throwable e) { // ignore } } return false; }
java
{ "resource": "" }
q173603
KubernetesResourceUtil.readAndEnrichFragment
test
private static Map<String, Object> readAndEnrichFragment(PlatformMode platformMode, ResourceVersioning apiVersions, File file, String appName) throws IOException { Pattern pattern = Pattern.compile(FILENAME_PATTERN, Pattern.CASE_INSENSITIVE); Matcher matcher = pattern.matcher(file.getName()); if (!matcher.matches()) { throw new IllegalArgumentException( String.format("Resource file name '%s' does not match pattern <name>-<type>.(yaml|yml|json)", file.getName())); } String name = matcher.group("name"); String type = matcher.group("type"); String ext = matcher.group("ext").toLowerCase(); String kind; Map<String,Object> fragment = readFragment(file, ext); if (type != null) { kind = getAndValidateKindFromType(file, type); } else { // Try name as type kind = FILENAME_TO_KIND_MAPPER.get(name.toLowerCase()); if (kind != null) { // Name is in fact the type, so lets erase the name. name = null; } } addKind(fragment, kind, file.getName()); String apiVersion = apiVersions.getCoreVersion(); if (Objects.equals(kind, "Ingress")) { apiVersion = apiVersions.getExtensionsVersion(); } else if (Objects.equals(kind, "StatefulSet") || Objects.equals(kind, "Deployment")) { apiVersion = apiVersions.getAppsVersion(); } else if (Objects.equals(kind, "Job")) { apiVersion = apiVersions.getJobVersion(); } else if (Objects.equals(kind, "DeploymentConfig") && platformMode == PlatformMode.openshift) { apiVersion = apiVersions.getOpenshiftV1version(); } addIfNotExistent(fragment, "apiVersion", apiVersion); Map<String, Object> metaMap = getMetadata(fragment); // No name means: generated app name should be taken as resource name addIfNotExistent(metaMap, "name", StringUtils.isNotBlank(name) ? name : appName); return fragment; }
java
{ "resource": "" }
q173604
KubernetesResourceUtil.convertToEnvVarList
test
public static List<EnvVar> convertToEnvVarList(Map<String, String> envVars) { List<EnvVar> envList = new LinkedList<>(); for (Map.Entry<String, String> entry : envVars.entrySet()) { String name = entry.getKey(); String value = entry.getValue(); if (name != null) { EnvVar env = new EnvVarBuilder().withName(name).withValue(value).build(); envList.add(env); } } return envList; }
java
{ "resource": "" }
q173605
KubernetesResourceUtil.mergeResources
test
public static HasMetadata mergeResources(HasMetadata item1, HasMetadata item2, Logger log, boolean switchOnLocalCustomisation) { if (item1 instanceof Deployment && item2 instanceof Deployment) { return mergeDeployments((Deployment) item1, (Deployment) item2, log, switchOnLocalCustomisation); } if (item1 instanceof ConfigMap && item2 instanceof ConfigMap) { ConfigMap cm1 = (ConfigMap) item1; ConfigMap cm2 = (ConfigMap) item2; return mergeConfigMaps(cm1, cm2, log, switchOnLocalCustomisation); } mergeMetadata(item1, item2); return item1; }
java
{ "resource": "" }
q173606
KubernetesResourceUtil.mergeMapsAndRemoveEmptyStrings
test
private static Map<String, String> mergeMapsAndRemoveEmptyStrings(Map<String, String> overrideMap, Map<String, String> originalMap) { Map<String, String> answer = MapUtil.mergeMaps(overrideMap, originalMap); Set<Map.Entry<String, String>> entries = overrideMap.entrySet(); for (Map.Entry<String, String> entry : entries) { String value = entry.getValue(); if (value == null || value.isEmpty()) { String key = entry.getKey(); answer.remove(key); } } return answer; }
java
{ "resource": "" }
q173607
KubernetesResourceUtil.isLocalCustomisation
test
private static boolean isLocalCustomisation(PodSpec podSpec) { List<Container> containers = podSpec.getContainers() != null ? podSpec.getContainers() : Collections.<Container>emptyList(); for (Container container : containers) { if (StringUtils.isNotBlank(container.getImage())) { return false; } } return true; }
java
{ "resource": "" }
q173608
AbstractPortsExtractor.readConfig
test
private Map<String, String> readConfig(File f) throws IOException { Map<String, String> map; if (f.getName().endsWith(JSON_EXTENSION)) { map = flatten(JSON_MAPPER.readValue(f, Map.class)); } else if (f.getName().endsWith(YAML_EXTENSION) || f.getName().endsWith(YML_EXTENSION)) { map = flatten(YAML_MAPPER.readValue(f, Map.class)); } else if (f.getName().endsWith(PROPERTIES_EXTENSION)) { Properties properties = new Properties(); properties.load(new FileInputStream(f)); map = propertiesToMap(properties); } else { throw new IllegalArgumentException("Can't read configuration from: [" + f.getName() + "]. Unknown file extension."); } return map; }
java
{ "resource": "" }
q173609
AbstractPortsExtractor.addPortIfValid
test
private void addPortIfValid(Map<String, Integer> map, String key, String port) { if (StringUtils.isNotBlank(port)) { String t = port.trim(); if (t.matches(NUMBER_REGEX)) { map.put(key, Integer.parseInt(t)); } } }
java
{ "resource": "" }
q173610
MavenEnricherContext.getDockerJsonConfigString
test
public String getDockerJsonConfigString(final Settings settings, final String serverId) { Server server = getServer(settings, serverId); if (server == null) { return ""; } JsonObject auth = new JsonObject(); auth.add("username", new JsonPrimitive(server.getUsername())); auth.add("password", new JsonPrimitive(server.getPassword())); String mail = getConfigurationValue(server, "email"); if (!StringUtils.isBlank(mail)) { auth.add("email", new JsonPrimitive(mail)); } JsonObject json = new JsonObject(); json.add(serverId, auth); return json.toString(); }
java
{ "resource": "" }
q173611
Configuration.getPluginConfiguration
test
public Optional<Map<String, Object>> getPluginConfiguration(String system, String id) { return pluginConfigLookup.apply(system, id); }
java
{ "resource": "" }
q173612
Configuration.getSecretConfiguration
test
public Optional<Map<String, Object>> getSecretConfiguration(String id) { return secretConfigLookup.apply(id); }
java
{ "resource": "" }
q173613
IoUtil.download
test
public static void download(Logger log, URL downloadUrl, File target) throws MojoExecutionException { log.progressStart(); try { OkHttpClient client = new OkHttpClient.Builder() .readTimeout(30, TimeUnit.MINUTES).build(); Request request = new Request.Builder() .url(downloadUrl) .build(); Response response = client.newCall(request).execute(); try (OutputStream out = new FileOutputStream(target); InputStream im = response.body().byteStream()) { long length = response.body().contentLength(); InputStream in = response.body().byteStream(); byte[] buffer = new byte[8192]; long readBytes = 0; while (true) { int len = in.read(buffer); readBytes += len; log.progressUpdate(target.getName(), "Downloading", getProgressBar(readBytes, length)); if (len <= 0) { out.flush(); break; } out.write(buffer, 0, len); } } } catch (IOException e) { throw new MojoExecutionException("Failed to download URL " + downloadUrl + " to " + target + ": " + e, e); } finally { log.progressFinished(); } }
java
{ "resource": "" }
q173614
VersionUtil.compareVersions
test
public static int compareVersions(String v1, String v2) { String[] components1 = split(v1); String[] components2 = split(v2); int diff; int length = Math.min(components1.length, components2.length); for (int i = 0; i < length; i++) { String s1 = components1[i]; String s2 = components2[i]; Integer i1 = tryParseInteger(s1); Integer i2 = tryParseInteger(s2); if (i1 != null && i2 != null) { diff = i1.compareTo(i2); } else { // lets assume strings instead diff = s1.compareTo(s2); } if (diff != 0) { return diff; } } diff = Integer.compare(components1.length, components2.length); if (diff == 0) { if (v1 == v2) { return 0; } /* if v1 == null then v2 can't be null here (see 'if' above). So for v1 == null its always smaller than v2 */; return v1 != null ? v1.compareTo(v2) : -1; } return diff; }
java
{ "resource": "" }
q173615
ProfileUtil.blendProfileWithConfiguration
test
public static ProcessorConfig blendProfileWithConfiguration(ProcessorConfigurationExtractor configExtractor, String profile, File resourceDir, ProcessorConfig config) throws IOException { // Get specified profile or the default profile ProcessorConfig profileConfig = extractProcesssorConfiguration(configExtractor, profile, resourceDir); return ProcessorConfig.mergeProcessorConfigs(config, profileConfig); }
java
{ "resource": "" }
q173616
ProfileUtil.lookup
test
public static Profile lookup(String name, File directory) throws IOException { // First check from the classpath, these profiles are used as a basis List<Profile> profiles = readProfileFromClasspath(name); File profileFile = findProfileYaml(directory); if (profileFile != null) { List<Profile> fileProfiles = fromYaml(new FileInputStream(profileFile)); for (Profile profile : fileProfiles) { if (profile.getName().equals(name)) { profiles.add(profile); break; } } } // "larger" orders are "earlier" in the list Collections.sort(profiles, Collections.<Profile>reverseOrder()); return mergeProfiles(profiles); }
java
{ "resource": "" }
q173617
ProfileUtil.readProfileFromClasspath
test
private static List<Profile> readProfileFromClasspath(String name) throws IOException { List<Profile> ret = new ArrayList<>(); ret.addAll(readAllFromClasspath(name, "default")); ret.addAll(readAllFromClasspath(name, "")); return ret; }
java
{ "resource": "" }
q173618
ProfileUtil.readAllFromClasspath
test
public static List<Profile> readAllFromClasspath(String name, String ext) throws IOException { List<Profile > ret = new ArrayList<>(); for (String location : getMetaInfProfilePaths(ext)) { for (String url : ClassUtil.getResources(location)) { for (Profile profile : fromYaml(new URL(url).openStream())) { if (name.equals(profile.getName())) { ret.add(profile); } } } } return ret; }
java
{ "resource": "" }
q173619
ProfileUtil.findProfileYaml
test
private static File findProfileYaml(File directory) { for (String profileFile : PROFILE_FILENAMES) { File ret = new File(directory, String.format(profileFile, "")); if (ret.exists()) { return ret; } } return null; }
java
{ "resource": "" }
q173620
ProfileUtil.getMetaInfProfilePaths
test
private static List<String> getMetaInfProfilePaths(String ext) { List<String> ret = new ArrayList<>(PROFILE_FILENAMES.length); for (String p : PROFILE_FILENAMES) { ret.add("META-INF/fabric8/" + getProfileFileName(p,ext)); } return ret; }
java
{ "resource": "" }
q173621
ProfileUtil.fromYaml
test
public static List<Profile> fromYaml(InputStream is) throws IOException { TypeReference<List<Profile>> typeRef = new TypeReference<List<Profile>>() {}; return mapper.readValue(is, typeRef); }
java
{ "resource": "" }
q173622
DefaultControllerEnricher.getImagePullPolicy
test
private String getImagePullPolicy(ResourceConfig resourceConfig, String defaultValue) { if(resourceConfig != null) { return resourceConfig.getImagePullPolicy() != null ? resourceConfig.getImagePullPolicy() : defaultValue; } return defaultValue; }
java
{ "resource": "" }
q173623
BaseEnricher.isOpenShiftMode
test
protected boolean isOpenShiftMode() { Properties properties = getContext().getConfiguration().getProperties(); if (properties != null) { return RuntimeMode.isOpenShiftMode(properties); } return false; }
java
{ "resource": "" }
q173624
BaseEnricher.getReplicaCount
test
protected int getReplicaCount(KubernetesListBuilder builder, ResourceConfig xmlResourceConfig, int defaultValue) { if (xmlResourceConfig != null) { List<HasMetadata> items = builder.buildItems(); for (HasMetadata item : items) { if (item instanceof Deployment) { if(((Deployment)item).getSpec().getReplicas() != null) { return ((Deployment)item).getSpec().getReplicas(); } } if (item instanceof DeploymentConfig) { if(((DeploymentConfig)item).getSpec().getReplicas() != null) { return ((DeploymentConfig)item).getSpec().getReplicas(); } } } return xmlResourceConfig.getReplicas() > 0 ? xmlResourceConfig.getReplicas() : defaultValue; } return defaultValue; }
java
{ "resource": "" }
q173625
XmlUtils.firstChild
test
public static Element firstChild(Element element, String name) { NodeList nodes = element.getChildNodes(); if (nodes != null) { for (int i = 0, size = nodes.getLength(); i < size; i++) { Node item = nodes.item(i); if (item instanceof Element) { Element childElement = (Element) item; if (name.equals(childElement.getTagName())) { return childElement; } } } } return null; }
java
{ "resource": "" }
q173626
ApplyService.installTemplate
test
public void installTemplate(Template entity, String sourceName) { OpenShiftClient openShiftClient = getOpenShiftClient(); if (openShiftClient == null) { // lets not install the template on Kubernetes! return; } if (!isProcessTemplatesLocally()) { String namespace = getNamespace(); String id = getName(entity); Objects.requireNonNull(id, "No name for " + entity + " " + sourceName); Template old = openShiftClient.templates().inNamespace(namespace).withName(id).get(); if (isRunning(old)) { if (UserConfigurationCompare.configEqual(entity, old)) { log.info("Template has not changed so not doing anything"); } else { boolean recreateMode = isRecreateMode(); // TODO seems you can't update templates right now recreateMode = true; if (recreateMode) { openShiftClient.templates().inNamespace(namespace).withName(id).delete(); doCreateTemplate(entity, namespace, sourceName); } else { log.info("Updating a Template from " + sourceName); try { Object answer = openShiftClient.templates().inNamespace(namespace).withName(id).replace(entity); log.info("Updated Template: " + answer); } catch (Exception e) { onApplyError("Failed to update Template from " + sourceName + ". " + e + ". " + entity, e); } } } } else { if (!isAllowCreate()) { log.warn("Creation disabled so not creating a Template from " + sourceName + " namespace " + namespace + " name " + getName(entity)); } else { doCreateTemplate(entity, namespace, sourceName); } } } }
java
{ "resource": "" }
q173627
ApplyService.removeTagByName
test
private int removeTagByName(List<TagReference> tags, String tagName) { List<TagReference> removeTags = new ArrayList<>(); for (TagReference tag : tags) { if (Objects.equals(tagName, tag.getName())) { removeTags.add(tag); } } tags.removeAll(removeTags); return removeTags.size(); }
java
{ "resource": "" }
q173628
ApplyService.applyNamespace
test
public boolean applyNamespace(Namespace entity) { String namespace = getOrCreateMetadata(entity).getName(); log.info("Using namespace: " + namespace); String name = getName(entity); Objects.requireNonNull(name, "No name for " + entity ); Namespace old = kubernetesClient.namespaces().withName(name).get(); if (!isRunning(old)) { try { Object answer = kubernetesClient.namespaces().create(entity); logGeneratedEntity("Created namespace: ", namespace, entity, answer); return true; } catch (Exception e) { onApplyError("Failed to create namespace: " + name + " due " + e.getMessage(), e); } } return false; }
java
{ "resource": "" }
q173629
ApplyService.applyProject
test
public boolean applyProject(Project project) { return applyProjectRequest(new ProjectRequestBuilder() .withDisplayName(project.getMetadata().getName()) .withMetadata(project.getMetadata()).build()); }
java
{ "resource": "" }
q173630
ApplyService.applyProjectRequest
test
public boolean applyProjectRequest(ProjectRequest entity) { String namespace = getOrCreateMetadata(entity).getName(); log.info("Using project: " + namespace); String name = getName(entity); Objects.requireNonNull(name, "No name for " + entity); OpenShiftClient openshiftClient = getOpenShiftClient(); if (openshiftClient == null) { log.warn("Cannot check for Project " + namespace + " as not running against OpenShift!"); return false; } boolean exists = checkNamespace(name); // We may want to be more fine-grained on the phase of the project if (!exists) { try { Object answer = openshiftClient.projectrequests().create(entity); logGeneratedEntity("Created ProjectRequest: ", namespace, entity, answer); return true; } catch (Exception e) { onApplyError("Failed to create ProjectRequest: " + name + " due " + e.getMessage(), e); } } return false; }
java
{ "resource": "" }
q173631
ApplyService.getNamespace
test
protected String getNamespace(HasMetadata entity) { String answer = KubernetesHelper.getNamespace(entity); if (StringUtils.isBlank(answer)) { answer = getNamespace(); } // lest make sure the namespace exists applyNamespace(answer); return answer; }
java
{ "resource": "" }
q173632
ApplyService.onApplyError
test
protected void onApplyError(String message, Exception e) { log.error(message, e); throw new RuntimeException(message, e); }
java
{ "resource": "" }
q173633
DefaultNamespaceEnricher.create
test
@Override public void create(PlatformMode platformMode, KubernetesListBuilder builder) { final String name = config.getNamespace(); if (name == null || name.isEmpty()) { return; } if (!KubernetesResourceUtil.checkForKind(builder, NAMESPACE_KINDS)) { String type = getConfig(Config.type); if ("project".equalsIgnoreCase(type) || "namespace".equalsIgnoreCase(type)) { if (platformMode == PlatformMode.kubernetes) { log.info("Adding a default Namespace:" + config.getNamespace()); Namespace namespace = handlerHub.getNamespaceHandler().getNamespace(config.getNamespace()); builder.addToNamespaceItems(namespace); } else { log.info("Adding a default Project" + config.getNamespace()); Project project = handlerHub.getProjectHandler().getProject(config.getNamespace()); builder.addToProjectItems(project); } } } }
java
{ "resource": "" }
q173634
DefaultNamespaceEnricher.enrich
test
@Override public void enrich(PlatformMode platformMode, KubernetesListBuilder builder) { builder.accept(new TypedVisitor<ObjectMetaBuilder>() { private String getNamespaceName() { String name = null; if (config.getNamespace() != null && !config.getNamespace().isEmpty()) { name = config.getNamespace(); } name = builder.getItems().stream() .filter(item -> Arrays.asList(NAMESPACE_KINDS).contains(item.getKind())) .findFirst().get().getMetadata().getName(); return name; } @Override public void visit(ObjectMetaBuilder metaBuilder) { if (!KubernetesResourceUtil.checkForKind(builder, NAMESPACE_KINDS)) { return; } String name = getNamespaceName(); if (name == null || name.isEmpty()) { return; } metaBuilder.withNamespace(name).build(); } }); // Removing namespace annotation from the namespace and project objects being generated. // to avoid unncessary trouble while applying these resources. builder.accept(new TypedVisitor<NamespaceBuilder>() { @Override public void visit(NamespaceBuilder builder) { builder.withNewStatus("active").editMetadata().withNamespace(null).endMetadata().build(); } }); builder.accept(new TypedVisitor<ProjectBuilder>() { @Override public void visit(ProjectBuilder builder) { builder.withNewStatus("active").editMetadata().withNamespace(null).endMetadata().build(); } }); }
java
{ "resource": "" }
q173635
JavaExecGenerator.getEnv
test
protected Map<String, String> getEnv(boolean prePackagePhase) throws MojoExecutionException { Map<String, String> ret = new HashMap<>(); if (!isFatJar()) { String mainClass = getConfig(Config.mainClass); if (mainClass == null) { mainClass = mainClassDetector.getMainClass(); if (mainClass == null) { if (!prePackagePhase) { throw new MojoExecutionException("Cannot extract main class to startup"); } } } if (mainClass != null) { log.verbose("Detected main class %s", mainClass); ret.put(JAVA_MAIN_CLASS_ENV_VAR, mainClass); } } List<String> javaOptions = getExtraJavaOptions(); if (javaOptions.size() > 0) { ret.put(JAVA_OPTIONS, StringUtils.join(javaOptions.iterator(), " ")); } return ret; }
java
{ "resource": "" }
q173636
GoTimeUtil.durationSeconds
test
public static Integer durationSeconds(String duration) { BigDecimal ns = durationNs(duration); if (ns == null) { return null; } BigDecimal sec = ns.divide(new BigDecimal(1_000_000_000)); if (sec.compareTo(new BigDecimal(Integer.MAX_VALUE)) > 0) { throw new IllegalArgumentException("Integer Overflow"); } return sec.intValue(); }
java
{ "resource": "" }
q173637
GoTimeUtil.durationNs
test
public static BigDecimal durationNs(String durationP) { if (durationP == null) { return null; } String duration = durationP.trim(); if (duration.length() == 0) { return null; } int unitPos = 1; while (unitPos < duration.length() && (Character.isDigit(duration.charAt(unitPos)) || duration.charAt(unitPos) == '.')) { unitPos++; } if (unitPos >= duration.length()) { throw new IllegalArgumentException("Time unit not found in string: " + duration); } String tail = duration.substring(unitPos); Long multiplier = null; Integer unitEnd = null; for(int i=0; i<TIME_UNITS.length; i++) { if (tail.startsWith(TIME_UNITS[i])) { multiplier = UNIT_MULTIPLIERS[i]; unitEnd = unitPos + TIME_UNITS[i].length(); break; } } if (multiplier == null) { throw new IllegalArgumentException("Unknown time unit in string: " + duration); } BigDecimal value = new BigDecimal(duration.substring(0, unitPos)); value = value.multiply(BigDecimal.valueOf(multiplier)); String remaining = duration.substring(unitEnd); BigDecimal remainingValue = durationNs(remaining); if (remainingValue != null) { value = value.add(remainingValue); } return value; }
java
{ "resource": "" }
q173638
AbstractAppServerHandler.scanFiles
test
protected String[] scanFiles(String... patterns) { String buildOutputDir = project.getBuild().getDirectory(); if (buildOutputDir != null && new File(buildOutputDir).exists()) { DirectoryScanner directoryScanner = new DirectoryScanner(); directoryScanner.setBasedir(buildOutputDir); directoryScanner.setIncludes(patterns); directoryScanner.scan(); return directoryScanner.getIncludedFiles(); } else { return new String[0]; } }
java
{ "resource": "" }
q173639
ApplyMojo.disableOpenShiftFeatures
test
protected void disableOpenShiftFeatures(ApplyService applyService) { // TODO we could check if the Templates service is running and if so we could still support templates? this.processTemplatesLocally = true; applyService.setSupportOAuthClients(false); applyService.setProcessTemplatesLocally(true); }
java
{ "resource": "" }
q173640
ApplyMojo.serviceHasIngressRule
test
private boolean serviceHasIngressRule(List<Ingress> ingresses, Service service) { String serviceName = KubernetesHelper.getName(service); for (Ingress ingress : ingresses) { IngressSpec spec = ingress.getSpec(); if (spec == null) { break; } List<IngressRule> rules = spec.getRules(); if (rules == null) { break; } for (IngressRule rule : rules) { HTTPIngressRuleValue http = rule.getHttp(); if (http == null) { break; } List<HTTPIngressPath> paths = http.getPaths(); if (paths == null) { break; } for (HTTPIngressPath path : paths) { IngressBackend backend = path.getBackend(); if (backend == null) { break; } if (Objects.equals(serviceName, backend.getServiceName())) { return true; } } } } return false; }
java
{ "resource": "" }
q173641
PropertiesMappingParser.parse
test
public Map<String, List<String>> parse(final InputStream mapping) { final Properties mappingProperties = new Properties(); try { mappingProperties.load(mapping); final Map<String, List<String>> serializedContent = new HashMap<>(); final Set<String> kinds = mappingProperties.stringPropertyNames(); for (String kind : kinds) { final String filenames = mappingProperties.getProperty(kind); final String[] filenameTypes = filenames.split(","); final List<String> scannedFiletypes = new ArrayList<>(); for (final String filenameType : filenameTypes) { scannedFiletypes.add(filenameType.trim()); } serializedContent.put(kind, scannedFiletypes); } return serializedContent; } catch (IOException e) { throw new IllegalStateException(e); } }
java
{ "resource": "" }
q173642
BuildMojo.getGeneratorContext
test
private GeneratorContext getGeneratorContext() { return new GeneratorContext.Builder() .config(extractGeneratorConfig()) .project(project) .logger(log) .runtimeMode(runtimeMode) .strategy(buildStrategy) .useProjectClasspath(useProjectClasspath) .artifactResolver(getFabric8ServiceHub().getArtifactResolverService()) .build(); }
java
{ "resource": "" }
q173643
BuildMojo.extractGeneratorConfig
test
private ProcessorConfig extractGeneratorConfig() { try { return ProfileUtil.blendProfileWithConfiguration(ProfileUtil.GENERATOR_CONFIG, profile, ResourceDirCreator.getFinalResourceDir(resourceDir, environment), generator); } catch (IOException e) { throw new IllegalArgumentException("Cannot extract generator config: " + e,e); } }
java
{ "resource": "" }
q173644
BuildMojo.getEnricherContext
test
public EnricherContext getEnricherContext() { return new MavenEnricherContext.Builder() .project(project) .properties(project.getProperties()) .session(session) .config(extractEnricherConfig()) .images(getResolvedImages()) .resources(resources) .log(log) .build(); }
java
{ "resource": "" }
q173645
BuildMojo.extractEnricherConfig
test
private ProcessorConfig extractEnricherConfig() { try { return ProfileUtil.blendProfileWithConfiguration(ProfileUtil.ENRICHER_CONFIG, profile, ResourceDirCreator.getFinalResourceDir(resourceDir, environment), enricher); } catch (IOException e) { throw new IllegalArgumentException("Cannot extract enricher config: " + e,e); } }
java
{ "resource": "" }
q173646
IconEnricher.getDefaultIconRef
test
private String getDefaultIconRef() { ProjectClassLoaders cls = getContext().getProjectClassLoaders(); if (cls.isClassInCompileClasspath(false, "io.fabric8.funktion.runtime.Main") || getContext().hasDependency( "io.fabric8.funktion", null)) { return "funktion"; } if (cls.isClassInCompileClasspath(false, "org.apache.camel.CamelContext")) { return "camel"; } if (getContext().hasPlugin(null, SpringBootConfigurationHelper.SPRING_BOOT_MAVEN_PLUGIN_ARTIFACT_ID) || cls.isClassInCompileClasspath(false, "org.springframework.boot.SpringApplication")) { return "spring-boot"; } if (cls.isClassInCompileClasspath(false, "org.springframework.core.Constants")) { return "spring"; } if (cls.isClassInCompileClasspath(false, "org.vertx.java.core.Handler", "io.vertx.core.Handler")) { return "vertx"; } if (getContext().hasPlugin("org.wildfly.swarm", "wildfly-swarm-plugin") || getContext().hasDependency( "org.wildfly.swarm", null)) { return "wildfly-swarm"; } if (getContext().hasPlugin( "io.thorntail", "thorntail-maven-plugin") || getContext().hasDependency( "io.thorntail", null)) { // use the WildFly Swarm icon until there's a dedicated Thorntail icon // Thorntail is a new name of WildFly Swarm return "wildfly-swarm"; } return null; }
java
{ "resource": "" }
q173647
IconEnricher.copyAppConfigFiles
test
private void copyAppConfigFiles(File appBuildDir, File appConfigDir) throws IOException { File[] files = appConfigDir.listFiles(); if (files != null) { appBuildDir.mkdirs(); for (File file : files) { File outFile = new File(appBuildDir, file.getName()); if (file.isDirectory()) { copyAppConfigFiles(outFile, file); } else { Files.copy(file, outFile); } } } }
java
{ "resource": "" }
q173648
SpringBootUtil.getPropertiesResource
test
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; }
java
{ "resource": "" }
q173649
SpringBootUtil.getSpringBootVersion
test
public static Optional<String> getSpringBootVersion(MavenProject mavenProject) { return Optional.ofNullable(MavenUtil.getDependencyVersion(mavenProject, SpringBootConfigurationHelper.SPRING_BOOT_GROUP_ID, SpringBootConfigurationHelper.SPRING_BOOT_ARTIFACT_ID)); }
java
{ "resource": "" }
q173650
PluginServiceFactory.createServiceObjects
test
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(); } }
java
{ "resource": "" }
q173651
EnricherManager.enrich
test
private void enrich(PlatformMode platformMode, final ProcessorConfig enricherConfig, final KubernetesListBuilder builder, final List<Enricher> enricherList) { loop(enricherConfig, enricher -> { enricher.enrich(platformMode, builder); return null; }); }
java
{ "resource": "" }
q173652
EnricherConfig.getRawConfig
test
public Map<String, String> getRawConfig() { return configuration.getProcessorConfig().orElse(ProcessorConfig.EMPTY).getConfigMap(name); }
java
{ "resource": "" }
q173653
YamlUtil.getFlattenedMap
test
private static Map<String, Object> getFlattenedMap(Map<String, Object> source) { Map<String, Object> result = new LinkedHashMap<>(); buildFlattenedMap(result, source, null); return result; }
java
{ "resource": "" }
q173654
WatchMojo.extractWatcherConfig
test
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); } }
java
{ "resource": "" }
q173655
ResourceMojo.getSingletonTemplate
test
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; }
java
{ "resource": "" }
q173656
ResourceMojo.getBuildReferenceDate
test
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); } }
java
{ "resource": "" }
q173657
GeneratorConfig.get
test
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; }
java
{ "resource": "" }
q173658
ProcessorConfig.getConfigMap
test
public Map<String, String> getConfigMap(String name) { return config.containsKey(name) ? Collections.unmodifiableMap(config.get(name)) : Collections.<String, String>emptyMap(); }
java
{ "resource": "" }
q173659
ProcessorConfig.prepareProcessors
test
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; }
java
{ "resource": "" }
q173660
BaseGenerator.addFrom
test
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())); } }
java
{ "resource": "" }
q173661
BaseGenerator.getFromModeDefault
test
private String getFromModeDefault(RuntimeMode mode) { if (mode == RuntimeMode.openshift && fromSelector != null && fromSelector.isRedHat()) { return "istag"; } else { return "docker"; } }
java
{ "resource": "" }
q173662
BaseGenerator.getImageName
test
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"); } }
java
{ "resource": "" }
q173663
BaseGenerator.getRegistry
test
protected String getRegistry() { if (!RuntimeMode.isOpenShiftMode(getProject().getProperties())) { return getConfigWithFallback(Config.registry, "fabric8.generator.registry", null); } return null; }
java
{ "resource": "" }
q173664
AbstractLiveEnricher.isOnline
test
boolean isOnline() { String isOnline = getConfig(Config.online); if (isOnline != null) { return Configs.asBoolean(isOnline); } Boolean ret = asBooleanFromGlobalProp("fabric8.online"); return ret != null ? ret : getDefaultOnline(); }
java
{ "resource": "" }
q173665
AbstractLiveEnricher.getExternalServiceURL
test
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; } } }
java
{ "resource": "" }
q173666
AbstractLiveEnricher.asBooleanFromGlobalProp
test
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; }
java
{ "resource": "" }
q173667
ElasticsearchJestAutoConfiguration.createJestClient
test
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(); }
java
{ "resource": "" }
q173668
ElasticsearchJestAutoConfiguration.createInternalNode
test
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")); }
java
{ "resource": "" }
q173669
ElasticsearchJestAutoConfiguration.scanPlugins
test
@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()); }
java
{ "resource": "" }
q173670
AmericanExpressRewardsBalance.fromJson
test
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; }
java
{ "resource": "" }
q173671
AmericanExpress.getRewardsBalance
test
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"); } }); } }); }
java
{ "resource": "" }
q173672
PayPalPaymentResource.fromJson
test
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; }
java
{ "resource": "" }
q173673
BraintreeHttpClient.get
test
@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); }
java
{ "resource": "" }
q173674
BraintreeHttpClient.post
test
@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); } }
java
{ "resource": "" }
q173675
VenmoConfiguration.fromJson
test
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; }
java
{ "resource": "" }
q173676
DataCollector.collectDeviceData
test
public static void collectDeviceData(BraintreeFragment fragment, BraintreeResponseListener<String> listener) { collectDeviceData(fragment, null, listener); }
java
{ "resource": "" }
q173677
DataCollector.collectDeviceData
test
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()); } } }); }
java
{ "resource": "" }
q173678
DataCollector.collectPayPalDeviceData
test
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()); }
java
{ "resource": "" }
q173679
DataCollector.getPayPalClientMetadataId
test
public static String getPayPalClientMetadataId(Context context) { try { return PayPalOneTouchCore.getClientMetadataId(context); } catch (NoClassDefFoundError ignored) {} try { return PayPalDataCollector.getClientMetadataId(context); } catch (NoClassDefFoundError ignored) {} return ""; }
java
{ "resource": "" }
q173680
SignatureVerification.isSignatureValid
test
@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; }
java
{ "resource": "" }
q173681
Json.optString
test
public static String optString(JSONObject json, String name, String fallback) { if (json.isNull(name)) { return fallback; } else { return json.optString(name, fallback); } }
java
{ "resource": "" }
q173682
PaymentMethodNonce.parsePaymentMethodNonces
test
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; }
java
{ "resource": "" }
q173683
OtcConfiguration.getBrowserCheckoutConfig
test
public CheckoutRecipe getBrowserCheckoutConfig() { for (CheckoutRecipe recipe : mCheckoutRecipesInDecreasingPriorityOrder) { if (recipe.getTarget() == RequestTarget.browser) { return recipe; } } return null; }
java
{ "resource": "" }
q173684
OtcConfiguration.getBrowserBillingAgreementConfig
test
public BillingAgreementRecipe getBrowserBillingAgreementConfig() { for (BillingAgreementRecipe recipe : mBillingAgreementRecipesInDecreasingPriorityOrder) { if (recipe.getTarget() == RequestTarget.browser) { return recipe; } } return null; }
java
{ "resource": "" }
q173685
HttpClient.get
test
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(); } } } }); }
java
{ "resource": "" }
q173686
HttpClient.post
test
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); } } }); }
java
{ "resource": "" }
q173687
HttpClient.post
test
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(); } } }
java
{ "resource": "" }
q173688
LocalPayment.startPayment
test
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); } }); } }); }
java
{ "resource": "" }
q173689
LocalPayment.approvePayment
test
public static void approvePayment(BraintreeFragment fragment, LocalPaymentRequest request) { fragment.browserSwitch(BraintreeRequestCodes.LOCAL_PAYMENT, request.getApprovalUrl()); fragment.sendAnalyticsEvent(paymentTypeForAnalytics() + ".local-payment.webswitch.initiate.succeeded"); }
java
{ "resource": "" }
q173690
BraintreeFragment.addListener
test
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(); }
java
{ "resource": "" }
q173691
BraintreeFragment.removeListener
test
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; } }
java
{ "resource": "" }
q173692
PayPal.requestBillingAgreement
test
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")); } }
java
{ "resource": "" }
q173693
PayPal.onActivityResult
test
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); } } }
java
{ "resource": "" }
q173694
PayPal.parseResponse
test
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; }
java
{ "resource": "" }
q173695
OpenKoreanTextProcessorJava.addNounsToDictionary
test
public static void addNounsToDictionary(List<String> words) { OpenKoreanTextProcessor.addNounsToDictionary(JavaConverters.asScalaBufferConverter(words).asScala()); }
java
{ "resource": "" }
q173696
OpenKoreanTextProcessorJava.removeWordFromDictionary
test
public static void removeWordFromDictionary(KoreanPosJava pos, List<String> words) { OpenKoreanTextProcessor.removeWordsFromDictionary(KoreanPos.withName(pos.toString()), JavaConverters.asScalaBufferConverter(words).asScala()); }
java
{ "resource": "" }
q173697
OpenKoreanTextProcessorJava.tokensToJavaStringList
test
public static List<String> tokensToJavaStringList(Seq<KoreanToken> tokens, boolean keepSpace) { Iterator<KoreanToken> tokenized = tokens.iterator(); List<String> output = new LinkedList<>(); while (tokenized.hasNext()) { final KoreanToken token = tokenized.next(); if (keepSpace || token.pos() != KoreanPos.Space()) { output.add(token.text()); } } return output; }
java
{ "resource": "" }
q173698
OpenKoreanTextProcessorJava.extractPhrases
test
public static List<KoreanPhraseExtractor.KoreanPhrase> extractPhrases(Seq<KoreanToken> tokens, boolean filterSpam, boolean includeHashtags) { Seq<KoreanPhraseExtractor.KoreanPhrase> seq = OpenKoreanTextProcessor.extractPhrases(tokens, filterSpam, includeHashtags); return toJavaList(seq); }
java
{ "resource": "" }
q173699
OpenKoreanTextProcessorJava.detokenize
test
public static String detokenize(List<String> tokens) { return OpenKoreanTextProcessor.detokenize(JavaConverters.asScalaBufferConverter(tokens).asScala()); }
java
{ "resource": "" }