repo stringlengths 7 58 | path stringlengths 12 218 | func_name stringlengths 3 140 | original_string stringlengths 73 34.1k | language stringclasses 1 value | code stringlengths 73 34.1k | code_tokens list | docstring stringlengths 3 16k | docstring_tokens list | sha stringlengths 40 40 | url stringlengths 105 339 | partition stringclasses 1 value |
|---|---|---|---|---|---|---|---|---|---|---|---|
arquillian/arquillian-cube | openshift/openshift/src/main/java/org/arquillian/cube/openshift/impl/resources/OpenShiftResourceFactory.java | OpenShiftResourceFactory.createImageStreamRequest | private static String createImageStreamRequest(String name, String version, String image, boolean insecure) {
JSONObject imageStream = new JSONObject();
JSONObject metadata = new JSONObject();
JSONObject annotations = new JSONObject();
metadata.put("name", name);
annotations.put("openshift.io/image.insecureRepository", insecure);
metadata.put("annotations", annotations);
// Definition of the image
JSONObject from = new JSONObject();
from.put("kind", "DockerImage");
from.put("name", image);
JSONObject importPolicy = new JSONObject();
importPolicy.put("insecure", insecure);
JSONObject tag = new JSONObject();
tag.put("name", version);
tag.put("from", from);
tag.put("importPolicy", importPolicy);
JSONObject tagAnnotations = new JSONObject();
tagAnnotations.put("version", version);
tag.put("annotations", tagAnnotations);
JSONArray tags = new JSONArray();
tags.add(tag);
// Add image definition to image stream
JSONObject spec = new JSONObject();
spec.put("tags", tags);
imageStream.put("kind", "ImageStream");
imageStream.put("apiVersion", "v1");
imageStream.put("metadata", metadata);
imageStream.put("spec", spec);
return imageStream.toJSONString();
} | java | private static String createImageStreamRequest(String name, String version, String image, boolean insecure) {
JSONObject imageStream = new JSONObject();
JSONObject metadata = new JSONObject();
JSONObject annotations = new JSONObject();
metadata.put("name", name);
annotations.put("openshift.io/image.insecureRepository", insecure);
metadata.put("annotations", annotations);
// Definition of the image
JSONObject from = new JSONObject();
from.put("kind", "DockerImage");
from.put("name", image);
JSONObject importPolicy = new JSONObject();
importPolicy.put("insecure", insecure);
JSONObject tag = new JSONObject();
tag.put("name", version);
tag.put("from", from);
tag.put("importPolicy", importPolicy);
JSONObject tagAnnotations = new JSONObject();
tagAnnotations.put("version", version);
tag.put("annotations", tagAnnotations);
JSONArray tags = new JSONArray();
tags.add(tag);
// Add image definition to image stream
JSONObject spec = new JSONObject();
spec.put("tags", tags);
imageStream.put("kind", "ImageStream");
imageStream.put("apiVersion", "v1");
imageStream.put("metadata", metadata);
imageStream.put("spec", spec);
return imageStream.toJSONString();
} | [
"private",
"static",
"String",
"createImageStreamRequest",
"(",
"String",
"name",
",",
"String",
"version",
",",
"String",
"image",
",",
"boolean",
"insecure",
")",
"{",
"JSONObject",
"imageStream",
"=",
"new",
"JSONObject",
"(",
")",
";",
"JSONObject",
"metadat... | Creates image stream request and returns it in JSON formatted string.
@param name Name of the image stream
@param insecure If the registry where the image is stored is insecure
@param image Image name, includes registry information and tag
@param version Image stream version.
@return JSON formatted string | [
"Creates",
"image",
"stream",
"request",
"and",
"returns",
"it",
"in",
"JSON",
"formatted",
"string",
"."
] | ce6b08062cc6ba2a68ecc29606bbae9acda5be13 | https://github.com/arquillian/arquillian-cube/blob/ce6b08062cc6ba2a68ecc29606bbae9acda5be13/openshift/openshift/src/main/java/org/arquillian/cube/openshift/impl/resources/OpenShiftResourceFactory.java#L159-L198 | train |
arquillian/arquillian-cube | openshift/openshift/src/main/java/org/arquillian/cube/openshift/impl/resources/OpenShiftResourceFactory.java | OpenShiftResourceFactory.getTemplates | static <T> List<Template> getTemplates(T objectType) {
try {
List<Template> templates = new ArrayList<>();
TEMP_FINDER.findAnnotations(templates, objectType);
return templates;
} catch (Exception e) {
throw new IllegalStateException(e);
}
} | java | static <T> List<Template> getTemplates(T objectType) {
try {
List<Template> templates = new ArrayList<>();
TEMP_FINDER.findAnnotations(templates, objectType);
return templates;
} catch (Exception e) {
throw new IllegalStateException(e);
}
} | [
"static",
"<",
"T",
">",
"List",
"<",
"Template",
">",
"getTemplates",
"(",
"T",
"objectType",
")",
"{",
"try",
"{",
"List",
"<",
"Template",
">",
"templates",
"=",
"new",
"ArrayList",
"<>",
"(",
")",
";",
"TEMP_FINDER",
".",
"findAnnotations",
"(",
"t... | Aggregates a list of templates specified by @Template | [
"Aggregates",
"a",
"list",
"of",
"templates",
"specified",
"by"
] | ce6b08062cc6ba2a68ecc29606bbae9acda5be13 | https://github.com/arquillian/arquillian-cube/blob/ce6b08062cc6ba2a68ecc29606bbae9acda5be13/openshift/openshift/src/main/java/org/arquillian/cube/openshift/impl/resources/OpenShiftResourceFactory.java#L203-L211 | train |
arquillian/arquillian-cube | openshift/openshift/src/main/java/org/arquillian/cube/openshift/impl/resources/OpenShiftResourceFactory.java | OpenShiftResourceFactory.syncInstantiation | static <T> boolean syncInstantiation(T objectType) {
List<Template> templates = new ArrayList<>();
Templates tr = TEMP_FINDER.findAnnotations(templates, objectType);
if (tr == null) {
/* Default to synchronous instantiation */
return true;
} else {
return tr.syncInstantiation();
}
} | java | static <T> boolean syncInstantiation(T objectType) {
List<Template> templates = new ArrayList<>();
Templates tr = TEMP_FINDER.findAnnotations(templates, objectType);
if (tr == null) {
/* Default to synchronous instantiation */
return true;
} else {
return tr.syncInstantiation();
}
} | [
"static",
"<",
"T",
">",
"boolean",
"syncInstantiation",
"(",
"T",
"objectType",
")",
"{",
"List",
"<",
"Template",
">",
"templates",
"=",
"new",
"ArrayList",
"<>",
"(",
")",
";",
"Templates",
"tr",
"=",
"TEMP_FINDER",
".",
"findAnnotations",
"(",
"templat... | Returns true if templates are to be instantiated synchronously and false if
asynchronously. | [
"Returns",
"true",
"if",
"templates",
"are",
"to",
"be",
"instantiated",
"synchronously",
"and",
"false",
"if",
"asynchronously",
"."
] | ce6b08062cc6ba2a68ecc29606bbae9acda5be13 | https://github.com/arquillian/arquillian-cube/blob/ce6b08062cc6ba2a68ecc29606bbae9acda5be13/openshift/openshift/src/main/java/org/arquillian/cube/openshift/impl/resources/OpenShiftResourceFactory.java#L217-L226 | train |
arquillian/arquillian-cube | kubernetes/kubernetes/src/main/java/org/arquillian/cube/kubernetes/impl/KubernetesAssistant.java | KubernetesAssistant.deployApplication | public void deployApplication(String applicationName, String... classpathLocations) throws IOException {
final List<URL> classpathElements = Arrays.stream(classpathLocations)
.map(classpath -> Thread.currentThread().getContextClassLoader().getResource(classpath))
.collect(Collectors.toList());
deployApplication(applicationName, classpathElements.toArray(new URL[classpathElements.size()]));
} | java | public void deployApplication(String applicationName, String... classpathLocations) throws IOException {
final List<URL> classpathElements = Arrays.stream(classpathLocations)
.map(classpath -> Thread.currentThread().getContextClassLoader().getResource(classpath))
.collect(Collectors.toList());
deployApplication(applicationName, classpathElements.toArray(new URL[classpathElements.size()]));
} | [
"public",
"void",
"deployApplication",
"(",
"String",
"applicationName",
",",
"String",
"...",
"classpathLocations",
")",
"throws",
"IOException",
"{",
"final",
"List",
"<",
"URL",
">",
"classpathElements",
"=",
"Arrays",
".",
"stream",
"(",
"classpathLocations",
... | Deploys application reading resources from specified classpath location
@param applicationName to configure in cluster
@param classpathLocations where resources are read
@throws IOException | [
"Deploys",
"application",
"reading",
"resources",
"from",
"specified",
"classpath",
"location"
] | ce6b08062cc6ba2a68ecc29606bbae9acda5be13 | https://github.com/arquillian/arquillian-cube/blob/ce6b08062cc6ba2a68ecc29606bbae9acda5be13/kubernetes/kubernetes/src/main/java/org/arquillian/cube/kubernetes/impl/KubernetesAssistant.java#L107-L114 | train |
arquillian/arquillian-cube | kubernetes/kubernetes/src/main/java/org/arquillian/cube/kubernetes/impl/KubernetesAssistant.java | KubernetesAssistant.deployApplication | public void deployApplication(String applicationName, URL... urls) throws IOException {
this.applicationName = applicationName;
for (URL url : urls) {
try (InputStream inputStream = url.openStream()) {
deploy(inputStream);
}
}
} | java | public void deployApplication(String applicationName, URL... urls) throws IOException {
this.applicationName = applicationName;
for (URL url : urls) {
try (InputStream inputStream = url.openStream()) {
deploy(inputStream);
}
}
} | [
"public",
"void",
"deployApplication",
"(",
"String",
"applicationName",
",",
"URL",
"...",
"urls",
")",
"throws",
"IOException",
"{",
"this",
".",
"applicationName",
"=",
"applicationName",
";",
"for",
"(",
"URL",
"url",
":",
"urls",
")",
"{",
"try",
"(",
... | Deploys application reading resources from specified URLs
@param applicationName to configure in cluster
@param urls where resources are read
@return the name of the application
@throws IOException | [
"Deploys",
"application",
"reading",
"resources",
"from",
"specified",
"URLs"
] | ce6b08062cc6ba2a68ecc29606bbae9acda5be13 | https://github.com/arquillian/arquillian-cube/blob/ce6b08062cc6ba2a68ecc29606bbae9acda5be13/kubernetes/kubernetes/src/main/java/org/arquillian/cube/kubernetes/impl/KubernetesAssistant.java#L136-L144 | train |
arquillian/arquillian-cube | kubernetes/kubernetes/src/main/java/org/arquillian/cube/kubernetes/impl/KubernetesAssistant.java | KubernetesAssistant.deploy | public void deploy(InputStream inputStream) throws IOException {
final List<? extends HasMetadata> entities = deploy("application", inputStream);
if (this.applicationName == null) {
Optional<String> deployment = entities.stream()
.filter(hm -> hm instanceof Deployment)
.map(hm -> (Deployment) hm)
.map(rc -> rc.getMetadata().getName()).findFirst();
deployment.ifPresent(name -> this.applicationName = name);
}
} | java | public void deploy(InputStream inputStream) throws IOException {
final List<? extends HasMetadata> entities = deploy("application", inputStream);
if (this.applicationName == null) {
Optional<String> deployment = entities.stream()
.filter(hm -> hm instanceof Deployment)
.map(hm -> (Deployment) hm)
.map(rc -> rc.getMetadata().getName()).findFirst();
deployment.ifPresent(name -> this.applicationName = name);
}
} | [
"public",
"void",
"deploy",
"(",
"InputStream",
"inputStream",
")",
"throws",
"IOException",
"{",
"final",
"List",
"<",
"?",
"extends",
"HasMetadata",
">",
"entities",
"=",
"deploy",
"(",
"\"application\"",
",",
"inputStream",
")",
";",
"if",
"(",
"this",
".... | Deploys application reading resources from specified InputStream
@param inputStream where resources are read
@throws IOException | [
"Deploys",
"application",
"reading",
"resources",
"from",
"specified",
"InputStream"
] | ce6b08062cc6ba2a68ecc29606bbae9acda5be13 | https://github.com/arquillian/arquillian-cube/blob/ce6b08062cc6ba2a68ecc29606bbae9acda5be13/kubernetes/kubernetes/src/main/java/org/arquillian/cube/kubernetes/impl/KubernetesAssistant.java#L231-L243 | train |
arquillian/arquillian-cube | kubernetes/kubernetes/src/main/java/org/arquillian/cube/kubernetes/impl/KubernetesAssistant.java | KubernetesAssistant.getServiceUrl | public Optional<URL> getServiceUrl(String name) {
Service service = client.services().inNamespace(namespace).withName(name).get();
return service != null ? createUrlForService(service) : Optional.empty();
} | java | public Optional<URL> getServiceUrl(String name) {
Service service = client.services().inNamespace(namespace).withName(name).get();
return service != null ? createUrlForService(service) : Optional.empty();
} | [
"public",
"Optional",
"<",
"URL",
">",
"getServiceUrl",
"(",
"String",
"name",
")",
"{",
"Service",
"service",
"=",
"client",
".",
"services",
"(",
")",
".",
"inNamespace",
"(",
"namespace",
")",
".",
"withName",
"(",
"name",
")",
".",
"get",
"(",
")",... | Gets the URL of the service with the given name that has been created during the current session.
@param name to return its URL
@return URL of the service. | [
"Gets",
"the",
"URL",
"of",
"the",
"service",
"with",
"the",
"given",
"name",
"that",
"has",
"been",
"created",
"during",
"the",
"current",
"session",
"."
] | ce6b08062cc6ba2a68ecc29606bbae9acda5be13 | https://github.com/arquillian/arquillian-cube/blob/ce6b08062cc6ba2a68ecc29606bbae9acda5be13/kubernetes/kubernetes/src/main/java/org/arquillian/cube/kubernetes/impl/KubernetesAssistant.java#L263-L266 | train |
arquillian/arquillian-cube | kubernetes/kubernetes/src/main/java/org/arquillian/cube/kubernetes/impl/KubernetesAssistant.java | KubernetesAssistant.getServiceUrl | public Optional<URL> getServiceUrl() {
Optional<Service> optionalService = client.services().inNamespace(namespace)
.list().getItems()
.stream()
.findFirst();
return optionalService
.map(this::createUrlForService)
.orElse(Optional.empty());
} | java | public Optional<URL> getServiceUrl() {
Optional<Service> optionalService = client.services().inNamespace(namespace)
.list().getItems()
.stream()
.findFirst();
return optionalService
.map(this::createUrlForService)
.orElse(Optional.empty());
} | [
"public",
"Optional",
"<",
"URL",
">",
"getServiceUrl",
"(",
")",
"{",
"Optional",
"<",
"Service",
">",
"optionalService",
"=",
"client",
".",
"services",
"(",
")",
".",
"inNamespace",
"(",
"namespace",
")",
".",
"list",
"(",
")",
".",
"getItems",
"(",
... | Gets the URL of the first service that have been created during the current session.
@return URL of the first service. | [
"Gets",
"the",
"URL",
"of",
"the",
"first",
"service",
"that",
"have",
"been",
"created",
"during",
"the",
"current",
"session",
"."
] | ce6b08062cc6ba2a68ecc29606bbae9acda5be13 | https://github.com/arquillian/arquillian-cube/blob/ce6b08062cc6ba2a68ecc29606bbae9acda5be13/kubernetes/kubernetes/src/main/java/org/arquillian/cube/kubernetes/impl/KubernetesAssistant.java#L273-L282 | train |
arquillian/arquillian-cube | kubernetes/kubernetes/src/main/java/org/arquillian/cube/kubernetes/impl/KubernetesAssistant.java | KubernetesAssistant.cleanup | public void cleanup() {
List<String> keys = new ArrayList<>(created.keySet());
keys.sort(String::compareTo);
for (String key : keys) {
created.remove(key)
.stream()
.sorted(Comparator.comparing(HasMetadata::getKind))
.forEach(metadata -> {
log.info(String.format("Deleting %s : %s", key, metadata.getKind()));
deleteWithRetries(metadata);
});
}
} | java | public void cleanup() {
List<String> keys = new ArrayList<>(created.keySet());
keys.sort(String::compareTo);
for (String key : keys) {
created.remove(key)
.stream()
.sorted(Comparator.comparing(HasMetadata::getKind))
.forEach(metadata -> {
log.info(String.format("Deleting %s : %s", key, metadata.getKind()));
deleteWithRetries(metadata);
});
}
} | [
"public",
"void",
"cleanup",
"(",
")",
"{",
"List",
"<",
"String",
">",
"keys",
"=",
"new",
"ArrayList",
"<>",
"(",
"created",
".",
"keySet",
"(",
")",
")",
";",
"keys",
".",
"sort",
"(",
"String",
"::",
"compareTo",
")",
";",
"for",
"(",
"String",... | Removes all resources deployed using this class. | [
"Removes",
"all",
"resources",
"deployed",
"using",
"this",
"class",
"."
] | ce6b08062cc6ba2a68ecc29606bbae9acda5be13 | https://github.com/arquillian/arquillian-cube/blob/ce6b08062cc6ba2a68ecc29606bbae9acda5be13/kubernetes/kubernetes/src/main/java/org/arquillian/cube/kubernetes/impl/KubernetesAssistant.java#L361-L373 | train |
arquillian/arquillian-cube | kubernetes/kubernetes/src/main/java/org/arquillian/cube/kubernetes/impl/KubernetesAssistant.java | KubernetesAssistant.awaitPodReadinessOrFail | public void awaitPodReadinessOrFail(Predicate<Pod> filter) {
await().atMost(5, TimeUnit.MINUTES).until(() -> {
List<Pod> list = client.pods().inNamespace(namespace).list().getItems();
return list.stream()
.filter(filter)
.filter(Readiness::isPodReady)
.collect(Collectors.toList()).size() >= 1;
}
);
} | java | public void awaitPodReadinessOrFail(Predicate<Pod> filter) {
await().atMost(5, TimeUnit.MINUTES).until(() -> {
List<Pod> list = client.pods().inNamespace(namespace).list().getItems();
return list.stream()
.filter(filter)
.filter(Readiness::isPodReady)
.collect(Collectors.toList()).size() >= 1;
}
);
} | [
"public",
"void",
"awaitPodReadinessOrFail",
"(",
"Predicate",
"<",
"Pod",
">",
"filter",
")",
"{",
"await",
"(",
")",
".",
"atMost",
"(",
"5",
",",
"TimeUnit",
".",
"MINUTES",
")",
".",
"until",
"(",
"(",
")",
"->",
"{",
"List",
"<",
"Pod",
">",
"... | Awaits at most 5 minutes until all pods meets the given predicate.
@param filter used to wait to detect that a pod is up and running. | [
"Awaits",
"at",
"most",
"5",
"minutes",
"until",
"all",
"pods",
"meets",
"the",
"given",
"predicate",
"."
] | ce6b08062cc6ba2a68ecc29606bbae9acda5be13 | https://github.com/arquillian/arquillian-cube/blob/ce6b08062cc6ba2a68ecc29606bbae9acda5be13/kubernetes/kubernetes/src/main/java/org/arquillian/cube/kubernetes/impl/KubernetesAssistant.java#L430-L439 | train |
arquillian/arquillian-cube | docker/docker/src/main/java/org/arquillian/cube/docker/impl/requirement/DockerRequirement.java | DockerRequirement.getDockerVersion | private static Version getDockerVersion(String serverUrl) {
try {
DockerClient client = DockerClientBuilder.getInstance(serverUrl).build();
return client.versionCmd().exec();
} catch (Exception e) {
return null;
}
} | java | private static Version getDockerVersion(String serverUrl) {
try {
DockerClient client = DockerClientBuilder.getInstance(serverUrl).build();
return client.versionCmd().exec();
} catch (Exception e) {
return null;
}
} | [
"private",
"static",
"Version",
"getDockerVersion",
"(",
"String",
"serverUrl",
")",
"{",
"try",
"{",
"DockerClient",
"client",
"=",
"DockerClientBuilder",
".",
"getInstance",
"(",
"serverUrl",
")",
".",
"build",
"(",
")",
";",
"return",
"client",
".",
"versio... | Returns the docker version.
@param serverUrl
The serverUrl to use. | [
"Returns",
"the",
"docker",
"version",
"."
] | ce6b08062cc6ba2a68ecc29606bbae9acda5be13 | https://github.com/arquillian/arquillian-cube/blob/ce6b08062cc6ba2a68ecc29606bbae9acda5be13/docker/docker/src/main/java/org/arquillian/cube/docker/impl/requirement/DockerRequirement.java#L59-L66 | train |
arquillian/arquillian-cube | core/src/main/java/org/arquillian/cube/impl/client/CubeConfigurator.java | CubeConfigurator.configure | public void configure(@Observes(precedence = -10) ArquillianDescriptor arquillianDescriptor) {
Map<String, String> config = arquillianDescriptor.extension(EXTENSION_NAME).getExtensionProperties();
CubeConfiguration cubeConfiguration = CubeConfiguration.fromMap(config);
configurationProducer.set(cubeConfiguration);
} | java | public void configure(@Observes(precedence = -10) ArquillianDescriptor arquillianDescriptor) {
Map<String, String> config = arquillianDescriptor.extension(EXTENSION_NAME).getExtensionProperties();
CubeConfiguration cubeConfiguration = CubeConfiguration.fromMap(config);
configurationProducer.set(cubeConfiguration);
} | [
"public",
"void",
"configure",
"(",
"@",
"Observes",
"(",
"precedence",
"=",
"-",
"10",
")",
"ArquillianDescriptor",
"arquillianDescriptor",
")",
"{",
"Map",
"<",
"String",
",",
"String",
">",
"config",
"=",
"arquillianDescriptor",
".",
"extension",
"(",
"EXTE... | Add precedence -10 because we need that ContainerRegistry is available in the Arquillian scope. | [
"Add",
"precedence",
"-",
"10",
"because",
"we",
"need",
"that",
"ContainerRegistry",
"is",
"available",
"in",
"the",
"Arquillian",
"scope",
"."
] | ce6b08062cc6ba2a68ecc29606bbae9acda5be13 | https://github.com/arquillian/arquillian-cube/blob/ce6b08062cc6ba2a68ecc29606bbae9acda5be13/core/src/main/java/org/arquillian/cube/impl/client/CubeConfigurator.java#L20-L24 | train |
arquillian/arquillian-cube | openshift/openshift-restassured/src/main/java/org/arquillian/cube/openshift/restassured/RestAssuredConfigurator.java | RestAssuredConfigurator.configure | public void configure(@Observes(precedence = -200) ArquillianDescriptor arquillianDescriptor) {
restAssuredConfigurationInstanceProducer.set(
RestAssuredConfiguration.fromMap(arquillianDescriptor
.extension("restassured")
.getExtensionProperties()));
} | java | public void configure(@Observes(precedence = -200) ArquillianDescriptor arquillianDescriptor) {
restAssuredConfigurationInstanceProducer.set(
RestAssuredConfiguration.fromMap(arquillianDescriptor
.extension("restassured")
.getExtensionProperties()));
} | [
"public",
"void",
"configure",
"(",
"@",
"Observes",
"(",
"precedence",
"=",
"-",
"200",
")",
"ArquillianDescriptor",
"arquillianDescriptor",
")",
"{",
"restAssuredConfigurationInstanceProducer",
".",
"set",
"(",
"RestAssuredConfiguration",
".",
"fromMap",
"(",
"arqui... | required for rest assured base URI configuration. | [
"required",
"for",
"rest",
"assured",
"base",
"URI",
"configuration",
"."
] | ce6b08062cc6ba2a68ecc29606bbae9acda5be13 | https://github.com/arquillian/arquillian-cube/blob/ce6b08062cc6ba2a68ecc29606bbae9acda5be13/openshift/openshift-restassured/src/main/java/org/arquillian/cube/openshift/restassured/RestAssuredConfigurator.java#L17-L22 | train |
arquillian/arquillian-cube | docker/docker/src/main/java/org/arquillian/cube/docker/impl/client/CubeDockerConfigurationResolver.java | CubeDockerConfigurationResolver.resolve | public Map<String, String> resolve(Map<String, String> config) {
config = resolveSystemEnvironmentVariables(config);
config = resolveSystemDefaultSetup(config);
config = resolveDockerInsideDocker(config);
config = resolveDownloadDockerMachine(config);
config = resolveAutoStartDockerMachine(config);
config = resolveDefaultDockerMachine(config);
config = resolveServerUriByOperativeSystem(config);
config = resolveServerIp(config);
config = resolveTlsVerification(config);
return config;
} | java | public Map<String, String> resolve(Map<String, String> config) {
config = resolveSystemEnvironmentVariables(config);
config = resolveSystemDefaultSetup(config);
config = resolveDockerInsideDocker(config);
config = resolveDownloadDockerMachine(config);
config = resolveAutoStartDockerMachine(config);
config = resolveDefaultDockerMachine(config);
config = resolveServerUriByOperativeSystem(config);
config = resolveServerIp(config);
config = resolveTlsVerification(config);
return config;
} | [
"public",
"Map",
"<",
"String",
",",
"String",
">",
"resolve",
"(",
"Map",
"<",
"String",
",",
"String",
">",
"config",
")",
"{",
"config",
"=",
"resolveSystemEnvironmentVariables",
"(",
"config",
")",
";",
"config",
"=",
"resolveSystemDefaultSetup",
"(",
"c... | Resolves the configuration.
@param config The specified configuration.
@return The resolved configuration. | [
"Resolves",
"the",
"configuration",
"."
] | ce6b08062cc6ba2a68ecc29606bbae9acda5be13 | https://github.com/arquillian/arquillian-cube/blob/ce6b08062cc6ba2a68ecc29606bbae9acda5be13/docker/docker/src/main/java/org/arquillian/cube/docker/impl/client/CubeDockerConfigurationResolver.java#L68-L79 | train |
arquillian/arquillian-cube | docker/drone/src/main/java/org/arquillian/cube/docker/drone/util/SeleniumVersionExtractor.java | SeleniumVersionExtractor.fromClassPath | public static String fromClassPath() {
Set<String> versions = new HashSet<>();
try {
ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
Enumeration<URL> manifests = classLoader.getResources("META-INF/MANIFEST.MF");
while (manifests.hasMoreElements()) {
URL manifestURL = manifests.nextElement();
try (InputStream is = manifestURL.openStream()) {
Manifest manifest = new Manifest();
manifest.read(is);
Attributes buildInfo = manifest.getAttributes("Build-Info");
if (buildInfo != null) {
if (buildInfo.getValue("Selenium-Version") != null) {
versions.add(buildInfo.getValue("Selenium-Version"));
} else {
// might be in build-info part
if (manifest.getEntries() != null) {
if (manifest.getEntries().containsKey("Build-Info")) {
final Attributes attributes = manifest.getEntries().get("Build-Info");
if (attributes.getValue("Selenium-Version") != null) {
versions.add(attributes.getValue("Selenium-Version"));
}
}
}
}
}
}
}
} catch (Exception e) {
logger.log(Level.WARNING,
"Exception {0} occurred while resolving selenium version and latest image is going to be used.",
e.getMessage());
return SELENIUM_VERSION;
}
if (versions.isEmpty()) {
logger.log(Level.INFO, "No version of Selenium found in classpath. Using latest image.");
return SELENIUM_VERSION;
}
String foundVersion = versions.iterator().next();
if (versions.size() > 1) {
logger.log(Level.WARNING, "Multiple versions of Selenium found in classpath. Using the first one found {0}.",
foundVersion);
}
return foundVersion;
} | java | public static String fromClassPath() {
Set<String> versions = new HashSet<>();
try {
ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
Enumeration<URL> manifests = classLoader.getResources("META-INF/MANIFEST.MF");
while (manifests.hasMoreElements()) {
URL manifestURL = manifests.nextElement();
try (InputStream is = manifestURL.openStream()) {
Manifest manifest = new Manifest();
manifest.read(is);
Attributes buildInfo = manifest.getAttributes("Build-Info");
if (buildInfo != null) {
if (buildInfo.getValue("Selenium-Version") != null) {
versions.add(buildInfo.getValue("Selenium-Version"));
} else {
// might be in build-info part
if (manifest.getEntries() != null) {
if (manifest.getEntries().containsKey("Build-Info")) {
final Attributes attributes = manifest.getEntries().get("Build-Info");
if (attributes.getValue("Selenium-Version") != null) {
versions.add(attributes.getValue("Selenium-Version"));
}
}
}
}
}
}
}
} catch (Exception e) {
logger.log(Level.WARNING,
"Exception {0} occurred while resolving selenium version and latest image is going to be used.",
e.getMessage());
return SELENIUM_VERSION;
}
if (versions.isEmpty()) {
logger.log(Level.INFO, "No version of Selenium found in classpath. Using latest image.");
return SELENIUM_VERSION;
}
String foundVersion = versions.iterator().next();
if (versions.size() > 1) {
logger.log(Level.WARNING, "Multiple versions of Selenium found in classpath. Using the first one found {0}.",
foundVersion);
}
return foundVersion;
} | [
"public",
"static",
"String",
"fromClassPath",
"(",
")",
"{",
"Set",
"<",
"String",
">",
"versions",
"=",
"new",
"HashSet",
"<>",
"(",
")",
";",
"try",
"{",
"ClassLoader",
"classLoader",
"=",
"Thread",
".",
"currentThread",
"(",
")",
".",
"getContextClassL... | Returns current selenium version from JAR set in classpath.
@return Version of Selenium. | [
"Returns",
"current",
"selenium",
"version",
"from",
"JAR",
"set",
"in",
"classpath",
"."
] | ce6b08062cc6ba2a68ecc29606bbae9acda5be13 | https://github.com/arquillian/arquillian-cube/blob/ce6b08062cc6ba2a68ecc29606bbae9acda5be13/docker/drone/src/main/java/org/arquillian/cube/docker/drone/util/SeleniumVersionExtractor.java#L26-L76 | train |
arquillian/arquillian-cube | kubernetes/kubernetes/src/main/java/org/arquillian/cube/kubernetes/impl/DefaultConfiguration.java | DefaultConfiguration.getKubernetesConfigurationUrl | public static URL getKubernetesConfigurationUrl(Map<String, String> map) throws MalformedURLException {
if (Strings.isNotNullOrEmpty(Utils.getSystemPropertyOrEnvVar(ENVIRONMENT_CONFIG_URL, ""))) {
return new URL(Utils.getSystemPropertyOrEnvVar(ENVIRONMENT_CONFIG_URL, ""));
} else if (Strings.isNotNullOrEmpty(Utils.getSystemPropertyOrEnvVar(ENVIRONMENT_CONFIG_RESOURCE_NAME, ""))) {
String resourceName = Utils.getSystemPropertyOrEnvVar(ENVIRONMENT_CONFIG_RESOURCE_NAME, "");
return findConfigResource(resourceName);
} else if (map.containsKey(ENVIRONMENT_CONFIG_URL)) {
return new URL(map.get(ENVIRONMENT_CONFIG_URL));
} else if (map.containsKey(ENVIRONMENT_CONFIG_RESOURCE_NAME)) {
String resourceName = map.get(ENVIRONMENT_CONFIG_RESOURCE_NAME);
return findConfigResource(resourceName);
} else {
// Let the resource locator find the resource
return null;
}
} | java | public static URL getKubernetesConfigurationUrl(Map<String, String> map) throws MalformedURLException {
if (Strings.isNotNullOrEmpty(Utils.getSystemPropertyOrEnvVar(ENVIRONMENT_CONFIG_URL, ""))) {
return new URL(Utils.getSystemPropertyOrEnvVar(ENVIRONMENT_CONFIG_URL, ""));
} else if (Strings.isNotNullOrEmpty(Utils.getSystemPropertyOrEnvVar(ENVIRONMENT_CONFIG_RESOURCE_NAME, ""))) {
String resourceName = Utils.getSystemPropertyOrEnvVar(ENVIRONMENT_CONFIG_RESOURCE_NAME, "");
return findConfigResource(resourceName);
} else if (map.containsKey(ENVIRONMENT_CONFIG_URL)) {
return new URL(map.get(ENVIRONMENT_CONFIG_URL));
} else if (map.containsKey(ENVIRONMENT_CONFIG_RESOURCE_NAME)) {
String resourceName = map.get(ENVIRONMENT_CONFIG_RESOURCE_NAME);
return findConfigResource(resourceName);
} else {
// Let the resource locator find the resource
return null;
}
} | [
"public",
"static",
"URL",
"getKubernetesConfigurationUrl",
"(",
"Map",
"<",
"String",
",",
"String",
">",
"map",
")",
"throws",
"MalformedURLException",
"{",
"if",
"(",
"Strings",
".",
"isNotNullOrEmpty",
"(",
"Utils",
".",
"getSystemPropertyOrEnvVar",
"(",
"ENVI... | Applies the kubernetes json url to the configuration.
@param map
The arquillian configuration. | [
"Applies",
"the",
"kubernetes",
"json",
"url",
"to",
"the",
"configuration",
"."
] | ce6b08062cc6ba2a68ecc29606bbae9acda5be13 | https://github.com/arquillian/arquillian-cube/blob/ce6b08062cc6ba2a68ecc29606bbae9acda5be13/kubernetes/kubernetes/src/main/java/org/arquillian/cube/kubernetes/impl/DefaultConfiguration.java#L237-L252 | train |
arquillian/arquillian-cube | kubernetes/kubernetes/src/main/java/org/arquillian/cube/kubernetes/impl/DefaultConfiguration.java | DefaultConfiguration.findConfigResource | public static URL findConfigResource(String resourceName) {
if (Strings.isNullOrEmpty(resourceName)) {
return null;
}
final URL url = resourceName.startsWith(ROOT) ? DefaultConfiguration.class.getResource(resourceName)
: DefaultConfiguration.class.getResource(ROOT + resourceName);
if (url != null) {
return url;
}
// This is useful to get resource under META-INF directory
String[] resourceNamePrefix = new String[] {"META-INF/fabric8/", "META-INF/fabric8/"};
for (String resource : resourceNamePrefix) {
String fullResourceName = resource + resourceName;
URL candidate = KubernetesResourceLocator.class.getResource(fullResourceName.startsWith(ROOT) ? fullResourceName : ROOT + fullResourceName);
if (candidate != null) {
return candidate;
}
}
return null;
} | java | public static URL findConfigResource(String resourceName) {
if (Strings.isNullOrEmpty(resourceName)) {
return null;
}
final URL url = resourceName.startsWith(ROOT) ? DefaultConfiguration.class.getResource(resourceName)
: DefaultConfiguration.class.getResource(ROOT + resourceName);
if (url != null) {
return url;
}
// This is useful to get resource under META-INF directory
String[] resourceNamePrefix = new String[] {"META-INF/fabric8/", "META-INF/fabric8/"};
for (String resource : resourceNamePrefix) {
String fullResourceName = resource + resourceName;
URL candidate = KubernetesResourceLocator.class.getResource(fullResourceName.startsWith(ROOT) ? fullResourceName : ROOT + fullResourceName);
if (candidate != null) {
return candidate;
}
}
return null;
} | [
"public",
"static",
"URL",
"findConfigResource",
"(",
"String",
"resourceName",
")",
"{",
"if",
"(",
"Strings",
".",
"isNullOrEmpty",
"(",
"resourceName",
")",
")",
"{",
"return",
"null",
";",
"}",
"final",
"URL",
"url",
"=",
"resourceName",
".",
"startsWith... | Returns the URL of a classpath resource.
@param resourceName
The name of the resource.
@return The URL. | [
"Returns",
"the",
"URL",
"of",
"a",
"classpath",
"resource",
"."
] | ce6b08062cc6ba2a68ecc29606bbae9acda5be13 | https://github.com/arquillian/arquillian-cube/blob/ce6b08062cc6ba2a68ecc29606bbae9acda5be13/kubernetes/kubernetes/src/main/java/org/arquillian/cube/kubernetes/impl/DefaultConfiguration.java#L262-L287 | train |
arquillian/arquillian-cube | kubernetes/kubernetes/src/main/java/org/arquillian/cube/kubernetes/impl/DefaultConfiguration.java | DefaultConfiguration.asUrlOrResource | public static URL asUrlOrResource(String s) {
if (Strings.isNullOrEmpty(s)) {
return null;
}
try {
return new URL(s);
} catch (MalformedURLException e) {
//If its not a valid URL try to treat it as a local resource.
return findConfigResource(s);
}
} | java | public static URL asUrlOrResource(String s) {
if (Strings.isNullOrEmpty(s)) {
return null;
}
try {
return new URL(s);
} catch (MalformedURLException e) {
//If its not a valid URL try to treat it as a local resource.
return findConfigResource(s);
}
} | [
"public",
"static",
"URL",
"asUrlOrResource",
"(",
"String",
"s",
")",
"{",
"if",
"(",
"Strings",
".",
"isNullOrEmpty",
"(",
"s",
")",
")",
"{",
"return",
"null",
";",
"}",
"try",
"{",
"return",
"new",
"URL",
"(",
"s",
")",
";",
"}",
"catch",
"(",
... | Convert a string to a URL and fallback to classpath resource, if not convertible.
@param s
The string to convert.
@return The URL. | [
"Convert",
"a",
"string",
"to",
"a",
"URL",
"and",
"fallback",
"to",
"classpath",
"resource",
"if",
"not",
"convertible",
"."
] | ce6b08062cc6ba2a68ecc29606bbae9acda5be13 | https://github.com/arquillian/arquillian-cube/blob/ce6b08062cc6ba2a68ecc29606bbae9acda5be13/kubernetes/kubernetes/src/main/java/org/arquillian/cube/kubernetes/impl/DefaultConfiguration.java#L297-L308 | train |
arquillian/arquillian-cube | openshift/openshift/src/main/java/org/arquillian/cube/openshift/impl/client/OpenShiftAssistant.java | OpenShiftAssistant.deploy | @Override
public void deploy(InputStream inputStream) throws IOException {
final List<? extends HasMetadata> entities = deploy("application", inputStream);
if (this.applicationName == null) {
Optional<String> deploymentConfig = entities.stream()
.filter(hm -> hm instanceof DeploymentConfig)
.map(hm -> (DeploymentConfig) hm)
.map(dc -> dc.getMetadata().getName()).findFirst();
deploymentConfig.ifPresent(name -> this.applicationName = name);
}
} | java | @Override
public void deploy(InputStream inputStream) throws IOException {
final List<? extends HasMetadata> entities = deploy("application", inputStream);
if (this.applicationName == null) {
Optional<String> deploymentConfig = entities.stream()
.filter(hm -> hm instanceof DeploymentConfig)
.map(hm -> (DeploymentConfig) hm)
.map(dc -> dc.getMetadata().getName()).findFirst();
deploymentConfig.ifPresent(name -> this.applicationName = name);
}
} | [
"@",
"Override",
"public",
"void",
"deploy",
"(",
"InputStream",
"inputStream",
")",
"throws",
"IOException",
"{",
"final",
"List",
"<",
"?",
"extends",
"HasMetadata",
">",
"entities",
"=",
"deploy",
"(",
"\"application\"",
",",
"inputStream",
")",
";",
"if",
... | Deploys application reading resources from specified InputStream.
@param inputStream where resources are read
@throws IOException | [
"Deploys",
"application",
"reading",
"resources",
"from",
"specified",
"InputStream",
"."
] | ce6b08062cc6ba2a68ecc29606bbae9acda5be13 | https://github.com/arquillian/arquillian-cube/blob/ce6b08062cc6ba2a68ecc29606bbae9acda5be13/openshift/openshift/src/main/java/org/arquillian/cube/openshift/impl/client/OpenShiftAssistant.java#L69-L82 | train |
arquillian/arquillian-cube | openshift/openshift/src/main/java/org/arquillian/cube/openshift/impl/client/OpenShiftAssistant.java | OpenShiftAssistant.getRoute | public Optional<URL> getRoute(String routeName) {
Route route = getClient().routes()
.inNamespace(namespace).withName(routeName).get();
return route != null ? Optional.ofNullable(createUrlFromRoute(route)) : Optional.empty();
} | java | public Optional<URL> getRoute(String routeName) {
Route route = getClient().routes()
.inNamespace(namespace).withName(routeName).get();
return route != null ? Optional.ofNullable(createUrlFromRoute(route)) : Optional.empty();
} | [
"public",
"Optional",
"<",
"URL",
">",
"getRoute",
"(",
"String",
"routeName",
")",
"{",
"Route",
"route",
"=",
"getClient",
"(",
")",
".",
"routes",
"(",
")",
".",
"inNamespace",
"(",
"namespace",
")",
".",
"withName",
"(",
"routeName",
")",
".",
"get... | Gets the URL of the route with given name.
@param routeName to return its URL
@return URL backed by the route with given name. | [
"Gets",
"the",
"URL",
"of",
"the",
"route",
"with",
"given",
"name",
"."
] | ce6b08062cc6ba2a68ecc29606bbae9acda5be13 | https://github.com/arquillian/arquillian-cube/blob/ce6b08062cc6ba2a68ecc29606bbae9acda5be13/openshift/openshift/src/main/java/org/arquillian/cube/openshift/impl/client/OpenShiftAssistant.java#L89-L94 | train |
arquillian/arquillian-cube | openshift/openshift/src/main/java/org/arquillian/cube/openshift/impl/client/OpenShiftAssistant.java | OpenShiftAssistant.getRoute | public Optional<URL> getRoute() {
Optional<Route> optionalRoute = getClient().routes().inNamespace(namespace)
.list().getItems()
.stream()
.findFirst();
return optionalRoute
.map(OpenShiftRouteLocator::createUrlFromRoute);
} | java | public Optional<URL> getRoute() {
Optional<Route> optionalRoute = getClient().routes().inNamespace(namespace)
.list().getItems()
.stream()
.findFirst();
return optionalRoute
.map(OpenShiftRouteLocator::createUrlFromRoute);
} | [
"public",
"Optional",
"<",
"URL",
">",
"getRoute",
"(",
")",
"{",
"Optional",
"<",
"Route",
">",
"optionalRoute",
"=",
"getClient",
"(",
")",
".",
"routes",
"(",
")",
".",
"inNamespace",
"(",
"namespace",
")",
".",
"list",
"(",
")",
".",
"getItems",
... | Returns the URL of the first route.
@return URL backed by the first route. | [
"Returns",
"the",
"URL",
"of",
"the",
"first",
"route",
"."
] | ce6b08062cc6ba2a68ecc29606bbae9acda5be13 | https://github.com/arquillian/arquillian-cube/blob/ce6b08062cc6ba2a68ecc29606bbae9acda5be13/openshift/openshift/src/main/java/org/arquillian/cube/openshift/impl/client/OpenShiftAssistant.java#L100-L108 | train |
arquillian/arquillian-cube | openshift/openshift/src/main/java/org/arquillian/cube/openshift/impl/client/OpenShiftAssistant.java | OpenShiftAssistant.projectExists | public boolean projectExists(String name) throws IllegalArgumentException {
if (name == null || name.isEmpty()) {
throw new IllegalArgumentException("Project name cannot be empty");
}
return listProjects().stream()
.map(p -> p.getMetadata().getName())
.anyMatch(Predicate.isEqual(name));
} | java | public boolean projectExists(String name) throws IllegalArgumentException {
if (name == null || name.isEmpty()) {
throw new IllegalArgumentException("Project name cannot be empty");
}
return listProjects().stream()
.map(p -> p.getMetadata().getName())
.anyMatch(Predicate.isEqual(name));
} | [
"public",
"boolean",
"projectExists",
"(",
"String",
"name",
")",
"throws",
"IllegalArgumentException",
"{",
"if",
"(",
"name",
"==",
"null",
"||",
"name",
".",
"isEmpty",
"(",
")",
")",
"{",
"throw",
"new",
"IllegalArgumentException",
"(",
"\"Project name canno... | Checks if the given project exists or not.
@param name project name
@return true/false
@throws IllegalArgumentException | [
"Checks",
"if",
"the",
"given",
"project",
"exists",
"or",
"not",
"."
] | ce6b08062cc6ba2a68ecc29606bbae9acda5be13 | https://github.com/arquillian/arquillian-cube/blob/ce6b08062cc6ba2a68ecc29606bbae9acda5be13/openshift/openshift/src/main/java/org/arquillian/cube/openshift/impl/client/OpenShiftAssistant.java#L230-L237 | train |
arquillian/arquillian-cube | openshift/openshift/src/main/java/org/arquillian/cube/openshift/impl/client/OpenShiftAssistant.java | OpenShiftAssistant.findProject | public Optional<Project> findProject(String name) throws IllegalArgumentException {
if (name == null || name.isEmpty()) {
throw new IllegalArgumentException("Project name cannot be empty");
}
return getProject(name);
} | java | public Optional<Project> findProject(String name) throws IllegalArgumentException {
if (name == null || name.isEmpty()) {
throw new IllegalArgumentException("Project name cannot be empty");
}
return getProject(name);
} | [
"public",
"Optional",
"<",
"Project",
">",
"findProject",
"(",
"String",
"name",
")",
"throws",
"IllegalArgumentException",
"{",
"if",
"(",
"name",
"==",
"null",
"||",
"name",
".",
"isEmpty",
"(",
")",
")",
"{",
"throw",
"new",
"IllegalArgumentException",
"(... | Finds for the given project.
@param name project name
@return given project or an empty {@code Optional} if project does not exist
@throws IllegalArgumentException | [
"Finds",
"for",
"the",
"given",
"project",
"."
] | ce6b08062cc6ba2a68ecc29606bbae9acda5be13 | https://github.com/arquillian/arquillian-cube/blob/ce6b08062cc6ba2a68ecc29606bbae9acda5be13/openshift/openshift/src/main/java/org/arquillian/cube/openshift/impl/client/OpenShiftAssistant.java#L246-L251 | train |
arquillian/arquillian-cube | requirement/src/main/java/org/arquillian/cube/requirement/Constraints.java | Constraints.loadConstraint | private static Constraint loadConstraint(Annotation context) {
Constraint constraint = null;
final ServiceLoader<Constraint> constraints = ServiceLoader.load(Constraint.class);
for (Constraint aConstraint : constraints) {
try {
aConstraint.getClass().getDeclaredMethod("check", context.annotationType());
constraint = aConstraint;
break;
} catch (NoSuchMethodException e) {
// Look for next implementation if method not found with required signature.
}
}
if (constraint == null) {
throw new IllegalStateException("Couldn't found any implementation of " + Constraint.class.getName());
}
return constraint;
} | java | private static Constraint loadConstraint(Annotation context) {
Constraint constraint = null;
final ServiceLoader<Constraint> constraints = ServiceLoader.load(Constraint.class);
for (Constraint aConstraint : constraints) {
try {
aConstraint.getClass().getDeclaredMethod("check", context.annotationType());
constraint = aConstraint;
break;
} catch (NoSuchMethodException e) {
// Look for next implementation if method not found with required signature.
}
}
if (constraint == null) {
throw new IllegalStateException("Couldn't found any implementation of " + Constraint.class.getName());
}
return constraint;
} | [
"private",
"static",
"Constraint",
"loadConstraint",
"(",
"Annotation",
"context",
")",
"{",
"Constraint",
"constraint",
"=",
"null",
";",
"final",
"ServiceLoader",
"<",
"Constraint",
">",
"constraints",
"=",
"ServiceLoader",
".",
"load",
"(",
"Constraint",
".",
... | we have only one implementation on classpath. | [
"we",
"have",
"only",
"one",
"implementation",
"on",
"classpath",
"."
] | ce6b08062cc6ba2a68ecc29606bbae9acda5be13 | https://github.com/arquillian/arquillian-cube/blob/ce6b08062cc6ba2a68ecc29606bbae9acda5be13/requirement/src/main/java/org/arquillian/cube/requirement/Constraints.java#L38-L56 | train |
arquillian/arquillian-cube | openshift/openshift/src/main/java/org/arquillian/cube/openshift/impl/CEEnvironmentProcessor.java | CEEnvironmentProcessor.createEnvironment | public void createEnvironment(@Observes(precedence = 10) BeforeClass event, OpenShiftAdapter client,
CubeOpenShiftConfiguration cubeOpenShiftConfiguration) {
final TestClass testClass = event.getTestClass();
log.info(String.format("Creating environment for %s", testClass.getName()));
OpenShiftResourceFactory.createResources(testClass.getName(), client, testClass.getJavaClass(),
cubeOpenShiftConfiguration.getProperties());
classTemplateProcessor = new ClassTemplateProcessor(client, cubeOpenShiftConfiguration, testClass);
final List<? extends OpenShiftResource> templateResources = classTemplateProcessor.processTemplateResources();
templateDetailsProducer.set(() -> templateResources);
} | java | public void createEnvironment(@Observes(precedence = 10) BeforeClass event, OpenShiftAdapter client,
CubeOpenShiftConfiguration cubeOpenShiftConfiguration) {
final TestClass testClass = event.getTestClass();
log.info(String.format("Creating environment for %s", testClass.getName()));
OpenShiftResourceFactory.createResources(testClass.getName(), client, testClass.getJavaClass(),
cubeOpenShiftConfiguration.getProperties());
classTemplateProcessor = new ClassTemplateProcessor(client, cubeOpenShiftConfiguration, testClass);
final List<? extends OpenShiftResource> templateResources = classTemplateProcessor.processTemplateResources();
templateDetailsProducer.set(() -> templateResources);
} | [
"public",
"void",
"createEnvironment",
"(",
"@",
"Observes",
"(",
"precedence",
"=",
"10",
")",
"BeforeClass",
"event",
",",
"OpenShiftAdapter",
"client",
",",
"CubeOpenShiftConfiguration",
"cubeOpenShiftConfiguration",
")",
"{",
"final",
"TestClass",
"testClass",
"="... | Create the environment as specified by @Template or
arq.extension.ce-cube.openshift.template.* properties.
<p>
In the future, this might be handled by starting application Cube
objects, e.g. CreateCube(application), StartCube(application)
<p>
Needs to fire before the containers are started. | [
"Create",
"the",
"environment",
"as",
"specified",
"by"
] | ce6b08062cc6ba2a68ecc29606bbae9acda5be13 | https://github.com/arquillian/arquillian-cube/blob/ce6b08062cc6ba2a68ecc29606bbae9acda5be13/openshift/openshift/src/main/java/org/arquillian/cube/openshift/impl/CEEnvironmentProcessor.java#L87-L96 | train |
arquillian/arquillian-cube | docker/docker/src/main/java/org/arquillian/cube/docker/impl/client/containerobject/DockerContainerObjectBuilder.java | DockerContainerObjectBuilder.withContainerObjectClass | public DockerContainerObjectBuilder<T> withContainerObjectClass(Class<T> containerObjectClass) {
if (containerObjectClass == null) {
throw new IllegalArgumentException("container object class cannot be null");
}
this.containerObjectClass = containerObjectClass;
//First we check if this ContainerObject is defining a @CubeDockerFile in static method
final List<Method> methodsWithCubeDockerFile =
ReflectionUtil.getMethodsWithAnnotation(containerObjectClass, CubeDockerFile.class);
if (methodsWithCubeDockerFile.size() > 1) {
throw new IllegalArgumentException(
String.format(
"More than one %s annotation found and only one was expected. Methods where annotation was found are: %s",
CubeDockerFile.class.getSimpleName(), methodsWithCubeDockerFile));
}
classHasMethodWithCubeDockerFile = !methodsWithCubeDockerFile.isEmpty();
classDefinesCubeDockerFile = containerObjectClass.isAnnotationPresent(CubeDockerFile.class);
classDefinesImage = containerObjectClass.isAnnotationPresent(Image.class);
if (classHasMethodWithCubeDockerFile) {
methodWithCubeDockerFile = methodsWithCubeDockerFile.get(0);
boolean isMethodStatic = Modifier.isStatic(methodWithCubeDockerFile.getModifiers());
boolean methodHasNoArguments = methodWithCubeDockerFile.getParameterCount() == 0;
boolean methodReturnsAnArchive = Archive.class.isAssignableFrom(methodWithCubeDockerFile.getReturnType());
if (!isMethodStatic || !methodHasNoArguments || !methodReturnsAnArchive) {
throw new IllegalArgumentException(
String.format("Method %s annotated with %s is expected to be static, no args and return %s.",
methodWithCubeDockerFile, CubeDockerFile.class.getSimpleName(), Archive.class.getSimpleName()));
}
}
// User has defined @CubeDockerfile on the class and a method
if (classHasMethodWithCubeDockerFile && classDefinesCubeDockerFile) {
throw new IllegalArgumentException(
String.format(
"More than one %s annotation found and only one was expected. Both class and method %s has the annotation.",
CubeDockerFile.class.getSimpleName(), methodWithCubeDockerFile));
}
// User has defined @CubeDockerfile and @Image
if ((classHasMethodWithCubeDockerFile || classDefinesCubeDockerFile) && classDefinesImage) {
throw new IllegalArgumentException(
String.format("Container Object %s has defined %s annotation and %s annotation together.",
containerObjectClass.getSimpleName(), Image.class.getSimpleName(),
CubeDockerFile.class.getSimpleName()));
}
// User has not defined either @CubeDockerfile or @Image
if (!classDefinesCubeDockerFile && !classDefinesImage && !classHasMethodWithCubeDockerFile) {
throw new IllegalArgumentException(
String.format("Container Object %s is not annotated with either %s or %s annotations.",
containerObjectClass.getName(), CubeDockerFile.class.getSimpleName(), Image.class.getSimpleName()));
}
return this;
} | java | public DockerContainerObjectBuilder<T> withContainerObjectClass(Class<T> containerObjectClass) {
if (containerObjectClass == null) {
throw new IllegalArgumentException("container object class cannot be null");
}
this.containerObjectClass = containerObjectClass;
//First we check if this ContainerObject is defining a @CubeDockerFile in static method
final List<Method> methodsWithCubeDockerFile =
ReflectionUtil.getMethodsWithAnnotation(containerObjectClass, CubeDockerFile.class);
if (methodsWithCubeDockerFile.size() > 1) {
throw new IllegalArgumentException(
String.format(
"More than one %s annotation found and only one was expected. Methods where annotation was found are: %s",
CubeDockerFile.class.getSimpleName(), methodsWithCubeDockerFile));
}
classHasMethodWithCubeDockerFile = !methodsWithCubeDockerFile.isEmpty();
classDefinesCubeDockerFile = containerObjectClass.isAnnotationPresent(CubeDockerFile.class);
classDefinesImage = containerObjectClass.isAnnotationPresent(Image.class);
if (classHasMethodWithCubeDockerFile) {
methodWithCubeDockerFile = methodsWithCubeDockerFile.get(0);
boolean isMethodStatic = Modifier.isStatic(methodWithCubeDockerFile.getModifiers());
boolean methodHasNoArguments = methodWithCubeDockerFile.getParameterCount() == 0;
boolean methodReturnsAnArchive = Archive.class.isAssignableFrom(methodWithCubeDockerFile.getReturnType());
if (!isMethodStatic || !methodHasNoArguments || !methodReturnsAnArchive) {
throw new IllegalArgumentException(
String.format("Method %s annotated with %s is expected to be static, no args and return %s.",
methodWithCubeDockerFile, CubeDockerFile.class.getSimpleName(), Archive.class.getSimpleName()));
}
}
// User has defined @CubeDockerfile on the class and a method
if (classHasMethodWithCubeDockerFile && classDefinesCubeDockerFile) {
throw new IllegalArgumentException(
String.format(
"More than one %s annotation found and only one was expected. Both class and method %s has the annotation.",
CubeDockerFile.class.getSimpleName(), methodWithCubeDockerFile));
}
// User has defined @CubeDockerfile and @Image
if ((classHasMethodWithCubeDockerFile || classDefinesCubeDockerFile) && classDefinesImage) {
throw new IllegalArgumentException(
String.format("Container Object %s has defined %s annotation and %s annotation together.",
containerObjectClass.getSimpleName(), Image.class.getSimpleName(),
CubeDockerFile.class.getSimpleName()));
}
// User has not defined either @CubeDockerfile or @Image
if (!classDefinesCubeDockerFile && !classDefinesImage && !classHasMethodWithCubeDockerFile) {
throw new IllegalArgumentException(
String.format("Container Object %s is not annotated with either %s or %s annotations.",
containerObjectClass.getName(), CubeDockerFile.class.getSimpleName(), Image.class.getSimpleName()));
}
return this;
} | [
"public",
"DockerContainerObjectBuilder",
"<",
"T",
">",
"withContainerObjectClass",
"(",
"Class",
"<",
"T",
">",
"containerObjectClass",
")",
"{",
"if",
"(",
"containerObjectClass",
"==",
"null",
")",
"{",
"throw",
"new",
"IllegalArgumentException",
"(",
"\"contain... | Specifies the container object class to be instantiated
@param containerObjectClass
container object class to be instantiated
@return the current builder instance | [
"Specifies",
"the",
"container",
"object",
"class",
"to",
"be",
"instantiated"
] | ce6b08062cc6ba2a68ecc29606bbae9acda5be13 | https://github.com/arquillian/arquillian-cube/blob/ce6b08062cc6ba2a68ecc29606bbae9acda5be13/docker/docker/src/main/java/org/arquillian/cube/docker/impl/client/containerobject/DockerContainerObjectBuilder.java#L184-L241 | train |
arquillian/arquillian-cube | docker/docker/src/main/java/org/arquillian/cube/docker/impl/client/containerobject/DockerContainerObjectBuilder.java | DockerContainerObjectBuilder.withEnrichers | public DockerContainerObjectBuilder<T> withEnrichers(Collection<TestEnricher> enrichers) {
if (enrichers == null) {
throw new IllegalArgumentException("enrichers cannot be null");
}
this.enrichers = enrichers;
return this;
} | java | public DockerContainerObjectBuilder<T> withEnrichers(Collection<TestEnricher> enrichers) {
if (enrichers == null) {
throw new IllegalArgumentException("enrichers cannot be null");
}
this.enrichers = enrichers;
return this;
} | [
"public",
"DockerContainerObjectBuilder",
"<",
"T",
">",
"withEnrichers",
"(",
"Collection",
"<",
"TestEnricher",
">",
"enrichers",
")",
"{",
"if",
"(",
"enrichers",
"==",
"null",
")",
"{",
"throw",
"new",
"IllegalArgumentException",
"(",
"\"enrichers cannot be null... | Specifies the list of enrichers that will be used to enrich the container object.
@param enrichers
list of enrichers that will be used to enrich the container object
@return the current builder instance | [
"Specifies",
"the",
"list",
"of",
"enrichers",
"that",
"will",
"be",
"used",
"to",
"enrich",
"the",
"container",
"object",
"."
] | ce6b08062cc6ba2a68ecc29606bbae9acda5be13 | https://github.com/arquillian/arquillian-cube/blob/ce6b08062cc6ba2a68ecc29606bbae9acda5be13/docker/docker/src/main/java/org/arquillian/cube/docker/impl/client/containerobject/DockerContainerObjectBuilder.java#L282-L288 | train |
arquillian/arquillian-cube | docker/docker/src/main/java/org/arquillian/cube/docker/impl/client/containerobject/DockerContainerObjectBuilder.java | DockerContainerObjectBuilder.build | public T build() throws IllegalAccessException, IOException, InvocationTargetException {
generatedConfigutation = new CubeContainer();
findContainerName();
// if needed, prepare prepare resources required to build a docker image
prepareImageBuild();
// instantiate container object
instantiateContainerObject();
// enrich container object (without cube instance)
enrichContainerObjectBeforeCube();
// extract configuration from container object class
extractConfigurationFromContainerObject();
// merge received configuration with extracted configuration
mergeContainerObjectConfiguration();
// create/start/register associated cube
initializeCube();
// enrich container object (with cube instance)
enrichContainerObjectWithCube();
// return created container object
return containerObjectInstance;
} | java | public T build() throws IllegalAccessException, IOException, InvocationTargetException {
generatedConfigutation = new CubeContainer();
findContainerName();
// if needed, prepare prepare resources required to build a docker image
prepareImageBuild();
// instantiate container object
instantiateContainerObject();
// enrich container object (without cube instance)
enrichContainerObjectBeforeCube();
// extract configuration from container object class
extractConfigurationFromContainerObject();
// merge received configuration with extracted configuration
mergeContainerObjectConfiguration();
// create/start/register associated cube
initializeCube();
// enrich container object (with cube instance)
enrichContainerObjectWithCube();
// return created container object
return containerObjectInstance;
} | [
"public",
"T",
"build",
"(",
")",
"throws",
"IllegalAccessException",
",",
"IOException",
",",
"InvocationTargetException",
"{",
"generatedConfigutation",
"=",
"new",
"CubeContainer",
"(",
")",
";",
"findContainerName",
"(",
")",
";",
"// if needed, prepare prepare reso... | Triggers the building process, builds, creates and starts the docker container associated with the requested
container object, creates the container object and returns it
@return the created container object
@throws IllegalAccessException
if there is an error accessing the container object fields
@throws IOException
if there is an I/O error while preparing the docker build
@throws InvocationTargetException
if there is an error while calling the DockerFile archive creation | [
"Triggers",
"the",
"building",
"process",
"builds",
"creates",
"and",
"starts",
"the",
"docker",
"container",
"associated",
"with",
"the",
"requested",
"container",
"object",
"creates",
"the",
"container",
"object",
"and",
"returns",
"it"
] | ce6b08062cc6ba2a68ecc29606bbae9acda5be13 | https://github.com/arquillian/arquillian-cube/blob/ce6b08062cc6ba2a68ecc29606bbae9acda5be13/docker/docker/src/main/java/org/arquillian/cube/docker/impl/client/containerobject/DockerContainerObjectBuilder.java#L318-L338 | train |
arquillian/arquillian-cube | docker/docker/src/main/java/org/arquillian/cube/docker/impl/client/DockerContainerDefinitionParser.java | DockerContainerDefinitionParser.resolveDockerDefinition | private static Path resolveDockerDefinition(Path fullpath) {
final Path ymlPath = fullpath.resolveSibling(fullpath.getFileName() + ".yml");
if (Files.exists(ymlPath)) {
return ymlPath;
} else {
final Path yamlPath = fullpath.resolveSibling(fullpath.getFileName() + ".yaml");
if (Files.exists(yamlPath)) {
return yamlPath;
}
}
return null;
} | java | private static Path resolveDockerDefinition(Path fullpath) {
final Path ymlPath = fullpath.resolveSibling(fullpath.getFileName() + ".yml");
if (Files.exists(ymlPath)) {
return ymlPath;
} else {
final Path yamlPath = fullpath.resolveSibling(fullpath.getFileName() + ".yaml");
if (Files.exists(yamlPath)) {
return yamlPath;
}
}
return null;
} | [
"private",
"static",
"Path",
"resolveDockerDefinition",
"(",
"Path",
"fullpath",
")",
"{",
"final",
"Path",
"ymlPath",
"=",
"fullpath",
".",
"resolveSibling",
"(",
"fullpath",
".",
"getFileName",
"(",
")",
"+",
"\".yml\"",
")",
";",
"if",
"(",
"Files",
".",
... | Resolves current full path with .yml and .yaml extensions
@param fullpath
without extension.
@return Path of existing definition or null | [
"Resolves",
"current",
"full",
"path",
"with",
".",
"yml",
"and",
".",
"yaml",
"extensions"
] | ce6b08062cc6ba2a68ecc29606bbae9acda5be13 | https://github.com/arquillian/arquillian-cube/blob/ce6b08062cc6ba2a68ecc29606bbae9acda5be13/docker/docker/src/main/java/org/arquillian/cube/docker/impl/client/DockerContainerDefinitionParser.java#L206-L218 | train |
arquillian/arquillian-cube | openshift/openshift/src/main/java/org/arquillian/cube/openshift/impl/client/ResourceUtil.java | ResourceUtil.awaitRoute | public static void awaitRoute(URL routeUrl, int timeout, TimeUnit timeoutUnit, int repetitions, int... statusCodes) {
AtomicInteger successfulAwaitsInARow = new AtomicInteger(0);
await().atMost(timeout, timeoutUnit).until(() -> {
if (tryConnect(routeUrl, statusCodes)) {
successfulAwaitsInARow.incrementAndGet();
} else {
successfulAwaitsInARow.set(0);
}
return successfulAwaitsInARow.get() >= repetitions;
});
} | java | public static void awaitRoute(URL routeUrl, int timeout, TimeUnit timeoutUnit, int repetitions, int... statusCodes) {
AtomicInteger successfulAwaitsInARow = new AtomicInteger(0);
await().atMost(timeout, timeoutUnit).until(() -> {
if (tryConnect(routeUrl, statusCodes)) {
successfulAwaitsInARow.incrementAndGet();
} else {
successfulAwaitsInARow.set(0);
}
return successfulAwaitsInARow.get() >= repetitions;
});
} | [
"public",
"static",
"void",
"awaitRoute",
"(",
"URL",
"routeUrl",
",",
"int",
"timeout",
",",
"TimeUnit",
"timeoutUnit",
",",
"int",
"repetitions",
",",
"int",
"...",
"statusCodes",
")",
"{",
"AtomicInteger",
"successfulAwaitsInARow",
"=",
"new",
"AtomicInteger",
... | Waits for the timeout duration until the url responds with correct status code
@param routeUrl URL to check (usually a route one)
@param timeout Max timeout value to await for route readiness.
If not set, default timeout value is set to 5.
@param timeoutUnit TimeUnit used for timeout duration.
If not set, Minutes is used as default TimeUnit.
@param repetitions How many times in a row the route must respond successfully to be considered available.
@param statusCodes list of status code that might return that service is up and running.
It is used as OR, so if one returns true, then the route is considered valid.
If not set, then only 200 status code is used. | [
"Waits",
"for",
"the",
"timeout",
"duration",
"until",
"the",
"url",
"responds",
"with",
"correct",
"status",
"code"
] | ce6b08062cc6ba2a68ecc29606bbae9acda5be13 | https://github.com/arquillian/arquillian-cube/blob/ce6b08062cc6ba2a68ecc29606bbae9acda5be13/openshift/openshift/src/main/java/org/arquillian/cube/openshift/impl/client/ResourceUtil.java#L190-L200 | train |
arquillian/arquillian-cube | core/src/main/java/org/arquillian/cube/impl/util/ReflectionUtil.java | ReflectionUtil.getConstructor | public static Constructor<?> getConstructor(final Class<?> clazz,
final Class<?>... argumentTypes) throws NoSuchMethodException {
try {
return AccessController
.doPrivileged(new PrivilegedExceptionAction<Constructor<?>>() {
public Constructor<?> run()
throws NoSuchMethodException {
return clazz.getConstructor(argumentTypes);
}
});
}
// Unwrap
catch (final PrivilegedActionException pae) {
final Throwable t = pae.getCause();
// Rethrow
if (t instanceof NoSuchMethodException) {
throw (NoSuchMethodException) t;
} else {
// No other checked Exception thrown by Class.getConstructor
try {
throw (RuntimeException) t;
}
// Just in case we've really messed up
catch (final ClassCastException cce) {
throw new RuntimeException(
"Obtained unchecked Exception; this code should never be reached",
t);
}
}
}
} | java | public static Constructor<?> getConstructor(final Class<?> clazz,
final Class<?>... argumentTypes) throws NoSuchMethodException {
try {
return AccessController
.doPrivileged(new PrivilegedExceptionAction<Constructor<?>>() {
public Constructor<?> run()
throws NoSuchMethodException {
return clazz.getConstructor(argumentTypes);
}
});
}
// Unwrap
catch (final PrivilegedActionException pae) {
final Throwable t = pae.getCause();
// Rethrow
if (t instanceof NoSuchMethodException) {
throw (NoSuchMethodException) t;
} else {
// No other checked Exception thrown by Class.getConstructor
try {
throw (RuntimeException) t;
}
// Just in case we've really messed up
catch (final ClassCastException cce) {
throw new RuntimeException(
"Obtained unchecked Exception; this code should never be reached",
t);
}
}
}
} | [
"public",
"static",
"Constructor",
"<",
"?",
">",
"getConstructor",
"(",
"final",
"Class",
"<",
"?",
">",
"clazz",
",",
"final",
"Class",
"<",
"?",
">",
"...",
"argumentTypes",
")",
"throws",
"NoSuchMethodException",
"{",
"try",
"{",
"return",
"AccessControl... | Obtains the Constructor specified from the given Class and argument types
@throws NoSuchMethodException | [
"Obtains",
"the",
"Constructor",
"specified",
"from",
"the",
"given",
"Class",
"and",
"argument",
"types"
] | ce6b08062cc6ba2a68ecc29606bbae9acda5be13 | https://github.com/arquillian/arquillian-cube/blob/ce6b08062cc6ba2a68ecc29606bbae9acda5be13/core/src/main/java/org/arquillian/cube/impl/util/ReflectionUtil.java#L53-L83 | train |
arquillian/arquillian-cube | core/src/main/java/org/arquillian/cube/impl/util/ConfigUtil.java | ConfigUtil.getStringProperty | public static String getStringProperty(String name, Map<String, String> map, String defaultValue) {
if (map.containsKey(name) && Strings.isNotNullOrEmpty(map.get(name))) {
defaultValue = map.get(name);
}
return getPropertyOrEnvironmentVariable(name, defaultValue);
} | java | public static String getStringProperty(String name, Map<String, String> map, String defaultValue) {
if (map.containsKey(name) && Strings.isNotNullOrEmpty(map.get(name))) {
defaultValue = map.get(name);
}
return getPropertyOrEnvironmentVariable(name, defaultValue);
} | [
"public",
"static",
"String",
"getStringProperty",
"(",
"String",
"name",
",",
"Map",
"<",
"String",
",",
"String",
">",
"map",
",",
"String",
"defaultValue",
")",
"{",
"if",
"(",
"map",
".",
"containsKey",
"(",
"name",
")",
"&&",
"Strings",
".",
"isNotN... | Gets a property from system, environment or an external map.
The lookup order is system > env > map > defaultValue.
@param name
The name of the property.
@param map
The external map.
@param defaultValue
The value that should be used if property is not found. | [
"Gets",
"a",
"property",
"from",
"system",
"environment",
"or",
"an",
"external",
"map",
".",
"The",
"lookup",
"order",
"is",
"system",
">",
"env",
">",
"map",
">",
"defaultValue",
"."
] | ce6b08062cc6ba2a68ecc29606bbae9acda5be13 | https://github.com/arquillian/arquillian-cube/blob/ce6b08062cc6ba2a68ecc29606bbae9acda5be13/core/src/main/java/org/arquillian/cube/impl/util/ConfigUtil.java#L25-L30 | train |
arquillian/arquillian-cube | openshift/openshift/src/main/java/org/arquillian/cube/openshift/impl/client/OpenShiftAssistantTemplate.java | OpenShiftAssistantTemplate.parameter | public OpenShiftAssistantTemplate parameter(String name, String value) {
parameterValues.put(name, value);
return this;
} | java | public OpenShiftAssistantTemplate parameter(String name, String value) {
parameterValues.put(name, value);
return this;
} | [
"public",
"OpenShiftAssistantTemplate",
"parameter",
"(",
"String",
"name",
",",
"String",
"value",
")",
"{",
"parameterValues",
".",
"put",
"(",
"name",
",",
"value",
")",
";",
"return",
"this",
";",
"}"
] | Stores template parameters for OpenShiftAssistantTemplate.
@param name template parameter name
@param value template parameter value | [
"Stores",
"template",
"parameters",
"for",
"OpenShiftAssistantTemplate",
"."
] | ce6b08062cc6ba2a68ecc29606bbae9acda5be13 | https://github.com/arquillian/arquillian-cube/blob/ce6b08062cc6ba2a68ecc29606bbae9acda5be13/openshift/openshift/src/main/java/org/arquillian/cube/openshift/impl/client/OpenShiftAssistantTemplate.java#L37-L40 | train |
arquillian/arquillian-cube | core/src/main/java/org/arquillian/cube/impl/util/Timespan.java | Timespan.create | public static Timespan create(Timespan... timespans) {
if (timespans == null) {
return null;
}
if (timespans.length == 0) {
return ZERO_MILLISECONDS;
}
Timespan res = timespans[0];
for (int i = 1; i < timespans.length; i++) {
Timespan timespan = timespans[i];
res = res.add(timespan);
}
return res;
} | java | public static Timespan create(Timespan... timespans) {
if (timespans == null) {
return null;
}
if (timespans.length == 0) {
return ZERO_MILLISECONDS;
}
Timespan res = timespans[0];
for (int i = 1; i < timespans.length; i++) {
Timespan timespan = timespans[i];
res = res.add(timespan);
}
return res;
} | [
"public",
"static",
"Timespan",
"create",
"(",
"Timespan",
"...",
"timespans",
")",
"{",
"if",
"(",
"timespans",
"==",
"null",
")",
"{",
"return",
"null",
";",
"}",
"if",
"(",
"timespans",
".",
"length",
"==",
"0",
")",
"{",
"return",
"ZERO_MILLISECONDS"... | Creates a timespan from a list of other timespans.
@return a timespan representing the sum of all the timespans provided | [
"Creates",
"a",
"timespan",
"from",
"a",
"list",
"of",
"other",
"timespans",
"."
] | ce6b08062cc6ba2a68ecc29606bbae9acda5be13 | https://github.com/arquillian/arquillian-cube/blob/ce6b08062cc6ba2a68ecc29606bbae9acda5be13/core/src/main/java/org/arquillian/cube/impl/util/Timespan.java#L470-L487 | train |
arquillian/arquillian-cube | docker/drone/src/main/java/org/arquillian/cube/docker/drone/InstallSeleniumCube.java | InstallSeleniumCube.install | public void install(@Observes(precedence = 90) CubeDockerConfiguration configuration,
ArquillianDescriptor arquillianDescriptor) {
DockerCompositions cubes = configuration.getDockerContainersContent();
final SeleniumContainers seleniumContainers =
SeleniumContainers.create(getBrowser(arquillianDescriptor), cubeDroneConfigurationInstance.get());
cubes.add(seleniumContainers.getSeleniumContainerName(), seleniumContainers.getSeleniumContainer());
final boolean recording = cubeDroneConfigurationInstance.get().isRecording();
if (recording) {
cubes.add(seleniumContainers.getVncContainerName(), seleniumContainers.getVncContainer());
cubes.add(seleniumContainers.getVideoConverterContainerName(),
seleniumContainers.getVideoConverterContainer());
}
seleniumContainersInstanceProducer.set(seleniumContainers);
System.out.println("SELENIUM INSTALLED");
System.out.println(ConfigUtil.dump(cubes));
} | java | public void install(@Observes(precedence = 90) CubeDockerConfiguration configuration,
ArquillianDescriptor arquillianDescriptor) {
DockerCompositions cubes = configuration.getDockerContainersContent();
final SeleniumContainers seleniumContainers =
SeleniumContainers.create(getBrowser(arquillianDescriptor), cubeDroneConfigurationInstance.get());
cubes.add(seleniumContainers.getSeleniumContainerName(), seleniumContainers.getSeleniumContainer());
final boolean recording = cubeDroneConfigurationInstance.get().isRecording();
if (recording) {
cubes.add(seleniumContainers.getVncContainerName(), seleniumContainers.getVncContainer());
cubes.add(seleniumContainers.getVideoConverterContainerName(),
seleniumContainers.getVideoConverterContainer());
}
seleniumContainersInstanceProducer.set(seleniumContainers);
System.out.println("SELENIUM INSTALLED");
System.out.println(ConfigUtil.dump(cubes));
} | [
"public",
"void",
"install",
"(",
"@",
"Observes",
"(",
"precedence",
"=",
"90",
")",
"CubeDockerConfiguration",
"configuration",
",",
"ArquillianDescriptor",
"arquillianDescriptor",
")",
"{",
"DockerCompositions",
"cubes",
"=",
"configuration",
".",
"getDockerContainer... | ten less than Cube Q | [
"ten",
"less",
"than",
"Cube",
"Q"
] | ce6b08062cc6ba2a68ecc29606bbae9acda5be13 | https://github.com/arquillian/arquillian-cube/blob/ce6b08062cc6ba2a68ecc29606bbae9acda5be13/docker/drone/src/main/java/org/arquillian/cube/docker/drone/InstallSeleniumCube.java#L31-L51 | train |
arquillian/arquillian-cube | docker/docker/src/main/java/org/arquillian/cube/docker/impl/util/DockerMachine.java | DockerMachine.startDockerMachine | public void startDockerMachine(String cliPathExec, String machineName) {
commandLineExecutor.execCommand(createDockerMachineCommand(cliPathExec), "start", machineName);
this.manuallyStarted = true;
} | java | public void startDockerMachine(String cliPathExec, String machineName) {
commandLineExecutor.execCommand(createDockerMachineCommand(cliPathExec), "start", machineName);
this.manuallyStarted = true;
} | [
"public",
"void",
"startDockerMachine",
"(",
"String",
"cliPathExec",
",",
"String",
"machineName",
")",
"{",
"commandLineExecutor",
".",
"execCommand",
"(",
"createDockerMachineCommand",
"(",
"cliPathExec",
")",
",",
"\"start\"",
",",
"machineName",
")",
";",
"this... | Starts given docker machine.
@param cliPathExec
location of docker-machine or null if it is on PATH.
@param machineName
to be started. | [
"Starts",
"given",
"docker",
"machine",
"."
] | ce6b08062cc6ba2a68ecc29606bbae9acda5be13 | https://github.com/arquillian/arquillian-cube/blob/ce6b08062cc6ba2a68ecc29606bbae9acda5be13/docker/docker/src/main/java/org/arquillian/cube/docker/impl/util/DockerMachine.java#L53-L56 | train |
arquillian/arquillian-cube | docker/docker/src/main/java/org/arquillian/cube/docker/impl/util/DockerMachine.java | DockerMachine.isDockerMachineInstalled | public boolean isDockerMachineInstalled(String cliPathExec) {
try {
commandLineExecutor.execCommand(createDockerMachineCommand(cliPathExec));
return true;
} catch (Exception e) {
return false;
}
} | java | public boolean isDockerMachineInstalled(String cliPathExec) {
try {
commandLineExecutor.execCommand(createDockerMachineCommand(cliPathExec));
return true;
} catch (Exception e) {
return false;
}
} | [
"public",
"boolean",
"isDockerMachineInstalled",
"(",
"String",
"cliPathExec",
")",
"{",
"try",
"{",
"commandLineExecutor",
".",
"execCommand",
"(",
"createDockerMachineCommand",
"(",
"cliPathExec",
")",
")",
";",
"return",
"true",
";",
"}",
"catch",
"(",
"Excepti... | Checks if Docker Machine is installed by running docker-machine and inspect the result.
@param cliPathExec
location of docker-machine or null if it is on PATH.
@return true if it is installed, false otherwise. | [
"Checks",
"if",
"Docker",
"Machine",
"is",
"installed",
"by",
"running",
"docker",
"-",
"machine",
"and",
"inspect",
"the",
"result",
"."
] | ce6b08062cc6ba2a68ecc29606bbae9acda5be13 | https://github.com/arquillian/arquillian-cube/blob/ce6b08062cc6ba2a68ecc29606bbae9acda5be13/docker/docker/src/main/java/org/arquillian/cube/docker/impl/util/DockerMachine.java#L85-L92 | train |
arquillian/arquillian-cube | docker/docker/src/main/java/org/arquillian/cube/docker/impl/client/config/DockerCompositions.java | DockerCompositions.overrideCubeProperties | public void overrideCubeProperties(DockerCompositions overrideDockerCompositions) {
final Set<String> containerIds = overrideDockerCompositions.getContainerIds();
for (String containerId : containerIds) {
// main definition of containers contains a container that must be overrode
if (containers.containsKey(containerId)) {
final CubeContainer cubeContainer = containers.get(containerId);
final CubeContainer overrideCubeContainer = overrideDockerCompositions.get(containerId);
cubeContainer.setRemoveVolumes(overrideCubeContainer.getRemoveVolumes());
cubeContainer.setAlwaysPull(overrideCubeContainer.getAlwaysPull());
if (overrideCubeContainer.hasAwait()) {
cubeContainer.setAwait(overrideCubeContainer.getAwait());
}
if (overrideCubeContainer.hasBeforeStop()) {
cubeContainer.setBeforeStop(overrideCubeContainer.getBeforeStop());
}
if (overrideCubeContainer.isManual()) {
cubeContainer.setManual(overrideCubeContainer.isManual());
}
if (overrideCubeContainer.isKillContainer()) {
cubeContainer.setKillContainer(overrideCubeContainer.isKillContainer());
}
} else {
logger.warning(String.format("Overriding Container %s are not defined in main definition of containers.",
containerId));
}
}
} | java | public void overrideCubeProperties(DockerCompositions overrideDockerCompositions) {
final Set<String> containerIds = overrideDockerCompositions.getContainerIds();
for (String containerId : containerIds) {
// main definition of containers contains a container that must be overrode
if (containers.containsKey(containerId)) {
final CubeContainer cubeContainer = containers.get(containerId);
final CubeContainer overrideCubeContainer = overrideDockerCompositions.get(containerId);
cubeContainer.setRemoveVolumes(overrideCubeContainer.getRemoveVolumes());
cubeContainer.setAlwaysPull(overrideCubeContainer.getAlwaysPull());
if (overrideCubeContainer.hasAwait()) {
cubeContainer.setAwait(overrideCubeContainer.getAwait());
}
if (overrideCubeContainer.hasBeforeStop()) {
cubeContainer.setBeforeStop(overrideCubeContainer.getBeforeStop());
}
if (overrideCubeContainer.isManual()) {
cubeContainer.setManual(overrideCubeContainer.isManual());
}
if (overrideCubeContainer.isKillContainer()) {
cubeContainer.setKillContainer(overrideCubeContainer.isKillContainer());
}
} else {
logger.warning(String.format("Overriding Container %s are not defined in main definition of containers.",
containerId));
}
}
} | [
"public",
"void",
"overrideCubeProperties",
"(",
"DockerCompositions",
"overrideDockerCompositions",
")",
"{",
"final",
"Set",
"<",
"String",
">",
"containerIds",
"=",
"overrideDockerCompositions",
".",
"getContainerIds",
"(",
")",
";",
"for",
"(",
"String",
"containe... | This method only overrides properties that are specific from Cube like await strategy or before stop events.
@param overrideDockerCompositions
that contains information to override. | [
"This",
"method",
"only",
"overrides",
"properties",
"that",
"are",
"specific",
"from",
"Cube",
"like",
"await",
"strategy",
"or",
"before",
"stop",
"events",
"."
] | ce6b08062cc6ba2a68ecc29606bbae9acda5be13 | https://github.com/arquillian/arquillian-cube/blob/ce6b08062cc6ba2a68ecc29606bbae9acda5be13/docker/docker/src/main/java/org/arquillian/cube/docker/impl/client/config/DockerCompositions.java#L109-L142 | train |
arquillian/arquillian-cube | docker/docker/src/main/java/org/arquillian/cube/docker/impl/docker/compose/DockerComposeEnvironmentVarResolver.java | DockerComposeEnvironmentVarResolver.replaceParameters | public static String replaceParameters(final InputStream stream) {
String content = IOUtil.asStringPreservingNewLines(stream);
return resolvePlaceholders(content);
} | java | public static String replaceParameters(final InputStream stream) {
String content = IOUtil.asStringPreservingNewLines(stream);
return resolvePlaceholders(content);
} | [
"public",
"static",
"String",
"replaceParameters",
"(",
"final",
"InputStream",
"stream",
")",
"{",
"String",
"content",
"=",
"IOUtil",
".",
"asStringPreservingNewLines",
"(",
"stream",
")",
";",
"return",
"resolvePlaceholders",
"(",
"content",
")",
";",
"}"
] | Method that takes an inputstream, read it preserving the end lines, and subtitute using commons-lang-3 calls
the variables, first searching as system properties vars and then in environment var list.
In case of missing the property is replaced by white space.
@param stream
@return | [
"Method",
"that",
"takes",
"an",
"inputstream",
"read",
"it",
"preserving",
"the",
"end",
"lines",
"and",
"subtitute",
"using",
"commons",
"-",
"lang",
"-",
"3",
"calls",
"the",
"variables",
"first",
"searching",
"as",
"system",
"properties",
"vars",
"and",
... | ce6b08062cc6ba2a68ecc29606bbae9acda5be13 | https://github.com/arquillian/arquillian-cube/blob/ce6b08062cc6ba2a68ecc29606bbae9acda5be13/docker/docker/src/main/java/org/arquillian/cube/docker/impl/docker/compose/DockerComposeEnvironmentVarResolver.java#L22-L25 | train |
arquillian/arquillian-cube | core/src/main/java/org/arquillian/cube/impl/util/Strings.java | Strings.join | public static String join(final Collection<?> collection, final String separator) {
StringBuffer buffer = new StringBuffer();
boolean first = true;
Iterator<?> iter = collection.iterator();
while (iter.hasNext()) {
Object next = iter.next();
if (first) {
first = false;
} else {
buffer.append(separator);
}
buffer.append(next);
}
return buffer.toString();
} | java | public static String join(final Collection<?> collection, final String separator) {
StringBuffer buffer = new StringBuffer();
boolean first = true;
Iterator<?> iter = collection.iterator();
while (iter.hasNext()) {
Object next = iter.next();
if (first) {
first = false;
} else {
buffer.append(separator);
}
buffer.append(next);
}
return buffer.toString();
} | [
"public",
"static",
"String",
"join",
"(",
"final",
"Collection",
"<",
"?",
">",
"collection",
",",
"final",
"String",
"separator",
")",
"{",
"StringBuffer",
"buffer",
"=",
"new",
"StringBuffer",
"(",
")",
";",
"boolean",
"first",
"=",
"true",
";",
"Iterat... | joins a collection of objects together as a String using a separator | [
"joins",
"a",
"collection",
"of",
"objects",
"together",
"as",
"a",
"String",
"using",
"a",
"separator"
] | ce6b08062cc6ba2a68ecc29606bbae9acda5be13 | https://github.com/arquillian/arquillian-cube/blob/ce6b08062cc6ba2a68ecc29606bbae9acda5be13/core/src/main/java/org/arquillian/cube/impl/util/Strings.java#L26-L40 | train |
arquillian/arquillian-cube | core/src/main/java/org/arquillian/cube/impl/util/Strings.java | Strings.splitAsList | public static List<String> splitAsList(String text, String delimiter) {
List<String> answer = new ArrayList<String>();
if (text != null && text.length() > 0) {
answer.addAll(Arrays.asList(text.split(delimiter)));
}
return answer;
} | java | public static List<String> splitAsList(String text, String delimiter) {
List<String> answer = new ArrayList<String>();
if (text != null && text.length() > 0) {
answer.addAll(Arrays.asList(text.split(delimiter)));
}
return answer;
} | [
"public",
"static",
"List",
"<",
"String",
">",
"splitAsList",
"(",
"String",
"text",
",",
"String",
"delimiter",
")",
"{",
"List",
"<",
"String",
">",
"answer",
"=",
"new",
"ArrayList",
"<",
"String",
">",
"(",
")",
";",
"if",
"(",
"text",
"!=",
"nu... | splits a string into a list of strings, ignoring the empty string | [
"splits",
"a",
"string",
"into",
"a",
"list",
"of",
"strings",
"ignoring",
"the",
"empty",
"string"
] | ce6b08062cc6ba2a68ecc29606bbae9acda5be13 | https://github.com/arquillian/arquillian-cube/blob/ce6b08062cc6ba2a68ecc29606bbae9acda5be13/core/src/main/java/org/arquillian/cube/impl/util/Strings.java#L45-L51 | train |
arquillian/arquillian-cube | core/src/main/java/org/arquillian/cube/impl/util/Strings.java | Strings.splitAndTrimAsList | public static List<String> splitAndTrimAsList(String text, String sep) {
ArrayList<String> answer = new ArrayList<>();
if (text != null && text.length() > 0) {
for (String v : text.split(sep)) {
String trim = v.trim();
if (trim.length() > 0) {
answer.add(trim);
}
}
}
return answer;
} | java | public static List<String> splitAndTrimAsList(String text, String sep) {
ArrayList<String> answer = new ArrayList<>();
if (text != null && text.length() > 0) {
for (String v : text.split(sep)) {
String trim = v.trim();
if (trim.length() > 0) {
answer.add(trim);
}
}
}
return answer;
} | [
"public",
"static",
"List",
"<",
"String",
">",
"splitAndTrimAsList",
"(",
"String",
"text",
",",
"String",
"sep",
")",
"{",
"ArrayList",
"<",
"String",
">",
"answer",
"=",
"new",
"ArrayList",
"<>",
"(",
")",
";",
"if",
"(",
"text",
"!=",
"null",
"&&",... | splits a string into a list of strings. Trims the results and ignores empty strings | [
"splits",
"a",
"string",
"into",
"a",
"list",
"of",
"strings",
".",
"Trims",
"the",
"results",
"and",
"ignores",
"empty",
"strings"
] | ce6b08062cc6ba2a68ecc29606bbae9acda5be13 | https://github.com/arquillian/arquillian-cube/blob/ce6b08062cc6ba2a68ecc29606bbae9acda5be13/core/src/main/java/org/arquillian/cube/impl/util/Strings.java#L56-L67 | train |
arquillian/arquillian-cube | openshift/openshift/src/main/java/org/arquillian/cube/openshift/impl/ext/TemplateContainerStarter.java | TemplateContainerStarter.waitForDeployments | public void waitForDeployments(@Observes(precedence = -100) AfterStart event, OpenShiftAdapter client,
CEEnvironmentProcessor.TemplateDetails details, TestClass testClass, CubeOpenShiftConfiguration configuration, OpenShiftClient openshiftClient)
throws Exception {
if (testClass == null) {
// nothing to do, since we're not in ClassScoped context
return;
}
if (details == null) {
log.warning(String.format("No environment for %s", testClass.getName()));
return;
}
log.info(String.format("Waiting for environment for %s", testClass.getName()));
try {
delay(client, details.getResources());
} catch (Throwable t) {
throw new IllegalArgumentException("Error waiting for template resources to deploy: " + testClass.getName(), t);
}
} | java | public void waitForDeployments(@Observes(precedence = -100) AfterStart event, OpenShiftAdapter client,
CEEnvironmentProcessor.TemplateDetails details, TestClass testClass, CubeOpenShiftConfiguration configuration, OpenShiftClient openshiftClient)
throws Exception {
if (testClass == null) {
// nothing to do, since we're not in ClassScoped context
return;
}
if (details == null) {
log.warning(String.format("No environment for %s", testClass.getName()));
return;
}
log.info(String.format("Waiting for environment for %s", testClass.getName()));
try {
delay(client, details.getResources());
} catch (Throwable t) {
throw new IllegalArgumentException("Error waiting for template resources to deploy: " + testClass.getName(), t);
}
} | [
"public",
"void",
"waitForDeployments",
"(",
"@",
"Observes",
"(",
"precedence",
"=",
"-",
"100",
")",
"AfterStart",
"event",
",",
"OpenShiftAdapter",
"client",
",",
"CEEnvironmentProcessor",
".",
"TemplateDetails",
"details",
",",
"TestClass",
"testClass",
",",
"... | Wait for the template resources to come up after the test container has
been started. This allows the test container and the template resources
to come up in parallel. | [
"Wait",
"for",
"the",
"template",
"resources",
"to",
"come",
"up",
"after",
"the",
"test",
"container",
"has",
"been",
"started",
".",
"This",
"allows",
"the",
"test",
"container",
"and",
"the",
"template",
"resources",
"to",
"come",
"up",
"in",
"parallel",
... | ce6b08062cc6ba2a68ecc29606bbae9acda5be13 | https://github.com/arquillian/arquillian-cube/blob/ce6b08062cc6ba2a68ecc29606bbae9acda5be13/openshift/openshift/src/main/java/org/arquillian/cube/openshift/impl/ext/TemplateContainerStarter.java#L25-L42 | train |
arquillian/arquillian-cube | docker/drone/src/main/java/org/arquillian/cube/docker/drone/util/IpAddressValidator.java | IpAddressValidator.validate | public static boolean validate(final String ip) {
Matcher matcher = pattern.matcher(ip);
return matcher.matches();
} | java | public static boolean validate(final String ip) {
Matcher matcher = pattern.matcher(ip);
return matcher.matches();
} | [
"public",
"static",
"boolean",
"validate",
"(",
"final",
"String",
"ip",
")",
"{",
"Matcher",
"matcher",
"=",
"pattern",
".",
"matcher",
"(",
"ip",
")",
";",
"return",
"matcher",
".",
"matches",
"(",
")",
";",
"}"
] | Validate ipv4 address with regular expression
@param ip
address for validation
@return true valid ip address, false invalid ip address | [
"Validate",
"ipv4",
"address",
"with",
"regular",
"expression"
] | ce6b08062cc6ba2a68ecc29606bbae9acda5be13 | https://github.com/arquillian/arquillian-cube/blob/ce6b08062cc6ba2a68ecc29606bbae9acda5be13/docker/drone/src/main/java/org/arquillian/cube/docker/drone/util/IpAddressValidator.java#L27-L30 | train |
spacecowboy/NoNonsense-FilePicker | examples/src/main/java/com/nononsenseapps/filepicker/examples/backbutton/BackHandlingFilePickerActivity.java | BackHandlingFilePickerActivity.getFragment | @Override
protected AbstractFilePickerFragment<File> getFragment(
final String startPath, final int mode, final boolean allowMultiple,
final boolean allowDirCreate, final boolean allowExistingFile,
final boolean singleClick) {
// startPath is allowed to be null.
// In that case, default folder should be SD-card and not "/"
String path = (startPath != null ? startPath
: Environment.getExternalStorageDirectory().getPath());
currentFragment = new BackHandlingFilePickerFragment();
currentFragment.setArgs(path, mode, allowMultiple, allowDirCreate,
allowExistingFile, singleClick);
return currentFragment;
} | java | @Override
protected AbstractFilePickerFragment<File> getFragment(
final String startPath, final int mode, final boolean allowMultiple,
final boolean allowDirCreate, final boolean allowExistingFile,
final boolean singleClick) {
// startPath is allowed to be null.
// In that case, default folder should be SD-card and not "/"
String path = (startPath != null ? startPath
: Environment.getExternalStorageDirectory().getPath());
currentFragment = new BackHandlingFilePickerFragment();
currentFragment.setArgs(path, mode, allowMultiple, allowDirCreate,
allowExistingFile, singleClick);
return currentFragment;
} | [
"@",
"Override",
"protected",
"AbstractFilePickerFragment",
"<",
"File",
">",
"getFragment",
"(",
"final",
"String",
"startPath",
",",
"final",
"int",
"mode",
",",
"final",
"boolean",
"allowMultiple",
",",
"final",
"boolean",
"allowDirCreate",
",",
"final",
"boole... | Return a copy of the new fragment and set the variable above. | [
"Return",
"a",
"copy",
"of",
"the",
"new",
"fragment",
"and",
"set",
"the",
"variable",
"above",
"."
] | 396ef7fa5e87791170791f9d94c78f6e42a7679a | https://github.com/spacecowboy/NoNonsense-FilePicker/blob/396ef7fa5e87791170791f9d94c78f6e42a7679a/examples/src/main/java/com/nononsenseapps/filepicker/examples/backbutton/BackHandlingFilePickerActivity.java#L20-L35 | train |
spacecowboy/NoNonsense-FilePicker | library/src/main/java/com/nononsenseapps/filepicker/FilePickerFragment.java | FilePickerFragment.getParent | @NonNull
@Override
public File getParent(@NonNull final File from) {
if (from.getPath().equals(getRoot().getPath())) {
// Already at root, we can't go higher
return from;
} else if (from.getParentFile() != null) {
return from.getParentFile();
} else {
return from;
}
} | java | @NonNull
@Override
public File getParent(@NonNull final File from) {
if (from.getPath().equals(getRoot().getPath())) {
// Already at root, we can't go higher
return from;
} else if (from.getParentFile() != null) {
return from.getParentFile();
} else {
return from;
}
} | [
"@",
"NonNull",
"@",
"Override",
"public",
"File",
"getParent",
"(",
"@",
"NonNull",
"final",
"File",
"from",
")",
"{",
"if",
"(",
"from",
".",
"getPath",
"(",
")",
".",
"equals",
"(",
"getRoot",
"(",
")",
".",
"getPath",
"(",
")",
")",
")",
"{",
... | Return the path to the parent directory. Should return the root if
from is root.
@param from either a file or directory
@return the parent directory | [
"Return",
"the",
"path",
"to",
"the",
"parent",
"directory",
".",
"Should",
"return",
"the",
"root",
"if",
"from",
"is",
"root",
"."
] | 396ef7fa5e87791170791f9d94c78f6e42a7679a | https://github.com/spacecowboy/NoNonsense-FilePicker/blob/396ef7fa5e87791170791f9d94c78f6e42a7679a/library/src/main/java/com/nononsenseapps/filepicker/FilePickerFragment.java#L145-L156 | train |
spacecowboy/NoNonsense-FilePicker | library/src/main/java/com/nononsenseapps/filepicker/FilePickerFragment.java | FilePickerFragment.getLoader | @NonNull
@Override
public Loader<SortedList<File>> getLoader() {
return new AsyncTaskLoader<SortedList<File>>(getActivity()) {
FileObserver fileObserver;
@Override
public SortedList<File> loadInBackground() {
File[] listFiles = mCurrentPath.listFiles();
final int initCap = listFiles == null ? 0 : listFiles.length;
SortedList<File> files = new SortedList<>(File.class, new SortedListAdapterCallback<File>(getDummyAdapter()) {
@Override
public int compare(File lhs, File rhs) {
return compareFiles(lhs, rhs);
}
@Override
public boolean areContentsTheSame(File file, File file2) {
return file.getAbsolutePath().equals(file2.getAbsolutePath()) && (file.isFile() == file2.isFile());
}
@Override
public boolean areItemsTheSame(File file, File file2) {
return areContentsTheSame(file, file2);
}
}, initCap);
files.beginBatchedUpdates();
if (listFiles != null) {
for (java.io.File f : listFiles) {
if (isItemVisible(f)) {
files.add(f);
}
}
}
files.endBatchedUpdates();
return files;
}
/**
* Handles a request to start the Loader.
*/
@Override
protected void onStartLoading() {
super.onStartLoading();
// handle if directory does not exist. Fall back to root.
if (mCurrentPath == null || !mCurrentPath.isDirectory()) {
mCurrentPath = getRoot();
}
// Start watching for changes
fileObserver = new FileObserver(mCurrentPath.getPath(),
FileObserver.CREATE |
FileObserver.DELETE
| FileObserver.MOVED_FROM | FileObserver.MOVED_TO
) {
@Override
public void onEvent(int event, String path) {
// Reload
onContentChanged();
}
};
fileObserver.startWatching();
forceLoad();
}
/**
* Handles a request to completely reset the Loader.
*/
@Override
protected void onReset() {
super.onReset();
// Stop watching
if (fileObserver != null) {
fileObserver.stopWatching();
fileObserver = null;
}
}
};
} | java | @NonNull
@Override
public Loader<SortedList<File>> getLoader() {
return new AsyncTaskLoader<SortedList<File>>(getActivity()) {
FileObserver fileObserver;
@Override
public SortedList<File> loadInBackground() {
File[] listFiles = mCurrentPath.listFiles();
final int initCap = listFiles == null ? 0 : listFiles.length;
SortedList<File> files = new SortedList<>(File.class, new SortedListAdapterCallback<File>(getDummyAdapter()) {
@Override
public int compare(File lhs, File rhs) {
return compareFiles(lhs, rhs);
}
@Override
public boolean areContentsTheSame(File file, File file2) {
return file.getAbsolutePath().equals(file2.getAbsolutePath()) && (file.isFile() == file2.isFile());
}
@Override
public boolean areItemsTheSame(File file, File file2) {
return areContentsTheSame(file, file2);
}
}, initCap);
files.beginBatchedUpdates();
if (listFiles != null) {
for (java.io.File f : listFiles) {
if (isItemVisible(f)) {
files.add(f);
}
}
}
files.endBatchedUpdates();
return files;
}
/**
* Handles a request to start the Loader.
*/
@Override
protected void onStartLoading() {
super.onStartLoading();
// handle if directory does not exist. Fall back to root.
if (mCurrentPath == null || !mCurrentPath.isDirectory()) {
mCurrentPath = getRoot();
}
// Start watching for changes
fileObserver = new FileObserver(mCurrentPath.getPath(),
FileObserver.CREATE |
FileObserver.DELETE
| FileObserver.MOVED_FROM | FileObserver.MOVED_TO
) {
@Override
public void onEvent(int event, String path) {
// Reload
onContentChanged();
}
};
fileObserver.startWatching();
forceLoad();
}
/**
* Handles a request to completely reset the Loader.
*/
@Override
protected void onReset() {
super.onReset();
// Stop watching
if (fileObserver != null) {
fileObserver.stopWatching();
fileObserver = null;
}
}
};
} | [
"@",
"NonNull",
"@",
"Override",
"public",
"Loader",
"<",
"SortedList",
"<",
"File",
">",
">",
"getLoader",
"(",
")",
"{",
"return",
"new",
"AsyncTaskLoader",
"<",
"SortedList",
"<",
"File",
">",
">",
"(",
"getActivity",
"(",
")",
")",
"{",
"FileObserver... | Get a loader that lists the Files in the current path,
and monitors changes. | [
"Get",
"a",
"loader",
"that",
"lists",
"the",
"Files",
"in",
"the",
"current",
"path",
"and",
"monitors",
"changes",
"."
] | 396ef7fa5e87791170791f9d94c78f6e42a7679a | https://github.com/spacecowboy/NoNonsense-FilePicker/blob/396ef7fa5e87791170791f9d94c78f6e42a7679a/library/src/main/java/com/nononsenseapps/filepicker/FilePickerFragment.java#L210-L297 | train |
spacecowboy/NoNonsense-FilePicker | library/src/main/java/com/nononsenseapps/filepicker/AbstractFilePickerFragment.java | AbstractFilePickerFragment.onLoadFinished | @Override
public void onLoadFinished(final Loader<SortedList<T>> loader,
final SortedList<T> data) {
isLoading = false;
mCheckedItems.clear();
mCheckedVisibleViewHolders.clear();
mFiles = data;
mAdapter.setList(data);
if (mCurrentDirView != null) {
mCurrentDirView.setText(getFullPath(mCurrentPath));
}
// Stop loading now to avoid a refresh clearing the user's selections
getLoaderManager().destroyLoader( 0 );
} | java | @Override
public void onLoadFinished(final Loader<SortedList<T>> loader,
final SortedList<T> data) {
isLoading = false;
mCheckedItems.clear();
mCheckedVisibleViewHolders.clear();
mFiles = data;
mAdapter.setList(data);
if (mCurrentDirView != null) {
mCurrentDirView.setText(getFullPath(mCurrentPath));
}
// Stop loading now to avoid a refresh clearing the user's selections
getLoaderManager().destroyLoader( 0 );
} | [
"@",
"Override",
"public",
"void",
"onLoadFinished",
"(",
"final",
"Loader",
"<",
"SortedList",
"<",
"T",
">",
">",
"loader",
",",
"final",
"SortedList",
"<",
"T",
">",
"data",
")",
"{",
"isLoading",
"=",
"false",
";",
"mCheckedItems",
".",
"clear",
"(",... | Called when a previously created loader has finished its load.
@param loader The Loader that has finished.
@param data The data generated by the Loader. | [
"Called",
"when",
"a",
"previously",
"created",
"loader",
"has",
"finished",
"its",
"load",
"."
] | 396ef7fa5e87791170791f9d94c78f6e42a7679a | https://github.com/spacecowboy/NoNonsense-FilePicker/blob/396ef7fa5e87791170791f9d94c78f6e42a7679a/library/src/main/java/com/nononsenseapps/filepicker/AbstractFilePickerFragment.java#L575-L588 | train |
spacecowboy/NoNonsense-FilePicker | library/src/main/java/com/nononsenseapps/filepicker/AbstractFilePickerFragment.java | AbstractFilePickerFragment.clearSelections | public void clearSelections() {
for (CheckableViewHolder vh : mCheckedVisibleViewHolders) {
vh.checkbox.setChecked(false);
}
mCheckedVisibleViewHolders.clear();
mCheckedItems.clear();
} | java | public void clearSelections() {
for (CheckableViewHolder vh : mCheckedVisibleViewHolders) {
vh.checkbox.setChecked(false);
}
mCheckedVisibleViewHolders.clear();
mCheckedItems.clear();
} | [
"public",
"void",
"clearSelections",
"(",
")",
"{",
"for",
"(",
"CheckableViewHolder",
"vh",
":",
"mCheckedVisibleViewHolders",
")",
"{",
"vh",
".",
"checkbox",
".",
"setChecked",
"(",
"false",
")",
";",
"}",
"mCheckedVisibleViewHolders",
".",
"clear",
"(",
")... | Animate de-selection of visible views and clear
selected set. | [
"Animate",
"de",
"-",
"selection",
"of",
"visible",
"views",
"and",
"clear",
"selected",
"set",
"."
] | 396ef7fa5e87791170791f9d94c78f6e42a7679a | https://github.com/spacecowboy/NoNonsense-FilePicker/blob/396ef7fa5e87791170791f9d94c78f6e42a7679a/library/src/main/java/com/nononsenseapps/filepicker/AbstractFilePickerFragment.java#L674-L680 | train |
spacecowboy/NoNonsense-FilePicker | sample/src/main/java/com/nononsenseapps/filepicker/sample/multimedia/MultimediaPickerFragment.java | MultimediaPickerFragment.isMultimedia | protected boolean isMultimedia(File file) {
//noinspection SimplifiableIfStatement
if (isDir(file)) {
return false;
}
String path = file.getPath().toLowerCase();
for (String ext : MULTIMEDIA_EXTENSIONS) {
if (path.endsWith(ext)) {
return true;
}
}
return false;
} | java | protected boolean isMultimedia(File file) {
//noinspection SimplifiableIfStatement
if (isDir(file)) {
return false;
}
String path = file.getPath().toLowerCase();
for (String ext : MULTIMEDIA_EXTENSIONS) {
if (path.endsWith(ext)) {
return true;
}
}
return false;
} | [
"protected",
"boolean",
"isMultimedia",
"(",
"File",
"file",
")",
"{",
"//noinspection SimplifiableIfStatement",
"if",
"(",
"isDir",
"(",
"file",
")",
")",
"{",
"return",
"false",
";",
"}",
"String",
"path",
"=",
"file",
".",
"getPath",
"(",
")",
".",
"toL... | An extremely simple method for identifying multimedia. This
could be improved, but it's good enough for this example.
@param file which could be an image or a video
@return true if the file can be previewed, false otherwise | [
"An",
"extremely",
"simple",
"method",
"for",
"identifying",
"multimedia",
".",
"This",
"could",
"be",
"improved",
"but",
"it",
"s",
"good",
"enough",
"for",
"this",
"example",
"."
] | 396ef7fa5e87791170791f9d94c78f6e42a7679a | https://github.com/spacecowboy/NoNonsense-FilePicker/blob/396ef7fa5e87791170791f9d94c78f6e42a7679a/sample/src/main/java/com/nononsenseapps/filepicker/sample/multimedia/MultimediaPickerFragment.java#L51-L65 | train |
spacecowboy/NoNonsense-FilePicker | sample/src/main/java/com/nononsenseapps/filepicker/sample/ftp/FtpPickerFragment.java | FtpPickerFragment.getLoader | @NonNull
@Override
public Loader<SortedList<FtpFile>> getLoader() {
return new AsyncTaskLoader<SortedList<FtpFile>>(getContext()) {
@Override
public SortedList<FtpFile> loadInBackground() {
SortedList<FtpFile> sortedList = new SortedList<>(FtpFile.class, new SortedListAdapterCallback<FtpFile>(getDummyAdapter()) {
@Override
public int compare(FtpFile lhs, FtpFile rhs) {
if (lhs.isDirectory() && !rhs.isDirectory()) {
return -1;
} else if (rhs.isDirectory() && !lhs.isDirectory()) {
return 1;
} else {
return lhs.getName().compareToIgnoreCase(rhs.getName());
}
}
@Override
public boolean areContentsTheSame(FtpFile oldItem, FtpFile newItem) {
return oldItem.getName().equals(newItem.getName());
}
@Override
public boolean areItemsTheSame(FtpFile item1, FtpFile item2) {
return item1.getName().equals(item2.getName());
}
});
if (!ftp.isConnected()) {
// Connect
try {
ftp.connect(server, port);
ftp.setFileType(FTP.ASCII_FILE_TYPE);
ftp.enterLocalPassiveMode();
ftp.setUseEPSVwithIPv4(false);
if (!(loggedIn = ftp.login(username, password))) {
ftp.logout();
Log.e(TAG, "Login failed");
}
} catch (IOException e) {
if (ftp.isConnected()) {
try {
ftp.disconnect();
} catch (IOException ignored) {
}
}
Log.e(TAG, "Could not connect to server.");
}
}
if (loggedIn) {
try {
// handle if directory does not exist. Fall back to root.
if (mCurrentPath == null || !mCurrentPath.isDirectory()) {
mCurrentPath = getRoot();
}
sortedList.beginBatchedUpdates();
for (FTPFile f : ftp.listFiles(mCurrentPath.getPath())) {
FtpFile file;
if (f.isDirectory()) {
file = new FtpDir(mCurrentPath, f.getName());
} else {
file = new FtpFile(mCurrentPath, f.getName());
}
if (isItemVisible(file)) {
sortedList.add(file);
}
}
sortedList.endBatchedUpdates();
} catch (IOException e) {
Log.e(TAG, "IOException: " + e.getMessage());
}
}
return sortedList;
}
/**
* Handles a request to start the Loader.
*/
@Override
protected void onStartLoading() {
super.onStartLoading();
// handle if directory does not exist. Fall back to root.
if (mCurrentPath == null || !mCurrentPath.isDirectory()) {
mCurrentPath = getRoot();
}
forceLoad();
}
};
} | java | @NonNull
@Override
public Loader<SortedList<FtpFile>> getLoader() {
return new AsyncTaskLoader<SortedList<FtpFile>>(getContext()) {
@Override
public SortedList<FtpFile> loadInBackground() {
SortedList<FtpFile> sortedList = new SortedList<>(FtpFile.class, new SortedListAdapterCallback<FtpFile>(getDummyAdapter()) {
@Override
public int compare(FtpFile lhs, FtpFile rhs) {
if (lhs.isDirectory() && !rhs.isDirectory()) {
return -1;
} else if (rhs.isDirectory() && !lhs.isDirectory()) {
return 1;
} else {
return lhs.getName().compareToIgnoreCase(rhs.getName());
}
}
@Override
public boolean areContentsTheSame(FtpFile oldItem, FtpFile newItem) {
return oldItem.getName().equals(newItem.getName());
}
@Override
public boolean areItemsTheSame(FtpFile item1, FtpFile item2) {
return item1.getName().equals(item2.getName());
}
});
if (!ftp.isConnected()) {
// Connect
try {
ftp.connect(server, port);
ftp.setFileType(FTP.ASCII_FILE_TYPE);
ftp.enterLocalPassiveMode();
ftp.setUseEPSVwithIPv4(false);
if (!(loggedIn = ftp.login(username, password))) {
ftp.logout();
Log.e(TAG, "Login failed");
}
} catch (IOException e) {
if (ftp.isConnected()) {
try {
ftp.disconnect();
} catch (IOException ignored) {
}
}
Log.e(TAG, "Could not connect to server.");
}
}
if (loggedIn) {
try {
// handle if directory does not exist. Fall back to root.
if (mCurrentPath == null || !mCurrentPath.isDirectory()) {
mCurrentPath = getRoot();
}
sortedList.beginBatchedUpdates();
for (FTPFile f : ftp.listFiles(mCurrentPath.getPath())) {
FtpFile file;
if (f.isDirectory()) {
file = new FtpDir(mCurrentPath, f.getName());
} else {
file = new FtpFile(mCurrentPath, f.getName());
}
if (isItemVisible(file)) {
sortedList.add(file);
}
}
sortedList.endBatchedUpdates();
} catch (IOException e) {
Log.e(TAG, "IOException: " + e.getMessage());
}
}
return sortedList;
}
/**
* Handles a request to start the Loader.
*/
@Override
protected void onStartLoading() {
super.onStartLoading();
// handle if directory does not exist. Fall back to root.
if (mCurrentPath == null || !mCurrentPath.isDirectory()) {
mCurrentPath = getRoot();
}
forceLoad();
}
};
} | [
"@",
"NonNull",
"@",
"Override",
"public",
"Loader",
"<",
"SortedList",
"<",
"FtpFile",
">",
">",
"getLoader",
"(",
")",
"{",
"return",
"new",
"AsyncTaskLoader",
"<",
"SortedList",
"<",
"FtpFile",
">",
">",
"(",
"getContext",
"(",
")",
")",
"{",
"@",
"... | Get a loader that lists the files in the current path,
and monitors changes. | [
"Get",
"a",
"loader",
"that",
"lists",
"the",
"files",
"in",
"the",
"current",
"path",
"and",
"monitors",
"changes",
"."
] | 396ef7fa5e87791170791f9d94c78f6e42a7679a | https://github.com/spacecowboy/NoNonsense-FilePicker/blob/396ef7fa5e87791170791f9d94c78f6e42a7679a/sample/src/main/java/com/nononsenseapps/filepicker/sample/ftp/FtpPickerFragment.java#L203-L300 | train |
line/centraldogma | server/src/main/java/com/linecorp/centraldogma/server/internal/metadata/UserAndTimestamp.java | UserAndTimestamp.timestamp | @JsonProperty
public String timestamp() {
if (timestampAsText == null) {
timestampAsText = DateTimeFormatter.ISO_INSTANT.format(timestamp);
}
return timestampAsText;
} | java | @JsonProperty
public String timestamp() {
if (timestampAsText == null) {
timestampAsText = DateTimeFormatter.ISO_INSTANT.format(timestamp);
}
return timestampAsText;
} | [
"@",
"JsonProperty",
"public",
"String",
"timestamp",
"(",
")",
"{",
"if",
"(",
"timestampAsText",
"==",
"null",
")",
"{",
"timestampAsText",
"=",
"DateTimeFormatter",
".",
"ISO_INSTANT",
".",
"format",
"(",
"timestamp",
")",
";",
"}",
"return",
"timestampAsTe... | Returns a date and time string which is formatted as ISO-8601. | [
"Returns",
"a",
"date",
"and",
"time",
"string",
"which",
"is",
"formatted",
"as",
"ISO",
"-",
"8601",
"."
] | b9e46c67fbc26628c2186ce2f46e7fb303c831e9 | https://github.com/line/centraldogma/blob/b9e46c67fbc26628c2186ce2f46e7fb303c831e9/server/src/main/java/com/linecorp/centraldogma/server/internal/metadata/UserAndTimestamp.java#L70-L76 | train |
line/centraldogma | server/src/main/java/com/linecorp/centraldogma/server/CentralDogma.java | CentralDogma.forConfig | public static CentralDogma forConfig(File configFile) throws IOException {
requireNonNull(configFile, "configFile");
return new CentralDogma(Jackson.readValue(configFile, CentralDogmaConfig.class));
} | java | public static CentralDogma forConfig(File configFile) throws IOException {
requireNonNull(configFile, "configFile");
return new CentralDogma(Jackson.readValue(configFile, CentralDogmaConfig.class));
} | [
"public",
"static",
"CentralDogma",
"forConfig",
"(",
"File",
"configFile",
")",
"throws",
"IOException",
"{",
"requireNonNull",
"(",
"configFile",
",",
"\"configFile\"",
")",
";",
"return",
"new",
"CentralDogma",
"(",
"Jackson",
".",
"readValue",
"(",
"configFile... | Creates a new instance from the given configuration file.
@throws IOException if failed to load the configuration from the specified file | [
"Creates",
"a",
"new",
"instance",
"from",
"the",
"given",
"configuration",
"file",
"."
] | b9e46c67fbc26628c2186ce2f46e7fb303c831e9 | https://github.com/line/centraldogma/blob/b9e46c67fbc26628c2186ce2f46e7fb303c831e9/server/src/main/java/com/linecorp/centraldogma/server/CentralDogma.java#L179-L182 | train |
line/centraldogma | server/src/main/java/com/linecorp/centraldogma/server/CentralDogma.java | CentralDogma.activePort | public Optional<ServerPort> activePort() {
final Server server = this.server;
return server != null ? server.activePort() : Optional.empty();
} | java | public Optional<ServerPort> activePort() {
final Server server = this.server;
return server != null ? server.activePort() : Optional.empty();
} | [
"public",
"Optional",
"<",
"ServerPort",
">",
"activePort",
"(",
")",
"{",
"final",
"Server",
"server",
"=",
"this",
".",
"server",
";",
"return",
"server",
"!=",
"null",
"?",
"server",
".",
"activePort",
"(",
")",
":",
"Optional",
".",
"empty",
"(",
"... | Returns the primary port of the server.
@return the primary {@link ServerPort} if the server is started. {@link Optional#empty()} otherwise. | [
"Returns",
"the",
"primary",
"port",
"of",
"the",
"server",
"."
] | b9e46c67fbc26628c2186ce2f46e7fb303c831e9 | https://github.com/line/centraldogma/blob/b9e46c67fbc26628c2186ce2f46e7fb303c831e9/server/src/main/java/com/linecorp/centraldogma/server/CentralDogma.java#L230-L233 | train |
line/centraldogma | server/src/main/java/com/linecorp/centraldogma/server/CentralDogma.java | CentralDogma.activePorts | public Map<InetSocketAddress, ServerPort> activePorts() {
final Server server = this.server;
if (server != null) {
return server.activePorts();
} else {
return Collections.emptyMap();
}
} | java | public Map<InetSocketAddress, ServerPort> activePorts() {
final Server server = this.server;
if (server != null) {
return server.activePorts();
} else {
return Collections.emptyMap();
}
} | [
"public",
"Map",
"<",
"InetSocketAddress",
",",
"ServerPort",
">",
"activePorts",
"(",
")",
"{",
"final",
"Server",
"server",
"=",
"this",
".",
"server",
";",
"if",
"(",
"server",
"!=",
"null",
")",
"{",
"return",
"server",
".",
"activePorts",
"(",
")",
... | Returns the ports of the server.
@return the {@link Map} which contains the pairs of local {@link InetSocketAddress} and
{@link ServerPort} is the server is started. {@link Optional#empty()} otherwise. | [
"Returns",
"the",
"ports",
"of",
"the",
"server",
"."
] | b9e46c67fbc26628c2186ce2f46e7fb303c831e9 | https://github.com/line/centraldogma/blob/b9e46c67fbc26628c2186ce2f46e7fb303c831e9/server/src/main/java/com/linecorp/centraldogma/server/CentralDogma.java#L241-L248 | train |
line/centraldogma | server/src/main/java/com/linecorp/centraldogma/server/CentralDogma.java | CentralDogma.stop | public CompletableFuture<Void> stop() {
numPendingStopRequests.incrementAndGet();
return startStop.stop().thenRun(numPendingStopRequests::decrementAndGet);
} | java | public CompletableFuture<Void> stop() {
numPendingStopRequests.incrementAndGet();
return startStop.stop().thenRun(numPendingStopRequests::decrementAndGet);
} | [
"public",
"CompletableFuture",
"<",
"Void",
">",
"stop",
"(",
")",
"{",
"numPendingStopRequests",
".",
"incrementAndGet",
"(",
")",
";",
"return",
"startStop",
".",
"stop",
"(",
")",
".",
"thenRun",
"(",
"numPendingStopRequests",
"::",
"decrementAndGet",
")",
... | Stops the server. This method does nothing if the server is stopped already. | [
"Stops",
"the",
"server",
".",
"This",
"method",
"does",
"nothing",
"if",
"the",
"server",
"is",
"stopped",
"already",
"."
] | b9e46c67fbc26628c2186ce2f46e7fb303c831e9 | https://github.com/line/centraldogma/blob/b9e46c67fbc26628c2186ce2f46e7fb303c831e9/server/src/main/java/com/linecorp/centraldogma/server/CentralDogma.java#L300-L303 | train |
line/centraldogma | server/src/main/java/com/linecorp/centraldogma/server/internal/storage/project/ProjectInitializer.java | ProjectInitializer.initializeInternalProject | public static void initializeInternalProject(CommandExecutor executor) {
final long creationTimeMillis = System.currentTimeMillis();
try {
executor.execute(createProject(creationTimeMillis, Author.SYSTEM, INTERNAL_PROJ))
.get();
} catch (Throwable cause) {
cause = Exceptions.peel(cause);
if (!(cause instanceof ProjectExistsException)) {
throw new Error("failed to initialize an internal project", cause);
}
}
// These repositories might be created when creating an internal project, but we try to create them
// again here in order to make sure them exist because sometimes their names are changed.
for (final String repo : ImmutableList.of(Project.REPO_META, Project.REPO_DOGMA)) {
try {
executor.execute(createRepository(creationTimeMillis, Author.SYSTEM, INTERNAL_PROJ, repo))
.get();
} catch (Throwable cause) {
cause = Exceptions.peel(cause);
if (!(cause instanceof RepositoryExistsException)) {
throw new Error(cause);
}
}
}
} | java | public static void initializeInternalProject(CommandExecutor executor) {
final long creationTimeMillis = System.currentTimeMillis();
try {
executor.execute(createProject(creationTimeMillis, Author.SYSTEM, INTERNAL_PROJ))
.get();
} catch (Throwable cause) {
cause = Exceptions.peel(cause);
if (!(cause instanceof ProjectExistsException)) {
throw new Error("failed to initialize an internal project", cause);
}
}
// These repositories might be created when creating an internal project, but we try to create them
// again here in order to make sure them exist because sometimes their names are changed.
for (final String repo : ImmutableList.of(Project.REPO_META, Project.REPO_DOGMA)) {
try {
executor.execute(createRepository(creationTimeMillis, Author.SYSTEM, INTERNAL_PROJ, repo))
.get();
} catch (Throwable cause) {
cause = Exceptions.peel(cause);
if (!(cause instanceof RepositoryExistsException)) {
throw new Error(cause);
}
}
}
} | [
"public",
"static",
"void",
"initializeInternalProject",
"(",
"CommandExecutor",
"executor",
")",
"{",
"final",
"long",
"creationTimeMillis",
"=",
"System",
".",
"currentTimeMillis",
"(",
")",
";",
"try",
"{",
"executor",
".",
"execute",
"(",
"createProject",
"(",... | Creates an internal project and repositories such as a token storage. | [
"Creates",
"an",
"internal",
"project",
"and",
"repositories",
"such",
"as",
"a",
"token",
"storage",
"."
] | b9e46c67fbc26628c2186ce2f46e7fb303c831e9 | https://github.com/line/centraldogma/blob/b9e46c67fbc26628c2186ce2f46e7fb303c831e9/server/src/main/java/com/linecorp/centraldogma/server/internal/storage/project/ProjectInitializer.java#L38-L62 | train |
line/centraldogma | server/src/main/java/com/linecorp/centraldogma/server/internal/replication/ZooKeeperCommandExecutor.java | ZooKeeperCommandExecutor.doExecute | @Override
protected <T> CompletableFuture<T> doExecute(Command<T> command) throws Exception {
final CompletableFuture<T> future = new CompletableFuture<>();
executor.execute(() -> {
try {
future.complete(blockingExecute(command));
} catch (Throwable t) {
future.completeExceptionally(t);
}
});
return future;
} | java | @Override
protected <T> CompletableFuture<T> doExecute(Command<T> command) throws Exception {
final CompletableFuture<T> future = new CompletableFuture<>();
executor.execute(() -> {
try {
future.complete(blockingExecute(command));
} catch (Throwable t) {
future.completeExceptionally(t);
}
});
return future;
} | [
"@",
"Override",
"protected",
"<",
"T",
">",
"CompletableFuture",
"<",
"T",
">",
"doExecute",
"(",
"Command",
"<",
"T",
">",
"command",
")",
"throws",
"Exception",
"{",
"final",
"CompletableFuture",
"<",
"T",
">",
"future",
"=",
"new",
"CompletableFuture",
... | Ensure that all logs are replayed, any other logs can not be added before end of this function. | [
"Ensure",
"that",
"all",
"logs",
"are",
"replayed",
"any",
"other",
"logs",
"can",
"not",
"be",
"added",
"before",
"end",
"of",
"this",
"function",
"."
] | b9e46c67fbc26628c2186ce2f46e7fb303c831e9 | https://github.com/line/centraldogma/blob/b9e46c67fbc26628c2186ce2f46e7fb303c831e9/server/src/main/java/com/linecorp/centraldogma/server/internal/replication/ZooKeeperCommandExecutor.java#L830-L841 | train |
line/centraldogma | common/src/main/java/com/linecorp/centraldogma/internal/api/v1/WatchTimeout.java | WatchTimeout.makeReasonable | public static long makeReasonable(long expectedTimeoutMillis, long bufferMillis) {
checkArgument(expectedTimeoutMillis > 0,
"expectedTimeoutMillis: %s (expected: > 0)", expectedTimeoutMillis);
checkArgument(bufferMillis >= 0,
"bufferMillis: %s (expected: > 0)", bufferMillis);
final long timeout = Math.min(expectedTimeoutMillis, MAX_MILLIS);
if (bufferMillis == 0) {
return timeout;
}
if (timeout > MAX_MILLIS - bufferMillis) {
return MAX_MILLIS;
} else {
return bufferMillis + timeout;
}
} | java | public static long makeReasonable(long expectedTimeoutMillis, long bufferMillis) {
checkArgument(expectedTimeoutMillis > 0,
"expectedTimeoutMillis: %s (expected: > 0)", expectedTimeoutMillis);
checkArgument(bufferMillis >= 0,
"bufferMillis: %s (expected: > 0)", bufferMillis);
final long timeout = Math.min(expectedTimeoutMillis, MAX_MILLIS);
if (bufferMillis == 0) {
return timeout;
}
if (timeout > MAX_MILLIS - bufferMillis) {
return MAX_MILLIS;
} else {
return bufferMillis + timeout;
}
} | [
"public",
"static",
"long",
"makeReasonable",
"(",
"long",
"expectedTimeoutMillis",
",",
"long",
"bufferMillis",
")",
"{",
"checkArgument",
"(",
"expectedTimeoutMillis",
">",
"0",
",",
"\"expectedTimeoutMillis: %s (expected: > 0)\"",
",",
"expectedTimeoutMillis",
")",
";"... | Returns a reasonable timeout duration for a watch request.
@param expectedTimeoutMillis timeout duration that a user wants to use, in milliseconds
@param bufferMillis buffer duration which needs to be added, in milliseconds
@return timeout duration in milliseconds, between the specified {@code bufferMillis} and
the {@link #MAX_MILLIS}. | [
"Returns",
"a",
"reasonable",
"timeout",
"duration",
"for",
"a",
"watch",
"request",
"."
] | b9e46c67fbc26628c2186ce2f46e7fb303c831e9 | https://github.com/line/centraldogma/blob/b9e46c67fbc26628c2186ce2f46e7fb303c831e9/common/src/main/java/com/linecorp/centraldogma/internal/api/v1/WatchTimeout.java#L49-L65 | train |
line/centraldogma | server/src/main/java/com/linecorp/centraldogma/server/CentralDogmaBuilder.java | CentralDogmaBuilder.port | public CentralDogmaBuilder port(InetSocketAddress localAddress, SessionProtocol protocol) {
return port(new ServerPort(localAddress, protocol));
} | java | public CentralDogmaBuilder port(InetSocketAddress localAddress, SessionProtocol protocol) {
return port(new ServerPort(localAddress, protocol));
} | [
"public",
"CentralDogmaBuilder",
"port",
"(",
"InetSocketAddress",
"localAddress",
",",
"SessionProtocol",
"protocol",
")",
"{",
"return",
"port",
"(",
"new",
"ServerPort",
"(",
"localAddress",
",",
"protocol",
")",
")",
";",
"}"
] | Adds a port that serves the HTTP requests. If unspecified, cleartext HTTP on port 36462 is used.
@param localAddress the TCP/IP load address to bind
@param protocol {@link SessionProtocol#HTTP} or {@link SessionProtocol#HTTPS} | [
"Adds",
"a",
"port",
"that",
"serves",
"the",
"HTTP",
"requests",
".",
"If",
"unspecified",
"cleartext",
"HTTP",
"on",
"port",
"36462",
"is",
"used",
"."
] | b9e46c67fbc26628c2186ce2f46e7fb303c831e9 | https://github.com/line/centraldogma/blob/b9e46c67fbc26628c2186ce2f46e7fb303c831e9/server/src/main/java/com/linecorp/centraldogma/server/CentralDogmaBuilder.java#L142-L144 | train |
line/centraldogma | server/src/main/java/com/linecorp/centraldogma/server/internal/storage/repository/git/GitRepository.java | GitRepository.close | void close(Supplier<CentralDogmaException> failureCauseSupplier) {
requireNonNull(failureCauseSupplier, "failureCauseSupplier");
if (closePending.compareAndSet(null, failureCauseSupplier)) {
repositoryWorker.execute(() -> {
rwLock.writeLock().lock();
try {
if (commitIdDatabase != null) {
try {
commitIdDatabase.close();
} catch (Exception e) {
logger.warn("Failed to close a commitId database:", e);
}
}
if (jGitRepository != null) {
try {
jGitRepository.close();
} catch (Exception e) {
logger.warn("Failed to close a Git repository: {}",
jGitRepository.getDirectory(), e);
}
}
} finally {
rwLock.writeLock().unlock();
commitWatchers.close(failureCauseSupplier);
closeFuture.complete(null);
}
});
}
closeFuture.join();
} | java | void close(Supplier<CentralDogmaException> failureCauseSupplier) {
requireNonNull(failureCauseSupplier, "failureCauseSupplier");
if (closePending.compareAndSet(null, failureCauseSupplier)) {
repositoryWorker.execute(() -> {
rwLock.writeLock().lock();
try {
if (commitIdDatabase != null) {
try {
commitIdDatabase.close();
} catch (Exception e) {
logger.warn("Failed to close a commitId database:", e);
}
}
if (jGitRepository != null) {
try {
jGitRepository.close();
} catch (Exception e) {
logger.warn("Failed to close a Git repository: {}",
jGitRepository.getDirectory(), e);
}
}
} finally {
rwLock.writeLock().unlock();
commitWatchers.close(failureCauseSupplier);
closeFuture.complete(null);
}
});
}
closeFuture.join();
} | [
"void",
"close",
"(",
"Supplier",
"<",
"CentralDogmaException",
">",
"failureCauseSupplier",
")",
"{",
"requireNonNull",
"(",
"failureCauseSupplier",
",",
"\"failureCauseSupplier\"",
")",
";",
"if",
"(",
"closePending",
".",
"compareAndSet",
"(",
"null",
",",
"failu... | Waits until all pending operations are complete and closes this repository.
@param failureCauseSupplier the {@link Supplier} that creates a new {@link CentralDogmaException}
which will be used to fail the operations issued after this method is called | [
"Waits",
"until",
"all",
"pending",
"operations",
"are",
"complete",
"and",
"closes",
"this",
"repository",
"."
] | b9e46c67fbc26628c2186ce2f46e7fb303c831e9 | https://github.com/line/centraldogma/blob/b9e46c67fbc26628c2186ce2f46e7fb303c831e9/server/src/main/java/com/linecorp/centraldogma/server/internal/storage/repository/git/GitRepository.java#L333-L364 | train |
line/centraldogma | server/src/main/java/com/linecorp/centraldogma/server/internal/storage/repository/git/GitRepository.java | GitRepository.diff | @Override
public CompletableFuture<Map<String, Change<?>>> diff(Revision from, Revision to, String pathPattern) {
final ServiceRequestContext ctx = context();
return CompletableFuture.supplyAsync(() -> {
requireNonNull(from, "from");
requireNonNull(to, "to");
requireNonNull(pathPattern, "pathPattern");
failFastIfTimedOut(this, logger, ctx, "diff", from, to, pathPattern);
final RevisionRange range = normalizeNow(from, to).toAscending();
readLock();
try (RevWalk rw = new RevWalk(jGitRepository)) {
final RevTree treeA = rw.parseTree(commitIdDatabase.get(range.from()));
final RevTree treeB = rw.parseTree(commitIdDatabase.get(range.to()));
// Compare the two Git trees.
// Note that we do not cache here because CachingRepository caches the final result already.
return toChangeMap(blockingCompareTreesUncached(treeA, treeB,
pathPatternFilterOrTreeFilter(pathPattern)));
} catch (StorageException e) {
throw e;
} catch (Exception e) {
throw new StorageException("failed to parse two trees: range=" + range, e);
} finally {
readUnlock();
}
}, repositoryWorker);
} | java | @Override
public CompletableFuture<Map<String, Change<?>>> diff(Revision from, Revision to, String pathPattern) {
final ServiceRequestContext ctx = context();
return CompletableFuture.supplyAsync(() -> {
requireNonNull(from, "from");
requireNonNull(to, "to");
requireNonNull(pathPattern, "pathPattern");
failFastIfTimedOut(this, logger, ctx, "diff", from, to, pathPattern);
final RevisionRange range = normalizeNow(from, to).toAscending();
readLock();
try (RevWalk rw = new RevWalk(jGitRepository)) {
final RevTree treeA = rw.parseTree(commitIdDatabase.get(range.from()));
final RevTree treeB = rw.parseTree(commitIdDatabase.get(range.to()));
// Compare the two Git trees.
// Note that we do not cache here because CachingRepository caches the final result already.
return toChangeMap(blockingCompareTreesUncached(treeA, treeB,
pathPatternFilterOrTreeFilter(pathPattern)));
} catch (StorageException e) {
throw e;
} catch (Exception e) {
throw new StorageException("failed to parse two trees: range=" + range, e);
} finally {
readUnlock();
}
}, repositoryWorker);
} | [
"@",
"Override",
"public",
"CompletableFuture",
"<",
"Map",
"<",
"String",
",",
"Change",
"<",
"?",
">",
">",
">",
"diff",
"(",
"Revision",
"from",
",",
"Revision",
"to",
",",
"String",
"pathPattern",
")",
"{",
"final",
"ServiceRequestContext",
"ctx",
"=",... | Get the diff between any two valid revisions.
@param from revision from
@param to revision to
@param pathPattern target path pattern
@return the map of changes mapped by path
@throws StorageException if {@code from} or {@code to} does not exist. | [
"Get",
"the",
"diff",
"between",
"any",
"two",
"valid",
"revisions",
"."
] | b9e46c67fbc26628c2186ce2f46e7fb303c831e9 | https://github.com/line/centraldogma/blob/b9e46c67fbc26628c2186ce2f46e7fb303c831e9/server/src/main/java/com/linecorp/centraldogma/server/internal/storage/repository/git/GitRepository.java#L655-L683 | train |
line/centraldogma | server/src/main/java/com/linecorp/centraldogma/server/internal/storage/repository/git/GitRepository.java | GitRepository.uncachedHeadRevision | private Revision uncachedHeadRevision() {
try (RevWalk revWalk = new RevWalk(jGitRepository)) {
final ObjectId headRevisionId = jGitRepository.resolve(R_HEADS_MASTER);
if (headRevisionId != null) {
final RevCommit revCommit = revWalk.parseCommit(headRevisionId);
return CommitUtil.extractRevision(revCommit.getFullMessage());
}
} catch (CentralDogmaException e) {
throw e;
} catch (Exception e) {
throw new StorageException("failed to get the current revision", e);
}
throw new StorageException("failed to determine the HEAD: " + jGitRepository.getDirectory());
} | java | private Revision uncachedHeadRevision() {
try (RevWalk revWalk = new RevWalk(jGitRepository)) {
final ObjectId headRevisionId = jGitRepository.resolve(R_HEADS_MASTER);
if (headRevisionId != null) {
final RevCommit revCommit = revWalk.parseCommit(headRevisionId);
return CommitUtil.extractRevision(revCommit.getFullMessage());
}
} catch (CentralDogmaException e) {
throw e;
} catch (Exception e) {
throw new StorageException("failed to get the current revision", e);
}
throw new StorageException("failed to determine the HEAD: " + jGitRepository.getDirectory());
} | [
"private",
"Revision",
"uncachedHeadRevision",
"(",
")",
"{",
"try",
"(",
"RevWalk",
"revWalk",
"=",
"new",
"RevWalk",
"(",
"jGitRepository",
")",
")",
"{",
"final",
"ObjectId",
"headRevisionId",
"=",
"jGitRepository",
".",
"resolve",
"(",
"R_HEADS_MASTER",
")",... | Returns the current revision. | [
"Returns",
"the",
"current",
"revision",
"."
] | b9e46c67fbc26628c2186ce2f46e7fb303c831e9 | https://github.com/line/centraldogma/blob/b9e46c67fbc26628c2186ce2f46e7fb303c831e9/server/src/main/java/com/linecorp/centraldogma/server/internal/storage/repository/git/GitRepository.java#L1443-L1457 | train |
line/centraldogma | common/src/main/java/com/linecorp/centraldogma/internal/Util.java | Util.simpleTypeName | public static String simpleTypeName(Object obj) {
if (obj == null) {
return "null";
}
return simpleTypeName(obj.getClass(), false);
} | java | public static String simpleTypeName(Object obj) {
if (obj == null) {
return "null";
}
return simpleTypeName(obj.getClass(), false);
} | [
"public",
"static",
"String",
"simpleTypeName",
"(",
"Object",
"obj",
")",
"{",
"if",
"(",
"obj",
"==",
"null",
")",
"{",
"return",
"\"null\"",
";",
"}",
"return",
"simpleTypeName",
"(",
"obj",
".",
"getClass",
"(",
")",
",",
"false",
")",
";",
"}"
] | Returns the simplified name of the type of the specified object. | [
"Returns",
"the",
"simplified",
"name",
"of",
"the",
"type",
"of",
"the",
"specified",
"object",
"."
] | b9e46c67fbc26628c2186ce2f46e7fb303c831e9 | https://github.com/line/centraldogma/blob/b9e46c67fbc26628c2186ce2f46e7fb303c831e9/common/src/main/java/com/linecorp/centraldogma/internal/Util.java#L224-L230 | train |
line/centraldogma | client/java/src/main/java/com/linecorp/centraldogma/client/AbstractCentralDogmaBuilder.java | AbstractCentralDogmaBuilder.accessToken | public final B accessToken(String accessToken) {
requireNonNull(accessToken, "accessToken");
checkArgument(!accessToken.isEmpty(), "accessToken is empty.");
this.accessToken = accessToken;
return self();
} | java | public final B accessToken(String accessToken) {
requireNonNull(accessToken, "accessToken");
checkArgument(!accessToken.isEmpty(), "accessToken is empty.");
this.accessToken = accessToken;
return self();
} | [
"public",
"final",
"B",
"accessToken",
"(",
"String",
"accessToken",
")",
"{",
"requireNonNull",
"(",
"accessToken",
",",
"\"accessToken\"",
")",
";",
"checkArgument",
"(",
"!",
"accessToken",
".",
"isEmpty",
"(",
")",
",",
"\"accessToken is empty.\"",
")",
";",... | Sets the access token to use when authenticating a client. | [
"Sets",
"the",
"access",
"token",
"to",
"use",
"when",
"authenticating",
"a",
"client",
"."
] | b9e46c67fbc26628c2186ce2f46e7fb303c831e9 | https://github.com/line/centraldogma/blob/b9e46c67fbc26628c2186ce2f46e7fb303c831e9/client/java/src/main/java/com/linecorp/centraldogma/client/AbstractCentralDogmaBuilder.java#L335-L340 | train |
line/centraldogma | common/src/main/java/com/linecorp/centraldogma/internal/jsonpatch/JsonPatch.java | JsonPatch.fromJson | public static JsonPatch fromJson(final JsonNode node) throws IOException {
requireNonNull(node, "node");
try {
return Jackson.treeToValue(node, JsonPatch.class);
} catch (JsonMappingException e) {
throw new JsonPatchException("invalid JSON patch", e);
}
} | java | public static JsonPatch fromJson(final JsonNode node) throws IOException {
requireNonNull(node, "node");
try {
return Jackson.treeToValue(node, JsonPatch.class);
} catch (JsonMappingException e) {
throw new JsonPatchException("invalid JSON patch", e);
}
} | [
"public",
"static",
"JsonPatch",
"fromJson",
"(",
"final",
"JsonNode",
"node",
")",
"throws",
"IOException",
"{",
"requireNonNull",
"(",
"node",
",",
"\"node\"",
")",
";",
"try",
"{",
"return",
"Jackson",
".",
"treeToValue",
"(",
"node",
",",
"JsonPatch",
".... | Static factory method to build a JSON Patch out of a JSON representation.
@param node the JSON representation of the generated JSON Patch
@return a JSON Patch
@throws IOException input is not a valid JSON patch
@throws NullPointerException input is null | [
"Static",
"factory",
"method",
"to",
"build",
"a",
"JSON",
"Patch",
"out",
"of",
"a",
"JSON",
"representation",
"."
] | b9e46c67fbc26628c2186ce2f46e7fb303c831e9 | https://github.com/line/centraldogma/blob/b9e46c67fbc26628c2186ce2f46e7fb303c831e9/common/src/main/java/com/linecorp/centraldogma/internal/jsonpatch/JsonPatch.java#L137-L144 | train |
line/centraldogma | common/src/main/java/com/linecorp/centraldogma/internal/jsonpatch/JsonPatch.java | JsonPatch.generate | public static JsonPatch generate(final JsonNode source, final JsonNode target, ReplaceMode replaceMode) {
requireNonNull(source, "source");
requireNonNull(target, "target");
final DiffProcessor processor = new DiffProcessor(replaceMode, () -> unchangedValues(source, target));
generateDiffs(processor, EMPTY_JSON_POINTER, source, target);
return processor.getPatch();
} | java | public static JsonPatch generate(final JsonNode source, final JsonNode target, ReplaceMode replaceMode) {
requireNonNull(source, "source");
requireNonNull(target, "target");
final DiffProcessor processor = new DiffProcessor(replaceMode, () -> unchangedValues(source, target));
generateDiffs(processor, EMPTY_JSON_POINTER, source, target);
return processor.getPatch();
} | [
"public",
"static",
"JsonPatch",
"generate",
"(",
"final",
"JsonNode",
"source",
",",
"final",
"JsonNode",
"target",
",",
"ReplaceMode",
"replaceMode",
")",
"{",
"requireNonNull",
"(",
"source",
",",
"\"source\"",
")",
";",
"requireNonNull",
"(",
"target",
",",
... | Generates a JSON patch for transforming the source node into the target node.
@param source the node to be patched
@param target the expected result after applying the patch
@param replaceMode the replace mode to be used
@return the patch as a {@link JsonPatch} | [
"Generates",
"a",
"JSON",
"patch",
"for",
"transforming",
"the",
"source",
"node",
"into",
"the",
"target",
"node",
"."
] | b9e46c67fbc26628c2186ce2f46e7fb303c831e9 | https://github.com/line/centraldogma/blob/b9e46c67fbc26628c2186ce2f46e7fb303c831e9/common/src/main/java/com/linecorp/centraldogma/internal/jsonpatch/JsonPatch.java#L154-L160 | train |
line/centraldogma | common/src/main/java/com/linecorp/centraldogma/internal/jsonpatch/JsonPatch.java | JsonPatch.apply | public JsonNode apply(final JsonNode node) {
requireNonNull(node, "node");
JsonNode ret = node.deepCopy();
for (final JsonPatchOperation operation : operations) {
ret = operation.apply(ret);
}
return ret;
} | java | public JsonNode apply(final JsonNode node) {
requireNonNull(node, "node");
JsonNode ret = node.deepCopy();
for (final JsonPatchOperation operation : operations) {
ret = operation.apply(ret);
}
return ret;
} | [
"public",
"JsonNode",
"apply",
"(",
"final",
"JsonNode",
"node",
")",
"{",
"requireNonNull",
"(",
"node",
",",
"\"node\"",
")",
";",
"JsonNode",
"ret",
"=",
"node",
".",
"deepCopy",
"(",
")",
";",
"for",
"(",
"final",
"JsonPatchOperation",
"operation",
":"... | Applies this patch to a JSON value.
@param node the value to apply the patch to
@return the patched JSON value
@throws JsonPatchException failed to apply patch
@throws NullPointerException input is null | [
"Applies",
"this",
"patch",
"to",
"a",
"JSON",
"value",
"."
] | b9e46c67fbc26628c2186ce2f46e7fb303c831e9 | https://github.com/line/centraldogma/blob/b9e46c67fbc26628c2186ce2f46e7fb303c831e9/common/src/main/java/com/linecorp/centraldogma/internal/jsonpatch/JsonPatch.java#L345-L353 | train |
line/centraldogma | server/src/main/java/com/linecorp/centraldogma/server/internal/thrift/Converter.java | Converter.convert | static Project convert(
String name, com.linecorp.centraldogma.server.storage.project.Project project) {
return new Project(name);
} | java | static Project convert(
String name, com.linecorp.centraldogma.server.storage.project.Project project) {
return new Project(name);
} | [
"static",
"Project",
"convert",
"(",
"String",
"name",
",",
"com",
".",
"linecorp",
".",
"centraldogma",
".",
"server",
".",
"storage",
".",
"project",
".",
"Project",
"project",
")",
"{",
"return",
"new",
"Project",
"(",
"name",
")",
";",
"}"
] | The parameter 'project' is not used at the moment, but will be used once schema and plugin support lands. | [
"The",
"parameter",
"project",
"is",
"not",
"used",
"at",
"the",
"moment",
"but",
"will",
"be",
"used",
"once",
"schema",
"and",
"plugin",
"support",
"lands",
"."
] | b9e46c67fbc26628c2186ce2f46e7fb303c831e9 | https://github.com/line/centraldogma/blob/b9e46c67fbc26628c2186ce2f46e7fb303c831e9/server/src/main/java/com/linecorp/centraldogma/server/internal/thrift/Converter.java#L159-L162 | train |
indeedeng/proctor | proctor-store/src/main/java/com/indeed/proctor/store/cache/CachingProctorStore.java | CachingProctorStore.getMatrixHistory | @Override
public List<Revision> getMatrixHistory(final int start, final int limit) throws StoreException {
return delegate.getMatrixHistory(start, limit);
} | java | @Override
public List<Revision> getMatrixHistory(final int start, final int limit) throws StoreException {
return delegate.getMatrixHistory(start, limit);
} | [
"@",
"Override",
"public",
"List",
"<",
"Revision",
">",
"getMatrixHistory",
"(",
"final",
"int",
"start",
",",
"final",
"int",
"limit",
")",
"throws",
"StoreException",
"{",
"return",
"delegate",
".",
"getMatrixHistory",
"(",
"start",
",",
"limit",
")",
";"... | caching is not supported for this method | [
"caching",
"is",
"not",
"supported",
"for",
"this",
"method"
] | b7795acfc26a30d013655d0e0fa1d3f8d0576571 | https://github.com/indeedeng/proctor/blob/b7795acfc26a30d013655d0e0fa1d3f8d0576571/proctor-store/src/main/java/com/indeed/proctor/store/cache/CachingProctorStore.java#L113-L116 | train |
indeedeng/proctor | proctor-store-svn/src/main/java/com/indeed/proctor/store/SvnWorkspaceProviderImpl.java | SvnWorkspaceProviderImpl.getUserDirectory | private static File getUserDirectory(final String prefix, final String suffix, final File parent) {
final String dirname = formatDirName(prefix, suffix);
return new File(parent, dirname);
} | java | private static File getUserDirectory(final String prefix, final String suffix, final File parent) {
final String dirname = formatDirName(prefix, suffix);
return new File(parent, dirname);
} | [
"private",
"static",
"File",
"getUserDirectory",
"(",
"final",
"String",
"prefix",
",",
"final",
"String",
"suffix",
",",
"final",
"File",
"parent",
")",
"{",
"final",
"String",
"dirname",
"=",
"formatDirName",
"(",
"prefix",
",",
"suffix",
")",
";",
"return... | Returns a File object whose path is the expected user directory.
Does not create or check for existence.
@param prefix
@param suffix
@param parent
@return | [
"Returns",
"a",
"File",
"object",
"whose",
"path",
"is",
"the",
"expected",
"user",
"directory",
".",
"Does",
"not",
"create",
"or",
"check",
"for",
"existence",
"."
] | b7795acfc26a30d013655d0e0fa1d3f8d0576571 | https://github.com/indeedeng/proctor/blob/b7795acfc26a30d013655d0e0fa1d3f8d0576571/proctor-store-svn/src/main/java/com/indeed/proctor/store/SvnWorkspaceProviderImpl.java#L169-L172 | train |
indeedeng/proctor | proctor-store-svn/src/main/java/com/indeed/proctor/store/SvnWorkspaceProviderImpl.java | SvnWorkspaceProviderImpl.formatDirName | private static String formatDirName(final String prefix, final String suffix) {
// Replace all invalid characters with '-'
final CharMatcher invalidCharacters = VALID_SUFFIX_CHARS.negate();
return String.format("%s-%s", prefix, invalidCharacters.trimAndCollapseFrom(suffix.toLowerCase(), '-'));
} | java | private static String formatDirName(final String prefix, final String suffix) {
// Replace all invalid characters with '-'
final CharMatcher invalidCharacters = VALID_SUFFIX_CHARS.negate();
return String.format("%s-%s", prefix, invalidCharacters.trimAndCollapseFrom(suffix.toLowerCase(), '-'));
} | [
"private",
"static",
"String",
"formatDirName",
"(",
"final",
"String",
"prefix",
",",
"final",
"String",
"suffix",
")",
"{",
"// Replace all invalid characters with '-'",
"final",
"CharMatcher",
"invalidCharacters",
"=",
"VALID_SUFFIX_CHARS",
".",
"negate",
"(",
")",
... | Returns the expected name of a workspace for a given suffix
@param suffix
@return | [
"Returns",
"the",
"expected",
"name",
"of",
"a",
"workspace",
"for",
"a",
"given",
"suffix"
] | b7795acfc26a30d013655d0e0fa1d3f8d0576571 | https://github.com/indeedeng/proctor/blob/b7795acfc26a30d013655d0e0fa1d3f8d0576571/proctor-store-svn/src/main/java/com/indeed/proctor/store/SvnWorkspaceProviderImpl.java#L180-L184 | train |
indeedeng/proctor | proctor-store-svn/src/main/java/com/indeed/proctor/store/SvnWorkspaceProviderImpl.java | SvnWorkspaceProviderImpl.deleteUserDirectories | private static void deleteUserDirectories(final File root,
final FileFilter filter) {
final File[] dirs = root.listFiles(filter);
LOGGER.info("Identified (" + dirs.length + ") directories to delete");
for (final File dir : dirs) {
LOGGER.info("Deleting " + dir);
if (!FileUtils.deleteQuietly(dir)) {
LOGGER.info("Failed to delete directory " + dir);
}
}
} | java | private static void deleteUserDirectories(final File root,
final FileFilter filter) {
final File[] dirs = root.listFiles(filter);
LOGGER.info("Identified (" + dirs.length + ") directories to delete");
for (final File dir : dirs) {
LOGGER.info("Deleting " + dir);
if (!FileUtils.deleteQuietly(dir)) {
LOGGER.info("Failed to delete directory " + dir);
}
}
} | [
"private",
"static",
"void",
"deleteUserDirectories",
"(",
"final",
"File",
"root",
",",
"final",
"FileFilter",
"filter",
")",
"{",
"final",
"File",
"[",
"]",
"dirs",
"=",
"root",
".",
"listFiles",
"(",
"filter",
")",
";",
"LOGGER",
".",
"info",
"(",
"\"... | Deletes all of the Directories in root that match the FileFilter
@param root
@param filter | [
"Deletes",
"all",
"of",
"the",
"Directories",
"in",
"root",
"that",
"match",
"the",
"FileFilter"
] | b7795acfc26a30d013655d0e0fa1d3f8d0576571 | https://github.com/indeedeng/proctor/blob/b7795acfc26a30d013655d0e0fa1d3f8d0576571/proctor-store-svn/src/main/java/com/indeed/proctor/store/SvnWorkspaceProviderImpl.java#L201-L211 | train |
indeedeng/proctor | proctor-common/src/main/java/com/indeed/proctor/common/Proctor.java | Proctor.construct | @Nonnull
public static Proctor construct(@Nonnull final TestMatrixArtifact matrix, ProctorLoadResult loadResult, FunctionMapper functionMapper) {
final ExpressionFactory expressionFactory = RuleEvaluator.EXPRESSION_FACTORY;
final Map<String, TestChooser<?>> testChoosers = Maps.newLinkedHashMap();
final Map<String, String> versions = Maps.newLinkedHashMap();
for (final Entry<String, ConsumableTestDefinition> entry : matrix.getTests().entrySet()) {
final String testName = entry.getKey();
final ConsumableTestDefinition testDefinition = entry.getValue();
final TestType testType = testDefinition.getTestType();
final TestChooser<?> testChooser;
if (TestType.RANDOM.equals(testType)) {
testChooser = new RandomTestChooser(expressionFactory, functionMapper, testName, testDefinition);
} else {
testChooser = new StandardTestChooser(expressionFactory, functionMapper, testName, testDefinition);
}
testChoosers.put(testName, testChooser);
versions.put(testName, testDefinition.getVersion());
}
return new Proctor(matrix, loadResult, testChoosers);
} | java | @Nonnull
public static Proctor construct(@Nonnull final TestMatrixArtifact matrix, ProctorLoadResult loadResult, FunctionMapper functionMapper) {
final ExpressionFactory expressionFactory = RuleEvaluator.EXPRESSION_FACTORY;
final Map<String, TestChooser<?>> testChoosers = Maps.newLinkedHashMap();
final Map<String, String> versions = Maps.newLinkedHashMap();
for (final Entry<String, ConsumableTestDefinition> entry : matrix.getTests().entrySet()) {
final String testName = entry.getKey();
final ConsumableTestDefinition testDefinition = entry.getValue();
final TestType testType = testDefinition.getTestType();
final TestChooser<?> testChooser;
if (TestType.RANDOM.equals(testType)) {
testChooser = new RandomTestChooser(expressionFactory, functionMapper, testName, testDefinition);
} else {
testChooser = new StandardTestChooser(expressionFactory, functionMapper, testName, testDefinition);
}
testChoosers.put(testName, testChooser);
versions.put(testName, testDefinition.getVersion());
}
return new Proctor(matrix, loadResult, testChoosers);
} | [
"@",
"Nonnull",
"public",
"static",
"Proctor",
"construct",
"(",
"@",
"Nonnull",
"final",
"TestMatrixArtifact",
"matrix",
",",
"ProctorLoadResult",
"loadResult",
",",
"FunctionMapper",
"functionMapper",
")",
"{",
"final",
"ExpressionFactory",
"expressionFactory",
"=",
... | Factory method to do the setup and transformation of inputs
@param matrix a {@link TestMatrixArtifact} loaded by ProctorLoader
@param loadResult a {@link ProctorLoadResult} which contains result of validation of test definition
@param functionMapper a given el {@link FunctionMapper}
@return constructed Proctor object | [
"Factory",
"method",
"to",
"do",
"the",
"setup",
"and",
"transformation",
"of",
"inputs"
] | b7795acfc26a30d013655d0e0fa1d3f8d0576571 | https://github.com/indeedeng/proctor/blob/b7795acfc26a30d013655d0e0fa1d3f8d0576571/proctor-common/src/main/java/com/indeed/proctor/common/Proctor.java#L45-L67 | train |
indeedeng/proctor | proctor-common/src/main/java/com/indeed/proctor/common/ProctorUtils.java | ProctorUtils.verifyWithoutSpecification | public static ProctorLoadResult verifyWithoutSpecification(@Nonnull final TestMatrixArtifact testMatrix,
final String matrixSource) {
final ProctorLoadResult.Builder resultBuilder = ProctorLoadResult.newBuilder();
for (final Entry<String, ConsumableTestDefinition> entry : testMatrix.getTests().entrySet()) {
final String testName = entry.getKey();
final ConsumableTestDefinition testDefinition = entry.getValue();
try {
verifyInternallyConsistentDefinition(testName, matrixSource, testDefinition);
} catch (IncompatibleTestMatrixException e) {
LOGGER.info(String.format("Unable to load test matrix for %s", testName), e);
resultBuilder.recordError(testName, e);
}
}
return resultBuilder.build();
} | java | public static ProctorLoadResult verifyWithoutSpecification(@Nonnull final TestMatrixArtifact testMatrix,
final String matrixSource) {
final ProctorLoadResult.Builder resultBuilder = ProctorLoadResult.newBuilder();
for (final Entry<String, ConsumableTestDefinition> entry : testMatrix.getTests().entrySet()) {
final String testName = entry.getKey();
final ConsumableTestDefinition testDefinition = entry.getValue();
try {
verifyInternallyConsistentDefinition(testName, matrixSource, testDefinition);
} catch (IncompatibleTestMatrixException e) {
LOGGER.info(String.format("Unable to load test matrix for %s", testName), e);
resultBuilder.recordError(testName, e);
}
}
return resultBuilder.build();
} | [
"public",
"static",
"ProctorLoadResult",
"verifyWithoutSpecification",
"(",
"@",
"Nonnull",
"final",
"TestMatrixArtifact",
"testMatrix",
",",
"final",
"String",
"matrixSource",
")",
"{",
"final",
"ProctorLoadResult",
".",
"Builder",
"resultBuilder",
"=",
"ProctorLoadResul... | Verifies that the TestMatrix is correct and sane without using a specification.
The Proctor API doesn't use a test specification so that it can serve all tests in the matrix
without restriction.
Does a limited set of sanity checks that are applicable when there is no specification,
and thus no required tests or provided context.
@param testMatrix the {@link TestMatrixArtifact} to be verified.
@param matrixSource a {@link String} of the source of proctor artifact. For example a path of proctor artifact file.
@return a {@link ProctorLoadResult} to describe the result of verification. It contains errors of verification and a list of missing test. | [
"Verifies",
"that",
"the",
"TestMatrix",
"is",
"correct",
"and",
"sane",
"without",
"using",
"a",
"specification",
".",
"The",
"Proctor",
"API",
"doesn",
"t",
"use",
"a",
"test",
"specification",
"so",
"that",
"it",
"can",
"serve",
"all",
"tests",
"in",
"t... | b7795acfc26a30d013655d0e0fa1d3f8d0576571 | https://github.com/indeedeng/proctor/blob/b7795acfc26a30d013655d0e0fa1d3f8d0576571/proctor-common/src/main/java/com/indeed/proctor/common/ProctorUtils.java#L321-L337 | train |
indeedeng/proctor | proctor-common/src/main/java/com/indeed/proctor/common/ProctorUtils.java | ProctorUtils.verify | public static ProctorLoadResult verify(
@Nonnull final TestMatrixArtifact testMatrix,
final String matrixSource,
@Nonnull final Map<String, TestSpecification> requiredTests,
@Nonnull final FunctionMapper functionMapper,
final ProvidedContext providedContext,
@Nonnull final Set<String> dynamicTests
) {
final ProctorLoadResult.Builder resultBuilder = ProctorLoadResult.newBuilder();
final Map<String, Map<Integer, String>> allTestsKnownBuckets = Maps.newHashMapWithExpectedSize(requiredTests.size());
for (final Entry<String, TestSpecification> entry : requiredTests.entrySet()) {
final Map<Integer, String> bucketValueToName = Maps.newHashMap();
for (final Entry<String, Integer> bucket : entry.getValue().getBuckets().entrySet()) {
bucketValueToName.put(bucket.getValue(), bucket.getKey());
}
allTestsKnownBuckets.put(entry.getKey(), bucketValueToName);
}
final Map<String, ConsumableTestDefinition> definedTests = testMatrix.getTests();
final SetView<String> missingTests = Sets.difference(requiredTests.keySet(), definedTests.keySet());
resultBuilder.recordAllMissing(missingTests);
for (final Entry<String, ConsumableTestDefinition> entry : definedTests.entrySet()) {
final String testName = entry.getKey();
final Map<Integer, String> knownBuckets;
final TestSpecification specification;
final boolean isRequired;
if (allTestsKnownBuckets.containsKey(testName)) {
// required in specification
isRequired = true;
knownBuckets = allTestsKnownBuckets.remove(testName);
specification = requiredTests.get(testName);
} else if (dynamicTests.contains(testName)) {
// resolved by dynamic filter
isRequired = false;
knownBuckets = Collections.emptyMap();
specification = new TestSpecification();
} else {
// we don't care about this test
continue;
}
final ConsumableTestDefinition testDefinition = entry.getValue();
try {
verifyTest(testName, testDefinition, specification, knownBuckets, matrixSource, functionMapper, providedContext);
} catch (IncompatibleTestMatrixException e) {
if (isRequired) {
LOGGER.error(String.format("Unable to load test matrix for a required test %s", testName), e);
resultBuilder.recordError(testName, e);
} else {
LOGGER.info(String.format("Unable to load test matrix for a dynamic test %s", testName), e);
resultBuilder.recordIncompatibleDynamicTest(testName, e);
}
}
}
// TODO mjs - is this check additive?
resultBuilder.recordAllMissing(allTestsKnownBuckets.keySet());
resultBuilder.recordVerifiedRules(providedContext.shouldEvaluate());
final ProctorLoadResult loadResult = resultBuilder.build();
return loadResult;
} | java | public static ProctorLoadResult verify(
@Nonnull final TestMatrixArtifact testMatrix,
final String matrixSource,
@Nonnull final Map<String, TestSpecification> requiredTests,
@Nonnull final FunctionMapper functionMapper,
final ProvidedContext providedContext,
@Nonnull final Set<String> dynamicTests
) {
final ProctorLoadResult.Builder resultBuilder = ProctorLoadResult.newBuilder();
final Map<String, Map<Integer, String>> allTestsKnownBuckets = Maps.newHashMapWithExpectedSize(requiredTests.size());
for (final Entry<String, TestSpecification> entry : requiredTests.entrySet()) {
final Map<Integer, String> bucketValueToName = Maps.newHashMap();
for (final Entry<String, Integer> bucket : entry.getValue().getBuckets().entrySet()) {
bucketValueToName.put(bucket.getValue(), bucket.getKey());
}
allTestsKnownBuckets.put(entry.getKey(), bucketValueToName);
}
final Map<String, ConsumableTestDefinition> definedTests = testMatrix.getTests();
final SetView<String> missingTests = Sets.difference(requiredTests.keySet(), definedTests.keySet());
resultBuilder.recordAllMissing(missingTests);
for (final Entry<String, ConsumableTestDefinition> entry : definedTests.entrySet()) {
final String testName = entry.getKey();
final Map<Integer, String> knownBuckets;
final TestSpecification specification;
final boolean isRequired;
if (allTestsKnownBuckets.containsKey(testName)) {
// required in specification
isRequired = true;
knownBuckets = allTestsKnownBuckets.remove(testName);
specification = requiredTests.get(testName);
} else if (dynamicTests.contains(testName)) {
// resolved by dynamic filter
isRequired = false;
knownBuckets = Collections.emptyMap();
specification = new TestSpecification();
} else {
// we don't care about this test
continue;
}
final ConsumableTestDefinition testDefinition = entry.getValue();
try {
verifyTest(testName, testDefinition, specification, knownBuckets, matrixSource, functionMapper, providedContext);
} catch (IncompatibleTestMatrixException e) {
if (isRequired) {
LOGGER.error(String.format("Unable to load test matrix for a required test %s", testName), e);
resultBuilder.recordError(testName, e);
} else {
LOGGER.info(String.format("Unable to load test matrix for a dynamic test %s", testName), e);
resultBuilder.recordIncompatibleDynamicTest(testName, e);
}
}
}
// TODO mjs - is this check additive?
resultBuilder.recordAllMissing(allTestsKnownBuckets.keySet());
resultBuilder.recordVerifiedRules(providedContext.shouldEvaluate());
final ProctorLoadResult loadResult = resultBuilder.build();
return loadResult;
} | [
"public",
"static",
"ProctorLoadResult",
"verify",
"(",
"@",
"Nonnull",
"final",
"TestMatrixArtifact",
"testMatrix",
",",
"final",
"String",
"matrixSource",
",",
"@",
"Nonnull",
"final",
"Map",
"<",
"String",
",",
"TestSpecification",
">",
"requiredTests",
",",
"@... | Does not mutate the TestMatrix.
Verifies that the test matrix contains all the required tests and that
each required test is valid.
@param testMatrix the {@link TestMatrixArtifact} to be verified.
@param matrixSource a {@link String} of the source of proctor artifact. For example a path of proctor artifact file.
@param requiredTests a {@link Map} of required test. The {@link TestSpecification} would be verified
@param functionMapper a given el {@link FunctionMapper}
@param providedContext a {@link Map} containing variables describing the context in which the request is executing. These will be supplied to verifying all rules.
@param dynamicTests a {@link Set} of dynamic tests determined by filters.
@return a {@link ProctorLoadResult} to describe the result of verification. It contains errors of verification and a list of missing test. | [
"Does",
"not",
"mutate",
"the",
"TestMatrix",
".",
"Verifies",
"that",
"the",
"test",
"matrix",
"contains",
"all",
"the",
"required",
"tests",
"and",
"that",
"each",
"required",
"test",
"is",
"valid",
"."
] | b7795acfc26a30d013655d0e0fa1d3f8d0576571 | https://github.com/indeedeng/proctor/blob/b7795acfc26a30d013655d0e0fa1d3f8d0576571/proctor-common/src/main/java/com/indeed/proctor/common/ProctorUtils.java#L401-L468 | train |
indeedeng/proctor | proctor-common/src/main/java/com/indeed/proctor/common/ProctorUtils.java | ProctorUtils.isEmptyWhitespace | static boolean isEmptyWhitespace(@Nullable final String s) {
if (s == null) {
return true;
}
return CharMatcher.WHITESPACE.matchesAllOf(s);
} | java | static boolean isEmptyWhitespace(@Nullable final String s) {
if (s == null) {
return true;
}
return CharMatcher.WHITESPACE.matchesAllOf(s);
} | [
"static",
"boolean",
"isEmptyWhitespace",
"(",
"@",
"Nullable",
"final",
"String",
"s",
")",
"{",
"if",
"(",
"s",
"==",
"null",
")",
"{",
"return",
"true",
";",
"}",
"return",
"CharMatcher",
".",
"WHITESPACE",
".",
"matchesAllOf",
"(",
"s",
")",
";",
"... | Returns flag whose value indicates if the string is null, empty or
only contains whitespace characters
@param s a string
@return true if the string is null, empty or only contains whitespace characters | [
"Returns",
"flag",
"whose",
"value",
"indicates",
"if",
"the",
"string",
"is",
"null",
"empty",
"or",
"only",
"contains",
"whitespace",
"characters"
] | b7795acfc26a30d013655d0e0fa1d3f8d0576571 | https://github.com/indeedeng/proctor/blob/b7795acfc26a30d013655d0e0fa1d3f8d0576571/proctor-common/src/main/java/com/indeed/proctor/common/ProctorUtils.java#L910-L915 | train |
indeedeng/proctor | proctor-common/src/main/java/com/indeed/proctor/common/ProctorUtils.java | ProctorUtils.generateSpecification | public static TestSpecification generateSpecification(@Nonnull final TestDefinition testDefinition) {
final TestSpecification testSpecification = new TestSpecification();
// Sort buckets by value ascending
final Map<String,Integer> buckets = Maps.newLinkedHashMap();
final List<TestBucket> testDefinitionBuckets = Ordering.from(new Comparator<TestBucket>() {
@Override
public int compare(final TestBucket lhs, final TestBucket rhs) {
return Ints.compare(lhs.getValue(), rhs.getValue());
}
}).immutableSortedCopy(testDefinition.getBuckets());
int fallbackValue = -1;
if(testDefinitionBuckets.size() > 0) {
final TestBucket firstBucket = testDefinitionBuckets.get(0);
fallbackValue = firstBucket.getValue(); // buckets are sorted, choose smallest value as the fallback value
final PayloadSpecification payloadSpecification = new PayloadSpecification();
if(firstBucket.getPayload() != null && !firstBucket.getPayload().equals(Payload.EMPTY_PAYLOAD)) {
final PayloadType payloadType = PayloadType.payloadTypeForName(firstBucket.getPayload().fetchType());
payloadSpecification.setType(payloadType.payloadTypeName);
if (payloadType == PayloadType.MAP) {
final Map<String, String> payloadSpecificationSchema = new HashMap<String, String>();
for (Map.Entry<String, Object> entry : firstBucket.getPayload().getMap().entrySet()) {
payloadSpecificationSchema.put(entry.getKey(), PayloadType.payloadTypeForValue(entry.getValue()).payloadTypeName);
}
payloadSpecification.setSchema(payloadSpecificationSchema);
}
testSpecification.setPayload(payloadSpecification);
}
for (int i = 0; i < testDefinitionBuckets.size(); i++) {
final TestBucket bucket = testDefinitionBuckets.get(i);
buckets.put(bucket.getName(), bucket.getValue());
}
}
testSpecification.setBuckets(buckets);
testSpecification.setDescription(testDefinition.getDescription());
testSpecification.setFallbackValue(fallbackValue);
return testSpecification;
} | java | public static TestSpecification generateSpecification(@Nonnull final TestDefinition testDefinition) {
final TestSpecification testSpecification = new TestSpecification();
// Sort buckets by value ascending
final Map<String,Integer> buckets = Maps.newLinkedHashMap();
final List<TestBucket> testDefinitionBuckets = Ordering.from(new Comparator<TestBucket>() {
@Override
public int compare(final TestBucket lhs, final TestBucket rhs) {
return Ints.compare(lhs.getValue(), rhs.getValue());
}
}).immutableSortedCopy(testDefinition.getBuckets());
int fallbackValue = -1;
if(testDefinitionBuckets.size() > 0) {
final TestBucket firstBucket = testDefinitionBuckets.get(0);
fallbackValue = firstBucket.getValue(); // buckets are sorted, choose smallest value as the fallback value
final PayloadSpecification payloadSpecification = new PayloadSpecification();
if(firstBucket.getPayload() != null && !firstBucket.getPayload().equals(Payload.EMPTY_PAYLOAD)) {
final PayloadType payloadType = PayloadType.payloadTypeForName(firstBucket.getPayload().fetchType());
payloadSpecification.setType(payloadType.payloadTypeName);
if (payloadType == PayloadType.MAP) {
final Map<String, String> payloadSpecificationSchema = new HashMap<String, String>();
for (Map.Entry<String, Object> entry : firstBucket.getPayload().getMap().entrySet()) {
payloadSpecificationSchema.put(entry.getKey(), PayloadType.payloadTypeForValue(entry.getValue()).payloadTypeName);
}
payloadSpecification.setSchema(payloadSpecificationSchema);
}
testSpecification.setPayload(payloadSpecification);
}
for (int i = 0; i < testDefinitionBuckets.size(); i++) {
final TestBucket bucket = testDefinitionBuckets.get(i);
buckets.put(bucket.getName(), bucket.getValue());
}
}
testSpecification.setBuckets(buckets);
testSpecification.setDescription(testDefinition.getDescription());
testSpecification.setFallbackValue(fallbackValue);
return testSpecification;
} | [
"public",
"static",
"TestSpecification",
"generateSpecification",
"(",
"@",
"Nonnull",
"final",
"TestDefinition",
"testDefinition",
")",
"{",
"final",
"TestSpecification",
"testSpecification",
"=",
"new",
"TestSpecification",
"(",
")",
";",
"// Sort buckets by value ascendi... | Generates a usable test specification for a given test definition
Uses the first bucket as the fallback value
@param testDefinition a {@link TestDefinition}
@return a {@link TestSpecification} which corresponding to given test definition. | [
"Generates",
"a",
"usable",
"test",
"specification",
"for",
"a",
"given",
"test",
"definition",
"Uses",
"the",
"first",
"bucket",
"as",
"the",
"fallback",
"value"
] | b7795acfc26a30d013655d0e0fa1d3f8d0576571 | https://github.com/indeedeng/proctor/blob/b7795acfc26a30d013655d0e0fa1d3f8d0576571/proctor-common/src/main/java/com/indeed/proctor/common/ProctorUtils.java#L924-L962 | train |
indeedeng/proctor | proctor-consumer/src/main/java/com/indeed/proctor/consumer/AbstractGroups.java | AbstractGroups.getPayload | @Nonnull
protected Payload getPayload(final String testName) {
// Get the current bucket.
final TestBucket testBucket = buckets.get(testName);
// Lookup Payloads for this test
if (testBucket != null) {
final Payload payload = testBucket.getPayload();
if (null != payload) {
return payload;
}
}
return Payload.EMPTY_PAYLOAD;
} | java | @Nonnull
protected Payload getPayload(final String testName) {
// Get the current bucket.
final TestBucket testBucket = buckets.get(testName);
// Lookup Payloads for this test
if (testBucket != null) {
final Payload payload = testBucket.getPayload();
if (null != payload) {
return payload;
}
}
return Payload.EMPTY_PAYLOAD;
} | [
"@",
"Nonnull",
"protected",
"Payload",
"getPayload",
"(",
"final",
"String",
"testName",
")",
"{",
"// Get the current bucket.",
"final",
"TestBucket",
"testBucket",
"=",
"buckets",
".",
"get",
"(",
"testName",
")",
";",
"// Lookup Payloads for this test",
"if",
"(... | Return the Payload attached to the current active bucket for |test|.
Always returns a payload so the client doesn't crash on a malformed
test definition.
@param testName test name
@return pay load attached to the current active bucket
@deprecated Use {@link #getPayload(String, Bucket)} instead | [
"Return",
"the",
"Payload",
"attached",
"to",
"the",
"current",
"active",
"bucket",
"for",
"|test|",
".",
"Always",
"returns",
"a",
"payload",
"so",
"the",
"client",
"doesn",
"t",
"crash",
"on",
"a",
"malformed",
"test",
"definition",
"."
] | b7795acfc26a30d013655d0e0fa1d3f8d0576571 | https://github.com/indeedeng/proctor/blob/b7795acfc26a30d013655d0e0fa1d3f8d0576571/proctor-consumer/src/main/java/com/indeed/proctor/consumer/AbstractGroups.java#L92-L106 | train |
indeedeng/proctor | proctor-consumer/src/main/java/com/indeed/proctor/consumer/ProctorConsumerUtils.java | ProctorConsumerUtils.parseForcedGroups | @Nonnull
public static Map<String, Integer> parseForcedGroups(@Nonnull final HttpServletRequest request) {
final String forceGroupsList = getForceGroupsStringFromRequest(request);
return parseForceGroupsList(forceGroupsList);
} | java | @Nonnull
public static Map<String, Integer> parseForcedGroups(@Nonnull final HttpServletRequest request) {
final String forceGroupsList = getForceGroupsStringFromRequest(request);
return parseForceGroupsList(forceGroupsList);
} | [
"@",
"Nonnull",
"public",
"static",
"Map",
"<",
"String",
",",
"Integer",
">",
"parseForcedGroups",
"(",
"@",
"Nonnull",
"final",
"HttpServletRequest",
"request",
")",
"{",
"final",
"String",
"forceGroupsList",
"=",
"getForceGroupsStringFromRequest",
"(",
"request",... | Consumer is required to do any privilege checks before getting here
@param request a {@link HttpServletRequest} which may contain forced groups parameters from URL, Header or Cookie.
@return a map of test names to bucket values specified by the request. Returns an empty {@link Map} if nothing was specified | [
"Consumer",
"is",
"required",
"to",
"do",
"any",
"privilege",
"checks",
"before",
"getting",
"here"
] | b7795acfc26a30d013655d0e0fa1d3f8d0576571 | https://github.com/indeedeng/proctor/blob/b7795acfc26a30d013655d0e0fa1d3f8d0576571/proctor-consumer/src/main/java/com/indeed/proctor/consumer/ProctorConsumerUtils.java#L56-L60 | train |
indeedeng/proctor | proctor-common/src/main/java/com/indeed/proctor/common/model/Payload.java | Payload.precheckStateAllNull | private void precheckStateAllNull() throws IllegalStateException {
if ((doubleValue != null) || (doubleArray != null)
|| (longValue != null) || (longArray != null)
|| (stringValue != null) || (stringArray != null)
|| (map != null)) {
throw new IllegalStateException("Expected all properties to be empty: " + this);
}
} | java | private void precheckStateAllNull() throws IllegalStateException {
if ((doubleValue != null) || (doubleArray != null)
|| (longValue != null) || (longArray != null)
|| (stringValue != null) || (stringArray != null)
|| (map != null)) {
throw new IllegalStateException("Expected all properties to be empty: " + this);
}
} | [
"private",
"void",
"precheckStateAllNull",
"(",
")",
"throws",
"IllegalStateException",
"{",
"if",
"(",
"(",
"doubleValue",
"!=",
"null",
")",
"||",
"(",
"doubleArray",
"!=",
"null",
")",
"||",
"(",
"longValue",
"!=",
"null",
")",
"||",
"(",
"longArray",
"... | Sanity check precondition for above setters | [
"Sanity",
"check",
"precondition",
"for",
"above",
"setters"
] | b7795acfc26a30d013655d0e0fa1d3f8d0576571 | https://github.com/indeedeng/proctor/blob/b7795acfc26a30d013655d0e0fa1d3f8d0576571/proctor-common/src/main/java/com/indeed/proctor/common/model/Payload.java#L123-L130 | train |
indeedeng/proctor | proctor-consumer/src/main/java/com/indeed/proctor/consumer/spring/SampleRandomGroupsHttpHandler.java | SampleRandomGroupsHttpHandler.runSampling | private Map<String, Integer> runSampling(
final ProctorContext proctorContext,
final Set<String> targetTestNames,
final TestType testType,
final int determinationsToRun
) {
final Set<String> targetTestGroups = getTargetTestGroups(targetTestNames);
final Map<String, Integer> testGroupToOccurrences = Maps.newTreeMap();
for (final String testGroup : targetTestGroups) {
testGroupToOccurrences.put(testGroup, 0);
}
for (int i = 0; i < determinationsToRun; ++i) {
final Identifiers identifiers = TestType.RANDOM.equals(testType)
? new Identifiers(Collections.<TestType, String>emptyMap(), /* randomEnabled */ true)
: Identifiers.of(testType, Long.toString(random.nextLong()));
final AbstractGroups groups = supplier.getRandomGroups(proctorContext, identifiers);
for (final Entry<String, TestBucket> e : groups.getProctorResult().getBuckets().entrySet()) {
final String testName = e.getKey();
if (targetTestNames.contains(testName)) {
final int group = e.getValue().getValue();
final String testGroup = testName + group;
testGroupToOccurrences.put(testGroup, testGroupToOccurrences.get(testGroup) + 1);
}
}
}
return testGroupToOccurrences;
} | java | private Map<String, Integer> runSampling(
final ProctorContext proctorContext,
final Set<String> targetTestNames,
final TestType testType,
final int determinationsToRun
) {
final Set<String> targetTestGroups = getTargetTestGroups(targetTestNames);
final Map<String, Integer> testGroupToOccurrences = Maps.newTreeMap();
for (final String testGroup : targetTestGroups) {
testGroupToOccurrences.put(testGroup, 0);
}
for (int i = 0; i < determinationsToRun; ++i) {
final Identifiers identifiers = TestType.RANDOM.equals(testType)
? new Identifiers(Collections.<TestType, String>emptyMap(), /* randomEnabled */ true)
: Identifiers.of(testType, Long.toString(random.nextLong()));
final AbstractGroups groups = supplier.getRandomGroups(proctorContext, identifiers);
for (final Entry<String, TestBucket> e : groups.getProctorResult().getBuckets().entrySet()) {
final String testName = e.getKey();
if (targetTestNames.contains(testName)) {
final int group = e.getValue().getValue();
final String testGroup = testName + group;
testGroupToOccurrences.put(testGroup, testGroupToOccurrences.get(testGroup) + 1);
}
}
}
return testGroupToOccurrences;
} | [
"private",
"Map",
"<",
"String",
",",
"Integer",
">",
"runSampling",
"(",
"final",
"ProctorContext",
"proctorContext",
",",
"final",
"Set",
"<",
"String",
">",
"targetTestNames",
",",
"final",
"TestType",
"testType",
",",
"final",
"int",
"determinationsToRun",
"... | test, how many times the group was present in the list of groups. | [
"test",
"how",
"many",
"times",
"the",
"group",
"was",
"present",
"in",
"the",
"list",
"of",
"groups",
"."
] | b7795acfc26a30d013655d0e0fa1d3f8d0576571 | https://github.com/indeedeng/proctor/blob/b7795acfc26a30d013655d0e0fa1d3f8d0576571/proctor-consumer/src/main/java/com/indeed/proctor/consumer/spring/SampleRandomGroupsHttpHandler.java#L143-L171 | train |
indeedeng/proctor | proctor-consumer/src/main/java/com/indeed/proctor/consumer/spring/SampleRandomGroupsHttpHandler.java | SampleRandomGroupsHttpHandler.getProctorNotNull | private Proctor getProctorNotNull() {
final Proctor proctor = proctorLoader.get();
if (proctor == null) {
throw new IllegalStateException("Proctor specification and/or text matrix has not been loaded");
}
return proctor;
} | java | private Proctor getProctorNotNull() {
final Proctor proctor = proctorLoader.get();
if (proctor == null) {
throw new IllegalStateException("Proctor specification and/or text matrix has not been loaded");
}
return proctor;
} | [
"private",
"Proctor",
"getProctorNotNull",
"(",
")",
"{",
"final",
"Proctor",
"proctor",
"=",
"proctorLoader",
".",
"get",
"(",
")",
";",
"if",
"(",
"proctor",
"==",
"null",
")",
"{",
"throw",
"new",
"IllegalStateException",
"(",
"\"Proctor specification and/or ... | return currently-loaded Proctor instance, throwing IllegalStateException if not loaded | [
"return",
"currently",
"-",
"loaded",
"Proctor",
"instance",
"throwing",
"IllegalStateException",
"if",
"not",
"loaded"
] | b7795acfc26a30d013655d0e0fa1d3f8d0576571 | https://github.com/indeedeng/proctor/blob/b7795acfc26a30d013655d0e0fa1d3f8d0576571/proctor-consumer/src/main/java/com/indeed/proctor/consumer/spring/SampleRandomGroupsHttpHandler.java#L211-L217 | train |
indeedeng/proctor | proctor-common/src/main/java/com/indeed/proctor/common/dynamic/DynamicFilters.java | DynamicFilters.registerFilterTypes | @SafeVarargs
public static void registerFilterTypes(final Class<? extends DynamicFilter>... types) {
FILTER_TYPES.addAll(Arrays.asList(types));
} | java | @SafeVarargs
public static void registerFilterTypes(final Class<? extends DynamicFilter>... types) {
FILTER_TYPES.addAll(Arrays.asList(types));
} | [
"@",
"SafeVarargs",
"public",
"static",
"void",
"registerFilterTypes",
"(",
"final",
"Class",
"<",
"?",
"extends",
"DynamicFilter",
">",
"...",
"types",
")",
"{",
"FILTER_TYPES",
".",
"addAll",
"(",
"Arrays",
".",
"asList",
"(",
"types",
")",
")",
";",
"}"... | Register custom filter types especially for serializer of specification json file | [
"Register",
"custom",
"filter",
"types",
"especially",
"for",
"serializer",
"of",
"specification",
"json",
"file"
] | b7795acfc26a30d013655d0e0fa1d3f8d0576571 | https://github.com/indeedeng/proctor/blob/b7795acfc26a30d013655d0e0fa1d3f8d0576571/proctor-common/src/main/java/com/indeed/proctor/common/dynamic/DynamicFilters.java#L48-L51 | train |
indeedeng/proctor | proctor-consumer/src/main/java/com/indeed/proctor/consumer/spring/AbstractSampleRandomGroupsController.java | AbstractSampleRandomGroupsController.getProctorContext | private ProctorContext getProctorContext(final HttpServletRequest request) throws IllegalAccessException, InstantiationException {
final ProctorContext proctorContext = contextClass.newInstance();
final BeanWrapper beanWrapper = new BeanWrapperImpl(proctorContext);
for (final PropertyDescriptor descriptor : beanWrapper.getPropertyDescriptors()) {
final String propertyName = descriptor.getName();
if (!"class".equals(propertyName)) { // ignore class property which every object has
final String parameterValue = request.getParameter(propertyName);
if (parameterValue != null) {
beanWrapper.setPropertyValue(propertyName, parameterValue);
}
}
}
return proctorContext;
} | java | private ProctorContext getProctorContext(final HttpServletRequest request) throws IllegalAccessException, InstantiationException {
final ProctorContext proctorContext = contextClass.newInstance();
final BeanWrapper beanWrapper = new BeanWrapperImpl(proctorContext);
for (final PropertyDescriptor descriptor : beanWrapper.getPropertyDescriptors()) {
final String propertyName = descriptor.getName();
if (!"class".equals(propertyName)) { // ignore class property which every object has
final String parameterValue = request.getParameter(propertyName);
if (parameterValue != null) {
beanWrapper.setPropertyValue(propertyName, parameterValue);
}
}
}
return proctorContext;
} | [
"private",
"ProctorContext",
"getProctorContext",
"(",
"final",
"HttpServletRequest",
"request",
")",
"throws",
"IllegalAccessException",
",",
"InstantiationException",
"{",
"final",
"ProctorContext",
"proctorContext",
"=",
"contextClass",
".",
"newInstance",
"(",
")",
";... | Do some magic to turn request parameters into a context object | [
"Do",
"some",
"magic",
"to",
"turn",
"request",
"parameters",
"into",
"a",
"context",
"object"
] | b7795acfc26a30d013655d0e0fa1d3f8d0576571 | https://github.com/indeedeng/proctor/blob/b7795acfc26a30d013655d0e0fa1d3f8d0576571/proctor-consumer/src/main/java/com/indeed/proctor/consumer/spring/AbstractSampleRandomGroupsController.java#L63-L76 | train |
indeedeng/proctor | proctor-store-git/src/main/java/com/indeed/proctor/store/GitProctorUtils.java | GitProctorUtils.resolveSvnMigratedRevision | public static String resolveSvnMigratedRevision(final Revision revision, final String branch) {
if (revision == null) {
return null;
}
final Pattern pattern = Pattern.compile("^git-svn-id: .*" + branch + "@([0-9]+) ", Pattern.MULTILINE);
final Matcher matcher = pattern.matcher(revision.getMessage());
if (matcher.find()) {
return matcher.group(1);
} else {
return revision.getRevision();
}
} | java | public static String resolveSvnMigratedRevision(final Revision revision, final String branch) {
if (revision == null) {
return null;
}
final Pattern pattern = Pattern.compile("^git-svn-id: .*" + branch + "@([0-9]+) ", Pattern.MULTILINE);
final Matcher matcher = pattern.matcher(revision.getMessage());
if (matcher.find()) {
return matcher.group(1);
} else {
return revision.getRevision();
}
} | [
"public",
"static",
"String",
"resolveSvnMigratedRevision",
"(",
"final",
"Revision",
"revision",
",",
"final",
"String",
"branch",
")",
"{",
"if",
"(",
"revision",
"==",
"null",
")",
"{",
"return",
"null",
";",
"}",
"final",
"Pattern",
"pattern",
"=",
"Patt... | Helper method to retrieve a canonical revision for git commits migrated from SVN. Migrated commits are
detected by the presence of 'git-svn-id' in the commit message.
@param revision the commit/revision to inspect
@param branch the name of the branch it came from
@return the original SVN revision if it was a migrated commit from the branch specified, otherwise the git revision | [
"Helper",
"method",
"to",
"retrieve",
"a",
"canonical",
"revision",
"for",
"git",
"commits",
"migrated",
"from",
"SVN",
".",
"Migrated",
"commits",
"are",
"detected",
"by",
"the",
"presence",
"of",
"git",
"-",
"svn",
"-",
"id",
"in",
"the",
"commit",
"mess... | b7795acfc26a30d013655d0e0fa1d3f8d0576571 | https://github.com/indeedeng/proctor/blob/b7795acfc26a30d013655d0e0fa1d3f8d0576571/proctor-store-git/src/main/java/com/indeed/proctor/store/GitProctorUtils.java#L26-L37 | train |
HubSpot/Rosetta | RosettaCore/src/main/java/com/hubspot/rosetta/RosettaMapper.java | RosettaMapper.mapRow | public T mapRow(ResultSet rs) throws SQLException {
Map<String, Object> map = new HashMap<String, Object>();
ResultSetMetaData metadata = rs.getMetaData();
for (int i = 1; i <= metadata.getColumnCount(); ++i) {
String label = metadata.getColumnLabel(i);
final Object value;
// calling getObject on a BLOB/CLOB produces weird results
switch (metadata.getColumnType(i)) {
case Types.BLOB:
value = rs.getBytes(i);
break;
case Types.CLOB:
value = rs.getString(i);
break;
default:
value = rs.getObject(i);
}
// don't use table name extractor because we don't want aliased table name
boolean overwrite = this.tableName != null && this.tableName.equals(metadata.getTableName(i));
String tableName = TABLE_NAME_EXTRACTOR.getTableName(metadata, i);
if (tableName != null && !tableName.isEmpty()) {
String qualifiedName = tableName + "." + metadata.getColumnName(i);
add(map, qualifiedName, value, overwrite);
}
add(map, label, value, overwrite);
}
return objectMapper.convertValue(map, type);
} | java | public T mapRow(ResultSet rs) throws SQLException {
Map<String, Object> map = new HashMap<String, Object>();
ResultSetMetaData metadata = rs.getMetaData();
for (int i = 1; i <= metadata.getColumnCount(); ++i) {
String label = metadata.getColumnLabel(i);
final Object value;
// calling getObject on a BLOB/CLOB produces weird results
switch (metadata.getColumnType(i)) {
case Types.BLOB:
value = rs.getBytes(i);
break;
case Types.CLOB:
value = rs.getString(i);
break;
default:
value = rs.getObject(i);
}
// don't use table name extractor because we don't want aliased table name
boolean overwrite = this.tableName != null && this.tableName.equals(metadata.getTableName(i));
String tableName = TABLE_NAME_EXTRACTOR.getTableName(metadata, i);
if (tableName != null && !tableName.isEmpty()) {
String qualifiedName = tableName + "." + metadata.getColumnName(i);
add(map, qualifiedName, value, overwrite);
}
add(map, label, value, overwrite);
}
return objectMapper.convertValue(map, type);
} | [
"public",
"T",
"mapRow",
"(",
"ResultSet",
"rs",
")",
"throws",
"SQLException",
"{",
"Map",
"<",
"String",
",",
"Object",
">",
"map",
"=",
"new",
"HashMap",
"<",
"String",
",",
"Object",
">",
"(",
")",
";",
"ResultSetMetaData",
"metadata",
"=",
"rs",
"... | Map a single ResultSet row to a T instance.
@throws SQLException | [
"Map",
"a",
"single",
"ResultSet",
"row",
"to",
"a",
"T",
"instance",
"."
] | 6b45a88d0e604a41c4825b131a4804cfe33e3b3c | https://github.com/HubSpot/Rosetta/blob/6b45a88d0e604a41c4825b131a4804cfe33e3b3c/RosettaCore/src/main/java/com/hubspot/rosetta/RosettaMapper.java#L55-L87 | train |
LarsWerkman/HoloColorPicker | library/src/main/java/com/larswerkman/holocolorpicker/OpacityBar.java | OpacityBar.getOpacity | public int getOpacity() {
int opacity = Math
.round((mPosToOpacFactor * (mBarPointerPosition - mBarPointerHaloRadius)));
if (opacity < 5) {
return 0x00;
} else if (opacity > 250) {
return 0xFF;
} else {
return opacity;
}
} | java | public int getOpacity() {
int opacity = Math
.round((mPosToOpacFactor * (mBarPointerPosition - mBarPointerHaloRadius)));
if (opacity < 5) {
return 0x00;
} else if (opacity > 250) {
return 0xFF;
} else {
return opacity;
}
} | [
"public",
"int",
"getOpacity",
"(",
")",
"{",
"int",
"opacity",
"=",
"Math",
".",
"round",
"(",
"(",
"mPosToOpacFactor",
"*",
"(",
"mBarPointerPosition",
"-",
"mBarPointerHaloRadius",
")",
")",
")",
";",
"if",
"(",
"opacity",
"<",
"5",
")",
"{",
"return"... | Get the currently selected opacity.
@return The int value of the currently selected opacity. | [
"Get",
"the",
"currently",
"selected",
"opacity",
"."
] | 8ba5971f8d25f80c22d9711713a51c7a7c4ac4aa | https://github.com/LarsWerkman/HoloColorPicker/blob/8ba5971f8d25f80c22d9711713a51c7a7c4ac4aa/library/src/main/java/com/larswerkman/holocolorpicker/OpacityBar.java#L458-L468 | train |
LarsWerkman/HoloColorPicker | library/src/main/java/com/larswerkman/holocolorpicker/ColorPicker.java | ColorPicker.calculateColor | private int calculateColor(float angle) {
float unit = (float) (angle / (2 * Math.PI));
if (unit < 0) {
unit += 1;
}
if (unit <= 0) {
mColor = COLORS[0];
return COLORS[0];
}
if (unit >= 1) {
mColor = COLORS[COLORS.length - 1];
return COLORS[COLORS.length - 1];
}
float p = unit * (COLORS.length - 1);
int i = (int) p;
p -= i;
int c0 = COLORS[i];
int c1 = COLORS[i + 1];
int a = ave(Color.alpha(c0), Color.alpha(c1), p);
int r = ave(Color.red(c0), Color.red(c1), p);
int g = ave(Color.green(c0), Color.green(c1), p);
int b = ave(Color.blue(c0), Color.blue(c1), p);
mColor = Color.argb(a, r, g, b);
return Color.argb(a, r, g, b);
} | java | private int calculateColor(float angle) {
float unit = (float) (angle / (2 * Math.PI));
if (unit < 0) {
unit += 1;
}
if (unit <= 0) {
mColor = COLORS[0];
return COLORS[0];
}
if (unit >= 1) {
mColor = COLORS[COLORS.length - 1];
return COLORS[COLORS.length - 1];
}
float p = unit * (COLORS.length - 1);
int i = (int) p;
p -= i;
int c0 = COLORS[i];
int c1 = COLORS[i + 1];
int a = ave(Color.alpha(c0), Color.alpha(c1), p);
int r = ave(Color.red(c0), Color.red(c1), p);
int g = ave(Color.green(c0), Color.green(c1), p);
int b = ave(Color.blue(c0), Color.blue(c1), p);
mColor = Color.argb(a, r, g, b);
return Color.argb(a, r, g, b);
} | [
"private",
"int",
"calculateColor",
"(",
"float",
"angle",
")",
"{",
"float",
"unit",
"=",
"(",
"float",
")",
"(",
"angle",
"/",
"(",
"2",
"*",
"Math",
".",
"PI",
")",
")",
";",
"if",
"(",
"unit",
"<",
"0",
")",
"{",
"unit",
"+=",
"1",
";",
"... | Calculate the color using the supplied angle.
@param angle The selected color's position expressed as angle (in rad).
@return The ARGB value of the color on the color wheel at the specified
angle. | [
"Calculate",
"the",
"color",
"using",
"the",
"supplied",
"angle",
"."
] | 8ba5971f8d25f80c22d9711713a51c7a7c4ac4aa | https://github.com/LarsWerkman/HoloColorPicker/blob/8ba5971f8d25f80c22d9711713a51c7a7c4ac4aa/library/src/main/java/com/larswerkman/holocolorpicker/ColorPicker.java#L475-L503 | train |
LarsWerkman/HoloColorPicker | library/src/main/java/com/larswerkman/holocolorpicker/ColorPicker.java | ColorPicker.colorToAngle | private float colorToAngle(int color) {
float[] colors = new float[3];
Color.colorToHSV(color, colors);
return (float) Math.toRadians(-colors[0]);
} | java | private float colorToAngle(int color) {
float[] colors = new float[3];
Color.colorToHSV(color, colors);
return (float) Math.toRadians(-colors[0]);
} | [
"private",
"float",
"colorToAngle",
"(",
"int",
"color",
")",
"{",
"float",
"[",
"]",
"colors",
"=",
"new",
"float",
"[",
"3",
"]",
";",
"Color",
".",
"colorToHSV",
"(",
"color",
",",
"colors",
")",
";",
"return",
"(",
"float",
")",
"Math",
".",
"t... | Convert a color to an angle.
@param color The RGB value of the color to "find" on the color wheel.
@return The angle (in rad) the "normalized" color is displayed on the
color wheel. | [
"Convert",
"a",
"color",
"to",
"an",
"angle",
"."
] | 8ba5971f8d25f80c22d9711713a51c7a7c4ac4aa | https://github.com/LarsWerkman/HoloColorPicker/blob/8ba5971f8d25f80c22d9711713a51c7a7c4ac4aa/library/src/main/java/com/larswerkman/holocolorpicker/ColorPicker.java#L577-L582 | train |
LarsWerkman/HoloColorPicker | library/src/main/java/com/larswerkman/holocolorpicker/ColorPicker.java | ColorPicker.calculatePointerPosition | private float[] calculatePointerPosition(float angle) {
float x = (float) (mColorWheelRadius * Math.cos(angle));
float y = (float) (mColorWheelRadius * Math.sin(angle));
return new float[] { x, y };
} | java | private float[] calculatePointerPosition(float angle) {
float x = (float) (mColorWheelRadius * Math.cos(angle));
float y = (float) (mColorWheelRadius * Math.sin(angle));
return new float[] { x, y };
} | [
"private",
"float",
"[",
"]",
"calculatePointerPosition",
"(",
"float",
"angle",
")",
"{",
"float",
"x",
"=",
"(",
"float",
")",
"(",
"mColorWheelRadius",
"*",
"Math",
".",
"cos",
"(",
"angle",
")",
")",
";",
"float",
"y",
"=",
"(",
"float",
")",
"("... | Calculate the pointer's coordinates on the color wheel using the supplied
angle.
@param angle The position of the pointer expressed as angle (in rad).
@return The coordinates of the pointer's center in our internal
coordinate system. | [
"Calculate",
"the",
"pointer",
"s",
"coordinates",
"on",
"the",
"color",
"wheel",
"using",
"the",
"supplied",
"angle",
"."
] | 8ba5971f8d25f80c22d9711713a51c7a7c4ac4aa | https://github.com/LarsWerkman/HoloColorPicker/blob/8ba5971f8d25f80c22d9711713a51c7a7c4ac4aa/library/src/main/java/com/larswerkman/holocolorpicker/ColorPicker.java#L687-L692 | train |
LarsWerkman/HoloColorPicker | library/src/main/java/com/larswerkman/holocolorpicker/ColorPicker.java | ColorPicker.addOpacityBar | public void addOpacityBar(OpacityBar bar) {
mOpacityBar = bar;
// Give an instance of the color picker to the Opacity bar.
mOpacityBar.setColorPicker(this);
mOpacityBar.setColor(mColor);
} | java | public void addOpacityBar(OpacityBar bar) {
mOpacityBar = bar;
// Give an instance of the color picker to the Opacity bar.
mOpacityBar.setColorPicker(this);
mOpacityBar.setColor(mColor);
} | [
"public",
"void",
"addOpacityBar",
"(",
"OpacityBar",
"bar",
")",
"{",
"mOpacityBar",
"=",
"bar",
";",
"// Give an instance of the color picker to the Opacity bar.",
"mOpacityBar",
".",
"setColorPicker",
"(",
"this",
")",
";",
"mOpacityBar",
".",
"setColor",
"(",
"mCo... | Add a Opacity bar to the color wheel.
@param bar The instance of the Opacity bar. | [
"Add",
"a",
"Opacity",
"bar",
"to",
"the",
"color",
"wheel",
"."
] | 8ba5971f8d25f80c22d9711713a51c7a7c4ac4aa | https://github.com/LarsWerkman/HoloColorPicker/blob/8ba5971f8d25f80c22d9711713a51c7a7c4ac4aa/library/src/main/java/com/larswerkman/holocolorpicker/ColorPicker.java#L711-L716 | train |
LarsWerkman/HoloColorPicker | library/src/main/java/com/larswerkman/holocolorpicker/ColorPicker.java | ColorPicker.setNewCenterColor | public void setNewCenterColor(int color) {
mCenterNewColor = color;
mCenterNewPaint.setColor(color);
if (mCenterOldColor == 0) {
mCenterOldColor = color;
mCenterOldPaint.setColor(color);
}
if (onColorChangedListener != null && color != oldChangedListenerColor ) {
onColorChangedListener.onColorChanged(color);
oldChangedListenerColor = color;
}
invalidate();
} | java | public void setNewCenterColor(int color) {
mCenterNewColor = color;
mCenterNewPaint.setColor(color);
if (mCenterOldColor == 0) {
mCenterOldColor = color;
mCenterOldPaint.setColor(color);
}
if (onColorChangedListener != null && color != oldChangedListenerColor ) {
onColorChangedListener.onColorChanged(color);
oldChangedListenerColor = color;
}
invalidate();
} | [
"public",
"void",
"setNewCenterColor",
"(",
"int",
"color",
")",
"{",
"mCenterNewColor",
"=",
"color",
";",
"mCenterNewPaint",
".",
"setColor",
"(",
"color",
")",
";",
"if",
"(",
"mCenterOldColor",
"==",
"0",
")",
"{",
"mCenterOldColor",
"=",
"color",
";",
... | Change the color of the center which indicates the new color.
@param color int of the color. | [
"Change",
"the",
"color",
"of",
"the",
"center",
"which",
"indicates",
"the",
"new",
"color",
"."
] | 8ba5971f8d25f80c22d9711713a51c7a7c4ac4aa | https://github.com/LarsWerkman/HoloColorPicker/blob/8ba5971f8d25f80c22d9711713a51c7a7c4ac4aa/library/src/main/java/com/larswerkman/holocolorpicker/ColorPicker.java#L735-L747 | train |
LarsWerkman/HoloColorPicker | library/src/main/java/com/larswerkman/holocolorpicker/SVBar.java | SVBar.setValue | public void setValue(float value) {
mBarPointerPosition = Math.round((mSVToPosFactor * (1 - value))
+ mBarPointerHaloRadius + (mBarLength / 2));
calculateColor(mBarPointerPosition);
mBarPointerPaint.setColor(mColor);
// Check whether the Saturation/Value bar is added to the ColorPicker
// wheel
if (mPicker != null) {
mPicker.setNewCenterColor(mColor);
mPicker.changeOpacityBarColor(mColor);
}
invalidate();
} | java | public void setValue(float value) {
mBarPointerPosition = Math.round((mSVToPosFactor * (1 - value))
+ mBarPointerHaloRadius + (mBarLength / 2));
calculateColor(mBarPointerPosition);
mBarPointerPaint.setColor(mColor);
// Check whether the Saturation/Value bar is added to the ColorPicker
// wheel
if (mPicker != null) {
mPicker.setNewCenterColor(mColor);
mPicker.changeOpacityBarColor(mColor);
}
invalidate();
} | [
"public",
"void",
"setValue",
"(",
"float",
"value",
")",
"{",
"mBarPointerPosition",
"=",
"Math",
".",
"round",
"(",
"(",
"mSVToPosFactor",
"*",
"(",
"1",
"-",
"value",
")",
")",
"+",
"mBarPointerHaloRadius",
"+",
"(",
"mBarLength",
"/",
"2",
")",
")",
... | Set the pointer on the bar. With the Value value.
@param value float between 0 and 1 | [
"Set",
"the",
"pointer",
"on",
"the",
"bar",
".",
"With",
"the",
"Value",
"value",
"."
] | 8ba5971f8d25f80c22d9711713a51c7a7c4ac4aa | https://github.com/LarsWerkman/HoloColorPicker/blob/8ba5971f8d25f80c22d9711713a51c7a7c4ac4aa/library/src/main/java/com/larswerkman/holocolorpicker/SVBar.java#L409-L421 | train |
mikepenz/Materialize | library/src/main/java/com/mikepenz/materialize/util/UIUtils.java | UIUtils.getNavigationBarHeight | public static int getNavigationBarHeight(Context context) {
Resources resources = context.getResources();
int id = resources.getIdentifier(context.getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT ? "navigation_bar_height" : "navigation_bar_height_landscape", "dimen", "android");
if (id > 0) {
return resources.getDimensionPixelSize(id);
}
return 0;
} | java | public static int getNavigationBarHeight(Context context) {
Resources resources = context.getResources();
int id = resources.getIdentifier(context.getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT ? "navigation_bar_height" : "navigation_bar_height_landscape", "dimen", "android");
if (id > 0) {
return resources.getDimensionPixelSize(id);
}
return 0;
} | [
"public",
"static",
"int",
"getNavigationBarHeight",
"(",
"Context",
"context",
")",
"{",
"Resources",
"resources",
"=",
"context",
".",
"getResources",
"(",
")",
";",
"int",
"id",
"=",
"resources",
".",
"getIdentifier",
"(",
"context",
".",
"getResources",
"(... | helper to calculate the navigationBar height
@param context
@return | [
"helper",
"to",
"calculate",
"the",
"navigationBar",
"height"
] | 2612c10c7570191a78d57f23620e945d61370e3d | https://github.com/mikepenz/Materialize/blob/2612c10c7570191a78d57f23620e945d61370e3d/library/src/main/java/com/mikepenz/materialize/util/UIUtils.java#L110-L117 | train |
mikepenz/Materialize | library/src/main/java/com/mikepenz/materialize/util/UIUtils.java | UIUtils.getActionBarHeight | public static int getActionBarHeight(Context context) {
int actionBarHeight = UIUtils.getThemeAttributeDimensionSize(context, R.attr.actionBarSize);
if (actionBarHeight == 0) {
actionBarHeight = context.getResources().getDimensionPixelSize(R.dimen.abc_action_bar_default_height_material);
}
return actionBarHeight;
} | java | public static int getActionBarHeight(Context context) {
int actionBarHeight = UIUtils.getThemeAttributeDimensionSize(context, R.attr.actionBarSize);
if (actionBarHeight == 0) {
actionBarHeight = context.getResources().getDimensionPixelSize(R.dimen.abc_action_bar_default_height_material);
}
return actionBarHeight;
} | [
"public",
"static",
"int",
"getActionBarHeight",
"(",
"Context",
"context",
")",
"{",
"int",
"actionBarHeight",
"=",
"UIUtils",
".",
"getThemeAttributeDimensionSize",
"(",
"context",
",",
"R",
".",
"attr",
".",
"actionBarSize",
")",
";",
"if",
"(",
"actionBarHei... | helper to calculate the actionBar height
@param context
@return | [
"helper",
"to",
"calculate",
"the",
"actionBar",
"height"
] | 2612c10c7570191a78d57f23620e945d61370e3d | https://github.com/mikepenz/Materialize/blob/2612c10c7570191a78d57f23620e945d61370e3d/library/src/main/java/com/mikepenz/materialize/util/UIUtils.java#L125-L131 | train |
mikepenz/Materialize | library/src/main/java/com/mikepenz/materialize/util/UIUtils.java | UIUtils.getStatusBarHeight | public static int getStatusBarHeight(Context context, boolean force) {
int result = 0;
int resourceId = context.getResources().getIdentifier("status_bar_height", "dimen", "android");
if (resourceId > 0) {
result = context.getResources().getDimensionPixelSize(resourceId);
}
int dimenResult = context.getResources().getDimensionPixelSize(R.dimen.tool_bar_top_padding);
//if our dimension is 0 return 0 because on those devices we don't need the height
if (dimenResult == 0 && !force) {
return 0;
} else {
//if our dimens is > 0 && the result == 0 use the dimenResult else the result;
return result == 0 ? dimenResult : result;
}
} | java | public static int getStatusBarHeight(Context context, boolean force) {
int result = 0;
int resourceId = context.getResources().getIdentifier("status_bar_height", "dimen", "android");
if (resourceId > 0) {
result = context.getResources().getDimensionPixelSize(resourceId);
}
int dimenResult = context.getResources().getDimensionPixelSize(R.dimen.tool_bar_top_padding);
//if our dimension is 0 return 0 because on those devices we don't need the height
if (dimenResult == 0 && !force) {
return 0;
} else {
//if our dimens is > 0 && the result == 0 use the dimenResult else the result;
return result == 0 ? dimenResult : result;
}
} | [
"public",
"static",
"int",
"getStatusBarHeight",
"(",
"Context",
"context",
",",
"boolean",
"force",
")",
"{",
"int",
"result",
"=",
"0",
";",
"int",
"resourceId",
"=",
"context",
".",
"getResources",
"(",
")",
".",
"getIdentifier",
"(",
"\"status_bar_height\"... | helper to calculate the statusBar height
@param context
@param force pass true to get the height even if the device has no translucent statusBar
@return | [
"helper",
"to",
"calculate",
"the",
"statusBar",
"height"
] | 2612c10c7570191a78d57f23620e945d61370e3d | https://github.com/mikepenz/Materialize/blob/2612c10c7570191a78d57f23620e945d61370e3d/library/src/main/java/com/mikepenz/materialize/util/UIUtils.java#L150-L165 | train |
mikepenz/Materialize | library/src/main/java/com/mikepenz/materialize/util/UIUtils.java | UIUtils.setTranslucentStatusFlag | public static void setTranslucentStatusFlag(Activity activity, boolean on) {
if (Build.VERSION.SDK_INT >= 19) {
setFlag(activity, WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS, on);
}
} | java | public static void setTranslucentStatusFlag(Activity activity, boolean on) {
if (Build.VERSION.SDK_INT >= 19) {
setFlag(activity, WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS, on);
}
} | [
"public",
"static",
"void",
"setTranslucentStatusFlag",
"(",
"Activity",
"activity",
",",
"boolean",
"on",
")",
"{",
"if",
"(",
"Build",
".",
"VERSION",
".",
"SDK_INT",
">=",
"19",
")",
"{",
"setFlag",
"(",
"activity",
",",
"WindowManager",
".",
"LayoutParam... | helper method to set the TranslucentStatusFlag
@param on | [
"helper",
"method",
"to",
"set",
"the",
"TranslucentStatusFlag"
] | 2612c10c7570191a78d57f23620e945d61370e3d | https://github.com/mikepenz/Materialize/blob/2612c10c7570191a78d57f23620e945d61370e3d/library/src/main/java/com/mikepenz/materialize/util/UIUtils.java#L200-L204 | train |
mikepenz/Materialize | library/src/main/java/com/mikepenz/materialize/util/UIUtils.java | UIUtils.setTranslucentNavigationFlag | public static void setTranslucentNavigationFlag(Activity activity, boolean on) {
if (Build.VERSION.SDK_INT >= 19) {
setFlag(activity, WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION, on);
}
} | java | public static void setTranslucentNavigationFlag(Activity activity, boolean on) {
if (Build.VERSION.SDK_INT >= 19) {
setFlag(activity, WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION, on);
}
} | [
"public",
"static",
"void",
"setTranslucentNavigationFlag",
"(",
"Activity",
"activity",
",",
"boolean",
"on",
")",
"{",
"if",
"(",
"Build",
".",
"VERSION",
".",
"SDK_INT",
">=",
"19",
")",
"{",
"setFlag",
"(",
"activity",
",",
"WindowManager",
".",
"LayoutP... | helper method to set the TranslucentNavigationFlag
@param on | [
"helper",
"method",
"to",
"set",
"the",
"TranslucentNavigationFlag"
] | 2612c10c7570191a78d57f23620e945d61370e3d | https://github.com/mikepenz/Materialize/blob/2612c10c7570191a78d57f23620e945d61370e3d/library/src/main/java/com/mikepenz/materialize/util/UIUtils.java#L211-L215 | train |
mikepenz/Materialize | library/src/main/java/com/mikepenz/materialize/util/UIUtils.java | UIUtils.setFlag | public static void setFlag(Activity activity, final int bits, boolean on) {
Window win = activity.getWindow();
WindowManager.LayoutParams winParams = win.getAttributes();
if (on) {
winParams.flags |= bits;
} else {
winParams.flags &= ~bits;
}
win.setAttributes(winParams);
} | java | public static void setFlag(Activity activity, final int bits, boolean on) {
Window win = activity.getWindow();
WindowManager.LayoutParams winParams = win.getAttributes();
if (on) {
winParams.flags |= bits;
} else {
winParams.flags &= ~bits;
}
win.setAttributes(winParams);
} | [
"public",
"static",
"void",
"setFlag",
"(",
"Activity",
"activity",
",",
"final",
"int",
"bits",
",",
"boolean",
"on",
")",
"{",
"Window",
"win",
"=",
"activity",
".",
"getWindow",
"(",
")",
";",
"WindowManager",
".",
"LayoutParams",
"winParams",
"=",
"win... | helper method to activate or deactivate a specific flag
@param bits
@param on | [
"helper",
"method",
"to",
"activate",
"or",
"deactivate",
"a",
"specific",
"flag"
] | 2612c10c7570191a78d57f23620e945d61370e3d | https://github.com/mikepenz/Materialize/blob/2612c10c7570191a78d57f23620e945d61370e3d/library/src/main/java/com/mikepenz/materialize/util/UIUtils.java#L223-L232 | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.