diff --git a/.gitignore b/.gitignore index 9b89fc9d..be2b3174 100644 --- a/.gitignore +++ b/.gitignore @@ -8,3 +8,4 @@ bin *.iml **/integrationTest.properties /target/ +.checkstyle diff --git a/.travis.yml b/.travis.yml deleted file mode 100644 index 5374a2d0..00000000 --- a/.travis.yml +++ /dev/null @@ -1,9 +0,0 @@ -language: java - -jdk: - - oraclejdk8 - -script: - mvn clean verify - -sudo: false diff --git a/README.md b/README.md index 3009c320..4f52894e 100755 --- a/README.md +++ b/README.md @@ -3,16 +3,88 @@ OpenShift Java REST Client [![Travis](https://travis-ci.org/openshift/openshift-restclient-java.svg?branch=master)](https://travis-ci.org/openshift/openshift-restclient-java) [![Maven Central](https://maven-badges.herokuapp.com/maven-central/com.openshift/openshift-restclient-java/badge.svg)](https://maven-badges.herokuapp.com/maven-central/com.openshift/openshift-restclient-java) +**The project is now in the maintenance mode. Only critical bugs will be fixed, and there won’t be any more feature development. Please consider moving to the OpenShift client library that's developed by the great team at [fabric8](https://github.com/fabric8io/kubernetes-client/).** + This is the Java REST client for the version 3 architecture of [OpenShift](https://github.com/openshift/origin) based on Kubernetes. The implementation is -a work in progress to provide functionality and features of the command-line interface and is used by JBoss Tools for OpenShift. For compatibility with +a work in progress to provide similar functionality and features of the command-line interface and is used by JBoss Tools for OpenShift. For compatibility with OpenShift 2.x see https://github.com/openshift/openshift-java-client/. -Usage ------ - IClient client = new ClientFactory().create(url, sslCertCallback); - client.setAuthorizationStrategy(new TokenAuthorizationStrategy("ADSASEAWRA-AFAEWAAA"); - List projects = client.list(ResourceKind.PROJECTS, "test-project"); +For questions or feedback, reach us on IRC on #openshift-client on Freenode or post to our [mailing list](https://lists.openshift.redhat.com/openshiftmm/listinfo/dev) Download -------- -You may either build from source using maven (mvn clean package) or get the prebuilt artifact from the maven central. +You may either build from source using maven (mvn clean package) which, using the master branch, will generate a snapshot build of the latest updates. You may also retrieve final released jars from [Maven Central](http://search.maven.org/#search%7Cgav%7C1%7Cg%3A%22com.openshift%22%20AND%20a%3A%22openshift-restclient-java%22). + +Compatibility +--------- +Versions of this client known to be compatible with OpenShift + +| Client Version | OpenShift Origin Server | +|--------------------------|-------------------------| +| 5.4.0-SNAPSHOT | v1.3.0 | +| 5.0.0-SNAPSHOT | latest, v1.3.0-alpha.2 | +| | v1.3.0-alpha.3 | + + +Usage +----- + +Creating a client: + + IClient client = new ClientBuilder("https://api.preview.openshift.com") + .withUserName("openshiftdev") + .withPassword("wouldntUlik3T0kn0w") + .build(); + +This will authorize the client if the cluster is configured for basic authorization. The alternative is to retrieve your OAUTH token and provide it to the client. The token can be set with the builder or later by accessing the authorization context: + + client.getAuthorizationContext().setToken("asfdsfd8a70a3qrfafdsadsf786324"); + +Create a project to associate with your application by submitting a project request: + + IResource request = client.getResourceFactory().stub(ResourceKind.PROJECT_REQUEST, "myfirstproject"); + IProject project = (IProject)client.create(request); + +Resources can be created by stubbing which will instantiate and instance of the resource but not create it on the server: + + IService service = client.getResourceFactory().stub(ResourceKind.SERVICE, "myfirstservice", project.getName()); + service.setSelector(labelSelectors); + service = client.create(service); + + +The client as well as resources supported by OpenShift may have certain capabilities that are instantiated when the resource is initialized. The [capabilities](https://github.com/openshift/openshift-restclient-java/tree/master/src/main/java/com/openshift/restclient/capability) are implemented using an adapter pattern and used like the following to create a BuildConfig: + + IBuildConfig buildConfig = client.accept(new CapabilityVisitor() { + + @Override + public IBuildConfig visit(IBuildConfigBuilder builder) { + return builder + .named("mybuildconfig") + .inNamespace(project.getName()) + .fromGitSource() + .fromGitUrl("https://github.com/openshift/rails-example") + .usingGitReference("master") + .end() + .usingSourceStrategy() + .fromImageStreamTag("ruby:latest") + .inNamespace("openshift") + .withEnvVars(envVars) + .end() + .buildOnSourceChange(true) + .buildOnConfigChange(true) + .buildOnImageChange(true) + .toImageStreamTag("mybuildconfig:latest") + .build(); + } + }, null); + +Various examples of using the capabilities may be found in the integration tests. + +Testing +------- + +To run the integration tests: + +1. Define a user with cluster admin privilege +1. Download the oc binary +1. Run the tests: `mvn integration-test -Pintegration-tests -DserverURL=https://localhost:8443 -Ddefault.cluster.admin=foo -Ddefault.cluster.password=bar -Ddefault.openshift.location=/tmp/oc` diff --git a/checkstyle-suppressions.xml b/checkstyle-suppressions.xml new file mode 100644 index 00000000..5859ee5c --- /dev/null +++ b/checkstyle-suppressions.xml @@ -0,0 +1,9 @@ + + + + + + + diff --git a/checkstyle.xml b/checkstyle.xml new file mode 100644 index 00000000..ef0dd3ab --- /dev/null +++ b/checkstyle.xml @@ -0,0 +1,261 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/pom.xml b/pom.xml old mode 100755 new mode 100644 index 0cc5ba5d..d2c2640f --- a/pom.xml +++ b/pom.xml @@ -1,360 +1,392 @@ + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> - - - org.jboss - jboss-parent - 6-beta-2 - - + + + org.jboss + jboss-parent + 6-beta-2 + + - - 4.0.0 + + 4.0.0 - - com.openshift - openshift-restclient-java - 4.1.0-SNAPSHOT - jar - OpenShift Java REST Client - http://openshift.redhat.com - OpenShift Java Client + + com.openshift + openshift-restclient-java + 9.0.6-SNAPSHOT + jar + OpenShift Java REST Client + http://openshift.redhat.com + OpenShift Java Client - + - - + + UTF-8 - - 2.1 - 1.8 - 1.8 + + 2.1 + 3.0.0-M1 + 1.8 + 1.8 - - 1.0.0-beta-6 - 1.0.0-beta-5 - 1.1.0-beta-1 + + 1.0.0-beta-6 + 1.0.0-beta-5 + 1.1.0-beta-1 + 2.0.1 + 2.19.0 - - ${basedir}/src/test/resources/integrationTest.properties - ${project.build.directory} - + + ${basedir}/src/test/resources/openshiftv3IntegrationTest.properties + ${project.build.directory} + - - - jira - https://issues.jboss.org/browse/OSJC - + + + jira + https://issues.jboss.org/browse/OSJC + - - - - Eclipse Public License v1.0 - http://www.eclipse.org/legal/epl-v10.html - - + + + + Eclipse Public License v1.0 + http://www.eclipse.org/legal/epl-v10.html + + - - - - src/main/resources - true - - - - - - - org.codehaus.mojo - properties-maven-plugin - 1.0-alpha-1 - - - initialize - - read-project-properties - - - - ${integrationtest.properties} - - - - - - - maven-surefire-plugin - 2.12 - - -Dfile.encoding=UTF-8 - - **/*IntegrationTest.java - - - - - maven-jar-plugin - 2.4 - - ${jar.outputDir} - - - - maven-source-plugin - - - package-sources - package - - jar - - - - - ${jar.outputDir} - - - - maven-deploy-plugin - 2.8.2 - - - - + + + + src/main/resources + true + + + + + org.apache.maven.plugins + maven-checkstyle-plugin + 3.1.0 + + + com.puppycrawl.tools + checkstyle + 8.29 + + + + + + ${project.basedir}/checkstyle.xml + UTF-8 + license.txt + true + true + false + true + warning + + + check + + + + + + + org.codehaus.mojo + properties-maven-plugin + 1.0-alpha-1 + + + initialize + + read-project-properties + + + + ${integrationtest.properties} + + + + + + + maven-surefire-plugin + 2.12 + + -Dfile.encoding=UTF-8 + + **/*IntegrationTest.java + + + + + maven-jar-plugin + 2.4 + + ${jar.outputDir} + + + + maven-source-plugin + + + package-sources + package + + jar + + + + + ${jar.outputDir} + + + + maven-deploy-plugin + 2.8.2 + + + - - - org.yaml - snakeyaml - 1.14 - - - org.jboss - jboss-dmr - 1.3.0.Final - - - com.jcraft - jsch - 0.1.51 - - - org.apache.commons - commons-io - 1.3.2 - - - org.apache.commons - commons-compress - 1.8.1 - - - junit - junit - 4.8.2 - test - - - org.mockito - mockito-core - 1.9.0-rc1 - test - - - org.easytesting - fest-assert - 1.4 - test - - - commons-io - commons-io - 2.1 - + + + com.squareup.okhttp3 + okhttp + 4.10.0 + + + org.yaml + snakeyaml + 1.32 + + + org.jboss + jboss-dmr + 1.6.1.Final + + + org.apache.commons + commons-io + 1.3.2 + + + org.apache.commons + commons-compress + 1.21 + + + commons-io + commons-io + 2.11.0 + org.slf4j slf4j-api - 1.6.4 - - - org.slf4j - slf4j-log4j12 - 1.6.4 - - - log4j - log4j - 1.2.16 + ${version.slf4j} + + commons-codec + commons-codec + 1.15 + + + commons-lang + commons-lang + 2.6 + - org.eclipse.jetty.websocket - websocket-client - 9.2.13.v20150730 + org.apache.logging.log4j + log4j-api + ${version.log4j} + test - org.eclipse.jetty - jetty-client - 9.2.13.v20150730 + org.apache.logging.log4j + log4j-core + ${version.log4j} + test - org.apache.httpcomponents - httpclient - 4.3.6 + org.apache.logging.log4j + log4j-slf4j-impl + ${version.log4j} + test + + junit + junit + 4.13.2 + test + + + org.mockito + mockito-core + 4.8.0 + test + - org.apache.httpcomponents - httpcore - 4.3.3 - - - commons-codec - commons-codec - 1.6 - - - commons-lang - commons-lang - 2.6 - - - org.skyscreamer - jsonassert - 1.2.3 - test - - + org.assertj + assertj-core + 3.23.1 + test + + + org.skyscreamer + jsonassert + 1.5.1 + test + + + + + release + + + + maven-release-plugin + + true + false + true + + + + maven-javadoc-plugin + + org.jboss.apiviz.APIviz + + org.jboss.apiviz + apiviz + 1.3.1.GA + + true + UTF-8 + UTF-8 + UTF-8 + true + true + true + true + -sourceclasspath + ${project.build.outputDirectory} + ${project.parent.parent.basedir}/javadoc/stylesheet.css + ${project.parent.parent.basedir}/javadoc + + + + attach-javadocs + + jar + + + + - - - release - - - - maven-release-plugin - - true - false - true - - - - maven-javadoc-plugin - - org.jboss.apiviz.APIviz - - org.jboss.apiviz - apiviz - 1.3.1.GA - - true - UTF-8 - UTF-8 - UTF-8 - true - true - true - true - -sourceclasspath - ${project.build.outputDirectory} - ${project.parent.parent.basedir}/javadoc/stylesheet.css - ${project.parent.parent.basedir}/javadoc - - - - attach-javadocs - - jar - - - - - - - + + + - - - defaultprofile - - - axis - defaultprofile - - - - true - - + + + defaultprofile + + + axis + defaultprofile + + + + true + + - - - integration-tests - - - axis - integration-tests - - - - - - org.apache.maven.plugins - maven-surefire-plugin - 2.12 - - - ${libra_server} - ${default_rhlogin} - ${rhpassword} - ${proxyHost} - ${proxyPort} - ${proxyHost} - ${proxyPort} - ${proxyHost} - ${proxyPort} - - - **/OpenShiftSuite.java - - - **/OpenShiftIntegrationTestSuite.java - - none - - - - integration-tests - integration-test - - test - - - false - - none - - - **/integration/*Test.java - - - - - - - - - - - https://github.com/openshift/openshift-restclient-java - - - Red Hat, Inc - http://www.redhat.com - + + + integration-tests + + + axis + integration-tests + + + + + + org.apache.maven.plugins + maven-surefire-plugin + 2.12 + + + ${libra_server} + ${default_rhlogin} + ${rhpassword} + ${openshift.binary.location} + + + none + + + **/*IntegrationTest.java + + + + + + integration-tests + integration-test + + test + + + false + + none + + + **/*IntegrationTest.java + + + + + + + + + + jdk9 + + 9 + + + + + maven-surefire-plugin + + -Dfile.encoding=UTF-8 + --add-modules=ALL-SYSTEM + + + + + + + + https://github.com/openshift/openshift-restclient-java + + + Red Hat, Inc + http://www.redhat.com + diff --git a/src/main/java/com/openshift/internal/restclient/APIModelVersion.java b/src/main/java/com/openshift/internal/restclient/APIModelVersion.java index ed58adb6..b9cc6af6 100644 --- a/src/main/java/com/openshift/internal/restclient/APIModelVersion.java +++ b/src/main/java/com/openshift/internal/restclient/APIModelVersion.java @@ -6,25 +6,31 @@ * * Contributors: Red Hat, Inc. ******************************************************************************/ + package com.openshift.internal.restclient; import java.util.Comparator; -/** - * @author Jeff Cantrill - */ public interface APIModelVersion { - int getOrder(); - - static class VersionComparitor implements Comparator { - @Override - public int compare(APIModelVersion v1, APIModelVersion v2) { - if(v2 == null) return 1; - if(v1 == null) return -1; - if(v1.getOrder() < v2.getOrder()) return -1; - if(v1.getOrder() > v2.getOrder()) return 1; - return 0; - } - }; + int getOrder(); + + static class VersionComparitor implements Comparator { + @Override + public int compare(APIModelVersion v1, APIModelVersion v2) { + if (v2 == null) { + return 1; + } + if (v1 == null) { + return -1; + } + if (v1.getOrder() < v2.getOrder()) { + return -1; + } + if (v1.getOrder() > v2.getOrder()) { + return 1; + } + return 0; + } + } } diff --git a/src/main/java/com/openshift/internal/restclient/ApiTypeMapper.java b/src/main/java/com/openshift/internal/restclient/ApiTypeMapper.java index 18019df9..f1863c85 100644 --- a/src/main/java/com/openshift/internal/restclient/ApiTypeMapper.java +++ b/src/main/java/com/openshift/internal/restclient/ApiTypeMapper.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2016 Red Hat, Inc. + * Copyright (c) 2016-2019 Red Hat, Inc. * Distributed under license by Red Hat, Inc. All rights reserved. * This program is made available under the terms of the * Eclipse Public License v1.0 which accompanies this distribution, @@ -8,10 +8,10 @@ * Contributors: * Red Hat, Inc. - initial API and implementation ******************************************************************************/ + package com.openshift.internal.restclient; -import java.net.MalformedURLException; -import java.net.SocketTimeoutException; +import java.io.IOException; import java.net.URL; import java.util.ArrayList; import java.util.Arrays; @@ -19,388 +19,524 @@ import java.util.HashMap; import java.util.List; import java.util.Map; +import java.util.Objects; import java.util.Optional; -import java.util.concurrent.atomic.AtomicBoolean; import java.util.stream.Collectors; -import java.util.stream.Stream; import org.apache.commons.lang.StringUtils; import org.jboss.dmr.ModelNode; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import com.openshift.internal.restclient.http.HttpClientException; -import com.openshift.internal.restclient.http.NotFoundException; import com.openshift.internal.restclient.model.properties.ResourcePropertyKeys; +import com.openshift.internal.restclient.okhttp.OpenShiftRequestBuilder; import com.openshift.internal.util.JBossDmrExtentions; import com.openshift.restclient.IApiTypeMapper; import com.openshift.restclient.OpenShiftException; import com.openshift.restclient.ResourceKind; -import com.openshift.restclient.http.IHttpClient; -import com.openshift.restclient.http.IHttpConstants; +import com.openshift.restclient.UnsupportedEndpointException; +import com.openshift.restclient.authorization.IAuthorizationContext; import com.openshift.restclient.model.IResource; +import okhttp3.OkHttpClient; +import okhttp3.Request; +import okhttp3.Response; + /** - * Typemapper to determine the endpoints for - * various openshift resources + * Typemapper to determine the endpoints for various openshift resources + * * @author jeff.cantrill * */ -public class ApiTypeMapper implements IApiTypeMapper, ResourcePropertyKeys{ - - private static final String FWD_SLASH = "/"; - private static final String KUBE_API = "api"; - private static final String OS_API = "oapi"; - private static final String API_GROUPS_API = "apis"; - private static final Logger LOGGER = LoggerFactory.getLogger(ApiTypeMapper.class); - private final String baseUrl; - private final IHttpClient client; - private List resourceEndpoints; - private Map preferedVersion = new HashMap<>(2); - private AtomicBoolean initialized = new AtomicBoolean(false); - - public ApiTypeMapper(String baseUrl, IHttpClient client) { - this.baseUrl = baseUrl; - this.client = client; - preferedVersion.put(KUBE_API, KubernetesAPIVersion.v1.toString()); - preferedVersion.put(OS_API, OpenShiftAPIVersion.v1.toString()); - } - - @Override - public boolean isSupported(IResource resource) { - return isSupported(resource.getApiVersion(), resource.getKind()); - } - - @Override - public IVersionedApiResource getEndpointFor(String apiVersion, String kind) { - init(); - IVersionedApiResource apiresource = endpointFor(apiVersion, kind); - if(apiresource == null) { - throw new OpenShiftException("No endpoint found for %s, version %s", kind, apiVersion); - } - return apiresource; - } - - private IVersionedApiResource endpointFor(String version, String kind) { - String[] split = StringUtils.isBlank(version) ? new String [] {} : version.split(FWD_SLASH); - Optional result = null; - if(split.length <=1) { - result = Stream.of(KUBE_API, OS_API) - .map(api->formatEndpointFor(api, (split.length == 0 ? preferedVersion.get(api) : split[0]), kind)) - .filter(e->resourceEndpoints.contains(e)) - .findFirst(); - }else{ - result = Optional.of(formatEndpointFor(API_GROUPS_API, version, ResourceKind.pluralize(kind, true, true))); - } - if(result.isPresent()) { - int index = resourceEndpoints.indexOf(result.get()); - if(index > -1) { - return resourceEndpoints.get(index); - } - } - return null; - } - - @Override - public boolean isSupported(String kind) { - return isSupported(null, kind); - } - - @Override - public boolean isSupported(String version, String kind) { - init(); - return endpointFor(version, kind) != null; - } - - private IVersionedApiResource formatEndpointFor(String prefix, String version, String kind) { - return new VersionedApiResource(prefix, version, ResourceKind.pluralize(kind, true, true)); - } - - private void init() { - if(initialized.compareAndSet(false, true)) { - try { - List resourceEndpoints = new ArrayList<>(); - Collection groups = getLegacyGroups(); - groups.addAll(getApiGroups()); - groups.forEach(g->{ - Collection versions = g.getVersions(); - versions.forEach(v->{ - Collection resources = getResources(g, v); - addEndpoints(resourceEndpoints, g.getPrefix(), g.getName(), v, resources); - }); - }); - this.resourceEndpoints = resourceEndpoints; - }catch(Exception e) { - initialized.set(false); - throw e; - } - } - } - - private void addEndpoints(List endpoints, final String prefix, final String apiGroupName, final String version, final Collection nodes) { - for (ModelNode node : nodes) { - String name = node.get(NAME).asString(); - String capability = null; - if(name.contains(FWD_SLASH)) { - int first = name.indexOf(FWD_SLASH); - capability = name.substring(first+1); - name = name.substring(0, first); - } - boolean namespaced = node.get("namespaced").asBoolean(); - VersionedApiResource resource = new VersionedApiResource(prefix, apiGroupName, version, name, node.get(KIND).asString(), namespaced); - if(!endpoints.contains(resource)) { - endpoints.add(resource); - } - if(capability != null) { - int index = endpoints.indexOf(resource); - endpoints.get(index).addCapability(capability); - } - } - } - - private Collection getApiGroups(){ - String json = readEndpoint(API_GROUPS_API); - return ModelNode.fromJSONString(json) - .get("groups") - .asList() - .stream() - .map(n->new ApiGroup(API_GROUPS_API, n)) - .collect(Collectors.toList()); - } - - private Collection getResources(IApiGroup group, String version){ - String json = readEndpoint(group.pathFor(version)); - if(StringUtils.isBlank(json)) { - return new ArrayList<>(); - } - ModelNode node = ModelNode.fromJSONString(json); - return node.get("resources").asList(); - } - - private Collection getLegacyGroups(){ - Collection groups = new ArrayList<>(); - for(String e: Arrays.asList(KUBE_API,OS_API)) { - String json = readEndpoint(e); - ModelNode n = ModelNode.fromJSONString(json); - groups.add(new LegacyApiGroup(e,n)); - } - return groups; - } - - private String readEndpoint(final String endpoint) { - try { - final URL url = new URL(new URL(this.baseUrl), endpoint); - LOGGER.debug(url.toString()); - String response = client.get(url, IHttpConstants.DEFAULT_READ_TIMEOUT); - LOGGER.debug(response); - return response; - } catch (MalformedURLException | SocketTimeoutException e) { - throw new OpenShiftException(e,""); - //HACK - This gets us around a server issue - } catch (HttpClientException e) { - if(e instanceof NotFoundException) { - throw new com.openshift.restclient.NotFoundException(e); - } - LOGGER.error("Unauthorized exception. Can system:anonymous get the API endpoint", e); - throw e; - } - } - - static class ApiGroup implements IApiGroup{ - private final ModelNode node; - private final String prefix; - private final String path; - - ApiGroup(String prefix, ModelNode node) { - this.prefix = prefix; - this.node = node; - StringBuilder builder = new StringBuilder(prefix); - if(getName() != null) { //null name for k8e or openshift - builder - .append(FWD_SLASH) - .append(getName()); - } - path = builder.toString(); - } - - protected ModelNode getNode() { - return node; - } - - @Override - public String getPrefix() { - return prefix; - } - - @Override - public String getName() { - return JBossDmrExtentions.asString(node, new HashMap<>(), NAME); - } - - @Override - public Collection getVersions() { - return JBossDmrExtentions.get(node, new HashMap<>(), "versions").asList() - .stream().map(n->n.get("version").asString()) - .collect(Collectors.toList()); - } - - @Override - public String getPreferedVersion() { - return JBossDmrExtentions.asString(node, new HashMap<>(), "preferedVersion.version"); - } - - @Override - public String pathFor(String version) { - //add check for supported version? - return String.format("%s/%s", path, version); - } - } - - static class LegacyApiGroup extends ApiGroup{ - - LegacyApiGroup(String prefix, ModelNode node) { - super(prefix, node); - } - - @Override - public String getName() { - return null; - } - - @Override - public Collection getVersions() { - return JBossDmrExtentions.get(getNode(), new HashMap<>(), "versions").asList() - .stream().map(n->n.asString()) - .collect(Collectors.toList()); - } - - @Override - public String getPreferedVersion() { - return OpenShiftAPIVersion.v1.toString(); - } - - - } - - static class VersionedApiResource implements IVersionedApiResource { - - private final String prefix; - private final String name; - private final boolean namespaced; - private final Collection capabilities = new ArrayList<>(); - private final String version; - private String apiGroupName; - private String kind; - - VersionedApiResource(String prefix, String version, String name){ - if(version == null) throw new IllegalArgumentException("version can not be null when creating a VersionedApiResource "); - if(version.contains(FWD_SLASH)) { - int last = version.lastIndexOf(FWD_SLASH); - this.apiGroupName = version.substring(0, last); - version = version.substring(last + 1); - } - this.prefix = prefix; - this.name = name; - this.version = version; - this.namespaced = false; - } - - VersionedApiResource(String prefix, String apiGroupName, String version, String name, String kind, boolean namespaced){ - this.prefix = prefix; - this.name = name; - this.namespaced = namespaced; - this.version = version; - this.apiGroupName = apiGroupName; - this.kind = kind; - } - - public void addCapability(String capability) { - capabilities.add(capability); - } - - @Override - public String getApiGroupName() { - return apiGroupName; - } - - @Override - public String getVersion() { - return this.version; - } - - @Override - public String getPrefix() { - return prefix; - } - - @Override - public String getName() { - return name; - } - - - @Override - public String getKind() { - return kind; - } - - @Override - public boolean isNamespaced() { - return namespaced; - } - - @Override - public boolean isSupported(String capability) { - return capabilities.contains(capability); - } - - @Override - public String toString() { - return String.format("%s/%s/%s/%s/%s", prefix, apiGroupName, version, name, version,kind); - } - - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = prime * result + ((apiGroupName == null) ? 0 : apiGroupName.hashCode()); - result = prime * result + ((name == null) ? 0 : name.hashCode()); - result = prime * result + ((prefix == null) ? 0 : prefix.hashCode()); - result = prime * result + ((version == null) ? 0 : version.hashCode()); - return result; - } - - @Override - public boolean equals(Object obj) { - if (this == obj) - return true; - if (obj == null) - return false; - if (getClass() != obj.getClass()) - return false; - VersionedApiResource other = (VersionedApiResource) obj; - if (apiGroupName == null) { - if (other.apiGroupName != null) - return false; - } else if (!apiGroupName.equals(other.apiGroupName)) - return false; - if (name == null) { - if (other.name != null) - return false; - } else if (!name.equals(other.name)) - return false; - if (prefix == null) { - if (other.prefix != null) - return false; - } else if (!prefix.equals(other.prefix)) - return false; - if (version == null) { - if (other.version != null) - return false; - } else if (!version.equals(other.version)) - return false; - return true; - } - - } +public class ApiTypeMapper implements IApiTypeMapper, ResourcePropertyKeys { + + private static final Logger LOGGER = LoggerFactory.getLogger(ApiTypeMapper.class); + private final String baseUrl; + private final OkHttpClient client; + private IAuthorizationContext authorizationContext; + private List resourceEndpoints; + private List types; + private final Map preferedVersion = new HashMap<>(2); + private boolean initialized = false; + + public ApiTypeMapper(String baseUrl, OkHttpClient client, IAuthorizationContext authorizationContext) { + this.baseUrl = baseUrl; + this.client = client; + this.authorizationContext = authorizationContext; + preferedVersion.put(KUBE_API, KubernetesAPIVersion.v1.toString()); + preferedVersion.put(OS_API, OpenShiftAPIVersion.v1.toString()); + } + + @Override + public String getPreferedVersionFor(String endpoint) { + return preferedVersion.get(endpoint); + } + + @Override + public boolean isSupported(IResource resource) { + return isSupported(resource.getApiVersion(), resource.getKind()); + } + + @Override + public boolean isSupported(String kind) { + return isSupported(null, kind); + } + + @Override + public boolean isSupported(String version, String kind) { + init(); + return endpointFor(version, kind) != null; + } + + @Override + public IVersionedApiResource getEndpointFor(String apiVersion, String kind) { + init(); + IVersionedApiResource apiresource = endpointFor(apiVersion, kind); + if (apiresource == null) { + throw new UnsupportedEndpointException("No endpoint found for %s, version %s", kind, apiVersion); + } + return apiresource; + } + + private boolean isResourceCompatible(String kind, String[] apiGroupNameAndVersion, + VersionedApiResource versionedResource) { + return versionedResource.getName().equals(ResourceKind.pluralize(kind, true, true)) + && (apiGroupNameAndVersion.length == 0 || versionedResource.getVersion().equals(apiGroupNameAndVersion[apiGroupNameAndVersion.length - 1])) + && (apiGroupNameAndVersion.length < 2 || versionedResource.getApiGroupName().equals(apiGroupNameAndVersion[0])); + } + + private IVersionedApiResource endpointFor(String version, String kind) { + String[] split = StringUtils.isBlank(version) ? new String[] {} : version.split(FWD_SLASH); + Optional result = null; + if (split.length <= 1) { + result = resourceEndpoints.stream().filter(e -> + isResourceCompatible(kind, split, e) + + ).findFirst(); + } else { + result = Optional.of(formatEndpointFor(API_GROUPS_API, version, kind)); + } + if (result.isPresent()) { + int index = resourceEndpoints.indexOf(result.get()); + if (index > -1) { + return resourceEndpoints.get(index); + } + } + return null; + } + + private IVersionedApiResource formatEndpointFor(String prefix, String version, String kind) { + return new VersionedApiResource(prefix, version, ResourceKind.pluralize(kind, true, true)); + } + + @Override + public IVersionedType getType(String apiVersion, String kind) { + init(); + IVersionedType type = typeFor(apiVersion, kind); + if (type == null) { + throw new UnsupportedEndpointException("No endpoint found for %s, version %s", kind, apiVersion); + } + return type; + } + + private IVersionedType typeFor(String version, String kind) { + String[] split = StringUtils.isBlank(version) ? new String[] {} : version.split(FWD_SLASH); + Optional result = null; + result = types.stream().filter(e -> + e.getKind().equals(kind) + && (split.length == 0 || split[split.length - 1].equals(e.getVersion())) + && (split.length < 2 || split[0].equals(e.getApiGroupName())) + + ).findFirst(); + return result.orElse(null); + } + + private synchronized void init() { + if (!this.initialized) { + List resourceEndpoints = new ArrayList<>(); + List types = new ArrayList<>(); + Collection groups = getLegacyGroups(); + groups.addAll(getApiGroups()); + groups.forEach(g -> { + Collection versions = g.getVersions(); + versions.forEach(v -> { + Collection resources = getResources(g, v); + addEndpoints(resourceEndpoints, types, g.getPrefix(), g.getName(), v, resources); + }); + }); + this.resourceEndpoints = resourceEndpoints; + this.types = types; + this.initialized = true; + } + } + + private void addEndpoints(List endpoints, List types, final String prefix, + final String apiGroupName, final String version, final Collection nodes) { + for (ModelNode node : nodes) { + addEndpoint(endpoints, types, prefix, apiGroupName, version, node); + } + } + + private void addEndpoint(List endpoints, List types, final String prefix, + final String apiGroupName, final String version, ModelNode node) { + String[] nameAndCapability = getNameAndCapability(node); + String name = nameAndCapability[0]; + String capability = nameAndCapability[1]; + String kind = node.get(KIND).asString(); + String typeApiGroupName = node.has(GROUP) ? node.get(GROUP).asString() : null; + String typeVersion = node.has(VERSION) ? node.get(VERSION).asString() : null; + boolean namespaced = node.get("namespaced").asBoolean(); + VersionedApiResource resource = new VersionedApiResource(prefix, apiGroupName, version, name, kind, namespaced); + VersionedType type = new VersionedType(prefix, typeApiGroupName != null ? typeApiGroupName : apiGroupName, + typeVersion != null ? typeVersion : version, kind); + if (capability == null && node.has(VERBS) && !node.get(VERBS).asList().isEmpty() + && !endpoints.contains(resource)) { + endpoints.add(resource); + } + if (!types.contains(type)) { + types.add(type); + } + addEndpointCapability(endpoints, capability, resource); + } + + public String[] getNameAndCapability(ModelNode node) { + String name = node.get(NAME).asString(); + String capability = null; + if (name.contains(FWD_SLASH)) { + int first = name.indexOf(FWD_SLASH); + capability = name.substring(first + 1); + name = name.substring(0, first); + } + return new String[] { name, capability }; + } + + private void addEndpointCapability(List endpoints, String capability, + VersionedApiResource resource) { + if (capability != null) { + int index = endpoints.indexOf(resource); + if (index != -1) { + endpoints.get(index).addCapability(capability); + } + } + } + + private Collection getApiGroups() { + String json = readEndpoint(API_GROUPS_API); + return ModelNode.fromJSONString(json).get("groups").asList().stream().map(n -> new ApiGroup(API_GROUPS_API, n)) + .collect(Collectors.toList()); + } + + private Collection getResources(IApiGroup group, String version) { + try { + String json = readEndpoint(group.pathFor(version)); + if (StringUtils.isBlank(json)) { + return new ArrayList<>(); + } + ModelNode node = ModelNode.fromJSONString(json); + return node.get("resources").asList(); + } catch (Exception e) { + LOGGER.error("Can't load api group {}", group.pathFor(version)); + return new ArrayList<>(); + } + } + + private Collection getLegacyGroups() { + Collection groups = new ArrayList<>(); + for (String endpoint : Arrays.asList(KUBE_API, OS_API)) { + try { + String json = readEndpoint(endpoint); + ModelNode n = ModelNode.fromJSONString(json); + groups.add(new LegacyApiGroup(endpoint, n)); + } catch (Exception ex) { + LOGGER.info("Can't access legacy endpoint {}", endpoint, ex); + } + } + return groups; + } + + private String readEndpoint(final String endpoint) { + try { + final URL url = new URL(new URL(this.baseUrl), endpoint); + LOGGER.debug(url.toString()); + return request(url); + } catch (IOException e) { + throw new OpenShiftException(e, "Unable to read endpoint %s/%s", this.baseUrl, endpoint); + } + } + + private String request(final URL url) throws IOException { + Request request = new OpenShiftRequestBuilder() + .url(url) + .acceptJson() + .authorization(authorizationContext) + .build(); + try (Response response = client.newCall(request).execute()) { + return response.body().string(); + } + } + + static class ApiGroup implements IApiGroup { + private final ModelNode node; + private final String prefix; + private final String path; + + ApiGroup(String prefix, ModelNode node) { + this.prefix = prefix; + this.node = node; + StringBuilder builder = new StringBuilder(prefix); + if (getName() != null) { // null name for k8e or openshift + builder.append(FWD_SLASH).append(getName()); + } + path = builder.toString(); + } + + protected ModelNode getNode() { + return node; + } + + @Override + public String getPrefix() { + return prefix; + } + + @Override + public String getName() { + return JBossDmrExtentions.asString(node, new HashMap<>(), NAME); + } + + @Override + public Collection getVersions() { + return JBossDmrExtentions.get(node, new HashMap<>(), "versions").asList().stream() + .map(n -> n.get("version").asString()).collect(Collectors.toList()); + } + + @Override + public String getPreferedVersion() { + return JBossDmrExtentions.asString(node, new HashMap<>(), "preferedVersion.version"); + } + + @Override + public String pathFor(String version) { + // add check for supported version? + return String.format("%s/%s", path, version); + } + } + + static class LegacyApiGroup extends ApiGroup { + + LegacyApiGroup(String prefix, ModelNode node) { + super(prefix, node); + } + + @Override + public String getName() { + return null; + } + + @Override + public Collection getVersions() { + return JBossDmrExtentions.get(getNode(), new HashMap<>(), "versions").asList().stream() + .map(ModelNode::asString) + .collect(Collectors.toList()); + } + + @Override + public String getPreferedVersion() { + return OpenShiftAPIVersion.v1.toString(); + } + + } + + static class VersionedApiResource implements IVersionedApiResource { + + private final String prefix; + private final String name; + private final boolean namespaced; + private final Collection capabilities = new ArrayList<>(); + private final String version; + private String apiGroupName; + private String kind; + + VersionedApiResource(String prefix, String version, String name) { + if (version == null) { + throw new IllegalArgumentException("version can not be null when creating a VersionedApiResource "); + } + if (version.contains(FWD_SLASH)) { + int last = version.lastIndexOf(FWD_SLASH); + this.apiGroupName = version.substring(0, last); + version = version.substring(last + 1); + } + this.prefix = prefix; + this.name = name; + this.version = version; + this.namespaced = false; + } + + VersionedApiResource(String prefix, String apiGroupName, String version, String name, String kind, + boolean namespaced) { + this.prefix = prefix; + this.name = name; + this.namespaced = namespaced; + this.version = version; + this.apiGroupName = apiGroupName; + this.kind = kind; + } + + public void addCapability(String capability) { + capabilities.add(capability); + } + + @Override + public String getApiGroupName() { + return apiGroupName; + } + + @Override + public String getVersion() { + return this.version; + } + + @Override + public String getPrefix() { + return prefix; + } + + @Override + public String getName() { + return name; + } + + @Override + public String getKind() { + return kind; + } + + @Override + public boolean isNamespaced() { + return namespaced; + } + + @Override + public boolean isSupported(String capability) { + return capabilities.contains(capability); + } + + @Override + public String toString() { + if (apiGroupName == null) { + return String.format("%s/%s/%s", prefix, version, name); + } + return String.format("%s/%s/%s/%s", prefix, apiGroupName, version, name); + } + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + ((apiGroupName == null) ? 0 : apiGroupName.hashCode()); + result = prime * result + ((name == null) ? 0 : name.hashCode()); + result = prime * result + ((prefix == null) ? 0 : prefix.hashCode()); + result = prime * result + ((version == null) ? 0 : version.hashCode()); + return result; + } + + @Override + public boolean equals(Object obj) { + if (this == obj) { + return true; + } + if (obj == null) { + return false; + } + if (getClass() != obj.getClass()) { + return false; + } + VersionedApiResource other = (VersionedApiResource) obj; + if (apiGroupName == null) { + if (other.apiGroupName != null) { + return false; + } + } else if (!apiGroupName.equals(other.apiGroupName)) { + return false; + } + if (name == null) { + if (other.name != null) { + return false; + } + } else if (!name.equals(other.name)) { + return false; + } + if (prefix == null) { + if (other.prefix != null) { + return false; + } + } else if (!prefix.equals(other.prefix)) { + return false; + } + if (version == null) { + if (other.version != null) { + return false; + } + } else if (!version.equals(other.version)) { + return false; + } + return true; + } + + } + + static class VersionedType implements IVersionedType { + private String prefix; + private String apiGroupName; + private String version; + private String kind; + + VersionedType(String prefix, String apiGroupName, String version, String kind) { + this.prefix = prefix; + this.apiGroupName = apiGroupName; + this.version = version; + this.kind = kind; + } + + @Override + public String getPrefix() { + return prefix; + } + + @Override + public String getApiGroupName() { + return apiGroupName; + } + + @Override + public String getVersion() { + return version; + } + + @Override + public String getKind() { + return kind; + } + + @Override + public int hashCode() { + return Objects.hash(apiGroupName, kind, version); + } + + @Override + public boolean equals(Object obj) { + if (this == obj) { + return true; + } + if (obj == null) { + return false; + } + if (!(obj instanceof VersionedType)) { + return false; + } + VersionedType other = (VersionedType) obj; + return Objects.equals(apiGroupName, other.apiGroupName) && Objects.equals(kind, other.kind) + && Objects.equals(version, other.version); + } + } } diff --git a/src/main/java/com/openshift/internal/restclient/AuthorizationEndpoints.java b/src/main/java/com/openshift/internal/restclient/AuthorizationEndpoints.java new file mode 100644 index 00000000..5e159e2b --- /dev/null +++ b/src/main/java/com/openshift/internal/restclient/AuthorizationEndpoints.java @@ -0,0 +1,73 @@ +/******************************************************************************* + * Copyright (c) 2019-2020 Red Hat, Inc. Distributed under license by Red Hat, Inc. + * All rights reserved. This program is made available under the terms of the + * Eclipse Public License v1.0 which accompanies this distribution, and is + * available at http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: Red Hat, Inc. + ******************************************************************************/ + +package com.openshift.internal.restclient; + +import java.net.MalformedURLException; +import java.net.URL; +import java.util.function.Function; + +import org.jboss.dmr.ModelNode; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import okhttp3.OkHttpClient; + +public class AuthorizationEndpoints { + + public static final String PATH_OAUTH_AUTHORIZATION_SERVER = ".well-known/oauth-authorization-server"; + + private static final Logger LOGGER = LoggerFactory.getLogger(AuthorizationEndpoints.class); + + private RequestingSupplier endpointsSupplier; + + protected AuthorizationEndpoints(String baseUrl, OkHttpClient client) { + this.endpointsSupplier = new RequestingSupplier( + baseUrl + "/" + PATH_OAUTH_AUTHORIZATION_SERVER, + "authorization- & token-endpoint", + client) { + + @Override + protected ModelNode extractValue(String response) { + return ModelNode.fromJSONString(response); + } + + @Override + protected ModelNode getDefaultValue() { + return null; + } + }; + } + + public URL getAuthorizationEndpoint() { + return getEndpoint(node -> node.get("authorization_endpoint").asString(), "authorization-endpoint"); + } + + public URL getTokenEndpoint() { + return getEndpoint(node -> node.get("token_endpoint").asString(), "token_endpoint"); + } + + private URL getEndpoint(Function extractor, String description) { + URL authorizationEndpoint = null; + try { + ModelNode node = endpointsSupplier.get(); + if (node != null) { + try { + authorizationEndpoint = new URL(extractor.apply(node)); + } catch (MalformedURLException e) { + LOGGER.info("Failed to determine {}.", description, e); + } + } + } catch (IllegalArgumentException e) { + LOGGER.error("Could not determine {} endpoint: invalid JSON.", description); + } + return authorizationEndpoint; + + } +} \ No newline at end of file diff --git a/src/main/java/com/openshift/internal/restclient/DefaultClient.java b/src/main/java/com/openshift/internal/restclient/DefaultClient.java index a269b430..7f640da5 100644 --- a/src/main/java/com/openshift/internal/restclient/DefaultClient.java +++ b/src/main/java/com/openshift/internal/restclient/DefaultClient.java @@ -1,522 +1,609 @@ /******************************************************************************* - * Copyright (c) 2015 Red Hat, Inc. Distributed under license by Red Hat, Inc. + * Copyright (c) 2015-2020 Red Hat, Inc. Distributed under license by Red Hat, Inc. * All rights reserved. This program is made available under the terms of the * Eclipse Public License v1.0 which accompanies this distribution, and is * available at http://www.eclipse.org/legal/epl-v10.html * * Contributors: Red Hat, Inc. ******************************************************************************/ + package com.openshift.internal.restclient; import static com.openshift.internal.restclient.capability.CapabilityInitializer.initializeClientCapabilities; +import static java.util.stream.Collectors.joining; +import java.io.IOException; +import java.io.InputStream; import java.net.MalformedURLException; -import java.net.SocketTimeoutException; import java.net.URL; -import java.security.cert.X509Certificate; +import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; +import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; +import java.util.Objects; -import org.apache.commons.lang.ObjectUtils; +import org.apache.commons.io.IOUtils; import org.apache.commons.lang.StringUtils; import org.jboss.dmr.ModelNode; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import com.openshift.internal.restclient.http.HttpClientException; -import com.openshift.internal.restclient.http.NotFoundException; -import com.openshift.internal.restclient.http.UnauthorizedException; -import com.openshift.internal.restclient.http.UrlConnectionHttpClientBuilder; -import com.openshift.internal.restclient.model.properties.ResourcePropertiesRegistry; +import com.openshift.internal.restclient.authorization.AuthorizationContext; +import com.openshift.internal.restclient.okhttp.OpenShiftRequestBuilder; +import com.openshift.internal.restclient.okhttp.WatchClient; import com.openshift.restclient.IApiTypeMapper; import com.openshift.restclient.IClient; import com.openshift.restclient.IOpenShiftWatchListener; import com.openshift.restclient.IResourceFactory; -import com.openshift.restclient.ISSLCertificateCallback; import com.openshift.restclient.IWatcher; import com.openshift.restclient.OpenShiftException; import com.openshift.restclient.ResourceKind; import com.openshift.restclient.UnsupportedOperationException; -import com.openshift.restclient.authorization.AuthorizationClientFactory; -import com.openshift.restclient.authorization.IAuthorizationClient; +import com.openshift.restclient.api.ITypeFactory; import com.openshift.restclient.authorization.IAuthorizationContext; -import com.openshift.restclient.authorization.IAuthorizationDetails; -import com.openshift.restclient.authorization.IAuthorizationStrategy; -import com.openshift.restclient.authorization.ResourceForbiddenException; import com.openshift.restclient.capability.CapabilityVisitor; import com.openshift.restclient.capability.ICapability; -import com.openshift.restclient.http.IHttpClient; import com.openshift.restclient.http.IHttpConstants; import com.openshift.restclient.model.IList; import com.openshift.restclient.model.IResource; -import com.openshift.restclient.model.IStatus; -import com.openshift.restclient.model.user.IUser; +import com.openshift.restclient.model.JSONSerializeable; + +import okhttp3.MediaType; +import okhttp3.OkHttpClient; +import okhttp3.Request; +import okhttp3.RequestBody; +import okhttp3.Response; +import okio.BufferedSink; +import okio.Okio; +import okio.Source; /** * @author Jeff Cantrill */ -public class DefaultClient implements IClient, IHttpConstants{ - - public static final String SYSTEM_PROP_K8E_API_VERSION = "osjc.k8e.apiversion"; - public static final String SYSTEM_PROP_OPENSHIFT_API_VERSION = "osjc.openshift.apiversion"; - - private static final Logger LOGGER = LoggerFactory.getLogger(DefaultClient.class); - private URL baseUrl; - private IHttpClient client; - private IResourceFactory factory; - private Map, ICapability> capabilities = new HashMap, ICapability>(); - private boolean capabilitiesInitialized = false; - - private static final String API_ENDPOINT = "api"; - private static final String OS_API_LEGACY_ENDPOINT = "osapi"; - private static final String OS_API_ENDPOINT = "oapi"; - - private String openShiftVersion; - private String kubernetesVersion; - private IAuthorizationStrategy strategy; - private IAuthorizationClient authClient; - private IApiTypeMapper typeMapper; - - public DefaultClient(URL baseUrl, IHttpClient httpClient, ISSLCertificateCallback sslCertCallback, IResourceFactory factory){ - this(baseUrl, httpClient, sslCertCallback, factory, null, null, null, IHttpClient.NO_TIMEOUT); - } - public DefaultClient(URL baseUrl, IHttpClient httpClient, ISSLCertificateCallback sslCertCallback, IResourceFactory factory, String alias, X509Certificate cert, int configTimeoutMillies) { - this(baseUrl, httpClient, sslCertCallback, factory, alias, cert, null, configTimeoutMillies); - } - public DefaultClient(URL baseUrl, IHttpClient httpClient, ISSLCertificateCallback sslCertCallback, IResourceFactory factory, String alias, X509Certificate cert, IApiTypeMapper typeMapper, int configTimeoutMillies){ - this.baseUrl = baseUrl; - client = httpClient != null ? httpClient : newIHttpClient(sslCertCallback, alias, cert, configTimeoutMillies); - this.factory = factory; - if(this.factory != null) { - this.factory.setClient(this); - } - openShiftVersion = System.getProperty(SYSTEM_PROP_OPENSHIFT_API_VERSION, null); - kubernetesVersion = System.getProperty(SYSTEM_PROP_K8E_API_VERSION, null); - authClient = new AuthorizationClientFactory.AuthorizationClientBuilder() - .withClient(this) - .withConnectTimeout(configTimeoutMillies) - .build(); - authClient.setSSLCertificateCallback(sslCertCallback); - this.typeMapper = typeMapper != null ? typeMapper : new ApiTypeMapper(baseUrl.toString(), client); - } - - /* - * Factory method for testing - */ - private IHttpClient newIHttpClient(ISSLCertificateCallback sslCertCallback, String alias, X509Certificate cert, int configTimeoutMillies){ - return new UrlConnectionHttpClientBuilder() - .setAcceptMediaType("application/json") - .setCertificate(alias, cert) - .setSSLCertificateCallback(sslCertCallback) - .setConfigTimeout(configTimeoutMillies) - .client(); - } - - @Override - public IResourceFactory getResourceFactory() { - return factory; - }; - - @Override - public IWatcher watch(String namespace, IOpenShiftWatchListener listener, String...kinds) { - WatchClient watcher = new WatchClient(getBaseURL(), typeMapper, this); - return watcher.watch(Arrays.asList(kinds), namespace, listener); - } - - @Override - public String getResourceURI(IResource resource) { - return new URLBuilder(getBaseURL(), typeMapper, resource).build().toString(); - } - - @Override - public List list(String kind) { - return list(kind,""); //assumes namespace=default - } - - @Override - public List list(String kind, String namespace) { - return list(kind, namespace, new HashMap()); - } - - @SuppressWarnings("unchecked") - @Override - public List list(String kind, String namespace, Map labels) { - try { - if(!typeMapper.isSupported(kind)) - // TODO: replace with specific runtime exception - throw new RuntimeException("No OpenShift resource endpoint for type: " + kind); - URLBuilder builder = new URLBuilder(this.baseUrl, typeMapper) - .kind(kind) - .namespace(namespace); - final URL endpoint = builder.build(); - String response = client.get(endpoint, IHttpClient.DEFAULT_READ_TIMEOUT); - LOGGER.debug(String.format("List Response: %s:", response)); - List items = (List) factory.createList(response, kind); - return filterItems(items, labels); //client filter until we can figure out how to restrict with a server call - } catch (HttpClientException e){ - throw createOpenShiftException(String.format("Could not list %s resources in namespace %s: %s", kind, namespace, e.getMessage()), e); - } catch (SocketTimeoutException e) { - throw new OpenShiftException(e, "Socket timeout listing resources"); - } - } - - private List filterItems(List items, Map labels){ - if(labels.isEmpty()) return items; - List filtered = new ArrayList(); - for (T item : items) { - if( item.getLabels().entrySet().containsAll(labels.entrySet())){ - filtered.add(item); - } - } - return filtered; - } - - @Override - public Collection create(IList list, String namespace){ - List results = new ArrayList(list.getItems().size()); - for (IResource resource : list.getItems()) { - try{ - results.add(createVersion(resource, namespace, resource.getApiVersion())); - }catch(OpenShiftException e){ - if(e.getStatus() != null){ - results.add(e.getStatus()); - }else{ - throw e; - } - } - } - return results; - } - - @Override - public T create(T resource) { - return create(resource, resource.getNamespace()); - } - - - @Override - public T create(T resource, String namespace) { - return createVersion(resource, namespace, null); - } - - private T createVersion(T resource, String namespace, String version) { - if(ResourceKind.LIST.equals(resource.getKind())) throw new UnsupportedOperationException("Generic create operation not supported for resource type 'List'"); - try { - namespace = ResourceKind.PROJECT.equals(resource.getKind()) ? "" : namespace; - final URL endpoint = new URLBuilder(this.baseUrl, typeMapper) - .kind(resource.getKind()) - .namespace(namespace) - .build(); - String response = client.post(endpoint, IHttpClient.DEFAULT_READ_TIMEOUT, resource); - LOGGER.debug(response); - return factory.create(response); - } catch (HttpClientException e){ - throw createOpenShiftException(String.format("Could not create resource %s in namespace '%s': %s", resource.getName(), namespace, e.getMessage()), e); - } catch (SocketTimeoutException e) { - throw new OpenShiftException(e, "Socket timeout creating resource %s", resource.getName()); - } - } - - @Override - public T create(String kind, String namespace, String name, String subresource, IResource payload) { - if(ResourceKind.LIST.equals(kind)) throw new UnsupportedOperationException("Generic create operation not supported for resource type 'List'"); - try { - namespace = ResourceKind.PROJECT.equals(kind) ? null : namespace; - final URL endpoint = new URLBuilder(this.baseUrl, typeMapper) - .kind(kind) - .name(name) - .namespace(namespace) - .subresource(subresource) - .build(); - String response = client.post(endpoint, IHttpClient.DEFAULT_READ_TIMEOUT, payload); - LOGGER.debug(response); - return factory.create(response); - } catch (HttpClientException e){ - throw createOpenShiftException(String.format("Could not create %s resource %s in namespace %s for subresource %s: %s", kind, name, namespace, subresource, e.getMessage()), e); - } catch (SocketTimeoutException e) { - throw new OpenShiftException(e, "Socket timeout creating resource %s", name); - } - } - - @Override - public T update(T resource) { - if(ResourceKind.LIST.equals(resource.getKind())) throw new UnsupportedOperationException("Update operation not supported for resource type 'List'"); - try { - final URL endpoint = new URLBuilder(getBaseURL(), typeMapper) - .resource(resource) - .namespace(resource.getNamespace()) - .build(); - String response = client.put(endpoint, IHttpClient.DEFAULT_READ_TIMEOUT, resource); - LOGGER.debug(response); - return factory.create(response); - } catch (HttpClientException e){ - throw createOpenShiftException(String.format("Could not update resource %s: %s", resource.getName(), e.getMessage()), e); - } catch (SocketTimeoutException e) { - throw new OpenShiftException(e, "Socket timeout updating resource %s", resource.getName()); - } - } - - @Override - public void delete(T resource) { - if(ResourceKind.LIST.equals(resource.getKind())) throw new UnsupportedOperationException("Delete operation not supported for resource type 'List'"); - try { - String namespace = ResourceKind.PROJECT.equals(resource.getKind()) ? "" : resource.getNamespace(); - final URL endpoint = new URLBuilder(this.baseUrl, typeMapper) - .resource(resource) - .namespace(namespace) - .build(); - LOGGER.debug(String.format("Deleting resource %s", endpoint)); - String response = client.delete(endpoint, IHttpClient.DEFAULT_READ_TIMEOUT); - LOGGER.debug(response); - //TODO return response object here - } catch (HttpClientException e){ - throw createOpenShiftException(String.format("Could not delete resource %s: %s", resource.getName(), e.getMessage()), e); - } catch (SocketTimeoutException e) { - throw new OpenShiftException(e, "SocketTimeout deleting resource %s", resource.getName()); - } - } - - - @Override - public IList get(String kind, String namespace) { - try { - final URL endpoint = new URLBuilder(this.baseUrl, typeMapper) - .kind(kind) - .namespace(namespace) - .build(); - String response = client.get(endpoint, IHttpClient.DEFAULT_READ_TIMEOUT); - LOGGER.debug(response); - return factory.create(response); - } catch (HttpClientException e){ - throw createOpenShiftException(String.format("Could not list resource kind %s in namespace '%s': %s", kind, namespace, e.getMessage()), e); - } catch (SocketTimeoutException e) { - throw new OpenShiftException(e, "SocketTimeout getting listing resource kind '%s' in namespace '%s'", kind, namespace); - } - - } - - @Override - public T get(String kind, String name, String namespace) { - try { - namespace = ResourceKind.PROJECT.equals(kind) ? "" : namespace; - final URL endpoint = new URLBuilder(this.baseUrl, typeMapper) - .kind(kind) - .name(name) - .namespace(namespace) - .build(); - String response = client.get(endpoint, IHttpClient.DEFAULT_READ_TIMEOUT); - LOGGER.debug(response); - return factory.create(response); - } catch (HttpClientException e){ - throw createOpenShiftException(String.format("Could not get resource %s in namespace %s: %s", name, namespace, e.getMessage()), e); - } catch (SocketTimeoutException e) { - throw new OpenShiftException(e, "SocketTimeout getting resource %s", name); - } - } - - public synchronized void initializeCapabilities(){ - if(capabilitiesInitialized) return; - initializeClientCapabilities(capabilities, this); - capabilitiesInitialized = true; - } - - @SuppressWarnings("unchecked") - @Override - public T getCapability(Class capability) { - return (T) capabilities.get(capability); - } - - @Override - public boolean supports(Class capability) { - if(!capabilitiesInitialized ){ - initializeCapabilities(); - } - return capabilities.containsKey(capability); - } - - @SuppressWarnings("unchecked") - @Override - public R accept(CapabilityVisitor visitor, R unsupportedCapabililityValue){ - if(!capabilitiesInitialized) initializeCapabilities(); - if(capabilities.containsKey(visitor.getCapabilityType())){ - T capability = (T) capabilities.get(visitor.getCapabilityType()); - return (R) visitor.visit(capability); - } - return unsupportedCapabililityValue; - } - - public List getKubernetesVersions() { - return getVersion(KubernetesAPIVersion.class, API_ENDPOINT); - } - - public List getOpenShiftVersions() { - List versions = getVersion(OpenShiftAPIVersion.class, OS_API_ENDPOINT); - versions.addAll(getVersion(OpenShiftAPIVersion.class, OS_API_LEGACY_ENDPOINT)); - return versions; - } - - public String getKubernetesVersion() { - if(kubernetesVersion == null){ - List versions = getKubernetesVersions(); - kubernetesVersion = ResourcePropertiesRegistry.getInstance().getMaxSupportedKubernetesVersion(versions).toString(); - } - return kubernetesVersion; - } - - @Override - public String getOpenShiftAPIVersion() { - if(openShiftVersion == null){ - List versions = getOpenShiftVersions(); - openShiftVersion = ResourcePropertiesRegistry.getInstance().getMaxSupportedOpenShiftVersion(versions).toString(); - } - return openShiftVersion; - } - - private > List getVersion(Class klass, String endpoint) { - try { - final URL url = new URL(this.baseUrl, endpoint); - LOGGER.debug(url.toString()); - String response = client.get(url, IHttpClient.DEFAULT_READ_TIMEOUT); - LOGGER.debug(response); - ModelNode json = ModelNode.fromJSONString(response); - List versionNodes = json.get("versions").asList(); - List versions = new ArrayList(versionNodes.size()); - for (ModelNode node : versionNodes) { - try{ - versions.add(Enum.valueOf(klass, node.asString())); - }catch(IllegalArgumentException e){ - LOGGER.warn(String.format("Unsupported server version '%s' for '%s'", node.asString(), klass.getSimpleName())); - } - } - return versions; - } catch (MalformedURLException e) { - LOGGER.error("Exception", e); - throw new OpenShiftException(e,""); - } catch (SocketTimeoutException e) { - LOGGER.error("Exception", e); - throw new OpenShiftException(e,""); - //HACK - This gets us around a server issue - } catch (HttpClientException e) { - if(e instanceof NotFoundException) { - throw new com.openshift.restclient.NotFoundException(e); - } - if(e.getResponseCode() != 403) { - throw e; - } - LOGGER.error("Unauthorized exception. Can system:anonymous get the API endpoint", e); - return new ArrayList(); - } - } - - @Override - public URL getBaseURL() { - return this.baseUrl; - } - - @SuppressWarnings("deprecation") - @Override - public void setAuthorizationStrategy(IAuthorizationStrategy strategy) { - this.strategy = strategy; - this.client.setAuthorizationStrategy(strategy); - } - - @Override - public IAuthorizationStrategy getAuthorizationStrategy() { - return this.strategy; - } - - private OpenShiftException createOpenShiftException(String message, HttpClientException e) { - LOGGER.debug(message, e); - final String token = strategy != null ? strategy.getToken() : ""; - if (e.getMessage() != null - && e.getMessage().startsWith("{")) { - IStatus status = factory.create(e.getMessage()); - if(status.getCode() == STATUS_FORBIDDEN) { - if(StringUtils.isNotBlank(token)) { //truly forbidden - return new ResourceForbiddenException(status.getMessage(), status, e); - }else { - return new com.openshift.restclient.authorization.UnauthorizedException(authClient.getAuthorizationDetails(this.baseUrl.toString())); - } - } - return new OpenShiftException(e, status, message); - } else { - if(e instanceof UnauthorizedException) { - return new com.openshift.restclient.authorization.UnauthorizedException(authClient.getAuthorizationDetails(this.baseUrl.toString())); - } - return new OpenShiftException(e, message); - } - } - - @Override - public IUser getCurrentUser() { - return get(ResourceKind.USER, "~", ""); - } - - @Override - public IAuthorizationContext getContext(String baseURL) { - return this.authClient.getContext(baseURL); - } - - @Override - public IAuthorizationDetails getAuthorizationDetails(String baseURL) { - return this.authClient.getAuthorizationDetails(baseURL); - } - - @Override - public void setSSLCertificateCallback(ISSLCertificateCallback callback) { - this.authClient.setSSLCertificateCallback(callback); - this.client.setSSLCertificateCallback(callback); - } - - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = prime * result + ((baseUrl == null) ? 0 : baseUrl.hashCode()); - result = prime * result + ((kubernetesVersion == null) ? 0 : kubernetesVersion.hashCode()); - result = prime * result + ((openShiftVersion == null) ? 0 : openShiftVersion.hashCode()); - result = prime * result + ((strategy == null || strategy.getToken() == null) ? 0 : strategy.getToken().hashCode()); - return result; - } - - @Override - public boolean equals(Object obj) { - if (this == obj) - return true; - if (obj == null) - return false; - if (!(obj instanceof DefaultClient)) - return false; - DefaultClient other = (DefaultClient) obj; - if (baseUrl == null) { - if (other.baseUrl != null) - return false; - } else if (!baseUrl.equals(other.baseUrl)) - return false; - if (kubernetesVersion == null) { - if (other.kubernetesVersion != null) - return false; - } else if (!kubernetesVersion.equals(other.kubernetesVersion)) - return false; - if (openShiftVersion == null) { - if (other.openShiftVersion != null) - return false; - } else if (!openShiftVersion.equals(other.openShiftVersion)) { - return false; - } - if (strategy == null) { - return other.strategy == null; - } else { - if (other.strategy == null) { - return false; - } - return ObjectUtils.equals(strategy.getUsername(), other.strategy.getUsername()); - } - } - - +public class DefaultClient implements IClient, IHttpConstants { + + + private static final Logger LOGGER = LoggerFactory.getLogger(DefaultClient.class); + + public static final String PATH_KUBERNETES_VERSION = "version"; + public static final String PATH_OPENSHIFT_VERSION = "version/openshift"; + public static final String PATH_HEALTH_CHECK = "healthz"; + public static final String PATH_DEFAULT_OAUTH_TOKEN = "oauth/token"; + public static final String PATH_DEFAULT_OAUTH_AUTHORIZE = "oauth/authorize"; + + public static final String SYSTEM_PROP_K8E_API_VERSION = "osjc.k8e.apiversion"; + public static final String SYSTEM_PROP_OPENSHIFT_API_VERSION = "osjc.openshift.apiversion"; + + private static final String OS_API_ENDPOINT = "oapi"; + + private URL baseUrl; + private OkHttpClient client; + private IResourceFactory factory; + private Map, ICapability> capabilities = new HashMap<>(); + private boolean capabilitiesInitialized = false; + + private final AuthorizationContext authContext; + private final IApiTypeMapper typeMapper; + private final ClusterVersion kubernetesVersion; + private final ClusterVersion openShiftVersion; + private final AuthorizationEndpoints authorizationEndpoints; + private OpenShiftMajorVersion openShiftMajorVersion; + + public DefaultClient(URL baseUrl, OkHttpClient client, IResourceFactory factory, IApiTypeMapper typeMapper, + AuthorizationContext authContext) { + this.baseUrl = baseUrl; + this.client = client; + this.factory = factory; + if (this.factory != null) { + this.factory.setClient(this); + } + this.typeMapper = typeMapper != null ? typeMapper : new ApiTypeMapper(baseUrl.toString(), client, authContext); + this.authContext = authContext; + this.kubernetesVersion = new ClusterVersion(baseUrl.toExternalForm() + "/" + PATH_KUBERNETES_VERSION, "Kubernetes Version", client); + this.openShiftVersion = new ClusterVersion(baseUrl.toExternalForm() + "/" + PATH_OPENSHIFT_VERSION, "OpenShift Version", client); + this.authorizationEndpoints = new AuthorizationEndpoints(baseUrl.toExternalForm(), client); + } + + @Override + public IClient clone() { + AuthorizationContext context = authContext.clone(); + DefaultClient clone = new DefaultClient(baseUrl, client, factory, typeMapper, context); + context.setClient(clone); + return clone; + } + + @Override + public IResourceFactory getResourceFactory() { + return factory; + } + + @Override + public IWatcher watch(String namespace, IOpenShiftWatchListener listener, String... kinds) { + WatchClient watcher = new WatchClient(this, this.typeMapper, this.client); + return watcher.watch(Arrays.asList(kinds), namespace, listener); + } + + @Override + public IWatcher watch(IOpenShiftWatchListener listener, String... kinds) { + return this.watch("", listener, kinds); + } + + @Override + public String getResourceURI(IResource resource) { + return new URLBuilder(getBaseURL(), typeMapper, resource).build().toString(); + } + + @Override + public List list(String kind) { + return list(kind, ""); + } + + @Override + public List list(String kind, Map labels) { + return list(kind, "", labels); + } + + @Override + public List list(String kind, String namespace) { + return list(kind, namespace, new HashMap<>()); + } + + @Override + public List list(String kind, String namespace, Map labels) { + String labelQuery = ""; + if (labels != null && !labels.isEmpty()) { + labelQuery = labels.entrySet().stream().map(e -> e.getKey() + "=" + e.getValue()).collect(joining(",")); + } + return list(kind, namespace, labelQuery); + } + + @SuppressWarnings("unchecked") + @Override + public List list(String kind, String namespace, String labelQuery) { + Map params = new HashMap<>(); + if (labelQuery != null && !labelQuery.isEmpty()) { + params.put("labelSelector", labelQuery); + } + + IList resources = execute(HttpMethod.GET.toString(), kind, namespace, null, null, null, params); + List items = new ArrayList<>(); + items.addAll((Collection) resources.getItems()); + return items; + } + + @Override + public Collection create(IList list, String namespace) { + List results = new ArrayList<>(list.getItems().size()); + for (IResource resource : list.getItems()) { + try { + results.add(create(resource, namespace)); + } catch (OpenShiftException e) { + if (e.getStatus() != null) { + results.add(e.getStatus()); + } else { + throw e; + } + } + } + return results; + } + + @Override + public T create(T resource) { + return create(resource, resource.getNamespaceName()); + } + + @Override + public T create(T resource, String namespace) { + return execute(HttpMethod.POST, resource.getKind(), namespace, null, null, resource); + } + + @Override + public T create(String kind, String namespace, String name, String subresource, + IResource payload) { + return execute(HttpMethod.POST, kind, namespace, name, subresource, payload); + } + + public T create(String kind, String version, String namespace, String name, String subresource, + InputStream payload) { + return create(kind, version, namespace, name, subresource, payload, Collections.emptyMap()); + } + + public T create(String kind, String version, String namespace, String name, String subresource, + InputStream payload, Map parameters) { + return execute(HttpMethod.POST, kind, version, namespace, name, subresource, payload, parameters); + } + + enum HttpMethod { + GET, PUT, POST, DELETE, HEAD + } + + private T execute(HttpMethod method, String kind, String namespace, String name, + String subresource, IResource payload) { + return execute(method.toString(), kind, namespace, name, subresource, payload); + } + + private T execute(HttpMethod method, String kind, String version, String namespace, String name, + String subresource, InputStream payload, Map parameters) { + return execute(method.toString(), kind, version, namespace, name, subresource, payload, parameters); + } + + public T execute(String method, String kind, String namespace, String name, + String subresource, IResource payload, String subContext) { + return execute(this.factory, method, kind, namespace, name, subresource, subContext, payload, + Collections.emptyMap()); + } + + @Override + public T execute(String method, String kind, String namespace, String name, + String subresource, IResource payload) { + return execute(this.factory, method, kind, namespace, name, subresource, null, payload, + Collections.emptyMap()); + } + + @Override + public T execute(String method, String kind, String version, String namespace, String name, + String subresource, InputStream payload) { + return execute(this.factory, method, kind, version, namespace, name, subresource, null, payload, + Collections.emptyMap()); + } + + @Override + public T execute(String method, String kind, String version, String namespace, String name, + String subresource, InputStream payload, Map parameters) { + return execute(this.factory, method, kind, version, namespace, name, subresource, null, payload, + parameters); + } + + @Override + public T execute(String method, String kind, String namespace, String name, + String subresource, IResource payload, Map params) { + return execute(this.factory, method, kind, namespace, name, subresource, null, payload, params); + } + + public T execute(ITypeFactory factory, String method, String kind, String version, String namespace, String name, + String subresource, String subContext, InputStream payload, Map params) { + return execute(factory, method, kind, version, namespace, name, subresource, subContext, + getPayload(payload, method), params); + } + + public T execute(ITypeFactory factory, String method, String kind, String namespace, String name, + String subresource, String subContext, JSONSerializeable payload, Map params) { + return execute(factory, method, kind, getApiVersion(payload), namespace, name, subresource, subContext, + getPayload(payload, method), params); + } + + @SuppressWarnings("unchecked") + private T execute(ITypeFactory factory, String method, String kind, String version, String namespace, + String name, String subresource, String subContext, RequestBody requestBody, Map params) { + if (factory == null) { + throw new OpenShiftException(ITypeFactory.class.getSimpleName() + " is null while trying to call IClient#execute"); + } + + if (params == null) { + params = Collections.emptyMap(); + } + + if (ResourceKind.LIST.equals(kind)) { + throw new UnsupportedOperationException("Generic create operation not supported for resource type 'List'"); + } + + final URL endpoint = new URLBuilder(this.baseUrl, typeMapper) + .apiVersion(version) + .kind(kind) + .name(name) + .namespace(namespace) + .subresource(subresource) + .subContext(subContext) + .addParameters(params) + .build(); + Request request = newRequestBuilder() + .url(endpoint) + .method(method, requestBody) + .acceptJson() + .authorization(authContext) + .build(); + LOGGER.debug("About to make {} request: {}", request.method(), request); + try { + String body = request(request); + return (T) factory.createInstanceFrom(body); + } catch (IOException e) { + throw new OpenShiftException(e, "Unable to execute request to %s", endpoint); + } + } + + private String request(Request request) throws IOException { + try (Response response = client.newCall(request).execute()) { + String body = response.body().string() ; + LOGGER.debug("Response: {}", body); + return body; + } + } + + private String getApiVersion(JSONSerializeable payload) { + String apiVersion = null; + if (payload instanceof IResource) { + apiVersion = ((IResource) payload).getApiVersion(); + } + return apiVersion; + } + + private RequestBody getPayload(JSONSerializeable payload, String method) { + if(isPayloadlessMethod(method)) { + return null; + } + String json = payload == null ? "" : payload.toJson(true); + LOGGER.debug("About to send payload: {}", json); + return RequestBody.create(json, MediaType.parse(MEDIATYPE_APPLICATION_JSON)); + } + + RequestBody getPayload(InputStream payload, String method) { + if(isPayloadlessMethod(method)) { + return null; + } + InputStream input = payload == null ? IOUtils.toInputStream("", StandardCharsets.UTF_8) : payload; + LOGGER.debug("About to send binary payload"); + return new RequestBody() { + @Override + public void writeTo(BufferedSink sink) throws IOException { + Source source = Okio.source(input); + sink.writeAll(source); + } + + @Override + public MediaType contentType() { + return MediaType.parse(MEDIATYPE_APPLICATION_OCTET_STREAM); + } + }; + } + + private boolean isPayloadlessMethod(String method) { + String uppercaseMethod = StringUtils.upperCase(method); + return HttpMethod.GET.name().equals(uppercaseMethod) + || HttpMethod.HEAD.name().equals(uppercaseMethod); + } + + @Override + public String getServerReadyStatus() { + try { + Request request = new Request.Builder() + .url(new URL(this.baseUrl, PATH_HEALTH_CHECK)) + .header(PROPERTY_ACCEPT, "*/*") + .build(); + return request(request); + } catch (IOException e) { + throw new OpenShiftException(e, + "Exception while trying to determine the health/ready response of the server"); + } + } + + /* for debugging purposes */ + protected OpenShiftRequestBuilder newRequestBuilder() { + return new OpenShiftRequestBuilder(); + } + + @Override + public T update(T resource) { + return execute(HttpMethod.PUT, resource.getKind(), resource.getNamespaceName(), resource.getName(), null, + resource); + } + + @Override + public void delete(T resource) { + delete(resource.getKind(), resource.getNamespaceName(), resource.getName()); + } + + @Override + public void delete(String resourceKind, String namespaceName, String name) { + execute(HttpMethod.DELETE, resourceKind, namespaceName, name, null, null); + } + + @Override + public IList get(String kind, String namespace) { + return execute(HttpMethod.GET, kind, namespace, null, null, (IResource)null); + } + + @Override + public T get(String kind, String name, String namespace) { + return execute(HttpMethod.GET, kind, namespace, name, null, (IResource)null); + } + + public synchronized void initializeCapabilities() { + if (capabilitiesInitialized) { + return; + } + initializeClientCapabilities(capabilities, this); + capabilitiesInitialized = true; + } + + @SuppressWarnings("unchecked") + @Override + public T getCapability(Class capability) { + return (T) capabilities.get(capability); + } + + @Override + public boolean supports(Class capability) { + if (!capabilitiesInitialized) { + initializeCapabilities(); + } + return capabilities.containsKey(capability); + } + + @SuppressWarnings("unchecked") + @Override + public R accept(CapabilityVisitor visitor, R unsupportedCapabililityValue) { + if (!capabilitiesInitialized) { + initializeCapabilities(); + } + if (capabilities.containsKey(visitor.getCapabilityType())) { + T capability = (T) capabilities.get(visitor.getCapabilityType()); + return visitor.visit(capability); + } + return unsupportedCapabililityValue; + } + + @Override + public String getOpenShiftAPIVersion() { + return typeMapper.getPreferedVersionFor(OS_API_ENDPOINT); + } + + @Override + public String getOpenshiftMasterVersion() { + return openShiftVersion.get(); + } + + @Override + public String getKubernetesMasterVersion() { + return kubernetesVersion.get(); + } + + @Override + public URL getBaseURL() { + return this.baseUrl; + } + + @Override + public URL getAuthorizationEndpoint() { + URL url = authorizationEndpoints.getAuthorizationEndpoint(); + if (url != null) { + return url; + } + return getDefaultAuthorizationEndpoint(); + + } + + protected URL getDefaultAuthorizationEndpoint() { + try { + return new URL(getBaseURL(), PATH_DEFAULT_OAUTH_AUTHORIZE); + } catch (MalformedURLException e) { + throw new OpenShiftException(e, e.getLocalizedMessage()); + } + } + + @Override + public URL getTokenEndpoint() { + URL url = authorizationEndpoints.getTokenEndpoint(); + if (url != null) { + return url; + } + return getDefaultTokenEndpoint(); + } + + protected URL getDefaultTokenEndpoint() { + try { + return new URL(getBaseURL(), PATH_DEFAULT_OAUTH_TOKEN); + } catch (MalformedURLException e) { + throw new OpenShiftException(e, e.getLocalizedMessage()); + } + } + + @Override + public IAuthorizationContext getAuthorizationContext() { + return this.authContext; + } + + public void setToken(String token) { + this.authContext.setToken(token); + } + + public String getToken() { + return getAuthorizationContext().getToken(); + } + + @Override + public int getOpenShiftMajorVersion() { + if (openShiftMajorVersion == null) { + this.openShiftMajorVersion = new OpenShiftMajorVersion(getOpenShiftAPIVersion(), getKubernetesMasterVersion()); + } + return openShiftMajorVersion.get(); + } + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + ((baseUrl == null) ? 0 : baseUrl.toString().hashCode()); + result = prime * result + ((kubernetesVersion == null) ? 0 : kubernetesVersion.hashCode()); + result = prime * result + ((openShiftVersion == null) ? 0 : openShiftVersion.hashCode()); + result = prime * result + + ((authContext == null || authContext.getToken() == null) ? 0 : authContext.getToken().hashCode()); + return result; + } + + @Override + public boolean equals(Object obj) { + if (this == obj) { + return true; + } + if (obj == null) { + return false; + } + if (!(obj instanceof DefaultClient)) { + return false; + } + DefaultClient other = (DefaultClient) obj; + if (baseUrl == null) { + if (other.baseUrl != null) { + return false; + } + } else if (!baseUrl.toString().equals(other.baseUrl.toString())) { + return false; + } + if (authContext == null) { + return other.authContext == null; + } else { + if (other.authContext == null) { + return false; + } + return Objects.equals(authContext.getUserName(), other.authContext.getUserName()); + } + } + + @SuppressWarnings("unchecked") + @Override + public T adapt(Class klass) { + if (DefaultClient.class.equals(klass)) { + return (T) this; + } + if (OkHttpClient.class.equals(klass)) { + return (T) this.client; + } + if (IApiTypeMapper.class.equals(klass)) { + return (T) this.typeMapper; + } + if (ICapability.class.isAssignableFrom(klass) && this.supports((Class) klass)) { + return (T) getCapability((Class) klass); + } + if (IResourceFactory.class.equals(klass)) { + return (T) this.factory; + } + return null; + } + + private class ClusterVersion extends RequestingSupplier { + + protected ClusterVersion(String url, String description, OkHttpClient client) { + super(url, description, client); + } + + @Override + protected String extractValue(String response) { + try { + return ModelNode.fromJSONString(response).get("gitVersion").asString(); + } catch (IllegalArgumentException e) { + LOGGER.error("Could not retrieve {}: Invalid JSON.", description); + return null; + } + } + + @Override + protected String getDefaultValue() { + return ""; + } + } } diff --git a/src/main/java/com/openshift/internal/restclient/KubernetesAPIVersion.java b/src/main/java/com/openshift/internal/restclient/KubernetesAPIVersion.java index 80efcb7b..3310dd2e 100644 --- a/src/main/java/com/openshift/internal/restclient/KubernetesAPIVersion.java +++ b/src/main/java/com/openshift/internal/restclient/KubernetesAPIVersion.java @@ -6,27 +6,26 @@ * * Contributors: Red Hat, Inc. ******************************************************************************/ + package com.openshift.internal.restclient; /** - * This list of supported Kubernetes API Models - * by this client + * This list of supported Kubernetes API Models by this client * * @author Jeff Cantrill */ -public enum KubernetesAPIVersion implements APIModelVersion{ - @Deprecated - v1beta3(2), - v1(3); - - private int order; - - KubernetesAPIVersion( int order){ - this.order = order; - } - - @Override - public int getOrder(){ - return order; - } +public enum KubernetesAPIVersion implements APIModelVersion { + @Deprecated + v1beta3(2), v1(3); + + private int order; + + KubernetesAPIVersion(int order) { + this.order = order; + } + + @Override + public int getOrder() { + return order; + } } diff --git a/src/main/java/com/openshift/internal/restclient/KubernetesVersion.java b/src/main/java/com/openshift/internal/restclient/KubernetesVersion.java new file mode 100644 index 00000000..7bd2b07e --- /dev/null +++ b/src/main/java/com/openshift/internal/restclient/KubernetesVersion.java @@ -0,0 +1,85 @@ +/******************************************************************************* + * Copyright (c) 2019 Red Hat, Inc. Distributed under license by Red Hat, Inc. + * All rights reserved. This program is made available under the terms of the + * Eclipse Public License v1.0 which accompanies this distribution, and is + * available at http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: Red Hat, Inc. + ******************************************************************************/ + +package com.openshift.internal.restclient; + +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +import org.apache.commons.lang.StringUtils; + +public class KubernetesVersion { + + public static final int NO_VERSION = -1; + private static final Pattern REGEX_KUBERVERSION = Pattern.compile("v(\\d{1,3})\\.(\\d{1,3})\\.(\\d{1,3})(\\+(\\p{ASCII}+)){0,1}"); + + private boolean detected = false; + private int major = NO_VERSION; + private int minor = NO_VERSION; + private int patch = NO_VERSION; + private String git; + + public KubernetesVersion(String kubernetesVersion) { + parse(kubernetesVersion); + } + + private void parse(String kubernetesVersion) { + reset(); + if (StringUtils.isEmpty(kubernetesVersion)) { + return; + } + Matcher matcher = REGEX_KUBERVERSION.matcher(kubernetesVersion); + if (!matcher.matches() + || matcher.groupCount() < 5) { + return; + } + try { + detected = true; + this.major = parseGroup(matcher.group(1)); + this.minor = parseGroup(matcher.group(2)); + this.patch = parseGroup(matcher.group(3)); + this.git = matcher.group(5); + } catch(NumberFormatException e) { + // stop when error encoutered + } + + } + + private int parseGroup(String version) { + return Integer.parseInt(version); + } + + private void reset() { + this.detected = false; + this.major = NO_VERSION; + this.minor = NO_VERSION; + this.patch = NO_VERSION; + this.git = null; + } + + public boolean isDetected() { + return detected; + } + + public int getMajor() { + return major; + } + + public int getMinor() { + return minor; + } + + public int getPatch() { + return patch; + } + + public String getGit() { + return git; + } +} diff --git a/src/main/java/com/openshift/internal/restclient/OpenShiftAPIVersion.java b/src/main/java/com/openshift/internal/restclient/OpenShiftAPIVersion.java index 7285d3e5..d3da3bcf 100644 --- a/src/main/java/com/openshift/internal/restclient/OpenShiftAPIVersion.java +++ b/src/main/java/com/openshift/internal/restclient/OpenShiftAPIVersion.java @@ -6,26 +6,25 @@ * * Contributors: Red Hat, Inc. ******************************************************************************/ + package com.openshift.internal.restclient; /** - * This list of supported OpenShift API Models - * by this client + * This list of supported OpenShift API Models by this client * - * @author Jeff Cantrill */ -public enum OpenShiftAPIVersion implements APIModelVersion{ - @Deprecated - v1beta3(2), - v1(3); - - private int order; - OpenShiftAPIVersion(int order){ - this.order = order; - } - - @Override - public int getOrder(){ - return order; - } +public enum OpenShiftAPIVersion implements APIModelVersion { + @Deprecated + v1beta3(2), v1(3); + + private int order; + + OpenShiftAPIVersion(int order) { + this.order = order; + } + + @Override + public int getOrder() { + return order; + } } diff --git a/src/main/java/com/openshift/internal/restclient/OpenShiftMajorVersion.java b/src/main/java/com/openshift/internal/restclient/OpenShiftMajorVersion.java new file mode 100644 index 00000000..5cc22bf2 --- /dev/null +++ b/src/main/java/com/openshift/internal/restclient/OpenShiftMajorVersion.java @@ -0,0 +1,52 @@ +/******************************************************************************* + * Copyright (c) 2019 Red Hat, Inc. Distributed under license by Red Hat, Inc. + * All rights reserved. This program is made available under the terms of the + * Eclipse Public License v1.0 which accompanies this distribution, and is + * available at http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: Red Hat, Inc. + ******************************************************************************/ + +package com.openshift.internal.restclient; + +public class OpenShiftMajorVersion { + + private KubernetesVersion openshiftVersion; + private KubernetesVersion kubernetesVersion; + + public OpenShiftMajorVersion(String openshiftAPIVersion, String kubernetesMasterVersion) { + this.openshiftVersion = new KubernetesVersion(openshiftAPIVersion); + this.kubernetesVersion = new KubernetesVersion(kubernetesMasterVersion); + } + + public boolean isDetected() { + return openshiftVersion.isDetected() + || kubernetesVersion.isDetected(); + } + + public int get() { + if (openshiftVersion.isDetected()) { + return openshiftVersion.getMajor(); + } + + if (!kubernetesVersion.isDetected()) { + return KubernetesVersion.NO_VERSION; + } + + return mapKubernetesToOpenShift(kubernetesVersion); + } + + private int mapKubernetesToOpenShift(KubernetesVersion kubernetesVersion) { + if (kubernetesVersion.getMajor() < 1) { + return 3; + } + + if (kubernetesVersion.getMajor() == 1 + && kubernetesVersion.getMinor() <= 11) { + return 3; + } + + return 4; + } + +} diff --git a/src/main/java/com/openshift/internal/restclient/RequestingSupplier.java b/src/main/java/com/openshift/internal/restclient/RequestingSupplier.java new file mode 100644 index 00000000..e7406ddb --- /dev/null +++ b/src/main/java/com/openshift/internal/restclient/RequestingSupplier.java @@ -0,0 +1,85 @@ +/******************************************************************************* + * Copyright (c) 2020 Red Hat, Inc. + * Distributed under license by Red Hat, Inc. All rights reserved. + * This program is made available under the terms of the + * Eclipse Public License v1.0 which accompanies this distribution, + * and is available at http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Red Hat, Inc. - initial API and implementation + ******************************************************************************/ + +package com.openshift.internal.restclient; + +import static com.openshift.restclient.http.IHttpConstants.MEDIATYPE_APPLICATION_JSON; +import static com.openshift.restclient.http.IHttpConstants.PROPERTY_ACCEPT; + +import java.io.IOException; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.openshift.internal.restclient.okhttp.ResponseCodeInterceptor; +import com.openshift.restclient.OpenShiftException; + +import okhttp3.OkHttpClient; +import okhttp3.Request; +import okhttp3.Request.Builder; +import okhttp3.Response; + +abstract class RequestingSupplier { + + private static final Logger LOGGER = LoggerFactory.getLogger(RequestingSupplier.class); + + private String url; + protected String description; + private OkHttpClient client; + + private boolean requested = false; + private T value; + + protected RequestingSupplier(String url, String description, OkHttpClient client) { + this.url = url; + this.description = description; + this.client = client; + this.value = getDefaultValue(); + } + + public T get() { + return requestIfRequired(); + } + + private T requestIfRequired() { + try { + if (!requested) { + this.value = request(url); + } + return value; + } catch (IOException e) { + throw new OpenShiftException(e, "Unable to execute request to request url %s", url); + } + } + + protected T request(String url) throws IOException { + Request request = new Builder() + .url(url) + .header(PROPERTY_ACCEPT, MEDIATYPE_APPLICATION_JSON) + .tag(new ResponseCodeInterceptor.Ignore() {}) + .build(); + try (Response response = client.newCall(request).execute()) { + this.requested = true; + if (response != null + && response.isSuccessful()) { + this.value = extractValue(response.body().string()); + } else { + LOGGER.info("Failed to determine {}: got {}", description, + response == null ? "null" : response.code()); + } + } + return this.value; + } + + protected abstract T getDefaultValue(); + + protected abstract T extractValue(String response); +} \ No newline at end of file diff --git a/src/main/java/com/openshift/internal/restclient/ResourceFactory.java b/src/main/java/com/openshift/internal/restclient/ResourceFactory.java index 7cc7709b..04ed5a01 100644 --- a/src/main/java/com/openshift/internal/restclient/ResourceFactory.java +++ b/src/main/java/com/openshift/internal/restclient/ResourceFactory.java @@ -1,60 +1,32 @@ /******************************************************************************* - * Copyright (c) 2015 Red Hat, Inc. Distributed under license by Red Hat, Inc. + * Copyright (c) 2015-2019 Red Hat, Inc. Distributed under license by Red Hat, Inc. * All rights reserved. This program is made available under the terms of the * Eclipse Public License v1.0 which accompanies this distribution, and is * available at http://www.eclipse.org/legal/epl-v10.html * * Contributors: Red Hat, Inc. ******************************************************************************/ + package com.openshift.internal.restclient; import java.io.IOException; import java.io.InputStream; import java.lang.reflect.Constructor; -import java.lang.reflect.InvocationTargetException; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; +import java.util.Optional; import org.apache.commons.io.IOUtils; import org.apache.commons.lang.StringUtils; import org.jboss.dmr.ModelNode; -import com.openshift.internal.restclient.model.Build; -import com.openshift.internal.restclient.model.BuildConfig; -import com.openshift.internal.restclient.model.Config; -import com.openshift.internal.restclient.model.DeploymentConfig; -import com.openshift.internal.restclient.model.ImageStream; -import com.openshift.internal.restclient.model.KubernetesEvent; import com.openshift.internal.restclient.model.KubernetesResource; -import com.openshift.internal.restclient.model.LimitRange; -import com.openshift.internal.restclient.model.volume.PersistentVolume; -import com.openshift.internal.restclient.model.Pod; -import com.openshift.internal.restclient.model.Project; -import com.openshift.internal.restclient.model.ReplicationController; -import com.openshift.internal.restclient.model.ResourceQuota; -import com.openshift.internal.restclient.model.Route; -import com.openshift.internal.restclient.model.Secret; -import com.openshift.internal.restclient.model.Service; -import com.openshift.internal.restclient.model.ServiceAccount; -import com.openshift.internal.restclient.model.Status; -import com.openshift.internal.restclient.model.authorization.OpenshiftPolicy; -import com.openshift.internal.restclient.model.authorization.OpenshiftRole; -import com.openshift.internal.restclient.model.authorization.PolicyBinding; -import com.openshift.internal.restclient.model.authorization.RoleBinding; -import com.openshift.internal.restclient.model.build.BuildRequest; -import com.openshift.internal.restclient.model.image.ImageStreamImport; -import com.openshift.internal.restclient.model.oauth.OAuthAccessToken; -import com.openshift.internal.restclient.model.oauth.OAuthAuthorizeToken; -import com.openshift.internal.restclient.model.oauth.OAuthClient; -import com.openshift.internal.restclient.model.oauth.OAuthClientAuthorization; -import com.openshift.internal.restclient.model.project.OpenshiftProjectRequest; import com.openshift.internal.restclient.model.properties.ResourcePropertiesRegistry; -import com.openshift.internal.restclient.model.template.Template; -import com.openshift.internal.restclient.model.user.OpenShiftUser; -import com.openshift.internal.restclient.model.volume.PersistentVolumeClaim; +import com.openshift.restclient.IApiTypeMapper; +import com.openshift.restclient.IApiTypeMapper.IVersionedType; import com.openshift.restclient.IClient; import com.openshift.restclient.IResourceFactory; import com.openshift.restclient.ResourceFactoryException; @@ -63,182 +35,162 @@ import com.openshift.restclient.model.IResource; /** - * ResourceFactory creates a list of resources from a json string + * ResourceFactory creates a list of resources from a json string * - * @author Jeff Cantrill */ -public class ResourceFactory implements IResourceFactory{ - - private static final String KIND = "kind"; - private static final String APIVERSION = "apiVersion"; - private static final Map> IMPL_MAP = new HashMap>(); - static { - //OpenShift kinds - IMPL_MAP.put(ResourceKind.BUILD, Build.class); - IMPL_MAP.put(ResourceKind.BUILD_CONFIG, BuildConfig.class); - IMPL_MAP.put(ResourceKind.BUILD_REQUEST, BuildRequest.class); - IMPL_MAP.put(ResourceKind.CONFIG, Config.class); - IMPL_MAP.put(ResourceKind.DEPLOYMENT_CONFIG, DeploymentConfig.class); - IMPL_MAP.put(ResourceKind.IMAGE_STREAM, ImageStream.class); - IMPL_MAP.put(ResourceKind.IMAGE_STREAM_IMPORT, ImageStreamImport.class); - IMPL_MAP.put(ResourceKind.LIST, com.openshift.internal.restclient.model.List.class); - IMPL_MAP.put(ResourceKind.OAUTH_ACCESS_TOKEN, OAuthAccessToken.class); - IMPL_MAP.put(ResourceKind.OAUTH_AUTHORIZE_TOKEN, OAuthAuthorizeToken.class); - IMPL_MAP.put(ResourceKind.OAUTH_CLIENT, OAuthClient.class); - IMPL_MAP.put(ResourceKind.OAUTH_CLIENT_AUTHORIZATION, OAuthClientAuthorization.class); - IMPL_MAP.put(ResourceKind.PROJECT, Project.class); - IMPL_MAP.put(ResourceKind.PROJECT_REQUEST, OpenshiftProjectRequest.class); - IMPL_MAP.put(ResourceKind.POLICY, OpenshiftPolicy.class); - IMPL_MAP.put(ResourceKind.POLICY_BINDING, PolicyBinding.class); - IMPL_MAP.put(ResourceKind.ROLE, OpenshiftRole.class); - IMPL_MAP.put(ResourceKind.ROLE_BINDING, RoleBinding.class); - IMPL_MAP.put(ResourceKind.ROUTE, Route.class); - IMPL_MAP.put(ResourceKind.TEMPLATE, Template.class); - IMPL_MAP.put(ResourceKind.USER, OpenShiftUser.class); - - //Kubernetes Kinds - IMPL_MAP.put(ResourceKind.EVENT, KubernetesEvent.class); - IMPL_MAP.put(ResourceKind.LIMIT_RANGE, LimitRange.class); - IMPL_MAP.put(ResourceKind.POD, Pod.class); - IMPL_MAP.put(ResourceKind.PVC, PersistentVolumeClaim.class); - IMPL_MAP.put(ResourceKind.PERSISTENT_VOLUME, PersistentVolume.class); - IMPL_MAP.put(ResourceKind.RESOURCE_QUOTA, ResourceQuota.class); - IMPL_MAP.put(ResourceKind.REPLICATION_CONTROLLER, ReplicationController.class); - IMPL_MAP.put(ResourceKind.STATUS, Status.class); - IMPL_MAP.put(ResourceKind.SERVICE, Service.class); - IMPL_MAP.put(ResourceKind.SECRET, Secret.class); - IMPL_MAP.put(ResourceKind.SERVICE_ACCOUNT, ServiceAccount.class); - - //fallback - IMPL_MAP.put(ResourceKind.UNRECOGNIZED, KubernetesResource.class); - - } - private IClient client; - - public ResourceFactory(IClient client) { - this.client = client; - } - - public static Map> getImplMap(){ - return Collections.unmodifiableMap(IMPL_MAP); - } - - public List createList(String json, String kind){ - ModelNode data = ModelNode.fromJSONString(json); - final String dataKind = data.get(KIND).asString(); - if(!(kind.toString() + "List").equals(dataKind)){ - throw new RuntimeException(String.format("Unexpected container type '%s' for desired kind: %s", dataKind, kind)); - } - - try{ - final String version = data.get(APIVERSION).asString(); - return buildList(version, data.get("items").asList(), kind); - }catch(Exception e){ - throw new RuntimeException(e); - } - } - - private List buildList(final String version, List items, String kind) throws NoSuchMethodException, SecurityException, InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException { - List resources = new ArrayList(items.size()); - for (ModelNode item : items) { - resources.add(create(item, version, kind, false)); - } - return resources; - } - - @Override - @SuppressWarnings("unchecked") - public T create(InputStream input) { - return (T) create(input, false); - } - - @Override - public IResource create(InputStream input, boolean strict) { - try { - String resource = IOUtils.toString(input, "UTF-8"); - return create(resource, strict); - } catch (IOException e) { - throw new ResourceFactoryException(e, "There was an exception creating the resource from the InputStream"); - } - } - - - @Override - @SuppressWarnings("unchecked") - public T create(String response) { - return (T) create(response, false); - } - - @Override - public IResource create(String response, boolean strict) { - try { - ModelNode node = ModelNode.fromJSONString(response); - String version = node.get(APIVERSION).asString(); - String kind = node.get(KIND).asString(); - return create(node, version, kind, strict); - } catch (UnsupportedVersionException e) { - throw e; - }catch(Exception e) { - throw new ResourceFactoryException(e, "There was an exception creating the resource from: %s", response); - } - } - - - @Override - @SuppressWarnings("unchecked") - public T create(String version, String kind) { - return (T) create(version, kind, false); - } - - @Override - public IResource create(String version, String kind, boolean strict) { - return create(new ModelNode(), version, kind, strict); - } - - private IResource create(ModelNode node, String version, String kind, boolean strict) { - try { - node.get(APIVERSION).set(version); - node.get(KIND).set(kind.toString()); - Map properyKeyMap = ResourcePropertiesRegistry.getInstance().get(version, kind); - if(IMPL_MAP.containsKey(kind)) { - Constructor constructor = IMPL_MAP.get(kind).getConstructor(ModelNode.class, IClient.class, Map.class); - return constructor.newInstance(node, client, properyKeyMap); - } - if(kind.endsWith("List")) { - return new com.openshift.internal.restclient.model.List(node, client, properyKeyMap); - } - return new KubernetesResource(node, client, properyKeyMap); - } catch (UnsupportedVersionException e) { - throw e; - } catch (Exception e) { - throw new ResourceFactoryException(e,"Unable to create %s resource kind %s from %s", version, kind, node); - } - } - - @SuppressWarnings("unchecked") - @Override - public T stub(String kind, String name, String namespace) { - //TODO get k8e or os - String version = client.getOpenShiftAPIVersion(); - KubernetesResource resource = (KubernetesResource) create(version, kind, true); - resource.setName(name); - resource.setNamespace(namespace); - if(StringUtils.isNotEmpty(namespace)) { - resource.setNamespace(namespace); - } - return (T) resource; - } - - @Override - public T stub(String kind, String name) { - return stub(kind, name, null); - } - - @Override - public void setClient(IClient client) { - this.client = client; - } - - - +public class ResourceFactory implements IResourceFactory { + + private static final String KIND = "kind"; + private static final String APIVERSION = "apiVersion"; + private static final Map> IMPL_MAP = new HashMap<>(); + + private IClient client; + + public ResourceFactory(IClient client) { + this.client = client; + } + + public static Map> getImplMap() { + return Collections.unmodifiableMap(IMPL_MAP); + } + + public List createList(String json, String kind) { + ModelNode data = ModelNode.fromJSONString(json); + final String dataKind = data.get(KIND).asString(); + if (!(kind + "List").equals(dataKind)) { + throw new RuntimeException( + String.format("Unexpected container type '%s' for desired kind: %s", dataKind, kind)); + } + + try { + final String version = data.get(APIVERSION).asString(); + return buildList(version, data.get("items").asList(), kind); + } catch (Exception e) { + throw new RuntimeException(e); + } + } + + private List buildList(final String version, List items, String kind) { + List resources = new ArrayList(items.size()); + for (ModelNode item : items) { + resources.add(create(item, version, kind)); + } + return resources; + } + + @Override + @SuppressWarnings("unchecked") + public IResource create(InputStream input) { + try { + String resource = IOUtils.toString(input, "UTF-8"); + return create(resource); + } catch (IOException e) { + throw new ResourceFactoryException(e, "There was an exception creating the resource from the InputStream"); + } + } + + + @Override + @SuppressWarnings("unchecked") + public T create(String response) { + try { + ModelNode node = ModelNode.fromJSONString(response); + String version = node.get(APIVERSION).asString(); + String kind = node.get(KIND).asString(); + return (T) create(node, version, kind); + } catch (UnsupportedVersionException e) { + throw e; + } catch (Exception e) { + throw new ResourceFactoryException(e, "There was an exception creating the resource from: %s", response); + } + } + + @Override + @SuppressWarnings("unchecked") + public T create(String version, String kind) { + return (T) create(new ModelNode(), version, kind); + } + + @Override + @SuppressWarnings("unchecked") + public T create(String version, String kind, String name) { + T resource = (T) create(new ModelNode(), version, kind); + ((KubernetesResource) resource).setName(name); + return resource; + } + + private IResource create(ModelNode node, String version, String kind) { + try { + node.get(APIVERSION).set(version); + node.get(KIND).set(kind); + Map properyKeyMap = ResourcePropertiesRegistry.getInstance().get(version, kind); + if (kind.endsWith("List")) { + return new com.openshift.internal.restclient.model.List(node, client, properyKeyMap); + } + Class klass = getResourceClass(version, kind); + if (klass != null) { + Constructor constructor = klass.getConstructor(ModelNode.class, IClient.class, + Map.class); + return constructor.newInstance(node, client, properyKeyMap); + } + return new KubernetesResource(node, client, properyKeyMap); + } catch (UnsupportedVersionException e) { + throw e; + } catch (Exception e) { + throw new ResourceFactoryException(e, "Unable to create %s resource kind %s from %s", version, kind, node); + } + } + + @Override + public Object createInstanceFrom(String response) { + return create(response); + } + + @SuppressWarnings("unchecked") + private Class getResourceClass(String version, String kind) { + IApiTypeMapper mapper = this.client.adapt(IApiTypeMapper.class); + if (mapper != null) { + try { + IVersionedType type = mapper.getType(version, kind); + return (Class) TypeRegistry.getInstance().getRegisteredType(type.getApiGroupNameAndVersion() + IApiTypeMapper.DOT + type.getKind()); + } catch (Exception e) { + return (Class) TypeRegistry.getInstance().getRegisteredType(version + IApiTypeMapper.DOT + kind); + } + } + return null; + } + + @SuppressWarnings("unchecked") + @Override + public T stub(String kind, String name, String namespace) { + String[] elements = ResourceKind.parse(kind); + IVersionedType type = client.adapt(IApiTypeMapper.class).getType(elements[0], elements[1]); + if (type != null) { + KubernetesResource resource = create(type.getApiGroupNameAndVersion(), elements[1]); + resource.setName(name); + resource.setNamespace(namespace); + if (StringUtils.isNotEmpty(namespace)) { + resource.setNamespace(namespace); + } + return (T) resource; + } else { + throw new ResourceFactoryException(null, "Unable to create resource from kind %s", kind); + } + } + + @Override + public T stub(String kind, String name) { + return stub(kind, name, null); + } + + @Override + public Object stubKind(String kind, Optional name, Optional namespace) { + return stub(kind, name.get(), namespace.get()); + } + + @Override + public void setClient(IClient client) { + this.client = client; + } + } diff --git a/src/main/java/com/openshift/internal/restclient/TypeRegistry.java b/src/main/java/com/openshift/internal/restclient/TypeRegistry.java new file mode 100644 index 00000000..52af0741 --- /dev/null +++ b/src/main/java/com/openshift/internal/restclient/TypeRegistry.java @@ -0,0 +1,112 @@ +/******************************************************************************* + * Copyright (c) 2019 Red Hat, Inc. Distributed under license by Red Hat, Inc. + * All rights reserved. This program is made available under the terms of the + * Eclipse Public License v1.0 which accompanies this distribution, and is + * available at http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: Red Hat, Inc. + ******************************************************************************/ + +package com.openshift.internal.restclient; + +import java.io.IOException; +import java.io.InputStream; +import java.net.URL; +import java.util.Enumeration; +import java.util.HashMap; +import java.util.Map; +import java.util.Map.Entry; +import java.util.Properties; + +import org.jboss.dmr.ModelNode; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.openshift.restclient.IClient; +import com.openshift.restclient.api.models.ITypeMeta; +import com.openshift.restclient.model.IResource; + +/** + * Registry for types implemented by custom classes + * + */ +public class TypeRegistry { + + private static final Logger LOGGER = LoggerFactory.getLogger(TypeRegistry.class); + + private static final String RESOURCE_NAME = "k8stypes.properties"; + + private static TypeRegistry instance; + + public static final TypeRegistry getInstance() { + if (instance == null) { + instance = new TypeRegistry(); + } + return instance; + } + + private Map> registeredTypes = new HashMap<>(); + + private TypeRegistry() { + load(); + } + + private void load() { + try { + Enumeration urls = TypeRegistry.class.getClassLoader().getResources(RESOURCE_NAME); + while (urls.hasMoreElements()) { + URL url = urls.nextElement(); + try (InputStream is = url.openStream()) { + load(is); + } catch (IOException e) { + LOGGER.error("Can't load resource from " + url, e); + } + } + } catch (IOException e) { + LOGGER.error("Can't load resources from " + RESOURCE_NAME, e); + } + } + + private void load(InputStream stream) throws IOException { + Properties p = new Properties(); + p.load(stream); + for (Entry entry : p.entrySet()) { + try { + String className = (String) entry.getKey(); + Class clazz = Class.forName(className); + if (check(clazz)) { + String types = (String) entry.getValue(); + for (String type : types.split(",")) { + registeredTypes.put(type, clazz); + } + } + } catch (ClassNotFoundException e) { + LOGGER.warn("Can't load class", e); + } + } + } + + private boolean check(Class clazz) { + boolean valid = false; + if (IResource.class.isAssignableFrom(clazz)) { + try { + clazz.getConstructor(ModelNode.class, IClient.class, Map.class); + valid = true; + } catch (NoSuchMethodException | SecurityException e) { + LOGGER.error(e.getLocalizedMessage(), e); + } + } else if (ITypeMeta.class.isAssignableFrom(clazz)) { + try { + clazz.getConstructor(ModelNode.class, Map.class); + valid = true; + } catch (NoSuchMethodException | SecurityException e) { + LOGGER.error(e.getLocalizedMessage(), e); + } + } + return valid; + } + + public Class getRegisteredType(String kind) { + return registeredTypes.get(kind); + } +} diff --git a/src/main/java/com/openshift/internal/restclient/URLBuilder.java b/src/main/java/com/openshift/internal/restclient/URLBuilder.java index 04f4aaa2..942488ee 100644 --- a/src/main/java/com/openshift/internal/restclient/URLBuilder.java +++ b/src/main/java/com/openshift/internal/restclient/URLBuilder.java @@ -6,16 +6,17 @@ * * Contributors: Red Hat, Inc. ******************************************************************************/ + package com.openshift.internal.restclient; import java.io.UnsupportedEncodingException; import java.net.MalformedURLException; import java.net.URL; import java.net.URLEncoder; -import java.util.HashMap; +import java.util.AbstractMap; +import java.util.ArrayList; import java.util.Iterator; import java.util.Map; -import java.util.Map.Entry; import org.apache.commons.lang.StringUtils; import org.slf4j.Logger; @@ -30,177 +31,199 @@ import com.openshift.restclient.model.IResource; /** - * Helper class to build the URL connection string in the proper - * format + * Helper class to build the URL connection string in the proper format * - * @author Jeff Cantrill */ public class URLBuilder { - - private static final Logger LOG = LoggerFactory.getLogger(URLBuilder.class); - - private String baseUrl; - private String kind; - private String name; - private Map params = new HashMap(); - private final IApiTypeMapper typeMappings; - - private String apiVersion; - private String namespace; - private String subResource; - - - /** - * - * @param baseUrl - * @param typeMappings the map of kinds to endpoint - * @param resource - */ - URLBuilder(URL baseUrl, IApiTypeMapper typeMappings, IResource resource) { - this(baseUrl, typeMappings); - resource(resource); - } - - /** - * - * @param baseUrl - * @param typeMappings the map of kinds to endpoint - */ - URLBuilder(URL baseUrl, IApiTypeMapper typeMappings) { - this.baseUrl = baseUrl.toString().replaceAll("/*$", ""); - this.typeMappings = typeMappings; - } - - URLBuilder apiVersion(String apiVersion){ - this.apiVersion = apiVersion; - return this; - } - - URLBuilder namespace(String namespace){ - if(StringUtils.isBlank(namespace)) return this; - this.namespace = namespace; - return this; - } - - URLBuilder name(String name) { - this.name = name; - return this; - } - - URLBuilder kind(String kind) { - if(!ResourceKind.values().contains(kind)) { - LOG.warn(String.format("There kind '%s' is not recognized by this client; this operation may fail.", kind)); - } - this.kind = kind; - return this; - } - - URLBuilder resource(IResource resource) { - if (resource == null) return this; - this.name = resource.getName(); - kind(resource.getKind()); - namespace(resource.getNamespace()); - return this; - } - - URLBuilder addParmeter(String key, String value) { - params.put(key, value); - return this; - } - - - URLBuilder subresource(String value) { - this.subResource = value; - return this; - } - - /** - * Builds a URL based on the information provided. Either a resource or - * a resource kind must be provided - * @return - */ - URL build() { - StringBuilder url = new StringBuilder(baseUrl); - if (kind == null) - throw new RuntimeException( - "Unable to build a URL because the ResourceKind is unknown"); - buildWithNamespaceInPath(url); - - try { - if(LOG.isDebugEnabled()) { - LOG.debug(String.format("Built url: %s", url.toString())); - } - return new URL(url.toString()); - } catch (MalformedURLException e) { - throw new RuntimeException(e); - } - } - - private void buildWithNamespaceInPath(StringBuilder url) { - if(!typeMappings.isSupported(apiVersion, kind)) { - throw new UnsupportedEndpointException("Unable to determine the api endpoint for kind '%s'", kind); - } - url.append("/"); - IVersionedApiResource apiResource = typeMappings.getEndpointFor(apiVersion, kind); - url.append(apiResource.getPrefix()).append("/").append(apiResource.getVersion()); - if(namespace == null && apiResource.isNamespaced()) { - throw new OpenShiftException("The api endpoint for kind '%s' requires a namespace", kind); - } - if(apiResource.isNamespaced()) { - url.append("/namespaces/") - .append(namespace); - } - url.append("/").append(apiResource.getName()); - if (name != null) { - url.append("/").append(name); - } - if(StringUtils.isNotBlank(subResource) && !apiResource.isSupported(subResource)){ - throw new OpenShiftException("The api endpoint for kind '%s' && subresource '%s' is not supported by the cluster", kind, subResource); - } - if(StringUtils.isNotBlank(subResource)) { - url.append("/").append(subResource); - } - url = appendParameters(url); - } - - private StringBuilder appendParameters(StringBuilder url) { - if (!params.isEmpty()) { - url.append(IHttpConstants.QUESTION_MARK); - for (Iterator> iterator = params.entrySet() - .iterator(); iterator.hasNext();) { - Entry entry = (Entry) iterator - .next(); - try { - if(StringUtils.isNotBlank(entry.getValue())) { - url.append(entry.getKey()) - .append(IHttpConstants.EQUALS) - .append(URLEncoder.encode(entry.getValue(), "UTF-8")); - }else { - LOG.error("Unable to append parameter: {} since it is blank", entry.getKey()); - } - } catch (UnsupportedEncodingException e) { - throw new RuntimeException(e); - } - if (iterator.hasNext()) { - url.append(IHttpConstants.AMPERSAND); - } - } - } - return url; - } - - public URLBuilder watch() { - addParmeter("watch", "true"); - return this; - } - - public String websocket() { - String url = build().toString(); - url = "wss" + url.substring(url.indexOf(":")); - if(LOG.isDebugEnabled()) { - LOG.debug(String.format("Built url: %s", url)); - } - return url; - } + + private static final Logger LOG = LoggerFactory.getLogger(URLBuilder.class); + + private String baseUrl; + private String kind; + private String name; + private ArrayList> params = new ArrayList<>(); + private final IApiTypeMapper typeMappings; + + private String apiVersion; + private String namespace; + private String subResource; + private String subContext; + + /** + * + * @param baseUrl the base url + * @param typeMappings + * the map of kinds to endpoint + * @param resource the resource to use for building + */ + URLBuilder(URL baseUrl, IApiTypeMapper typeMappings, IResource resource) { + this(baseUrl, typeMappings); + resource(resource); + } + + /** + * + * @param typeMappings + * the map of kinds to endpoint + */ + public URLBuilder(URL baseUrl, IApiTypeMapper typeMappings) { + this.baseUrl = baseUrl.toString().replaceAll("/*$", ""); + this.typeMappings = typeMappings; + } + + public URLBuilder apiVersion(String apiVersion) { + this.apiVersion = apiVersion; + return this; + } + + public URLBuilder namespace(String namespace) { + if (StringUtils.isBlank(namespace)) { + return this; + } + this.namespace = namespace; + return this; + } + + public URLBuilder name(String name) { + this.name = name; + return this; + } + + public URLBuilder kind(String kind) { + if (!ResourceKind.values().contains(kind)) { + LOG.warn(String.format("There kind '%s' is not recognized by this client; this operation may fail.", kind)); + } + this.kind = kind; + return this; + } + + public URLBuilder resource(IResource resource) { + if (resource == null) { + return this; + } + this.name = resource.getName(); + kind(resource.getKind()); + namespace(resource.getNamespaceName()); + return this; + } + + public URLBuilder addParmeter(String key, String value) { + params.add(new AbstractMap.SimpleEntry<>(key, value)); + return this; + } + + public URLBuilder subresource(String value) { + this.subResource = value; + return this; + } + + public URLBuilder subContext(String value) { + this.subContext = value; + return this; + } + + /** + * Builds a URL based on the information provided. Either a resource or a + * resource kind must be provided + * + */ + public URL build() { + StringBuilder url = new StringBuilder(baseUrl); + if (kind == null) { + throw new RuntimeException("Unable to build a URL because the ResourceKind is unknown"); + } + buildWithNamespaceInPath(url); + + try { + if (LOG.isDebugEnabled()) { + LOG.debug(String.format("Built url: %s", url.toString())); + } + return new URL(url.toString()); + } catch (MalformedURLException e) { + throw new RuntimeException(e); + } + } + + private void buildWithNamespaceInPath(StringBuilder url) { + if (!typeMappings.isSupported(apiVersion, kind)) { + throw new UnsupportedEndpointException("Unable to determine the api endpoint for kind '%s'", kind); + } + url.append("/"); + IVersionedApiResource apiResource = typeMappings.getEndpointFor(apiVersion, kind); + appendApiResource(url, apiResource); + appendNamespace(url); + url.append("/").append(apiResource.getName()); + if (name != null) { + url.append("/").append(name); + } + if (StringUtils.isNotBlank(subResource) && !apiResource.isSupported(subResource)) { + throw new OpenShiftException( + "The api endpoint for kind '%s' && subresource '%s' is not supported by the cluster", kind, + subResource); + } + if (StringUtils.isNotBlank(subResource)) { + url.append("/").append(subResource); + } + if (StringUtils.isNotBlank(subContext)) { + url.append("/").append(subContext); + } + url = appendParameters(url); + } + + private void appendApiResource(StringBuilder url, IVersionedApiResource apiResource) { + url.append(apiResource.getPrefix()).append("/"); + if (!StringUtils.isEmpty(apiResource.getApiGroupName())) { + url.append(apiResource.getApiGroupName()).append("/"); + } + url.append(apiResource.getVersion()); + } + + private void appendNamespace(StringBuilder url) { + if (!ResourceKind.PROJECT.equals(kind) && namespace != null) { + url.append("/namespaces/").append(namespace); + } + } + + private StringBuilder appendParameters(StringBuilder url) { + if (!params.isEmpty()) { + url.append(IHttpConstants.QUESTION_MARK); + for (Iterator> iterator = params.iterator(); iterator.hasNext();) { + AbstractMap.SimpleEntry entry = iterator.next(); + try { + if (StringUtils.isNotBlank(entry.getValue())) { + url.append(entry.getKey()).append(IHttpConstants.EQUALS) + .append(URLEncoder.encode(entry.getValue(), "UTF-8")); + } else { + LOG.error("Unable to append parameter: {} since it is blank", entry.getKey()); + } + } catch (UnsupportedEncodingException e) { + throw new RuntimeException(e); + } + if (iterator.hasNext()) { + url.append(IHttpConstants.AMPERSAND); + } + } + } + return url; + } + + public URLBuilder watch() { + addParmeter("watch", "true"); + return this; + } + + public String websocket() { + String url = build().toString(); + url = "wss" + url.substring(url.indexOf(":")); + if (LOG.isDebugEnabled()) { + LOG.debug(String.format("Built url: %s", url)); + } + return url; + } + + public URLBuilder addParameters(Map params) { + params.forEach((k, v) -> addParmeter(k, v)); + return this; + } } diff --git a/src/main/java/com/openshift/internal/restclient/WatchClient.java b/src/main/java/com/openshift/internal/restclient/WatchClient.java deleted file mode 100644 index f9d0e598..00000000 --- a/src/main/java/com/openshift/internal/restclient/WatchClient.java +++ /dev/null @@ -1,284 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2015 Red Hat, Inc. - * Distributed under license by Red Hat, Inc. All rights reserved. - * This program is made available under the terms of the - * Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * Red Hat, Inc. - initial API and implementation - ******************************************************************************/ -package com.openshift.internal.restclient; - -import java.net.URI; -import java.net.URL; -import java.util.ArrayList; -import java.util.Collection; -import java.util.List; -import java.util.concurrent.TimeUnit; -import java.util.concurrent.atomic.AtomicReference; -import java.util.concurrent.locks.Condition; -import java.util.concurrent.locks.Lock; -import java.util.concurrent.locks.ReentrantLock; - -import org.apache.commons.lang.StringUtils; -import org.eclipse.jetty.util.component.LifeCycle; -import org.eclipse.jetty.util.ssl.SslContextFactory; -import org.eclipse.jetty.websocket.api.Session; -import org.eclipse.jetty.websocket.api.UpgradeException; -import org.eclipse.jetty.websocket.api.WebSocketAdapter; -import org.eclipse.jetty.websocket.client.ClientUpgradeRequest; -import org.eclipse.jetty.websocket.client.WebSocketClient; -import org.jboss.dmr.ModelNode; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import com.openshift.internal.restclient.model.KubernetesResource; -import com.openshift.restclient.IApiTypeMapper; -import com.openshift.restclient.IClient; -import com.openshift.restclient.IOpenShiftWatchListener; -import com.openshift.restclient.IOpenShiftWatchListener.ChangeType; -import com.openshift.restclient.IResourceFactory; -import com.openshift.restclient.IWatcher; -import com.openshift.restclient.OpenShiftException; -import com.openshift.restclient.authorization.ResourceForbiddenException; -import com.openshift.restclient.http.IHttpConstants; -import com.openshift.restclient.model.IList; -import com.openshift.restclient.model.IResource; - -/** - * Encapsulation of the logic to handle watching resources. - * @author Jeff Cantrill - * - */ -public class WatchClient implements IHttpConstants, IWatcher{ - private static final Logger LOGGER = LoggerFactory.getLogger(WatchClient.class); - private static final long DEFAULT_LOCK_TIMEOUT = 30 * 1000; - - private URL baseUrl; - private IApiTypeMapper typeMappings; - private IResourceFactory factory; - private IClient client; - private static WebSocketClient wsClient; - private static AtomicReference status = new AtomicReference<>(Status.Stopped); - private static Lock lock = new ReentrantLock(); - private static Condition isStarted = lock.newCondition(); - private static long lockTimeout; - - private enum Status { - Started, - Starting, - Stopped, - Stopping - } - - static { - lockTimeout = getLockTimeout(); - // TODO: move this to lazy creation - wsClient = createWebSocketClient(); - } - - private static WebSocketClient createWebSocketClient() { - WebSocketClient wsClient = newWebSocketClient(); - wsClient.addLifeCycleListener(new LifeCycle.Listener() { - - @Override - public void lifeCycleStopping(LifeCycle event) { - status.set(Status.Stopping); - } - - @Override - public void lifeCycleStopped(LifeCycle event) { - status.set(Status.Stopped); - } - - @Override - public void lifeCycleStarting(LifeCycle event) { - status.set(Status.Starting); - } - - @Override - public void lifeCycleStarted(LifeCycle event) { - status.set(Status.Started); - try { - if (lock.tryLock(lockTimeout, TimeUnit.MILLISECONDS)) { - isStarted.signalAll(); - } - } catch (InterruptedException e) { - LOGGER.debug("Exception while trying to get lock", e); - } finally { - lock.unlock(); - } - } - - @Override - public void lifeCycleFailure(LifeCycle event, Throwable cause) { - LOGGER.error("The watchclient failed:", cause); - status.set(Status.Stopped); - } - }); - return wsClient; - } - - private static long getLockTimeout() { - try { - return Long.parseLong(System.getProperty("com.openshift.restclient.watchlocktimeoutms", String.valueOf(DEFAULT_LOCK_TIMEOUT))); - } catch (NumberFormatException e) { - return DEFAULT_LOCK_TIMEOUT; - } - } - - public WatchClient(URL baseUrl, IApiTypeMapper typeMappings, IClient client) { - this.baseUrl = baseUrl; - this.typeMappings = typeMappings; - this.factory = client.getResourceFactory(); - this.client = client; - } - - private class WatchEndpoint extends WebSocketAdapter{ - private IOpenShiftWatchListener listener; - private List resources; - private final String kind; - - public WatchEndpoint(IOpenShiftWatchListener listener, String kind) { - this.listener = listener; - this.kind = kind; - } - - public void setResources(List resources) { - this.resources = resources; - } - - @Override - public void onWebSocketClose(int statusCode, String reason) { - LOGGER.debug("WatchSocket closed for kind {}", kind); - getSession().close(statusCode, reason); - super.onWebSocketClose(statusCode, reason); - listener.disconnected(); - } - - @Override - public void onWebSocketConnect(Session session) { - LOGGER.debug("WatchSocket connected {}", kind); - super.onWebSocketConnect(session); - listener.connected(resources); - - } - - @Override - public void onWebSocketError(Throwable err) { - LOGGER.debug("WatchSocket Error for kind " + kind, err); - listener.error(createOpenShiftException("WatchSocket Error", err)); - } - - @Override - public void onWebSocketText(String message) { - LOGGER.debug(message); - KubernetesResource payload = factory.create(message); - ModelNode node = payload.getNode(); - IOpenShiftWatchListener.ChangeType event = new ChangeType(node.get("type").asString()); - IResource resource = factory.create(node.get("object").toJSONString(true)); - if(StringUtils.isEmpty(resource.getKind())) { - LOGGER.error("Unable to determine resource kind from: " + node.get("object").toJSONString(false)); - } - listener.received(resource, event); - } - } - - public IWatcher watch(Collection kinds, String namespace, IOpenShiftWatchListener listener) { - try { - ClientUpgradeRequest request = newRequest(this.client.getAuthorizationStrategy().getToken()); - for (String kind : kinds) { - WatchEndpoint socket = new WatchEndpoint(listener, kind); - final String resourceVersion = getResourceVersion(kind, namespace, socket); - - final String endpoint = new URLBuilder(baseUrl, typeMappings) - .kind(kind) - .namespace(namespace) - .watch() - .addParmeter("resourceVersion", resourceVersion) - .websocket(); - connect(socket, endpoint, request); - } - } catch (Exception e) { - throw createOpenShiftException(String.format("Could not watch resources in namespace %s: %s", namespace, e.getMessage()), e); - } - return this; - } - - private void connect(WatchEndpoint socket, String endpoint, ClientUpgradeRequest request) throws Exception { - start(); - if(status.get() == Status.Starting) { - isStarted.await(lockTimeout, TimeUnit.MILLISECONDS); - } - wsClient.connect(socket, new URI(endpoint), request); - } - - public void start() { - if(status.get() == Status.Started - || status.get() == Status.Starting) { - return; - } - try { - wsClient.start(); - } catch (Exception e) { - throw createOpenShiftException(String.format("Could not start watchClient"),e); - } - } - - @Override - public void stop(){ - if(status.get() == Status.Stopping - || status.get() == Status.Stopped) { - return; - } - try { - wsClient.stop(); - } catch (Exception e) { - LOGGER.debug("Unable to stop the watch client",e); - } - } - - - - private ClientUpgradeRequest newRequest(final String token) { - ClientUpgradeRequest request = new ClientUpgradeRequest(); - request.setHeader("Origin", baseUrl.toString()); - request.setHeader("User-Agent", "openshift-restclient-java"); - request.setHeader("Authorization", "Bearer " + token); - return request; - } - - private static WebSocketClient newWebSocketClient() { - SslContextFactory factory = new SslContextFactory(); - factory.setTrustAll(true); - WebSocketClient client = new WebSocketClient(factory); - return client; - } - - private String getResourceVersion(String kind, String namespace, WatchEndpoint endpoint) throws Exception{ - IList list = client.get(kind, namespace); - Collection items = list.getItems(); - List resources = new ArrayList<>(items.size()); - resources.addAll(items); - endpoint.setResources(resources); - return list.getMetadata().get("resourceVersion"); - } - - private OpenShiftException createOpenShiftException(String message, Throwable e) { - LOGGER.debug(message, e); - int responseCode = 0; - if(e instanceof UpgradeException) { - UpgradeException ex = (UpgradeException)e; - responseCode = ex.getResponseStatusCode(); - } - switch(responseCode) { - case STATUS_FORBIDDEN: - return new ResourceForbiddenException("Resource Forbidden", e); - case STATUS_UNAUTHORIZED: - return new com.openshift.restclient.authorization.UnauthorizedException(client.getAuthorizationDetails(this.baseUrl.toString())); - default: - return new OpenShiftException(e, message); - } - } -} diff --git a/src/main/java/com/openshift/internal/restclient/api/capabilities/PodExec.java b/src/main/java/com/openshift/internal/restclient/api/capabilities/PodExec.java new file mode 100644 index 00000000..41eff79d --- /dev/null +++ b/src/main/java/com/openshift/internal/restclient/api/capabilities/PodExec.java @@ -0,0 +1,200 @@ +/******************************************************************************* + * Copyright (c) 2015-2018 Red Hat, Inc. + * Distributed under license by Red Hat, Inc. All rights reserved. + * This program is made available under the terms of the + * Eclipse Public License v1.0 which accompanies this distribution, + * and is available at http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Red Hat, Inc. - initial API and implementation + ******************************************************************************/ + +package com.openshift.internal.restclient.api.capabilities; + +import java.util.Map; +import java.util.concurrent.atomic.AtomicBoolean; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.openshift.internal.restclient.DefaultClient; +import com.openshift.internal.restclient.URLBuilder; +import com.openshift.internal.restclient.capability.AbstractCapability; +import com.openshift.internal.restclient.okhttp.OpenShiftRequestBuilder; +import com.openshift.internal.restclient.okhttp.ResponseCodeInterceptor; +import com.openshift.restclient.IApiTypeMapper; +import com.openshift.restclient.IClient; +import com.openshift.restclient.api.capabilities.IPodExec; +import com.openshift.restclient.capability.IStoppable; +import com.openshift.restclient.http.IHttpConstants; +import com.openshift.restclient.model.IPod; + +import okhttp3.OkHttpClient; +import okhttp3.Request; +import okhttp3.Response; +import okhttp3.WebSocket; +import okhttp3.WebSocketListener; +import okio.ByteString; + +public class PodExec extends AbstractCapability implements IPodExec { + + private static final Logger LOG = LoggerFactory.getLogger(PodExec.class); + private static final String CAPABILITY = "exec"; + + private static final String COMMAND = "command"; + + private static final String K8S_PROTOCOL_HEADER = "X-Stream-Protocol-Version"; + + private static final String K8S_PROTOCOL = "channel.k8s.io"; + + public static final int CHANNEL_STDOUT = 1; + public static final int CHANNEL_STDERR = 2; + public static final int CHANNEL_EXECERR = 3; + + private final IPod pod; + private final DefaultClient client; + private final IApiTypeMapper mapper; + + public PodExec(IPod pod, IClient client) { + super(pod, client, CAPABILITY); + this.pod = pod; + this.client = client.adapt(DefaultClient.class); + this.mapper = client.adapt(IApiTypeMapper.class); + } + + @Override + public String getName() { + return PodExec.class.getSimpleName(); + } + + @Override + public IStoppable start(IPodExecOutputListener listener, Options options, String... commands) { + + if (options == null) { + options = new Options(); + } + + /* + * with 3.7 per https://github.com/openshift/origin/issues/15330, 3.6 was + * evidently broke in allowing stdErr/stdOut to not be set; need to set + * stdout/stderr to true + */ + options.stdErr(true); + options.stdOut(true); + + Map parameters = options.getMap(); + + OkHttpClient okClient = client.adapt(OkHttpClient.class); + + URLBuilder urlBuilder = new URLBuilder(client.getBaseURL(), mapper).resource(pod).subresource(CAPABILITY) + .addParameters(parameters); + + // The main command and all arguments are specified as 'command' parameters + for (String command : commands) { + urlBuilder.addParmeter(COMMAND, command); + } + + final String endpoint = urlBuilder.websocket(); + + Request request = new OpenShiftRequestBuilder() + .url(endpoint) + .method("GET", null) + .accept(IHttpConstants.MEDIATYPE_ANY) + .authorization(client.getAuthorizationContext()) + .addHeader(K8S_PROTOCOL_HEADER, K8S_PROTOCOL) + // Unless we mark this as ignored, exceptions triggered by interceptor would be + // lost in dispatcher thread + .tag(new ResponseCodeInterceptor.Ignore() {}) + .build(); + + ExecOutputListenerAdapter adapter = new ExecOutputListenerAdapter(listener); + okClient.newWebSocket(request, adapter); + return adapter; + } + + static class ExecOutputListenerAdapter extends WebSocketListener implements IStoppable { + + private final IPodExecOutputListener listener; + private WebSocket call; + private AtomicBoolean open = new AtomicBoolean(false); + private boolean shouldStop = false; + + public ExecOutputListenerAdapter(IPodExecOutputListener listener) { + this.listener = listener; + } + + @Override + public void stop() { + if (call != null) { + call.cancel(); + } else { + shouldStop = true; + } + } + + @Override + public void onOpen(WebSocket webSocket, Response response) { + if (open.compareAndSet(false, true)) { + this.call = webSocket; + listener.onOpen(); + if (shouldStop) { + webSocket.cancel(); + } + } + } + + @Override + public void onClosing(WebSocket socket, int code, String reason) { + if (open.compareAndSet(true, false)) { + listener.onClose(code, reason); + } + } + + @Override + public void onFailure(WebSocket socket, Throwable e, Response response) { + listener.onFailure(e); + } + + public void deliver(int channel, String msg) { + switch (channel) { + case CHANNEL_STDOUT: + listener.onStdOut(msg); + break; + case CHANNEL_STDERR: + listener.onStdErr(msg); + break; + case CHANNEL_EXECERR: + listener.onExecErr(msg); + break; + default: + LOG.warn("Unable to deliver exec message of type [%d]: %s", channel, msg); + } + } + + @Override + public void onMessage(WebSocket webSocket, String text) { + throw new IllegalStateException("Should not receive text message on pod exec sockets"); + } + + @Override + public void onMessage(WebSocket socket, ByteString message) { + + /** + * https://godoc.org/k8s.io/kubernetes/pkg/util/wsstream The Websocket + * subprotocol "channel.k8s.io" prepends each binary message with a byte + * indicating the channel number (zero indexed) the message was sent on. + * Messages in both directions should prefix their messages with this channel + * byte. When used for remote execution, the channel numbers are by convention + * defined to match the POSIX file-descriptors assigned to STDIN, STDOUT, and + * STDERR (0, 1, and 2). No other conversion is performed on the raw subprotocol + * - writes are sent as they are received by the server. + */ + + int channel = message.getByte(0); + String msg = message.substring(1).utf8(); + deliver(channel, msg); + } + + } + +} diff --git a/src/main/java/com/openshift/internal/restclient/api/capabilities/ScaleCapability.java b/src/main/java/com/openshift/internal/restclient/api/capabilities/ScaleCapability.java new file mode 100644 index 00000000..11a87dd5 --- /dev/null +++ b/src/main/java/com/openshift/internal/restclient/api/capabilities/ScaleCapability.java @@ -0,0 +1,70 @@ +/******************************************************************************* + * Copyright (c) 2016 Red Hat, Inc. + * Distributed under license by Red Hat, Inc. All rights reserved. + * This program is made available under the terms of the + * Eclipse Public License v1.0 which accompanies this distribution, + * and is available at http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Red Hat, Inc. - initial API and implementation + ******************************************************************************/ + +package com.openshift.internal.restclient.api.capabilities; + +import java.util.Collections; +import java.util.HashMap; +import java.util.Map; +import java.util.Optional; + +import com.openshift.internal.restclient.capability.AbstractCapability; +import com.openshift.restclient.IClient; +import com.openshift.restclient.ResourceKind; +import com.openshift.restclient.api.ITypeFactory; +import com.openshift.restclient.api.capabilities.IScalable; +import com.openshift.restclient.apis.autoscaling.models.IScale; +import com.openshift.restclient.http.IHttpConstants; +import com.openshift.restclient.model.IReplicationController; + +/** + * Implementation of the scalable interface. Applies to a deploymentconfig for + * the moment + * + */ +public class ScaleCapability extends AbstractCapability implements IScalable { + + private static final Map ARG_KINDS = new HashMap<>(); + + static { + ARG_KINDS.put(ResourceKind.DEPLOYMENT_CONFIG, "extensions/v1beta1.Scale"); + ARG_KINDS.put(ResourceKind.REPLICATION_CONTROLLER, "autoscaling/v1.Scale"); + } + + private static final int MIN_VALUE = 0; + private static final String CAPABILITY = "scale"; + private final IClient client; + private IReplicationController rc; + private final ITypeFactory factory; + + public ScaleCapability(IReplicationController rc, IClient client, ITypeFactory factory) { + super(rc, client, CAPABILITY); + this.client = client; + this.rc = rc; + this.factory = factory; + } + + @Override + public String getName() { + return ScaleCapability.class.getSimpleName(); + } + + @Override + public IScale scaleTo(int replicas) { + replicas = replicas >= MIN_VALUE ? replicas : MIN_VALUE; + IScale scale = (IScale) factory.stubKind(ARG_KINDS.get(rc.getKind()), Optional.of(rc.getName()), + Optional.of(rc.getNamespaceName())); + scale.setSpecReplicas(replicas); + return client.execute(factory, IHttpConstants.PUT, rc.getKind(), rc.getNamespaceName(), rc.getName(), + CAPABILITY, null, scale, Collections.emptyMap()); + } + +} diff --git a/src/main/java/com/openshift/internal/restclient/api/models/Endpoints.java b/src/main/java/com/openshift/internal/restclient/api/models/Endpoints.java new file mode 100644 index 00000000..5a527dde --- /dev/null +++ b/src/main/java/com/openshift/internal/restclient/api/models/Endpoints.java @@ -0,0 +1,143 @@ +/******************************************************************************* + * Copyright (c) 2016 Red Hat, Inc. + * Distributed under license by Red Hat, Inc. All rights reserved. + * This program is made available under the terms of the + * Eclipse Public License v1.0 which accompanies this distribution, + * and is available at http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Red Hat, Inc. - initial API and implementation + ******************************************************************************/ + +package com.openshift.internal.restclient.api.models; + +import java.util.ArrayList; +import java.util.List; +import java.util.Map; + +import org.jboss.dmr.ModelNode; + +import com.openshift.internal.restclient.model.KubernetesResource; +import com.openshift.internal.restclient.model.ModelNodeAdapter; +import com.openshift.internal.restclient.model.ObjectReference; +import com.openshift.internal.util.JBossDmrExtentions; +import com.openshift.restclient.IClient; +import com.openshift.restclient.api.models.IEndpoints; +import com.openshift.restclient.model.IObjectReference; + +public class Endpoints extends KubernetesResource implements IEndpoints { + + public Endpoints(ModelNode node, IClient client, Map overrideProperties) { + super(node, client, overrideProperties); + } + + @Override + public List getSubSets() { + List root = get("subsets").asList(); + ArrayList subsets = new ArrayList(root.size()); + for (ModelNode n : root) { + subsets.add(new EndpointSubset(n, getPropertyKeys())); + } + return subsets; + } + + private static class EndpointSubset extends ModelNodeAdapter implements IEndpointSubset { + + protected EndpointSubset(ModelNode node, Map propertyKeys) { + super(node, propertyKeys); + } + + @Override + public List getAddresses() { + List root = JBossDmrExtentions.get(getNode(), getPropertyKeys(), "addresses").asList(); + ArrayList addresses = new ArrayList(root.size()); + for (ModelNode n : root) { + addresses.add(new EndpointAddress(n, getPropertyKeys())); + } + return addresses; + } + + @Override + public List getNotReadyAddresses() { + List root = JBossDmrExtentions.get(getNode(), getPropertyKeys(), "notreadyaddresses").asList(); + ArrayList addresses = new ArrayList(root.size()); + for (ModelNode n : root) { + addresses.add(new EndpointAddress(n, getPropertyKeys())); + } + return addresses; + } + + @Override + public List getPorts() { + List root = JBossDmrExtentions.get(getNode(), getPropertyKeys(), PORTS).asList(); + ArrayList ports = new ArrayList(root.size()); + for (ModelNode n : root) { + ports.add(new EndpointPort(n, getPropertyKeys())); + } + return ports; + } + + } + + private static class EndpointAddress extends ModelNodeAdapter implements IEndpointAddress { + + private static final String TARGET_REF = "targetRef"; + + protected EndpointAddress(ModelNode node, Map propertyKeys) { + super(node, propertyKeys); + } + + @Override + public String getIP() { + return JBossDmrExtentions.asString(getNode(), getPropertyKeys(), "ip"); + } + + @Override + public String getHostName() { + return JBossDmrExtentions.asString(getNode(), getPropertyKeys(), "hostname"); + } + + @Override + public String getNodeName() { + return JBossDmrExtentions.asString(getNode(), getPropertyKeys(), "nodeName"); + } + + @Override + public String getName() { + return JBossDmrExtentions.asString(getNode(), getPropertyKeys(), NAME); + } + + @Override + public IObjectReference getTargetRef() { + if (getNode().has(JBossDmrExtentions.getPath(getPropertyKeys(), TARGET_REF))) { + ModelNode node = JBossDmrExtentions.get(getNode(), getPropertyKeys(), TARGET_REF); + return new ObjectReference(node); + } + return null; + } + + } + + private static class EndpointPort extends ModelNodeAdapter implements IEndpointPort { + + protected EndpointPort(ModelNode node, Map propertyKeys) { + super(node, propertyKeys); + } + + @Override + public String getName() { + return JBossDmrExtentions.asString(getNode(), getPropertyKeys(), NAME); + } + + @Override + public int getPort() { + return JBossDmrExtentions.asInt(getNode(), getPropertyKeys(), "port"); + } + + @Override + public String getProtocol() { + return JBossDmrExtentions.asString(getNode(), getPropertyKeys(), PROTOCOL); + } + + } +} diff --git a/src/main/java/com/openshift/internal/restclient/api/models/TypeMeta.java b/src/main/java/com/openshift/internal/restclient/api/models/TypeMeta.java new file mode 100644 index 00000000..c70d9168 --- /dev/null +++ b/src/main/java/com/openshift/internal/restclient/api/models/TypeMeta.java @@ -0,0 +1,46 @@ +/******************************************************************************* + * Copyright (c) 2016 Red Hat, Inc. + * Distributed under license by Red Hat, Inc. All rights reserved. + * This program is made available under the terms of the + * Eclipse Public License v1.0 which accompanies this distribution, + * and is available at http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Red Hat, Inc. - initial API and implementation + ******************************************************************************/ + +package com.openshift.internal.restclient.api.models; + +import static com.openshift.internal.util.JBossDmrExtentions.asString; + +import java.util.Map; + +import org.jboss.dmr.ModelNode; + +import com.openshift.internal.restclient.model.ModelNodeAdapter; +import com.openshift.internal.restclient.model.properties.ResourcePropertyKeys; +import com.openshift.restclient.api.models.ITypeMeta; + +public class TypeMeta extends ModelNodeAdapter implements ITypeMeta, ResourcePropertyKeys { + + /** + * + * @param node the node + * @param propertyKeys + * overrides based on version + */ + public TypeMeta(ModelNode node, Map propertyKeys) { + super(node, propertyKeys); + } + + @Override + public String getApiVersion() { + return asString(getNode(), getPropertyKeys(), APIVERSION); + } + + @Override + public String getKind() { + return asString(getNode(), getPropertyKeys(), KIND); + } + +} diff --git a/src/main/java/com/openshift/internal/restclient/apis/TypeMetaFactory.java b/src/main/java/com/openshift/internal/restclient/apis/TypeMetaFactory.java new file mode 100644 index 00000000..b51a7000 --- /dev/null +++ b/src/main/java/com/openshift/internal/restclient/apis/TypeMetaFactory.java @@ -0,0 +1,108 @@ +/******************************************************************************* + * Copyright (c) 2016-2019 Red Hat, Inc. + * Distributed under license by Red Hat, Inc. All rights reserved. + * This program is made available under the terms of the + * Eclipse Public License v1.0 which accompanies this distribution, + * and is available at http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Red Hat, Inc. - initial API and implementation + ******************************************************************************/ + +package com.openshift.internal.restclient.apis; + +import java.lang.reflect.Constructor; +import java.util.Map; +import java.util.Optional; + +import org.apache.commons.lang.StringUtils; +import org.jboss.dmr.ModelNode; + +import com.openshift.internal.restclient.TypeRegistry; +import com.openshift.internal.restclient.api.models.TypeMeta; +import com.openshift.internal.restclient.model.properties.ResourcePropertiesRegistry; +import com.openshift.internal.restclient.model.properties.ResourcePropertyKeys; +import com.openshift.internal.util.JBossDmrExtentions; +import com.openshift.restclient.IApiTypeMapper; +import com.openshift.restclient.OpenShiftException; +import com.openshift.restclient.ResourceFactoryException; +import com.openshift.restclient.UnsupportedVersionException; +import com.openshift.restclient.api.ITypeFactory; +import com.openshift.restclient.api.models.INameSetable; +import com.openshift.restclient.api.models.INamespaceSetable; +import com.openshift.restclient.api.models.ITypeMeta; + +public class TypeMetaFactory implements ITypeFactory, ResourcePropertyKeys { + + private static final String DELIMITER = "."; + + @Override + public Object stubKind(String kind, Optional name, Optional namespace) { + if (StringUtils.isEmpty(kind)) { + throw new OpenShiftException("Unable to stub a kind when the kind passed in is empty"); + } + try { + String version = ""; + if (kind.contains(DELIMITER)) { + int delimeter = kind.indexOf(DELIMITER); + version = StringUtils.left(kind, delimeter); + kind = StringUtils.right(kind, kind.length() - delimeter - DELIMITER.length()); + } + Map properyKeyMap = ResourcePropertiesRegistry.getInstance().get(version, kind); + ModelNode node = new ModelNode(); + JBossDmrExtentions.set(node, properyKeyMap, APIVERSION, version); + JBossDmrExtentions.set(node, properyKeyMap, KIND, kind); + + ITypeMeta instance = null; + Class clazz = (Class) TypeRegistry.getInstance().getRegisteredType(version + IApiTypeMapper.DOT + kind); + if (clazz != null) { + Constructor constructor = clazz.getConstructor(ModelNode.class, + Map.class); + instance = constructor.newInstance(node, properyKeyMap); + } else { + instance = new TypeMeta(node, properyKeyMap); + } + + if (name.isPresent() && instance instanceof INameSetable) { + ((INameSetable) instance).setName(name.get()); + } + if (namespace.isPresent() && instance instanceof INamespaceSetable) { + ((INamespaceSetable) instance).setNamespace(namespace.get()); + } + + return instance; + } catch (UnsupportedVersionException e) { + throw e; + } catch (Exception e) { + throw new ResourceFactoryException(e, "Unable to stub instance from %s", kind); + } + } + + @Override + public Object createInstanceFrom(String response) { + try { + ModelNode node = ModelNode.fromJSONString(response); + String version = node.get(APIVERSION).asString(); + String kind = node.get(KIND).asString(); + + Map properyKeyMap = ResourcePropertiesRegistry.getInstance().get(version, kind); + Class clazz = (Class) TypeRegistry.getInstance().getRegisteredType(version + IApiTypeMapper.DOT + kind); + + try { + if (clazz != null) { + Constructor constructor = clazz.getConstructor(ModelNode.class, + Map.class); + return constructor.newInstance(node, properyKeyMap); + } + } catch (Exception e) { + return new TypeMeta(node, properyKeyMap); + } + return new TypeMeta(node, properyKeyMap); + } catch (UnsupportedVersionException e) { + throw e; + } catch (Exception e) { + throw new ResourceFactoryException(e, "Unable to create from %s", response); + } + } + +} diff --git a/src/main/java/com/openshift/internal/restclient/apis/autoscaling/models/Scale.java b/src/main/java/com/openshift/internal/restclient/apis/autoscaling/models/Scale.java new file mode 100644 index 00000000..66799cb0 --- /dev/null +++ b/src/main/java/com/openshift/internal/restclient/apis/autoscaling/models/Scale.java @@ -0,0 +1,122 @@ +/******************************************************************************* + * Copyright (c) 2016 Red Hat, Inc. + * Distributed under license by Red Hat, Inc. All rights reserved. + * This program is made available under the terms of the + * Eclipse Public License v1.0 which accompanies this distribution, + * and is available at http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Red Hat, Inc. - initial API and implementation + ******************************************************************************/ + +package com.openshift.internal.restclient.apis.autoscaling.models; + +import static com.openshift.internal.util.JBossDmrExtentions.asInt; +import static com.openshift.internal.util.JBossDmrExtentions.asMap; +import static com.openshift.internal.util.JBossDmrExtentions.asString; +import static com.openshift.internal.util.JBossDmrExtentions.get; +import static com.openshift.internal.util.JBossDmrExtentions.getPath; +import static com.openshift.internal.util.JBossDmrExtentions.set; + +import java.util.Collections; +import java.util.Map; + +import org.jboss.dmr.ModelNode; + +import com.openshift.internal.restclient.api.models.TypeMeta; +import com.openshift.restclient.apis.autoscaling.models.IScale; + +public class Scale extends TypeMeta implements IScale { + + private static final String SPEC_REPLICAS = "spec.replicas"; + + public Scale() { + super(new ModelNode(), Collections.emptyMap()); + } + + /** + * + * @param propertyKeys + * overrides based on version + */ + public Scale(ModelNode node, Map propertyKeys) { + super(node, propertyKeys); + } + + @Override + public int getSpecReplicas() { + return asInt(getNode(), getPropertyKeys(), SPEC_REPLICAS); + } + + @Override + public void setSpecReplicas(int replicas) { + set(getNode(), getPropertyKeys(), SPEC_REPLICAS, replicas); + } + + @Override + public String getName() { + return asString(getNode(), getPropertyKeys(), METADATA_NAME); + } + + @Override + public void setName(String name) { + set(getNode(), getPropertyKeys(), METADATA_NAME, name); + } + + @Override + public String getCreationTimeStamp() { + return asString(getNode(), getPropertyKeys(), CREATION_TIMESTAMP); + } + + @Override + public String getNamespace() { + return asString(getNode(), getPropertyKeys(), METADATA_NAMESPACE); + } + + @Override + public void setNamespace(String namespace) { + set(getNode(), getPropertyKeys(), METADATA_NAMESPACE, namespace); + } + + @Override + public String getResourceVersion() { + return asString(getNode(), getPropertyKeys(), METADATA_RESOURCE_VERSION); + } + + @Override + public Map getLabels() { + return asMap(getNode(), getPropertyKeys(), LABELS); + } + + @Override + public void addLabel(String key, String value) { + ModelNode labels = getNode().get(getPath(LABELS)); + labels.get(key).set(value); + } + + @Override + public Map getAnnotations() { + return asMap(getNode(), getPropertyKeys(), ANNOTATIONS); + } + + @Override + public String getAnnotation(String key) { + return getAnnotations().get(key); + } + + @Override + public void setAnnotation(String name, String value) { + if (value == null) { + return; + } + ModelNode annotations = get(getNode(), getPropertyKeys(), ANNOTATIONS); + annotations.get(name).set(value); + } + + @Override + public boolean isAnnotatedWith(String key) { + Map annotations = getAnnotations(); + return annotations.containsKey(key); + } + +} diff --git a/src/main/java/com/openshift/internal/restclient/authorization/AuthorizationClient.java b/src/main/java/com/openshift/internal/restclient/authorization/AuthorizationClient.java deleted file mode 100644 index 2b9a7baf..00000000 --- a/src/main/java/com/openshift/internal/restclient/authorization/AuthorizationClient.java +++ /dev/null @@ -1,247 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2015 Red Hat, Inc. Distributed under license by Red Hat, Inc. - * All rights reserved. This program is made available under the terms of the - * Eclipse Public License v1.0 which accompanies this distribution, and is - * available at http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: Red Hat, Inc. - ******************************************************************************/ -package com.openshift.internal.restclient.authorization; - -import java.io.Closeable; -import java.io.IOException; -import java.net.ProxySelector; -import java.net.URISyntaxException; -import java.security.GeneralSecurityException; -import java.security.KeyManagementException; -import java.security.KeyStore; -import java.security.KeyStoreException; -import java.security.NoSuchAlgorithmException; -import java.security.cert.CertificateException; -import java.security.cert.X509Certificate; - -import javax.net.ssl.SSLContext; -import javax.net.ssl.TrustManager; -import javax.net.ssl.TrustManagerFactory; -import javax.net.ssl.X509TrustManager; - -import org.apache.http.client.ClientProtocolException; -import org.apache.http.client.CredentialsProvider; -import org.apache.http.client.config.RequestConfig; -import org.apache.http.client.methods.CloseableHttpResponse; -import org.apache.http.client.methods.HttpGet; -import org.apache.http.client.utils.URIBuilder; -import org.apache.http.conn.ssl.AllowAllHostnameVerifier; -import org.apache.http.conn.ssl.X509HostnameVerifier; -import org.apache.http.impl.client.CloseableHttpClient; -import org.apache.http.impl.client.HttpClients; -import org.apache.http.impl.conn.SystemDefaultRoutePlanner; -import org.apache.http.params.HttpParams; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import com.openshift.restclient.IClient; -import com.openshift.restclient.ISSLCertificateCallback; -import com.openshift.restclient.NoopSSLCertificateCallback; -import com.openshift.restclient.OpenShiftException; -import com.openshift.restclient.authorization.IAuthorizationClient; -import com.openshift.restclient.authorization.IAuthorizationContext; -import com.openshift.restclient.authorization.IAuthorizationDetails; -import com.openshift.restclient.authorization.IAuthorizationStrategy; -import com.openshift.restclient.authorization.ResourceForbiddenException; -import com.openshift.restclient.authorization.TokenAuthorizationStrategy; -import com.openshift.restclient.authorization.UnauthorizedException; -import com.openshift.restclient.http.IHttpClient; - -/** - * @author Jeff Cantrill - */ -public class AuthorizationClient implements IAuthorizationClient { - private static final Logger LOG = LoggerFactory.getLogger(IAuthorizationClient.class); - - private static final int TIMEOUT = 10 * 1000; //10 seconds - - private SSLContext sslContext; - private X509HostnameVerifier hostnameVerifier = new AllowAllHostnameVerifier(); - private IClient openshiftClient; - private int connectTimeoutMillis; - - - public AuthorizationClient(IClient client) { - this(client, TIMEOUT); - connectTimeoutMillis = TIMEOUT; - } - - - public AuthorizationClient(IClient client, int connectTimeoutMillis) { - this.openshiftClient = client; - this.connectTimeoutMillis = connectTimeoutMillis; - setSSLCertificateCallback(new NoopSSLCertificateCallback()); - } - - - @Override - public IAuthorizationDetails getAuthorizationDetails(final String baseURL) { - try { - getContextUsingCredentials(baseURL, null); - return new AuthorizationDetails(String.format("%s/oauth/token/request", baseURL)); - }catch(UnauthorizedException e) { - return e.getAuthorizationDetails(); - } - } - - @Override - public IAuthorizationContext getContext(final String baseURL) { - OpenShiftCredentialsProvider credentialsProvider = new OpenShiftCredentialsProvider(); - openshiftClient.getAuthorizationStrategy().accept(credentialsProvider); - final IAuthorizationStrategy configuredAuthStrategy = openshiftClient.getAuthorizationStrategy(); - try { - final String token = credentialsProvider.getToken(); - openshiftClient.setAuthorizationStrategy(new TokenAuthorizationStrategy(token)); - return new AuthorizationContext(token, null, openshiftClient.getCurrentUser(), credentialsProvider.getScheme()); - }catch(ResourceForbiddenException e) { - //the response if token is invalid because we tried to - //get the current user - }catch(UnauthorizedException | com.openshift.internal.restclient.http.UnauthorizedException e) { - openshiftClient.setAuthorizationStrategy(configuredAuthStrategy); - return getContextUsingCredentials(baseURL, credentialsProvider); - }finally{ - openshiftClient.setAuthorizationStrategy(configuredAuthStrategy); - } - return getContextUsingCredentials(baseURL, credentialsProvider); - - } - - private IAuthorizationContext getContextUsingCredentials(final String baseURL, CredentialsProvider credentialsProvider) { - - CloseableHttpResponse response = null; - CloseableHttpClient client = null; - try { - OpenShiftAuthorizationRedirectStrategy redirectStrategy = new OpenShiftAuthorizationRedirectStrategy(openshiftClient); - RequestConfig defaultRequestConfig = RequestConfig.custom() - .setSocketTimeout(connectTimeoutMillis) - .setConnectTimeout(connectTimeoutMillis) - .setConnectionRequestTimeout(connectTimeoutMillis) - .setStaleConnectionCheckEnabled(true) - .build(); - client = HttpClients.custom() - .setRedirectStrategy(redirectStrategy) - .setRoutePlanner(new SystemDefaultRoutePlanner(ProxySelector.getDefault())) - .setHostnameVerifier(hostnameVerifier) - .setDefaultCredentialsProvider(credentialsProvider) - .setSslcontext(sslContext) - .setDefaultRequestConfig(defaultRequestConfig) - .build(); - HttpGet request = - new HttpGet( - new URIBuilder(String.format("%s/oauth/authorize", baseURL)) - .addParameter("response_type", "token") - .addParameter("client_id", "openshift-challenging-client") - .build()); - request.addHeader("X-CSRF-Token", "1"); - response = client.execute(request); - return redirectStrategy.getAuthorizationContext(); - } catch (URISyntaxException e) { - throw new OpenShiftException(e, String.format("Unvalid URI while trying to get an authorization context for server %s", baseURL)); - } catch (ClientProtocolException e) { - throw new OpenShiftException(e, String.format("Client protocol exception while trying to get authorization context for server %s", baseURL)); - } catch (IOException e) { - throw new OpenShiftException(e, String.format("%s while trying to get an authorization context for server %s", e.getClass().getName(), baseURL)); - } finally { - close(response); - close(client); - } - - } - - private void close(Closeable closer) { - if (closer == null) - return; - try { - closer.close(); - } catch (IOException e) { - e.printStackTrace(); - } - } - - @Override - public void setSSLCertificateCallback(ISSLCertificateCallback callback) { - X509TrustManager trustManager = null; - if (callback != null) { - trustManager = createCallbackTrustManager(callback); - } - try { - this.sslContext = SSLContext.getInstance("TLS"); - this.sslContext.init(null, new TrustManager[] { trustManager }, null); - } catch (NoSuchAlgorithmException e) { - LOG.warn("Could not install trust manager callback", e); - this.sslContext = null; - } catch (KeyManagementException e) { - LOG.warn("Could not install trust manager callback", e); - this.sslContext = null; - } - } - - // TODO REPLACE me with osjc impl - private X509TrustManager createCallbackTrustManager(ISSLCertificateCallback sslAuthorizationCallback) { - X509TrustManager trustManager = null; - try { - trustManager = getCurrentTrustManager(); - if (trustManager == null) { - LOG.warn("Could not install trust manager callback, no trustmanager was found."); - } else { - trustManager = new CallbackTrustManager(trustManager, sslAuthorizationCallback); - } - } catch (GeneralSecurityException e) { - LOG.warn("Could not install trust manager callback.", e); - } - return trustManager; - } - - // TODO replace me with OSJC implementation - private X509TrustManager getCurrentTrustManager() throws NoSuchAlgorithmException, KeyStoreException { - TrustManagerFactory trustManagerFactory = - TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()); - trustManagerFactory.init((KeyStore) null); - - X509TrustManager x509TrustManager = null; - for (TrustManager trustManager : trustManagerFactory.getTrustManagers()) { - if (trustManager instanceof X509TrustManager) { - x509TrustManager = (X509TrustManager) trustManager; - break; - } - } - return x509TrustManager; - } - - // TODO - Replace me with instance in OSJC - private static class CallbackTrustManager implements X509TrustManager { - - private X509TrustManager trustManager; - private ISSLCertificateCallback callback; - - private CallbackTrustManager(X509TrustManager currentTrustManager, ISSLCertificateCallback callback) - throws NoSuchAlgorithmException, KeyStoreException { - this.trustManager = currentTrustManager; - this.callback = callback; - } - - public X509Certificate[] getAcceptedIssuers() { - return trustManager.getAcceptedIssuers(); - } - - public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException { - try { - trustManager.checkServerTrusted(chain, authType); - } catch (CertificateException e) { - if (!callback.allowCertificate(chain)) { - throw e; - } - } - } - - public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException { - trustManager.checkServerTrusted(chain, authType); - } - } -} diff --git a/src/main/java/com/openshift/internal/restclient/authorization/AuthorizationContext.java b/src/main/java/com/openshift/internal/restclient/authorization/AuthorizationContext.java index 4f72bbac..a503c35a 100644 --- a/src/main/java/com/openshift/internal/restclient/authorization/AuthorizationContext.java +++ b/src/main/java/com/openshift/internal/restclient/authorization/AuthorizationContext.java @@ -1,63 +1,131 @@ /******************************************************************************* - * Copyright (c) 2015 Red Hat, Inc. Distributed under license by Red Hat, Inc. + * Copyright (c) 2015-2019 Red Hat, Inc. Distributed under license by Red Hat, Inc. * All rights reserved. This program is made available under the terms of the * Eclipse Public License v1.0 which accompanies this distribution, and is * available at http://www.eclipse.org/legal/epl-v10.html * * Contributors: Red Hat, Inc. ******************************************************************************/ + package com.openshift.internal.restclient.authorization; import org.apache.commons.lang.StringUtils; +import com.openshift.restclient.IClient; +import com.openshift.restclient.ResourceKind; import com.openshift.restclient.authorization.IAuthorizationContext; +import com.openshift.restclient.authorization.IAuthorizationDetails; import com.openshift.restclient.model.user.IUser; -/** - * @author Jeff Cantrill - */ public class AuthorizationContext implements IAuthorizationContext { - - private String token; - private String expires; - private String scheme; - private IUser user; - - public AuthorizationContext(String scope){ - this.scheme = scope; - } - - - public AuthorizationContext(String token, String expires, IUser user, String scheme){ - this.token = token; - this.expires = expires; - this.user = user; - this.scheme = scheme; - } - - @Override - public boolean isAuthorized() { - return StringUtils.isNotEmpty(token); - } - - @Override - public String getToken(){ - return this.token; - } - - @Override - public String getExpiresIn(){ - return expires; - } - - @Override - public String getAuthScheme() { - return scheme; - } - - @Override - public IUser getUser() { - return user; - } - + + private String token; + private String expires; + private String scheme; + private IUser user; + private String userName; + private String password; + private IClient client; + + public AuthorizationContext(String scope) { + this.scheme = scope; + } + + public AuthorizationContext(String token, String userName, String password) { + this.token = token; + this.userName = userName; + this.password = password; + } + + public AuthorizationContext(String token, String expires, IUser user, String scheme) { + this.token = token; + this.expires = expires; + this.user = user; + this.scheme = scheme; + } + + public AuthorizationContext clone() { + AuthorizationContext context = new AuthorizationContext(this.token, this.expires, this.user, this.scheme); + context.setUserName(this.userName); + context.setPassword(this.password); + context.setClient(this.client); + return context; + } + + public void setClient(IClient client) { + this.client = client; + } + + @Override + public boolean isAuthorized() { + if (user == null) { + synchronized (this) { + user = client.get(ResourceKind.USER, "~", ""); + } + } + return StringUtils.isNotEmpty(token); + } + + @Override + public IAuthorizationDetails getAuthorizationDetails() { + return new AuthorizationDetails(String.format("%s/request", client.getTokenEndpoint())); + } + + @Override + public String getToken() { + return this.token; + } + + @Override + public String getExpiresIn() { + return expires; + } + + @Override + public String getAuthScheme() { + return scheme; + } + + @Override + public IUser getUser() { + return user; + } + + public void setUser(IUser user) { + this.user = user; + } + + @Override + public void setToken(String token) { + this.token = token; + } + + @Override + public void setUserName(String userName) { + this.userName = userName; + } + + @Override + public String getUserName() { + return this.userName; + } + + @Override + public void setPassword(String password) { + this.password = password; + } + + @Override + public String getPassword() { + return this.password; + } + + @Override + public void invalidate() { + this.user = null; + this.token = null; + } + + + } diff --git a/src/main/java/com/openshift/internal/restclient/authorization/AuthorizationDetails.java b/src/main/java/com/openshift/internal/restclient/authorization/AuthorizationDetails.java index eff2781b..fd90f496 100644 --- a/src/main/java/com/openshift/internal/restclient/authorization/AuthorizationDetails.java +++ b/src/main/java/com/openshift/internal/restclient/authorization/AuthorizationDetails.java @@ -8,90 +8,92 @@ * Contributors: * Red Hat, Inc. - initial API and implementation ******************************************************************************/ + package com.openshift.internal.restclient.authorization; import java.util.regex.Matcher; import java.util.regex.Pattern; -import org.apache.http.Header; - import com.openshift.restclient.authorization.IAuthorizationDetails; -/** - * @author Jeff Cantrill - */ -public class AuthorizationDetails implements IAuthorizationDetails { +import okhttp3.Headers; - private static final String LINK = "Link"; - private static final String WARNING = "Warning"; - private static final String WWW_AUTHENTICATE = "WWW-Authenticate"; - - private static final Pattern LINK_RE = Pattern.compile(".*?((?:http|https)(?::\\/{2}[\\w]+)(?:[\\/|\\.]?)(?:[^\\s\"<>]*))",Pattern.CASE_INSENSITIVE | Pattern.DOTALL); - private static final Pattern WARNING_RE = Pattern.compile(".*?(\".*?\")",Pattern.CASE_INSENSITIVE | Pattern.DOTALL); - - private String message = ""; - private String link = ""; - private String scheme = ""; - - public AuthorizationDetails(String link) { - this.link = link; - } - - public AuthorizationDetails(String error, String errorDetails) { - this.message = "Unknown authorization error"; - if (error != null) { - this.message = error; - } - if (errorDetails != null) { - this.message = this.message + ": " + errorDetails; - } - } - - public AuthorizationDetails(Header[] headers) { - for (Header header : headers) { - final String name = header.getName(); - if(LINK.equalsIgnoreCase(name)) { - Matcher matcher = LINK_RE.matcher(header.getValue()); - if(matcher.find()) { - link = matcher.group(1); - } - }else if(WARNING.equalsIgnoreCase(name)) { - Matcher matcher = WARNING_RE.matcher(header.getValue()); - if(matcher.find()) { - message = matcher.group(1); - } - }else if(WWW_AUTHENTICATE.equalsIgnoreCase(name)) { - scheme = header.getValue(); - if(scheme.contains("realm")) { - scheme = scheme.split(" ")[0]; - } - } - } - } - - - @Override - public String getScheme() { - return scheme ; - } - - - - @Override - public String getMessage() { - return message; - } - - @Override - public String getRequestTokenLink() { - return link; - } - - - @Override - public String toString() { - return message; - } +public class AuthorizationDetails implements IAuthorizationDetails { + private static final String LINK = "Link"; + private static final String WARNING = "Warning"; + private static final String WWW_AUTHENTICATE = "WWW-Authenticate"; + + private static final Pattern LINK_RE = Pattern.compile( + ".*?((?:http|https)(?::\\/{2}[\\w]+)(?:[\\/|\\.]?)(?:[^\\s\"<>]*))", + Pattern.CASE_INSENSITIVE | Pattern.DOTALL); + private static final Pattern WARNING_RE = Pattern.compile(".*?(\".*?\")", + Pattern.CASE_INSENSITIVE | Pattern.DOTALL); + + private String message = ""; + private String link = ""; + private String scheme = ""; + + public AuthorizationDetails(String link) { + this.link = link; + } + + public AuthorizationDetails(String error, String errorDetails) { + this.message = "Unknown authorization error"; + if (error != null) { + this.message = error; + } + if (errorDetails != null) { + this.message = this.message + ": " + errorDetails; + } + } + + public AuthorizationDetails(Headers headers) { + for (String name : headers.names()) { + if (LINK.equalsIgnoreCase(name)) { + Matcher matcher = LINK_RE.matcher(headers.get(name)); + if (matcher.find()) { + link = matcher.group(1); + } + } else if (WARNING.equalsIgnoreCase(name)) { + Matcher matcher = WARNING_RE.matcher(headers.get(name)); + if (matcher.find()) { + message = matcher.group(1); + } + } else if (WWW_AUTHENTICATE.equalsIgnoreCase(name)) { + scheme = headers.get(name); + if (scheme.contains("realm")) { + scheme = scheme.split(" ")[0]; + } + } + } + } + + public AuthorizationDetails(Headers headers, String link) { + this(headers); + if (link != null) { + this.link = link; + } + } + + @Override + public String getScheme() { + return scheme; + } + + @Override + public String getMessage() { + return message; + } + + @Override + public String getRequestTokenLink() { + return link; + } + + @Override + public String toString() { + return message; + } } diff --git a/src/main/java/com/openshift/internal/restclient/authorization/OpenShiftAuthorizationRedirectStrategy.java b/src/main/java/com/openshift/internal/restclient/authorization/OpenShiftAuthorizationRedirectStrategy.java deleted file mode 100644 index 24731374..00000000 --- a/src/main/java/com/openshift/internal/restclient/authorization/OpenShiftAuthorizationRedirectStrategy.java +++ /dev/null @@ -1,95 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2015 Red Hat, Inc. Distributed under license by Red Hat, Inc. - * All rights reserved. This program is made available under the terms of the - * Eclipse Public License v1.0 which accompanies this distribution, and is - * available at http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: Red Hat, Inc. - ******************************************************************************/ -package com.openshift.internal.restclient.authorization; - -import java.net.URI; -import java.util.Map; - -import org.apache.http.Header; -import org.apache.http.HttpRequest; -import org.apache.http.HttpResponse; -import org.apache.http.HttpStatus; -import org.apache.http.ProtocolException; -import org.apache.http.impl.client.DefaultRedirectStrategy; -import org.apache.http.protocol.HttpContext; - -import com.openshift.internal.util.Assert; -import com.openshift.internal.util.URIUtils; -import com.openshift.restclient.IClient; -import com.openshift.restclient.authorization.IAuthorizationContext; -import com.openshift.restclient.authorization.IAuthorizationDetails; -import com.openshift.restclient.authorization.IAuthorizationStrategy; -import com.openshift.restclient.authorization.TokenAuthorizationStrategy; -import com.openshift.restclient.authorization.UnauthorizedException; - -/** - * OpenShift authorization redirect strategy to disable - * redirects once an access token is granted - * - * @author Jeff Cantrill - */ -public class OpenShiftAuthorizationRedirectStrategy extends DefaultRedirectStrategy{ - // access_token and expires_in fragment params are an OAuth token response - private static final String ACCESS_TOKEN = "access_token"; - private static final String EXPIRES = "expires_in"; - - // error and error_details query params are an OAuth error response - private static final String ERROR = "error"; - private static final String ERROR_DETAILS = "error_details"; - - private IAuthorizationContext authcontext; - private IClient client; - - public OpenShiftAuthorizationRedirectStrategy(IClient client) { - Assert.notNull(this.client = client); - } - - public IAuthorizationContext getAuthorizationContext() { - return authcontext; - } - - @Override - public boolean isRedirected(HttpRequest request, HttpResponse response, HttpContext context) throws ProtocolException { - // 401 response - if (response.getStatusLine().getStatusCode() == HttpStatus.SC_UNAUTHORIZED) { - IAuthorizationDetails details = new AuthorizationDetails(response.getAllHeaders()); - throw new UnauthorizedException(details); - } - - // 302 response - if (response.getStatusLine().getStatusCode() == HttpStatus.SC_MOVED_TEMPORARILY) { - Header locationHeader = response.getFirstHeader("Location"); - if (locationHeader == null) { - return false; - } - URI locationURI = createLocationURI(locationHeader.getValue()); - - // check access_token fragment param - Map pairs = URIUtils.splitFragment(locationURI); - if (pairs.containsKey(ACCESS_TOKEN)) { - final String token = pairs.get(ACCESS_TOKEN); - IAuthorizationStrategy strategy = client.getAuthorizationStrategy(); - client.setAuthorizationStrategy(new TokenAuthorizationStrategy(token)); - this.authcontext = new AuthorizationContext(token, pairs.get(EXPIRES), client.getCurrentUser(), IAuthorizationContext.AUTHSCHEME_BASIC); - client.setAuthorizationStrategy(strategy); - return false; - } - - // check error query param - Map queryParams = URIUtils.splitQuery(locationURI.getQuery()); - if (queryParams.containsKey(ERROR)) { - IAuthorizationDetails details = new AuthorizationDetails(queryParams.get(ERROR), queryParams.get(ERROR_DETAILS)); - throw new UnauthorizedException(details); - } - } - - return super.isRedirected(request, response, context); - } - -} \ No newline at end of file diff --git a/src/main/java/com/openshift/internal/restclient/authorization/OpenShiftCredentialsProvider.java b/src/main/java/com/openshift/internal/restclient/authorization/OpenShiftCredentialsProvider.java deleted file mode 100644 index a279981d..00000000 --- a/src/main/java/com/openshift/internal/restclient/authorization/OpenShiftCredentialsProvider.java +++ /dev/null @@ -1,77 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2015 Red Hat, Inc. Distributed under license by Red Hat, Inc. - * All rights reserved. This program is made available under the terms of the - * Eclipse Public License v1.0 which accompanies this distribution, and is - * available at http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: Red Hat, Inc. - initial API and implementation - ******************************************************************************/ -package com.openshift.internal.restclient.authorization; - -import java.util.HashMap; -import java.util.Map; - -import org.apache.http.auth.AuthScope; -import org.apache.http.auth.Credentials; -import org.apache.http.auth.UsernamePasswordCredentials; -import org.apache.http.client.CredentialsProvider; -import org.apache.http.impl.client.SystemDefaultCredentialsProvider; - -import com.openshift.restclient.authorization.BasicAuthorizationStrategy; -import com.openshift.restclient.authorization.IAuthorizationContext; -import com.openshift.restclient.authorization.IAuthorizationStrategyVisitor; -import com.openshift.restclient.authorization.TokenAuthorizationStrategy; - -public class OpenShiftCredentialsProvider implements CredentialsProvider, IAuthorizationStrategyVisitor{ - - private CredentialsProvider provider = new SystemDefaultCredentialsProvider(); - private Map creds = new HashMap(2); - private String token; - private String scheme; - - /** - * Get the token if known; - * @return - */ - public String getToken() { - return token; - } - - public String getScheme() { - return scheme; - } - - @Override - public void visit(BasicAuthorizationStrategy strategy) { - creds.put(IAuthorizationContext.AUTHSCHEME_BASIC.toLowerCase(), new UsernamePasswordCredentials(strategy.getUsername(), strategy.getPassword())); - scheme = IAuthorizationContext.AUTHSCHEME_BASIC; - token = strategy.getToken(); - } - - - @Override - public void visit(TokenAuthorizationStrategy strategy) { - this.scheme = IAuthorizationContext.AUTHSCHEME_OAUTH; - this.token = strategy.getToken(); - } - - @Override - public void setCredentials(AuthScope authscope, Credentials credentials) { - provider.setCredentials(authscope, credentials); - } - - @Override - public Credentials getCredentials(AuthScope authscope) { - final String scheme = authscope.getScheme().toLowerCase(); - if(creds.containsKey(scheme)){ - return creds.get(scheme); - } - return provider.getCredentials(authscope); - } - - @Override - public void clear() { - provider.clear(); - } - -} \ No newline at end of file diff --git a/src/main/java/com/openshift/internal/restclient/capability/AbstractCapability.java b/src/main/java/com/openshift/internal/restclient/capability/AbstractCapability.java new file mode 100644 index 00000000..4aeaa979 --- /dev/null +++ b/src/main/java/com/openshift/internal/restclient/capability/AbstractCapability.java @@ -0,0 +1,48 @@ +/******************************************************************************* + * Copyright (c) 2016 Red Hat, Inc. + * Distributed under license by Red Hat, Inc. All rights reserved. + * This program is made available under the terms of the + * Eclipse Public License v1.0 which accompanies this distribution, + * and is available at http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Red Hat, Inc. - initial API and implementation + ******************************************************************************/ + +package com.openshift.internal.restclient.capability; + +import com.openshift.restclient.IApiTypeMapper; +import com.openshift.restclient.IClient; +import com.openshift.restclient.UnsupportedEndpointException; +import com.openshift.restclient.capability.ICapability; +import com.openshift.restclient.model.IResource; + +/** + * Capability base + * + */ +public abstract class AbstractCapability implements ICapability { + + private IApiTypeMapper mapper; + private IResource resource; + private final String capability; + + protected AbstractCapability(IResource resource, IClient client, String capability) { + this.capability = capability; + this.resource = resource; + this.mapper = client.adapt(IApiTypeMapper.class); + } + + @Override + public boolean isSupported() { + if (mapper != null) { + try { + return mapper.getEndpointFor(resource.getApiVersion(), resource.getKind()).isSupported(capability); + } catch (UnsupportedEndpointException e) { + // endpoint not found for version/kind + } + } + return false; + } + +} diff --git a/src/main/java/com/openshift/internal/restclient/capability/CapabilityInitializer.java b/src/main/java/com/openshift/internal/restclient/capability/CapabilityInitializer.java index 5cf8712b..0b7fd498 100644 --- a/src/main/java/com/openshift/internal/restclient/capability/CapabilityInitializer.java +++ b/src/main/java/com/openshift/internal/restclient/capability/CapabilityInitializer.java @@ -1,44 +1,57 @@ /******************************************************************************* - * Copyright (c) 2015 Red Hat, Inc. Distributed under license by Red Hat, Inc. + * Copyright (c) 2015-2019 Red Hat, Inc. Distributed under license by Red Hat, Inc. * All rights reserved. This program is made available under the terms of the * Eclipse Public License v1.0 which accompanies this distribution, and is * available at http://www.eclipse.org/legal/epl-v10.html * * Contributors: Red Hat, Inc. ******************************************************************************/ + package com.openshift.internal.restclient.capability; import java.util.Map; +import com.openshift.internal.restclient.api.capabilities.PodExec; +import com.openshift.internal.restclient.api.capabilities.ScaleCapability; +import com.openshift.internal.restclient.apis.TypeMetaFactory; +import com.openshift.internal.restclient.capability.resources.BinaryBuildTrigger; import com.openshift.internal.restclient.capability.resources.BuildCanceller; import com.openshift.internal.restclient.capability.resources.BuildTrigger; import com.openshift.internal.restclient.capability.resources.ClientCapability; import com.openshift.internal.restclient.capability.resources.DeployCapability; import com.openshift.internal.restclient.capability.resources.DeploymentConfigTraceability; import com.openshift.internal.restclient.capability.resources.DeploymentTraceability; +import com.openshift.internal.restclient.capability.resources.DeploymentTrigger; import com.openshift.internal.restclient.capability.resources.ImageStreamImportCapability; import com.openshift.internal.restclient.capability.resources.OpenShiftBinaryPodLogRetrieval; import com.openshift.internal.restclient.capability.resources.OpenShiftBinaryPortForwarding; import com.openshift.internal.restclient.capability.resources.OpenShiftBinaryRSync; +import com.openshift.internal.restclient.capability.resources.PodLogRetrievalAsync; import com.openshift.internal.restclient.capability.resources.ProjectTemplateListCapability; import com.openshift.internal.restclient.capability.resources.ProjectTemplateProcessing; import com.openshift.internal.restclient.capability.resources.PropertyAccessCapability; import com.openshift.internal.restclient.capability.resources.TagCapability; import com.openshift.internal.restclient.capability.resources.TemplateTraceability; import com.openshift.internal.restclient.capability.resources.UpdateableCapability; +import com.openshift.internal.restclient.capability.server.Console; import com.openshift.internal.restclient.capability.server.ServerTemplateProcessing; import com.openshift.internal.restclient.model.Service; import com.openshift.internal.restclient.model.build.BuildConfigBuilder; import com.openshift.restclient.IClient; +import com.openshift.restclient.api.capabilities.IPodExec; +import com.openshift.restclient.api.capabilities.IScalable; import com.openshift.restclient.capability.ICapability; +import com.openshift.restclient.capability.resources.IBinaryBuildTriggerable; import com.openshift.restclient.capability.resources.IBuildCancelable; import com.openshift.restclient.capability.resources.IBuildTriggerable; import com.openshift.restclient.capability.resources.IClientCapability; import com.openshift.restclient.capability.resources.IDeployCapability; import com.openshift.restclient.capability.resources.IDeploymentConfigTraceability; import com.openshift.restclient.capability.resources.IDeploymentTraceability; +import com.openshift.restclient.capability.resources.IDeploymentTriggerable; import com.openshift.restclient.capability.resources.IImageStreamImportCapability; import com.openshift.restclient.capability.resources.IPodLogRetrieval; +import com.openshift.restclient.capability.resources.IPodLogRetrievalAsync; import com.openshift.restclient.capability.resources.IPortForwardable; import com.openshift.restclient.capability.resources.IProjectTemplateList; import com.openshift.restclient.capability.resources.IProjectTemplateProcessing; @@ -47,95 +60,117 @@ import com.openshift.restclient.capability.resources.ITags; import com.openshift.restclient.capability.resources.ITemplateTraceability; import com.openshift.restclient.capability.resources.IUpdatable; +import com.openshift.restclient.capability.server.IConsole; import com.openshift.restclient.capability.server.ITemplateProcessing; import com.openshift.restclient.model.IBuild; import com.openshift.restclient.model.IBuildConfig; import com.openshift.restclient.model.IDeploymentConfig; import com.openshift.restclient.model.IPod; import com.openshift.restclient.model.IProject; +import com.openshift.restclient.model.IReplicationController; import com.openshift.restclient.model.IResource; import com.openshift.restclient.model.build.IBuildConfigBuilder; /** - * Convenience class to initialize capabilies. Only adds entry - * to underlying map if the capability is supported + * Convenience class to initialize capabilies. Only adds entry to underlying map + * if the capability is supported * - * @author Jeff Cantrill */ public class CapabilityInitializer { - /** - * Registers the capability if it is supported - * @param capabilities - * @param capability - * @param impl - */ - private static void initializeCapability(Map, ICapability> capabilities, Class capability, ICapability impl){ - if(impl.isSupported()){ - capabilities.put(capability, impl); - } - } - - /** - * Initialize Build specific capabilities - * @param capabilities - * @param resource - */ - public static void initializeCapabilities(Map, ICapability> capabilities, IBuild build, IClient client){ - initializeCapability(capabilities, IBuildTriggerable.class, new BuildTrigger(build, client)); - initializeCapability(capabilities, IBuildCancelable.class, new BuildCanceller(build, client)); - } + private CapabilityInitializer() { + } + + /** + * Registers the capability if it is supported + * + */ + private static void initializeCapability(Map, ICapability> capabilities, + Class capability, ICapability impl) { + if (impl.isSupported()) { + capabilities.put(capability, impl); + } + } + + /** + * Initialize Build specific capabilities + * + */ + public static void initializeCapabilities(Map, ICapability> capabilities, IBuild build, + IClient client) { + initializeCapability(capabilities, IBuildTriggerable.class, new BuildTrigger(build, client)); + initializeCapability(capabilities, IBuildCancelable.class, new BuildCanceller(build, client)); + } + + /** + * Initialize BuildConfig specific capabilities + * + */ + public static void initializeCapabilities(Map, ICapability> capabilities, + IBuildConfig buildConfig, IClient client) { + initializeCapability(capabilities, IBuildTriggerable.class, new BuildTrigger(buildConfig, client)); + initializeCapability(capabilities, IBinaryBuildTriggerable.class, new BinaryBuildTrigger(buildConfig, client)); + } + + /** + * Initialize Pod specific capabilities + * + */ + public static void initializeCapabilities(Map, ICapability> capabilities, IPod pod, + IClient client) { + initializeCapability(capabilities, IPortForwardable.class, new OpenShiftBinaryPortForwarding(pod, client)); + initializeCapability(capabilities, IPodLogRetrieval.class, new OpenShiftBinaryPodLogRetrieval(pod, client)); + initializeCapability(capabilities, IPodLogRetrievalAsync.class, new PodLogRetrievalAsync(pod, client)); + initializeCapability(capabilities, IPodExec.class, new PodExec(pod, client)); + initializeCapability(capabilities, IRSyncable.class, new OpenShiftBinaryRSync(client)); + } + + /** + * Initialize Project specific capabilities + * + */ + public static void initializeCapabilities(Map, ICapability> capabilities, + IProject project, IClient client) { + initializeCapability(capabilities, IProjectTemplateProcessing.class, + new ProjectTemplateProcessing(project, client)); + initializeCapability(capabilities, IProjectTemplateList.class, + new ProjectTemplateListCapability(project, client)); + initializeCapability(capabilities, IImageStreamImportCapability.class, + new ImageStreamImportCapability(project, client)); + } + + public static void initializeCapabilities(Map, ICapability> capabilities, + Service service, IClient client) { + } + + public static void initializeCapabilities(Map, ICapability> capabilities, + IDeploymentConfig config, IClient client) { + initializeCapability(capabilities, IDeployCapability.class, new DeployCapability(config, client)); + initializeCapability(capabilities, IDeploymentTriggerable.class, + new DeploymentTrigger(config, client, new TypeMetaFactory())); + } - /** - * Initialize BuildConfig specific capabilities - * @param capabilities - * @param resource - */ - public static void initializeCapabilities(Map, ICapability> capabilities, IBuildConfig buildConfig, IClient client){ - initializeCapability(capabilities, IBuildTriggerable.class, new BuildTrigger(buildConfig, client)); - } - - /** - * Initialize Pod specific capabilities - * @param capabilities - * @param resource - */ - public static void initializeCapabilities(Map, ICapability> capabilities, IPod pod, IClient client){ - initializeCapability(capabilities, IPortForwardable.class, new OpenShiftBinaryPortForwarding(pod, client)); - initializeCapability(capabilities, IPodLogRetrieval.class, new OpenShiftBinaryPodLogRetrieval(pod, client)); - initializeCapability(capabilities, IRSyncable.class, new OpenShiftBinaryRSync(client)); - } + public static void initializeCapabilities(Map, ICapability> capabilities, + IReplicationController rc, IClient client) { + initializeCapability(capabilities, IScalable.class, new ScaleCapability(rc, client, new TypeMetaFactory())); + } - /** - * Initialize Project specific capabilities - * @param capabilities - * @param resource - */ - public static void initializeCapabilities(Map, ICapability> capabilities, IProject project, IClient client){ - initializeCapability(capabilities, IProjectTemplateProcessing.class, new ProjectTemplateProcessing(project, client)); - initializeCapability(capabilities, IProjectTemplateList.class, new ProjectTemplateListCapability(project, client)); - initializeCapability(capabilities, IImageStreamImportCapability.class, new ImageStreamImportCapability(project, client)); - } - - public static void initializeCapabilities(Map, ICapability> capabilities, Service service, IClient client){ - } - - public static void initializeCapabilities(Map, ICapability> capabilities, IDeploymentConfig config, IClient client){ - initializeCapability(capabilities, IDeployCapability.class, new DeployCapability(config, client)); - } + public static void initializeCapabilities(Map, ICapability> capabilities, + IResource resource, IClient client) { + initializeCapability(capabilities, ITemplateTraceability.class, new TemplateTraceability(resource)); + initializeCapability(capabilities, IDeploymentConfigTraceability.class, + new DeploymentConfigTraceability(resource, client)); + initializeCapability(capabilities, IDeploymentTraceability.class, new DeploymentTraceability(resource, client)); + initializeCapability(capabilities, ITags.class, new TagCapability(resource)); + initializeCapability(capabilities, IClientCapability.class, new ClientCapability(client)); + initializeCapability(capabilities, IUpdatable.class, new UpdateableCapability(resource)); + initializeCapability(capabilities, IPropertyAccessCapability.class, new PropertyAccessCapability(resource)); + } - public static void initializeCapabilities(Map, ICapability> capabilities, IResource resource, IClient client){ - initializeCapability(capabilities, ITemplateTraceability.class, new TemplateTraceability(resource)); - initializeCapability(capabilities, IDeploymentConfigTraceability.class, new DeploymentConfigTraceability(resource, client)); - initializeCapability(capabilities, IDeploymentTraceability.class, new DeploymentTraceability(resource, client)); - initializeCapability(capabilities, ITags.class, new TagCapability(resource)); - initializeCapability(capabilities, IClientCapability.class, new ClientCapability(client)); - initializeCapability(capabilities, IUpdatable.class, new UpdateableCapability(resource)); - initializeCapability(capabilities, IPropertyAccessCapability.class, new PropertyAccessCapability(resource)); - } - - public static void initializeClientCapabilities(Map, ICapability> capabilities, IClient client){ - initializeCapability(capabilities, ITemplateProcessing.class, new ServerTemplateProcessing(client)); - initializeCapability(capabilities, IBuildConfigBuilder.class, new BuildConfigBuilder(client)); - } + public static void initializeClientCapabilities(Map, ICapability> capabilities, + IClient client) { + initializeCapability(capabilities, ITemplateProcessing.class, new ServerTemplateProcessing(client)); + initializeCapability(capabilities, IBuildConfigBuilder.class, new BuildConfigBuilder(client)); + initializeCapability(capabilities, IConsole.class, new Console(client)); + } } diff --git a/src/main/java/com/openshift/internal/restclient/capability/resources/AbstractOpenShiftBinaryCapability.java b/src/main/java/com/openshift/internal/restclient/capability/resources/AbstractOpenShiftBinaryCapability.java index b383b985..f39afa56 100644 --- a/src/main/java/com/openshift/internal/restclient/capability/resources/AbstractOpenShiftBinaryCapability.java +++ b/src/main/java/com/openshift/internal/restclient/capability/resources/AbstractOpenShiftBinaryCapability.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2015 Red Hat, Inc. + * Copyright (c) 2015-2018 Red Hat, Inc. * Distributed under license by Red Hat, Inc. All rights reserved. * This program is made available under the terms of the * Eclipse Public License v1.0 which accompanies this distribution, @@ -8,10 +8,15 @@ * Contributors: * Red Hat, Inc. - initial API and implementation ******************************************************************************/ + package com.openshift.internal.restclient.capability.resources; +import java.io.File; import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.util.ArrayList; import java.util.Arrays; +import java.util.Collection; import java.util.List; import org.apache.commons.io.IOUtils; @@ -19,219 +24,247 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import com.openshift.internal.util.StringSplitter; import com.openshift.restclient.IClient; import com.openshift.restclient.OpenShiftContext; import com.openshift.restclient.OpenShiftException; -import com.openshift.restclient.authorization.BasicAuthorizationStrategy; -import com.openshift.restclient.authorization.IAuthorizationStrategyVisitor; -import com.openshift.restclient.authorization.TokenAuthorizationStrategy; import com.openshift.restclient.capability.IBinaryCapability; import com.openshift.restclient.capability.resources.LocationNotFoundException; +import com.openshift.restclient.model.IResource; /** * Capability that wraps the OpenShift binary * - * @author Jeff Cantrill - * */ public abstract class AbstractOpenShiftBinaryCapability implements IBinaryCapability { - - private static final Logger LOG = LoggerFactory.getLogger(AbstractOpenShiftBinaryCapability.class); - - private Process process; - - private IClient client; - - protected AbstractOpenShiftBinaryCapability(IClient client) { - this.client = client; - } - - /** - * Cleanup required when stopping the process - */ - protected abstract void cleanup(); - - /** - * Validate arguments before starting process - * @return true if start should continue; false otherwise; - */ - protected abstract boolean validate(); - - /** - * Callback for building args to be sent to the {@code oc} command. - * @return the String representation of all the arguments to use when running the {@code oc} command. - */ - protected abstract String buildArgs(final List options); - - protected IClient getClient() { - return client; - } - - protected AbstractOpenShiftBinaryCapability() { - addShutdownHook(); - } - - protected Process getProcess() { - return process; - } - - private void addShutdownHook() { - Runnable runnable = new Runnable() { - @Override - public void run() { - stop(); - } - }; - Runtime.getRuntime().addShutdownHook(new Thread(runnable)); - } - - protected String getUserFlag() { - final StringBuilder argBuilder = new StringBuilder(); - argBuilder.append("--user=").append(client.getCurrentUser().getName()).append(" "); - return argBuilder.toString(); - } - - /** - * @return - */ - protected String getServerFlag() { - final StringBuilder argBuilder = new StringBuilder(); - argBuilder.append("--server=").append(client.getBaseURL()).append(" "); - return argBuilder.toString(); - } - - /** - * Adds the authentication token - * @return the command-line argument to use the current token - */ - protected String getTokenFlag() { - final StringBuilder argBuilder = new StringBuilder(); - argBuilder.append("--token="); - client.getAuthorizationStrategy().accept(new IAuthorizationStrategyVisitor() { - - @Override - public void visit(TokenAuthorizationStrategy strategy) { - argBuilder.append(strategy.getToken()); - } - - @Override - public void visit(BasicAuthorizationStrategy strategy) { - argBuilder.append(strategy.getToken()); - } - }); - argBuilder.append(" "); - return argBuilder.toString(); - } - - /** - * @return the command-line flag to use insecure connection (skip TLS verification) - */ - protected String getSkipTlsVerifyFlag() { - return "--insecure-skip-tls-verify=true "; - } - - /** - * @return the command-line flag to exclude some files/directories that do - * not need to be synchronized between the remote pod and the local - * deployment directory. - */ - protected String getGitFolderExclusionFlag() { - // no support for multiple exclusion, so excluding '.git' only for now - // see https://github.com/openshift/origin/issues/8223 - return "--exclude='.git' "; - } - - /** - * @return the command-line flag to avoid transferring permissions. - */ - protected String getNoPermsFlags() { - return "--no-perms=true "; - } - - /** - * @return the command-line flag to delete extraneous file from destination directories. - */ - protected String getDeleteFlags() { - return "--delete "; - } - - /** - * Starts the {@link Process} to run the {@code oc} command. - * @param options the command line options - */ - public final void start(final OpenShiftBinaryOption... options) { - String location = getOpenShiftBinaryLocation(); - if(!validate()) { - return; - } - startProcess(location, options); - } - - private void startProcess(final String location, final OpenShiftBinaryOption... options) { - String cmdLine = new StringBuilder(location).append(' ').append(buildArgs(Arrays.asList(options))).toString(); - String[] args = StringUtils.split(cmdLine, " "); - ProcessBuilder builder = new ProcessBuilder(args); - LOG.debug("OpenShift binary args: {}", builder.command()); - try { - process = builder.start(); - checkProcessIsAlive(); - } catch (IOException e) { - LOG.error("Could not start process for {}.", new Object[]{ getName(), e }); - throw new OpenShiftException(e, "Does your OpenShift binary location exist? Error starting process: %s", - e.getMessage()); - } - } - - private void checkProcessIsAlive() throws IOException { - try { - // TODO: replace fixed wait with wait for process to be running - Thread.sleep(1000); - if(!process.isAlive() && process.exitValue() != 0) { - throw new OpenShiftException("OpenShiftBinaryCapability process exited: %s", - IOUtils.toString(process.getErrorStream())); - } - } catch (InterruptedException e) { - if(!process.isAlive() && process.exitValue() != 0) { - throw new OpenShiftException("OpenShiftBinaryCapability process exited: %s", - IOUtils.toString(process.getErrorStream())); - } - } - } - - /** - * Stops the {@link Process} running the {@code oc} command. - */ - public final synchronized void stop() { - if(process == null) return; - cleanup(); - if(!process.isAlive()) { - final int exitValue = process.exitValue(); - LOG.debug("OpenShiftBinaryCapability process exit code {}", exitValue); - if(exitValue != 0) { - try { - LOG.debug("OpenShiftBinaryCapability process error stream", IOUtils.toString(process.getErrorStream())); - } catch (IOException e) { - LOG.debug("IOException trying to debug the process error stream", e); - } - } - process = null; - return; - } - process.destroyForcibly(); - } - - protected String getOpenShiftBinaryLocation() { - //Check the ThreadLocal for oc binary - String location = OpenShiftContext.get().get(OPENSHIFT_BINARY_LOCATION); - if (StringUtils.isBlank(location)) { - //Fall back to System property - location = System.getProperty(OPENSHIFT_BINARY_LOCATION); - } - if(StringUtils.isBlank(location)) { - throw new LocationNotFoundException( - String.format("The OpenShift 'oc' binary location was not specified. Set the property %s", - OPENSHIFT_BINARY_LOCATION)); - } - return location; - } + + private static final Logger LOG = LoggerFactory.getLogger(AbstractOpenShiftBinaryCapability.class); + + private static final boolean IS_MAC = StringUtils.isNotEmpty(System.getProperty("os.name")) + && System.getProperty("os.name").toLowerCase().contains("mac"); + + static class Server implements OpenShiftBinaryOption { + + private IClient client; + + public Server(IClient client) { + this.client = client; + } + + @Override + public void append(StringBuilder commandLine) { + commandLine.append(" --server=").append(client.getBaseURL()).append(" "); + } + } + + static class Token implements OpenShiftBinaryOption { + + private IClient client; + + Token(IClient client) { + this.client = client; + } + + @Override + public void append(StringBuilder commandLine) { + commandLine.append(" --token=").append(client.getAuthorizationContext().getToken()); + } + } + + static class Namespace implements OpenShiftBinaryOption { + + private IResource resource; + + public Namespace(IResource resource) { + this.resource = resource; + } + + @Override + public void append(StringBuilder commandLine) { + if (resource == null) { + return; + } + commandLine.append(" -n ").append(resource.getNamespaceName()); + } + } + + protected static class CommandLineBuilder { + + private StringBuilder sb; + + public CommandLineBuilder(String command) { + this.sb = new StringBuilder(command); + } + + public CommandLineBuilder append(OpenShiftBinaryOption argument) { + if (argument != null) { + argument.append(sb); + } + return this; + } + + public CommandLineBuilder append(Collection arguments) { + if (arguments == null) { + return this; + } + + for (OpenShiftBinaryOption argument : arguments) { + append(argument); + } + return this; + } + + public String build() { + return sb.toString(); + } + } + + private Process process; + private IClient client; + + protected AbstractOpenShiftBinaryCapability(IClient client) { + this.client = client; + } + + /** + * Cleanup required when stopping the process + */ + protected abstract void cleanup(); + + /** + * Validate arguments before starting process + * + * @return true if start should continue; false otherwise; + */ + protected abstract boolean validate(); + + /** + * Callback for building args to be sent to the {@code oc} command. + * + * @return the String representation of all the arguments to use when running + * the {@code oc} command. + */ + protected abstract String buildArgs(final List options); + + protected IClient getClient() { + return client; + } + + protected AbstractOpenShiftBinaryCapability() { + addShutdownHook(); + } + + protected Process getProcess() { + return process; + } + + private void addShutdownHook() { + Runtime.getRuntime().addShutdownHook(new Thread(this::stop)); + } + + /** + * Starts the {@link Process} to run the {@code oc} command. + * + * @param arguments + * the command line options + */ + public final Process start(final OpenShiftBinaryOption... arguments) { + String location = getOpenShiftBinaryLocation(); + if (!validate()) { + return null; + } + ProcessBuilder processBuilder = initProcessBuilder(location, arguments); + return startProcess(processBuilder); + } + + protected Process startProcess(ProcessBuilder builder) { + try { + process = builder.start(); + checkProcessIsAlive(); + return process; + } catch (IOException e) { + LOG.error("Could not start process for {}.", new Object[] { getName(), e }); + throw new OpenShiftException(e, "Does your OpenShift binary location exist? Error starting process: %s", + e.getMessage()); + } + } + + private ProcessBuilder initProcessBuilder(String location, final OpenShiftBinaryOption... options) { + List args = new ArrayList<>(); + ProcessBuilder builder = null; + // the condition is made in order to solve mac problem + // with launching binaries containing spaces in its path + // https://issues.jboss.org/browse/JBIDE-23862 - see the latest comments + if (IS_MAC) { + args.add(location); + StringSplitter.split(buildArgs(Arrays.asList(options)), args); + builder = new ProcessBuilder(args); + } else { + args.add(location); + StringSplitter.split(buildArgs(Arrays.asList(options)), args); + File oc = new File(location); + builder = new ProcessBuilder(args); + builder.directory(oc.getParentFile()); + } + builder.environment().remove("KUBECONFIG"); + LOG.debug("OpenShift binary args: {}", builder.command()); + return builder; + } + + private void checkProcessIsAlive() throws IOException { + try { + // TODO: replace fixed wait with wait for process to be running + Thread.sleep(1000); + if (!process.isAlive() && process.exitValue() != 0) { + throw new OpenShiftException("OpenShiftBinaryCapability process exited: %s", + IOUtils.toString(process.getErrorStream(), StandardCharsets.UTF_8)); + } + } catch (InterruptedException e) { + if (!process.isAlive() && process.exitValue() != 0) { + throw new OpenShiftException("OpenShiftBinaryCapability process exited: %s", + IOUtils.toString(process.getErrorStream(), StandardCharsets.UTF_8)); + } + } + } + + /** + * Stops the {@link Process} running the {@code oc} command. + */ + public final synchronized void stop() { + if (process == null) { + return; + } + cleanup(); + if (!process.isAlive()) { + final int exitValue = process.exitValue(); + LOG.debug("OpenShiftBinaryCapability process exit code {}", exitValue); + if (exitValue != 0) { + try { + LOG.debug("OpenShiftBinaryCapability process error stream: {}", + IOUtils.toString(process.getErrorStream(), StandardCharsets.UTF_8)); + } catch (IOException e) { + LOG.debug("IOException trying to debug the process error stream", e); + } + } + process = null; + return; + } + process.destroyForcibly(); + } + + protected String getOpenShiftBinaryLocation() { + // Check the ThreadLocal for oc binary + String location = OpenShiftContext.get().get(OPENSHIFT_BINARY_LOCATION); + if (StringUtils.isBlank(location)) { + // Fall back to System property + location = System.getProperty(OPENSHIFT_BINARY_LOCATION); + } + if (StringUtils.isBlank(location)) { + throw new LocationNotFoundException( + String.format("The OpenShift 'oc' binary location was not specified. Set the property %s", + OPENSHIFT_BINARY_LOCATION)); + } + return location; + } + } diff --git a/src/main/java/com/openshift/internal/restclient/capability/resources/AnnotationCapability.java b/src/main/java/com/openshift/internal/restclient/capability/resources/AnnotationCapability.java index a364ebbf..782426e2 100644 --- a/src/main/java/com/openshift/internal/restclient/capability/resources/AnnotationCapability.java +++ b/src/main/java/com/openshift/internal/restclient/capability/resources/AnnotationCapability.java @@ -6,53 +6,51 @@ * * Contributors: Red Hat, Inc. ******************************************************************************/ + package com.openshift.internal.restclient.capability.resources; import com.openshift.restclient.capability.ICapability; import com.openshift.restclient.model.IResource; /** - * Determine if a resource has a capability if it - * has the given annotation + * Determine if a resource has a capability if it has the given annotation * - * @author Jeff Cantrill */ public abstract class AnnotationCapability implements ICapability { - private final IResource resource; - private final String name; - - public AnnotationCapability(String name, IResource resource) { - this.resource = resource; - this.name = name; - } - - @Override - public boolean isSupported() { - return resource.isAnnotatedWith(getAnnotationKey()); - } - - @Override - public String getName() { - return this.name; - } - - protected IResource getResource(){ - return this.resource; - } - - - /** - * The annotation key - * @return - */ - protected abstract String getAnnotationKey(); - - /** - * The annotations value - * @return - */ - public String getAnnotationValue(){ - return getResource().getAnnotation(getAnnotationKey()); - } + private final IResource resource; + private final String name; + + public AnnotationCapability(String name, IResource resource) { + this.resource = resource; + this.name = name; + } + + @Override + public boolean isSupported() { + return resource.isAnnotatedWith(getAnnotationKey()); + } + + @Override + public String getName() { + return this.name; + } + + protected IResource getResource() { + return this.resource; + } + + /** + * The annotation key + * + */ + protected abstract String getAnnotationKey(); + + /** + * The annotations value + * + */ + public String getAnnotationValue() { + return getResource().getAnnotation(getAnnotationKey()); + } } diff --git a/src/main/java/com/openshift/internal/restclient/capability/resources/AssociationCapability.java b/src/main/java/com/openshift/internal/restclient/capability/resources/AssociationCapability.java index 90d6c8b2..6741eaa9 100644 --- a/src/main/java/com/openshift/internal/restclient/capability/resources/AssociationCapability.java +++ b/src/main/java/com/openshift/internal/restclient/capability/resources/AssociationCapability.java @@ -6,46 +6,49 @@ * * Contributors: Red Hat, Inc. ******************************************************************************/ + package com.openshift.internal.restclient.capability.resources; import com.openshift.restclient.IClient; -import com.openshift.restclient.ResourceKind; import com.openshift.restclient.model.IResource; /** - * Retrieve the associated resource from the given - * resource's annotation + * Retrieve the associated resource from the given resource's annotation * - * @author Jeff Cantrill */ -public abstract class AssociationCapability extends AnnotationCapability{ - - private IClient client; - - public AssociationCapability(String name, IResource resource, IClient client) { - super(name, resource); - this.client = client; - } - - protected IClient getClient(){ - return client; - } - - @Override - public boolean isSupported() { - if(client == null) return false; - return super.isSupported(); - } - - /** - * Get the associated resource of the given kind using the - * name from the annotation key; - * @param kind - * @return - */ - protected T getAssociatedResource(String kind){ - if(!isSupported()) return null; - String name = getResource().getAnnotation(getAnnotationKey()); - return getClient().get(kind, name, getResource().getNamespace()); - } +public abstract class AssociationCapability extends AnnotationCapability { + + private IClient client; + + public AssociationCapability(String name, IResource resource, IClient client) { + super(name, resource); + this.client = client; + } + + protected IClient getClient() { + return client; + } + + @Override + public boolean isSupported() { + if (client == null) { + return false; + } + return super.isSupported(); + } + + /** + * Get the associated resource of the given kind using the name from the + * annotation key; + * + * @param kind The kind + * @return the resource + */ + protected T getAssociatedResource(String kind) { + if (!isSupported()) { + return null; + } + String name = getResource().getAnnotation(getAnnotationKey()); + return getClient().get(kind, name, getResource().getNamespaceName()); + } } diff --git a/src/main/java/com/openshift/internal/restclient/capability/resources/BinaryBuildTrigger.java b/src/main/java/com/openshift/internal/restclient/capability/resources/BinaryBuildTrigger.java new file mode 100644 index 00000000..25544dae --- /dev/null +++ b/src/main/java/com/openshift/internal/restclient/capability/resources/BinaryBuildTrigger.java @@ -0,0 +1,162 @@ +/******************************************************************************* + * Copyright (c) 2018 Red Hat, Inc. + * Distributed under license by Red Hat, Inc. All rights reserved. + * This program is made available under the terms of the + * Eclipse Public License v1.0 which accompanies this distribution, + * and is available at http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Red Hat, Inc. - initial API and implementation + ******************************************************************************/ + +package com.openshift.internal.restclient.capability.resources; + +import java.io.InputStream; +import java.util.HashMap; +import java.util.Map; + +import org.apache.commons.lang.StringUtils; + +import com.openshift.restclient.IClient; +import com.openshift.restclient.ResourceKind; +import com.openshift.restclient.capability.resources.IBinaryBuildTriggerable; +import com.openshift.restclient.model.IBuild; +import com.openshift.restclient.model.IBuildConfig; +import com.openshift.restclient.model.IResource; +import com.openshift.restclient.model.build.IBinaryBuildSource; + +public class BinaryBuildTrigger implements IBinaryBuildTriggerable { + + private static final String BUILDCONFIG_BINARY_SUBRESOURCE = "instantiatebinary"; + private static final String AS_FILE_PARAMETER = "asFile"; + private static final String AUTHOR_EMAIL_PARAMETER = "revision.authorEmail"; + private static final String AUTHOR_NAME_PARAMETER = "revision.authorName"; + private static final String COMMIT_PARAMETER = "revision.commit"; + private static final String COMMITTER_EMAIL_PARAMETER = "revision.committerEmail"; + private static final String COMMITTER_NAME_PARAMETER = "revision.committerName"; + private static final String MESSAGE_PARAMETER = "revision.message"; + private IResource resource; + private IClient client; + private final String subresource; + private String asFile; + private String authorEmail; + private String authorName; + private String commit; + private String committerEmail; + private String committerName; + private String message; + + public BinaryBuildTrigger(IBuildConfig buildConfig, IClient client) { + this.resource = buildConfig; + this.client = client; + this.subresource = BUILDCONFIG_BINARY_SUBRESOURCE; + } + + @Override + public boolean isSupported() { + return resource != null && client != null && ResourceKind.BUILD_CONFIG.equals(resource.getKind()) + && ((IBuildConfig) resource).getBuildSource() instanceof IBinaryBuildSource; + } + + @Override + public String getName() { + return BinaryBuildTrigger.class.getSimpleName(); + } + + @Override + public IBuild triggerBinary(InputStream payload) { + Map parameters = new HashMap<>(); + if (StringUtils.isNotBlank(asFile)) { + parameters.put(AS_FILE_PARAMETER, asFile); + } + if (StringUtils.isNotBlank(authorEmail)) { + parameters.put(AUTHOR_EMAIL_PARAMETER, authorEmail); + } + if (StringUtils.isNotBlank(authorName)) { + parameters.put(AUTHOR_NAME_PARAMETER, authorName); + } + if (StringUtils.isNotBlank(commit)) { + parameters.put(COMMIT_PARAMETER, commit); + } + if (StringUtils.isNotBlank(committerEmail)) { + parameters.put(COMMITTER_EMAIL_PARAMETER, committerEmail); + } + if (StringUtils.isNotBlank(committerName)) { + parameters.put(COMMITTER_NAME_PARAMETER, committerName); + } + if (StringUtils.isNotBlank(message)) { + parameters.put(MESSAGE_PARAMETER, message); + } + return client.create(resource.getKind(), resource.getApiVersion(), resource.getNamespaceName(), resource.getName(), subresource, payload, parameters); + } + + @Override + public void setAsFile(String asFile) { + this.asFile = asFile; + } + + @Override + public String getAsFile() { + return asFile; + } + + @Override + public void setCommit(String commit) { + this.commit = commit; + } + + @Override + public String getCommit() { + return commit; + } + + @Override + public void setAuthorEmail(String authorEmail) { + this.authorEmail = authorEmail; + } + + @Override + public String getAuthorEmail() { + return authorEmail; + } + + @Override + public void setAuthorName(String authorName) { + this.authorName = authorName; + } + + @Override + public String getAuthorName() { + return authorName; + } + + @Override + public void setCommitterEmail(String committerEmail) { + this.committerEmail = committerEmail; + } + + @Override + public String getCommitterEmail() { + return committerEmail; + } + + @Override + public void setCommitterName(String committerName) { + this.committerName = committerName; + } + + @Override + public String getCommitterName() { + return committerName; + } + + @Override + public void setMessage(String message) { + this.message = message; + } + + @Override + public String getMessage() { + return message; + } +} diff --git a/src/main/java/com/openshift/internal/restclient/capability/resources/BuildCanceller.java b/src/main/java/com/openshift/internal/restclient/capability/resources/BuildCanceller.java index 4192f756..18d62f2f 100644 --- a/src/main/java/com/openshift/internal/restclient/capability/resources/BuildCanceller.java +++ b/src/main/java/com/openshift/internal/restclient/capability/resources/BuildCanceller.java @@ -7,31 +7,31 @@ public class BuildCanceller implements IBuildCancelable { - private IBuild build; - private IClient client; - - public BuildCanceller(IBuild build, IClient client) { - this.build = build; - this.client = client; - } - - @Override - public boolean isSupported() { - return build != null && client != null && ResourceKind.BUILD.equals(build.getKind()); - } - - @Override - public String getName() { - return BuildCanceller.class.getSimpleName(); - } - - @Override - public IBuild cancel() { - boolean cancelled = build.cancel(); - if (cancelled) { - build = client.update(build); - } - return build; - } + private IBuild build; + private IClient client; + + public BuildCanceller(IBuild build, IClient client) { + this.build = build; + this.client = client; + } + + @Override + public boolean isSupported() { + return build != null && client != null && ResourceKind.BUILD.equals(build.getKind()); + } + + @Override + public String getName() { + return BuildCanceller.class.getSimpleName(); + } + + @Override + public IBuild cancel() { + boolean cancelled = build.cancel(); + if (cancelled) { + build = client.update(build); + } + return build; + } } diff --git a/src/main/java/com/openshift/internal/restclient/capability/resources/BuildTrigger.java b/src/main/java/com/openshift/internal/restclient/capability/resources/BuildTrigger.java index 6e6475b6..6b4a43d1 100644 --- a/src/main/java/com/openshift/internal/restclient/capability/resources/BuildTrigger.java +++ b/src/main/java/com/openshift/internal/restclient/capability/resources/BuildTrigger.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2015 Red Hat, Inc. + * Copyright (c) 2015-2018 Red Hat, Inc. * Distributed under license by Red Hat, Inc. All rights reserved. * This program is made available under the terms of the * Eclipse Public License v1.0 which accompanies this distribution, @@ -8,64 +8,111 @@ * Contributors: * Red Hat, Inc. - initial API and implementation ******************************************************************************/ + package com.openshift.internal.restclient.capability.resources; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; + +import org.apache.commons.lang.StringUtils; + import com.openshift.restclient.IClient; import com.openshift.restclient.ResourceKind; import com.openshift.restclient.capability.resources.IBuildTriggerable; import com.openshift.restclient.model.IBuild; import com.openshift.restclient.model.IBuildConfig; import com.openshift.restclient.model.IResource; +import com.openshift.restclient.model.build.IBinaryBuildSource; import com.openshift.restclient.model.build.IBuildRequest; -/** - * - * @author Jeff Cantrill - * - */ public class BuildTrigger implements IBuildTriggerable { - private static final String BUILDCONFIG_SUBRESOURCE = "instantiate"; - private static final String BUILD_SUBRESOURCE = "clone"; - private IResource resource; - private IClient client; - private final String subresource; - - public BuildTrigger(IBuildConfig buildConfig, IClient client) { - this.resource = buildConfig; - this.client = client; - this.subresource = BUILDCONFIG_SUBRESOURCE; - } - - public BuildTrigger(IBuild build, IClient client) { - this.resource = build; - this.client = client; - this.subresource = BUILD_SUBRESOURCE; - } - - @Override - public boolean isSupported() { - return resource != null && client != null && (ResourceKind.BUILD.equals(resource.getKind()) || ResourceKind.BUILD_CONFIG.equals(resource.getKind())); - } - - @Override - public String getName() { - return BuildTrigger.class.getSimpleName(); - } - - @Override - public IBuild trigger() { - IBuildRequest request = client.getResourceFactory().stub(ResourceKind.BUILD_REQUEST, resource.getName()); - return client.create(resource.getKind(), resource.getNamespace(), resource.getName(), subresource, request); - } - - @Override - public IBuild trigger(String commitId) { - IBuildRequest request = client.getResourceFactory().stub(ResourceKind.BUILD_REQUEST, resource.getName()); - request.setCommitId(commitId); - return client.create(resource.getKind(), resource.getNamespace(), resource.getName(), subresource, request); - } - - + private static final String BUILDCONFIG_SUBRESOURCE = "instantiate"; + private static final String BUILD_SUBRESOURCE = "clone"; + private IResource resource; + private IClient client; + private final String subresource; + private String commitId; + private List causes; + private HashMap envVars = new HashMap<>(); + + public BuildTrigger(IBuildConfig buildConfig, IClient client) { + this.resource = buildConfig; + this.client = client; + this.subresource = BUILDCONFIG_SUBRESOURCE; + this.causes = new ArrayList<>(); + } + + public BuildTrigger(IBuild build, IClient client) { + this.resource = build; + this.client = client; + this.subresource = BUILD_SUBRESOURCE; + this.causes = new ArrayList<>(); + } + + @Override + public boolean isSupported() { + return resource != null && client != null && (isSupportedBuild() || isSupportedBuildConfig()); + } + + private boolean isSupportedBuild() { + return ResourceKind.BUILD.equals(resource.getKind()) + && !(((IBuild) resource).getBuildSource() instanceof IBinaryBuildSource); + } + + private boolean isSupportedBuildConfig() { + return ResourceKind.BUILD_CONFIG.equals(resource.getKind()) + && !(((IBuildConfig) resource).getBuildSource() instanceof IBinaryBuildSource); + } + + @Override + public String getName() { + return BuildTrigger.class.getSimpleName(); + } + + @Override + public IBuild trigger() { + IBuildRequest request = client.getResourceFactory().stub(ResourceKind.BUILD_REQUEST, resource.getName()); + if (StringUtils.isNotEmpty(commitId)) { + request.setCommitId(commitId); + } + causes.forEach(request::addBuildCause); + envVars.forEach(request::setEnvironmentVariable); + return client.create(resource.getKind(), resource.getNamespaceName(), resource.getName(), subresource, request); + } + + @Override + @Deprecated + public IBuild trigger(String commitId) { + IBuildRequest request = client.getResourceFactory().stub(ResourceKind.BUILD_REQUEST, resource.getName()); + request.setCommitId(commitId); + return client.create(resource.getKind(), resource.getNamespaceName(), resource.getName(), subresource, request); + } + + @Override + public void setCommitId(String commitId) { + this.commitId = commitId; + } + + @Override + public String getCommitId() { + return commitId; + } + + @Override + public void addBuildCause(String cause) { + causes.add(cause); + } + + @Override + public List getBuildCauses() { + return new ArrayList<>(causes); + } + + @Override + public void setEnvironmentVariable(String name, String value) { + envVars.put(name, value); + } } diff --git a/src/main/java/com/openshift/internal/restclient/capability/resources/ClientCapability.java b/src/main/java/com/openshift/internal/restclient/capability/resources/ClientCapability.java index 28779c71..a76a4407 100644 --- a/src/main/java/com/openshift/internal/restclient/capability/resources/ClientCapability.java +++ b/src/main/java/com/openshift/internal/restclient/capability/resources/ClientCapability.java @@ -8,6 +8,7 @@ * Contributors: * Red Hat, Inc. - initial API and implementation ******************************************************************************/ + package com.openshift.internal.restclient.capability.resources; import com.openshift.restclient.IClient; @@ -15,29 +16,28 @@ /** * Implementation to retrieve the client from a resource - * @author Jeff Cantrill */ public class ClientCapability implements IClientCapability { - - private IClient client; - - public ClientCapability(IClient client) { - this.client = client; - } - - @Override - public boolean isSupported() { - return client != null; - } - - @Override - public String getName() { - return getClass().getSimpleName(); - } - - @Override - public IClient getClient() { - return client; - } + + private IClient client; + + public ClientCapability(IClient client) { + this.client = client; + } + + @Override + public boolean isSupported() { + return client != null; + } + + @Override + public String getName() { + return getClass().getSimpleName(); + } + + @Override + public IClient getClient() { + return client; + } } diff --git a/src/main/java/com/openshift/internal/restclient/capability/resources/DeployCapability.java b/src/main/java/com/openshift/internal/restclient/capability/resources/DeployCapability.java index 3294e2a1..b8be851a 100644 --- a/src/main/java/com/openshift/internal/restclient/capability/resources/DeployCapability.java +++ b/src/main/java/com/openshift/internal/restclient/capability/resources/DeployCapability.java @@ -8,8 +8,8 @@ * Contributors: * Red Hat, Inc. - initial API and implementation ******************************************************************************/ -package com.openshift.internal.restclient.capability.resources; +package com.openshift.internal.restclient.capability.resources; import java.util.Arrays; import java.util.List; @@ -18,7 +18,6 @@ import org.slf4j.LoggerFactory; import com.openshift.restclient.IClient; -import com.openshift.restclient.NotFoundException; import com.openshift.restclient.OpenShiftException; import com.openshift.restclient.ResourceKind; import com.openshift.restclient.capability.resources.IDeployCapability; @@ -26,65 +25,66 @@ import com.openshift.restclient.model.IDeploymentConfig; import com.openshift.restclient.model.IReplicationController; -public class DeployCapability implements IDeployCapability{ - - private static final List COMPLETED_STATES = Arrays.asList("Complete", "Failed"); - private static final Logger LOG = LoggerFactory.getLogger(IDeployCapability.class); - - - private final IClient client; - private final IDeploymentConfig config; - - public DeployCapability(IDeploymentConfig config, IClient client) { - this.config = config; - this.client = client; - - } - - @Override - public boolean isSupported() { - return true; - } - - @Override - public String getName() { - return DeployCapability.class.getSimpleName(); - } - - @Override - public void deploy() { - try { - final String deploymentName = getLatestDeploymentName(); - LOG.debug("Attempting to deploy latest deployment for config %s. Loading deployment: %s", config.getName(), deploymentName); - IReplicationController deployment = client.get(ResourceKind.REPLICATION_CONTROLLER, deploymentName, config.getNamespace()); - final String status = getStatusFor(deployment); - if(!COMPLETED_STATES.contains(status)) { - LOG.debug("Skipping deployment because deployment status %s for %s is not in %s", new Object [] {status, deploymentName, COMPLETED_STATES}); - return; - } - }catch(OpenShiftException e) { - if(e.getStatus() == null || e.getStatus().getCode() != IHttpConstants.STATUS_NOT_FOUND) { - //swallow exception like cli - throw e; - } - } - - //bumping as currently not supporting 'retry' - int version = config.getLatestVersionNumber(); - config.setLatestVersionNumber(++version); - client.update(config); - - } - - - private String getLatestDeploymentName() { - return String.format("%s-%d", config.getName(), config.getLatestVersionNumber()); - } - - private String getStatusFor(IReplicationController rc) { - if(rc.isAnnotatedWith(IReplicationController.DEPLOYMENT_PHASE)) { - return rc.getAnnotation(IReplicationController.DEPLOYMENT_PHASE); - } - return ""; - } +public class DeployCapability implements IDeployCapability { + + private static final List COMPLETED_STATES = Arrays.asList("Complete", "Failed"); + private static final Logger LOG = LoggerFactory.getLogger(DeployCapability.class); + + private final IClient client; + private final IDeploymentConfig config; + + public DeployCapability(IDeploymentConfig config, IClient client) { + this.config = config; + this.client = client; + + } + + @Override + public boolean isSupported() { + return true; + } + + @Override + public String getName() { + return DeployCapability.class.getSimpleName(); + } + + @Override + public void deploy() { + try { + final String deploymentName = getLatestDeploymentName(); + LOG.debug("Attempting to deploy latest deployment for config %s. Loading deployment: %s", config.getName(), + deploymentName); + IReplicationController deployment = client.get(ResourceKind.REPLICATION_CONTROLLER, deploymentName, + config.getNamespaceName()); + final String status = getStatusFor(deployment); + if (!COMPLETED_STATES.contains(status)) { + LOG.debug("Skipping deployment because deployment status %s for %s is not in %s", + new Object[] { status, deploymentName, COMPLETED_STATES }); + return; + } + } catch (OpenShiftException e) { + if (e.getStatus() == null || e.getStatus().getCode() != IHttpConstants.STATUS_NOT_FOUND) { + // swallow exception like cli + throw e; + } + } + + // bumping as currently not supporting 'retry' + int version = config.getLatestVersionNumber(); + config.setLatestVersionNumber(++version); + client.update(config); + + } + + private String getLatestDeploymentName() { + return String.format("%s-%d", config.getName(), config.getLatestVersionNumber()); + } + + private String getStatusFor(IReplicationController rc) { + if (rc.isAnnotatedWith(IReplicationController.DEPLOYMENT_PHASE)) { + return rc.getAnnotation(IReplicationController.DEPLOYMENT_PHASE); + } + return ""; + } } diff --git a/src/main/java/com/openshift/internal/restclient/capability/resources/DeploymentConfigTraceability.java b/src/main/java/com/openshift/internal/restclient/capability/resources/DeploymentConfigTraceability.java index f7b0c630..7861be65 100644 --- a/src/main/java/com/openshift/internal/restclient/capability/resources/DeploymentConfigTraceability.java +++ b/src/main/java/com/openshift/internal/restclient/capability/resources/DeploymentConfigTraceability.java @@ -6,6 +6,7 @@ * * Contributors: Red Hat, Inc. ******************************************************************************/ + package com.openshift.internal.restclient.capability.resources; import com.openshift.restclient.IClient; @@ -15,25 +16,23 @@ import com.openshift.restclient.model.IResource; /** - * Capability for a resource to determine - * to which deploymentconfig it is associated - * - * @author Jeff Cantrill + * Capability for a resource to determine to which deploymentconfig it is + * associated */ public class DeploymentConfigTraceability extends AssociationCapability implements IDeploymentConfigTraceability { - public DeploymentConfigTraceability(IResource resource, IClient client) { - super(DeploymentConfigTraceability.class.getSimpleName(), resource, client); - } + public DeploymentConfigTraceability(IResource resource, IClient client) { + super(DeploymentConfigTraceability.class.getSimpleName(), resource, client); + } - @Override - public IDeploymentConfig getDeploymentConfig() { - return getAssociatedResource(ResourceKind.DEPLOYMENT_CONFIG); - } + @Override + public IDeploymentConfig getDeploymentConfig() { + return getAssociatedResource(ResourceKind.DEPLOYMENT_CONFIG); + } - @Override - protected String getAnnotationKey() { - return "deploymentconfig"; - } + @Override + protected String getAnnotationKey() { + return "deploymentconfig"; + } } diff --git a/src/main/java/com/openshift/internal/restclient/capability/resources/DeploymentTraceability.java b/src/main/java/com/openshift/internal/restclient/capability/resources/DeploymentTraceability.java index 9fe28294..eeca998f 100644 --- a/src/main/java/com/openshift/internal/restclient/capability/resources/DeploymentTraceability.java +++ b/src/main/java/com/openshift/internal/restclient/capability/resources/DeploymentTraceability.java @@ -6,6 +6,7 @@ * * Contributors: Red Hat, Inc. ******************************************************************************/ + package com.openshift.internal.restclient.capability.resources; import com.openshift.restclient.IClient; @@ -15,28 +16,25 @@ import com.openshift.restclient.model.IResource; /** - * Determine which deployment caused a resource to - * be deployed based on the information found in its - * annotations - * - * @author Jeff Cantrill + * Determine which deployment caused a resource to be deployed based on the + * information found in its annotations */ public class DeploymentTraceability extends AssociationCapability implements IDeploymentTraceability { - - private static final String DEPLOYMENT_ANNOTATION = "deployment"; - - public DeploymentTraceability(IResource resource, IClient client) { - super(DeploymentTraceability.class.getSimpleName(), resource, client); - } - - @Override - public IReplicationController getDeployment() { - return getAssociatedResource(ResourceKind.REPLICATION_CONTROLLER); - } - - @Override - protected String getAnnotationKey() { - return DEPLOYMENT_ANNOTATION; - } + + private static final String DEPLOYMENT_ANNOTATION = "deployment"; + + public DeploymentTraceability(IResource resource, IClient client) { + super(DeploymentTraceability.class.getSimpleName(), resource, client); + } + + @Override + public IReplicationController getDeployment() { + return getAssociatedResource(ResourceKind.REPLICATION_CONTROLLER); + } + + @Override + protected String getAnnotationKey() { + return DEPLOYMENT_ANNOTATION; + } } diff --git a/src/main/java/com/openshift/internal/restclient/capability/resources/DeploymentTrigger.java b/src/main/java/com/openshift/internal/restclient/capability/resources/DeploymentTrigger.java new file mode 100644 index 00000000..2a12091f --- /dev/null +++ b/src/main/java/com/openshift/internal/restclient/capability/resources/DeploymentTrigger.java @@ -0,0 +1,108 @@ +/******************************************************************************* + * Copyright (c) 2016 Red Hat, Inc. + * Distributed under license by Red Hat, Inc. All rights reserved. + * This program is made available under the terms of the + * Eclipse Public License v1.0 which accompanies this distribution, + * and is available at http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Red Hat, Inc. - initial API and implementation + ******************************************************************************/ + +package com.openshift.internal.restclient.capability.resources; + +import java.util.Collections; +import java.util.Optional; + +import com.openshift.internal.restclient.capability.AbstractCapability; +import com.openshift.restclient.IClient; +import com.openshift.restclient.ResourceKind; +import com.openshift.restclient.api.ITypeFactory; +import com.openshift.restclient.capability.resources.IDeployCapability; +import com.openshift.restclient.capability.resources.IDeploymentTriggerable; +import com.openshift.restclient.http.IHttpConstants; +import com.openshift.restclient.model.IDeploymentConfig; +import com.openshift.restclient.model.deploy.IDeploymentRequest; + +/** + * + * @author Gabe Montero + * + */ +public class DeploymentTrigger extends AbstractCapability implements IDeploymentTriggerable { + private static final String DEPLOYMENT_ENDPOINT = "instantiate"; + private static final String DEPLOYMENT_REQUEST = "DeploymentRequest"; + + private IClient client; + private IDeploymentConfig config; + private ITypeFactory factory; + private boolean latest; + private boolean force; + private String resourceName; + + public DeploymentTrigger(IDeploymentConfig resource, IClient client, ITypeFactory factory) { + super(resource, client, DEPLOYMENT_ENDPOINT); + this.client = client; + this.config = resource; + this.factory = factory; + } + + @Override + public String getName() { + return DeploymentTrigger.class.getSimpleName(); + } + + @Override + public boolean isSupported() { + return true; + } + + @Override + public IDeploymentConfig trigger() { + if (super.isSupported()) { + IDeploymentRequest request = (IDeploymentRequest) factory.stubKind(DEPLOYMENT_REQUEST, + Optional.of(config.getName()), Optional.empty()); + request.setForce(force); + request.setLatest(latest); + request.setName(resourceName); + return client.execute(client.getResourceFactory(), IHttpConstants.POST, + config.getKind(), config.getNamespaceName(), config.getName(), DEPLOYMENT_ENDPOINT, null, request, + Collections.emptyMap()); + } else { + IDeployCapability deployer = config.getCapability(IDeployCapability.class); + deployer.deploy(); + return client.get(ResourceKind.DEPLOYMENT_CONFIG, config.getName(), config.getNamespaceName()); + } + } + + @Override + public void setLatest(boolean latest) { + this.latest = latest; + } + + @Override + public boolean isLatest() { + return latest; + } + + @Override + public void setForce(boolean force) { + this.force = force; + } + + @Override + public boolean isForce() { + return force; + } + + @Override + public void setResourceName(String name) { + this.resourceName = name; + } + + @Override + public String getResourceName() { + return resourceName; + } + +} diff --git a/src/main/java/com/openshift/internal/restclient/capability/resources/DockerRegistryImageStreamImportCapability.java b/src/main/java/com/openshift/internal/restclient/capability/resources/DockerRegistryImageStreamImportCapability.java index cc291f19..91d19528 100644 --- a/src/main/java/com/openshift/internal/restclient/capability/resources/DockerRegistryImageStreamImportCapability.java +++ b/src/main/java/com/openshift/internal/restclient/capability/resources/DockerRegistryImageStreamImportCapability.java @@ -8,8 +8,10 @@ * Contributors: * Red Hat, Inc. - initial API and implementation ******************************************************************************/ + package com.openshift.internal.restclient.capability.resources; +import java.io.IOException; import java.util.Comparator; import java.util.HashMap; import java.util.List; @@ -18,11 +20,6 @@ import java.util.stream.Collectors; import org.apache.commons.lang.StringUtils; -import org.eclipse.jetty.client.HttpClient; -import org.eclipse.jetty.client.api.ContentResponse; -import org.eclipse.jetty.client.api.Request; -import org.eclipse.jetty.http.HttpHeader; -import org.eclipse.jetty.util.ssl.SslContextFactory; import org.jboss.dmr.ModelNode; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -30,7 +27,9 @@ import com.openshift.internal.restclient.model.ModelNodeBuilder; import com.openshift.internal.restclient.model.image.ImageStreamImport; import com.openshift.internal.restclient.model.properties.ResourcePropertyKeys; +import com.openshift.internal.restclient.okhttp.ResponseCodeInterceptor; import com.openshift.internal.util.JBossDmrExtentions; +import com.openshift.restclient.IClient; import com.openshift.restclient.IResourceFactory; import com.openshift.restclient.ResourceKind; import com.openshift.restclient.capability.resources.IImageStreamImportCapability; @@ -39,247 +38,274 @@ import com.openshift.restclient.model.IProject; import com.openshift.restclient.model.image.IImageStreamImport; +import okhttp3.HttpUrl; +import okhttp3.OkHttpClient; +import okhttp3.Request; +import okhttp3.Response; +import okhttp3.ResponseBody; + /** * Retrieve metadata directly from docker. - * @author jeff.cantrill - * */ -public class DockerRegistryImageStreamImportCapability implements IImageStreamImportCapability, IHttpConstants, ResourcePropertyKeys { - - private static final String TOKEN = "token"; - private static final String STATUS_STATUS = "status.status"; - private static final int TIMEOUT = 10 * 1000; //10 seconds - private static final String ID = "id"; - private static final String PARENT = "parent"; - private static final String REALM = "realm"; - private static final Logger LOG = LoggerFactory.getLogger(IImageStreamImportCapability.class); - private static final String DEFAULT_DOCKER_REGISTRY = "https://registry-1.docker.io/v2"; - private IResourceFactory factory; - private IProject project; - - public DockerRegistryImageStreamImportCapability(IProject project, IResourceFactory factory) { - this.factory = factory; - this.project = project; - } - - @Override - public boolean isSupported() { - return true; - } - - @Override - public String getName() { - return DockerRegistryImageStreamImportCapability.class.getSimpleName(); - } - - private boolean registryExists(HttpClient client) throws Exception{ - ContentResponse response = client.newRequest(DEFAULT_DOCKER_REGISTRY).send(); - if(response == null) return false; - return (response.getStatus() == STATUS_UNAUTHORIZED || response.getStatus() == STATUS_OK); - } - - /** - * @return the token required to pull docker metadata - */ - private String retrieveAuthToken(HttpClient client, String details) throws Exception { - if(StringUtils.isNotBlank(details)) { - Map auth = parseAuthDetails(details); - if(auth.containsKey(REALM)) { - Request request = createAuthRequest(client, auth); - ContentResponse response = request.send(); - LOG.debug("Auth response: " + response.toString()); - if(response.getStatus() == STATUS_OK && response.getHeaders().contains(PROPERTY_CONTENT_TYPE, MEDIATYPE_APPLICATION_JSON)) { - ModelNode tokenNode = ModelNode.fromJSONString(response.getContentAsString()); - if(tokenNode.hasDefined(TOKEN)) { - return tokenNode.get(TOKEN).asString(); - }else { - LOG.debug("No auth token was found on auth response: " + tokenNode.toJSONString(false)); - } - } else { - LOG.info("Unable to retrieve authentication token as response was not OK and/or unexpected content type"); - } - }else { - LOG.info("Unable to retrieve authentication token - 'realm' was not found in the authenticate header: " + auth.toString()); - } - } - return null; - } - - private Request createAuthRequest(HttpClient client, Map authParams) { - Request request = client.newRequest(StringUtils.strip(authParams.get(REALM),"\"")); - for (Entry e: authParams.entrySet()) { - if(!REALM.equals(e.getKey())) { - request.param(StringUtils.strip(e.getKey(),"\""), StringUtils.strip(e.getValue(),"\"")); - } - } - LOG.debug("Auth request uri: " + request.getURI()); - return request; - } - - private Map parseAuthDetails(String auth){ - LOG.debug("Auth details header: " + auth); - Map map = new HashMap<>(); - String [] authAndValues = auth.split(" "); - if(authAndValues.length == 2 && AUTHORIZATION_BEARER.equals(authAndValues[0])) { - String [] params = authAndValues[1].split(","); - for (String p : params) { - String[] knv = p.split("="); - if(knv.length >= 2 ) { - map.put(knv[0], knv[1]); - } - } - } - return map; - } - - private DockerResponse retrieveMetaData(HttpClient client, String token, DockerImageURI uri) throws Exception { - String regUri = String.format("%s/%s/%s/manifests/%s", - DEFAULT_DOCKER_REGISTRY, - StringUtils.defaultIfBlank(uri.getUserName(),"library"), - uri.getName(), - uri.getTag()); - Request request = client.newRequest(regUri); - if(token != null) { - request.header(PROPERTY_AUTHORIZATION, String.format("%s %s", AUTHORIZATION_BEARER, token)); - - } - LOG.debug("retrieveMetaData uri: " + regUri); - ContentResponse response = request.send(); - LOG.debug("retrieveMetaData response: " + response.toString()); - switch(response.getStatus()) { - case STATUS_OK: - return new DockerResponse(DockerResponse.DATA, response.getContentAsString()); - case STATUS_UNAUTHORIZED: - return new DockerResponse(DockerResponse.AUTH, response.getHeaders().get(HttpHeader.WWW_AUTHENTICATE)); - } - LOG.info("Unable to retrieve docker meta data: " + response.toString()); - return null; - } - - private static class DockerResponse { - public static final String DATA = "data"; - public static final String AUTH = "auth"; - String responseType; - String data; - DockerResponse(String responseType, String data){ - this.responseType = responseType; - this.data = data; - } - public Object getResponseType() { - return responseType; - } - public String getData() { - return data; - } - } - - @Override - public IImageStreamImport importImageMetadata(DockerImageURI uri) { - - HttpClient client = null; - try { - SslContextFactory sslFactory = new SslContextFactory(true); - client = new HttpClient(sslFactory); - client.setConnectTimeout(TIMEOUT); - client.start(); - if(registryExists(client)) { - String token = null; - DockerResponse response = retrieveMetaData(client, token, uri); - if(DockerResponse.AUTH.equals(response.getResponseType())){ - LOG.debug("Unauthorized. Trying to retrieve token..."); - token = retrieveAuthToken(client, response.getData()); - response = retrieveMetaData(client, token, uri); - } - if(DockerResponse.DATA.equals(response.getResponseType())) { - String meta = response.getData(); - LOG.debug("Raw Docker image metadata: " + meta); - return buildResponse(meta, uri); - }else { - LOG.info("Unable to retrieve image metadata from docker registry"); - return buildErrorResponse(uri); - } - } - } catch (Exception e) { - LOG.error("Exception while trying to retrieve image metadata from docker", e); - }finally { - try { - if(client != null) { - client.stop(); - } - } catch (Exception e) { - LOG.warn("Exception while trying to stop http client", e); - } - } - return buildErrorResponse(uri); - } - - private IImageStreamImport buildErrorResponse(DockerImageURI uri) { - ModelNodeBuilder builder = new ModelNodeBuilder() - .set(STATUS_STATUS, "Failure") - .set("status.message", String.format("you may not have access to the Docker image \"%s\"", uri.getUriWithoutHost())) - .set("status.reason", "Unauthorized") - .set("status.code", IHttpConstants.STATUS_UNAUTHORIZED); - - return buildImageStreamImport(uri, builder.build()); - } - - private IImageStreamImport buildResponse(String meta, DockerImageURI uri) { - ModelNode raw = ModelNode.fromJSONString(meta); - ModelNode last = findNewestHistoryEntry(raw); - ModelNode containerConfig = last.remove("container_config"); - last.get("ContainerConfig").set(containerConfig); - - ModelNodeBuilder builder = new ModelNodeBuilder() - .set(STATUS_STATUS, "Success") - .set("tag", uri.getTag()) - .set("image.metadata.name", uri.getName()) - .set(ImageStreamImport.IMAGE_DOCKER_IMAGE_REFERENCE,uri.getUriUserNameAndName()) - .set("image.dockerImageMetadata", last); - - return buildImageStreamImport(uri, builder.build()); - } - - private ImageStreamImport buildImageStreamImport(DockerImageURI uri, ModelNode node) { - ImageStreamImport isImport = (ImageStreamImport) factory.stub(ResourceKind.IMAGE_STREAM_IMPORT, uri.getName(), this.project.getName()); - ModelNode root = isImport.getNode(); - ModelNode images = JBossDmrExtentions.get(root,null, ImageStreamImport.STATUS_IMAGES); - images.add(node); - - return isImport; - } - - private ModelNode findNewestHistoryEntry(ModelNode root) { - ModelNode history = root.get("history"); - List entries = history.asList().stream().map(n->ModelNode.fromJSONString(n.get("v1Compatibility").asString())).collect(Collectors.toList()); - entries.sort(new Comparator() { - - @Override - public int compare(ModelNode one, ModelNode two) { - String parent1 = one.has(PARENT ) ? one.get(PARENT).asString() : null; - String parent2 = two.has(PARENT ) ? one.get(PARENT).asString() : null; - if(parent1 == null && parent2 != null) { - return -1; - }else if(parent1 != null && parent2 == null) { - return 1; - }else if(parent1 == null && parent2 == null) { - return 0; //we should never get here - } - String id1 = one.get(ID).asString(); - String id2 = two.get(ID).asString(); - - if(parent2.equals(id1)) { - return -1; - }else if(parent1.equals(id2)) { - return 1; - } - - return 0; //we should never get here - } - }); - - ModelNode last = entries.get(0); - LOG.debug("newest history: " + last.toJSONString(false)); - return last; - } +public class DockerRegistryImageStreamImportCapability + implements IImageStreamImportCapability, IHttpConstants, ResourcePropertyKeys { + + private static final String TOKEN = "token"; + private static final String STATUS_STATUS = "status.status"; + private static final String ID = "id"; + private static final String PARENT = "parent"; + private static final String REALM = "realm"; + private static final Logger LOG = LoggerFactory.getLogger(IImageStreamImportCapability.class); + private static final String DEFAULT_DOCKER_REGISTRY = "https://registry-1.docker.io/v2"; + private IResourceFactory factory; + private IProject project; + private OkHttpClient okClient; + + public DockerRegistryImageStreamImportCapability(IProject project, IResourceFactory factory, IClient client) { + this.factory = factory; + this.project = project; + this.okClient = client.adapt(OkHttpClient.class); + if (okClient != null) { + okClient = okClient.newBuilder().followRedirects(true).build(); + } + } + + @Override + public boolean isSupported() { + return true; + } + + @Override + public String getName() { + return DockerRegistryImageStreamImportCapability.class.getSimpleName(); + } + + private boolean registryExists(OkHttpClient client) throws Exception { + Request req = new Request.Builder().url(DEFAULT_DOCKER_REGISTRY) + .header(ResponseCodeInterceptor.X_OPENSHIFT_IGNORE_RCI, "true").build(); + try (Response response = client.newCall(req).execute()) { + if (response == null) { + return false; + } + return (response.code() == STATUS_UNAUTHORIZED || response.code() == STATUS_OK); + } + } + + /** + * @return the token required to pull docker metadata + */ + private String retrieveAuthToken(OkHttpClient client, String details) throws Exception { + if (StringUtils.isNotBlank(details)) { + Map auth = parseAuthDetails(details); + if (auth.containsKey(REALM)) { + Request request = createAuthRequest(auth); + return retrieveAuthToken(client, request); + } else { + LOG.info("Unable to retrieve authentication token - 'realm' was not found in the authenticate header: {}", + auth.toString()); + } + } + return null; + } + + private String retrieveAuthToken(OkHttpClient client, Request request) throws IOException { + String token = null; + try (Response response = client.newCall(request).execute(); + ResponseBody responseBody = response.body()) { + LOG.debug("Auth response: {}", responseBody.string()); + if (response.code() == STATUS_OK + && MEDIATYPE_APPLICATION_JSON.equals(response.headers().get(PROPERTY_CONTENT_TYPE))) { + ModelNode tokenNode = ModelNode.fromJSONString(responseBody.string()); + if (tokenNode.hasDefined(TOKEN)) { + token = tokenNode.get(TOKEN).asString(); + } else { + LOG.debug("No auth token was found on auth response: {}", tokenNode.toJSONString(false)); + } + } else { + LOG.info( + "Unable to retrieve authentication token as response was not OK and/or unexpected content type"); + } + } + return token; + } + + private Request createAuthRequest(Map authParams) { + HttpUrl.Builder builder = HttpUrl.parse(StringUtils.strip(authParams.get(REALM), "\"")).newBuilder(); + for (Entry e : authParams.entrySet()) { + if (!REALM.equals(e.getKey())) { + builder.addQueryParameter(StringUtils.strip(e.getKey(), "\""), StringUtils.strip(e.getValue(), "\"")); + } + } + Request request = new Request.Builder().url(builder.build()) + .header(ResponseCodeInterceptor.X_OPENSHIFT_IGNORE_RCI, "true").build(); + LOG.debug("Auth request uri: {}", request.url()); + return request; + } + + private Map parseAuthDetails(String auth) { + LOG.debug("Auth details header: {}", auth); + Map map = new HashMap<>(); + String[] authAndValues = auth.split(" "); + if (authAndValues.length == 2 && AUTHORIZATION_BEARER.equals(authAndValues[0])) { + String[] params = authAndValues[1].split(","); + for (String p : params) { + String[] knv = p.split("="); + if (knv.length >= 2) { + map.put(knv[0], knv[1]); + } + } + } + return map; + } + + private DockerResponse retrieveMetaData(OkHttpClient client, String token, DockerImageURI uri) throws Exception { + String regUri = String.format("%s/%s/%s/manifests/%s", DEFAULT_DOCKER_REGISTRY, + StringUtils.defaultIfBlank(uri.getUserName(), "library"), uri.getName(), uri.getTag()); + Request.Builder builder = new Request.Builder().url(regUri) + .header(ResponseCodeInterceptor.X_OPENSHIFT_IGNORE_RCI, "true"); + if (token != null) { + builder.header(PROPERTY_AUTHORIZATION, String.format("%s %s", AUTHORIZATION_BEARER, token)); + + } + LOG.debug("retrieveMetaData uri: {}", regUri); + try (Response response = client.newCall(builder.build()).execute(); + ResponseBody responseBody = response.body()) { + LOG.debug("retrieveMetaData response: {}", responseBody.string()); + switch (response.code()) { + case STATUS_OK: + return new DockerResponse(DockerResponse.DATA, responseBody.string()); + case STATUS_UNAUTHORIZED: + return new DockerResponse(DockerResponse.AUTH, + response.headers().get(IHttpConstants.PROPERTY_WWW_AUTHENTICATE)); + default: + LOG.info("Unable to retrieve docker meta data: {}", responseBody.string()); + return null; + } + } + } + + private static class DockerResponse { + public static final String DATA = "data"; + public static final String AUTH = "auth"; + String responseType; + String data; + + DockerResponse(String responseType, String data) { + this.responseType = responseType; + this.data = data; + } + + public Object getResponseType() { + return responseType; + } + + public String getData() { + return data; + } + } + + @Override + public IImageStreamImport importImageMetadata(DockerImageURI uri) { + if (okClient != null) { + try { + if (registryExists(okClient)) { + String token = null; + DockerResponse response = retrieveMetaData(okClient, token, uri); + if (DockerResponse.AUTH.equals(response.getResponseType())) { + LOG.debug("Unauthorized. Trying to retrieve token..."); + token = retrieveAuthToken(okClient, response.getData()); + response = retrieveMetaData(okClient, token, uri); + } + if (DockerResponse.DATA.equals(response.getResponseType())) { + String meta = response.getData(); + LOG.debug("Raw Docker image metadata: " + meta); + return buildResponse(meta, uri); + } else { + LOG.info("Unable to retrieve image metadata from docker registry"); + return buildErrorResponse(uri); + } + } + } catch (Exception e) { + LOG.error("Exception while trying to retrieve image metadata from docker", e); + } + } + return buildErrorResponse(uri); + } + + private IImageStreamImport buildErrorResponse(DockerImageURI uri) { + ModelNodeBuilder builder = new ModelNodeBuilder().set(STATUS_STATUS, "Failure") + .set("status.message", + String.format("you may not have access to the Docker image \"%s\"", uri.getUriWithoutHost())) + .set("status.reason", "Unauthorized").set("status.code", IHttpConstants.STATUS_UNAUTHORIZED); + + return buildImageStreamImport(uri, builder.build()); + } + + private IImageStreamImport buildResponse(String meta, DockerImageURI uri) { + ModelNode raw = ModelNode.fromJSONString(meta); + ModelNode last = findNewestHistoryEntry(raw); + ModelNode containerConfig = last.remove("container_config"); + last.get("ContainerConfig").set(containerConfig); + + ModelNodeBuilder builder = new ModelNodeBuilder().set(STATUS_STATUS, "Success").set("tag", uri.getTag()) + .set("image.metadata.name", uri.getName()) + .set(ImageStreamImport.IMAGE_DOCKER_IMAGE_REFERENCE, uri.getUriUserNameAndName()) + .set("image.dockerImageMetadata", last).set("status.code", IHttpConstants.STATUS_OK); + + return buildImageStreamImport(uri, builder.build()); + } + + private ImageStreamImport buildImageStreamImport(DockerImageURI uri, ModelNode node) { + ImageStreamImport isImport = factory.stub(ResourceKind.IMAGE_STREAM_IMPORT, uri.getName(), + this.project.getName()); + ModelNode root = isImport.getNode(); + ModelNode images = JBossDmrExtentions.get(root, null, ImageStreamImport.STATUS_IMAGES); + images.add(node); + + return isImport; + } + + private ModelNode findNewestHistoryEntry(ModelNode root) { + ModelNode history = root.get("history"); + List entries = history.asList().stream() + .map(n -> ModelNode.fromJSONString(n.get("v1Compatibility").asString())).collect(Collectors.toList()); + entries.sort(new ManifestComparator()); + + ModelNode last = entries.get(entries.size() - 1); + LOG.debug("newest history: " + last.toJSONString(false)); + return last; + } + + /** + * Sorts history entries ordering from oldest to newest by comparing the entry + * id to its referenced parent + * + * @author jeff.cantrill + * + */ + static class ManifestComparator implements Comparator { + + @Override + public int compare(ModelNode one, ModelNode two) { + String parent1 = one.has(PARENT) ? one.get(PARENT).asString() : null; + String parent2 = two.has(PARENT) ? one.get(PARENT).asString() : null; + if (parent1 == null && parent2 != null) { + return -1; + } else if (parent1 != null && parent2 == null) { + return 1; + } else if (parent1 == null && parent2 == null) { + return 0; // we should never get here + } + String id1 = one.get(ID).asString(); + String id2 = two.get(ID).asString(); + + if (parent2.equals(id1)) { + return -1; + } else if (parent1.equals(id2)) { + return 1; + } + return 0; // we should never get here + } + } } diff --git a/src/main/java/com/openshift/internal/restclient/capability/resources/ImageStreamImportCapability.java b/src/main/java/com/openshift/internal/restclient/capability/resources/ImageStreamImportCapability.java index fb09d86d..85a631a4 100644 --- a/src/main/java/com/openshift/internal/restclient/capability/resources/ImageStreamImportCapability.java +++ b/src/main/java/com/openshift/internal/restclient/capability/resources/ImageStreamImportCapability.java @@ -8,8 +8,8 @@ * Contributors: * Red Hat, Inc. - initial API and implementation ******************************************************************************/ -package com.openshift.internal.restclient.capability.resources; +package com.openshift.internal.restclient.capability.resources; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -24,53 +24,49 @@ import com.openshift.restclient.model.IStatus; import com.openshift.restclient.model.image.IImageStreamImport; -/** - * - * @author jeff.cantrill - * - */ public class ImageStreamImportCapability implements IImageStreamImportCapability { - private static final Logger LOG = LoggerFactory.getLogger(IImageStreamImportCapability.class); - private IClient client; - private IProject project; + private static final Logger LOG = LoggerFactory.getLogger(IImageStreamImportCapability.class); + private IClient client; + private IProject project; + + public ImageStreamImportCapability(IProject project, IClient client) { + this.project = project; + this.client = client; + } - public ImageStreamImportCapability(IProject project, IClient client) { - this.project = project; - this.client = client; - } - - @Override - public IImageStreamImport importImageMetadata(DockerImageURI uri) { - - LOG.debug("first trying imagestreamimport against OpenShift server..."); - IImageStreamImport streamImport = client.getResourceFactory().stub(ResourceKind.IMAGE_STREAM_IMPORT, "jbosstools-openshift-deployimage", project.getName()); - streamImport.setImport(false); - streamImport.addImage("DockerImage", uri); - try { - IImageStreamImport result = client.create(streamImport); - for (IStatus status : result.getImageStatus()) { - if("Success".equalsIgnoreCase(status.getStatus())) { - return result; - } - } - }catch(ResourceForbiddenException | UnsupportedEndpointException e) { - LOG.info("Unsuccessful in trying OpenShift server. ImageStreamImport is not supported."); - } - LOG.debug("Unsuccessful in trying OpenShift server. Trying dockerhub v2 registry..."); - DockerRegistryImageStreamImportCapability reg = new DockerRegistryImageStreamImportCapability(this.project, client.getResourceFactory()); - return reg.importImageMetadata(uri); - } + @Override + public IImageStreamImport importImageMetadata(DockerImageURI uri) { + LOG.debug("first trying imagestreamimport against OpenShift server..."); + IImageStreamImport streamImport = client.getResourceFactory().stub(ResourceKind.IMAGE_STREAM_IMPORT, + "jbosstools-openshift-deployimage", project.getName()); + streamImport.setImport(false); + streamImport.addImage("DockerImage", uri); + try { + IImageStreamImport result = client.create(streamImport); + for (IStatus status : result.getImageStatus()) { + if (IStatus.SUCCESS.equalsIgnoreCase(status.getStatus())) { + return result; + } + } + } catch (ResourceForbiddenException | UnsupportedEndpointException e) { + LOG.info("Unsuccessful in trying OpenShift server. ImageStreamImport is not supported."); + } + LOG.debug("Unsuccessful in trying OpenShift server. Trying dockerhub v2 registry..."); + DockerRegistryImageStreamImportCapability reg = new DockerRegistryImageStreamImportCapability(this.project, + client.getResourceFactory(), client); + return reg.importImageMetadata(uri); + } - @Override - public boolean isSupported() { - return true; - } + @Override + public boolean isSupported() { + return true; + } - @Override - public String getName() { - return ImageStreamImportCapability.class.getSimpleName(); - } + @Override + public String getName() { + return ImageStreamImportCapability.class.getSimpleName(); + } } diff --git a/src/main/java/com/openshift/internal/restclient/capability/resources/OpenShiftBinaryPodLogRetrieval.java b/src/main/java/com/openshift/internal/restclient/capability/resources/OpenShiftBinaryPodLogRetrieval.java index e6e62d83..980d0a5c 100644 --- a/src/main/java/com/openshift/internal/restclient/capability/resources/OpenShiftBinaryPodLogRetrieval.java +++ b/src/main/java/com/openshift/internal/restclient/capability/resources/OpenShiftBinaryPodLogRetrieval.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2015 Red Hat, Inc. + * Copyright (c) 2015-2018 Red Hat, Inc. * Distributed under license by Red Hat, Inc. All rights reserved. * This program is made available under the terms of the * Eclipse Public License v1.0 which accompanies this distribution, @@ -8,6 +8,7 @@ * Contributors: * Red Hat, Inc. - initial API and implementation ******************************************************************************/ + package com.openshift.internal.restclient.capability.resources; import java.io.InputStream; @@ -28,137 +29,173 @@ import com.openshift.restclient.model.IPod; public class OpenShiftBinaryPodLogRetrieval implements IPodLogRetrieval { - - private static final Logger LOG = LoggerFactory.getLogger(IPodLogRetrieval.class); - private IPod pod; - private IClient client; - private Map cache = new HashMap<>(); - - public OpenShiftBinaryPodLogRetrieval(IPod pod, IClient client) { - this.pod = pod; - this.client = client; - } - - @Override - public boolean isSupported() { - return true; - } - - @Override - public String getName() { - return OpenShiftBinaryPodLogRetrieval.class.getSimpleName(); - } - - @Override - public InputStream getLogs(final boolean follow, final OpenShiftBinaryOption... options) { - return getLogs(follow, null, options); - } - - @Override - public InputStream getLogs(final boolean follow, final String container, final OpenShiftBinaryOption... options) { - final String normalizedContainer = StringUtils.defaultIfBlank(container, ""); - synchronized (cache) { - if(cache.containsKey(normalizedContainer)) { - return cache.get(normalizedContainer).getLogs(); - } - PodLogs logs = null; - try { - logs = new PodLogs(client, follow, normalizedContainer, options); - return logs.getLogs(); - }catch(Exception e) { - throw e; - }finally { - if(logs != null) { - cache.put(normalizedContainer, logs); - } - } - } - } - - @Override - public void stop() { - new ArrayList<>(cache.keySet()).forEach(c->stop(c)); - } - - @Override - public synchronized void stop(String container) { - if(!cache.containsKey(container)) return; - try { - PodLogs logs = cache.remove(container); - logs.stop(); - }catch(Exception e) { - LOG.warn("Unable to stop pod logs",e); - } - } - - - private class PodLogs extends AbstractOpenShiftBinaryCapability{ - - private String container; - private boolean follow; - private SequenceInputStream is; - private OpenShiftBinaryOption[] options; - - PodLogs(IClient client, boolean follow, String container, OpenShiftBinaryOption... options){ - super(client); - this.follow = follow; - this.container = container; - this.options = options; - } - - public synchronized InputStream getLogs() { - if(is == null) { - start(options); - is = new SequenceInputStream(getProcess().getInputStream(), getProcess().getErrorStream()); - } - return is; - } - - @Override - public boolean isSupported() { - return true; - } - - @Override - public String getName() { - return ""; - } - - @Override - protected void cleanup() { - follow = false; - if(getProcess() != null) { - IOUtils.closeQuietly(getProcess().getInputStream()); - IOUtils.closeQuietly(getProcess().getErrorStream()); - } - synchronized (cache) { - cache.remove(this.container); - } - } - - @Override - protected boolean validate() { - return true; - } - - @Override - protected String buildArgs(final List options) { - final StringBuilder argsBuilder = new StringBuilder(); - argsBuilder.append("logs "); - if(options.contains(OpenShiftBinaryOption.SKIP_TLS_VERIFY)) { - argsBuilder.append(getSkipTlsVerifyFlag()); - } - argsBuilder.append(getServerFlag()).append(" ") - .append(pod.getName()).append(" ").append("-n ").append(pod.getNamespace()).append(" ") - .append(getTokenFlag()); - if(follow) { - argsBuilder.append(" -f "); - } - if(StringUtils.isNotBlank(container)) { - argsBuilder.append( " -c ").append(container); - } - return argsBuilder.toString(); - } - } - + + static class PodName implements OpenShiftBinaryOption { + + private IPod pod; + + public PodName(IPod pod) { + this.pod = pod; + } + + @Override + public void append(StringBuilder commandLine) { + if (pod == null) { + return; + } + commandLine.append(" ").append(pod.getName()); + } + } + + static class ContainerName implements OpenShiftBinaryOption { + + private String name; + + public ContainerName(String name) { + this.name = name; + } + + @Override + public void append(StringBuilder commandLine) { + commandLine.append(" -c ").append(name); + } + } + + static class Follow implements OpenShiftBinaryOption { + + @Override + public void append(StringBuilder commandLine) { + commandLine.append(" -f"); + } + } + + private static final Logger LOG = LoggerFactory.getLogger(IPodLogRetrieval.class); + private IPod pod; + private IClient client; + private Map cache = new HashMap<>(); + + public OpenShiftBinaryPodLogRetrieval(IPod pod, IClient client) { + this.pod = pod; + this.client = client; + } + + @Override + public boolean isSupported() { + return true; + } + + @Override + public String getName() { + return OpenShiftBinaryPodLogRetrieval.class.getSimpleName(); + } + + @Override + public InputStream getLogs(final boolean follow, final OpenShiftBinaryOption... options) { + return getLogs(follow, null, options); + } + + @Override + public InputStream getLogs(final boolean follow, final String container, final OpenShiftBinaryOption... options) { + final String normalizedContainer = StringUtils.defaultIfBlank(container, ""); + synchronized (cache) { + if (cache.containsKey(normalizedContainer)) { + return cache.get(normalizedContainer).getLogs(); + } + PodLogs logs = null; + try { + logs = new PodLogs(client, follow, normalizedContainer, options); + return logs.getLogs(); + } finally { + if (logs != null) { + cache.put(normalizedContainer, logs); + } + } + } + } + + @Override + public void stop() { + new ArrayList<>(cache.keySet()).forEach(container -> stop(container)); + } + + @Override + public synchronized void stop(String container) { + if (!cache.containsKey(container)) { + return; + } + try { + PodLogs logs = cache.remove(container); + logs.stop(); + } catch (Exception e) { + LOG.warn("Unable to stop pod logs", e); + } + } + + protected class PodLogs extends AbstractOpenShiftBinaryCapability { + + public static final String LOGS_COMMAND = "logs"; + + private String container; + private boolean follow; + private SequenceInputStream is; + private OpenShiftBinaryOption[] options; + + protected PodLogs(IClient client, boolean follow, String container, OpenShiftBinaryOption... options) { + super(client); + this.follow = follow; + this.container = container; + this.options = options; + } + + public synchronized InputStream getLogs() { + if (is == null) { + Process process = start(options); + if (process != null) { + is = new SequenceInputStream(process.getInputStream(), process.getErrorStream()); + } + } + return is; + } + + @Override + public boolean isSupported() { + return true; + } + + @Override + public String getName() { + return ""; + } + + @Override + protected void cleanup() { + follow = false; + if (getProcess() != null) { + IOUtils.closeQuietly(getProcess().getInputStream()); + IOUtils.closeQuietly(getProcess().getErrorStream()); + } + synchronized (cache) { + cache.remove(this.container); + } + } + + @Override + protected boolean validate() { + return true; + } + + @Override + protected String buildArgs(final List options) { + CommandLineBuilder builder = new CommandLineBuilder(LOGS_COMMAND).append(new Token(client)) + .append(new Server(client)).append(options).append(new PodName(pod)).append(new Namespace(pod)); + if (follow) { + builder.append(new Follow()); + } + if (StringUtils.isNotBlank(container)) { + builder.append(new ContainerName(container)); + } + return builder.build(); + } + } + } diff --git a/src/main/java/com/openshift/internal/restclient/capability/resources/OpenShiftBinaryPortForwarding.java b/src/main/java/com/openshift/internal/restclient/capability/resources/OpenShiftBinaryPortForwarding.java index 99395aa5..c94858bd 100644 --- a/src/main/java/com/openshift/internal/restclient/capability/resources/OpenShiftBinaryPortForwarding.java +++ b/src/main/java/com/openshift/internal/restclient/capability/resources/OpenShiftBinaryPortForwarding.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2015 Red Hat, Inc. + * Copyright (c) 2015-2018 Red Hat, Inc. * Distributed under license by Red Hat, Inc. All rights reserved. * This program is made available under the terms of the * Eclipse Public License v1.0 which accompanies this distribution, @@ -8,6 +8,7 @@ * Contributors: * Red Hat, Inc. - initial API and implementation ******************************************************************************/ + package com.openshift.internal.restclient.capability.resources; import java.util.ArrayList; @@ -22,72 +23,100 @@ /** * Port forwarding implementation that wraps the OpenShift binary * - * @author Jeff Cantrill - * */ public class OpenShiftBinaryPortForwarding extends AbstractOpenShiftBinaryCapability implements IPortForwardable { - - private final IPod pod; - private final Collection pairs = new ArrayList<>(); - - public OpenShiftBinaryPortForwarding(IPod pod, IClient client) { - super(client); - this.pod = pod; - } - - @Override - protected void cleanup() { - this.pairs.clear(); - } - - @Override - protected boolean validate() { - return !pairs.isEmpty(); - } - - @Override - public boolean isForwarding() { - return getProcess() != null && getProcess().isAlive(); - } - - @Override - public boolean isSupported() { - return true; - } - - @Override - public String getName() { - return OpenShiftBinaryPortForwarding.class.getSimpleName(); - } - - @Override - public Collection getPortPairs() { - return pairs; - } - - @Override - public synchronized void forwardPorts(final Collection ports, final OpenShiftBinaryOption... options) { - if (ports != null && !ports.isEmpty()) { - this.pairs.addAll(ports); - } else { - throw new OpenShiftException("Port-forwarding was invoked but not port was specified."); - } - start(options); - } - - @Override - protected String buildArgs(final List options) { - final StringBuilder argBuilder = new StringBuilder(); - argBuilder.append("port-forward "); - if(options.contains(OpenShiftBinaryOption.SKIP_TLS_VERIFY)) { - argBuilder.append(getSkipTlsVerifyFlag()); - } - argBuilder.append(getServerFlag()).append(getTokenFlag()).append("-n ").append(pod.getNamespace()).append(" ") - .append("-p ").append(pod.getName()).append(" "); - for (PortPair pair : pairs) { - argBuilder.append(pair.getLocalPort()).append(":").append(pair.getRemotePort()).append(" "); - } - return argBuilder.toString(); - } - + + public static final String PORT_FORWARD_COMMAND = "port-forward"; + private final IPod pod; + private final Collection pairs = new ArrayList<>(); + + static class PodName implements OpenShiftBinaryOption { + + private IPod pod; + + public PodName(IPod pod) { + this.pod = pod; + } + + @Override + public void append(StringBuilder commandLine) { + commandLine.append(' ').append(pod.getName()); + } + } + + static class PortPairs implements OpenShiftBinaryOption { + + private Collection pairs; + + public PortPairs(Collection pairs) { + this.pairs = pairs; + } + + @Override + public void append(StringBuilder commandLine) { + if (pairs == null) { + return; + } + for (PortPair pair : pairs) { + append(pair, commandLine); + } + } + + protected void append(PortPair pair, StringBuilder commandLine) { + commandLine.append(" ").append(pair.getLocalPort()).append(":").append(pair.getRemotePort()).append(" "); + } + } + + public OpenShiftBinaryPortForwarding(IPod pod, IClient client) { + super(client); + this.pod = pod; + } + + @Override + protected void cleanup() { + this.pairs.clear(); + } + + @Override + protected boolean validate() { + return !pairs.isEmpty(); + } + + @Override + public boolean isForwarding() { + return getProcess() != null && getProcess().isAlive(); + } + + @Override + public boolean isSupported() { + return true; + } + + @Override + public String getName() { + return OpenShiftBinaryPortForwarding.class.getSimpleName(); + } + + @Override + public Collection getPortPairs() { + return pairs; + } + + @Override + public synchronized void forwardPorts(final Collection ports, final OpenShiftBinaryOption... options) { + if (ports == null || ports.isEmpty()) { + throw new OpenShiftException("Port-forwarding was invoked but no ports were specified."); + } + + this.pairs.addAll(ports); + start(options); + } + + @Override + protected String buildArgs(final List options) { + return new CommandLineBuilder(PORT_FORWARD_COMMAND).append(new Token(getClient())) + .append(new Server(getClient())).append(options).append(new Namespace(pod)).append(new PodName(pod)) + .append(new PortPairs(pairs)).build(); + } + } diff --git a/src/main/java/com/openshift/internal/restclient/capability/resources/OpenShiftBinaryRSync.java b/src/main/java/com/openshift/internal/restclient/capability/resources/OpenShiftBinaryRSync.java index 72a16956..7d01f9c3 100644 --- a/src/main/java/com/openshift/internal/restclient/capability/resources/OpenShiftBinaryRSync.java +++ b/src/main/java/com/openshift/internal/restclient/capability/resources/OpenShiftBinaryRSync.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2015 Red Hat, Inc. + * Copyright (c) 2015-2018 Red Hat, Inc. * Distributed under license by Red Hat, Inc. All rights reserved. * This program is made available under the terms of the * Eclipse Public License v1.0 which accompanies this distribution, @@ -8,23 +8,26 @@ * Contributors: * Red Hat, Inc. - initial API and implementation ******************************************************************************/ + package com.openshift.internal.restclient.capability.resources; import java.io.IOException; import java.io.InputStream; +import java.nio.charset.StandardCharsets; import java.util.List; import java.util.concurrent.Executor; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; import org.apache.commons.io.IOUtils; -import org.eclipse.jetty.util.StringUtil; +import org.apache.commons.lang.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.openshift.restclient.IClient; import com.openshift.restclient.OpenShiftException; import com.openshift.restclient.capability.resources.IRSyncable; +import com.openshift.restclient.model.IPod; /** * Port forwarding implementation that wraps the OpenShift binary @@ -33,131 +36,134 @@ * */ public class OpenShiftBinaryRSync extends AbstractOpenShiftBinaryCapability implements IRSyncable { - - private static final Logger LOG = LoggerFactory.getLogger(OpenShiftBinaryRSync.class); - - private static final long WAIT_FOR_EXIT_TIMEOUT = 5; // mins - - private Peer source; - private Peer destination; - - private final Executor executor = Executors.newCachedThreadPool(); - - /** - * Constructor. - * @param client the client to connect to OpenShift. - */ - public OpenShiftBinaryRSync(final IClient client) { - super(client); - } - - @Override - public InputStream sync(final Peer source, final Peer destination, final OpenShiftBinaryOption... options) throws OpenShiftException { - this.source = source; - this.destination = destination; - start(options); - // monitor the process completion in a separate thread - this.executor.execute(() -> { - try { - this.getProcess().waitFor(); - } catch (InterruptedException e) { - throw new OpenShiftException("Error occurred while waiting for rsync operation to complete", e); - } - - }); - return getProcess().getInputStream(); - } - - @Override - public boolean isDone() { - return !getProcess().isAlive(); - } - - @Override - public int exitValue() { - return getProcess().exitValue(); - } - - @Override - public void await() throws InterruptedException { - try { - if (getProcess() == null) { - throw new OpenShiftException("Could not sync %s to %s, no process was launched.", - destination); - } - if (!getProcess().waitFor(WAIT_FOR_EXIT_TIMEOUT, TimeUnit.MINUTES)) { - throw new OpenShiftException("Syncing %s to %s did not terminate within %d minutes.", - source, destination, WAIT_FOR_EXIT_TIMEOUT); - } - - if (getProcess().exitValue() != 0) { - String errorMessage = getErrorMessage(getProcess().getErrorStream()); - throw new OpenShiftException("Syncing %s to %s failed" - + (StringUtil.isBlank(errorMessage) ? "" : ": %s"), - source, destination, errorMessage); - } - } catch (InterruptedException e) { - throw new OpenShiftException(e, "Syncing %s to %s was interrupted.", - source, destination); - } - } - - private static String getErrorMessage(InputStream errorStream) { - try { - return IOUtils.toString(errorStream); - } catch (IOException e) { - LOG.error("Could not retrieve error message from process", e); - return null; - } - } - - @Override - protected void cleanup() { - this.source = null; - this.destination = null; - } - - @Override - protected boolean validate() { - return source != null - && destination != null - && hasPodPeer(source, destination); - } - - private static boolean hasPodPeer(Peer source, Peer destination) { - return source.isPod() - || destination.isPod(); - } - - @Override - public boolean isSupported() { - return true; - } - - @Override - public String getName() { - return OpenShiftBinaryRSync.class.getSimpleName(); - } - - @Override - protected String buildArgs(final List options) { - final StringBuilder argsBuilder = new StringBuilder("rsync "); - argsBuilder.append(getUserFlag()).append(getTokenFlag()).append(getServerFlag()); - if(options.contains(OpenShiftBinaryOption.SKIP_TLS_VERIFY)) { - argsBuilder.append(getSkipTlsVerifyFlag()); - } - if(options.contains(OpenShiftBinaryOption.EXCLUDE_GIT_FOLDER)) { - argsBuilder.append(getGitFolderExclusionFlag()); - } - if(options.contains(OpenShiftBinaryOption.NO_PERMS)) { - argsBuilder.append(getNoPermsFlags()); - } - if(options.contains(OpenShiftBinaryOption.DELETE)) { - argsBuilder.append(getDeleteFlags()); - } - argsBuilder.append(source.getParameter()).append(" ") - .append(destination.getParameter()); - return argsBuilder.toString(); - } - + + private static final Logger LOG = LoggerFactory.getLogger(OpenShiftBinaryRSync.class); + public static final String RSYNC_COMMAND = "rsync"; + private static final long WAIT_FOR_EXIT_TIMEOUT = 5; // mins + + private Peer source; + private Peer destination; + private IPod pod; + + private final Executor executor = Executors.newCachedThreadPool(); + + /** + * Constructor. + * + * @param client + * the client to connect to OpenShift. + */ + public OpenShiftBinaryRSync(final IClient client) { + super(client); + } + + @Override + public InputStream sync(final Peer source, final Peer destination, final OpenShiftBinaryOption... options) + throws OpenShiftException { + this.source = source; + this.destination = destination; + this.pod = getPod(source, destination); + Process process = start(options); + waitFor(process); + if (process == null) { + return null; + } + return process.getInputStream(); + } + + private IPod getPod(Peer source, Peer destination) { + if (source.isPod()) { + return source.getPod(); + } else if (destination.isPod()) { + return destination.getPod(); + } else { + return null; + } + } + + protected void waitFor(Process process) { + if (process == null) { + return; + } + + this.executor.execute(() -> { + try { + process.waitFor(); + } catch (InterruptedException e) { + throw new OpenShiftException("Error occurred while waiting for rsync operation to complete", e); + } + }); + } + + @Override + public boolean isDone() { + return !getProcess().isAlive(); + } + + @Override + public int exitValue() { + return getProcess().exitValue(); + } + + @Override + public void await() throws InterruptedException { + try { + if (getProcess() == null) { + throw new OpenShiftException("Could not sync %s to %s, no process was launched.", destination); + } + if (!getProcess().waitFor(WAIT_FOR_EXIT_TIMEOUT, TimeUnit.MINUTES)) { + throw new OpenShiftException("Syncing %s to %s did not terminate within %d minutes.", source, + destination, WAIT_FOR_EXIT_TIMEOUT); + } + + if (getProcess().exitValue() != 0) { + String errorMessage = getErrorMessage(getProcess().getErrorStream()); + throw new OpenShiftException( + "Syncing %s to %s failed" + (StringUtils.isBlank(errorMessage) ? "" : ": %s"), source, + destination, errorMessage); + } + } catch (InterruptedException e) { + throw new OpenShiftException(e, "Syncing %s to %s was interrupted.", source, destination); + } + } + + private static String getErrorMessage(InputStream errorStream) { + try { + return IOUtils.toString(errorStream, StandardCharsets.UTF_8); + } catch (IOException e) { + LOG.error("Could not retrieve error message from process", e); + return null; + } + } + + @Override + protected void cleanup() { + this.source = null; + this.destination = null; + } + + @Override + protected boolean validate() { + return source != null && destination != null && hasPodPeer(source, destination); + } + + private static boolean hasPodPeer(Peer source, Peer destination) { + return source.isPod() || destination.isPod(); + } + + @Override + public boolean isSupported() { + return true; + } + + @Override + public String getName() { + return OpenShiftBinaryRSync.class.getSimpleName(); + } + + @Override + protected String buildArgs(final List options) { + return new CommandLineBuilder(RSYNC_COMMAND).append(new Token(getClient())).append(new Server(getClient())) + .append(new Namespace(pod)).append(options).append(source).append(destination).build(); + } } diff --git a/src/main/java/com/openshift/internal/restclient/capability/resources/PodLogRetrievalAsync.java b/src/main/java/com/openshift/internal/restclient/capability/resources/PodLogRetrievalAsync.java new file mode 100644 index 00000000..d4785acb --- /dev/null +++ b/src/main/java/com/openshift/internal/restclient/capability/resources/PodLogRetrievalAsync.java @@ -0,0 +1,153 @@ +/******************************************************************************* + * Copyright (c) 2016-2018 Red Hat, Inc. + * Distributed under license by Red Hat, Inc. All rights reserved. + * This program is made available under the terms of the + * Eclipse Public License v1.0 which accompanies this distribution, + * and is available at http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Red Hat, Inc. - initial API and implementation + ******************************************************************************/ + +package com.openshift.internal.restclient.capability.resources; + +import java.util.HashMap; +import java.util.Map; +import java.util.concurrent.atomic.AtomicBoolean; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.openshift.internal.restclient.DefaultClient; +import com.openshift.internal.restclient.URLBuilder; +import com.openshift.internal.restclient.okhttp.OpenShiftRequestBuilder; +import com.openshift.internal.restclient.okhttp.ResponseCodeInterceptor; +import com.openshift.restclient.IApiTypeMapper; +import com.openshift.restclient.IClient; +import com.openshift.restclient.UnsupportedEndpointException; +import com.openshift.restclient.capability.IStoppable; +import com.openshift.restclient.capability.resources.IPodLogRetrievalAsync; +import com.openshift.restclient.http.IHttpConstants; +import com.openshift.restclient.model.IPod; + +import okhttp3.OkHttpClient; +import okhttp3.Request; +import okhttp3.Response; +import okhttp3.WebSocket; +import okhttp3.WebSocketListener; +import okio.ByteString; + +/** + * Impl of Pod log retrieval using websocket + * + */ +public class PodLogRetrievalAsync implements IPodLogRetrievalAsync { + + private static final Logger LOG = LoggerFactory.getLogger(PodLogRetrievalAsync.class); + private static final String CAPABILITY = "log"; + private final IPod pod; + private final DefaultClient client; + private final IApiTypeMapper mapper; + + public PodLogRetrievalAsync(IPod pod, IClient client) { + this.pod = pod; + this.client = client.adapt(DefaultClient.class); + this.mapper = client.adapt(IApiTypeMapper.class); + } + + @Override + public boolean isSupported() { + if (client != null && mapper != null) { + try { + return mapper.getEndpointFor(pod.getApiVersion(), pod.getKind()).isSupported(CAPABILITY); + } catch (UnsupportedEndpointException e) { + // endpoint not found for version/kind + } + } + return false; + } + + @Override + public String getName() { + return PodLogRetrievalAsync.class.getSimpleName(); + } + + @Override + public IStoppable start(IPodLogListener listener) { + return start(listener, null); + } + + @Override + public IStoppable start(IPodLogListener listener, Options options) { + Map parameters = options != null ? options.getMap() : new HashMap<>(); + PodLogListenerAdapter adapter = new PodLogListenerAdapter(listener); + + OkHttpClient okClient = client.adapt(OkHttpClient.class); + final String endpoint = new URLBuilder(client.getBaseURL(), mapper).kind(pod.getKind()) + .namespace(pod.getNamespaceName()).name(pod.getName()).subresource(CAPABILITY).addParameters(parameters) + .websocket(); + Request request = new OpenShiftRequestBuilder() + .url(endpoint) + .acceptJson() + .authorization(client.getAuthorizationContext()) + .tag(new ResponseCodeInterceptor.Ignore() {}) + .build(); + okClient.newWebSocket(request, adapter); + return adapter; + } + + static class PodLogListenerAdapter extends WebSocketListener implements IStoppable { + + private final IPodLogListener listener; + private WebSocket wsClient; + private AtomicBoolean open = new AtomicBoolean(false); + + public PodLogListenerAdapter(IPodLogListener listener) { + this.listener = listener; + } + + @Override + public void stop() { + try { + if (open.get()) { + wsClient.close(IHttpConstants.STATUS_NORMAL_STOP, "Client asking to stop."); + } + } catch (Exception e) { + LOG.debug("Unable to stop the watch client", e); + } finally { + wsClient = null; + } + } + + @Override + public void onOpen(WebSocket webSocket, Response response) { + if (open.compareAndSet(false, true)) { + wsClient = webSocket; + listener.onOpen(); + } + } + + @Override + public void onClosing(WebSocket socket, int code, String reason) { + if (open.compareAndSet(true, false)) { + listener.onClose(code, reason); + } + } + + @Override + public void onMessage(WebSocket socket, String message) { + listener.onMessage(message); + } + + @Override + public void onMessage(WebSocket webSocket, ByteString bytes) { + listener.onMessage(bytes.utf8()); + } + + @Override + public void onFailure(WebSocket socket, Throwable t, Response response) { + listener.onFailure(t); + } + + } +} diff --git a/src/main/java/com/openshift/internal/restclient/capability/resources/ProjectTemplateListCapability.java b/src/main/java/com/openshift/internal/restclient/capability/resources/ProjectTemplateListCapability.java index e59748f9..6695dc27 100644 --- a/src/main/java/com/openshift/internal/restclient/capability/resources/ProjectTemplateListCapability.java +++ b/src/main/java/com/openshift/internal/restclient/capability/resources/ProjectTemplateListCapability.java @@ -6,6 +6,7 @@ * * Contributors: Red Hat, Inc. - initial API and implementation ******************************************************************************/ + package com.openshift.internal.restclient.capability.resources; import java.util.Collection; @@ -17,35 +18,40 @@ import com.openshift.restclient.model.template.ITemplate; public class ProjectTemplateListCapability implements IProjectTemplateList { - - private static final String COMMON_NAMESPACE = "openshift"; //eventually configurable - private IProject project; - private IClient client; - - public ProjectTemplateListCapability(IProject project, IClient client) { - this.project = project; - this.client = client; - } - - @Override - public boolean isSupported() { - return client != null && project != null; - } - - @Override - public String getName() { - return this.getClass().getSimpleName(); - } - - @Override - public Collection getTemplates() { - return client.list(ResourceKind.TEMPLATE, project.getNamespace()); - } - - @Override - public Collection getCommonTemplates() { - return client.list(ResourceKind.TEMPLATE,COMMON_NAMESPACE); - } - - + + private static final String COMMON_NAMESPACE = "openshift"; // eventually configurable + private IProject project; + private IClient client; + + public ProjectTemplateListCapability(IProject project, IClient client) { + this.project = project; + this.client = client; + } + + @Override + public boolean isSupported() { + return client != null && project != null; + } + + @Override + public String getName() { + return this.getClass().getSimpleName(); + } + + @Override + public Collection getTemplates() { + return client.list(ResourceKind.TEMPLATE, project.getNamespaceName()); + } + + @Override + public Collection getCommonTemplates() { + return getCommonTemplates(COMMON_NAMESPACE); + } + + @Override + public Collection getCommonTemplates(String clusterNamespace) { + return client.list(ResourceKind.TEMPLATE, + clusterNamespace == null ? COMMON_NAMESPACE : clusterNamespace); + } + } diff --git a/src/main/java/com/openshift/internal/restclient/capability/resources/ProjectTemplateProcessing.java b/src/main/java/com/openshift/internal/restclient/capability/resources/ProjectTemplateProcessing.java index 2df39cc3..8e892f88 100644 --- a/src/main/java/com/openshift/internal/restclient/capability/resources/ProjectTemplateProcessing.java +++ b/src/main/java/com/openshift/internal/restclient/capability/resources/ProjectTemplateProcessing.java @@ -6,6 +6,7 @@ * * Contributors: Red Hat, Inc. - initial API and implementation ******************************************************************************/ + package com.openshift.internal.restclient.capability.resources; import java.util.Collection; @@ -24,39 +25,39 @@ * */ public class ProjectTemplateProcessing implements IProjectTemplateProcessing { - - private String namespace; - private IClient client; - private ITemplateProcessing serverCapability; - - public ProjectTemplateProcessing(IProject project, IClient client) { - if(client != null && client.supports(ITemplateProcessing.class)) { - serverCapability = client.getCapability(ITemplateProcessing.class); - this.client = client; - this.namespace = project.getNamespace(); - } - } - - @Override - public boolean isSupported() { - return serverCapability != null; - } - - @Override - public String getName() { - return ProjectTemplateProcessing.class.getSimpleName(); - } - - @Override - public ITemplate process(ITemplate template) { - return serverCapability.process(template, namespace); - } - - @Override - public Collection apply(ITemplate template) { - IList resources = client.getResourceFactory().create(template.getApiVersion(), ResourceKind.LIST); - resources.addAll(template.getItems()); - return client.create(resources, this.namespace); - } + + private String namespace; + private IClient client; + private ITemplateProcessing serverCapability; + + public ProjectTemplateProcessing(IProject project, IClient client) { + if (client != null && client.supports(ITemplateProcessing.class)) { + serverCapability = client.getCapability(ITemplateProcessing.class); + this.client = client; + this.namespace = project.getNamespaceName(); + } + } + + @Override + public boolean isSupported() { + return serverCapability != null; + } + + @Override + public String getName() { + return ProjectTemplateProcessing.class.getSimpleName(); + } + + @Override + public ITemplate process(ITemplate template) { + return serverCapability.process(template, namespace); + } + + @Override + public Collection apply(ITemplate template) { + IList resources = client.getResourceFactory().create(template.getApiVersion(), ResourceKind.LIST); + resources.addAll(template.getObjects()); + return client.create(resources, this.namespace); + } } diff --git a/src/main/java/com/openshift/internal/restclient/capability/resources/PropertyAccessCapability.java b/src/main/java/com/openshift/internal/restclient/capability/resources/PropertyAccessCapability.java index d05eecda..9fcc749c 100644 --- a/src/main/java/com/openshift/internal/restclient/capability/resources/PropertyAccessCapability.java +++ b/src/main/java/com/openshift/internal/restclient/capability/resources/PropertyAccessCapability.java @@ -8,15 +8,16 @@ * Contributors: * Red Hat, Inc. - initial API and implementation ******************************************************************************/ + package com.openshift.internal.restclient.capability.resources; +import static com.openshift.internal.util.JBossDmrExtentions.get; + import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; -import static com.openshift.internal.util.JBossDmrExtentions.*; - import org.jboss.dmr.ModelNode; import com.openshift.internal.restclient.model.KubernetesResource; @@ -25,109 +26,111 @@ public class PropertyAccessCapability implements IPropertyAccessCapability { - private KubernetesResource resource; - - public PropertyAccessCapability(IResource resource) { - if(resource instanceof KubernetesResource) { - this.resource = (KubernetesResource) resource; - } - } - - @Override - public String asString(String path) { - ModelNode node = get(resource.getNode(), null, path); - if(!node.isDefined()) { - throw new UnresolvablePathException(); - } - return node.asString(); - } - - @Override - public Map asMap(String path) { - return asMap(get(resource.getNode(), null, path)); - } - - private Map asMap(ModelNode node) { - if(!node.isDefined()) { - throw new UnresolvablePathException(); - } - Map result = new HashMap<>(); - for (String key : node.keys()) { - ModelNode value = node.get(key); - switch(value.getType()) { - case OBJECT: - result.put(key, asMap(value)); - break; - case LIST: - result.put(key, asList(value)); - case STRING: - result.put(key, value.asString()); - break; - case INT: - result.put(key, value.asInt()); - break; - case BIG_INTEGER: - result.put(key, value.asBigInteger()); - break; - case BIG_DECIMAL: - result.put(key, value.asBigDecimal()); - break; - case LONG: - result.put(key, value.asBigDecimal()); - break; - case BOOLEAN: - result.put(key, value.asBoolean()); - break; - default: - result.put(key, value.asString()); - } - } - return result; - } - - private List asList(ModelNode node) { - List list = new ArrayList<>(); - for (ModelNode entry : node.asList()) { - switch(entry.getType()) { - case OBJECT: - list.add(asMap(entry)); - break; - case LIST: - list.add(asList(entry)); - case STRING: - list.add(entry.asString()); - break; - case INT: - list.add(entry.asInt()); - break; - case BIG_INTEGER: - list.add(entry.asBigInteger()); - break; - case BIG_DECIMAL: - list.add(entry.asBigDecimal()); - break; - case LONG: - list.add(entry.asBigDecimal()); - break; - case BOOLEAN: - list.add(entry.asBoolean()); - break; - default: - list.add(entry.asString()); - } - - } - return list; - } - - @Override - public boolean isSupported() { - return resource != null; - } - - @Override - public String getName() { - return this.getClass().getSimpleName(); - } + private KubernetesResource resource; + + public PropertyAccessCapability(IResource resource) { + if (resource instanceof KubernetesResource) { + this.resource = (KubernetesResource) resource; + } + } + + @Override + public String asString(String path) { + ModelNode node = get(resource.getNode(), null, path); + if (!node.isDefined()) { + throw new UnresolvablePathException(); + } + return node.asString(); + } + + @Override + public Map asMap(String path) { + return asMap(get(resource.getNode(), null, path)); + } + + private Map asMap(ModelNode node) { + if (!node.isDefined()) { + throw new UnresolvablePathException(); + } + Map result = new HashMap<>(); + for (String key : node.keys()) { + ModelNode value = node.get(key); + switch (value.getType()) { + case OBJECT: + result.put(key, asMap(value)); + break; + case LIST: + result.put(key, asList(value)); + break; + case STRING: + result.put(key, value.asString()); + break; + case INT: + result.put(key, value.asInt()); + break; + case BIG_INTEGER: + result.put(key, value.asBigInteger()); + break; + case BIG_DECIMAL: + result.put(key, value.asBigDecimal()); + break; + case LONG: + result.put(key, value.asBigDecimal()); + break; + case BOOLEAN: + result.put(key, value.asBoolean()); + break; + default: + result.put(key, value.asString()); + } + } + return result; + } + + private List asList(ModelNode node) { + List list = new ArrayList<>(); + for (ModelNode entry : node.asList()) { + switch (entry.getType()) { + case OBJECT: + list.add(asMap(entry)); + break; + case LIST: + list.add(asList(entry)); + break; + case STRING: + list.add(entry.asString()); + break; + case INT: + list.add(entry.asInt()); + break; + case BIG_INTEGER: + list.add(entry.asBigInteger()); + break; + case BIG_DECIMAL: + list.add(entry.asBigDecimal()); + break; + case LONG: + list.add(entry.asBigDecimal()); + break; + case BOOLEAN: + list.add(entry.asBoolean()); + break; + default: + list.add(entry.asString()); + } + + } + return list; + } + + @Override + public boolean isSupported() { + return resource != null; + } + + @Override + public String getName() { + return this.getClass().getSimpleName(); + } } diff --git a/src/main/java/com/openshift/internal/restclient/capability/resources/TagCapability.java b/src/main/java/com/openshift/internal/restclient/capability/resources/TagCapability.java index c2ff5bab..a1b9b469 100644 --- a/src/main/java/com/openshift/internal/restclient/capability/resources/TagCapability.java +++ b/src/main/java/com/openshift/internal/restclient/capability/resources/TagCapability.java @@ -6,6 +6,7 @@ * * Contributors: Red Hat, Inc. ******************************************************************************/ + package com.openshift.internal.restclient.capability.resources; import java.util.Arrays; @@ -14,24 +15,21 @@ import com.openshift.restclient.capability.resources.ITags; import com.openshift.restclient.model.IResource; -/** - * @author Jeff Cantrill - */ public class TagCapability extends AnnotationCapability implements ITags { - public TagCapability(IResource resource) { - super(TagCapability.class.getSimpleName(), resource); - } + public TagCapability(IResource resource) { + super(TagCapability.class.getSimpleName(), resource); + } - @Override - public Collection getTags() { - String value = getAnnotationValue(); - return Arrays.asList(value.split(",")); - } + @Override + public Collection getTags() { + String value = getAnnotationValue(); + return Arrays.asList(value.split(",")); + } - @Override - protected String getAnnotationKey() { - return "tags"; - } + @Override + protected String getAnnotationKey() { + return "tags"; + } } diff --git a/src/main/java/com/openshift/internal/restclient/capability/resources/TemplateTraceability.java b/src/main/java/com/openshift/internal/restclient/capability/resources/TemplateTraceability.java index 047bc2b5..c93a9658 100644 --- a/src/main/java/com/openshift/internal/restclient/capability/resources/TemplateTraceability.java +++ b/src/main/java/com/openshift/internal/restclient/capability/resources/TemplateTraceability.java @@ -6,40 +6,40 @@ * * Contributors: Red Hat, Inc. ******************************************************************************/ + package com.openshift.internal.restclient.capability.resources; import com.openshift.restclient.capability.resources.ITemplateTraceability; import com.openshift.restclient.model.IResource; /** - * Capability of resource tracing the template from which - * it was generated - * - * @author Jeff Cantrill + * Capability of resource tracing the template from which it was generated */ -public class TemplateTraceability implements ITemplateTraceability { - - private static final String TEMPLATE_ANNOTATION = "template"; - private IResource resource; - - public TemplateTraceability(IResource resource) { - this.resource = resource; - } - - @Override - public String getTemplateName() { - if(!isSupported()) return ""; - return resource.getAnnotation(TEMPLATE_ANNOTATION); - } - - @Override - public boolean isSupported() { - return resource.isAnnotatedWith(TEMPLATE_ANNOTATION); - } - - @Override - public String getName() { - return TemplateTraceability.class.getSimpleName(); - } +public class TemplateTraceability implements ITemplateTraceability { + + private static final String TEMPLATE_ANNOTATION = "template"; + private IResource resource; + + public TemplateTraceability(IResource resource) { + this.resource = resource; + } + + @Override + public String getTemplateName() { + if (!isSupported()) { + return ""; + } + return resource.getAnnotation(TEMPLATE_ANNOTATION); + } + + @Override + public boolean isSupported() { + return resource.isAnnotatedWith(TEMPLATE_ANNOTATION); + } + + @Override + public String getName() { + return TemplateTraceability.class.getSimpleName(); + } } diff --git a/src/main/java/com/openshift/internal/restclient/capability/resources/UpdateableCapability.java b/src/main/java/com/openshift/internal/restclient/capability/resources/UpdateableCapability.java index 3baab3e6..3a97333d 100644 --- a/src/main/java/com/openshift/internal/restclient/capability/resources/UpdateableCapability.java +++ b/src/main/java/com/openshift/internal/restclient/capability/resources/UpdateableCapability.java @@ -1,3 +1,14 @@ +/******************************************************************************* + * Copyright (c) 2016 Red Hat, Inc. + * Distributed under license by Red Hat, Inc. All rights reserved. + * This program is made available under the terms of the + * Eclipse Public License v1.0 which accompanies this distribution, + * and is available at http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Red Hat, Inc. - initial API and implementation + ******************************************************************************/ + package com.openshift.internal.restclient.capability.resources; import com.openshift.internal.restclient.model.KubernetesResource; @@ -6,31 +17,32 @@ public class UpdateableCapability implements IUpdatable { - private boolean isSupported; - private KubernetesResource resource; - public UpdateableCapability(IResource resource) { - if(resource instanceof KubernetesResource) { - isSupported = true; - this.resource = (KubernetesResource) resource; - } - } - - @Override - public boolean isSupported() { - return isSupported; - } - - @Override - public String getName() { - return UpdateableCapability.class.getSimpleName(); - } - - @Override - public void updateFrom(IResource source) { - if(source instanceof KubernetesResource) { - KubernetesResource from = (KubernetesResource) source; - resource.setNode(from.getNode()); - } - } + private boolean isSupported; + private KubernetesResource resource; + + public UpdateableCapability(IResource resource) { + if (resource instanceof KubernetesResource) { + isSupported = true; + this.resource = (KubernetesResource) resource; + } + } + + @Override + public boolean isSupported() { + return isSupported; + } + + @Override + public String getName() { + return UpdateableCapability.class.getSimpleName(); + } + + @Override + public void updateFrom(IResource source) { + if (source instanceof KubernetesResource) { + KubernetesResource from = (KubernetesResource) source; + resource.setNode(from.getNode()); + } + } } diff --git a/src/main/java/com/openshift/internal/restclient/capability/server/Console.java b/src/main/java/com/openshift/internal/restclient/capability/server/Console.java new file mode 100644 index 00000000..b00fc6ac --- /dev/null +++ b/src/main/java/com/openshift/internal/restclient/capability/server/Console.java @@ -0,0 +1,189 @@ +/******************************************************************************* + * Copyright (c) 2019 Red Hat, Inc. Distributed under license by Red Hat, Inc. + * All rights reserved. This program is made available under the terms of the + * Eclipse Public License v1.0 which accompanies this distribution, and is + * available at http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: Red Hat, Inc. + ******************************************************************************/ + +package com.openshift.internal.restclient.capability.server; + +import java.util.Arrays; +import java.util.Map; +import java.util.function.Function; +import java.util.stream.Stream; + +import com.openshift.restclient.IClient; +import com.openshift.restclient.ResourceKind; +import com.openshift.restclient.capability.server.IConsole; +import com.openshift.restclient.model.IConfigMap; +import com.openshift.restclient.model.IProject; +import com.openshift.restclient.model.IResource; + +public class Console implements IConsole { + + public static final String CONFIGMAP_DATA_CONSOLE_URL = "consoleURL"; + public static final String NAMESPACE_OPENSHIFT_CONFIG_MANAGED = "openshift-config-managed"; + public static final String CONFIGMAP_CONSOLE_PUBLIC = "console-public"; + + private IClient client; + + public Console(IClient client) { + this.client = client; + } + + @Override + public boolean isSupported() { + return true; + } + + @Override + public String getName() { + return this.getClass().getSimpleName(); + } + + @Override + public String getConsoleUrl() { + switch (client.getOpenShiftMajorVersion()) { + case 3: + return getOpenShift3ConsoleUrl(); + case 4: + return getOpenShift4ConsoleUrl(); + default: + return null; + } + } + + @Override + public String getConsoleUrl(R resource) { + switch (client.getOpenShiftMajorVersion()) { + case 3: + return getOpenShift3ConsoleUrl(resource); + case 4: + return getOpenShift4ConsoleUrl(resource); + default: + return null; + } + } + + private String getOpenShift3ConsoleUrl() { + return client.getBaseURL() + "/console"; + } + + private String getOpenShift3ConsoleUrl(R resource) { + StringBuilder builder = new StringBuilder(getOpenShift3ConsoleUrl()); + String projectName = resource == null ? null : resource.getNamespaceName(); + if (projectName != null) { + builder.append("/project/").append(projectName); + } + if (resource != null + && !(resource instanceof IProject)) { + String consoleResourceUrl = getOpenShiftResourceURL(resource, + Arrays.stream(OpenShiftConsoleResourceUrls.values()) + .filter(resourceUrl -> resourceUrl.getVersion() == 3)); + if (consoleResourceUrl != null) { + builder.append(consoleResourceUrl); + } + } + return builder.toString(); + } + + private String getOpenShift4ConsoleUrl() { + IConfigMap configMap = client.get( + ResourceKind.CONFIG_MAP, CONFIGMAP_CONSOLE_PUBLIC, NAMESPACE_OPENSHIFT_CONFIG_MANAGED); + if (configMap == null) { + return null; + } + Map data = configMap.getData(); + if (data == null + || data.isEmpty()) { + return null; + } + return data.get(CONFIGMAP_DATA_CONSOLE_URL); + } + + private String getOpenShift4ConsoleUrl(R resource) { + StringBuilder builder = new StringBuilder(getOpenShift4ConsoleUrl()); + if (resource == null) { + return builder.toString(); + } + String projectName = resource.getNamespaceName(); + if (resource.getKind().equals(ResourceKind.PROJECT)) { + builder.append("/overview/ns/").append(projectName); + } else { + String consoleResourceUrl = getOpenShiftResourceURL(resource, + Arrays.stream(OpenShiftConsoleResourceUrls.values()) + .filter(resourceUrl -> resourceUrl.getVersion() == 4)); + if (consoleResourceUrl != null) { + builder.append("/k8s/ns/").append(projectName).append(consoleResourceUrl); + } else { + // show project overview + builder.append("/overview/ns/").append(projectName); + } + } + return builder.toString(); + } + + protected String getOpenShiftResourceURL(IResource resource, Stream resourceUrls) { + return resourceUrls + .filter(resUrl -> resUrl.getResType().equals(resource.getKind())) + .findAny() + .map(resUrl -> resUrl.getUrlPart() + resUrl.getEndUrlFunc().apply(resource)) + .orElse(null); + } + + protected enum OpenShiftConsoleResourceUrls { + // OS3 + V3_BUILD(3, ResourceKind.BUILD, "/browse/builds/", r -> String.join("/", r.getLabels().get("buildconfig"), r.getName())), + V3_BUILDCONFIG(3, ResourceKind.BUILD_CONFIG, "/browse/builds/", IResource::getName), + V3_DEPLOYMENT(3, ResourceKind.REPLICATION_CONTROLLER, "/browse/rc/", IResource::getName), + V3_DEPLOYMENTCONFIG(3, ResourceKind.DEPLOYMENT_CONFIG, "/browse/deployments/", IResource::getName), + V3_EVENT(3, ResourceKind.EVENT, "/browse/events/", r -> org.apache.commons.lang.StringUtils.EMPTY), + V3_IMAGESTREAM(3, ResourceKind.IMAGE_STREAM, "/browse/images/", IResource::getName), + V3_PERSISTENTVOLUMECLAIM(3, ResourceKind.PVC, "/browse/persistentvolumeclaims/", IResource::getName), + V3_POD(3, ResourceKind.POD, "/browse/pods/", IResource::getName), + V3_ROUTES(3, ResourceKind.ROUTE, "/browse/routes/", IResource::getName), + V3_SERVICE(3, ResourceKind.SERVICE, "/browse/services/", IResource::getName), + // OS4 + V4_BUILDCONFIG(4, ResourceKind.BUILD_CONFIG, "/buildconfigs/", IResource::getName), + V4_BUILD(4, ResourceKind.BUILD, "/builds/", IResource::getName), + V4_DEPLOYMENT(4, ResourceKind.REPLICATION_CONTROLLER, "/replicationcontrollers/", IResource::getName), + V4_DEPLOYMENTCONFIG(4, ResourceKind.DEPLOYMENT_CONFIG, "/deploymentconfigs/", IResource::getName), + V4_EVENT(4, ResourceKind.EVENT, "/events/", r -> org.apache.commons.lang.StringUtils.EMPTY), + V4_IMAGESTREAM(4, ResourceKind.IMAGE_STREAM, "/imagestreams/", IResource::getName), + V4_PERSISTENTVOLUMECLAIM(4, ResourceKind.PVC, "/persistentvolumeclaims/", IResource::getName), + V4_POD(4, ResourceKind.POD, "/pods/", IResource::getName), + V4_ROUTES(4, ResourceKind.ROUTE, "/routes/", IResource::getName), + V4_SERVICE(4, ResourceKind.SERVICE, "/services/", IResource::getName); + + private int openShiftVersion; + private final String resourceKind; + private final String urlPart; + private final Function endUrlFunc; + + private OpenShiftConsoleResourceUrls(int version, String resourceKind, String urlPart, + Function endUrlFunc) { + this.openShiftVersion = version; + this.resourceKind = resourceKind; + this.urlPart = urlPart; + this.endUrlFunc = endUrlFunc; + } + + public int getVersion() { + return openShiftVersion; + } + + public String getResType() { + return resourceKind; + } + + public String getUrlPart() { + return urlPart; + } + + public Function getEndUrlFunc() { + return endUrlFunc; + } + } +} diff --git a/src/main/java/com/openshift/internal/restclient/capability/server/ServerTemplateProcessing.java b/src/main/java/com/openshift/internal/restclient/capability/server/ServerTemplateProcessing.java index 4d583965..a3768b85 100644 --- a/src/main/java/com/openshift/internal/restclient/capability/server/ServerTemplateProcessing.java +++ b/src/main/java/com/openshift/internal/restclient/capability/server/ServerTemplateProcessing.java @@ -6,127 +6,41 @@ * * Contributors: Red Hat, Inc. ******************************************************************************/ -package com.openshift.internal.restclient.capability.server; - -import java.util.Collection; -import java.util.Map; -import org.apache.commons.lang.StringUtils; -import org.jboss.dmr.ModelNode; +package com.openshift.internal.restclient.capability.server; -import com.openshift.internal.restclient.OpenShiftAPIVersion; -import com.openshift.internal.restclient.model.KubernetesResource; +import com.openshift.restclient.IApiTypeMapper; import com.openshift.restclient.IClient; import com.openshift.restclient.ResourceKind; import com.openshift.restclient.capability.server.ITemplateProcessing; -import com.openshift.restclient.model.IResource; -import com.openshift.restclient.model.template.IParameter; import com.openshift.restclient.model.template.ITemplate; -/** - * @author Jeff Cantrill - */ public class ServerTemplateProcessing implements ITemplateProcessing { - private IClient client; - - public ServerTemplateProcessing(IClient client){ - this.client = client; - } - - @Override - public boolean isSupported() { - return true; - } - - @Override - public String getName() { - return this.getClass().getSimpleName(); - } - - @SuppressWarnings("unchecked") - @Override - public ITemplate process(ITemplate template, String namespace) { - return client.create(new TemplateConfigAdapter(template, namespace)); - } - - protected static class TemplateConfigAdapter extends KubernetesResource implements ITemplate { - - private ITemplate template; - private String namespace; - - public TemplateConfigAdapter(ITemplate template, String namespace){ - super(new ModelNode(), null, null); - this.template = template; - this.namespace = namespace; - } - - @Override - public String getName() { - return template.getName(); - } - - @Override - public String getNamespace(){ - return namespace; - } - - @Override - public String getKind() { - return ResourceKind.PROCESSED_TEMPLATES; - } - - @Override - public String toString() { - return template.toString(); - } - - @Override - public Collection getItems() { - return template.getItems(); - } + private IClient client; - @Override - public Map getParameters() { - return template.getParameters(); - } + public ServerTemplateProcessing(IClient client) { + this.client = client; + } - @Override - public void updateParameterValues(Collection parameters) { - template.updateParameterValues(parameters); - } - - + @Override + public boolean isSupported() { + IApiTypeMapper mapper = client.adapt(IApiTypeMapper.class); + if (mapper != null) { + return mapper.isSupported(ResourceKind.PROCESSED_TEMPLATES); + } + return false; + } - @Override - public void updateParameter(String key, String value) { - template.updateParameter(key, value); - } + @Override + public String getName() { + return this.getClass().getSimpleName(); + } - @Override - public Map getObjectLabels() { - return template.getObjectLabels(); - } + @Override + public ITemplate process(ITemplate template, String namespace) { + return client.execute("POST", ResourceKind.PROCESSED_TEMPLATES, namespace, null, null, template); - @Override - public void addObjectLabel(String key, String value) { - template.addObjectLabel(key, value); - } + } - @Override - public boolean isMatching(String text) { - if (StringUtils.isEmpty(text)) { - return true; - } - if (text.equals(getNamespace())) { - return true; - } - if (template == null) { - return false; - } - - return template.isMatching(text); - } - - } } diff --git a/src/main/java/com/openshift/internal/restclient/http/CallbackTrustManager.java b/src/main/java/com/openshift/internal/restclient/http/CallbackTrustManager.java deleted file mode 100644 index 638dcd8f..00000000 --- a/src/main/java/com/openshift/internal/restclient/http/CallbackTrustManager.java +++ /dev/null @@ -1,62 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2011 Red Hat, Inc. - * Distributed under license by Red Hat, Inc. All rights reserved. - * This program is made available under the terms of the - * Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * Red Hat, Inc. - initial API and implementation - ******************************************************************************/ -package com.openshift.internal.restclient.http; - -import java.security.cert.CertificateException; -import java.security.cert.X509Certificate; - -import javax.net.ssl.X509TrustManager; - -import com.openshift.internal.util.Assert; - -/** - * A trust manager that calls a callback if the wrapped trustmanager fails to - * validate a given certificate. - * - * @author Andre Dietisheim - * - * @see TrustManagerCallback - */ -public class CallbackTrustManager implements X509TrustManager { - - private X509TrustManager trustManager; - private TrustManagerCallback callback; - - private CallbackTrustManager(X509TrustManager trustManager, TrustManagerCallback callback) { - Assert.isTrue(trustManager != null); - this.trustManager = trustManager; - this.callback = callback; - } - - public X509Certificate[] getAcceptedIssuers() { - return trustManager.getAcceptedIssuers(); - } - - public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException { - try { - trustManager.checkServerTrusted(chain, authType); - } catch (CertificateException e) { - if (callback.allow(chain)) { - throw e; - } - } - } - - public void checkClientTrusted(X509Certificate[] chain, - String authType) throws CertificateException { - trustManager.checkServerTrusted(chain, authType); - } - - public interface TrustManagerCallback { - - public boolean allow(X509Certificate[] chain); - } -} \ No newline at end of file diff --git a/src/main/java/com/openshift/internal/restclient/http/FormUrlEncodedMediaType.java b/src/main/java/com/openshift/internal/restclient/http/FormUrlEncodedMediaType.java deleted file mode 100644 index 541e4573..00000000 --- a/src/main/java/com/openshift/internal/restclient/http/FormUrlEncodedMediaType.java +++ /dev/null @@ -1,120 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2012 Red Hat, Inc. - * Distributed under license by Red Hat, Inc. All rights reserved. - * This program is made available under the terms of the - * Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * Red Hat, Inc. - initial API and implementation - ******************************************************************************/ -package com.openshift.internal.restclient.http; - -import java.io.IOException; -import java.io.OutputStream; -import java.io.UnsupportedEncodingException; -import java.net.URLEncoder; -import java.text.MessageFormat; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import com.openshift.internal.util.URLUtils; -import com.openshift.restclient.http.IHttpConstants; - -/** - * A class that encodes request parameters to formurl-encoded format so that they may get sent to - * the server. There are 4 types that are recognized and correctly encoded: - *
    - *
  • Parameter (key-/value-pair, keys are always strings, values may be - * StringValue, ParameterValueArray, ParameterValueMap))
  • - *
  • StringValue (string value: paramname="value")/li> - *
  • ParameterValueArray (array of values: paramname[]="value"¶mname[]="value")
  • - *
  • ParameterValueMap (map of values: paramname[key]="value"¶mname[key]="value)"
  • - *
- * - * @author Andre Dietisheim - * - * @see IHttpClient#post(java.net.URL, IMediaType, int, - * com.openshift.internal.restclient.http.client.httpclient.request.Parameter...) - * @see IHttpClient#put(java.net.URL, IMediaType, int, - * com.openshift.internal.restclient.http.client.httpclient.request.Parameter...) - * @see IHttpClient#delete(java.net.URL, IMediaType, int, - * com.openshift.internal.restclient.http.client.httpclient.request.Parameter...) - */ -public class FormUrlEncodedMediaType implements IMediaType { - - private static final Logger LOGGER = LoggerFactory.getLogger(FormUrlEncodedMediaType.class); - - private static final String UTF8 = "UTF-8"; - private boolean firstParameter = true; - - @Override - public String getType() { - return IHttpConstants.MEDIATYPE_APPLICATION_FORMURLENCODED; - } - - public void writeTo(ParameterValueMap parameterMap, OutputStream out) throws EncodingException { - // reset for eventual 2nd write - try { - this.firstParameter = true; - for (Parameter parameter : parameterMap.getValue().values()) { - writeTo(parameter.getName(), parameter.getValue(), out); - } - } catch (IOException e) { - throw new EncodingException( - MessageFormat.format("Could not encode parameters {0}", parameterMap.toString()), e); - } - } - - private void writeTo(String name, ParameterValueMap parameterMap, OutputStream out) throws IOException { - for (Parameter parameter : parameterMap.getValue().values()) { - String childName = new StringBuilder() - .append(name) - .append('[').append(parameter.getName()).append(']') - .toString(); - writeTo(childName, parameter.getValue(), out); - } - } - - private void writeTo(String name, ParameterValue value, OutputStream out) throws IOException { - if (StringValue.class.isAssignableFrom(value.getClass())) { - writeTo(name, (StringValue) value, out); - } else if (ParameterValueArray.class.isAssignableFrom(value.getClass())) { - writeTo(name, (ParameterValueArray) value, out); - } else if (ParameterValueMap.class.isAssignableFrom(value.getClass())) { - writeTo(name, (ParameterValueMap) value, out); - } - } - - private void writeTo(String name, ParameterValueArray array, OutputStream out) throws IOException { - String childName = name + "[]"; - for (ParameterValue value : array.getValue()) { - writeTo(childName, value, out); - } - } - - private void writeTo(String name, StringValue stringValue, OutputStream out) throws IOException { - StringBuilder builder = new StringBuilder(); - if (!firstParameter) { - builder.append(IHttpConstants.AMPERSAND); - } else { - firstParameter = false; - } - String value = encode(stringValue.getValue()); - String parameterString = builder - .append(name) - .append(IHttpConstants.EQUALS).append(value) - .toString(); - out.write(parameterString.getBytes()); - LOGGER.trace(out.toString()); - } - - private String encode(String value) throws UnsupportedEncodingException { - if (URLUtils.isUrl(value)) { - // dont encode url payload - return value; - } - return URLEncoder.encode(value, UTF8); - } -} diff --git a/src/main/java/com/openshift/internal/restclient/http/HttpClientException.java b/src/main/java/com/openshift/internal/restclient/http/HttpClientException.java deleted file mode 100644 index b7064b66..00000000 --- a/src/main/java/com/openshift/internal/restclient/http/HttpClientException.java +++ /dev/null @@ -1,42 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2011 Red Hat, Inc. - * Distributed under license by Red Hat, Inc. All rights reserved. - * This program is made available under the terms of the - * Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * Red Hat, Inc. - initial API and implementation - ******************************************************************************/ -package com.openshift.internal.restclient.http; - -/** - * @author André Dietisheim - */ -public class HttpClientException extends RuntimeException { - - private static final long serialVersionUID = 1L; - private int code = -1; - - public HttpClientException(String message, Throwable cause) { - super(message, cause); - } - - public HttpClientException(String message, Throwable cause, int code) { - super(message, cause); - this.code = code; - } - - public HttpClientException(String message) { - super(message); - } - - public HttpClientException(Throwable cause) { - super(cause); - } - - public int getResponseCode() { - return code; - } - -} diff --git a/src/main/java/com/openshift/internal/restclient/http/HttpMethod.java b/src/main/java/com/openshift/internal/restclient/http/HttpMethod.java deleted file mode 100644 index 686a8774..00000000 --- a/src/main/java/com/openshift/internal/restclient/http/HttpMethod.java +++ /dev/null @@ -1,35 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2011 Red Hat, Inc. - * Distributed under license by Red Hat, Inc. All rights reserved. - * This program is made available under the terms of the - * Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * Red Hat, Inc. - initial API and implementation - ******************************************************************************/ -package com.openshift.internal.restclient.http; - -/** - * @author Andre Dietisheim - */ -public enum HttpMethod { - GET, POST, PUT, DELETE, PATCH, HEAD, OPTIONS; - - /** - * hasValue determines if enum can safely convert string to enum value - * - * @param value the value to inspect - * @return true if the value can be safely converted to the enum; false otherwise - */ - public static boolean hasValue(String value) { - HttpMethod[] enumConstants = HttpMethod.class.getEnumConstants(); - for (int i = 0; i < enumConstants.length; i++) { - HttpMethod httpMethod = enumConstants[i]; - if(httpMethod.name().equalsIgnoreCase(value)){ - return true; - } - } - return false; - } -} diff --git a/src/main/java/com/openshift/internal/restclient/http/IMediaType.java b/src/main/java/com/openshift/internal/restclient/http/IMediaType.java deleted file mode 100644 index 04436d42..00000000 --- a/src/main/java/com/openshift/internal/restclient/http/IMediaType.java +++ /dev/null @@ -1,31 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2012 Red Hat, Inc. - * Distributed under license by Red Hat, Inc. All rights reserved. - * This program is made available under the terms of the - * Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * Red Hat, Inc. - initial API and implementation - ******************************************************************************/ -package com.openshift.internal.restclient.http; - -import java.io.OutputStream; - -/** - * - * A media type that encodes and writes request parameters before they get sent by the client. - * - * @author Andre Dietisheim - * - * @see IHttpClient#post(java.net.URL, IMediaType, int, com.openshift.internal.restclient.client.httpclient.request.Parameter...) - * @see IHttpClient#put(java.net.URL, IMediaType, int, com.openshift.internal.restclient.client.httpclient.request.Parameter...) - * @see IHttpClient#delete(java.net.URL, IMediaType, int, com.openshift.internal.restclient.client.httpclient.request.Parameter...) - */ -public interface IMediaType { - - public String getType(); - - public void writeTo(ParameterValueMap parameterMap, OutputStream out) throws EncodingException; - -} diff --git a/src/main/java/com/openshift/internal/restclient/http/InternalServerErrorException.java b/src/main/java/com/openshift/internal/restclient/http/InternalServerErrorException.java deleted file mode 100644 index d17b6e78..00000000 --- a/src/main/java/com/openshift/internal/restclient/http/InternalServerErrorException.java +++ /dev/null @@ -1,27 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2011 Red Hat, Inc. - * Distributed under license by Red Hat, Inc. All rights reserved. - * This program is made available under the terms of the - * Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * Red Hat, Inc. - initial API and implementation - ******************************************************************************/ -package com.openshift.internal.restclient.http; - -/** - * @author André Dietisheim - */ -public class InternalServerErrorException extends HttpClientException { - - private static final long serialVersionUID = 1L; - - public InternalServerErrorException(String message, Throwable cause) { - super(message, cause); - } - - public InternalServerErrorException(String message) { - super(message); - } -} diff --git a/src/main/java/com/openshift/internal/restclient/http/JsonMediaType.java b/src/main/java/com/openshift/internal/restclient/http/JsonMediaType.java deleted file mode 100644 index e192182e..00000000 --- a/src/main/java/com/openshift/internal/restclient/http/JsonMediaType.java +++ /dev/null @@ -1,100 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2012 Red Hat, Inc. - * Distributed under license by Red Hat, Inc. All rights reserved. - * This program is made available under the terms of the - * Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * Red Hat, Inc. - initial API and implementation - ******************************************************************************/ -package com.openshift.internal.restclient.http; - -import java.io.OutputStream; -import java.io.PrintWriter; - -import org.jboss.dmr.ModelNode; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import com.openshift.restclient.http.IHttpConstants; - -/** - * A class that encodes request parameters to json so that they may get sent to - * the server. There are 4 types that are recognized and correctly encoded: - *
    - *
  • Parameter (key-/value-pair, keys are always strings, values may be - * StringValue, ParameterValueArray, ParameterValueMap))
  • - *
  • StringValue (string value, in json: string)/li> - *
  • ParameterValueArray (array of values, in json: array
  • - *
  • ParameterValueMap (map of values, in json: object
  • - *
- * - * @author Andre Dietisheim - * - * @see IHttpClient#post(java.net.URL, IMediaType, int, com.openshift.internal.restclient.http.client.httpclient.request.Parameter...) - * @see IHttpClient#put(java.net.URL, IMediaType, int, com.openshift.internal.restclient.http.client.httpclient.request.Parameter...) - * @see IHttpClient#delete(java.net.URL, IMediaType, int, com.openshift.internal.restclient.http.client.httpclient.request.Parameter...) - */ -public class JsonMediaType implements IMediaType { - - private static final Logger LOGGER = LoggerFactory.getLogger(JsonMediaType.class); - - @Override - public String getType() { - return IHttpConstants.MEDIATYPE_APPLICATION_JSON; - } - - public void writeTo(ParameterValueMap parameterMap, OutputStream out) throws EncodingException { - ModelNode root = new ModelNode(); - for (Parameter parameter : parameterMap.getValue().values()) { - ModelNode property = root.get(parameter.getName()); - create(parameter.getValue(), property); - } - - writeTo(out, root); - log(root); - } - - private void create(ParameterValueMap parameterMap, ModelNode node) { - for (Parameter parameter : parameterMap.getValue().values()) { - ModelNode property = node.get(parameter.getName()); - create(parameter.getValue(), property); - } - } - - private void create(ParameterValue value, ModelNode node) { - if (StringValue.class.isAssignableFrom(value.getClass())) { - create((StringValue) value, node); - } else if (ParameterValueArray.class.isAssignableFrom(value.getClass())) { - create((ParameterValueArray) value, node); - } else if (ParameterValueMap.class.isAssignableFrom(value.getClass())) { - create((ParameterValueMap) value, node); - } - } - - private void create(ParameterValueArray array, ModelNode node) { - for (ParameterValue value : array.getValue()) { - ModelNode member = new ModelNode(); - create(value, member); - node.add(member); - } - } - - private void create(StringValue stringValue, ModelNode node) { - node.set(stringValue.getValue()); - } - - private void writeTo(OutputStream out, ModelNode node) { - PrintWriter writer = new PrintWriter(out); - node.writeJSONString(writer, true); - writer.flush(); - } - - private void log(ModelNode node) { - if (LOGGER.isTraceEnabled()) { - LOGGER.trace(node.toJSONString(true)); - } - } - -} diff --git a/src/main/java/com/openshift/internal/restclient/http/Parameter.java b/src/main/java/com/openshift/internal/restclient/http/Parameter.java deleted file mode 100644 index a23e2c92..00000000 --- a/src/main/java/com/openshift/internal/restclient/http/Parameter.java +++ /dev/null @@ -1,75 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2013 Red Hat, Inc. - * Distributed under license by Red Hat, Inc. All rights reserved. - * This program is made available under the terms of the - * Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * Red Hat, Inc. - initial API and implementation - ******************************************************************************/ -package com.openshift.internal.restclient.http; - -/** - * A parameter wrapper to pass param key/values to the service when executing a - * remote operation from a link. - * - * @author Andre Dietisheim - * - */ -public class Parameter extends ParameterValue> { - - private final String name; - - public Parameter(final String name, final String value) { - this(name, new StringValue(value)); - } - - public Parameter(final String name, final ParameterValue value) { - super(value); - this.name = name; - } - - public String getName() { - return name; - } - - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = prime * result + ((name == null) ? 0 : name.hashCode()); - result = prime * result + ((getValue() == null) ? 0 : getValue().hashCode()); - return result; - } - - @Override - public boolean equals(Object obj) { - if (this == obj) - return true; - if (obj == null) - return false; - if (getClass() != obj.getClass()) - return false; - Parameter other = (Parameter) obj; - if (name == null) { - if (other.name != null) - return false; - } else if (!name.equals(other.name)) - return false; - if (getValue() == null) { - if (other.getValue() != null) - return false; - } else if (!getValue().equals(other.getValue())) - return false; - return true; - } - - @Override - public String toString() { - return "Parameter [" - + "name=" + name - + ", value=" + String.valueOf(getValue()) - + "]"; - } -} diff --git a/src/main/java/com/openshift/internal/restclient/http/ParameterValue.java b/src/main/java/com/openshift/internal/restclient/http/ParameterValue.java deleted file mode 100644 index 380afeec..00000000 --- a/src/main/java/com/openshift/internal/restclient/http/ParameterValue.java +++ /dev/null @@ -1,60 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2011 Red Hat, Inc. - * Distributed under license by Red Hat, Inc. All rights reserved. - * This program is made available under the terms of the - * Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * Red Hat, Inc. - initial API and implementation - ******************************************************************************/ - -package com.openshift.internal.restclient.http; - -/** - * @author Andre Dietisheim - */ -public abstract class ParameterValue { - - private V value; - - public ParameterValue(V value) { - this.value = value; - } - - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = prime * result + ((value == null) ? 0 : value.hashCode()); - return result; - } - - @Override - public boolean equals(Object obj) { - if (this == obj) - return true; - if (obj == null) - return false; - if (getClass() != obj.getClass()) - return false; - @SuppressWarnings("rawtypes") - ParameterValue other = (ParameterValue) obj; - if (value == null) { - if (other.value != null) - return false; - } else if (!value.equals(other.value)) - return false; - return true; - } - - public V getValue() { - return value; - } - - @Override - public String toString() { - return "ParameterValue [value=" + value + "]"; - } -} - diff --git a/src/main/java/com/openshift/internal/restclient/http/ParameterValueArray.java b/src/main/java/com/openshift/internal/restclient/http/ParameterValueArray.java deleted file mode 100644 index 9c5a4947..00000000 --- a/src/main/java/com/openshift/internal/restclient/http/ParameterValueArray.java +++ /dev/null @@ -1,50 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2011 Red Hat, Inc. - * Distributed under license by Red Hat, Inc. All rights reserved. - * This program is made available under the terms of the - * Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * Red Hat, Inc. - initial API and implementation - ******************************************************************************/ -package com.openshift.internal.restclient.http; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; - -/** - * @author Andre Dietisheim - */ -public class ParameterValueArray extends ParameterValue>> { - - public ParameterValueArray() { - this(new ArrayList>()); - } - - public ParameterValueArray(List> values) { - super(values); - } - - public ParameterValueArray add(String name, String value) { - return add(new StringParameter(name, value)); - } - - public ParameterValueArray add(ParameterValue value) { - getValue().add(value); - return this; - } - - public ParameterValueArray addAll(List> values) { - getValue().addAll(values); - return this; - } - - @Override - public String toString() { - return "ParameterValueArray [" - + "values=" + Arrays.toString(getValue().toArray()) + "]"; - } - -} diff --git a/src/main/java/com/openshift/internal/restclient/http/ParameterValueMap.java b/src/main/java/com/openshift/internal/restclient/http/ParameterValueMap.java deleted file mode 100644 index 036b3eef..00000000 --- a/src/main/java/com/openshift/internal/restclient/http/ParameterValueMap.java +++ /dev/null @@ -1,95 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2011 Red Hat, Inc. - * Distributed under license by Red Hat, Inc. All rights reserved. - * This program is made available under the terms of the - * Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * Red Hat, Inc. - initial API and implementation - ******************************************************************************/ -package com.openshift.internal.restclient.http; - -import java.util.Arrays; -import java.util.LinkedHashMap; -import java.util.List; -import java.util.Map; - -import com.openshift.restclient.OpenShiftException; - - -/** - * @author Andre Dietisheim - */ -public class ParameterValueMap extends ParameterValue> { - - public ParameterValueMap(List parameters) { - this(); - addAll(parameters); - } - - public ParameterValueMap(Parameter... parameters) { - this(); - addAll(Arrays.asList(parameters)); - } - - public ParameterValueMap() { - super(new LinkedHashMap()); - } - - public ParameterValueMap addAll(List parameters) { - for (Parameter parameter : parameters) { - add(parameter); - } - return this; - } - - public ParameterValueMap add(String name, String value) { - add(new StringParameter(name, value)); - return this; - } - - public ParameterValueMap add(Parameter parameter) { - if (getValue().put(parameter.getName(), parameter) != null) { - throw new OpenShiftException( - "Duplicate parameter found. There's already a parameter named {0}", parameter.getName()); - } - return this; - } - - public Parameter getParamater(String name) { - return getValue().get(name); - } - - public boolean isEmpty() { - Map values = getValue(); - return values == null - || values.isEmpty(); - } - - @Override - public boolean equals(Object obj) { - if (this == obj) - return true; - if (obj == null) - return false; - if (getClass() != obj.getClass()) - return false; - @SuppressWarnings("rawtypes") - ParameterValue other = (ParameterValue) obj; - if (getValue() == null) { - if (other.getValue() != null) - return false; - } else if (!getValue().equals(other.getValue())) - return false; - return true; - } - - @Override - public String toString() { - return "ParameterValueMap [" - + "values=" + getValue() + "]"; - } - - -} diff --git a/src/main/java/com/openshift/internal/restclient/http/UnauthorizedException.java b/src/main/java/com/openshift/internal/restclient/http/UnauthorizedException.java deleted file mode 100644 index 43d9e09c..00000000 --- a/src/main/java/com/openshift/internal/restclient/http/UnauthorizedException.java +++ /dev/null @@ -1,28 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2011 Red Hat, Inc. - * Distributed under license by Red Hat, Inc. All rights reserved. - * This program is made available under the terms of the - * Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * Red Hat, Inc. - initial API and implementation - ******************************************************************************/ -package com.openshift.internal.restclient.http; - -/** - * @author André Dietisheim - */ -public class UnauthorizedException extends HttpClientException { - - private static final long serialVersionUID = 1L; - - public UnauthorizedException(String message, Throwable cause) { - super(message, cause); - } - - public UnauthorizedException(Throwable cause) { - super(cause); - } - -} diff --git a/src/main/java/com/openshift/internal/restclient/http/UrlConnectionHttpClient.java b/src/main/java/com/openshift/internal/restclient/http/UrlConnectionHttpClient.java deleted file mode 100755 index b3dee93b..00000000 --- a/src/main/java/com/openshift/internal/restclient/http/UrlConnectionHttpClient.java +++ /dev/null @@ -1,601 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2013-2014 Red Hat, Inc. - * Distributed under license by Red Hat, Inc. All rights reserved. - * This program is made available under the terms of the - * Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * Red Hat, Inc. - initial API and implementation - ******************************************************************************/ -package com.openshift.internal.restclient.http; - -import java.io.IOException; -import java.io.PrintWriter; -import java.net.HttpURLConnection; -import java.net.InetAddress; -import java.net.ProtocolException; -import java.net.Socket; -import java.net.SocketTimeoutException; -import java.net.URL; -import java.net.URLConnection; -import java.net.UnknownHostException; -import java.security.GeneralSecurityException; -import java.security.KeyStore; -import java.security.KeyStoreException; -import java.security.NoSuchAlgorithmException; -import java.security.cert.CertificateException; -import java.security.cert.X509Certificate; -import java.text.MessageFormat; - -import javax.net.ssl.HostnameVerifier; -import javax.net.ssl.HttpsURLConnection; -import javax.net.ssl.SSLContext; -import javax.net.ssl.SSLSession; -import javax.net.ssl.SSLSocket; -import javax.net.ssl.SSLSocketFactory; -import javax.net.ssl.TrustManager; -import javax.net.ssl.TrustManagerFactory; -import javax.net.ssl.X509TrustManager; - -import org.apache.commons.io.IOUtils; -import org.apache.commons.lang.StringUtils; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import com.openshift.restclient.ISSLCertificateCallback; -import com.openshift.restclient.authorization.IAuthorizationStrategy; -import com.openshift.restclient.authorization.URLConnectionRequest; -import com.openshift.restclient.http.IHttpClient; -import com.openshift.restclient.http.IHttpConstants; -import com.openshift.restclient.model.IResource; -import com.openshift.restclient.utils.SSLUtils; - -/** - * @author Andre Dietisheim - * @author Nicolas Spano - * @author Corey Daley - * @author Sean Kavanagh - */ -public class UrlConnectionHttpClient implements IHttpClient { - - private static final Logger LOGGER = LoggerFactory.getLogger(UrlConnectionHttpClient.class); - - protected String userAgent; - protected String acceptedMediaType; - protected String acceptedVersion; - protected ISSLCertificateCallback sslAuthorizationCallback; - protected Integer configTimeout; - private String excludedSSLCipherRegex; - private IAuthorizationStrategy authStrategy; - - private TrustManagerFactory trustManagerFactory; - private NoSuchAlgorithmException trustManagerFactoryException; - - public UrlConnectionHttpClient(String userAgent, String acceptedMediaType, String version){ - this(userAgent, acceptedMediaType, version, null, null, null); - } - - public UrlConnectionHttpClient(String userAgent, String acceptedMediaType, - String version, ISSLCertificateCallback callback, Integer configTimeout, String excludedSSLCipherRegex) { - this(userAgent, acceptedMediaType, version, callback, configTimeout, excludedSSLCipherRegex, null, null); - } - - public UrlConnectionHttpClient(String userAgent, String acceptedMediaType, - String version, ISSLCertificateCallback callback, Integer configTimeout, String excludedSSLCipherRegex, - String alias, X509Certificate cert) { - this.userAgent = userAgent; - this.acceptedMediaType = acceptedMediaType; - this.acceptedVersion = version; - this.sslAuthorizationCallback = callback; - this.configTimeout = configTimeout; - this.excludedSSLCipherRegex = excludedSSLCipherRegex; - this.initTrustManagerFactory(alias, cert); - } - - private void initTrustManagerFactory(String alias, X509Certificate cert) { - try { - trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()); - if (alias != null && cert != null) { - KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType()); - // need this load to initialize the key store, and allow for the subsequent set certificate entry - ks.load(null, null); - cert.checkValidity(); - ks.setCertificateEntry(alias, cert); - // testing has proven that you can only call init() once for a TrustManagerFactory wrt loading certs - // from the KeyStore ... subsequent KeyStore.setCertificateEntry / TrustManagerFactory.init calls are - // ignored. - // So if a specific cert is required to validate this connection's communication with the server, add it up front - // in the ctor. - trustManagerFactory.init(ks); - } else { - trustManagerFactory.init((KeyStore)null); - } - - } catch (NoSuchAlgorithmException e) { - LOGGER.warn("Could not get trust manager factory.", e); - trustManagerFactoryException = e; - } catch (KeyStoreException e) { - LOGGER.warn("Count not get key store.", e); - } catch (CertificateException e) { - LOGGER.warn("An invalid certificate was provided to this connection.", e); - } catch (IOException e) { - LOGGER.warn("An IO exception occurred while setting up a cert with the trust store.", e); - } - } - - // not part of IHttpClient currently, only put in place for test verification - public X509Certificate[] getTrustedCertificates() throws KeyStoreException, NoSuchAlgorithmException { - return getCurrentTrustManager().getAcceptedIssuers(); - } - - @Override - public void setSSLCertificateCallback(ISSLCertificateCallback callback) { - this.sslAuthorizationCallback = callback; - } - - @Override - public ISSLCertificateCallback getSSLCertificateCallback() { - return sslAuthorizationCallback; - } - - @Override - public void setAuthorizationStrategy(IAuthorizationStrategy strategy) { - this.authStrategy = strategy; - } - - @Override - public String get(URL url, int timeout) throws HttpClientException, SocketTimeoutException { - return request(HttpMethod.GET, url, null, timeout); - } - - @Override - public String head(URL url, int timeout) throws HttpClientException, SocketTimeoutException { - return request(HttpMethod.HEAD, url, null, timeout); - } - - public String put(URL url, IMediaType mediaType, int timeout, Parameter... parameters) - throws HttpClientException, SocketTimeoutException, EncodingException { - return request(HttpMethod.PUT, url, mediaType, timeout, parameters); - } - - @Override - public String put(URL url, int timeout, IResource resource) - throws HttpClientException, SocketTimeoutException, EncodingException { - return request(HttpMethod.PUT, url, timeout, resource); - } - - @Override - public String post(URL url, int timeout, IResource resource) throws HttpClientException, SocketTimeoutException, EncodingException { - return request(HttpMethod.POST, url, timeout, resource); - } - - public String delete(URL url, IMediaType mediaType, int timeout, Parameter... parameters) - throws HttpClientException, SocketTimeoutException, EncodingException { - return request(HttpMethod.DELETE, url, mediaType, timeout, parameters); - } - - @Override - public String delete(URL url, int timeout) - throws HttpClientException, SocketTimeoutException, EncodingException { - return delete(url, null, timeout); - } - - protected String request(HttpMethod httpMethod, URL url, IMediaType requestMediaType, int timeout, - Parameter... parameters) - throws SocketTimeoutException, HttpClientException { - return request(httpMethod, url, requestMediaType, timeout, new ParameterValueMap(parameters)); - } - - protected String request(HttpMethod httpMethod, URL url, IMediaType requestMediaType, int timeout, - ParameterValueMap parameters) - throws SocketTimeoutException, HttpClientException { - HttpURLConnection connection = null; - try { - connection = createConnection( - url, userAgent, acceptedVersion, acceptedMediaType, sslAuthorizationCallback, timeout); - if (httpMethod == HttpMethod.POST || httpMethod == HttpMethod.PUT) { - setContentTypeHeader(acceptedVersion, acceptedMediaType, connection); - } - // PATCH not yet supported by JVM - setRequestMethod(httpMethod, connection); - if (!parameters.isEmpty()) { - connection.setDoOutput(true); - setRequestMediaType(requestMediaType, connection); - requestMediaType.writeTo(parameters, connection.getOutputStream()); - } - return IOUtils.toString(connection.getInputStream(), "UTF-8"); - } catch (SocketTimeoutException e) { - throw e; - } catch (IOException e) { - throw createException(e, connection); - } finally { - disconnect(connection); - } - } - - protected String request(HttpMethod httpMethod, URL url, int timeout, IResource resource) - throws SocketTimeoutException, HttpClientException { - HttpURLConnection connection = null; - try { - connection = createConnection( - url, userAgent, acceptedVersion, acceptedMediaType, sslAuthorizationCallback, timeout); - if (httpMethod == HttpMethod.POST || httpMethod == HttpMethod.PUT) { - setContentTypeHeader(acceptedVersion, acceptedMediaType, connection); - } - // PATCH not yet supported by JVM - setRequestMethod(httpMethod, connection); - if(LOGGER.isDebugEnabled()) { - LOGGER.debug(String.format("Request Properties: %s", connection.getRequestProperties())); - LOGGER.debug(String.format("Request Method: %s", connection.getRequestMethod())); - } - if(resource != null){ - if(LOGGER.isDebugEnabled()) LOGGER.debug(resource.toJson(false)); - connection.setDoOutput(true); - PrintWriter writer = new PrintWriter(connection.getOutputStream()); - writer.write(resource.toString()); - writer.flush(); - } - return IOUtils.toString(connection.getInputStream(), "UTF-8"); - } catch (SocketTimeoutException e) { - throw e; - } catch (IOException e) { - throw createException(e, connection); - } finally { - disconnect(connection); - } - } - - private void setRequestMethod(HttpMethod httpMethod, HttpURLConnection connection) throws ProtocolException { - if (httpMethod == HttpMethod.PATCH) { - httpMethod = HttpMethod.POST; - connection.setRequestProperty("X-Http-Method-Override", "PATCH"); - } - connection.setRequestMethod(httpMethod.toString()); - } - - private void disconnect(HttpURLConnection connection) { - if (connection != null) { - connection.disconnect(); - } - } - - private HttpClientException createException(IOException ioe, HttpURLConnection connection) - throws SocketTimeoutException { - try { - int responseCode = connection.getResponseCode(); - String errorMessage = createErrorMessage(ioe, connection); - switch (responseCode) { - case IHttpConstants.STATUS_INTERNAL_SERVER_ERROR: - return new InternalServerErrorException(errorMessage, ioe); - case IHttpConstants.STATUS_BAD_REQUEST: - return new BadRequestException(errorMessage, ioe); - case IHttpConstants.STATUS_UNAUTHORIZED: - return new UnauthorizedException(errorMessage, ioe); - case IHttpConstants.STATUS_NOT_FOUND: - return new NotFoundException(errorMessage, ioe); - default: - return new HttpClientException(errorMessage, ioe, responseCode); - } - } catch (SocketTimeoutException e) { - throw e; - } catch (IOException e) { - return new HttpClientException(e); - } - } - - protected String createErrorMessage(IOException ioe, HttpURLConnection connection) throws IOException { - String errorMessage = IOUtils.toString(connection.getErrorStream()); - if (!StringUtils.isEmpty(errorMessage)) { - return errorMessage; - } - StringBuilder builder = new StringBuilder("Connection to ") - .append(connection.getURL()); - String reason = connection.getResponseMessage(); - if (!StringUtils.isEmpty(reason)) { - builder.append(": ").append(reason); - } - return builder.toString(); - } - - private boolean isHttps(URL url) { - return "https".equals(url.getProtocol()); - } - - protected HttpURLConnection createConnection(URL url, String userAgent, String acceptedVersion, String acceptedMediaType, - ISSLCertificateCallback callback, int timeout) - throws IOException { - HttpURLConnection connection = (HttpURLConnection) url.openConnection(); - if (isHttps(url)) { - HttpsURLConnection httpsConnection = (HttpsURLConnection) connection; - SSLContext sslContext = setSSLCallback(sslAuthorizationCallback, url, httpsConnection); - setFilteredCiphers(excludedSSLCipherRegex, sslContext, httpsConnection); - } - setAuthorization(connection); - connection.setUseCaches(false); - connection.setDoInput(true); - connection.setAllowUserInteraction(false); - setConnectTimeout(NO_TIMEOUT, connection); - setReadTimeout(timeout, connection); - // wont work when switching http->https - // http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4620571 - connection.setInstanceFollowRedirects(true); - setUserAgent(userAgent, connection); - setAcceptHeader(acceptedVersion, acceptedMediaType, connection); - - return connection; - } - - private void setUserAgent(String userAgent, HttpURLConnection connection) { - if (!StringUtils.isEmpty(userAgent)) { - connection.setRequestProperty(IHttpConstants.PROPERTY_USER_AGENT, userAgent); - } - } - - private void setAcceptHeader(String acceptedVersion, String acceptedMediaType, HttpURLConnection connection) { - if (StringUtils.isEmpty(acceptedMediaType)) { - throw new HttpClientException(MessageFormat.format( - "Accepted media type (ex. {0}) is not defined", IHttpConstants.MEDIATYPE_APPLICATION_JSON)); - } - - StringBuilder builder = new StringBuilder(acceptedMediaType); - if (acceptedVersion != null) { - builder.append(IHttpConstants.SEMICOLON).append(IHttpConstants.SPACE) - .append(IHttpConstants.VERSION).append(IHttpConstants.EQUALS).append(acceptedVersion); - } - - connection.setRequestProperty(IHttpConstants.PROPERTY_ACCEPT, builder.toString()); - } - - private void setContentTypeHeader(String version, String mediaType, HttpURLConnection connection) { - if (StringUtils.isEmpty(mediaType)) { - throw new HttpClientException(MessageFormat.format( - "Accepted media type (ex. {0}) is not defined", IHttpConstants.MEDIATYPE_APPLICATION_JSON)); - } - - StringBuilder builder = new StringBuilder(mediaType); - if (acceptedVersion != null) { - builder.append(IHttpConstants.SEMICOLON).append(IHttpConstants.SPACE) - .append(IHttpConstants.VERSION).append(IHttpConstants.EQUALS).append(version); - } - - connection.setRequestProperty(IHttpConstants.PROPERTY_CONTENT_TYPE, builder.toString()); - } - - protected final void setAuthorization(HttpURLConnection connection) { - if(authStrategy != null){ - authStrategy.authorize(new URLConnectionRequest(connection)); - return; - } - } - - private SSLContext setSSLCallback(ISSLCertificateCallback sslAuthorizationCallback, URL url, HttpsURLConnection connection) { - X509TrustManager trustManager = null; - if (sslAuthorizationCallback != null) { - connection.setHostnameVerifier(new CallbackHostnameVerifier()); - trustManager = createCallbackTrustManager(sslAuthorizationCallback, connection); - } - - try { - SSLContext sslContext = SSLUtils.getSSLContext(trustManager); - connection.setSSLSocketFactory(sslContext.getSocketFactory()); - return sslContext; - } catch (GeneralSecurityException e) { - LOGGER.warn("Could not install trust manager callback", e);; - return null; - } - } - - /** - * Returns the callback trustmanager or null if it could not be created. - * - * @see ISSLCertificateCallback - */ - private X509TrustManager createCallbackTrustManager(ISSLCertificateCallback sslAuthorizationCallback,HttpsURLConnection connection) { - X509TrustManager trustManager = null; - try { - trustManager = getCurrentTrustManager(); - if (trustManager == null) { - LOGGER.warn("Could not install trust manager callback, no trustmanager was found.", trustManager); - } else { - trustManager = new CallbackTrustManager(trustManager, sslAuthorizationCallback); - } - } catch (GeneralSecurityException e) { - LOGGER.warn("Could not install trust manager callback.", e);; - } - return trustManager; - } - - /** - * Sets a ssl socket factory that sets a filtered list of ciphers based on - * the #excludedSSLCipherRegex to the given connection. - * - * @param sslContext - * - * @param sslContext - * the ssl context that shall be used - * @param url - * the url we are connecting to - * @param connection - * the connection that the cipher filter shall be applied to - */ - protected SSLContext setFilteredCiphers(String excludedSSLCipherRegex, SSLContext sslContext, HttpsURLConnection connection) { - if (excludedSSLCipherRegex != null) { - connection.setSSLSocketFactory( - new EnabledCiphersSSLSocketFactory( - SSLUtils.filterCiphers( - excludedSSLCipherRegex, getSupportedCiphers(sslContext)), sslContext - .getSocketFactory())); - } - return sslContext; - } - - protected String[] getSupportedCiphers(SSLContext sslContext) { - return sslContext.getSupportedSSLParameters().getCipherSuites(); - } - - private void setConnectTimeout(int timeout, URLConnection connection) { - if (getTimeout(timeout) != NO_TIMEOUT) { - connection.setConnectTimeout(getTimeout(timeout)); - } - } - - private void setReadTimeout(int timeout, URLConnection connection) { - if (getTimeout(timeout) != NO_TIMEOUT) { - connection.setReadTimeout(getTimeout(timeout)); - } - } - - private int getTimeout(int timeout) { - if (timeout == NO_TIMEOUT) { - if (configTimeout != null) { - timeout = this.configTimeout; - } - } - return timeout; - } - - private void setRequestMediaType(IMediaType mediaType, HttpURLConnection connection) { - if (mediaType == null - || StringUtils.isEmpty(mediaType.getType())) { - throw new HttpClientException( - MessageFormat.format("Request media type (ex. {0}) is not defined", - IHttpConstants.MEDIATYPE_APPLICATION_FORMURLENCODED)); - } - connection.setRequestProperty(IHttpConstants.PROPERTY_CONTENT_TYPE, mediaType.getType()); - } - - private X509TrustManager getCurrentTrustManager() throws NoSuchAlgorithmException, KeyStoreException { - if (trustManagerFactoryException != null) - throw trustManagerFactoryException; - - X509TrustManager x509TrustManager = null; - for (TrustManager trustManager : trustManagerFactory.getTrustManagers()) { - if (trustManager instanceof X509TrustManager) { - x509TrustManager = (X509TrustManager) trustManager; - break; - } - } - return x509TrustManager; - - } - - @Override - public void setUserAgent(String userAgent) { - this.userAgent = userAgent; - } - - @Override - public void setAcceptVersion(String version) { - this.acceptedVersion = version; - } - - @Override - public void setAcceptedMediaType(String acceptedMediaType) { - this.acceptedMediaType = acceptedMediaType; - } - - public class CallbackTrustManager implements X509TrustManager { - - private X509TrustManager trustManager; - private ISSLCertificateCallback callback; - - private CallbackTrustManager(X509TrustManager currentTrustManager, ISSLCertificateCallback callback) - throws NoSuchAlgorithmException, KeyStoreException { - this.trustManager = currentTrustManager; - this.callback = callback; - } - - public X509Certificate[] getAcceptedIssuers() { - return trustManager.getAcceptedIssuers(); - } - - public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException { - try { - trustManager.checkServerTrusted(chain, authType); - } catch (CertificateException e) { - if (!callback.allowCertificate(chain)) { - throw e; - } - } - } - - public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException { - trustManager.checkServerTrusted(chain, authType); - } - } - - private class CallbackHostnameVerifier implements HostnameVerifier { - - @Override - public boolean verify(String hostname, SSLSession session) { - return sslAuthorizationCallback.allowHostname(hostname, session); - } - } - - /** - * SSL socket factory that wraps a given socket factory and sets given ciphers - * to the socket that the wrapped factory creates. - * - * @see http://stackoverflow.com/questions/6851461/java-why-does-ssl-handshake-give-could-not-generate-dh-keypair-exception/16686994#16686994 - */ - private static class EnabledCiphersSSLSocketFactory extends SSLSocketFactory { - - private String[] enabledCiphers; - private SSLSocketFactory socketFactory; - - EnabledCiphersSSLSocketFactory(String[] enabledCiphers, SSLSocketFactory socketFactory) { - this.enabledCiphers = enabledCiphers; - this.socketFactory = socketFactory; - } - - @Override - public Socket createSocket(InetAddress host, int port, InetAddress localHost, int localPort) throws IOException { - return setEnabledCiphers((SSLSocket) socketFactory.createSocket(host, port, localHost, localPort)); - } - - @Override - public Socket createSocket(String host, int port, InetAddress localHost, int localPort) - throws IOException, UnknownHostException { - return setEnabledCiphers((SSLSocket) socketFactory.createSocket(host, port, localHost, localPort)); - } - - @Override - public Socket createSocket(InetAddress host, int port) throws IOException { - return setEnabledCiphers((SSLSocket) socketFactory.createSocket(host, port)); - } - - @Override - public Socket createSocket(String host, int port) throws IOException, UnknownHostException { - return setEnabledCiphers((SSLSocket) socketFactory.createSocket(host, port)); - } - - @Override - public String[] getSupportedCipherSuites() { - if (enabledCiphers == null) { - return socketFactory.getSupportedCipherSuites(); - } else { - return enabledCiphers; - } - } - - @Override - public String[] getDefaultCipherSuites() { - return socketFactory.getDefaultCipherSuites(); - } - - @Override - public Socket createSocket(Socket socket, String host, int port, boolean autoClose) throws IOException { - return setEnabledCiphers((SSLSocket) socketFactory.createSocket(socket, host, port, autoClose)); - } - - private SSLSocket setEnabledCiphers(SSLSocket socket) { - if (enabledCiphers == null) { - return socket; - } - socket.setEnabledCipherSuites(enabledCiphers); - return socket; - } - } - -} diff --git a/src/main/java/com/openshift/internal/restclient/http/UrlConnectionHttpClientBuilder.java b/src/main/java/com/openshift/internal/restclient/http/UrlConnectionHttpClientBuilder.java deleted file mode 100755 index 24aeca31..00000000 --- a/src/main/java/com/openshift/internal/restclient/http/UrlConnectionHttpClientBuilder.java +++ /dev/null @@ -1,88 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2012-2014 Red Hat, Inc. - * Distributed under license by Red Hat, Inc. All rights reserved. - * This program is made available under the terms of the - * Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * Red Hat, Inc. - initial API and implementation - ******************************************************************************/ -package com.openshift.internal.restclient.http; - -import java.security.cert.X509Certificate; - -import com.openshift.restclient.ISSLCertificateCallback; -import com.openshift.restclient.authorization.BasicAuthorizationStrategy; -import com.openshift.restclient.authorization.IAuthorizationStrategy; -import com.openshift.restclient.http.IHttpClient; - -/** - * @author André Dietisheim - * @author Corey Daley - * @author Sean Kavanagh - */ -public class UrlConnectionHttpClientBuilder { - - private String userAgent; - private String acceptedMediaType; - private String version; - private Integer configTimeout; - private ISSLCertificateCallback callback; - private String certificateAlias; - private X509Certificate certificate; - private String excludeSSLCipherRegex; - private IAuthorizationStrategy authStrategy; - - public UrlConnectionHttpClientBuilder setUserAgent(String userAgent) { - this.userAgent = userAgent; - return this; - } - - public UrlConnectionHttpClientBuilder setAuthorizationStrategy(IAuthorizationStrategy strategy){ - this.authStrategy = strategy; - return this; - } - - public UrlConnectionHttpClientBuilder setCredentials(String username, String password, String token) { - return setAuthorizationStrategy(new BasicAuthorizationStrategy(username, password, token)); - } - - public UrlConnectionHttpClientBuilder setCertificate(String alias, X509Certificate cert) { - this.certificateAlias = alias; - this.certificate = cert; - return this; - } - - public UrlConnectionHttpClientBuilder setConfigTimeout (Integer configTimeout) { - this.configTimeout = configTimeout; - return this; - } - - public UrlConnectionHttpClientBuilder setAcceptMediaType(String mediaType) { - this.acceptedMediaType = mediaType; - return this; - } - - public UrlConnectionHttpClientBuilder setSSLCertificateCallback(ISSLCertificateCallback callback) { - this.callback = callback; - return this; - } - - public UrlConnectionHttpClientBuilder setVersion(String version) { - this.version = version; - return this; - } - - public UrlConnectionHttpClientBuilder excludeSSLCipher(String excludeSSLCipherRegex) { - this.excludeSSLCipherRegex = excludeSSLCipherRegex; - return this; - } - - public IHttpClient client() { - UrlConnectionHttpClient urlClient = new UrlConnectionHttpClient( - userAgent, acceptedMediaType, version, callback, configTimeout, excludeSSLCipherRegex, certificateAlias, certificate); - urlClient.setAuthorizationStrategy(authStrategy); - return urlClient; - } -} diff --git a/src/main/java/com/openshift/internal/restclient/model/Build.java b/src/main/java/com/openshift/internal/restclient/model/Build.java index 5b337ea4..8a1a676d 100644 --- a/src/main/java/com/openshift/internal/restclient/model/Build.java +++ b/src/main/java/com/openshift/internal/restclient/model/Build.java @@ -1,22 +1,30 @@ /******************************************************************************* - * Copyright (c) 2015 Red Hat, Inc. Distributed under license by Red Hat, Inc. + * Copyright (c) 2015-2018 Red Hat, Inc. Distributed under license by Red Hat, Inc. * All rights reserved. This program is made available under the terms of the * Eclipse Public License v1.0 which accompanies this distribution, and is * available at http://www.eclipse.org/legal/epl-v10.html * * Contributors: Red Hat, Inc. ******************************************************************************/ + package com.openshift.internal.restclient.model; +import static com.openshift.internal.restclient.model.BuildConfig.BUILDCONFIG_SOURCE_BINARY_ASFILE; +import static com.openshift.internal.restclient.model.BuildConfig.BUILDCONFIG_SOURCE_CONTEXTDIR; +import static com.openshift.internal.restclient.model.BuildConfig.BUILDCONFIG_SOURCE_REF; +import static com.openshift.internal.restclient.model.BuildConfig.BUILDCONFIG_SOURCE_URI; + import java.util.Map; import org.jboss.dmr.ModelNode; import com.openshift.internal.restclient.capability.CapabilityInitializer; +import com.openshift.internal.restclient.model.build.BinaryBuildSource; import com.openshift.internal.restclient.model.build.BuildStatus; import com.openshift.internal.restclient.model.build.CustomBuildStrategy; import com.openshift.internal.restclient.model.build.DockerBuildStrategy; import com.openshift.internal.restclient.model.build.GitBuildSource; +import com.openshift.internal.restclient.model.build.JenkinsPipelineStrategy; import com.openshift.internal.restclient.model.build.SourceBuildStrategy; import com.openshift.restclient.IClient; import com.openshift.restclient.images.DockerImageURI; @@ -27,110 +35,108 @@ import com.openshift.restclient.model.build.IBuildStatus; import com.openshift.restclient.model.build.IBuildStrategy; -/** - * @author Jeff Cantrill - */ -public class Build extends KubernetesResource implements IBuild{ - - private static final String BUILD_MESSAGE = "status.message"; - private static final String BUILD_PODNAME = "podName"; - private static final String BUILD_STATUS = "status.phase"; - private static final String BUILD_STATUS_CANCELLED = "status.cancelled"; - private static final String OUTPUT_KIND = "spec.output.to.kind"; - private static final String OUTPUT_NAME = "spec.output.to.name"; - - private static final String COMPLETE = "Complete"; - private static final String FAILED = "Failed"; - private static final String CANCELLED = "Cancelled"; - private Map propertyKeys; - - - public Build(ModelNode node, IClient client, Map propertyKeys) { - super(node, client, propertyKeys); - this.propertyKeys = propertyKeys; - CapabilityInitializer.initializeCapabilities(getModifiableCapabilities(), this, client); - } - - @Override - public String getStatus() { - return asString(BUILD_STATUS); - } - - @Override - public String getMessage() { - return asString(BUILD_MESSAGE); - } - - @Override - public String getPodName() { - return asString(BUILD_PODNAME); - } - - @Override - public boolean cancel() { - String currentStatus = getStatus(); - if (!currentStatus.equalsIgnoreCase(COMPLETE) && !currentStatus.equalsIgnoreCase(FAILED) && !currentStatus.equalsIgnoreCase(CANCELLED)) { - set(BUILD_STATUS_CANCELLED, true); - return true; - } - return false; - } - - @Override - public DockerImageURI getOutputTo() { - return new DockerImageURI(asString(OUTPUT_NAME)); - } - - @Override - public String getOutputKind() { - return asString(OUTPUT_KIND); - } - - @SuppressWarnings("unchecked") - @Override - public T getBuildSource() { - switch(asString("spec.source.type")){ - case BuildSourceType.GIT: - return (T) new GitBuildSource(asString("spec.source.git.uri"), asString("spec.source.git.ref"), asString("spec.source.git.contextDir")); - default: - } - return null; - } - - @SuppressWarnings("unchecked") - public T getBuildStrategy() { - switch(asString("spec.strategy.type")){ - case BuildStrategyType.CUSTOM: - return (T) new CustomBuildStrategy( - asString("spec.strategy.customStrategy.image"), - asBoolean("spec.strategy.customStrategy.exposeDockerSocket"), - getEnvMap("spec.strategy.customStrategy.env") - ); - case BuildStrategyType.SOURCE: - return (T) new SourceBuildStrategy(get("spec.strategy"), getPropertyKeys()); - - case BuildStrategyType.DOCKER: - - return (T) new DockerBuildStrategy( - asString("spec.strategy.dockerStrategy.contextDir"), - asBoolean("spec.strategy.dockerStrategy.noCache"), - asString("spec.strategy.dockerStrategy.baseImage") - ); - default: - } - return null; - } - - @Override - public String getPushSecret() { - return asString("spec.output.pushSecret.name"); - } - - @Override - public IBuildStatus getBuildStatus() { - return new BuildStatus(get("status"), this.propertyKeys); - } - - - +public class Build extends KubernetesResource implements IBuild { + + private static final String BUILD_MESSAGE = "status.message"; + private static final String BUILD_PODNAME = "podName"; + private static final String BUILD_STATUS = "status.phase"; + private static final String BUILD_STATUS_CANCELLED = "status.cancelled"; + private static final String OUTPUT_KIND = "spec.output.to.kind"; + private static final String OUTPUT_NAME = "spec.output.to.name"; + + private static final String COMPLETE = "Complete"; + private static final String FAILED = "Failed"; + private static final String CANCELLED = "Cancelled"; + private Map propertyKeys; + + public Build(ModelNode node, IClient client, Map propertyKeys) { + super(node, client, propertyKeys); + this.propertyKeys = propertyKeys; + CapabilityInitializer.initializeCapabilities(getModifiableCapabilities(), this, client); + } + + @Override + public String getStatus() { + return asString(BUILD_STATUS); + } + + @Override + public String getMessage() { + return asString(BUILD_MESSAGE); + } + + @Override + public String getPodName() { + return asString(BUILD_PODNAME); + } + + @Override + public boolean cancel() { + String currentStatus = getStatus(); + if (!currentStatus.equalsIgnoreCase(COMPLETE) && !currentStatus.equalsIgnoreCase(FAILED) + && !currentStatus.equalsIgnoreCase(CANCELLED)) { + set(BUILD_STATUS_CANCELLED, true); + return true; + } + return false; + } + + @Override + public DockerImageURI getOutputTo() { + return new DockerImageURI(asString(OUTPUT_NAME)); + } + + @Override + public String getOutputKind() { + return asString(OUTPUT_KIND); + } + + @SuppressWarnings("unchecked") + @Override + public T getBuildSource() { + switch (asString("spec.source.type")) { + case BuildSourceType.GIT: + return (T) new GitBuildSource(asString(BUILDCONFIG_SOURCE_URI), asString(BUILDCONFIG_SOURCE_REF), + asString(BUILDCONFIG_SOURCE_CONTEXTDIR)); + case BuildSourceType.BINARY: + return (T) new BinaryBuildSource(asString(BUILDCONFIG_SOURCE_BINARY_ASFILE), asString(BUILDCONFIG_SOURCE_CONTEXTDIR)); + default: + } + return null; + } + + @SuppressWarnings("unchecked") + public T getBuildStrategy() { + switch (asString("spec.strategy.type")) { + + case BuildStrategyType.CUSTOM: + return (T) new CustomBuildStrategy(asString("spec.strategy.customStrategy.image"), + asBoolean("spec.strategy.customStrategy.exposeDockerSocket"), + getEnvMap("spec.strategy.customStrategy.env")); + case BuildStrategyType.SOURCE: + return (T) new SourceBuildStrategy(get("spec.strategy"), getPropertyKeys()); + + case BuildStrategyType.DOCKER: + return (T) new DockerBuildStrategy(asString("spec.strategy.dockerStrategy.contextDir"), + asBoolean("spec.strategy.dockerStrategy.noCache"), + asString("spec.strategy.dockerStrategy.baseImage")); + + case BuildStrategyType.JENKINS_PIPELINE: + return (T) new JenkinsPipelineStrategy(get("spec.strategy"), getPropertyKeys()); + + default: + } + return null; + } + + @Override + public String getPushSecret() { + return asString("spec.output.pushSecret.name"); + } + + @Override + public IBuildStatus getBuildStatus() { + return new BuildStatus(get("status"), this.propertyKeys); + } + } diff --git a/src/main/java/com/openshift/internal/restclient/model/BuildConfig.java b/src/main/java/com/openshift/internal/restclient/model/BuildConfig.java index b376d362..961f51a0 100644 --- a/src/main/java/com/openshift/internal/restclient/model/BuildConfig.java +++ b/src/main/java/com/openshift/internal/restclient/model/BuildConfig.java @@ -1,11 +1,12 @@ /******************************************************************************* - * Copyright (c) 2015 Red Hat, Inc. Distributed under license by Red Hat, Inc. + * Copyright (c) 2015-2018 Red Hat, Inc. Distributed under license by Red Hat, Inc. * All rights reserved. This program is made available under the terms of the * Eclipse Public License v1.0 which accompanies this distribution, and is * available at http://www.eclipse.org/legal/epl-v10.html * * Contributors: Red Hat, Inc. ******************************************************************************/ + package com.openshift.internal.restclient.model; import java.util.ArrayList; @@ -16,20 +17,21 @@ import org.jboss.dmr.ModelNode; import com.openshift.internal.restclient.capability.CapabilityInitializer; +import com.openshift.internal.restclient.model.build.BinaryBuildSource; import com.openshift.internal.restclient.model.build.CustomBuildStrategy; import com.openshift.internal.restclient.model.build.DockerBuildStrategy; import com.openshift.internal.restclient.model.build.GitBuildSource; import com.openshift.internal.restclient.model.build.ImageChangeTrigger; -import com.openshift.internal.restclient.model.build.STIBuildStrategy; +import com.openshift.internal.restclient.model.build.JenkinsPipelineStrategy; import com.openshift.internal.restclient.model.build.SourceBuildStrategy; import com.openshift.internal.restclient.model.build.WebhookTrigger; import com.openshift.restclient.IClient; -import com.openshift.restclient.images.DockerImageURI; import com.openshift.restclient.model.IBuildConfig; import com.openshift.restclient.model.IObjectReference; import com.openshift.restclient.model.build.BuildSourceType; import com.openshift.restclient.model.build.BuildStrategyType; import com.openshift.restclient.model.build.BuildTriggerType; +import com.openshift.restclient.model.build.IBinaryBuildSource; import com.openshift.restclient.model.build.IBuildSource; import com.openshift.restclient.model.build.IBuildStrategy; import com.openshift.restclient.model.build.IBuildTrigger; @@ -37,247 +39,236 @@ import com.openshift.restclient.model.build.IDockerBuildStrategy; import com.openshift.restclient.model.build.IGitBuildSource; import com.openshift.restclient.model.build.IImageChangeTrigger; -import com.openshift.restclient.model.build.ISTIBuildStrategy; +import com.openshift.restclient.model.build.IJenkinsPipelineStrategy; import com.openshift.restclient.model.build.ISourceBuildStrategy; import com.openshift.restclient.model.build.IWebhookTrigger; -/** - * @author Jeff Cantrill - */ public class BuildConfig extends KubernetesResource implements IBuildConfig { - - private static final String BUILDCONFIG_SOURCE_CONTEXTDIR = "spec.source.contextDir"; - private static final String BUILDCONFIG_SOURCE_TYPE = "spec.source.type"; - private static final String BUILDCONFIG_SOURCE_URI = "spec.source.git.uri"; - private static final String BUILDCONFIG_SOURCE_REF = "spec.source.git.ref"; - - public static final String BUILDCONFIG_TYPE = "spec.strategy.type"; - private static final String BUILDCONFIG_CUSTOM_IMAGE = "spec.strategy.customStrategy.image"; - private static final String BUILDCONFIG_CUSTOM_EXPOSEDOCKERSOCKET = "spec.strategy.customStrategy.exposeDockerSocket"; - private static final String BUILDCONFIG_CUSTOM_ENV = "spec.strategy.customStrategy.env"; - public static final String BUILDCONFIG_DOCKER_CONTEXTDIR = "spec.strategy.dockerStrategy.contextDir"; - public static final String BUILDCONFIG_DOCKER_NOCACHE = "spec.strategy.dockerStrategy.noCache"; - public static final String BUILDCONFIG_DOCKER_BASEIMAGE = "spec.strategy.dockerStrategy.baseImage"; - private static final String BUILDCONFIG_OUTPUT_REPO = "spec.output.to.name"; - private static final String BUILDCONFIG_STI_IMAGE = "spec.strategy.sourceStrategy.from.name"; - private static final String BUILDCONFIG_STI_SCRIPTS = "spec.strategy.sourceStrategy.scripts"; - private static final String BUILDCONFIG_STI_INCREMENTAL = "spec.strategy.sourceStrategy.incremental"; - private static final String BUILDCONFIG_STI_ENV = "spec.strategy.sourceStrategy.env"; - private static final String BUILDCONFIG_TRIGGERS = "spec.triggers"; - private static final String BUILD_CONFIG_WEBHOOK_GITHUB_SECRET = "github.secret"; - private static final String BUILD_CONFIG_WEBHOOK_GENERIC_SECRET = "generic.secret"; - private static final String BUILD_CONFIG_IMAGECHANGE_IMAGE = "imageChange.image"; - private static final String BUILD_CONFIG_IMAGECHANGE_NAME = "imageChange.from.name"; - private static final String BUILD_CONFIG_IMAGECHANGE_TAG = "imageChange.tag"; - private static final String SOURCE_STRATEGY = "spec.strategy"; + public static final String BUILDCONFIG_SOURCE_CONTEXTDIR = "spec.source.contextDir"; + public static final String BUILDCONFIG_SOURCE_TYPE = "spec.source.type"; + public static final String BUILDCONFIG_SOURCE_URI = "spec.source.git.uri"; + public static final String BUILDCONFIG_SOURCE_REF = "spec.source.git.ref"; + public static final String BUILDCONFIG_SOURCE_BINARY_ASFILE = "spec.source.binary.asFile"; + + public static final String BUILDCONFIG_TYPE = "spec.strategy.type"; + private static final String BUILDCONFIG_CUSTOM_IMAGE = "spec.strategy.customStrategy.image"; + private static final String BUILDCONFIG_CUSTOM_EXPOSEDOCKERSOCKET = "spec.strategy.customStrategy.exposeDockerSocket"; + private static final String BUILDCONFIG_CUSTOM_ENV = "spec.strategy.customStrategy.env"; + public static final String BUILDCONFIG_DOCKER_CONTEXTDIR = "spec.strategy.dockerStrategy.contextDir"; + public static final String BUILDCONFIG_DOCKER_NOCACHE = "spec.strategy.dockerStrategy.noCache"; + public static final String BUILDCONFIG_DOCKER_BASEIMAGE = "spec.strategy.dockerStrategy.baseImage"; + private static final String BUILDCONFIG_OUTPUT_REPO = "spec.output.to.name"; + private static final String BUILDCONFIG_TRIGGERS = "spec.triggers"; + private static final String BUILDCONFIG_STRATEGY = "spec.strategy"; + private static final String BUILD_CONFIG_WEBHOOK_GITHUB_SECRET = "github.secret"; + private static final String BUILD_CONFIG_WEBHOOK_GENERIC_SECRET = "generic.secret"; + private static final String BUILD_CONFIG_IMAGECHANGE_IMAGE = "imageChange.image"; + private static final String BUILD_CONFIG_IMAGECHANGE_NAME = "imageChange.from.name"; + private static final String BUILD_CONFIG_IMAGECHANGE_TAG = "imageChange.tag"; + + public BuildConfig(ModelNode node, IClient client, Map overrideProperties) { + super(node, client, null); + CapabilityInitializer.initializeCapabilities(getModifiableCapabilities(), this, client); + } + + @Override + public IObjectReference getBuildOutputReference() { + return new ObjectReference(get("spec.output.to")); + } + + @Override + public List getBuildTriggers() { + List triggers = new ArrayList<>(); + if (has(BUILDCONFIG_TRIGGERS)) { + List list = get(BUILDCONFIG_TRIGGERS).asList(); + final String url = getClient() != null && StringUtils.isNotEmpty(getNamespaceName()) + ? getClient().getResourceURI(this) + : ""; + for (ModelNode node : list) { + String type = node.get(TYPE).asString(); + switch (type) { + case BuildTriggerType.GENERIC: + triggers.add(new WebhookTrigger(BuildTriggerType.GENERIC, + asString(node, BUILD_CONFIG_WEBHOOK_GENERIC_SECRET), url)); + break; + case BuildTriggerType.GITHUB: + triggers.add(new WebhookTrigger(BuildTriggerType.GITHUB, + asString(node, BUILD_CONFIG_WEBHOOK_GITHUB_SECRET), url)); + break; + case BuildTriggerType.IMAGE_CHANGE: + triggers.add(new ImageChangeTrigger(BuildTriggerType.IMAGE_CHANGE, + asString(node, BUILD_CONFIG_IMAGECHANGE_IMAGE), + asString(node, BUILD_CONFIG_IMAGECHANGE_NAME), + asString(node, BUILD_CONFIG_IMAGECHANGE_TAG))); + break; + case BuildTriggerType.CONFIG_CHANGE: + triggers.add(new ImageChangeTrigger(BuildTriggerType.CONFIG_CHANGE, null, null)); + break; + default: + } + } + } + return triggers; + } + + @Override + public void addBuildTrigger(IBuildTrigger trigger) { + ModelNode triggers = get(BUILDCONFIG_TRIGGERS); + ModelNode triggerNode = triggers.add(); + switch (trigger.getType()) { + case BuildTriggerType.GENERIC: + if (!(trigger instanceof IWebhookTrigger)) { + throw new IllegalArgumentException("IBuildTrigger of type generic does not implement IWebhookTrigger"); + } + IWebhookTrigger generic = (IWebhookTrigger) trigger; + triggerNode.get(getPath(BUILD_CONFIG_WEBHOOK_GENERIC_SECRET)).set(generic.getSecret()); + break; + case BuildTriggerType.GITHUB: + if (!(trigger instanceof IWebhookTrigger)) { + throw new IllegalArgumentException("IBuildTrigger of type github does not implement IWebhookTrigger"); + } + IWebhookTrigger github = (IWebhookTrigger) trigger; + triggerNode.get(getPath(BUILD_CONFIG_WEBHOOK_GITHUB_SECRET)).set(github.getSecret()); + break; + case BuildTriggerType.IMAGE_CHANGE: { + if (!(trigger instanceof IImageChangeTrigger)) { + throw new IllegalArgumentException( + "IBuildTrigger of type imageChange does not implement IImageChangeTrigger"); + } + IImageChangeTrigger image = (IImageChangeTrigger) trigger; + if (image.getImage() != null) { + triggerNode.get(getPath(BUILD_CONFIG_IMAGECHANGE_IMAGE)).set(image.getImage().toString()); + } + if (image.getFrom() != null) { + triggerNode.get(getPath(BUILD_CONFIG_IMAGECHANGE_NAME)).set(image.getFrom().toString()); + } + if (StringUtils.isNotEmpty(image.getTag())) { + triggerNode.get(getPath(BUILD_CONFIG_IMAGECHANGE_TAG)) + .set(StringUtils.defaultIfBlank(image.getTag(), "")); + } + break; + + } + } + triggerNode.get(TYPE).set(trigger.getType()); + } - public BuildConfig(ModelNode node, IClient client, Map overrideProperties) { - super(node, client, null); - CapabilityInitializer.initializeCapabilities(getModifiableCapabilities(), this, client); - } + @Override + public String getOutputRepositoryName() { + return asString(BUILDCONFIG_OUTPUT_REPO); + } - @Override - public IObjectReference getBuildOutputReference() { - ModelNode node = get("spec.output.to"); - if(!node.isDefined()) return null; - return new ObjectReference(node); - } + public String getSourceURI() { + return asString(BUILDCONFIG_SOURCE_URI); + } + @SuppressWarnings("unchecked") + @Override + public T getBuildSource() { + switch (asString(BUILDCONFIG_SOURCE_TYPE)) { + case BuildSourceType.GIT: + return (T) new GitBuildSource(asString(BUILDCONFIG_SOURCE_URI), asString(BUILDCONFIG_SOURCE_REF), + asString(BUILDCONFIG_SOURCE_CONTEXTDIR)); + case BuildSourceType.BINARY: + return (T) new BinaryBuildSource(asString(BUILDCONFIG_SOURCE_BINARY_ASFILE), asString(BUILDCONFIG_SOURCE_CONTEXTDIR)); + default: + } + return null; + } - @Override - public List getBuildTriggers() { - List triggers = new ArrayList(); - List list = get(BUILDCONFIG_TRIGGERS).asList(); - final String url = getClient() != null ? getClient().getResourceURI(this) : ""; - for (ModelNode node : list) { - String type = node.get(TYPE).asString(); - switch(type){ - case BuildTriggerType.generic: - case BuildTriggerType.GENERIC: - triggers.add(new WebhookTrigger(BuildTriggerType.GENERIC, - asString(node, BUILD_CONFIG_WEBHOOK_GENERIC_SECRET), url)); - break; - case BuildTriggerType.github: - case BuildTriggerType.GITHUB: - triggers.add(new WebhookTrigger(BuildTriggerType.GITHUB, asString(node, BUILD_CONFIG_WEBHOOK_GITHUB_SECRET), url)); - break; - case BuildTriggerType.imageChange: - case BuildTriggerType.IMAGE_CHANGE: - triggers.add(new ImageChangeTrigger(BuildTriggerType.IMAGE_CHANGE, - asString(node, BUILD_CONFIG_IMAGECHANGE_IMAGE), - asString(node, BUILD_CONFIG_IMAGECHANGE_NAME), - asString(node, BUILD_CONFIG_IMAGECHANGE_TAG)) - ); - break; - case BuildTriggerType.CONFIG_CHANGE: - triggers.add(new ImageChangeTrigger(BuildTriggerType.CONFIG_CHANGE, null, null)); - default: - } - } - return triggers; - } + @Override + public void setBuildSource(IBuildSource source) { + switch (source.getType()) { + case BuildSourceType.GIT: + if (!(source instanceof IGitBuildSource)) { + throw new IllegalArgumentException("IBuildSource of type Git does not implement IGitBuildSource"); + } + IGitBuildSource git = (IGitBuildSource) source; + set(BUILDCONFIG_SOURCE_REF, git.getRef()); + set(BUILDCONFIG_SOURCE_URI, git.getURI()); + break; + case BuildSourceType.BINARY: + if (!(source instanceof IBinaryBuildSource)) { + throw new IllegalArgumentException("IBuildSource of type Binary does not implement IBinaryBuildSource"); + } + IBinaryBuildSource binary = (IBinaryBuildSource) source; + set(BUILDCONFIG_SOURCE_BINARY_ASFILE, binary.getAsFile()); + break; + } + set(BUILDCONFIG_SOURCE_TYPE, source.getType()); + set(BUILDCONFIG_SOURCE_CONTEXTDIR, source.getContextDir()); + } - @Override - public void addBuildTrigger(IBuildTrigger trigger) { - ModelNode triggers = get(BUILDCONFIG_TRIGGERS); - ModelNode triggerNode = triggers.add(); - switch(trigger.getType()) { - case BuildTriggerType.generic: - case BuildTriggerType.GENERIC: - if(!(trigger instanceof IWebhookTrigger)) { - throw new IllegalArgumentException("IBuildTrigger of type generic does not implement IWebhookTrigger"); - } - IWebhookTrigger generic = (IWebhookTrigger)trigger; - triggerNode.get(getPath(BUILD_CONFIG_WEBHOOK_GENERIC_SECRET)).set(generic.getSecret()); - break; - case BuildTriggerType.github: - case BuildTriggerType.GITHUB: - if(!(trigger instanceof IWebhookTrigger)) { - throw new IllegalArgumentException("IBuildTrigger of type github does not implement IWebhookTrigger"); - } - IWebhookTrigger github = (IWebhookTrigger)trigger; - triggerNode.get(getPath(BUILD_CONFIG_WEBHOOK_GITHUB_SECRET)).set(github.getSecret()); - break; - case BuildTriggerType.imageChange: - case BuildTriggerType.IMAGE_CHANGE:{ - if(!(trigger instanceof IImageChangeTrigger)) { - throw new IllegalArgumentException("IBuildTrigger of type imageChange does not implement IImageChangeTrigger"); - } - IImageChangeTrigger image = (IImageChangeTrigger)trigger; - if(image.getImage() != null) - triggerNode.get(getPath(BUILD_CONFIG_IMAGECHANGE_IMAGE)).set(image.getImage().toString()); - if(image.getFrom() != null) - triggerNode.get(getPath(BUILD_CONFIG_IMAGECHANGE_NAME)).set(image.getFrom().toString()); - if(StringUtils.isNotEmpty(image.getTag())) - triggerNode.get(getPath(BUILD_CONFIG_IMAGECHANGE_TAG)).set(StringUtils.defaultIfBlank(image.getTag(), "")); - break; - - } - } - triggerNode.get(TYPE).set(trigger.getType()); - } + @Override + public void setBuildStrategy(IBuildStrategy strategy) { + // Remove other strategies if already set? + switch (strategy.getType()) { + case BuildStrategyType.CUSTOM: + if (!(strategy instanceof ICustomBuildStrategy)) { + throw new IllegalArgumentException( + "IBuildStrategy of type Custom does not implement ICustomBuildStrategy"); + } + ICustomBuildStrategy custom = (ICustomBuildStrategy) strategy; + if (custom.getImage() != null) { + set(BUILDCONFIG_CUSTOM_IMAGE, custom.getImage().toString()); + } + set(BUILDCONFIG_CUSTOM_EXPOSEDOCKERSOCKET, custom.exposeDockerSocket()); + if (custom.getEnvironmentVariables() != null) { + setEnvMap(BUILDCONFIG_CUSTOM_ENV, custom.getEnvironmentVariables()); + } + break; + case BuildStrategyType.SOURCE: + ISourceBuildStrategy source = (ISourceBuildStrategy) strategy; + get(BUILDCONFIG_STRATEGY).set(ModelNode.fromJSONString(source.toString())); + break; + case BuildStrategyType.DOCKER: + if (!(strategy instanceof IDockerBuildStrategy)) { + throw new IllegalArgumentException( + "IBuildStrategy of type Custom does not implement IDockerBuildStrategy"); + } + IDockerBuildStrategy docker = (IDockerBuildStrategy) strategy; + if (docker.getBaseImage() != null) { + set(BUILDCONFIG_DOCKER_BASEIMAGE, docker.getBaseImage().toString()); + } + if (docker.getContextDir() != null) { + set(BUILDCONFIG_DOCKER_CONTEXTDIR, docker.getContextDir()); + } + set(BUILDCONFIG_DOCKER_NOCACHE, docker.isNoCache()); + break; + case BuildStrategyType.JENKINS_PIPELINE: + if (!(strategy instanceof IJenkinsPipelineStrategy)) { + throw new IllegalArgumentException( + "IBuildStrategy of type Custom does not implement IJenkinsPipelineStrategy"); + } + IJenkinsPipelineStrategy jenkins = (IJenkinsPipelineStrategy) strategy; + get(BUILDCONFIG_STRATEGY).set(ModelNode.fromJSONString(jenkins.toString())); + break; + } - @Override - public String getOutputRepositoryName() { - return asString(BUILDCONFIG_OUTPUT_REPO); - } + set(BUILDCONFIG_TYPE, strategy.getType()); + } - public String getSourceURI() { - return asString(BUILDCONFIG_SOURCE_URI); - } - - @SuppressWarnings("unchecked") - @Override - public T getBuildSource() { - switch(asString(BUILDCONFIG_SOURCE_TYPE)){ - case BuildSourceType.GIT: - return (T) new GitBuildSource(asString(BUILDCONFIG_SOURCE_URI), asString(BUILDCONFIG_SOURCE_REF), asString(BUILDCONFIG_SOURCE_CONTEXTDIR)); - default: - } - return null; - } + @SuppressWarnings("unchecked") + @Override + public T getBuildStrategy() { + switch (asString(BUILDCONFIG_TYPE)) { - @Override - public void setBuildSource(IBuildSource source){ - switch(source.getType()) { - case BuildSourceType.GIT: - if(!(source instanceof IGitBuildSource)) { - throw new IllegalArgumentException("IBuildSource of type Git does not implement IGitBuildSource"); - } - IGitBuildSource git = (IGitBuildSource) source; - set(BUILDCONFIG_SOURCE_REF, git.getRef()); - break; - } - set(BUILDCONFIG_SOURCE_URI, source.getURI()); - set(BUILDCONFIG_SOURCE_TYPE, source.getType().toString()); - set(BUILDCONFIG_SOURCE_CONTEXTDIR, source.getContextDir()); - } - - @Override - public void setBuildStrategy(IBuildStrategy strategy) { - // Remove other strategies if already set? - switch(strategy.getType()) { - case BuildStrategyType.CUSTOM: - if ( !(strategy instanceof ICustomBuildStrategy)) { - throw new IllegalArgumentException("IBuildStrategy of type Custom does not implement ICustomBuildStrategy"); - } - ICustomBuildStrategy custom = (ICustomBuildStrategy)strategy; - if(custom.getImage() != null) { - set(BUILDCONFIG_CUSTOM_IMAGE, custom.getImage().toString()); - } - set(BUILDCONFIG_CUSTOM_EXPOSEDOCKERSOCKET, custom.exposeDockerSocket()); - if(custom.getEnvironmentVariables() != null) { - setEnvMap(BUILDCONFIG_CUSTOM_ENV, custom.getEnvironmentVariables()); - } - break; - case BuildStrategyType.STI: - if ( !(strategy instanceof ISTIBuildStrategy)) { - throw new IllegalArgumentException("IBuildStrategy of type Custom does not implement ISTIBuildStrategy"); - } - ISTIBuildStrategy sti = (ISTIBuildStrategy)strategy; - if(sti.getImage() != null) { - set(BUILDCONFIG_STI_IMAGE, sti.getImage().toString()); - } - if(sti.getScriptsLocation() != null) { - set(BUILDCONFIG_STI_SCRIPTS, sti.getScriptsLocation()); - } - set(BUILDCONFIG_STI_INCREMENTAL, sti.incremental()); - if(sti.getEnvironmentVariables() != null) { - setEnvMap(BUILDCONFIG_STI_ENV, sti.getEnvironmentVariables()); - } - break; - case BuildStrategyType.SOURCE: - ISourceBuildStrategy source = (ISourceBuildStrategy) strategy; - get(SOURCE_STRATEGY).set(ModelNode.fromJSONString(source.toString())); - break; - case BuildStrategyType.DOCKER: - if ( !(strategy instanceof IDockerBuildStrategy)) { - throw new IllegalArgumentException("IBuildStrategy of type Custom does not implement IDockerBuildStrategy"); - } - IDockerBuildStrategy docker = (IDockerBuildStrategy)strategy; - if(docker.getBaseImage() != null) { - set(BUILDCONFIG_DOCKER_BASEIMAGE, docker.getBaseImage().toString()); - } - if(docker.getContextDir() != null) { - set(BUILDCONFIG_DOCKER_CONTEXTDIR, docker.getContextDir()); - } - set(BUILDCONFIG_DOCKER_NOCACHE, docker.isNoCache()); - break; - } + case BuildStrategyType.CUSTOM: + return (T) new CustomBuildStrategy(asString(BUILDCONFIG_CUSTOM_IMAGE), + asBoolean(BUILDCONFIG_CUSTOM_EXPOSEDOCKERSOCKET), getEnvMap(BUILDCONFIG_CUSTOM_ENV)); + case BuildStrategyType.SOURCE: + return (T) new SourceBuildStrategy(get(BUILDCONFIG_STRATEGY), getPropertyKeys()); - set(BUILDCONFIG_TYPE, strategy.getType()); - } - - public void setOutput(DockerImageURI imageUri){ - //FIXME -// ModelNode output = getNode().get(new String []{"parameters","output"}); -// output.get("imageTag").set(imageUri.getUriWithoutHost()); -// output.get("registry").set(imageUri.getRepositoryHost()); - } + case BuildStrategyType.DOCKER: + return (T) new DockerBuildStrategy(asString(BUILDCONFIG_DOCKER_CONTEXTDIR), + asBoolean(BUILDCONFIG_DOCKER_NOCACHE), asString(BUILDCONFIG_DOCKER_BASEIMAGE)); - @SuppressWarnings("unchecked") - @Override - public T getBuildStrategy() { - switch(asString(BUILDCONFIG_TYPE)){ - case BuildStrategyType.CUSTOM: - return (T) new CustomBuildStrategy( - asString(BUILDCONFIG_CUSTOM_IMAGE), - asBoolean(BUILDCONFIG_CUSTOM_EXPOSEDOCKERSOCKET), - getEnvMap(BUILDCONFIG_CUSTOM_ENV) - ); - case BuildStrategyType.STI: - case BuildStrategyType.SOURCE: - return (T) new SourceBuildStrategy(get(SOURCE_STRATEGY), getPropertyKeys()); + case BuildStrategyType.JENKINS_PIPELINE: + return (T) new JenkinsPipelineStrategy(get(BUILDCONFIG_STRATEGY), getPropertyKeys()); - case BuildStrategyType.DOCKER: - return (T) new DockerBuildStrategy( - asString(BUILDCONFIG_DOCKER_CONTEXTDIR), - asBoolean(BUILDCONFIG_DOCKER_NOCACHE), - asString(BUILDCONFIG_DOCKER_BASEIMAGE) - ); - default: - } - return null; - } + default: + } + return null; + } } diff --git a/src/main/java/com/openshift/internal/restclient/model/Config.java b/src/main/java/com/openshift/internal/restclient/model/Config.java deleted file mode 100644 index 17f30025..00000000 --- a/src/main/java/com/openshift/internal/restclient/model/Config.java +++ /dev/null @@ -1,27 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2015 Red Hat, Inc. Distributed under license by Red Hat, Inc. - * All rights reserved. This program is made available under the terms of the - * Eclipse Public License v1.0 which accompanies this distribution, and is - * available at http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: Red Hat, Inc. - ******************************************************************************/ -package com.openshift.internal.restclient.model; - -import java.util.Map; - -import org.jboss.dmr.ModelNode; - -import com.openshift.restclient.IClient; -import com.openshift.restclient.model.IConfig; - -/** - * @author Jeff Cantrill - */ -@Deprecated -public class Config extends List implements IConfig{ - - public Config(ModelNode node, IClient client, Map propertyKeys) { - super(node, client, propertyKeys); - } -} diff --git a/src/main/java/com/openshift/internal/restclient/model/ConfigMap.java b/src/main/java/com/openshift/internal/restclient/model/ConfigMap.java index ba2be9f3..8786e5f0 100644 --- a/src/main/java/com/openshift/internal/restclient/model/ConfigMap.java +++ b/src/main/java/com/openshift/internal/restclient/model/ConfigMap.java @@ -1,12 +1,11 @@ package com.openshift.internal.restclient.model; -import com.openshift.restclient.IClient; -import com.openshift.restclient.model.IConfigMap; -import org.jboss.dmr.ModelNode; - import java.util.Map; -import static com.openshift.internal.restclient.capability.CapabilityInitializer.initializeCapabilities; +import org.jboss.dmr.ModelNode; + +import com.openshift.restclient.IClient; +import com.openshift.restclient.model.IConfigMap; /** * @author Ulf Lilleengen diff --git a/src/main/java/com/openshift/internal/restclient/model/Container.java b/src/main/java/com/openshift/internal/restclient/model/Container.java index 8b040bab..4e27e8ab 100644 --- a/src/main/java/com/openshift/internal/restclient/model/Container.java +++ b/src/main/java/com/openshift/internal/restclient/model/Container.java @@ -8,193 +8,322 @@ * Contributors: * Red Hat, Inc. - initial API and implementation ******************************************************************************/ + package com.openshift.internal.restclient.model; -import static com.openshift.internal.util.JBossDmrExtentions.*; +import static com.openshift.internal.util.JBossDmrExtentions.asList; +import static com.openshift.internal.util.JBossDmrExtentions.asString; +import static com.openshift.internal.util.JBossDmrExtentions.get; +import static com.openshift.internal.util.JBossDmrExtentions.set; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; +import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Set; +import org.apache.commons.lang.StringUtils; import org.jboss.dmr.ModelNode; +import org.jboss.dmr.ModelType; +import com.openshift.internal.restclient.model.probe.Probe; import com.openshift.internal.restclient.model.properties.ResourcePropertyKeys; import com.openshift.internal.restclient.model.volume.EmptyDirVolume; import com.openshift.internal.restclient.model.volume.VolumeMount; import com.openshift.restclient.images.DockerImageURI; import com.openshift.restclient.model.IContainer; +import com.openshift.restclient.model.ILifecycle; import com.openshift.restclient.model.IPort; +import com.openshift.restclient.model.probe.IProbe; import com.openshift.restclient.model.volume.IVolume; import com.openshift.restclient.model.volume.IVolumeMount; public class Container extends ModelNodeAdapter implements IContainer, ResourcePropertyKeys { - - private static final String IMAGE = "image"; - private static final String ENV = "env"; - private static final String IMAGE_PULL_POLICY = "imagePullPolicy"; - private static final String LIFECYCLE = "lifecycle"; - private static final String VOLUMEMOUNTS = "volumeMounts"; - - private ModelNode node; - private Map propertyKeys; - - public Container(ModelNode node) { - this(node, Collections.emptyMap()); - } - /** - * - * @param node - * @param propertyKeys the override paths from the defaults - */ - public Container(ModelNode node, Map propertyKeys) { - super(node, propertyKeys); - this.node = node; - this.propertyKeys = propertyKeys; - } - @Override - public void setName(String name) { - set(node, propertyKeys, NAME, name); - } - - @Override - public String getName() { - return asString(node, propertyKeys, NAME); - } - - @Override - public void setImage(DockerImageURI tag) { - set(node, propertyKeys, IMAGE, tag.getAbsoluteUri()); - } - - @Override - public DockerImageURI getImage() { - return new DockerImageURI(asString(node, propertyKeys, IMAGE)); - } - - @Override - public void setEnvVars(Map vars) { - if(!vars.isEmpty()) { - ModelNode env = get(node, propertyKeys, ENV); - env.clear(); - for (Entry var : vars.entrySet()) { - addEnvVar(var.getKey(), var.getValue()); - } - } - } - - @Override - public Map getEnvVars() { - HashMap hashMap = new HashMap<>(); - ModelNode env = get(node, propertyKeys, ENV); - if(env.isDefined()) { - for (ModelNode var : env.asList()) { - hashMap.put( - asString(var,propertyKeys,NAME), - asString(var,propertyKeys,VALUE) - ); - } - } - return hashMap; - } - - @Override - public void addEnvVar(String key, String value) { - ModelNode env = get(node, propertyKeys, ENV); - ModelNode varNode = new ModelNode(); - varNode.get(NAME).set(key); - varNode.get(VALUE).set(value); - env.add(varNode); - } - - @Override - public void setPorts(Set ports) { - ModelNode nodePorts = get(node, propertyKeys, PORTS); - nodePorts.clear(); - for (IPort port : ports) { - ModelNode portNode = nodePorts.add(); - new Port(portNode, port); - } - } - - @Override - public Set getPorts() { - ModelNode nodePorts = get(node, propertyKeys, PORTS); - Set ports = new HashSet<>(); - if(nodePorts.isDefined()) { - for (ModelNode port : nodePorts.asList()) { - ports.add(new Port(port)); - } - } - return ports; - } - - @Override - public void setImagePullPolicy(String policy) { - set(node, propertyKeys, IMAGE_PULL_POLICY, policy); - } - - @Override - public String getImagePullPolicy() { - return asString(node, propertyKeys, IMAGE_PULL_POLICY); - } - - @Override - public void setLifecycle(String lifecycle) { - set(node, propertyKeys, LIFECYCLE, lifecycle); - } - - @Override - public String getLifecycle() { - return asString(node, propertyKeys, LIFECYCLE); - } - - @Override - public void setVolumes(Set volumes) { - ModelNode mounts = get(node, propertyKeys, VOLUMEMOUNTS); - mounts.clear(); - for (IVolume volume : volumes) { - new EmptyDirVolume(mounts.add(), volume); - } - } - - @Override - public Set getVolumes() { - Set volumes = new HashSet<>(); - ModelNode mounts = get(node, propertyKeys, VOLUMEMOUNTS); - if(mounts.isDefined()) { - for (ModelNode node : mounts.asList()) { - volumes.add(new VolumeMount(node)); - } - } - return volumes; - } - @Override - public void setVolumeMounts(Set volumes) { - ModelNode mounts = get(node, propertyKeys, VOLUMEMOUNTS); - mounts.clear(); - for (IVolumeMount volume : volumes) { - new VolumeMount(mounts.add(), volume); - } - } - - @Override - public Set getVolumeMounts() { - Set volumes = new HashSet<>(); - ModelNode mounts = get(node, propertyKeys, VOLUMEMOUNTS); - if(mounts.isDefined()) { - for (ModelNode node : mounts.asList()) { - volumes.add(new VolumeMount(node)); - } - } - return volumes; - } - - @Override - public String toJSONString() { - return super.toJson(false); - } - + + private static final String IMAGE = "image"; + private static final String ENV = "env"; + private static final String IMAGE_PULL_POLICY = "imagePullPolicy"; + private static final String COMMAND = "command"; + private static final String COMMANDARGS = "args"; + private static final String LIFECYCLE = "lifecycle"; + private static final String VOLUMEMOUNTS = "volumeMounts"; + private static final String PROPERTY_REQUESTS_MEMORY = "resources.requests.memory"; + private static final String PROPERTY_REQUESTS_CPU = "resources.requests.cpu"; + private static final String PROPERTY_LIMITS_MEMORY = "resources.limits.memory"; + private static final String PROPERTY_LIMITS_CPU = "resources.limits.cpu"; + private static final String LIVENESSPROBE = "livenessProbe"; + private static final String READINESSPROBE = "readinessProbe"; + + private ModelNode node; + private Map propertyKeys; + + public Container(ModelNode node) { + this(node, Collections.emptyMap()); + } + + /** + * + * @param node the node + * @param propertyKeys + * the override paths from the defaults + */ + public Container(ModelNode node, Map propertyKeys) { + super(node, propertyKeys); + this.node = node; + this.propertyKeys = propertyKeys; + } + + @Override + public void setName(String name) { + set(node, propertyKeys, NAME, name); + } + + @Override + public String getName() { + return asString(node, propertyKeys, NAME); + } + + @Override + public void setImage(DockerImageURI tag) { + set(node, propertyKeys, IMAGE, tag.getAbsoluteUri()); + } + + @Override + public DockerImageURI getImage() { + return new DockerImageURI(asString(node, propertyKeys, IMAGE)); + } + + @Override + public void setEnvVars(Map vars) { + if (!vars.isEmpty()) { + ModelNode env = get(node, propertyKeys, ENV); + env.clear(); + for (Entry var : vars.entrySet()) { + addEnvVar(var.getKey(), var.getValue()); + } + } + } + + @Override + public Map getEnvVars() { + HashMap hashMap = new HashMap<>(); + ModelNode env = get(node, propertyKeys, ENV); + if (env.isDefined()) { + for (ModelNode var : env.asList()) { + hashMap.put(asString(var, propertyKeys, NAME), asString(var, propertyKeys, VALUE)); + } + } + return hashMap; + } + + @Override + public void addEnvVar(String key, String value) { + ModelNode env = get(node, propertyKeys, ENV); + ModelNode varNode = new ModelNode(); + varNode.get(NAME).set(key); + varNode.get(VALUE).set(value); + env.add(varNode); + } + + @Override + public void setPorts(Set ports) { + ModelNode nodePorts = get(node, propertyKeys, PORTS); + nodePorts.clear(); + for (IPort port : ports) { + ModelNode portNode = nodePorts.add(); + new Port(portNode, port); + } + } + + @Override + public Set getPorts() { + ModelNode nodePorts = get(node, propertyKeys, PORTS); + Set ports = new HashSet<>(); + if (nodePorts.isDefined()) { + for (ModelNode port : nodePorts.asList()) { + ports.add(new Port(port)); + } + } + return ports; + } + + @Override + public void setImagePullPolicy(String policy) { + set(node, propertyKeys, IMAGE_PULL_POLICY, policy); + } + + @Override + public String getImagePullPolicy() { + return asString(node, propertyKeys, IMAGE_PULL_POLICY); + } + + @Override + public void setCommand(List command) { + set(node, propertyKeys, COMMAND, command.toArray(new String[0])); + } + + @Override + public List getCommand() { + return asList(node, propertyKeys, COMMAND, ModelType.STRING); + } + + @Override + public void setCommandArgs(List args) { + set(node, propertyKeys, COMMANDARGS, args.toArray(new String[0])); + } + + @Override + public List getCommandArgs() { + return asList(node, propertyKeys, COMMANDARGS, ModelType.STRING); + } + + @Override + public void setLifecycle(ILifecycle lifecycle) { + ModelNode lifecycleNode = ModelNode.fromJSONString(lifecycle.toJson()); + get(node, propertyKeys, LIFECYCLE).set(lifecycleNode); + } + + @Override + public ILifecycle getLifecycle() { + if (node.has(LIFECYCLE)) { + return Lifecycle.fromJson(get(node, propertyKeys, LIFECYCLE)); + } else { + return new Lifecycle.Builder().build(); + } + } + + @Override + public void setVolumes(Set volumes) { + ModelNode mounts = get(node, propertyKeys, VOLUMEMOUNTS); + mounts.clear(); + for (IVolume volume : volumes) { + new EmptyDirVolume(mounts.add(), volume); + } + } + + @Override + public Set getVolumes() { + Set volumes = new HashSet<>(); + ModelNode mounts = get(node, propertyKeys, VOLUMEMOUNTS); + if (mounts.isDefined()) { + for (ModelNode node : mounts.asList()) { + volumes.add(new VolumeMount(node)); + } + } + return volumes; + } + + @Override + public void setVolumeMounts(Set volumes) { + ModelNode mounts = get(node, propertyKeys, VOLUMEMOUNTS); + mounts.clear(); + for (IVolumeMount volume : volumes) { + new VolumeMount(mounts.add(), volume); + } + } + + @Override + public Set getVolumeMounts() { + Set volumes = new HashSet<>(); + ModelNode mounts = get(node, propertyKeys, VOLUMEMOUNTS); + if (mounts.isDefined()) { + for (ModelNode node : mounts.asList()) { + volumes.add(new VolumeMount(node)); + } + } + return volumes; + } + + @Override + public IVolumeMount addVolumeMount(String name) { + ModelNode mounts = get(node, propertyKeys, VOLUMEMOUNTS); + VolumeMount volume = new VolumeMount(mounts.add()); + volume.setName(name); + return volume; + } + + @Override + public String getRequestsMemory() { + return asString(node, propertyKeys, PROPERTY_REQUESTS_MEMORY); + } + + @Override + public void setRequestsMemory(String requestsMemory) { + ModelNode child = get(getNode(), propertyKeys, PROPERTY_REQUESTS_MEMORY); + if (StringUtils.isBlank(requestsMemory)) { + child.clear(); + } else { + child.set(requestsMemory); + } + } + + @Override + public String getRequestsCPU() { + return asString(node, propertyKeys, PROPERTY_REQUESTS_CPU); + } + + @Override + public void setRequestsCPU(String requestsCPU) { + ModelNode child = get(getNode(), propertyKeys, PROPERTY_REQUESTS_CPU); + if (StringUtils.isBlank(requestsCPU)) { + child.clear(); + } else { + child.set(requestsCPU); + } + } + + @Override + public String getLimitsMemory() { + return asString(node, propertyKeys, PROPERTY_LIMITS_MEMORY); + } + + @Override + public void setLimitsMemory(String limitsMemory) { + ModelNode child = get(getNode(), propertyKeys, PROPERTY_LIMITS_MEMORY); + if (StringUtils.isBlank(limitsMemory)) { + child.clear(); + } else { + child.set(limitsMemory); + } + } + + @Override + public String getLimitsCPU() { + return asString(node, propertyKeys, PROPERTY_LIMITS_CPU); + } + + @Override + public void setLimitsCPU(String limitsCPU) { + ModelNode child = get(getNode(), propertyKeys, PROPERTY_LIMITS_CPU); + if (StringUtils.isBlank(limitsCPU)) { + child.clear(); + } else { + child.set(limitsCPU); + } + } + + @Override + public IProbe getReadinessProbe() { + ModelNode readinessProbeNode = get(getNode(), propertyKeys, READINESSPROBE); + if (!readinessProbeNode.isDefined()) { + return null; + } + return new Probe(readinessProbeNode); + } + + @Override + public IProbe getLivenessProbe() { + ModelNode lifenessProbeNode = get(getNode(), propertyKeys, LIVENESSPROBE); + if (!lifenessProbeNode.isDefined()) { + return null; + } + return new Probe(lifenessProbeNode); + } + + @Override + public String toJson(){ + return super.toJson(false); + } } diff --git a/src/main/java/com/openshift/internal/restclient/model/DeploymentConfig.java b/src/main/java/com/openshift/internal/restclient/model/DeploymentConfig.java index bb4d0f16..4232f187 100644 --- a/src/main/java/com/openshift/internal/restclient/model/DeploymentConfig.java +++ b/src/main/java/com/openshift/internal/restclient/model/DeploymentConfig.java @@ -8,6 +8,7 @@ * Contributors: * Red Hat, Inc. - initial API and implementation ******************************************************************************/ + package com.openshift.internal.restclient.model; import static com.openshift.internal.restclient.capability.CapabilityInitializer.initializeCapabilities; @@ -29,167 +30,164 @@ import com.openshift.restclient.model.deploy.DeploymentTriggerType; import com.openshift.restclient.model.deploy.IDeploymentTrigger; -/** - * @author Jeff Cantrill - */ -public class DeploymentConfig extends ReplicationController implements IDeploymentConfig{ - - public static final String DEPLOYMENTCONFIG_CONTAINERS = "spec.template.spec.containers"; - private static final String DEPLOYMENTCONFIG_TRIGGERS = "spec.triggers"; - private static final String DEPLOYMENTCONFIG_STRATEGY = "spec.strategy.type"; - private static final String DEPLOYMENTCONFIG_LATEST_VERSION = "status.latestVersion"; - private static final String DEPLOYMENTCONFIG_CAUSES = "status.details.causes"; - - private static final String TYPE = "type"; - private static final String IMAGE_CHANGE = "ImageChange"; - private static final String IMAGE_TRIGGER = "imageTrigger"; - private static final String FROM = "from"; - private static final String NAME = "name"; - private static final String IMAGE_CHANGE_PARAMS = "imageChangeParams"; - private static final String LAST_TRIGGER_IMAGE = "lastTriggeredImage"; - private static final String IMAGE_TRIGGER_FROM_NAME = IMAGE_TRIGGER + "." + FROM + "." + NAME; - private static final String IMAGE_CHANGE_PARAMS_FROM_NAME = IMAGE_CHANGE_PARAMS + "." + FROM + "." + NAME; - private static final String IMAGE_CHANGE_PARAMS_LAST_TRIGGER_IMAGE = IMAGE_CHANGE_PARAMS + "." + LAST_TRIGGER_IMAGE; - - private final Map propertyKeys; - - public DeploymentConfig(ModelNode node, IClient client, Map propertyKeys) { - super(node, client, propertyKeys); - this.propertyKeys = propertyKeys; - initializeCapabilities(getModifiableCapabilities(), this, getClient()); - } - - @Override - public Collection getTriggerTypes(){ - List types = new ArrayList(); - ModelNode triggers = get(DEPLOYMENTCONFIG_TRIGGERS); - for (ModelNode node : triggers.asList()) { - types.add(asString(node,TYPE)); - } - return types; - } - - @Override - public Collection getTriggers() { - List triggers = new ArrayList<>(); - ModelNode list = get(DEPLOYMENTCONFIG_TRIGGERS); - for (ModelNode node : list.asList()) { - String type = asString(node,TYPE); - switch(type) { - case(DeploymentTriggerType.CONFIG_CHANGE): - triggers.add(new ConfigChangeTrigger(node, propertyKeys)); - break; - case(DeploymentTriggerType.IMAGE_CHANGE): - triggers.add(new ImageChangeTrigger(node, propertyKeys)); - break; - } - } - return triggers; - } - - //FIXME - public List getImageNames(){ - List names = new ArrayList(); - List containers = get(DEPLOYMENTCONFIG_CONTAINERS).asList(); - for (ModelNode container : containers) { - names.add(container.get("image").asString()); - } - return names; - } - - - - @Override - public int getLatestVersionNumber() { - return asInt(DEPLOYMENTCONFIG_LATEST_VERSION); - } - - - - @Override - public void setLatestVersionNumber(int newVersionNumber) { - set(DEPLOYMENTCONFIG_LATEST_VERSION, newVersionNumber); - } - - @Override - public IDeploymentTrigger addTrigger(String type) { - ModelNode triggers = get(DEPLOYMENTCONFIG_TRIGGERS); - ModelNode triggerNode = triggers.add(); - triggerNode.get(TYPE).set(type); - switch(type) { - case DeploymentTriggerType.IMAGE_CHANGE: - return new ImageChangeTrigger(triggerNode, propertyKeys); - case DeploymentTriggerType.CONFIG_CHANGE: - default: - } - return new DeploymentTrigger(triggerNode, propertyKeys); - } - - @Override - public String getDeploymentStrategyType() { - return asString(DEPLOYMENTCONFIG_STRATEGY); - } - - @Override - public boolean haveTriggersFired() { - ModelNode causes = get(DEPLOYMENTCONFIG_CAUSES); - if (causes.getType() == ModelType.UNDEFINED || causes.getType() != ModelType.LIST) - return false; - return causes.asList().size() > 0; - } - - @Override - public boolean didImageTrigger(String imageNameTag) { - if (!haveTriggersFired() || imageNameTag == null) - return false; - ModelNode causes = get(DEPLOYMENTCONFIG_CAUSES); - if (causes.getType() == ModelType.UNDEFINED || - causes.getType() != ModelType.LIST) - return false; - for (ModelNode cause : causes.asList()) { - String type = asString(cause, TYPE); - if (type.equalsIgnoreCase(IMAGE_CHANGE)) { - String triggerName = asString(cause, IMAGE_TRIGGER_FROM_NAME); - DockerImageURI uri = new DockerImageURI(triggerName); - if (imageNameTag.equals(uri.getNameAndTag())) - return true; - } - } - return false; - } - - @Override - public String getImageHexIDForImageNameAndTag(String imageNameTag) { - ModelNode triggers = get(DEPLOYMENTCONFIG_TRIGGERS); - if (triggers.getType() == ModelType.UNDEFINED || triggers.getType() != ModelType.LIST || imageNameTag == null) - return null; - for (ModelNode trigger : triggers.asList()) { - if (asString(trigger, TYPE).equalsIgnoreCase(IMAGE_CHANGE)) { - String nameTag = null; - nameTag = asString(trigger, IMAGE_CHANGE_PARAMS_FROM_NAME); - if (imageNameTag.equals(nameTag)) { - return asString(trigger, IMAGE_CHANGE_PARAMS_LAST_TRIGGER_IMAGE); - } - } - } - return null; - } - - @Override - public String getImageNameAndTagForTriggeredDeployment() { - ModelNode causes = get(DEPLOYMENTCONFIG_CAUSES); - if (causes.getType() == ModelType.UNDEFINED || causes.getType() != ModelType.LIST) - return null; - for (ModelNode cause : causes.asList()) { - String type = asString(cause, TYPE); - if (type.equalsIgnoreCase(IMAGE_CHANGE)) { - String imageTag = asString(cause, IMAGE_TRIGGER_FROM_NAME); - DockerImageURI uri = new DockerImageURI(imageTag); - return uri.getNameAndTag(); - } - } - return null; - } - - +public class DeploymentConfig extends ReplicationController implements IDeploymentConfig { + + public static final String DEPLOYMENTCONFIG_CONTAINERS = "spec.template.spec.containers"; + private static final String DEPLOYMENTCONFIG_TRIGGERS = "spec.triggers"; + private static final String DEPLOYMENTCONFIG_STRATEGY = "spec.strategy.type"; + private static final String DEPLOYMENTCONFIG_LATEST_VERSION = "status.latestVersion"; + private static final String DEPLOYMENTCONFIG_CAUSES = "status.details.causes"; + + private static final String TYPE = "type"; + private static final String IMAGE_CHANGE = "ImageChange"; + private static final String IMAGE_TRIGGER = "imageTrigger"; + private static final String FROM = "from"; + private static final String NAME = "name"; + private static final String IMAGE_CHANGE_PARAMS = "imageChangeParams"; + private static final String LAST_TRIGGER_IMAGE = "lastTriggeredImage"; + private static final String IMAGE_TRIGGER_FROM_NAME = IMAGE_TRIGGER + "." + FROM + "." + NAME; + private static final String IMAGE_CHANGE_PARAMS_FROM_NAME = IMAGE_CHANGE_PARAMS + "." + FROM + "." + NAME; + private static final String IMAGE_CHANGE_PARAMS_LAST_TRIGGER_IMAGE = IMAGE_CHANGE_PARAMS + "." + LAST_TRIGGER_IMAGE; + + private final Map propertyKeys; + + public DeploymentConfig(ModelNode node, IClient client, Map propertyKeys) { + super(node, client, propertyKeys); + this.propertyKeys = propertyKeys; + initializeCapabilities(getModifiableCapabilities(), this, getClient()); + } + + @Override + public Collection getTriggerTypes() { + List types = new ArrayList<>(); + ModelNode triggers = get(DEPLOYMENTCONFIG_TRIGGERS); + for (ModelNode node : triggers.asList()) { + types.add(asString(node, TYPE)); + } + return types; + } + + @Override + public Collection getTriggers() { + List triggers = new ArrayList<>(); + ModelNode list = get(DEPLOYMENTCONFIG_TRIGGERS); + for (ModelNode node : list.asList()) { + String type = asString(node, TYPE); + switch (type) { + case (DeploymentTriggerType.CONFIG_CHANGE): + triggers.add(new ConfigChangeTrigger(node, propertyKeys)); + break; + case (DeploymentTriggerType.IMAGE_CHANGE): + triggers.add(new ImageChangeTrigger(node, propertyKeys)); + break; + } + } + return triggers; + } + + // FIXME + public List getImageNames() { + List names = new ArrayList<>(); + List containers = get(DEPLOYMENTCONFIG_CONTAINERS).asList(); + for (ModelNode container : containers) { + names.add(container.get("image").asString()); + } + return names; + } + + @Override + public int getLatestVersionNumber() { + return asInt(DEPLOYMENTCONFIG_LATEST_VERSION); + } + + @Override + public void setLatestVersionNumber(int newVersionNumber) { + set(DEPLOYMENTCONFIG_LATEST_VERSION, newVersionNumber); + } + + @Override + public IDeploymentTrigger addTrigger(String type) { + ModelNode triggers = get(DEPLOYMENTCONFIG_TRIGGERS); + ModelNode triggerNode = triggers.add(); + triggerNode.get(TYPE).set(type); + switch (type) { + case DeploymentTriggerType.IMAGE_CHANGE: + return new ImageChangeTrigger(triggerNode, propertyKeys); + case DeploymentTriggerType.CONFIG_CHANGE: + default: + } + return new DeploymentTrigger(triggerNode, propertyKeys); + } + + @Override + public String getDeploymentStrategyType() { + return asString(DEPLOYMENTCONFIG_STRATEGY); + } + + @Override + public boolean haveTriggersFired() { + ModelNode causes = get(DEPLOYMENTCONFIG_CAUSES); + if (causes.getType() == ModelType.UNDEFINED || causes.getType() != ModelType.LIST) { + return false; + } + return !causes.asList().isEmpty(); + } + + @Override + public boolean didImageTrigger(String imageNameTag) { + if (!haveTriggersFired() || imageNameTag == null) { + return false; + } + ModelNode causes = get(DEPLOYMENTCONFIG_CAUSES); + if (causes.getType() == ModelType.UNDEFINED || causes.getType() != ModelType.LIST) { + return false; + } + for (ModelNode cause : causes.asList()) { + String type = asString(cause, TYPE); + if (type.equalsIgnoreCase(IMAGE_CHANGE)) { + String triggerName = asString(cause, IMAGE_TRIGGER_FROM_NAME); + DockerImageURI uri = new DockerImageURI(triggerName); + if (imageNameTag.equals(uri.getNameAndTag())) { + return true; + } + } + } + return false; + } + + @Override + public String getImageHexIDForImageNameAndTag(String imageNameTag) { + ModelNode triggers = get(DEPLOYMENTCONFIG_TRIGGERS); + if (triggers.getType() == ModelType.UNDEFINED || triggers.getType() != ModelType.LIST || imageNameTag == null) { + return null; + } + for (ModelNode trigger : triggers.asList()) { + if (asString(trigger, TYPE).equalsIgnoreCase(IMAGE_CHANGE)) { + String nameTag = null; + nameTag = asString(trigger, IMAGE_CHANGE_PARAMS_FROM_NAME); + if (imageNameTag.equals(nameTag)) { + return asString(trigger, IMAGE_CHANGE_PARAMS_LAST_TRIGGER_IMAGE); + } + } + } + return null; + } + + @Override + public String getImageNameAndTagForTriggeredDeployment() { + ModelNode causes = get(DEPLOYMENTCONFIG_CAUSES); + if (causes.getType() == ModelType.UNDEFINED || causes.getType() != ModelType.LIST) { + return null; + } + for (ModelNode cause : causes.asList()) { + String type = asString(cause, TYPE); + if (type.equalsIgnoreCase(IMAGE_CHANGE)) { + String imageTag = asString(cause, IMAGE_TRIGGER_FROM_NAME); + DockerImageURI uri = new DockerImageURI(imageTag); + return uri.getNameAndTag(); + } + } + return null; + } + } diff --git a/src/main/java/com/openshift/internal/restclient/model/EnvironmentVariable.java b/src/main/java/com/openshift/internal/restclient/model/EnvironmentVariable.java index ad24b03f..ea768236 100644 --- a/src/main/java/com/openshift/internal/restclient/model/EnvironmentVariable.java +++ b/src/main/java/com/openshift/internal/restclient/model/EnvironmentVariable.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2016 Red Hat, Inc. + * Copyright (c) 2016-2020 Red Hat, Inc. * Distributed under license by Red Hat, Inc. All rights reserved. * This program is made available under the terms of the * Eclipse Public License v1.0 which accompanies this distribution, @@ -8,9 +8,10 @@ * Contributors: * Red Hat, Inc. - initial API and implementation ******************************************************************************/ + package com.openshift.internal.restclient.model; -import static com.openshift.internal.util.JBossDmrExtentions.*; +import static com.openshift.internal.util.JBossDmrExtentions.asString; import java.util.Map; @@ -24,64 +25,119 @@ public class EnvironmentVariable extends ModelNodeAdapter implements IEnvironmentVariable, ResourcePropertyKeys { - public EnvironmentVariable(ModelNode node, Map propertyKeys) { - super(node, propertyKeys); - } - - @Override - public String getName() { - return asString(getNode(), getPropertyKeys(), NAME); - } - - @Override - public String getValue() { - return asString(getNode(), getPropertyKeys(), VALUE); - } - - @Override - public IEnvVarSource getValueFrom() { - if(getNode().hasDefined("fieldRef")) { - return new IObjectFieldSelector(){ - @Override - public String getApiVersion() { - return asString(getNode(), getPropertyKeys(), "fieldRef.apiVersion"); - } - - @Override - public String getFieldPath() { - return asString(getNode(), getPropertyKeys(), "fieldRef.fieldPath"); - } - - }; - }else if(getNode().hasDefined("configMapKeyRef")) { - return new IConfigMapKeySelector() { - - @Override - public String getName() { - return asString(getNode(), getPropertyKeys(), "configMapKeyRef.name"); - } - - @Override - public String getKey() { - return asString(getNode(), getPropertyKeys(), "configMapKeyRef.key"); - } - }; - - }else if(getNode().hasDefined("secretKeyRef")) { - return new ISecretKeySelector() { - - @Override - public String getName() { - return asString(getNode(), getPropertyKeys(), "secretKeyRef.name"); - } - - @Override - public String getKey() { - return asString(getNode(), getPropertyKeys(), "secretKeyRef.key"); - } - }; - } - return null; - } - + private static final String PROP_VALUE_FROM = "valueFrom"; + private static final String PROP_FIELD_REF = "fieldRef"; + private static final String PROP_CONFIG_MAP_KEY_REF = "configMapKeyRef"; + private static final String PROP_SECRET_KEY_REF = "secretKeyRef"; + + public EnvironmentVariable(ModelNode node, Map propertyKeys) { + super(node, propertyKeys); + } + + @Override + public String getName() { + return asString(getNode(), getPropertyKeys(), NAME); + } + + @Override + public String getValue() { + return asString(getNode(), getPropertyKeys(), VALUE); + } + + @Override + public IEnvVarSource getValueFrom() { + ModelNode valueFrom = getNode().get(PROP_VALUE_FROM); + if (valueFrom == null) { + return null; + } + if (valueFrom.hasDefined(PROP_FIELD_REF)) { + return createObjectFieldSelector(valueFrom); + } else if (valueFrom.hasDefined(PROP_CONFIG_MAP_KEY_REF)) { + return createConfigMapKeySelector(valueFrom); + } else if (valueFrom.hasDefined(PROP_SECRET_KEY_REF)) { + return createSecretKeySelector(valueFrom); + } + return null; + } + + private IEnvVarSource createSecretKeySelector(ModelNode valueFrom) { + return new ISecretKeySelector() { + + @Override + public String getName() { + return asString(valueFrom, getPropertyKeys(), PROP_SECRET_KEY_REF + ".name"); + } + + @Override + public String getKey() { + return asString(valueFrom, getPropertyKeys(), PROP_SECRET_KEY_REF + ".key"); + } + }; + } + + private IEnvVarSource createConfigMapKeySelector(ModelNode valueFrom) { + return new IConfigMapKeySelector() { + + @Override + public String getName() { + return asString(valueFrom, getPropertyKeys(), PROP_CONFIG_MAP_KEY_REF + ".name"); + } + + @Override + public String getKey() { + return asString(valueFrom, getPropertyKeys(), PROP_CONFIG_MAP_KEY_REF + ".key"); + } + }; + } + + private IEnvVarSource createObjectFieldSelector(ModelNode valueFrom) { + return new IObjectFieldSelector() { + + @Override + public String getFieldPath() { + return asString(valueFrom, getPropertyKeys(), PROP_FIELD_REF + ".fieldPath"); + } + + }; + } + + @Override + public boolean equals(Object object) { + if (!(object instanceof IEnvironmentVariable)) { + return false; + } + + IEnvironmentVariable otherVar = (IEnvironmentVariable) object; + String thisName = getName(); + String otherName = otherVar.getName(); + if (thisName == null) { + if (otherName != null) { + return false; + } + } else { + if (!thisName.equals(otherName)) { + return false; + } + } + + String thisValue = getValue(); + String otherValue = otherVar.getValue(); + if (thisValue == null) { + if (otherValue != null) { + return false; + } + } else { + if (!thisValue.equals(otherValue)) { + return false; + } + } + return true; + } + + @Override + public int hashCode() { + String name = getName(); + String value = getValue(); + return 37 * (name == null ? 0 : name.hashCode()) + (value == null ? 0 : value.hashCode()); + } } diff --git a/src/main/java/com/openshift/internal/restclient/model/ExecAction.java b/src/main/java/com/openshift/internal/restclient/model/ExecAction.java new file mode 100644 index 00000000..38b61051 --- /dev/null +++ b/src/main/java/com/openshift/internal/restclient/model/ExecAction.java @@ -0,0 +1,78 @@ +/******************************************************************************* + * Copyright (c) 2016 Red Hat, Inc. + * Distributed under license by Red Hat, Inc. All rights reserved. + * This program is made available under the terms of the + * Eclipse Public License v1.0 which accompanies this distribution, + * and is available at http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Red Hat, Inc. - initial API and implementation + ******************************************************************************/ + +package com.openshift.internal.restclient.model; + +import java.util.ArrayList; +import java.util.Collections; + +import org.jboss.dmr.ModelNode; + +import com.openshift.restclient.model.IExecAction; + +/** + * @author Ulf Lilleengen + */ +public class ExecAction implements IExecAction { + + private static final String COMMAND = "command"; + private java.util.List command; + + private ExecAction(java.util.List command) { + this.command = command; + } + + @Override + public java.util.List getCommand() { + return command; + } + + @Override + public String toJson() { + ModelNode node = new ModelNode(); + ModelNode commandNode = node.get(COMMAND); + for (String cmd : command) { + commandNode.add().set(cmd); + } + return node.toJSONString(true); + } + + public static IExecAction fromJson(ModelNode execNode) { + Builder builder = new ExecAction.Builder(); + if (execNode.has(COMMAND)) { + ModelNode commandNode = execNode.get(COMMAND); + commandNode.asList().stream() + .map(ModelNode::asString) + .forEach(builder::command); + } + return builder.build(); + } + + @Override + public String getType() { + return EXEC; + } + + public static class Builder implements IBuilder { + private java.util.List commands = new ArrayList<>(); + + @Override + public IBuilder command(String command) { + commands.add(command); + return this; + } + + @Override + public IExecAction build() { + return new ExecAction(Collections.unmodifiableList(commands)); + } + } +} diff --git a/src/main/java/com/openshift/internal/restclient/model/ImageStream.java b/src/main/java/com/openshift/internal/restclient/model/ImageStream.java index c1c3d06f..1cbca30e 100644 --- a/src/main/java/com/openshift/internal/restclient/model/ImageStream.java +++ b/src/main/java/com/openshift/internal/restclient/model/ImageStream.java @@ -6,6 +6,7 @@ * * Contributors: Red Hat, Inc. ******************************************************************************/ + package com.openshift.internal.restclient.model; import java.util.ArrayList; @@ -23,121 +24,120 @@ import com.openshift.restclient.model.IImageStream; import com.openshift.restclient.model.image.ITagReference; -/** - * @author Jeff Cantrill - */ public class ImageStream extends KubernetesResource implements IImageStream { - private static final String DOCKER_IMAGE_REPO = "spec.dockerImageRepository"; - private static final String STATUS_DOCKER_IMAGE_REPO = "status.dockerImageRepository"; - private static final String SPEC_TAGS = "spec.tags"; - private static final String STATUS_TAGS = "status.tags"; - private static final String TAG = "tag"; - private static final String ITEMS = "items"; - private static final String IMAGE = "image"; - private Map propertyKeys; - - public ImageStream(){ - this(new ModelNode(), null, null); - } - - public ImageStream(ModelNode node, IClient client, Map propertyKeys) { - super(node, client, propertyKeys); - this.propertyKeys = propertyKeys; - } - - @Override - public void setDockerImageRepository(DockerImageURI uri) { - setDockerImageRepository(uri.getAbsoluteUri()); - } - - @Override - public void setDockerImageRepository(String uri) { - set(DOCKER_IMAGE_REPO, uri); - } - - @Override - public DockerImageURI getDockerImageRepository() { - if(getNode().has(getPath(DOCKER_IMAGE_REPO))) { - return new DockerImageURI(asString(DOCKER_IMAGE_REPO)); - } - return new DockerImageURI(asString(STATUS_DOCKER_IMAGE_REPO)); - } - - @Override - public Collection getTagNames() { - ModelNode node = get(STATUS_TAGS); - if(!node.isDefined()) return new ArrayList<>(); - return node.asList().stream().map(n->asString(n,TAG)).collect(Collectors.toList()); - } - - @Override - public Collection getTags() { - ModelNode node = get(SPEC_TAGS); - if(!node.isDefined()) return new ArrayList<>(); - return node.asList().stream().map(n->new TagReference(n, propertyKeys)).collect(Collectors.toList()); - } - - - - @Override - public ITagReference addTag(String name, String fromKind, String fromName) { - TagReference reference = new TagReference(name, fromKind, fromName); - //add last since its copy of node. future sets will do nothing - ModelNode tags = get(SPEC_TAGS); - tags.add(reference.getNode()); - return reference; - } - - @Override - public ITagReference addTag(String name, String fromKind, String fromName, String fromNamespace) { - TagReference reference = new TagReference(name, fromKind, fromName, fromNamespace); - //add last since its copy of node. future sets will do nothing - ModelNode tags = get(SPEC_TAGS); - tags.add(reference.getNode()); - return reference; - } - - @Override - public void setTag(String newTag, String fromTag) { - ModelNode tags = get(SPEC_TAGS); - ModelNode tag = new ModelNode(); - tag.get("name").set(newTag); - ModelNode from = new ModelNode(); - from.get("kind").set("ImageStreamTag"); - from.get("name").set(fromTag); - tag.get("from").set(from); - tags.add(tag); - } - - protected String getImageId(List itemWrappers) { - for (ModelNode itemWrapper : itemWrappers) { - ModelNode image = itemWrapper.get(IMAGE); - if (image != null) { - return image.asString(); - } - } - return null; - } - - @Override - public String getImageId(String tagName) { - String imageId = null; - ModelNode tags = get(STATUS_TAGS); - if (tags.getType() != ModelType.LIST || tagName == null) - return null; - - List tagWrappers = tags.asList(); - for (ModelNode tagWrapper : tagWrappers) { - ModelNode tag = tagWrapper.get(TAG); - ModelNode items = tagWrapper.get(ITEMS); - if (tag.asString().equals(tagName) && items.getType() == ModelType.LIST) { - imageId = getImageId(items.asList()); - break; - } - } - return imageId; - } - -} + private static final String DOCKER_IMAGE_REPO = "spec.dockerImageRepository"; + private static final String STATUS_DOCKER_IMAGE_REPO = "status.dockerImageRepository"; + private static final String SPEC_TAGS = "spec.tags"; + private static final String STATUS_TAGS = "status.tags"; + private static final String TAG = "tag"; + private static final String ITEMS = "items"; + private static final String IMAGE = "image"; + private Map propertyKeys; + + public ImageStream() { + this(new ModelNode(), null, null); + } + + public ImageStream(ModelNode node, IClient client, Map propertyKeys) { + super(node, client, propertyKeys); + this.propertyKeys = propertyKeys; + } + + @Override + public void setDockerImageRepository(DockerImageURI uri) { + setDockerImageRepository(uri.getAbsoluteUri()); + } + + @Override + public void setDockerImageRepository(String uri) { + set(DOCKER_IMAGE_REPO, uri); + } + + @Override + public DockerImageURI getDockerImageRepository() { + if (getNode().has(getPath(DOCKER_IMAGE_REPO))) { + return new DockerImageURI(asString(DOCKER_IMAGE_REPO)); + } + return new DockerImageURI(asString(STATUS_DOCKER_IMAGE_REPO)); + } + + @Override + public Collection getTagNames() { + ModelNode node = get(STATUS_TAGS); + if (!node.isDefined()) { + return new ArrayList<>(); + } + return node.asList().stream().map(n -> asString(n, TAG)).collect(Collectors.toList()); + } + @Override + public Collection getTags() { + ModelNode node = get(SPEC_TAGS); + if (!node.isDefined()) { + return new ArrayList<>(); + } + return node.asList().stream().map(n -> new TagReference(n, propertyKeys)).collect(Collectors.toList()); + } + + @Override + public ITagReference addTag(String name, String fromKind, String fromName) { + TagReference reference = new TagReference(name, fromKind, fromName); + // add last since its copy of node. future sets will do nothing + ModelNode tags = get(SPEC_TAGS); + tags.add(reference.getNode()); + return reference; + } + + @Override + public ITagReference addTag(String name, String fromKind, String fromName, String fromNamespace) { + TagReference reference = new TagReference(name, fromKind, fromName, fromNamespace); + // add last since its copy of node. future sets will do nothing + ModelNode tags = get(SPEC_TAGS); + tags.add(reference.getNode()); + return reference; + } + + @Override + public void setTag(String newTag, String fromTag) { + ModelNode tag = new ModelNode(); + tag.get("name").set(newTag); + ModelNode from = new ModelNode(); + from.get("kind").set("ImageStreamTag"); + from.get("name").set(fromTag); + tag.get("from").set(from); + ModelNode tags = get(SPEC_TAGS); + tags.add(tag); + } + + protected String getImageId(List itemWrappers) { + for (ModelNode itemWrapper : itemWrappers) { + ModelNode image = itemWrapper.get(IMAGE); + if (image != null) { + return image.asString(); + } + } + return null; + } + + @Override + public String getImageId(String tagName) { + String imageId = null; + ModelNode tags = get(STATUS_TAGS); + if (tags.getType() != ModelType.LIST || tagName == null) { + return null; + } + + List tagWrappers = tags.asList(); + for (ModelNode tagWrapper : tagWrappers) { + ModelNode tag = tagWrapper.get(TAG); + ModelNode items = tagWrapper.get(ITEMS); + if (tag.asString().equals(tagName) && items.getType() == ModelType.LIST) { + imageId = getImageId(items.asList()); + break; + } + } + return imageId; + } + +} diff --git a/src/main/java/com/openshift/internal/restclient/model/KubernetesEvent.java b/src/main/java/com/openshift/internal/restclient/model/KubernetesEvent.java index 6258ff00..37902c45 100644 --- a/src/main/java/com/openshift/internal/restclient/model/KubernetesEvent.java +++ b/src/main/java/com/openshift/internal/restclient/model/KubernetesEvent.java @@ -8,23 +8,79 @@ * Contributors: * Red Hat, Inc. - initial API and implementation ******************************************************************************/ + package com.openshift.internal.restclient.model; import java.util.Map; import org.jboss.dmr.ModelNode; +import com.openshift.internal.util.JBossDmrExtentions; import com.openshift.restclient.IClient; import com.openshift.restclient.model.IEvent; +import com.openshift.restclient.model.IObjectReference; -/** - * @author Jeff Cantrill - */ public class KubernetesEvent extends KubernetesResource implements IEvent { - public KubernetesEvent(ModelNode node, IClient client, Map propertyKeys) { - super(node, client, propertyKeys); - // TODO Auto-generated constructor stub - } + public KubernetesEvent(ModelNode node, IClient client, Map propertyKeys) { + super(node, client, propertyKeys); + } + + @Override + public String getReason() { + return asString("reason"); + } + + @Override + public String getMessage() { + return asString("message"); + } + + @Override + public IObjectReference getInvolvedObject() { + return new ObjectReference(get("involvedObject")); + } + + @Override + public String getFirstSeenTimestamp() { + return asString("firstTimestamp"); + } + + @Override + public String getLastSeenTimestamp() { + return asString("lastTimestamp"); + } + + @Override + public int getCount() { + return asInt("count"); + } + + @Override + public String getType() { + return asString("type"); + } + + @Override + public IEventSource getEventSource() { + return new EventSource(get("source"), this.getPropertyKeys()); + } + + private static class EventSource extends ModelNodeAdapter implements IEventSource { + + protected EventSource(ModelNode node, Map propertyKeys) { + super(node, propertyKeys); + } + + @Override + public String getComponent() { + return JBossDmrExtentions.asString(getNode(), getPropertyKeys(), "component"); + } + + @Override + public String getHost() { + return JBossDmrExtentions.asString(getNode(), getPropertyKeys(), "host"); + } + } } diff --git a/src/main/java/com/openshift/internal/restclient/model/KubernetesResource.java b/src/main/java/com/openshift/internal/restclient/model/KubernetesResource.java index 804770d3..792c7c34 100644 --- a/src/main/java/com/openshift/internal/restclient/model/KubernetesResource.java +++ b/src/main/java/com/openshift/internal/restclient/model/KubernetesResource.java @@ -6,8 +6,11 @@ * * Contributors: Red Hat, Inc. ******************************************************************************/ + package com.openshift.internal.restclient.model; +import static com.openshift.internal.restclient.capability.CapabilityInitializer.initializeCapabilities; + import java.util.Collections; import java.util.HashMap; import java.util.Map; @@ -22,350 +25,363 @@ import com.openshift.restclient.ResourceKind; import com.openshift.restclient.capability.CapabilityVisitor; import com.openshift.restclient.capability.ICapability; +import com.openshift.restclient.model.INamespace; import com.openshift.restclient.model.IProject; import com.openshift.restclient.model.IResource; -import static com.openshift.internal.restclient.capability.CapabilityInitializer.initializeCapabilities; - /** * Resource is an abstract representation of a Kubernetes resource * - * @author Jeff Cantrill */ public class KubernetesResource implements IResource, ResourcePropertyKeys { - - private ModelNode node; - private IClient client; - private Map, ICapability> capabilities = new HashMap, ICapability>(); - private Map propertyKeys; - private IProject project; - - /** - * - * @param node - * @param client - * @param overrideProperties the map of properties that override the defaults - */ - public KubernetesResource(ModelNode node, IClient client, Map overrideProperties){ - if(overrideProperties == null) overrideProperties = new HashMap(); - this.node = node; - this.client = client; - this.propertyKeys = overrideProperties; - initializeCapabilities(capabilities, this, client); - } - - @Override - public String getResourceVersion() { - return asString(METADATA_RESOURCE_VERSION); - } - - @Override - public Map getMetadata() { - return asMap(METADATA); - } - - @SuppressWarnings("unchecked") - @Override - public T getCapability(Class capability) { - return (T) capabilities.get(capability); - } - - public Set> getCapabilities(){ - return Collections.unmodifiableSet(capabilities.keySet()); - } - - protected Map, ICapability> getModifiableCapabilities(){ - return capabilities; - } - - @Override - public boolean supports(Class capability) { - return capabilities.containsKey(capability); - } - - @SuppressWarnings("unchecked") - @Override - public R accept(CapabilityVisitor visitor, R unsupportedValue){ - if(capabilities.containsKey(visitor.getCapabilityType())){ - T capability = (T) capabilities.get(visitor.getCapabilityType()); - return (R) visitor.visit(capability); - } - return unsupportedValue; - } - - @Override - public IProject getProject() { - if(this.project == null) { - this.project = client.get(ResourceKind.PROJECT, getNamespace(), ""); - } - return this.project; - } - - @Override - public Map getAnnotations() { - return asMap(ANNOTATIONS); - } - - @Override - public String getAnnotation(String key) { - return getAnnotations().get(key); - } - - - @Override - public void setAnnotation(String name, String value) { - if(value == null) return; - ModelNode annotations = get(ANNOTATIONS); - annotations.get(name).set(value); - } - - @Override - public void removeAnnotation(String name) { - ModelNode annotations = get(ANNOTATIONS); - annotations.remove(name); - } - - @Override - public boolean isAnnotatedWith(String key) { - Map annotations = getAnnotations(); - return annotations.containsKey(key); - } - - public Map getPropertyKeys(){ - return this.propertyKeys; - } - - public IClient getClient(){ - return client; - } - - public void setNode(ModelNode node) { - this.node = node.clone(); - } - public ModelNode getNode(){ - return node; - } - - public void refresh(){ - //TODO find better way to bypass serialization/deserialization - this.node = ModelNode.fromJSONString(client.get(getKind(), getName(), getNamespace()).toString()); - } - - @Override - public String getKind(){ - return asString(KIND); - } - - @Override - public String getApiVersion(){ - return asString(APIVERSION); - } - - @Override - public String getCreationTimeStamp(){ - return asString(CREATION_TIMESTAMP); - } - @Override - public String getName(){ - return asString(METADATA_NAME); - } - - public void setName(String name) { - set(METADATA_NAME, name); - } - - @Override - public String getNamespace(){ - return asString(METADATA_NAMESPACE); - } - - public void setNamespace(String namespace){ - set(METADATA_NAMESPACE, namespace); - } - - @Override - public void addLabel(String key, String value) { - ModelNode labels = node.get(getPath(LABELS)); - labels.get(key).set(value); - } - - - @Override - public Map getLabels() { - return asMap(LABELS); - } - - /*---------- utility methods ------*/ - protected ModelNode get(String key){ - return get(node, key); - } - protected ModelNode get(ModelNode node, String key){ - return node.get(getPath(key)); - } - - protected Map getEnvMap(String key) { - Map values = new HashMap(); - ModelNode source = node.get(getPath(key)); - if(source.getType() == ModelType.LIST){ - for (ModelNode value : source.asList()) { - values.put(value.get("name").asString(), value.get("value").asString()); - } - } - return values; - } - - protected void set(String key, Map values) { - JBossDmrExtentions.set(node, propertyKeys, key, values); - } - - protected void set(String key, int value) { - JBossDmrExtentions.set(node, propertyKeys, key, value); - } - - protected void set(ModelNode node, String key, int value) { - JBossDmrExtentions.set(node, propertyKeys, key, value); - } - - protected void set(String key, String value){ - JBossDmrExtentions.set(node, propertyKeys, key, value); - } - - protected void set(ModelNode node, String key, String value){ - JBossDmrExtentions.set(node, propertyKeys, key, value); - } - - protected void set(String key, boolean value){ - JBossDmrExtentions.set(node, propertyKeys, key, value); - } - - protected void set(ModelNode node, String key, boolean value){ - JBossDmrExtentions.set(node, propertyKeys, key, value); - } - - protected void setEnvMap(String key, Map values) { - ModelNode mapNodeParent = node.get(getPath(key)); - for(Map.Entry value: values.entrySet()) { - ModelNode mapNode = mapNodeParent.add(); - mapNode.get("name").set(value.getKey()); - mapNode.get("value").set(value.getValue()); - } - } - - protected String[] getPath(String key) { - return JBossDmrExtentions.getPath(propertyKeys, key); - } - - protected String asString(ModelNode node, String subKey) { - return JBossDmrExtentions.asString(node, propertyKeys, subKey); - } - - protected int asInt(String key){ - return JBossDmrExtentions.asInt(node, propertyKeys, key); - } - - protected int asInt(ModelNode node, String key){ - return JBossDmrExtentions.asInt(node, propertyKeys, key); - } - - protected Map asMap(String property){ - return JBossDmrExtentions.asMap(this.node, propertyKeys, property); - } - - protected String asString(String property){ - return JBossDmrExtentions.asString(node, propertyKeys, property); - } - - protected boolean asBoolean(ModelNode node, String property) { - return JBossDmrExtentions.asBoolean(node, propertyKeys, property); - } - - protected boolean asBoolean(String property) { - return JBossDmrExtentions.asBoolean(node, propertyKeys, property); - } - - protected Set asSet(String property, ModelType type) { - return JBossDmrExtentions.asSet(node, propertyKeys, property, type); - } - - protected void set(String property, Set values) { - JBossDmrExtentions.set(node, propertyKeys, property, values); - } - - protected void set(String property, String... values) { - JBossDmrExtentions.set(node, propertyKeys, property, values); - } - - @Override - public String toString() { - return toJson(true); - } - - public String toPrettyString(){ - return toJson(false); - } - - @Override - public int hashCode() { - String namespace = getNamespace(); - String name = getName(); - String kind = getKind(); - final int prime = 31; - return prime * (namespace.hashCode() + name.hashCode() + kind.hashCode()); - } - - @Override - public boolean equals(Object obj) { - if (this == obj) - return true; - else if (obj == null) - return false; - else if (getClass() != obj.getClass()) - return false; - else { - KubernetesResource other = (KubernetesResource) obj; - if (getKind() != null){ - if (!getKind().equals(other.getKind())) { - return false; - } - } else { - if (other.getKind() != null) { - return false; - } - } - if (getNamespace() != null) { - if(!getNamespace().equals(other.getNamespace())) { - return false; - } - } else { - if (other.getNamespace() != null) { - return false; - } - } - if (getName() != null) { - if(!getName().equals(other.getName())) { - return false; - } - } else { - if (other.getName() != null) { - return false; - } - } - - } - return true; - } - - @Override - public String toJson() { - return toJson(false); - } - - @Override - public String toJson(boolean compact) { - return JBossDmrExtentions.toJsonString(node, compact); - } - - -} + private ModelNode node; + private IClient client; + private Map, ICapability> capabilities = new HashMap, ICapability>(); + private Map propertyKeys; + private IProject project; + private INamespace namespace; + + /** + * + * @param overrideProperties + * the map of properties that override the defaults + */ + public KubernetesResource(ModelNode node, IClient client, Map overrideProperties) { + if (overrideProperties == null) { + overrideProperties = new HashMap(); + } + this.node = node; + this.client = client; + this.propertyKeys = overrideProperties; + initializeCapabilities(capabilities, this, client); + } + + @Override + public String getResourceVersion() { + return asString(METADATA_RESOURCE_VERSION); + } + + @Override + public Map getMetadata() { + return asMap(METADATA); + } + + @SuppressWarnings("unchecked") + @Override + public T getCapability(Class capability) { + return (T) capabilities.get(capability); + } + + public Set> getCapabilities() { + return Collections.unmodifiableSet(capabilities.keySet()); + } + + protected Map, ICapability> getModifiableCapabilities() { + return capabilities; + } + + @Override + public boolean supports(Class capability) { + return capabilities.containsKey(capability); + } + + @SuppressWarnings("unchecked") + @Override + public R accept(CapabilityVisitor visitor, R unsupportedValue) { + if (capabilities.containsKey(visitor.getCapabilityType())) { + T capability = (T) capabilities.get(visitor.getCapabilityType()); + return (R) visitor.visit(capability); + } + return unsupportedValue; + } + + @Override + public IProject getProject() { + if (this.project == null) { + this.project = client.get(ResourceKind.PROJECT, getNamespaceName(), ""); + } + return this.project; + } + + @Override + public INamespace getNamespace() { + if (this.namespace == null) { + this.namespace = client.get(ResourceKind.NAMESPACE, getNamespaceName(), ""); + } + return this.namespace; + } + + @Override + public Map getAnnotations() { + return asMap(ANNOTATIONS); + } + + @Override + public String getAnnotation(String key) { + return getAnnotations().get(key); + } + + @Override + public void setAnnotation(String name, String value) { + if (value == null) { + return; + } + ModelNode annotations = get(ANNOTATIONS); + annotations.get(name).set(value); + } + + @Override + public void removeAnnotation(String name) { + ModelNode annotations = get(ANNOTATIONS); + annotations.remove(name); + } + + @Override + public boolean isAnnotatedWith(String key) { + Map annotations = getAnnotations(); + return annotations.containsKey(key); + } + + public Map getPropertyKeys() { + return this.propertyKeys; + } + + public IClient getClient() { + return client; + } + + public void setNode(ModelNode node) { + this.node = node.clone(); + } + + public ModelNode getNode() { + return node; + } + + public void refresh() { + // TODO find better way to bypass serialization/deserialization + this.node = ModelNode.fromJSONString(client.get(getKind(), getName(), getNamespaceName()).toString()); + } + + @Override + public String getKind() { + return asString(KIND); + } + + @Override + public String getApiVersion() { + return asString(APIVERSION); + } + + @Override + public String getCreationTimeStamp() { + return asString(CREATION_TIMESTAMP); + } + + @Override + public String getName() { + return asString(METADATA_NAME); + } + + public void setName(String name) { + set(METADATA_NAME, name); + } + + @Override + public String getNamespaceName() { + return asString(METADATA_NAMESPACE); + } + public void setNamespace(String namespace) { + set(METADATA_NAMESPACE, namespace); + } + + @Override + public void addLabel(String key, String value) { + ModelNode labels = node.get(getPath(LABELS)); + labels.get(key).set(value); + } + + @Override + public Map getLabels() { + return asMap(LABELS); + } + + /*---------- utility methods ------*/ + protected boolean has(String key) { + return node.has(getPath(key)); + } + + protected ModelNode get(String key) { + return get(node, key); + } + + protected ModelNode get(ModelNode node, String key) { + return node.get(getPath(key)); + } + + protected Map getEnvMap(String key) { + Map values = new HashMap(); + ModelNode source = node.get(getPath(key)); + if (source.getType() == ModelType.LIST) { + for (ModelNode value : source.asList()) { + values.put(value.get("name").asString(), value.get("value").asString()); + } + } + return values; + } + + protected void set(String key, Map values) { + JBossDmrExtentions.set(node, propertyKeys, key, values); + } + + protected void set(String key, int value) { + JBossDmrExtentions.set(node, propertyKeys, key, value); + } + + protected void set(ModelNode node, String key, int value) { + JBossDmrExtentions.set(node, propertyKeys, key, value); + } + + protected void set(String key, String value) { + JBossDmrExtentions.set(node, propertyKeys, key, value); + } + + protected void set(ModelNode node, String key, String value) { + JBossDmrExtentions.set(node, propertyKeys, key, value); + } + + protected void set(String key, boolean value) { + JBossDmrExtentions.set(node, propertyKeys, key, value); + } + + protected void set(ModelNode node, String key, boolean value) { + JBossDmrExtentions.set(node, propertyKeys, key, value); + } + + protected void set(String property, Set values) { + JBossDmrExtentions.set(node, propertyKeys, property, values); + } + + protected void set(String property, String... values) { + JBossDmrExtentions.set(node, propertyKeys, property, values); + } + + protected void setEnvMap(String key, Map values) { + ModelNode mapNodeParent = node.get(getPath(key)); + for (Map.Entry value : values.entrySet()) { + ModelNode mapNode = mapNodeParent.add(); + mapNode.get("name").set(value.getKey()); + mapNode.get("value").set(value.getValue()); + } + } + + protected String[] getPath(String key) { + return JBossDmrExtentions.getPath(propertyKeys, key); + } + + protected String asString(ModelNode node, String subKey) { + return JBossDmrExtentions.asString(node, propertyKeys, subKey); + } + + protected String asString(String property) { + return JBossDmrExtentions.asString(node, propertyKeys, property); + } + + protected int asInt(String key) { + return JBossDmrExtentions.asInt(node, propertyKeys, key); + } + + protected int asInt(ModelNode node, String key) { + return JBossDmrExtentions.asInt(node, propertyKeys, key); + } + + protected Map asMap(String property) { + return JBossDmrExtentions.asMap(this.node, propertyKeys, property); + } + + protected boolean asBoolean(ModelNode node, String property) { + return JBossDmrExtentions.asBoolean(node, propertyKeys, property); + } + + protected boolean asBoolean(String property) { + return JBossDmrExtentions.asBoolean(node, propertyKeys, property); + } + + @SuppressWarnings("rawtypes") + protected Set asSet(String property, ModelType type) { + return JBossDmrExtentions.asSet(node, propertyKeys, property, type); + } + + @Override + public String toString() { + return toJson(true); + } + + public String toPrettyString() { + return toJson(false); + } + + @Override + public int hashCode() { + String namespace = getNamespaceName(); + String name = getName(); + String kind = getKind(); + final int prime = 31; + return prime * (namespace.hashCode() + name.hashCode() + kind.hashCode()); + } + + @Override + public boolean equals(Object obj) { + if (this == obj) { + return true; + } else if (obj == null) { + return false; + } else if (getClass() != obj.getClass()) { + return false; + } else { + KubernetesResource other = (KubernetesResource) obj; + if (getKind() != null) { + if (!getKind().equals(other.getKind())) { + return false; + } + } else { + if (other.getKind() != null) { + return false; + } + } + if (getNamespaceName() != null) { + if (!getNamespaceName().equals(other.getNamespaceName())) { + return false; + } + } else { + if (other.getNamespaceName() != null) { + return false; + } + } + if (getName() != null) { + if (!getName().equals(other.getName())) { + return false; + } + } else { + if (other.getName() != null) { + return false; + } + } + + } + return true; + } + + @Override + public String toJson() { + return toJson(false); + } + + @Override + public String toJson(boolean compact) { + return JBossDmrExtentions.toJsonString(node, compact); + } + +} diff --git a/src/main/java/com/openshift/internal/restclient/model/Lifecycle.java b/src/main/java/com/openshift/internal/restclient/model/Lifecycle.java new file mode 100644 index 00000000..bd4f3339 --- /dev/null +++ b/src/main/java/com/openshift/internal/restclient/model/Lifecycle.java @@ -0,0 +1,95 @@ +/******************************************************************************* + * Copyright (c) 2016 Red Hat, Inc. + * Distributed under license by Red Hat, Inc. All rights reserved. + * This program is made available under the terms of the + * Eclipse Public License v1.0 which accompanies this distribution, + * and is available at http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Red Hat, Inc. - initial API and implementation + ******************************************************************************/ + +package com.openshift.internal.restclient.model; + +import java.util.Optional; + +import org.jboss.dmr.ModelNode; + +import com.openshift.restclient.model.IHandler; +import com.openshift.restclient.model.ILifecycle; + +/** + * @author Ulf Lilleengen + */ +public class Lifecycle implements ILifecycle { + private static final String PRESTOP = "preStop"; + private static final String POSTSTART = "postStart"; + + private final Optional postStart; + private final Optional preStop; + + private Lifecycle(Optional preStop, Optional postStart) { + this.preStop = preStop; + this.postStart = postStart; + } + + @Override + public Optional getPostStart() { + return postStart; + } + + @Override + public Optional getPreStop() { + return preStop; + } + + @Override + public String toJson() { + ModelNode node = new ModelNode(); + preStop.ifPresent( + handler -> node.get(PRESTOP).get(handler.getType()).set(ModelNode.fromJSONString(handler.toJson()))); + postStart.ifPresent( + handler -> node.get(POSTSTART).get(handler.getType()).set(ModelNode.fromJSONString(handler.toJson()))); + return node.toJSONString(true); + } + + public static ILifecycle fromJson(ModelNode json) { + Builder builder = new Builder(); + if (json.has(PRESTOP)) { + builder.preStop(parseHandler(json.get(PRESTOP)).orElse(null)); + } + + if (json.has(POSTSTART)) { + builder.postStart(parseHandler(json.get(POSTSTART)).orElse(null)); + } + return builder.build(); + } + + private static Optional parseHandler(ModelNode node) { + if (node.has(IHandler.EXEC)) { + return Optional.of(ExecAction.fromJson(node.get(IHandler.EXEC))); + } else { + return Optional.empty(); + } + } + + public static class Builder implements IBuilder { + + private IHandler preStop = null; + private IHandler postStart = null; + + public ILifecycle build() { + return new Lifecycle(Optional.ofNullable(preStop), Optional.ofNullable(postStart)); + } + + public Builder postStart(IHandler handler) { + this.postStart = handler; + return this; + } + + public Builder preStop(IHandler handler) { + this.preStop = handler; + return this; + } + } +} diff --git a/src/main/java/com/openshift/internal/restclient/model/LimitRange.java b/src/main/java/com/openshift/internal/restclient/model/LimitRange.java index 2896cb05..cf33253c 100644 --- a/src/main/java/com/openshift/internal/restclient/model/LimitRange.java +++ b/src/main/java/com/openshift/internal/restclient/model/LimitRange.java @@ -8,6 +8,7 @@ * Contributors: * Red Hat, Inc. - initial API and implementation ******************************************************************************/ + package com.openshift.internal.restclient.model; import java.util.Map; @@ -19,9 +20,8 @@ public class LimitRange extends KubernetesResource implements ILimitRange { - public LimitRange(ModelNode node, IClient client, Map propertyKeys) { - super(node, client, propertyKeys); - // TODO Auto-generated constructor stub - } + public LimitRange(ModelNode node, IClient client, Map propertyKeys) { + super(node, client, propertyKeys); + } } diff --git a/src/main/java/com/openshift/internal/restclient/model/List.java b/src/main/java/com/openshift/internal/restclient/model/List.java index 4c050961..a52fb3cc 100644 --- a/src/main/java/com/openshift/internal/restclient/model/List.java +++ b/src/main/java/com/openshift/internal/restclient/model/List.java @@ -6,6 +6,7 @@ * * Contributors: Red Hat, Inc. ******************************************************************************/ + package com.openshift.internal.restclient.model; import java.util.ArrayList; @@ -21,57 +22,58 @@ import com.openshift.restclient.model.IList; import com.openshift.restclient.model.IResource; -/** - * @author Jeff Cantrill - */ -public class List extends KubernetesResource implements IList{ +public class List extends KubernetesResource implements IList { + + private static final String ITEMS = "items"; + + private String kind; + private Collection items; + + public List(ModelNode node, IClient client, Map propertyKeys) { + super(node, client, propertyKeys); + String listKind = asString(KIND); + if (StringUtils.isNotBlank(listKind)) { + kind = listKind.substring(0, listKind.length() - "List".length()); + } + } - private String kind; - private Collection items; - public List(ModelNode node, IClient client, Map propertyKeys) { - super(node, client, propertyKeys); - String listKind = asString(KIND); - if(StringUtils.isNotBlank(listKind)) { - kind = listKind.substring(0, listKind.length() - "List".length()); - } - - } - - @Override - public Collection getItems(){ - if(items == null) { - String key = getNode().has(OBJECTS) ? OBJECTS : "items"; - ModelNode listNode = get(key); - if (listNode.isDefined()) { - Collection nodes = get(key).asList(); - items = new ArrayList<>(nodes.size()); - IResourceFactory factory = getClient().getResourceFactory(); - if (factory != null) { - for (ModelNode node : nodes) { - if (kind != null && !node.get(KIND).isDefined()) { - set(node, KIND, kind); - } - IResource resource = factory.create(node.toJSONString(true)); - items.add(resource); - } - } - } else { - items = Collections.emptyList(); - } - } - return Collections.unmodifiableCollection(items); - } + @Override + public Collection getItems() { + if (items == null) { + ModelNode listNode = get(ITEMS); + if (listNode.isDefined()) { + Collection nodes = listNode.asList(); + items = new ArrayList<>(nodes.size()); + IResourceFactory factory = getClient().getResourceFactory(); + if (factory != null) { + for (ModelNode node : nodes) { + if (kind != null && !node.get(KIND).isDefined()) { + set(node, KIND, kind); + } + if (!node.get(APIVERSION).isDefined()) { + set(node, APIVERSION, getApiVersion()); + } + IResource resource = factory.create(node.toJSONString(true)); + items.add(resource); + } + } + } else { + items = Collections.emptyList(); + } + } + return Collections.unmodifiableCollection(items); + } - @Override - public void addAll(Collection items) { - if(this.items == null) { - this.items = new ArrayList<>(); - } - ModelNode itemNode = get(OBJECTS); - for (IResource resource : items) { - itemNode.add(ModelNode.fromJSONString(resource.toString())); - this.items.add(resource); - } - } + @Override + public void addAll(Collection items) { + if (this.items == null) { + this.items = new ArrayList<>(); + } + ModelNode itemNode = get(ITEMS); + for (IResource resource : items) { + itemNode.add(ModelNode.fromJSONString(resource.toString())); + this.items.add(resource); + } + } } diff --git a/src/main/java/com/openshift/internal/restclient/model/ModelNodeAdapter.java b/src/main/java/com/openshift/internal/restclient/model/ModelNodeAdapter.java index 2fd1723c..bc35e76f 100644 --- a/src/main/java/com/openshift/internal/restclient/model/ModelNodeAdapter.java +++ b/src/main/java/com/openshift/internal/restclient/model/ModelNodeAdapter.java @@ -8,6 +8,7 @@ * Contributors: * Red Hat, Inc. - initial API and implementation ******************************************************************************/ + package com.openshift.internal.restclient.model; import java.util.Map; @@ -15,46 +16,43 @@ import org.jboss.dmr.ModelNode; import com.openshift.internal.util.JBossDmrExtentions; +import com.openshift.restclient.model.JSONSerializeable; /** - * Adapter class between what we want - * and the backing DMR json store - * @author Jeff Cantrill + * Adapter class between what we want and the backing DMR json store * */ public class ModelNodeAdapter implements JSONSerializeable { - - private ModelNode node; - private Map propertyKeys; - - protected ModelNodeAdapter(ModelNode node, Map propertyKeys) { - this.node = node; - this.propertyKeys = propertyKeys; - } + private ModelNode node; + private Map propertyKeys; - protected ModelNode getNode(){ - return node; - } - - @Override - public String toJson() { - return toJson(false); - } + protected ModelNodeAdapter(ModelNode node, Map propertyKeys) { + this.node = node; + this.propertyKeys = propertyKeys; + } - public String toJson(boolean compact) { - return JBossDmrExtentions.toJsonString(node, compact); - } + protected ModelNode getNode() { + return node; + } - protected Map getPropertyKeys() { - return propertyKeys; - } + @Override + public String toJson() { + return toJson(false); + } + @Override + public String toJson(boolean compact) { + return JBossDmrExtentions.toJsonString(node, compact); + } + protected Map getPropertyKeys() { + return propertyKeys; + } - @Override - public String toString() { - return toJson(false); - } + @Override + public String toString() { + return toJson(false); + } } diff --git a/src/main/java/com/openshift/internal/restclient/model/ModelNodeBuilder.java b/src/main/java/com/openshift/internal/restclient/model/ModelNodeBuilder.java index c4ce16f8..f5fa85ea 100644 --- a/src/main/java/com/openshift/internal/restclient/model/ModelNodeBuilder.java +++ b/src/main/java/com/openshift/internal/restclient/model/ModelNodeBuilder.java @@ -8,57 +8,56 @@ * Contributors: * Red Hat, Inc. - initial API and implementation ******************************************************************************/ + package com.openshift.internal.restclient.model; +import java.util.Collections; +import java.util.Map; + import org.jboss.dmr.ModelNode; import com.openshift.internal.util.JBossDmrExtentions; -import java.util.Collections; -import java.util.Map; - /** - * Builder to streamline the creation - * of ModelNode trees - * @author jeff.cantrill + * Builder to streamline the creation of ModelNode trees * */ public class ModelNodeBuilder { - - private static final Map PROPS = Collections.emptyMap(); - private ModelNode node; - public ModelNodeBuilder() { - this.node = new ModelNode(); - } + private static final Map PROPS = Collections.emptyMap(); + private ModelNode node; + + public ModelNodeBuilder() { + this.node = new ModelNode(); + } + + public ModelNodeBuilder set(String path, String value) { + JBossDmrExtentions.set(node, PROPS, path, value); + return this; + } + + public ModelNodeBuilder set(String path, ModelNode child) { + JBossDmrExtentions.get(node, PROPS, path).set(child); + return this; + } + + public ModelNodeBuilder set(String path, int value) { + JBossDmrExtentions.set(node, PROPS, path, value); + return this; + } - public ModelNodeBuilder set(String path, String value) { - JBossDmrExtentions.set(node, PROPS, path, value); - return this; - } + public ModelNodeBuilder set(String path, boolean value) { + JBossDmrExtentions.set(node, PROPS, path, value); + return this; + } - public ModelNodeBuilder set(String path, ModelNode child) { - JBossDmrExtentions.get(node, PROPS, path).set(child); - return this; - } + public ModelNodeBuilder add(String path, ModelNodeBuilder builder) { + node.get(JBossDmrExtentions.getPath(path)).add(builder.build()); + return this; + } - public ModelNodeBuilder set(String path, int value) { - JBossDmrExtentions.set(node, PROPS, path, value); - return this; - } + public ModelNode build() { + return this.node; + } - public ModelNodeBuilder set(String path, boolean value) { - JBossDmrExtentions.set(node, PROPS, path, value); - return this; - } - - public ModelNodeBuilder add(String path, ModelNodeBuilder builder) { - node.get(JBossDmrExtentions.getPath(path)).add(builder.build()); - return this; - } - - public ModelNode build() { - return this.node; - } - } diff --git a/src/main/java/com/openshift/internal/restclient/model/Namespace.java b/src/main/java/com/openshift/internal/restclient/model/Namespace.java new file mode 100644 index 00000000..1caedf3d --- /dev/null +++ b/src/main/java/com/openshift/internal/restclient/model/Namespace.java @@ -0,0 +1,73 @@ +package com.openshift.internal.restclient.model; + +import static com.openshift.internal.restclient.capability.CapabilityInitializer.initializeCapabilities; + +import java.util.ArrayList; +import java.util.List; +import java.util.Map; + +import org.jboss.dmr.ModelNode; + +import com.openshift.restclient.IClient; +import com.openshift.restclient.model.INamespace; +import com.openshift.restclient.model.IResource; + +public class Namespace extends KubernetesResource implements INamespace { + + private static final String ANNOTATION_DISPLAY_NAME = "openshift.io/display-name"; + private static final String ANNOTATION_DESCRIPTION = "openshift.io/description"; + private static final String ANNOTATION_REQUESTER = "openshift.io/requester"; + + public Namespace(ModelNode node, IClient client, Map propertyKeys) { + super(node, client, propertyKeys); + initializeCapabilities(getModifiableCapabilities(), this, getClient()); + } + + @Override + public List getResources(String kind) { + if(getClient() == null) { + return new ArrayList<>(); + } + return getClient().list(kind, getName()); + } + + @Override + public Namespace getNamespace() { + return this; + } + + @Override + public String getNamespaceName() { + return this.getName(); + } + + @Override + public String getDisplayName() { + return getAnnotation(ANNOTATION_DISPLAY_NAME); + } + + @Override + public void setDisplayName(String displayName) { + setAnnotation(ANNOTATION_DISPLAY_NAME, displayName); + } + + @Override + public String getDescription() { + return getAnnotation(ANNOTATION_DESCRIPTION); + } + + @Override + public void setDescription(String description) { + setAnnotation(ANNOTATION_DESCRIPTION, description); + } + + @Override + public String getRequester() { + return getAnnotation(ANNOTATION_REQUESTER); + } + + @Override + public void setRequest(String requester) { + setAnnotation(ANNOTATION_REQUESTER, requester); + } +} diff --git a/src/main/java/com/openshift/internal/restclient/model/ObjectReference.java b/src/main/java/com/openshift/internal/restclient/model/ObjectReference.java index 6a4e7120..5a9410b9 100644 --- a/src/main/java/com/openshift/internal/restclient/model/ObjectReference.java +++ b/src/main/java/com/openshift/internal/restclient/model/ObjectReference.java @@ -8,10 +8,16 @@ * Contributors: * Red Hat, Inc. - initial API and implementation ******************************************************************************/ + package com.openshift.internal.restclient.model; -import static com.openshift.internal.restclient.model.properties.ResourcePropertyKeys.*; -import static com.openshift.internal.util.JBossDmrExtentions.*; +import static com.openshift.internal.restclient.model.properties.ResourcePropertyKeys.APIVERSION; +import static com.openshift.internal.restclient.model.properties.ResourcePropertyKeys.KIND; +import static com.openshift.internal.restclient.model.properties.ResourcePropertyKeys.NAME; +import static com.openshift.internal.restclient.model.properties.ResourcePropertyKeys.NAMESPACE; +import static com.openshift.internal.restclient.model.properties.ResourcePropertyKeys.RESOURCE_VERSION; +import static com.openshift.internal.util.JBossDmrExtentions.asString; +import static com.openshift.internal.util.JBossDmrExtentions.set; import java.util.Collections; import java.util.Map; @@ -22,94 +28,99 @@ import com.openshift.restclient.model.IObjectReference; public class ObjectReference implements IObjectReference { - - private static final Map KEYS = Collections.emptyMap(); - private ModelNode node; - - public ObjectReference(ModelNode node) { - this.node = node; - } - - @Override - public String getKind() { - return asString(node, null, KIND); - } - - public void setKind(String kind) { - set(node, KEYS, KIND, kind); - } - - public void setName(String name) { - set(node, KEYS, NAME, name); - } - - public void setNamespace(String namespace) { - set(node, KEYS, NAMESPACE, namespace); - } - - @Override - public String getApiVersion() { - return asString(node, null, APIVERSION); - } - - @Override - public String getResourceVersion() { - return asString(node, null, RESOURCE_VERSION); - } - - @Override - public String getName() { - return asString(node, null, NAME); - } - - @Override - public String getNamespace() { - return asString(node, null, "namespace"); - } - - @Override - public String getFieldPath() { - return asString(node, null, "fieldPath"); - } - - @Override - public String getUID() { - return asString(node, null, "uid"); - } - - @Override - public String toJson() { - return JBossDmrExtentions.toJsonString(node, false); - } - - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = prime * result + ((node == null) ? 0 : node.hashCode()); - return result; - } - - @Override - public boolean equals(Object obj) { - if (this == obj) - return true; - if (obj == null) - return false; - if (getClass() != obj.getClass()) - return false; - ObjectReference other = (ObjectReference) obj; - if (node == null) { - if (other.node != null) - return false; - } else if (!node.equals(other.node)) - return false; - return true; - } - - @Override - public String toString() { - return toJson(); - } + + private static final Map KEYS = Collections.emptyMap(); + private ModelNode node; + + public ObjectReference(ModelNode node) { + this.node = node; + } + + @Override + public String getKind() { + return asString(node, null, KIND); + } + + public void setKind(String kind) { + set(node, KEYS, KIND, kind); + } + + public void setName(String name) { + set(node, KEYS, NAME, name); + } + + public void setNamespace(String namespace) { + set(node, KEYS, NAMESPACE, namespace); + } + + @Override + public String getApiVersion() { + return asString(node, null, APIVERSION); + } + + @Override + public String getResourceVersion() { + return asString(node, null, RESOURCE_VERSION); + } + + @Override + public String getName() { + return asString(node, null, NAME); + } + + @Override + public String getNamespace() { + return asString(node, null, "namespace"); + } + + @Override + public String getFieldPath() { + return asString(node, null, "fieldPath"); + } + + @Override + public String getUID() { + return asString(node, null, "uid"); + } + + @Override + public String toJson() { + return JBossDmrExtentions.toJsonString(node, false); + } + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + ((node == null) ? 0 : node.hashCode()); + return result; + } + + @Override + public boolean equals(Object obj) { + if (this == obj) { + return true; + } + if (obj == null) { + return false; + } + if (getClass() != obj.getClass()) { + return false; + } + ObjectReference other = (ObjectReference) obj; + if (node == null) { + if (other.node != null) { + return false; + } + } else if (!node.equals(other.node)) { + return false; + } + return true; + } + + @Override + public String toString() { + return toJson(); + } } diff --git a/src/main/java/com/openshift/internal/restclient/model/Pod.java b/src/main/java/com/openshift/internal/restclient/model/Pod.java index b1785317..0d7caa57 100644 --- a/src/main/java/com/openshift/internal/restclient/model/Pod.java +++ b/src/main/java/com/openshift/internal/restclient/model/Pod.java @@ -6,102 +6,160 @@ * * Contributors: Red Hat, Inc. ******************************************************************************/ + package com.openshift.internal.restclient.model; import static com.openshift.internal.restclient.capability.CapabilityInitializer.initializeCapabilities; import java.util.ArrayList; +import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.HashSet; +import java.util.List; import java.util.Map; import java.util.Set; import java.util.stream.Collectors; +import org.apache.commons.lang.StringUtils; import org.jboss.dmr.ModelNode; import org.jboss.dmr.ModelType; +import com.openshift.internal.util.JBossDmrExtentions; import com.openshift.restclient.IClient; import com.openshift.restclient.model.IContainer; import com.openshift.restclient.model.IPod; import com.openshift.restclient.model.IPort; +import com.openshift.restclient.utils.ResourceStatus; -/** - * @author Jeff Cantrill - */ public class Pod extends KubernetesResource implements IPod { - private static final String POD_IP = "status.podIP"; - private static final String POD_HOST = "status.hostIP"; - private static final String POD_STATUS = "status.phase"; - private static final String POD_CONTAINERS = "spec.containers"; - - public Pod(ModelNode node, IClient client, Map propertyKeys) { - super(node, client, propertyKeys); - initializeCapabilities(getModifiableCapabilities(), this, client); - } - - @Override - public String getIP() { - return asString(POD_IP); - } - - @Override - public String getHost() { - return asString(POD_HOST); - } - - @Override - public Collection getImages() { - Collection images = new ArrayList(); - ModelNode node = get(POD_CONTAINERS); - if(node.getType() != ModelType.LIST) return images; - for (ModelNode entry : node.asList()) { - images.add(entry.get("image").asString()); - } - return images; - } - - @Override - public String getStatus() { - return asString(POD_STATUS); - } - - @Override - public Set getContainerPorts() { - Set ports = new HashSet(); - ModelNode node = get(POD_CONTAINERS); - if(node.getType() == ModelType.LIST) { - for (ModelNode container : node.asList()) { - ModelNode containerPorts = container.get(getPath(PORTS)); - if(containerPorts.getType() == ModelType.LIST) { - for (ModelNode portNode : containerPorts.asList()) { - ports.add(new Port(portNode)); - } - } - } - } - return Collections.unmodifiableSet(ports); - } - - @Override - public IContainer addContainer(String name) { - ModelNode containers = get(POD_CONTAINERS); - Container container = new Container(containers.add()); - container.setName(name); - return container; - } - - @Override - public Collection getContainers() { - ModelNode containers = get(POD_CONTAINERS); - if(containers.isDefined() && ModelType.LIST == containers.getType()) { - return containers.asList().stream().map(n->new Container(n, getPropertyKeys())).collect(Collectors.toList()); - } - return Collections.emptyList(); - } - - - - + private static final String POD_IP = "status.podIP"; + private static final String POD_HOST = "status.hostIP"; + private static final String POD_CONTAINERS = "spec.containers"; + private static final String POD_DELETION_TIMESTAMP = "metadata.deletionTimestamp"; + + private static final String POD_STATUS_PHASE = "status.phase"; + private static final String POD_STATUS_REASON = "status.reason"; + private static final String POD_STATUS_CONTAINER_STATUSES = "status.containerStatuses"; + private static final String CONTAINER_STATUS_READY = "ready"; + + // container reasons fields and corresponding status prefixes + private static final List POD_STATUS_CONTAINER_STATES = Arrays.asList( + new String[] { "state.waiting.reason", "" }, + new String[] { "state.terminated.reason", "" }, + new String[] { "state.terminated.signal", "Signal: " }, + new String[] { "state.terminated.exitCode", "Exit Code: " }); + + public Pod(ModelNode node, IClient client, Map propertyKeys) { + super(node, client, propertyKeys); + initializeCapabilities(getModifiableCapabilities(), this, client); + } + + @Override + public String getIP() { + return asString(POD_IP); + } + + @Override + public String getHost() { + return asString(POD_HOST); + } + + @Override + public Collection getImages() { + Collection images = new ArrayList<>(); + ModelNode node = get(POD_CONTAINERS); + if (node.getType() != ModelType.LIST) { + return images; + } + for (ModelNode entry : node.asList()) { + images.add(entry.get("image").asString()); + } + return images; + } + + /** + * The logic of the method is a copied from 'podStatus' function of + * [app/scripts/filters/resources.js] of [openshift/origin-web-console] + */ + @Override + public String getStatus() { + if (has(POD_DELETION_TIMESTAMP)) { + return ResourceStatus.TERMINATING; + } + ModelNode node = get(POD_STATUS_CONTAINER_STATUSES); + if (node.getType() == ModelType.LIST) { + for (ModelNode containerStatus : node.asList()) { + String status = getContainerStatusStringIfExist(containerStatus); + // TODO: take all containers into account + // -> fetch all status and merge them, currently we're returning the 1st one. + if (status != null) { + return status; + } + } + } + return has(POD_STATUS_REASON) ? asString(POD_STATUS_REASON) : asString(POD_STATUS_PHASE); + } + + private String getContainerStatusStringIfExist(ModelNode containerStatus) { + for (String[] pathAndLabel : POD_STATUS_CONTAINER_STATES) { + String path = pathAndLabel[0]; + String statusPostfix = JBossDmrExtentions.asString(containerStatus, null, path); + if (StringUtils.isNotEmpty(statusPostfix)) { + String label = pathAndLabel[1]; + return label + statusPostfix; + } + } + return null; + } + + @Override + public Set getContainerPorts() { + Set ports = new HashSet<>(); + ModelNode node = get(POD_CONTAINERS); + if (node.getType() == ModelType.LIST) { + for (ModelNode container : node.asList()) { + ModelNode containerPorts = container.get(getPath(PORTS)); + if (containerPorts.getType() == ModelType.LIST) { + for (ModelNode portNode : containerPorts.asList()) { + ports.add(new Port(portNode)); + } + } + } + } + return Collections.unmodifiableSet(ports); + } + + @Override + public IContainer addContainer(String name) { + ModelNode containers = get(POD_CONTAINERS); + Container container = new Container(containers.add()); + container.setName(name); + return container; + } + + @Override + public Collection getContainers() { + ModelNode containers = get(POD_CONTAINERS); + if (containers.isDefined() && ModelType.LIST == containers.getType()) { + return containers.asList().stream().map(n -> new Container(n, getPropertyKeys())) + .collect(Collectors.toList()); + } + return Collections.emptyList(); + } + + @Override + public boolean isReady() { + ModelNode node = get(POD_STATUS_CONTAINER_STATUSES); + if (node.getType() != ModelType.LIST) { + return false; + } + boolean allContainersReady = true; + for (ModelNode containerStatus : node.asList()) { + String ready = containerStatus.get(CONTAINER_STATUS_READY).asString(); + allContainersReady &= Boolean.parseBoolean(ready); + } + return allContainersReady; + } } diff --git a/src/main/java/com/openshift/internal/restclient/model/Port.java b/src/main/java/com/openshift/internal/restclient/model/Port.java index 5ab9fd03..7569da53 100644 --- a/src/main/java/com/openshift/internal/restclient/model/Port.java +++ b/src/main/java/com/openshift/internal/restclient/model/Port.java @@ -8,9 +8,12 @@ * Contributors: * Red Hat, Inc. - initial API and implementation ******************************************************************************/ + package com.openshift.internal.restclient.model; -import static com.openshift.internal.util.JBossDmrExtentions.*; +import static com.openshift.internal.util.JBossDmrExtentions.asInt; +import static com.openshift.internal.util.JBossDmrExtentions.asString; +import static com.openshift.internal.util.JBossDmrExtentions.set; import java.util.HashMap; import java.util.Map; @@ -20,103 +23,105 @@ import com.openshift.restclient.model.IPort; -/** - * - * @author Jeff Cantrill - * - */ public class Port implements IPort { - - private static final String PROPERTY_NAME = "name"; - private static final String PROPERTY_PROTOCOL = "protocol"; - private static final String PROPERTY_CONTAINER_PORT = "containerPort"; - private static final Map KEY_MAP = new HashMap<>(); - - static { - KEY_MAP.put(PROPERTY_NAME, new String[] {PROPERTY_NAME}); - KEY_MAP.put(PROPERTY_PROTOCOL, new String[] {PROPERTY_PROTOCOL}); - KEY_MAP.put(PROPERTY_CONTAINER_PORT, new String[] {PROPERTY_CONTAINER_PORT}); - } - - private ModelNode node; - - public Port(ModelNode node) { - this.node = node; - } - - public Port(ModelNode node, IPort port) { - this(node); - if(StringUtils.isNotEmpty(port.getName())) { - setName(port.getName()); - } - setProtocol(port.getProtocol()); - setContainerPort(port.getContainerPort()); - } - - public ModelNode getNode() { - return this.node; - } - - @Override - public String getName() { - return asString(node, KEY_MAP, PROPERTY_NAME); - } - - public void setName(String name) { - set(node, KEY_MAP, PROPERTY_NAME, name); - } - - public void setContainerPort(int port) { - set(node, KEY_MAP, PROPERTY_CONTAINER_PORT, port); - } - - @Override - public int getContainerPort() { - return asInt(node, KEY_MAP, PROPERTY_CONTAINER_PORT); - } - - public void setProtocol(String name) { - set(node, KEY_MAP, PROPERTY_PROTOCOL, name); - } - - @Override - public String getProtocol() { - return asString(node, KEY_MAP, PROPERTY_PROTOCOL); - } - - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = prime * result + getContainerPort(); - result = prime * result + ((getName() == null) ? 0 : getName().hashCode()); - result = prime * result + ((getProtocol() == null) ? 0 : getProtocol().hashCode()); - return result; - } - - @Override - public boolean equals(Object obj) { - if (this == obj) - return true; - if (obj == null) - return false; - if (getClass() != obj.getClass()) - return false; - Port other = (Port) obj; - if (getContainerPort() != other.getContainerPort()) - return false; - if (getName() == null) { - if (other.getName() != null) - return false; - } else if (!getName().equals(other.getName())) - return false; - if (getProtocol() == null) { - if (other.getProtocol() != null) - return false; - } else if (!getProtocol().equals(other.getProtocol())) - return false; - return true; - } - - + + private static final String PROPERTY_NAME = "name"; + private static final String PROPERTY_PROTOCOL = "protocol"; + private static final String PROPERTY_CONTAINER_PORT = "containerPort"; + private static final Map KEY_MAP = new HashMap<>(); + + static { + KEY_MAP.put(PROPERTY_NAME, new String[] { PROPERTY_NAME }); + KEY_MAP.put(PROPERTY_PROTOCOL, new String[] { PROPERTY_PROTOCOL }); + KEY_MAP.put(PROPERTY_CONTAINER_PORT, new String[] { PROPERTY_CONTAINER_PORT }); + } + + private ModelNode node; + + public Port(ModelNode node) { + this.node = node; + } + + public Port(ModelNode node, IPort port) { + this(node); + if (StringUtils.isNotEmpty(port.getName())) { + setName(port.getName()); + } + setProtocol(port.getProtocol()); + setContainerPort(port.getContainerPort()); + } + + public ModelNode getNode() { + return this.node; + } + + @Override + public String getName() { + return asString(node, KEY_MAP, PROPERTY_NAME); + } + + public void setName(String name) { + set(node, KEY_MAP, PROPERTY_NAME, name); + } + + public void setContainerPort(int port) { + set(node, KEY_MAP, PROPERTY_CONTAINER_PORT, port); + } + + @Override + public int getContainerPort() { + return asInt(node, KEY_MAP, PROPERTY_CONTAINER_PORT); + } + + public void setProtocol(String name) { + set(node, KEY_MAP, PROPERTY_PROTOCOL, name); + } + + @Override + public String getProtocol() { + return asString(node, KEY_MAP, PROPERTY_PROTOCOL); + } + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + getContainerPort(); + result = prime * result + ((getName() == null) ? 0 : getName().hashCode()); + result = prime * result + ((getProtocol() == null) ? 0 : getProtocol().hashCode()); + return result; + } + + @Override + public boolean equals(Object obj) { + if (this == obj) { + return true; + } + if (obj == null) { + return false; + } + if (getClass() != obj.getClass()) { + return false; + } + Port other = (Port) obj; + if (getContainerPort() != other.getContainerPort()) { + return false; + } + if (getName() == null) { + if (other.getName() != null) { + return false; + } + } else if (!getName().equals(other.getName())) { + return false; + } + if (getProtocol() == null) { + if (other.getProtocol() != null) { + return false; + } + } else if (!getProtocol().equals(other.getProtocol())) { + return false; + } + return true; + } + } diff --git a/src/main/java/com/openshift/internal/restclient/model/Project.java b/src/main/java/com/openshift/internal/restclient/model/Project.java index 7d28ae79..ee433bfb 100644 --- a/src/main/java/com/openshift/internal/restclient/model/Project.java +++ b/src/main/java/com/openshift/internal/restclient/model/Project.java @@ -6,6 +6,7 @@ * * Contributors: Red Hat, Inc. ******************************************************************************/ + package com.openshift.internal.restclient.model; import static com.openshift.internal.restclient.capability.CapabilityInitializer.initializeCapabilities; @@ -23,57 +24,62 @@ /** * DMR implementation of a project - * @author Jeff Cantrill */ -public class Project extends KubernetesResource implements IProject{ - - private static final String ANNOTATION_DISPLAY_NAME = "openshift.io/display-name"; - private static final String ANNOTATION_DESCRIPTION = "openshift.io/description"; - - public Project(ModelNode node, IClient client, Map propertyKeys) { - super(node, client, propertyKeys); - initializeCapabilities(getModifiableCapabilities(), this, getClient()); - } - - - @Override - public IProject getProject() { - return this; - } +public class Project extends KubernetesResource implements IProject { + + private static final String ANNOTATION_DISPLAY_NAME = "openshift.io/display-name"; + private static final String ANNOTATION_DESCRIPTION = "openshift.io/description"; + + private static final String PROJECT_STATUS = "status"; + private static final String PROJECT_STATUS_PHASE = "phase"; - @Override - public String getNamespace() { - if(StringUtils.isEmpty(super.getNamespace())) - return getName(); - return super.getNamespace(); - } + public Project(ModelNode node, IClient client, Map propertyKeys) { + super(node, client, propertyKeys); + initializeCapabilities(getModifiableCapabilities(), this, getClient()); + } + @Override + public IProject getProject() { + return this; + } - @Override - public String getDisplayName(){ - return getAnnotation(ANNOTATION_DISPLAY_NAME); - } - - public void setDisplayName(String name) { - setAnnotation(ANNOTATION_DISPLAY_NAME, name); - } - + @Override + public String getNamespaceName() { + if (StringUtils.isEmpty(super.getNamespaceName())) { + return getName(); + } + return super.getNamespaceName(); + } - @Override - public String getDescription() { - return getAnnotation(ANNOTATION_DESCRIPTION); - } + @Override + public String getDisplayName() { + return getAnnotation(ANNOTATION_DISPLAY_NAME); + } + public void setDisplayName(String name) { + setAnnotation(ANNOTATION_DISPLAY_NAME, name); + } - @Override - public void setDescription(String value) { - setAnnotation(ANNOTATION_DESCRIPTION, value); - } + @Override + public String getDescription() { + return getAnnotation(ANNOTATION_DESCRIPTION); + } + @Override + public void setDescription(String value) { + setAnnotation(ANNOTATION_DESCRIPTION, value); + } - @Override - public List getResources(String kind){ - if(getClient() == null) return new ArrayList(); - return getClient().list(kind, getName()); - } + @Override + public List getResources(String kind) { + if (getClient() == null) { + return new ArrayList(); + } + return getClient().list(kind, getName()); + } + + @Override + public String getStatus() { + return getNode().get(PROJECT_STATUS, PROJECT_STATUS_PHASE).asString(); + } } diff --git a/src/main/java/com/openshift/internal/restclient/model/ReplicationController.java b/src/main/java/com/openshift/internal/restclient/model/ReplicationController.java index 23d22370..80be4d70 100644 --- a/src/main/java/com/openshift/internal/restclient/model/ReplicationController.java +++ b/src/main/java/com/openshift/internal/restclient/model/ReplicationController.java @@ -6,8 +6,11 @@ * * Contributors: Red Hat, Inc. ******************************************************************************/ + package com.openshift.internal.restclient.model; +import static com.openshift.internal.restclient.capability.CapabilityInitializer.initializeCapabilities; + import java.util.ArrayList; import java.util.Collection; import java.util.Collections; @@ -19,13 +22,11 @@ import java.util.Set; import java.util.stream.Collectors; -import com.openshift.internal.restclient.model.volume.EmptyDirVolumeSource; -import com.openshift.restclient.model.volume.IEmptyDirVolumeSource; -import com.openshift.restclient.model.volume.IVolume; import org.apache.commons.lang.StringUtils; import org.jboss.dmr.ModelNode; import org.jboss.dmr.ModelType; +import com.openshift.internal.restclient.model.volume.EmptyDirVolumeSource; import com.openshift.internal.restclient.model.volume.VolumeMount; import com.openshift.internal.restclient.model.volume.VolumeSource; import com.openshift.internal.util.JBossDmrExtentions; @@ -35,325 +36,358 @@ import com.openshift.restclient.model.IEnvironmentVariable; import com.openshift.restclient.model.IPort; import com.openshift.restclient.model.IReplicationController; +import com.openshift.restclient.model.volume.IEmptyDirVolumeSource; import com.openshift.restclient.model.volume.IVolumeMount; import com.openshift.restclient.model.volume.IVolumeSource; -/** - * @author Jeff Cantrill - */ -public class ReplicationController extends KubernetesResource implements IReplicationController{ - - public static final String SPEC_TEMPLATE_CONTAINERS = "spec.template.spec.containers"; - protected static final String SPEC_TEMPLATE_LABELS = "spec.template.metadata.labels"; - protected static final String VOLUMES = "spec.template.spec.volumes"; - protected static final String SPEC_REPLICAS = "spec.replicas"; - protected static final String SPEC_SELECTOR = "spec.selector"; - protected static final String STATUS_REPLICA = "status.replicas"; - - protected static final String IMAGE = "image"; - protected static final String ENV = "env"; - private Map propertyKeys; - - public ReplicationController(ModelNode node, IClient client, Map propertyKeys) { - super(node, client, propertyKeys); - this.propertyKeys = propertyKeys; - } - - @Override - public void setEnvironmentVariable(String name, String value) { - setEnvironmentVariable(null, name, value); - } - - @Override - public void setEnvironmentVariable(String containerName, String name, String value) { - String defaultedContainerName = StringUtils.defaultIfBlank(containerName, ""); - ModelNode specContainers = get(SPEC_TEMPLATE_CONTAINERS); - if(specContainers.isDefined()) { //should ALWAYS exist - List containers = specContainers.asList(); - if(!containers.isEmpty()) { - - Optional opt = containers.stream().filter(n->defaultedContainerName.equals(asString(n, NAME))).findFirst(); - ModelNode node = opt.isPresent() ? opt.get() : containers.get(0); - ModelNode envNode = get(node, ENV); - - List varList = new ArrayList<>(); - if (ModelType.LIST.equals(envNode.getType())){ - varList.addAll(envNode.asList()); - } - - //Check if variable already exists - Optional targetVar = varList.stream().filter(n->name.equals(asString(n, NAME))).findFirst(); - - ModelNode var; - if (targetVar.isPresent()) { - var = targetVar.get(); - int i = varList.indexOf(var); - set(var, VALUE, value); - varList.set(i, var); - } else { - var = new ModelNode(); - set(var, NAME, name); - set(var, VALUE, value); - varList.add(var); - } - envNode.set(varList); - } - } - } - - @Override - public void removeEnvironmentVariable(String name) { - removeEnvironmentVariable(null, name); - } - - @Override - public void removeEnvironmentVariable(String containerName, String name) { - if(name == null) { - throw new IllegalArgumentException("Name cannot be null."); - } - String defaultedContainerName = StringUtils.defaultIfBlank(containerName, ""); - ModelNode specContainers = get(SPEC_TEMPLATE_CONTAINERS); - if(specContainers.isDefined()) { //should ALWAYS exist - List containers = specContainers.asList(); - if(!containers.isEmpty()) { - - Optional opt = containers.stream().filter(n->defaultedContainerName.equals(asString(n, NAME))).findFirst(); - ModelNode node = opt.isPresent() ? opt.get() : containers.get(0); - ModelNode envNode = get(node, ENV); - - List varList = new ArrayList<>(); - if (ModelType.LIST.equals(envNode.getType())){ - varList.addAll(envNode.asList()); - } - - //Check if variable exists - Optional targetVar = varList.stream().filter(n->name.equals(asString(n, NAME))).findFirst(); - - ModelNode var; - if (targetVar.isPresent()) { - var = targetVar.get(); - int i = varList.indexOf(var); - varList.remove(i); - envNode.set(varList); - } else { - //do nothing - } - } - } - } - - @Override - public Collection getEnvironmentVariables() { - return getEnvironmentVariables(null); - } - - @Override - public Collection getEnvironmentVariables(String containerName) { - String name = StringUtils.defaultIfBlank(containerName, ""); - ModelNode specContainers = get(SPEC_TEMPLATE_CONTAINERS); - if(specContainers.isDefined()) { - List containers = specContainers.asList(); - if(!containers.isEmpty()) { - Optional opt = containers.stream().filter(n->name.equals(asString(n, NAME))).findFirst(); - ModelNode node = opt.isPresent() ? opt.get() : containers.get(0); - ModelNode envNode = get(node, ENV); - if(envNode.isDefined()) { - return envNode.asList() - .stream() - .map(n-> new EnvironmentVariable(n, propertyKeys)) - .collect(Collectors.toList()); - } - } - } - return Collections.emptyList(); - } - - @Override - public int getDesiredReplicaCount() { - return asInt(SPEC_REPLICAS); - } - - @Override - public int getReplicas() { - return getDesiredReplicaCount(); - } - - @Override - public void setDesiredReplicaCount(int count) { - set(SPEC_REPLICAS, count); - } - - @Override - public void setReplicas(int count) { - setDesiredReplicaCount(count); - } - - @Override - public Map getReplicaSelector() { - return asMap(SPEC_SELECTOR); - } - - - @Override - public void setReplicaSelector(String key, String value) { - Map selector = new HashMap<>(); - selector.put(key, value); - setReplicaSelector(selector); - } - - @Override - public void setReplicaSelector(Map selector) { - get(SPEC_SELECTOR).clear(); - set(SPEC_SELECTOR, selector); - selector.forEach((k,v)->addTemplateLabel(k,v)); - } - @Override - public int getCurrentReplicaCount() { - return asInt(STATUS_REPLICA); - } - - @Override - public Collection getImages() { - ModelNode node = get(SPEC_TEMPLATE_CONTAINERS); - if(node.getType() != ModelType.LIST) return new ArrayList<>(); - Collection list = new ArrayList<>(); - for (ModelNode entry : node.asList()) { - list.add(entry.get(IMAGE).asString()); - } - return list; - } - - @Override - public IContainer getContainer(String name) { - if(StringUtils.isBlank(name)) { - return null; - } - ModelNode containers = get(SPEC_TEMPLATE_CONTAINERS); - if(containers.isDefined() && containers.getType() == ModelType.LIST ) { - Optional first = containers.asList().stream().filter(n->name.equals(JBossDmrExtentions.asString(n, this.propertyKeys, NAME))).findFirst(); - if(first.isPresent()) { - return new Container(first.get(), this.propertyKeys); - } - } - return null; - } - - @Override - public Collection getContainers() { - ModelNode containers = get(SPEC_TEMPLATE_CONTAINERS); - if(containers.isDefined() && containers.getType() == ModelType.LIST ) { - return containers.asList().stream().map(n->new Container(n, this.propertyKeys)).collect(Collectors.toList()); - } - return Collections.emptyList(); - } - - @Override - public void addTemplateLabel(String key, String value) { - ModelNode labels = get(SPEC_TEMPLATE_LABELS); - labels.get(key).set(value); - } - - @Override - public IContainer addContainer(DockerImageURI tag, Set containerPorts, Map envVars){ - return addContainer(tag.getName(), tag, containerPorts, envVars, new ArrayList()); - } - - @Override - public IContainer addContainer(String name, DockerImageURI tag, Set containerPorts, Map envVars, List emptyDirVolumes) { - - IContainer container = addContainer(name); - container.setImage(tag); - - if(!emptyDirVolumes.isEmpty()) { - Set volumes = new HashSet<>(); - for (String path : emptyDirVolumes) { - VolumeMount volume = new VolumeMount(new ModelNode()); - volume.setMountPath(path); - volume.setName(String.format("%s-%s", name, emptyDirVolumes.indexOf(path) + 1)); - volumes.add(volume); - addEmptyDirVolumeToPodSpec(volume); - } - container.setVolumeMounts(volumes); - } - if(!containerPorts.isEmpty()) { - Set ports = new HashSet<>(); - for (IPort port : containerPorts) { - ports.add(new Port(new ModelNode(), port)); - } - container.setPorts(ports); - } - container.setEnvVars(envVars); - return container; - } - - private boolean hasVolumeNamed(ModelNode volNode, String name) { - if(volNode.isDefined()) { - List podVolumes = volNode.asList(); - for (ModelNode node : podVolumes) { - if(name.equals(asString(node,NAME))) { - return true; - } - } - } - return false; - } - - private void addEmptyDirVolumeToPodSpec(VolumeMount volume) { - ModelNode volNode = get(VOLUMES); - if (hasVolumeNamed(volNode, volume.getName())) { - //already exists - return; - } - IEmptyDirVolumeSource volumeSource = new EmptyDirVolumeSource(volume.getName()); - volumeSource.setMedium(""); - addVolume(volumeSource); - } - - @Override - public IContainer addContainer(String name) { - ModelNode containers = get(SPEC_TEMPLATE_CONTAINERS); - Container container = new Container(containers.add()); - container.setName(name); - return container; - } - - @Override - public void setContainers(Collection containers) { - ModelNode nodeContainers = get(SPEC_TEMPLATE_CONTAINERS); - nodeContainers.clear(); - if (containers != null) { - containers.forEach(c -> nodeContainers.add(ModelNode.fromJSONString(c.toJSONString()))); - } - } - - @Override - public Set getVolumes() { - ModelNode vol = get(VOLUMES); - Set volumes = new HashSet<>(); - if(vol.isDefined()) { - for (ModelNode node : vol.asList()) { - volumes.add(VolumeSource.create(node)); - } - } - return volumes; - } - - @Override - public void setVolumes(Set volumeSources) { - ModelNode vol = get(VOLUMES); - vol.clear(); - if (volumeSources != null) { - volumeSources.forEach(v -> vol.add(ModelNode.fromJSONString(v.toJSONString()))); - } - } - - @Override - public void addVolume(IVolumeSource volumeSource) { - ModelNode volList = get(VOLUMES); - if (hasVolumeNamed(volList, volumeSource.getName())) { - //already exists - return; - } - volList.add(ModelNode.fromJSONString(volumeSource.toJSONString())); - } +public class ReplicationController extends KubernetesResource implements IReplicationController { + + public static final String SPEC_TEMPLATE_CONTAINERS = "spec.template.spec.containers"; + protected static final String SPEC_TEMPLATE_LABELS = "spec.template.metadata.labels"; + protected static final String VOLUMES = "spec.template.spec.volumes"; + protected static final String SPEC_REPLICAS = "spec.replicas"; + protected static final String SPEC_SELECTOR = "spec.selector"; + protected static final String STATUS_REPLICA = "status.replicas"; + protected static final String SERVICEACCOUNTNAME = "spec.template.spec.serviceAccountName"; + + protected static final String IMAGE = "image"; + protected static final String ENV = "env"; + private Map propertyKeys; + + public ReplicationController(ModelNode node, IClient client, Map propertyKeys) { + super(node, client, propertyKeys); + this.propertyKeys = propertyKeys; + initializeCapabilities(getModifiableCapabilities(), this, getClient()); + } + + @Override + public void setEnvironmentVariable(String name, String value) { + setEnvironmentVariable(null, name, value); + } + + @Override + public void setEnvironmentVariable(String containerName, String name, String value) { + String defaultedContainerName = StringUtils.defaultIfBlank(containerName, ""); + ModelNode specContainers = get(SPEC_TEMPLATE_CONTAINERS); + if (specContainers.isDefined()) { // should ALWAYS exist + List containers = specContainers.asList(); + if (!containers.isEmpty()) { + + Optional opt = containers.stream() + .filter(n -> defaultedContainerName.equals(asString(n, NAME))).findFirst(); + ModelNode node = opt.isPresent() ? opt.get() : containers.get(0); + ModelNode envNode = get(node, ENV); + + List varList = new ArrayList<>(); + if (ModelType.LIST.equals(envNode.getType())) { + varList.addAll(envNode.asList()); + } + + // Check if variable already exists + Optional targetVar = varList.stream().filter(n -> name.equals(asString(n, NAME))) + .findFirst(); + + ModelNode var; + if (targetVar.isPresent()) { + var = targetVar.get(); + int i = varList.indexOf(var); + set(var, VALUE, value); + varList.set(i, var); + } else { + var = new ModelNode(); + set(var, NAME, name); + set(var, VALUE, value); + varList.add(var); + } + envNode.set(varList); + } + } + } + + @Override + public void removeEnvironmentVariable(String name) { + removeEnvironmentVariable(null, name); + } + + @Override + public void removeEnvironmentVariable(String containerName, String name) { + if (name == null) { + throw new IllegalArgumentException("Name cannot be null."); + } + String defaultedContainerName = StringUtils.defaultIfBlank(containerName, ""); + ModelNode specContainers = get(SPEC_TEMPLATE_CONTAINERS); + if (specContainers.isDefined()) { // should ALWAYS exist + List containers = specContainers.asList(); + if (!containers.isEmpty()) { + + Optional opt = containers.stream() + .filter(n -> defaultedContainerName.equals(asString(n, NAME))).findFirst(); + ModelNode node = opt.isPresent() ? opt.get() : containers.get(0); + ModelNode envNode = get(node, ENV); + + List varList = new ArrayList<>(); + if (ModelType.LIST.equals(envNode.getType())) { + varList.addAll(envNode.asList()); + } + + // Check if variable exists + Optional targetVar = varList.stream().filter(n -> name.equals(asString(n, NAME))) + .findFirst(); + + ModelNode var; + if (targetVar.isPresent()) { + var = targetVar.get(); + int i = varList.indexOf(var); + varList.remove(i); + envNode.set(varList); + } else { + // do nothing + } + } + } + } + + @Override + public Collection getEnvironmentVariables() { + return getEnvironmentVariables(null); + } + + @Override + public Collection getEnvironmentVariables(String containerName) { + String name = StringUtils.defaultIfBlank(containerName, ""); + ModelNode specContainers = get(SPEC_TEMPLATE_CONTAINERS); + if (specContainers.isDefined()) { + List containers = specContainers.asList(); + if (!containers.isEmpty()) { + Optional opt = containers.stream().filter(n -> name.equals(asString(n, NAME))).findFirst(); + ModelNode node = opt.isPresent() ? opt.get() : containers.get(0); + ModelNode envNode = get(node, ENV); + if (envNode.isDefined()) { + return envNode.asList().stream().map(n -> new EnvironmentVariable(n, propertyKeys)) + .collect(Collectors.toList()); + } + } + } + return Collections.emptyList(); + } + + @Override + public int getDesiredReplicaCount() { + return asInt(SPEC_REPLICAS); + } + + @Override + public int getReplicas() { + return getDesiredReplicaCount(); + } + + @Override + public void setDesiredReplicaCount(int count) { + set(SPEC_REPLICAS, count); + } + + @Override + public void setReplicas(int count) { + setDesiredReplicaCount(count); + } + + @Override + public Map getReplicaSelector() { + return asMap(SPEC_SELECTOR); + } + + @Override + public void setReplicaSelector(String key, String value) { + Map selector = new HashMap<>(); + selector.put(key, value); + setReplicaSelector(selector); + } + + @Override + public void setReplicaSelector(Map selector) { + get(SPEC_SELECTOR).clear(); + set(SPEC_SELECTOR, selector); + selector.forEach((k, v) -> addTemplateLabel(k, v)); + } + + @Override + public int getCurrentReplicaCount() { + return asInt(STATUS_REPLICA); + } + + @Override + public Collection getImages() { + ModelNode node = get(SPEC_TEMPLATE_CONTAINERS); + if (node.getType() != ModelType.LIST) { + return new ArrayList<>(); + } + Collection list = new ArrayList<>(); + for (ModelNode entry : node.asList()) { + list.add(entry.get(IMAGE).asString()); + } + return list; + } + + @Override + public IContainer getContainer(String name) { + if (StringUtils.isBlank(name)) { + return null; + } + ModelNode containers = get(SPEC_TEMPLATE_CONTAINERS); + if (containers.isDefined() && containers.getType() == ModelType.LIST) { + Optional first = containers.asList().stream() + .filter(n -> name.equals(JBossDmrExtentions.asString(n, this.propertyKeys, NAME))).findFirst(); + if (first.isPresent()) { + return new Container(first.get(), this.propertyKeys); + } + } + return null; + } + + @Override + public Collection getContainers() { + ModelNode containers = get(SPEC_TEMPLATE_CONTAINERS); + if (containers.isDefined() && containers.getType() == ModelType.LIST) { + return containers.asList().stream().map(n -> new Container(n, this.propertyKeys)) + .collect(Collectors.toList()); + } + return Collections.emptyList(); + } + + @Override + public Map getTemplateLabels() { + return asMap(SPEC_TEMPLATE_LABELS); + } + + @Override + public void addTemplateLabel(String key, String value) { + ModelNode labels = get(SPEC_TEMPLATE_LABELS); + labels.get(key).set(value); + } + + @Override + public IContainer addContainer(DockerImageURI tag, Set containerPorts, Map envVars) { + return addContainer(tag.getName(), tag, containerPorts, envVars, new ArrayList()); + } + + @Override + public IContainer addContainer(String name, DockerImageURI tag, Set containerPorts, + Map envVars, List emptyDirVolumes) { + + IContainer container = addContainer(name); + container.setImage(tag); + + if (!emptyDirVolumes.isEmpty()) { + Set volumes = new HashSet<>(); + for (String path : emptyDirVolumes) { + VolumeMount volume = new VolumeMount(new ModelNode()); + volume.setMountPath(path); + volume.setName(String.format("%s-%s", name, emptyDirVolumes.indexOf(path) + 1)); + volumes.add(volume); + addEmptyDirVolumeToPodSpec(volume); + } + container.setVolumeMounts(volumes); + } + if (!containerPorts.isEmpty()) { + Set ports = new HashSet<>(); + for (IPort port : containerPorts) { + ports.add(new Port(new ModelNode(), port)); + } + container.setPorts(ports); + } + container.setEnvVars(envVars); + return container; + } + + @Override + public IContainer addContainer(String name) { + ModelNode containers = get(SPEC_TEMPLATE_CONTAINERS); + Container container = new Container(containers.add()); + container.setName(name); + return container; + } + + private boolean hasVolumeNamed(ModelNode volNode, String name) { + if (volNode.isDefined()) { + List podVolumes = volNode.asList(); + for (ModelNode node : podVolumes) { + if (name.equals(asString(node, NAME))) { + return true; + } + } + } + return false; + } + + private void addEmptyDirVolumeToPodSpec(VolumeMount volume) { + ModelNode volNode = get(VOLUMES); + if (hasVolumeNamed(volNode, volume.getName())) { + // already exists + return; + } + IEmptyDirVolumeSource volumeSource = new EmptyDirVolumeSource(volume.getName()); + volumeSource.setMedium(""); + addVolume(volumeSource); + } + + @Override + public void setContainers(Collection containers) { + ModelNode nodeContainers = get(SPEC_TEMPLATE_CONTAINERS); + nodeContainers.clear(); + if (containers != null) { + containers.forEach(c -> nodeContainers.add(ModelNode.fromJSONString(c.toJson()))); + } + } + + @Override + public Set getVolumes() { + ModelNode vol = get(VOLUMES); + Set volumes = new HashSet<>(); + if (vol.isDefined()) { + for (ModelNode node : vol.asList()) { + volumes.add(VolumeSource.create(node)); + } + } + return volumes; + } + + @Override + public void setVolumes(Set volumeSources) { + ModelNode vol = get(VOLUMES); + vol.clear(); + if (volumeSources != null) { + volumeSources.forEach(v -> vol.add(ModelNode.fromJSONString(v.toJSONString()))); + } + } + + @Override + public void addVolume(IVolumeSource volumeSource) { + ModelNode volList = get(VOLUMES); + if (hasVolumeNamed(volList, volumeSource.getName())) { + // already exists + return; + } + volList.add(ModelNode.fromJSONString(volumeSource.toJSONString())); + } + + @SuppressWarnings("unchecked") + @Override + public T addVolume(String volumetype, String name) { + ModelNode volList = get(VOLUMES); + ModelNode node = volList.add(); + node.get(volumetype).set(new ModelNode()); + IVolumeSource source = VolumeSource.create(node); + source.setName(name); + return (T) source; + } + + @Override + public void setServiceAccountName(String serviceAccountName) { + set(SERVICEACCOUNTNAME, serviceAccountName); + } + + @Override + public String getServiceAccountName() { + return asString(SERVICEACCOUNTNAME); + } } diff --git a/src/main/java/com/openshift/internal/restclient/model/ResourceQuota.java b/src/main/java/com/openshift/internal/restclient/model/ResourceQuota.java index becdd904..2b05a589 100644 --- a/src/main/java/com/openshift/internal/restclient/model/ResourceQuota.java +++ b/src/main/java/com/openshift/internal/restclient/model/ResourceQuota.java @@ -8,6 +8,7 @@ * Contributors: * Red Hat, Inc. - initial API and implementation ******************************************************************************/ + package com.openshift.internal.restclient.model; import java.util.Map; @@ -19,9 +20,8 @@ public class ResourceQuota extends KubernetesResource implements IResourceQuota { - public ResourceQuota(ModelNode node, IClient client, Map propertyKeys) { - super(node, client, propertyKeys); - // TODO Auto-generated constructor stub - } + public ResourceQuota(ModelNode node, IClient client, Map propertyKeys) { + super(node, client, propertyKeys); + } } diff --git a/src/main/java/com/openshift/internal/restclient/model/Route.java b/src/main/java/com/openshift/internal/restclient/model/Route.java index 08610535..0e605c88 100644 --- a/src/main/java/com/openshift/internal/restclient/model/Route.java +++ b/src/main/java/com/openshift/internal/restclient/model/Route.java @@ -6,6 +6,7 @@ * * Contributors: Red Hat, Inc. ******************************************************************************/ + package com.openshift.internal.restclient.model; import java.util.Map; @@ -16,140 +17,191 @@ import com.openshift.restclient.ResourceKind; import com.openshift.restclient.model.route.IRoute; import com.openshift.restclient.model.route.ITLSConfig; +import com.openshift.restclient.model.route.ITargetPort; -/** - * @author Jeff Cantrill - */ public class Route extends KubernetesResource implements IRoute { - - private static final String ROUTE_HOST = "spec.host"; - private static final String ROUTE_PATH = "spec.path"; - private static final String ROUTE_KIND = "spec.to.kind"; - private static final String ROUTE_SERVICE_NAME = "spec.to.name"; - private static final String ROUTE_TLS = "spec.tls"; - private static final String ROUTE_TLS_TERMINATION_TYPE = "spec.tls.termination"; - private static final String ROUTE_TLS_CERTIFICATE = "spec.tls.certificate"; - private static final String ROUTE_TLS_KEY = "spec.tls.key"; - private static final String ROUTE_TLS_CACERT = "spec.tls.caCertificate"; - private static final String ROUTE_TLS_DESTINATION_CACERT = "spec.tls.destinationCACertificate"; - - public Route(ModelNode node, IClient client, - Map propertyKeys) { - super(node, client, propertyKeys); - } - - @Override - public String getHost() { - return asString(ROUTE_HOST); - } - - @Override - public void setHost(String host) { - get(ROUTE_HOST).set(host); - } - - @Override - public String getPath() { - return asString(ROUTE_PATH); - } - - @Override - public void setPath(String path) { - get(ROUTE_PATH).set(path); - } - - @Override - public String getServiceName() { - return asString(ROUTE_SERVICE_NAME); - } - - @Override - public void setServiceName(String serviceName) { - get(ROUTE_SERVICE_NAME).set(serviceName); - get(ROUTE_KIND).set(ResourceKind.SERVICE); - } - - @Override - public ITLSConfig getTLSConfig() { - if(get(ROUTE_TLS).isDefined()){ - return new TLSConfig(); - } - return null; - } - - @Override - public ITLSConfig createTLSConfig() { - ITLSConfig config = getTLSConfig(); - if(config == null) { - get(ROUTE_TLS).set(new ModelNode()); - config = new TLSConfig(); - } - return config; - } - - @Override - public String getURL() { - String scheme = getTLSConfig() == null ? "http" : "https"; - String path = getPath(); - if(!path.startsWith("/")) { - path = "/" + path; - } - return String.format("%s://%s%s", scheme, getHost(), path); - } - - - - private class TLSConfig implements ITLSConfig { - - @Override - public String getTerminationType() { - return asString(ROUTE_TLS_TERMINATION_TYPE); - } - - @Override - public void setTerminationType(String type) { - get(ROUTE_TLS_TERMINATION_TYPE).set(type); - } - - @Override - public String getCertificate() { - return asString(ROUTE_TLS_CERTIFICATE); - } - - @Override - public void setCertificate(String certificate) { - get(ROUTE_TLS_CERTIFICATE).set(certificate); - } - - @Override - public String getKey() { - return asString(ROUTE_TLS_KEY); - } - - @Override - public void setKey(String key) { - get(ROUTE_TLS_KEY).set(key); - } - - @Override - public String getCACertificate() { - return asString(ROUTE_TLS_CACERT); - } - - @Override - public void setCACertificate(String caCertificate) { - get(ROUTE_TLS_CACERT).set(caCertificate); - } - - @Override - public String getDestinationCertificate() { - return asString(ROUTE_TLS_DESTINATION_CACERT); - } - - @Override - public void setDestinationCertificate(String destinationCertificate) { - get(ROUTE_TLS_DESTINATION_CACERT).set(destinationCertificate); - } - - } + + private static final String ROUTE_HOST = "spec.host"; + private static final String ROUTE_PATH = "spec.path"; + private static final String ROUTE_KIND = "spec.to.kind"; + private static final String ROUTE_SERVICE_NAME = "spec.to.name"; + private static final String ROUTE_TLS = "spec.tls"; + private static final String ROUTE_TLS_TERMINATION_TYPE = "spec.tls.termination"; + private static final String ROUTE_TLS_CERTIFICATE = "spec.tls.certificate"; + private static final String ROUTE_TLS_KEY = "spec.tls.key"; + private static final String ROUTE_TLS_CACERT = "spec.tls.caCertificate"; + private static final String ROUTE_TLS_DESTINATION_CACERT = "spec.tls.destinationCACertificate"; + private static final String ROUTE_TLS_INSECURE_EDGE_TERMINATION_POLICY = "spec.tls.insecureEdgeTerminationPolicy"; + private static final String ROUTE_PORT = "spec.port"; + private static final String ROUTE_PORT_TARGETPORT = "spec.port.targetPort"; + + public Route(ModelNode node, IClient client, Map propertyKeys) { + super(node, client, propertyKeys); + } + + @Override + public String getHost() { + return asString(ROUTE_HOST); + } + + @Override + public void setHost(String host) { + get(ROUTE_HOST).set(host); + } + + @Override + public String getPath() { + return asString(ROUTE_PATH); + } + + @Override + public void setPath(String path) { + get(ROUTE_PATH).set(path); + } + + @Override + public String getServiceName() { + return asString(ROUTE_SERVICE_NAME); + } + + @Override + public void setServiceName(String serviceName) { + get(ROUTE_SERVICE_NAME).set(serviceName); + get(ROUTE_KIND).set(ResourceKind.SERVICE); + } + + @Override + public ITLSConfig getTLSConfig() { + if (get(ROUTE_TLS).isDefined()) { + return new TLSConfig(); + } + return null; + } + + @Override + public ITLSConfig createTLSConfig() { + ITLSConfig config = getTLSConfig(); + if (config == null) { + get(ROUTE_TLS).set(new ModelNode()); + config = new TLSConfig(); + } + return config; + } + + @Override + public ITargetPort getPort() { + if (get(ROUTE_PORT).isDefined()) { + return new TargetPort(); + } + return null; + } + + @Override + public ITargetPort createPort() { + ITargetPort targetPort = getPort(); + if (targetPort == null) { + get(ROUTE_PORT).set(new ModelNode()); + targetPort = new TargetPort(); + } + return targetPort; + } + + @Override + public String getURL() { + String scheme = getTLSConfig() == null ? "http" : "https"; + String path = getPath(); + if (!path.startsWith("/")) { + path = "/" + path; + } + return String.format("%s://%s%s", scheme, getHost(), path); + } + + private class TLSConfig implements ITLSConfig { + + @Override + public String getTerminationType() { + return asString(ROUTE_TLS_TERMINATION_TYPE); + } + + @Override + public void setTerminationType(String type) { + get(ROUTE_TLS_TERMINATION_TYPE).set(type); + } + + @Override + public String getCertificate() { + return asString(ROUTE_TLS_CERTIFICATE); + } + + @Override + public void setCertificate(String certificate) { + get(ROUTE_TLS_CERTIFICATE).set(certificate); + } + + @Override + public String getKey() { + return asString(ROUTE_TLS_KEY); + } + + @Override + public void setKey(String key) { + get(ROUTE_TLS_KEY).set(key); + } + + @Override + public String getCACertificate() { + return asString(ROUTE_TLS_CACERT); + } + + @Override + public void setCACertificate(String caCertificate) { + get(ROUTE_TLS_CACERT).set(caCertificate); + } + + @Override + public String getDestinationCertificate() { + return asString(ROUTE_TLS_DESTINATION_CACERT); + } + + @Override + public void setDestinationCertificate(String destinationCertificate) { + get(ROUTE_TLS_DESTINATION_CACERT).set(destinationCertificate); + } + + @Override + public String getInsecureEdgeTerminationPolicy() { + return asString(ROUTE_TLS_INSECURE_EDGE_TERMINATION_POLICY); + } + + @Override + public void setInsecureEdgeTerminationPolicy(String insecureEdgeTerminationPolicy) { + get(ROUTE_TLS_INSECURE_EDGE_TERMINATION_POLICY).set(insecureEdgeTerminationPolicy); + } + } + + private class TargetPort implements ITargetPort { + @Override + public String getTargetPortName() { + return asString(ROUTE_PORT_TARGETPORT); + } + + @Override + public void setTargetPortName(String portName) { + get(ROUTE_PORT_TARGETPORT).set(portName); + } + + @Override + public Integer getTargetPort() { + if (has(ROUTE_PORT_TARGETPORT)) { + return asInt(ROUTE_PORT_TARGETPORT); + } else { + return -1; + } + } + + @Override + public void setTargetPort(Integer port) { + get(ROUTE_PORT_TARGETPORT).set(port); + } + } } diff --git a/src/main/java/com/openshift/internal/restclient/model/Secret.java b/src/main/java/com/openshift/internal/restclient/model/Secret.java index fb3a2c76..29f7c850 100644 --- a/src/main/java/com/openshift/internal/restclient/model/Secret.java +++ b/src/main/java/com/openshift/internal/restclient/model/Secret.java @@ -6,6 +6,7 @@ * * Contributors: Red Hat, Inc. ******************************************************************************/ + package com.openshift.internal.restclient.model; import java.io.ByteArrayOutputStream; @@ -24,46 +25,44 @@ * @author Jiri Pechanec */ public class Secret extends KubernetesResource implements ISecret { - - private static final String SECRET_TYPE = "type"; - private static final String SECRET_DATA = "data"; + private static final String SECRET_TYPE = "type"; + private static final String SECRET_DATA = "data"; + + public Secret(ModelNode node, IClient client, Map propertyKeys) { + super(node, client, propertyKeys); + } - public Secret(ModelNode node, IClient client, Map propertyKeys) { - super(node, client, propertyKeys); - } + @Override + public void addData(String key, InputStream data) { + try { + ByteArrayOutputStream os = new ByteArrayOutputStream(); + IOUtils.copy(data, os); + addData(key, os.toByteArray()); + } catch (IOException e) { + throw new IllegalArgumentException("Could not process data stream", e); + } + } - @Override - public void addData(String key, InputStream data) { - try { - ByteArrayOutputStream os = new ByteArrayOutputStream(); - IOUtils.copy(data, os); - addData(key, os.toByteArray()); - } - catch (IOException e) { - throw new IllegalArgumentException("Could not process data stream", e); - } - } + @Override + public void addData(final String key, final byte[] data) { + ModelNode dataNode = get(SECRET_DATA); + dataNode.get(key).set(Base64Coder.encode(data)); + } - @Override - public void addData(final String key, final byte[] data) { - ModelNode dataNode = get(SECRET_DATA); - dataNode.get(key).set(Base64Coder.encode(data)); - } + @Override + public byte[] getData(final String key) { + return Base64Coder.decodeBinary(asMap(SECRET_DATA).get(key)); + } - @Override - public byte[] getData(final String key) { - return Base64Coder.decodeBinary(asMap(SECRET_DATA).get(key)); - } + @Override + public void setType(final String type) { + get(SECRET_TYPE).set(type); + } - @Override - public void setType(final String type) { - get(SECRET_TYPE).set(type.toString()); - } + @Override + public String getType() { + return asString(SECRET_TYPE); + } - @Override - public String getType() { - return asString(SECRET_TYPE); - } - } diff --git a/src/main/java/com/openshift/internal/restclient/model/Service.java b/src/main/java/com/openshift/internal/restclient/model/Service.java index 1afb6918..0f9a3fce 100644 --- a/src/main/java/com/openshift/internal/restclient/model/Service.java +++ b/src/main/java/com/openshift/internal/restclient/model/Service.java @@ -6,6 +6,7 @@ * * Contributors: Red Hat, Inc. ******************************************************************************/ + package com.openshift.internal.restclient.model; import static com.openshift.internal.restclient.capability.CapabilityInitializer.initializeCapabilities; @@ -16,8 +17,8 @@ import java.util.List; import java.util.Map; +import org.apache.commons.lang.StringUtils; import org.jboss.dmr.ModelNode; -import org.jboss.dmr.ModelType; import com.openshift.restclient.IClient; import com.openshift.restclient.ResourceKind; @@ -25,119 +26,150 @@ import com.openshift.restclient.model.IService; import com.openshift.restclient.model.IServicePort; -/** - * @author Jeff Cantrill - */ public class Service extends KubernetesResource implements IService { + private static final String SERVICE_SELECTOR = "spec.selector"; + private static final String SERVICE_PORT = "spec.ports"; + + public Service(ModelNode node, IClient client, Map propertyKeys) { + super(node, client, propertyKeys); + initializeCapabilities(getModifiableCapabilities(), this, getClient()); + } + + @Override + public void setPort(int port) { + IServicePort lowestPort = getLowestPort(); + if (lowestPort == null) { + lowestPort = addPort(0, 0); + } + lowestPort.setPort(port); + } + + public IServicePort addPort(int port, int targetPort) { + return addPort(port, targetPort, null); + } + + public IServicePort addPort(int port, int targetPort, String name) { + ServicePort servicePort = new ServicePort(get(SERVICE_PORT).add()); + if (port > 0) { + servicePort.setPort(port); + } + if (targetPort > 0) { + servicePort.setTargetPort(targetPort); + } + if (StringUtils.isNotEmpty(name)) { + servicePort.setName(name); + } + return servicePort; + } + + @Override + public int getPort() { + IServicePort port = getLowestPort(); + return port != null ? port.getPort() : 0; + } + + private IServicePort getLowestPort() { + List ports = getPorts(); + return ports.size() == 0 ? null : ports.get(0); + } + + @Override + public List getPorts() { + return getPorts(false); + } + + private List getPorts(boolean modifiable) { + List ports = new ArrayList<>(); + if (!get(SERVICE_PORT).isDefined()) { + return ports; + } + for (ModelNode node : get(SERVICE_PORT).asList()) { + ports.add(new ServicePort(node)); + } + Collections.sort(ports, new Comparator() { + @Override + public int compare(IServicePort first, IServicePort second) { + Integer port0 = first.getPort(); + Integer port1 = second.getPort(); + return port0.compareTo(port1); + } + }); + return modifiable ? ports : Collections.unmodifiableList(ports); + } + + @Override + public void setPorts(List ports) { + ModelNode portspec = get(SERVICE_PORT).clear(); + for (IServicePort port : ports) { + new ServicePort(portspec.add(), port); + } + } + + @Override + public Map getSelector() { + return asMap(SERVICE_SELECTOR); + } + + @Override + public void setSelector(Map selector) { + ModelNode node = new ModelNode(); + for (Map.Entry entry : selector.entrySet()) { + node.get(entry.getKey()).set(entry.getValue()); + } + get(SERVICE_SELECTOR).set(node); + } + + @Override + public void setSelector(String key, String value) { + get(SERVICE_SELECTOR).get(key).set(value); + } + + @Override + public void setTargetPort(int port) { + IServicePort portspec = getLowestPort(); + if (portspec == null) { + portspec = addPort(0, 0); + } + portspec.setTargetPort(port); + } + + @Override + public String getTargetPort() { + IServicePort port = getLowestPort(); + return port != null ? port.getTargetPort() : "0"; + } + + @Override + @Deprecated + public String getPortalIP() { + String tmp = asString("spec.portalIP"); + if (StringUtils.isBlank(tmp)) { + tmp = getClusterIP(); + } + return tmp; + } + + @Override + public String getClusterIP() { + return asString("spec.clusterIP"); + } + + @Override + public List getPods() { + if (getClient() == null) { + return new ArrayList(); + } + return getClient().list(ResourceKind.POD, getNamespaceName(), getSelector()); + } + + @Override + public String getType() { + return asString("spec.type"); + } - private static final String SERVICE_SELECTOR = "spec.selector"; - private static final String SERVICE_PORT = "spec.ports"; - - public Service(ModelNode node, IClient client, Map propertyKeys) { - super(node, client, propertyKeys); - initializeCapabilities(getModifiableCapabilities(), this, getClient()); - } - - @Override - public void setPort(int port){ - IServicePort lowestPort = getLowestPort(); - if(lowestPort == null) { - lowestPort = addPort(0,0); - } - lowestPort.setPort(port); - } - - public IServicePort addPort(int port, int targetPort) { - ServicePort servicePort = new ServicePort(get(SERVICE_PORT).add()); - if(port > 0) servicePort.setPort(port); - if(targetPort >0) servicePort.setTargetPort(targetPort); - return servicePort; - } - - @Override - public int getPort(){ - IServicePort port = getLowestPort(); - return port != null ? port.getPort() : 0; - } - - private IServicePort getLowestPort() { - List ports = getPorts(); - return ports.size() == 0 ? null : ports.get(0); - } - @Override - public List getPorts() { - return getPorts(false); - } - - private List getPorts(boolean modifiable) { - List ports = new ArrayList<>(); - if(!get(SERVICE_PORT).isDefined()) return ports; - for (ModelNode node : get(SERVICE_PORT).asList()) { - ports.add(new ServicePort(node)); - } - Collections.sort(ports, new Comparator() { - @Override - public int compare(IServicePort first, IServicePort second) { - Integer port0 = first.getPort(); - Integer port1 = second.getPort(); - return port0.compareTo(port1); - } - }); - return modifiable ? ports : Collections.unmodifiableList(ports); - } - - @Override - public void setPorts(List ports) { - ModelNode portspec = get(SERVICE_PORT).clear(); - for (IServicePort port : ports) { - new ServicePort(portspec.add(), port); - } - } - - @Override - public Map getSelector(){ - return asMap(SERVICE_SELECTOR); - } - - @Override - public void setSelector(Map selector) { - ModelNode node = new ModelNode(); - for (Map.Entry entry : selector.entrySet()) { - node.get(entry.getKey()).set(entry.getValue()); - } - get(SERVICE_SELECTOR).set(node); - } - - - @Override - public void setSelector(String key, String value) { - get(SERVICE_SELECTOR).get(key).set(value); - } - - @Override - public void setTargetPort(int port) { - IServicePort portspec = getLowestPort(); - if(portspec == null) { - portspec = addPort(0,0); - } - portspec.setTargetPort(port); - } - - @Override - public String getTargetPort() { - IServicePort port = getLowestPort(); - return port != null ? port.getTargetPort() : "0"; - } - - @Override - public String getPortalIP() { - return asString("spec.portalIP"); - } - - @Override - public List getPods() { - if(getClient() == null) return new ArrayList(); - return getClient().list(ResourceKind.POD, getNamespace(), getSelector()); - } + @Override + public void setType(String type) { + set("spec.type", type); + } } diff --git a/src/main/java/com/openshift/internal/restclient/model/ServiceAccount.java b/src/main/java/com/openshift/internal/restclient/model/ServiceAccount.java index 4a76a5ee..dbc69e86 100644 --- a/src/main/java/com/openshift/internal/restclient/model/ServiceAccount.java +++ b/src/main/java/com/openshift/internal/restclient/model/ServiceAccount.java @@ -6,63 +6,67 @@ * * Contributors: Red Hat, Inc. ******************************************************************************/ -package com.openshift.internal.restclient.model; -import com.openshift.restclient.IClient; -import com.openshift.restclient.model.serviceaccount.IServiceAccount; -import org.jboss.dmr.ModelNode; -import org.jboss.dmr.ModelType; +package com.openshift.internal.restclient.model; import java.util.ArrayList; import java.util.Collection; import java.util.Map; +import org.jboss.dmr.ModelNode; +import org.jboss.dmr.ModelType; + +import com.openshift.restclient.IClient; +import com.openshift.restclient.model.serviceaccount.IServiceAccount; + /** * @author David Simansky | dsimansk@redhat.com */ public class ServiceAccount extends KubernetesResource implements IServiceAccount { - private static final String SERVICE_ACCOUNT_SECRETS = "secrets"; - private static final String SERVICE_ACCOUNT_IMAGE_PULL_SECRETS = "imagePullSecrets"; - - - public ServiceAccount(ModelNode node, IClient client, Map propertyKeys) { - super(node, client, propertyKeys); - } + private static final String SERVICE_ACCOUNT_SECRETS = "secrets"; + private static final String SERVICE_ACCOUNT_IMAGE_PULL_SECRETS = "imagePullSecrets"; - @Override - public Collection getSecrets() { - Collection secrets = new ArrayList<>(); - ModelNode node = get(SERVICE_ACCOUNT_SECRETS); - if(node.getType() != ModelType.LIST) return secrets; - for (ModelNode entry : node.asList()) { - secrets.add(asString(entry, NAME)); - } - return secrets; - } + public ServiceAccount(ModelNode node, IClient client, Map propertyKeys) { + super(node, client, propertyKeys); + } - @Override - public void addSecret(String secret) { - ModelNode secretNodeName = get(SERVICE_ACCOUNT_SECRETS).add(); - set(secretNodeName, NAME, secret); - } + @Override + public Collection getSecrets() { + Collection secrets = new ArrayList<>(); + ModelNode node = get(SERVICE_ACCOUNT_SECRETS); + if (node.getType() != ModelType.LIST) { + return secrets; + } + for (ModelNode entry : node.asList()) { + secrets.add(asString(entry, NAME)); + } + return secrets; + } - @Override - public Collection getImagePullSecrets() { - Collection secrets = new ArrayList<>(); - ModelNode node = get(SERVICE_ACCOUNT_IMAGE_PULL_SECRETS); - if(node.getType() != ModelType.LIST) return secrets; - for (ModelNode entry : node.asList()) { - secrets.add(asString(entry, NAME)); - } - return secrets; - } + @Override + public void addSecret(String secret) { + ModelNode secretNodeName = get(SERVICE_ACCOUNT_SECRETS).add(); + set(secretNodeName, NAME, secret); + } - @Override - public void addImagePullSecret(String imagePullSecret) { - ModelNode secretNodeName = get(SERVICE_ACCOUNT_IMAGE_PULL_SECRETS).add(); - set(secretNodeName, NAME, imagePullSecret); - } + @Override + public Collection getImagePullSecrets() { + Collection secrets = new ArrayList<>(); + ModelNode node = get(SERVICE_ACCOUNT_IMAGE_PULL_SECRETS); + if (node.getType() != ModelType.LIST) { + return secrets; + } + for (ModelNode entry : node.asList()) { + secrets.add(asString(entry, NAME)); + } + return secrets; + } + @Override + public void addImagePullSecret(String imagePullSecret) { + ModelNode secretNodeName = get(SERVICE_ACCOUNT_IMAGE_PULL_SECRETS).add(); + set(secretNodeName, NAME, imagePullSecret); + } } diff --git a/src/main/java/com/openshift/internal/restclient/model/ServicePort.java b/src/main/java/com/openshift/internal/restclient/model/ServicePort.java index 66717cb8..64b8f785 100644 --- a/src/main/java/com/openshift/internal/restclient/model/ServicePort.java +++ b/src/main/java/com/openshift/internal/restclient/model/ServicePort.java @@ -8,6 +8,7 @@ * Contributors: * Red Hat, Inc. - initial API and implementation ******************************************************************************/ + package com.openshift.internal.restclient.model; import static com.openshift.internal.util.JBossDmrExtentions.asInt; @@ -22,133 +23,159 @@ import com.openshift.restclient.model.IServicePort; -/** - * @author Jeff Cantrill - */ public class ServicePort extends ModelNodeAdapter implements IServicePort { - private static final String PROPERTY_NAME = "name"; - private static final String PROPERTY_PORT = "port"; - private static final String PROPERTY_PROTOCOL = "protocol"; - private static final String PROPERTY_TARGET_PORT = "targetPort"; - private static final Map KEY_MAP = new HashMap<>(); - - static { - KEY_MAP.put(PROPERTY_NAME, new String[] {PROPERTY_NAME}); - KEY_MAP.put(PROPERTY_PORT, new String[] {PROPERTY_PORT}); - KEY_MAP.put(PROPERTY_PROTOCOL, new String[] {PROPERTY_PROTOCOL}); - KEY_MAP.put(PROPERTY_TARGET_PORT, new String[] {PROPERTY_TARGET_PORT}); - } - - public ServicePort(ModelNode node) { - super(node, KEY_MAP); - } - - /** - * copy constructor - * @param the node to copy - * @param spec - */ - public ServicePort(ModelNode node, IServicePort port) { - this(node); - setName(port.getName()); - setPort(port.getPort()); - setProtocol(port.getProtocol()); - setTargetPort(port.getTargetPort()); - } - - @Override - public String getName() { - return asString(getNode(), KEY_MAP, PROPERTY_NAME); - } - - @Override - public void setName(String name) { - set(getNode(), KEY_MAP, PROPERTY_NAME, name); - } - - @Override - public String getTargetPort() { - return asString(getNode(), KEY_MAP, PROPERTY_TARGET_PORT); - } - - @Override - public void setTargetPort(int port) { - set(getNode(), KEY_MAP, PROPERTY_TARGET_PORT, port); - } - - @Override - public void setTargetPort(String name) { - if(StringUtils.isNumeric(name)) { - setTargetPort((Integer.parseInt(name))); - return; - } - set(getNode(), KEY_MAP, PROPERTY_TARGET_PORT, name); - } - - @Override - public void setPort(int port) { - set(getNode(), KEY_MAP, PROPERTY_PORT, port); - } - - @Override - public int getPort() { - return asInt(getNode(), KEY_MAP, PROPERTY_PORT); - } - - @Override - public String getProtocol() { - return asString(getNode(), KEY_MAP, PROPERTY_PROTOCOL); - } - - public void setProtocol(String proto) { - set(getNode(), KEY_MAP, PROPERTY_PROTOCOL, proto); - } - - - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = prime * result + getPort(); - result = prime * result + getTargetPort().hashCode(); - result = prime * result + ((getName() == null) ? 0 : getName().hashCode()); - result = prime * result + ((getProtocol() == null) ? 0 : getProtocol().hashCode()); - return result; - } - - @Override - public boolean equals(Object obj) { - if (this == obj) - return true; - if (obj == null) - return false; - if (getClass() != obj.getClass()) - return false; - ServicePort other = (ServicePort) obj; - if (getPort() != other.getPort()) - return false; - if (getTargetPort() == null) { - if (other.getTargetPort() != null) - return false; - } else if (!getTargetPort().equals(other.getTargetPort())) - return false; - if (getName() == null) { - if (other.getName() != null) - return false; - } else if (!getName().equals(other.getName())) - return false; - if (getProtocol() == null) { - if (other.getProtocol() != null) - return false; - } else if (!getProtocol().equals(other.getProtocol())) - return false; - return true; - } - - @Override - public String toString() { - return toJson(false); - } - - + private static final String PROPERTY_NAME = "name"; + private static final String PROPERTY_PORT = "port"; + private static final String PROPERTY_PROTOCOL = "protocol"; + private static final String PROPERTY_TARGET_PORT = "targetPort"; + private static final String PROPERTY_NODE_PORT = "nodePort"; + private static final Map KEY_MAP = new HashMap<>(); + + static { + KEY_MAP.put(PROPERTY_NAME, new String[] { PROPERTY_NAME }); + KEY_MAP.put(PROPERTY_PORT, new String[] { PROPERTY_PORT }); + KEY_MAP.put(PROPERTY_PROTOCOL, new String[] { PROPERTY_PROTOCOL }); + KEY_MAP.put(PROPERTY_TARGET_PORT, new String[] { PROPERTY_TARGET_PORT }); + KEY_MAP.put(PROPERTY_NODE_PORT, new String[] { PROPERTY_NODE_PORT }); + } + + public ServicePort(ModelNode node) { + super(node, KEY_MAP); + } + + /** + * copy constructor + * + * @param node the node to copy + * @param port the service ort + */ + public ServicePort(ModelNode node, IServicePort port) { + this(node); + setName(port.getName()); + setPort(port.getPort()); + setProtocol(port.getProtocol()); + setTargetPort(port.getTargetPort()); + setNodePort(port.getNodePort()); + } + + @Override + public String getName() { + return asString(getNode(), KEY_MAP, PROPERTY_NAME); + } + + @Override + public void setName(String name) { + set(getNode(), KEY_MAP, PROPERTY_NAME, name); + } + + @Override + public String getTargetPort() { + return asString(getNode(), KEY_MAP, PROPERTY_TARGET_PORT); + } + + @Override + public void setTargetPort(int port) { + set(getNode(), KEY_MAP, PROPERTY_TARGET_PORT, port); + } + + @Override + public void setTargetPort(String name) { + if (StringUtils.isNumeric(name)) { + setTargetPort((Integer.parseInt(name))); + return; + } + set(getNode(), KEY_MAP, PROPERTY_TARGET_PORT, name); + } + + @Override + public void setPort(int port) { + set(getNode(), KEY_MAP, PROPERTY_PORT, port); + } + + @Override + public int getPort() { + return asInt(getNode(), KEY_MAP, PROPERTY_PORT); + } + + @Override + public String getProtocol() { + return asString(getNode(), KEY_MAP, PROPERTY_PROTOCOL); + } + + public void setProtocol(String proto) { + set(getNode(), KEY_MAP, PROPERTY_PROTOCOL, proto); + } + + @Override + public String getNodePort() { + return asString(getNode(), KEY_MAP, PROPERTY_NODE_PORT); + } + + @Override + public void setNodePort(String nodePort) { + set(getNode(), KEY_MAP, PROPERTY_NODE_PORT, nodePort); + } + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + getPort(); + result = prime * result + getTargetPort().hashCode(); + result = prime * result + ((getName() == null) ? 0 : getName().hashCode()); + result = prime * result + ((getProtocol() == null) ? 0 : getProtocol().hashCode()); + return result; + } + + @Override + public boolean equals(Object obj) { + if (this == obj) { + return true; + } + if (obj == null) { + return false; + } + if (getClass() != obj.getClass()) { + return false; + } + ServicePort other = (ServicePort) obj; + if (getPort() != other.getPort()) { + return false; + } + if (getTargetPort() == null) { + if (other.getTargetPort() != null) { + return false; + } + } else if (!getTargetPort().equals(other.getTargetPort())) { + return false; + } + if (getName() == null) { + if (other.getName() != null) { + return false; + } + } else if (!getName().equals(other.getName())) { + return false; + } + if (getProtocol() == null) { + if (other.getProtocol() != null) { + return false; + } + } else if (!getProtocol().equals(other.getProtocol())) { + return false; + } + if (getNodePort() == null) { + if (other.getNodePort() != null) { + return false; + } + } else if (!getNodePort().equals(other.getNodePort())) { + return false; + } + return true; + } + + @Override + public String toString() { + return toJson(false); + } + } diff --git a/src/main/java/com/openshift/internal/restclient/model/Status.java b/src/main/java/com/openshift/internal/restclient/model/Status.java index 7bad4d9b..3b59e45e 100644 --- a/src/main/java/com/openshift/internal/restclient/model/Status.java +++ b/src/main/java/com/openshift/internal/restclient/model/Status.java @@ -6,8 +6,10 @@ * * Contributors: Red Hat, Inc. ******************************************************************************/ + package com.openshift.internal.restclient.model; +import java.util.HashMap; import java.util.Map; import org.jboss.dmr.ModelNode; @@ -15,42 +17,42 @@ import com.openshift.restclient.IClient; import com.openshift.restclient.model.IStatus; -/** - * @author Jeff Cantrill - */ -public class Status extends KubernetesResource implements IStatus{ - - private static final String STATUS_MESSAGE = "message"; - private static final String STATUS_CODE = "code"; - private static final String STATUS_STATUS = "status"; - - - public Status(ModelNode node, IClient client, Map propertyKeys) { - super(node, client, propertyKeys); - } - - public String getMessage(){ - return asString(STATUS_MESSAGE); - } - - @Override - public int getCode() { - return asInt(STATUS_CODE); - } - - @Override - public String getStatus() { - return asString(STATUS_STATUS); - } - - @Override - public boolean isFailure() { - return FAILURE.equalsIgnoreCase(getStatus()); - } - - @Override - public boolean isSuccess() { - return SUCCESS.equalsIgnoreCase(getStatus()); - } +public class Status extends KubernetesResource implements IStatus { + + private static final String STATUS_MESSAGE = "message"; + private static final String STATUS_CODE = "code"; + private static final String STATUS_STATUS = "status"; + + public Status(String json) { + this(ModelNode.fromJSONString(json), null, new HashMap<>()); + } + + public Status(ModelNode node, IClient client, Map propertyKeys) { + super(node, client, propertyKeys); + } + + public String getMessage() { + return asString(STATUS_MESSAGE); + } + + @Override + public int getCode() { + return asInt(STATUS_CODE); + } + + @Override + public String getStatus() { + return asString(STATUS_STATUS); + } + + @Override + public boolean isFailure() { + return FAILURE.equalsIgnoreCase(getStatus()); + } + + @Override + public boolean isSuccess() { + return SUCCESS.equalsIgnoreCase(getStatus()); + } } diff --git a/src/main/java/com/openshift/internal/restclient/model/authorization/OpenshiftPolicy.java b/src/main/java/com/openshift/internal/restclient/model/authorization/OpenshiftPolicy.java index 9d804c71..e6ce92ce 100644 --- a/src/main/java/com/openshift/internal/restclient/model/authorization/OpenshiftPolicy.java +++ b/src/main/java/com/openshift/internal/restclient/model/authorization/OpenshiftPolicy.java @@ -8,6 +8,7 @@ * Contributors: * Red Hat, Inc. - initial API and implementation ******************************************************************************/ + package com.openshift.internal.restclient.model.authorization; import java.util.Map; @@ -20,9 +21,8 @@ public class OpenshiftPolicy extends KubernetesResource implements IPolicy { - public OpenshiftPolicy(ModelNode node, IClient client, Map propertyKeys) { - super(node, client, propertyKeys); - // TODO Auto-generated constructor stub - } + public OpenshiftPolicy(ModelNode node, IClient client, Map propertyKeys) { + super(node, client, propertyKeys); + } } diff --git a/src/main/java/com/openshift/internal/restclient/model/authorization/OpenshiftRole.java b/src/main/java/com/openshift/internal/restclient/model/authorization/OpenshiftRole.java index e2e9c615..10b10f86 100644 --- a/src/main/java/com/openshift/internal/restclient/model/authorization/OpenshiftRole.java +++ b/src/main/java/com/openshift/internal/restclient/model/authorization/OpenshiftRole.java @@ -8,6 +8,7 @@ * Contributors: * Red Hat, Inc. - initial API and implementation ******************************************************************************/ + package com.openshift.internal.restclient.model.authorization; import java.util.Map; @@ -20,9 +21,8 @@ public class OpenshiftRole extends KubernetesResource implements IRole { - public OpenshiftRole(ModelNode node, IClient client, Map propertyKeys) { - super(node, client, propertyKeys); - // TODO Auto-generated constructor stub - } + public OpenshiftRole(ModelNode node, IClient client, Map propertyKeys) { + super(node, client, propertyKeys); + } } diff --git a/src/main/java/com/openshift/internal/restclient/model/authorization/PolicyBinding.java b/src/main/java/com/openshift/internal/restclient/model/authorization/PolicyBinding.java index 957f997a..154b68bf 100644 --- a/src/main/java/com/openshift/internal/restclient/model/authorization/PolicyBinding.java +++ b/src/main/java/com/openshift/internal/restclient/model/authorization/PolicyBinding.java @@ -8,6 +8,7 @@ * Contributors: * Red Hat, Inc. - initial API and implementation ******************************************************************************/ + package com.openshift.internal.restclient.model.authorization; import java.util.Map; @@ -20,9 +21,8 @@ public class PolicyBinding extends KubernetesResource implements IPolicyBinding { - public PolicyBinding(ModelNode node, IClient client, Map propertyKeys) { - super(node, client, propertyKeys); - // TODO Auto-generated constructor stub - } + public PolicyBinding(ModelNode node, IClient client, Map propertyKeys) { + super(node, client, propertyKeys); + } } diff --git a/src/main/java/com/openshift/internal/restclient/model/authorization/RoleBinding.java b/src/main/java/com/openshift/internal/restclient/model/authorization/RoleBinding.java index 73cfaad0..844ecd79 100644 --- a/src/main/java/com/openshift/internal/restclient/model/authorization/RoleBinding.java +++ b/src/main/java/com/openshift/internal/restclient/model/authorization/RoleBinding.java @@ -8,6 +8,7 @@ * Contributors: * Red Hat, Inc. - initial API and implementation ******************************************************************************/ + package com.openshift.internal.restclient.model.authorization; import java.util.Collections; @@ -26,86 +27,86 @@ public class RoleBinding extends KubernetesResource implements IRoleBinding { - private static final String ROLE_REF = "roleRef"; - private static final String USER_NAMES = "userNames"; - private static final String GROUP_NAMES = "groupNames"; - - public RoleBinding(ModelNode node, IClient client, Map propertyKeys) { - super(node, client, propertyKeys); - } - - @Override - public void setUserNames(Set names) { - if(names == null) { - names = Collections.emptySet(); - } - set(USER_NAMES, names); - } - - @SuppressWarnings("unchecked") - @Override - public Set getUserNames() { - return asSet(USER_NAMES, ModelType.STRING); - } - - @Override - public void addUserName(String name) { - get(USER_NAMES).add(name); - } - - @Override - public void setGroupNames(Set names) { - if(names == null) { - names = Collections.emptySet(); - } - set(GROUP_NAMES, names); - - } - - @SuppressWarnings("unchecked") - @Override - public Set getGroupNames() { - return asSet(GROUP_NAMES, ModelType.STRING); - } - - @Override - public void addGroupName(String name) { - get(GROUP_NAMES).add(name); - } - - @Override - public void setSubjects(Set subjects) { - if(subjects == null) - subjects = Collections.emptySet(); - ModelNode node = get("subjects"); - node.clear(); - for (IObjectReference ref : subjects) { - node.add(ModelNode.fromJSONString(ref.toJson())); - } - } - - @Override - public Set getSubjects() { - Set set = new HashSet<>(); - ModelNode node = get("subjects"); - if(node.isDefined()) { - for (ModelNode ref : node.asList()) { - set.add(new ObjectReference(ref)); - } - } - return set; - } - - @Override - public IObjectReference getRoleRef() { - return new ObjectReference(get(ROLE_REF)); - } - - @Override - public void setRoleRef(IObjectReference roleRef) { - ModelNode node = get(ROLE_REF); - node.set(ModelNode.fromJSONString(roleRef.toJson())); - } - - + private static final String ROLE_REF = "roleRef"; + private static final String USER_NAMES = "userNames"; + private static final String GROUP_NAMES = "groupNames"; + + public RoleBinding(ModelNode node, IClient client, Map propertyKeys) { + super(node, client, propertyKeys); + } + + @Override + public void setUserNames(Set names) { + if (names == null) { + names = Collections.emptySet(); + } + set(USER_NAMES, names); + } + + @SuppressWarnings("unchecked") + @Override + public Set getUserNames() { + return asSet(USER_NAMES, ModelType.STRING); + } + + @Override + public void addUserName(String name) { + get(USER_NAMES).add(name); + } + + @Override + public void setGroupNames(Set names) { + if (names == null) { + names = Collections.emptySet(); + } + set(GROUP_NAMES, names); + + } + + @SuppressWarnings("unchecked") + @Override + public Set getGroupNames() { + return asSet(GROUP_NAMES, ModelType.STRING); + } + + @Override + public void addGroupName(String name) { + get(GROUP_NAMES).add(name); + } + + @Override + public void setSubjects(Set subjects) { + if (subjects == null) { + subjects = Collections.emptySet(); + } + ModelNode node = get("subjects"); + node.clear(); + for (IObjectReference ref : subjects) { + node.add(ModelNode.fromJSONString(ref.toJson())); + } + } + + @Override + public Set getSubjects() { + Set set = new HashSet<>(); + ModelNode node = get("subjects"); + if (node.isDefined()) { + for (ModelNode ref : node.asList()) { + set.add(new ObjectReference(ref)); + } + } + return set; + } + + @Override + public IObjectReference getRoleRef() { + return new ObjectReference(get(ROLE_REF)); + } + + @Override + public void setRoleRef(IObjectReference roleRef) { + ModelNode node = get(ROLE_REF); + node.set(ModelNode.fromJSONString(roleRef.toJson())); + } + } diff --git a/src/main/java/com/openshift/internal/restclient/model/build/BinaryBuildSource.java b/src/main/java/com/openshift/internal/restclient/model/build/BinaryBuildSource.java new file mode 100644 index 00000000..b7a92c9d --- /dev/null +++ b/src/main/java/com/openshift/internal/restclient/model/build/BinaryBuildSource.java @@ -0,0 +1,48 @@ +/******************************************************************************* + * Copyright (c) 2018 Red Hat, Inc. Distributed under license by Red Hat, Inc. + * All rights reserved. This program is made available under the terms of the + * Eclipse Public License v1.0 which accompanies this distribution, and is + * available at http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: Red Hat, Inc. + ******************************************************************************/ + +package com.openshift.internal.restclient.model.build; + +import com.openshift.restclient.model.build.BuildSourceType; +import com.openshift.restclient.model.build.IBinaryBuildSource; + +public class BinaryBuildSource implements IBinaryBuildSource { + + private String asFile; + private String contextDir; + + public BinaryBuildSource(String asFile, String contextDir) { + this.asFile = asFile; + this.contextDir = contextDir; + } + + @Override + public String getType() { + return BuildSourceType.BINARY; + } + + @Override + public String getAsFile() { + return asFile; + } + + public void setAsFile(String asFile) { + this.asFile = asFile; + } + + @Override + public String getContextDir() { + return contextDir; + } + + public void setContextDir(String contextDir) { + this.contextDir = contextDir; + } + +} diff --git a/src/main/java/com/openshift/internal/restclient/model/build/BuildConfigBuilder.java b/src/main/java/com/openshift/internal/restclient/model/build/BuildConfigBuilder.java index 200de401..9d4a8b69 100644 --- a/src/main/java/com/openshift/internal/restclient/model/build/BuildConfigBuilder.java +++ b/src/main/java/com/openshift/internal/restclient/model/build/BuildConfigBuilder.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2016 Red Hat, Inc. + * Copyright (c) 2016-2018 Red Hat, Inc. * Distributed under license by Red Hat, Inc. All rights reserved. * This program is made available under the terms of the * Eclipse Public License v1.0 which accompanies this distribution, @@ -8,218 +8,321 @@ * Contributors: * Red Hat, Inc. - initial API and implementation ******************************************************************************/ + package com.openshift.internal.restclient.model.build; -import java.util.Collections; import java.util.List; import java.util.Map; import java.util.UUID; +import org.apache.commons.lang.StringUtils; import org.jboss.dmr.ModelNode; import com.openshift.internal.restclient.model.BuildConfig; -import com.openshift.internal.util.JBossDmrExtentions; import com.openshift.restclient.IClient; import com.openshift.restclient.ResourceKind; import com.openshift.restclient.images.DockerImageURI; import com.openshift.restclient.model.IBuildConfig; import com.openshift.restclient.model.IEnvironmentVariable; +import com.openshift.restclient.model.IObjectReference; import com.openshift.restclient.model.build.BuildTriggerType; import com.openshift.restclient.model.build.IBuildConfigBuilder; - +/** + * Impl of a builder to create buildconfigs + * + */ public class BuildConfigBuilder implements IBuildConfigBuilder { - - private SourceStrategyBuilder sourceStrategyBuilder; - private GitSourceBuilder gitSourceBuilder; - private String imageStreamTagOutput; - private boolean buildOnConfigChange; - private boolean buildOnImageChange; - private boolean buildOnSourceChange; - private final IClient client; - private String name; - private String namespace; - - public BuildConfigBuilder(IClient client) { - this.client = client; - } - - @Override - public boolean isSupported() { - return true; - } - - @Override - public String getName() { - return BuildConfigBuilder.class.getSimpleName(); - } - - @Override - public IBuildConfigBuilder named(String name) { - this.name = name; - return this; - } - - @Override - public IBuildConfigBuilder inNamespace(String namespace) { - this.namespace = namespace; - return this; - } - - @Override - public IBuildConfig build() { - BuildConfig bc = client.getResourceFactory().stub(ResourceKind.BUILD_CONFIG, this.name, this.namespace); - - if(sourceStrategyBuilder != null) { - bc.setBuildStrategy(sourceStrategyBuilder.build(bc.getPropertyKeys())); - } - if(gitSourceBuilder != null) { - bc.setBuildSource(gitSourceBuilder.build()); - } - - - //TODO move into bc - ModelNode node = bc.getNode(); - JBossDmrExtentions.set(node, Collections.emptyMap(), "spec.output.to.kind", ResourceKind.IMAGE_STREAM_TAG); - JBossDmrExtentions.set(node, Collections.emptyMap(), "spec.output.to.name", imageStreamTagOutput); - - bc.addBuildTrigger(new WebhookTrigger(BuildTriggerType.GENERIC, UUID.randomUUID().toString(), null)); - if(buildOnImageChange) { - bc.addBuildTrigger(new ImageChangeTrigger(BuildTriggerType.IMAGE_CHANGE, null, null, null)); - } - if(buildOnConfigChange) { - bc.addBuildTrigger(new ImageChangeTrigger(BuildTriggerType.CONFIG_CHANGE,null, null, null)); - } - if(buildOnSourceChange) { - bc.addBuildTrigger(new WebhookTrigger(BuildTriggerType.GITHUB, UUID.randomUUID().toString(), null)); - } - - return bc; - } - - @Override - public IBuildConfigBuilder buildOnSourceChange(boolean onSourceChange) { - this.buildOnSourceChange = onSourceChange; - return this; - } - - @Override - public IBuildConfigBuilder buildOnImageChange(boolean onImageChange) { - this.buildOnImageChange = onImageChange; - return this; - } - - @Override - public IBuildConfigBuilder buildOnConfigChange(boolean onConfigChange) { - this.buildOnConfigChange = onConfigChange; - return this; - } - - @Override - public IBuildConfigBuilder toImageStreamTag(String tag) { - imageStreamTagOutput = tag; - return this; - } - - @Override - public ISourceStrategyBuilder usingSourceStrategy() { - sourceStrategyBuilder = new SourceStrategyBuilder(this); - return sourceStrategyBuilder; - } - - @Override - public IGitSourceBuilder fromGitSource() { - gitSourceBuilder = new GitSourceBuilder(this); - return gitSourceBuilder; - } - - class GitSourceBuilder implements IGitSourceBuilder { - - private IBuildConfigBuilder builder; - private String url; - private String ref; - private String contextDir; - - GitSourceBuilder(IBuildConfigBuilder builder){ - this.builder = builder; - } - - private GitBuildSource build() { - return new GitBuildSource(url, ref, contextDir); - } - - @Override - public IBuildConfigBuilder end() { - return builder; - } - - @Override - public IGitSourceBuilder fromGitUrl(String url) { - this.url = url; - return this; - } - - @Override - public IGitSourceBuilder usingGitReference(String ref) { - this.ref = ref; - return this; - } - - @Override - public IGitSourceBuilder inContextDir(String contextDir) { - this.contextDir = contextDir; - return this; - } - - } - - - class SourceStrategyBuilder implements ISourceStrategyBuilder{ - - private IBuildConfigBuilder builder; - private List envVars; - private String namespace; - private String tag; - private String fromKind; - - SourceStrategyBuilder(IBuildConfigBuilder builder){ - this.builder = builder; - } - - public SourceBuildStrategy build(Map overrides) { - SourceBuildStrategy strategy = new SourceBuildStrategy(new ModelNode(), overrides); - strategy.setEnvVars(envVars); - strategy.setFromNamespace(namespace); - strategy.setImage(new DockerImageURI(tag)); - strategy.setFromKind(fromKind); - return strategy; - } - - @Override - public IBuildConfigBuilder end() { - return builder; - } - - @Override - public ISourceStrategyBuilder fromImageStreamTag(String tag) { - this.tag = tag; - this.fromKind = ResourceKind.IMAGE_STREAM_TAG; - return this; - } - - @Override - public ISourceStrategyBuilder inNamespace(String namespace) { - this.namespace = namespace; - return this; - } - - - @Override - public ISourceStrategyBuilder withEnvVars(List envVars) { - this.envVars = envVars; - return this; - } - - } + + private SourceStrategyBuilder sourceStrategyBuilder; + private GitSourceBuilder gitSourceBuilder; + private BinarySourceBuilder binarySourceBuilder; + private JenkinsPipelineStrategyBuilder jenkinsPipelineStrategyBuilder; + private String imageStreamTagOutput; + private boolean buildOnConfigChange; + private boolean buildOnImageChange; + private boolean buildOnSourceChange; + private final IClient client; + private String name; + private String namespace; + private Map labels; + + public BuildConfigBuilder(IClient client) { + this.client = client; + } + + @Override + public boolean isSupported() { + return true; + } + + @Override + public String getName() { + return BuildConfigBuilder.class.getSimpleName(); + } + + @Override + public IBuildConfigBuilder named(String name) { + this.name = name; + return this; + } + + @Override + public IBuildConfigBuilder inNamespace(String namespace) { + this.namespace = namespace; + return this; + } + + @Override + public IBuildConfigBuilder withLabels(Map labels) { + this.labels = labels; + return this; + } + + @Override + public IBuildConfig build() { + BuildConfig bc = client.getResourceFactory().stub(ResourceKind.BUILD_CONFIG, this.name, this.namespace); + + if (sourceStrategyBuilder != null) { + bc.setBuildStrategy(sourceStrategyBuilder.build(bc.getPropertyKeys())); + } else if (jenkinsPipelineStrategyBuilder != null) { + bc.setBuildStrategy(jenkinsPipelineStrategyBuilder.build(bc.getPropertyKeys())); + } + + if (gitSourceBuilder != null) { + bc.setBuildSource(gitSourceBuilder.build()); + } else if (binarySourceBuilder != null) { + bc.setBuildSource(binarySourceBuilder.build()); + } + + if (labels != null && !labels.isEmpty()) { + for (Map.Entry label : labels.entrySet()) { + bc.addLabel(label.getKey(), label.getValue()); + } + } + + DockerImageURI uri = new DockerImageURI(imageStreamTagOutput); + IObjectReference outRef = bc.getBuildOutputReference(); + outRef.setKind(ResourceKind.IMAGE_STREAM_TAG); + outRef.setName(uri.getNameAndTag()); + if (StringUtils.isNotBlank(uri.getUserName())) { + outRef.setNamespace(uri.getUserName()); + } + + bc.addBuildTrigger(new WebhookTrigger(BuildTriggerType.GENERIC, UUID.randomUUID().toString(), null)); + if (buildOnImageChange) { + bc.addBuildTrigger(new ImageChangeTrigger(BuildTriggerType.IMAGE_CHANGE, null, null, null)); + } + if (buildOnConfigChange) { + bc.addBuildTrigger(new ImageChangeTrigger(BuildTriggerType.CONFIG_CHANGE, null, null, null)); + } + if (buildOnSourceChange) { + bc.addBuildTrigger(new WebhookTrigger(BuildTriggerType.GITHUB, UUID.randomUUID().toString(), null)); + } + + return bc; + } + + @Override + public IBuildConfigBuilder buildOnSourceChange(boolean onSourceChange) { + this.buildOnSourceChange = onSourceChange; + return this; + } + + @Override + public IBuildConfigBuilder buildOnImageChange(boolean onImageChange) { + this.buildOnImageChange = onImageChange; + return this; + } + + @Override + public IBuildConfigBuilder buildOnConfigChange(boolean onConfigChange) { + this.buildOnConfigChange = onConfigChange; + return this; + } + + @Override + public IBuildConfigBuilder toImageStreamTag(String tag) { + imageStreamTagOutput = tag; + return this; + } + + @Override + public ISourceStrategyBuilder usingSourceStrategy() { + sourceStrategyBuilder = new SourceStrategyBuilder(this); + return sourceStrategyBuilder; + } + + @Override + public IGitSourceBuilder fromGitSource() { + gitSourceBuilder = new GitSourceBuilder(this); + return gitSourceBuilder; + } + + @Override + public IBinarySourceBuilder fromBinarySource() { + binarySourceBuilder = new BinarySourceBuilder(this); + return binarySourceBuilder; + } + + @Override + public IJenkinsPipelineStrategyBuilder usingJenkinsPipelineStrategy() { + jenkinsPipelineStrategyBuilder = new JenkinsPipelineStrategyBuilder(this); + return jenkinsPipelineStrategyBuilder; + } + + class SourceBuilder implements ISourceBuilder { + + protected IBuildConfigBuilder builder; + protected String contextDir; + + SourceBuilder(IBuildConfigBuilder builder) { + this.builder = builder; + } + + @Override + public IBuildConfigBuilder end() { + return builder; + } + + @Override + public T inContextDir(String contextDir) { + this.contextDir = contextDir; + return (T) this; + } + + } + + class GitSourceBuilder extends SourceBuilder implements IGitSourceBuilder { + private String url; + private String ref; + + GitSourceBuilder(IBuildConfigBuilder builder) { + super(builder); + } + + private GitBuildSource build() { + return new GitBuildSource(url, ref, contextDir); + } + + @Override + public IGitSourceBuilder fromGitUrl(String url) { + this.url = url; + return this; + } + + @Override + public IGitSourceBuilder usingGitReference(String ref) { + this.ref = ref; + return this; + } + } + + class BinarySourceBuilder extends SourceBuilder implements IBinarySourceBuilder { + private String asFile; + + BinarySourceBuilder(IBuildConfigBuilder builder) { + super(builder); + } + + private BinaryBuildSource build() { + return new BinaryBuildSource(asFile, contextDir); + } + + @Override + public IBinarySourceBuilder fromAsFile(String asFile) { + this.asFile = asFile; + return this; + } + } + + class SourceStrategyBuilder implements ISourceStrategyBuilder { + + private IBuildConfigBuilder builder; + private List envVars; + private String namespace; + private String tag; + private String fromKind; + + SourceStrategyBuilder(IBuildConfigBuilder builder) { + this.builder = builder; + } + + public SourceBuildStrategy build(Map overrides) { + SourceBuildStrategy strategy = new SourceBuildStrategy(new ModelNode(), overrides); + strategy.setEnvVars(envVars); + strategy.setFromNamespace(namespace); + strategy.setImage(new DockerImageURI(tag)); + strategy.setFromKind(fromKind); + return strategy; + } + + @Override + public IBuildConfigBuilder end() { + return builder; + } + + @Override + public ISourceStrategyBuilder fromImageStreamTag(String tag) { + this.tag = tag; + this.fromKind = ResourceKind.IMAGE_STREAM_TAG; + return this; + } + + @Override + public ISourceStrategyBuilder inNamespace(String namespace) { + this.namespace = namespace; + return this; + } + + @Override + public ISourceStrategyBuilder withEnvVars(List envVars) { + this.envVars = envVars; + return this; + } + + @Override + public ISourceStrategyBuilder fromDockerImage(String tag) { + this.tag = tag; + this.fromKind = "DockerImage"; + return this; + } + } + + class JenkinsPipelineStrategyBuilder implements IJenkinsPipelineStrategyBuilder { + + private IBuildConfigBuilder builder; + private String jenkinsFilePath; + private String jenkinsFile; + + JenkinsPipelineStrategyBuilder(IBuildConfigBuilder builder) { + this.builder = builder; + } + + @Override + public IJenkinsPipelineStrategyBuilder usingFile(String file) { + this.jenkinsFile = file; + return this; + } + + @Override + public IJenkinsPipelineStrategyBuilder usingFilePath(String filePath) { + this.jenkinsFilePath = filePath; + return this; + } + + private JenkinsPipelineStrategy build(Map overrides) { + JenkinsPipelineStrategy strategy = new JenkinsPipelineStrategy(new ModelNode(), overrides); + strategy.setJenkinsfilePath(jenkinsFilePath); + strategy.setJenkinsfile(jenkinsFile); + return strategy; + } + + @Override + public IBuildConfigBuilder end() { + return builder; + } + + } } diff --git a/src/main/java/com/openshift/internal/restclient/model/build/BuildRequest.java b/src/main/java/com/openshift/internal/restclient/model/build/BuildRequest.java index 67fc88f2..076b9a21 100644 --- a/src/main/java/com/openshift/internal/restclient/model/build/BuildRequest.java +++ b/src/main/java/com/openshift/internal/restclient/model/build/BuildRequest.java @@ -8,8 +8,11 @@ * Contributors: * Red Hat, Inc. - initial API and implementation ******************************************************************************/ + package com.openshift.internal.restclient.model.build; +import java.util.ArrayList; +import java.util.List; import java.util.Map; import org.jboss.dmr.ModelNode; @@ -18,31 +21,56 @@ import com.openshift.restclient.IClient; import com.openshift.restclient.model.build.IBuildRequest; -/** - * - * @author Jeff Cantrill - * - */ -public class BuildRequest extends KubernetesResource implements IBuildRequest{ - - private static final String COMMIT = "commit"; - private static final String GIT = "git"; - private static final String BIGGIT = "Git"; - private static final String TYPE = "type"; - private static final String REVISION = "revision"; - private static final String REVISION_GIT_COMMIT = REVISION + "." + GIT + "." + COMMIT; - private static final String REVISION_TYPE = REVISION + "." + TYPE; - - - public BuildRequest(ModelNode node, IClient client, Map propertyKeys) { - super(node, client, propertyKeys); - } - - - @Override - public void setCommitId(String commitId) { - set(REVISION_TYPE, BIGGIT); - set(REVISION_GIT_COMMIT, commitId); - } +public class BuildRequest extends KubernetesResource implements IBuildRequest { + + private static final String COMMIT = "commit"; + private static final String GIT = "git"; + private static final String BIGGIT = "Git"; + private static final String TYPE = "type"; + private static final String REVISION = "revision"; + private static final String REVISION_GIT_COMMIT = REVISION + "." + GIT + "." + COMMIT; + private static final String REVISION_TYPE = REVISION + "." + TYPE; + private static final String TRIGGERED_BY = "triggeredBy"; + private static final String MESSAGE = "message"; + private static final String ENV = "env"; + + public BuildRequest(ModelNode node, IClient client, Map propertyKeys) { + super(node, client, propertyKeys); + } + + @Override + public void setCommitId(String commitId) { + set(REVISION_TYPE, BIGGIT); + set(REVISION_GIT_COMMIT, commitId); + } + + @Override + public void addBuildCause(String cause) { + ModelNode triggeredBys = get(TRIGGERED_BY); + triggeredBys.add(MESSAGE, cause); + } + + @Override + public String getCommitId() { + return get(REVISION_GIT_COMMIT).asString(); + } + + @Override + public List getBuildCauses() { + List causes = get(TRIGGERED_BY).asList(); + ArrayList ret = new ArrayList<>(); + for (ModelNode cause : causes) { + ret.add(cause.asString()); + } + return ret; + } + + @Override + public void setEnvironmentVariable(String name, String value) { + ModelNode envs = get(ENV); + ModelNode entry = envs.add(); + entry.get(NAME).set(name); + entry.get(VALUE).set(value); + } } diff --git a/src/main/java/com/openshift/internal/restclient/model/build/BuildStatus.java b/src/main/java/com/openshift/internal/restclient/model/build/BuildStatus.java index 226c731b..78b4bdcc 100644 --- a/src/main/java/com/openshift/internal/restclient/model/build/BuildStatus.java +++ b/src/main/java/com/openshift/internal/restclient/model/build/BuildStatus.java @@ -8,9 +8,12 @@ * Contributors: * Red Hat, Inc. - initial API and implementation ******************************************************************************/ + package com.openshift.internal.restclient.model.build; -import static com.openshift.internal.util.JBossDmrExtentions.*; +import static com.openshift.internal.util.JBossDmrExtentions.asString; +import static com.openshift.internal.util.JBossDmrExtentions.get; + import java.util.Map; import org.jboss.dmr.ModelNode; @@ -21,33 +24,32 @@ public class BuildStatus extends ModelNodeAdapter implements IBuildStatus { - public BuildStatus(ModelNode node, Map propertyKeys) { - super(node, propertyKeys); - } - - @Override - public String getPhase() { - return asString(getNode(), getPropertyKeys(), "phase"); - } - - @Override - public String getStartTime() { - return asString(getNode(), getPropertyKeys(), "startTimestamp"); - } - - @Override - public long getDuration() { - ModelNode node = get(getNode(), getPropertyKeys(), "duration"); - if(!node.isDefined()) { - return 0L; - } - return node.asLong(); - } - - @Override - public DockerImageURI getOutputDockerImage() { - return new DockerImageURI(asString(getNode(), getPropertyKeys(), "outputDockerImageReference")); - } - - + public BuildStatus(ModelNode node, Map propertyKeys) { + super(node, propertyKeys); + } + + @Override + public String getPhase() { + return asString(getNode(), getPropertyKeys(), "phase"); + } + + @Override + public String getStartTime() { + return asString(getNode(), getPropertyKeys(), "startTimestamp"); + } + + @Override + public long getDuration() { + ModelNode node = get(getNode(), getPropertyKeys(), "duration"); + if (!node.isDefined()) { + return 0L; + } + return node.asLong(); + } + + @Override + public DockerImageURI getOutputDockerImage() { + return new DockerImageURI(asString(getNode(), getPropertyKeys(), "outputDockerImageReference")); + } + } diff --git a/src/main/java/com/openshift/internal/restclient/model/build/CustomBuildStrategy.java b/src/main/java/com/openshift/internal/restclient/model/build/CustomBuildStrategy.java index bfe04f49..d739f0c3 100644 --- a/src/main/java/com/openshift/internal/restclient/model/build/CustomBuildStrategy.java +++ b/src/main/java/com/openshift/internal/restclient/model/build/CustomBuildStrategy.java @@ -6,6 +6,7 @@ * * Contributors: Red Hat, Inc. ******************************************************************************/ + package com.openshift.internal.restclient.model.build; import java.util.Map; @@ -14,38 +15,36 @@ import com.openshift.restclient.model.build.BuildStrategyType; import com.openshift.restclient.model.build.ICustomBuildStrategy; -/** - * @author Jeff Cantrill - */ public class CustomBuildStrategy implements ICustomBuildStrategy { - private DockerImageURI image; - private boolean exposeDockerSocket; - private Map env; - - public CustomBuildStrategy(String image, boolean exposeDockerSocket, Map env){ - this.image = new DockerImageURI(image); - this.exposeDockerSocket = exposeDockerSocket; - this.env = env; - } - @Override - public String getType() { - return BuildStrategyType.CUSTOM; - } - - @Override - public Map getEnvironmentVariables() { - return env; - } - - @Override - public boolean exposeDockerSocket() { - return exposeDockerSocket; - } - - @Override - public DockerImageURI getImage() { - return image; - } + private DockerImageURI image; + private boolean exposeDockerSocket; + private Map env; + + public CustomBuildStrategy(String image, boolean exposeDockerSocket, Map env) { + this.image = new DockerImageURI(image); + this.exposeDockerSocket = exposeDockerSocket; + this.env = env; + } + + @Override + public String getType() { + return BuildStrategyType.CUSTOM; + } + + @Override + public Map getEnvironmentVariables() { + return env; + } + + @Override + public boolean exposeDockerSocket() { + return exposeDockerSocket; + } + + @Override + public DockerImageURI getImage() { + return image; + } } diff --git a/src/main/java/com/openshift/internal/restclient/model/build/DockerBuildStrategy.java b/src/main/java/com/openshift/internal/restclient/model/build/DockerBuildStrategy.java index e94d3c1d..ae958756 100644 --- a/src/main/java/com/openshift/internal/restclient/model/build/DockerBuildStrategy.java +++ b/src/main/java/com/openshift/internal/restclient/model/build/DockerBuildStrategy.java @@ -6,47 +6,43 @@ * * Contributors: Red Hat, Inc. ******************************************************************************/ + package com.openshift.internal.restclient.model.build; import com.openshift.restclient.images.DockerImageURI; import com.openshift.restclient.model.build.BuildStrategyType; import com.openshift.restclient.model.build.IDockerBuildStrategy; -/** - * @author Jeff Cantrill - */ public class DockerBuildStrategy implements IDockerBuildStrategy { - private boolean noCache; - private DockerImageURI image; - private String contextDir; - - public DockerBuildStrategy(String contextDir, boolean noCache, - String baseImage) { - this.contextDir = contextDir; - this.noCache = noCache; - this.image = new DockerImageURI(baseImage); - } - - @Override - public String getType() { - return BuildStrategyType.DOCKER; - } - - @Override - public String getContextDir() { - return contextDir; - } - - @Override - public boolean isNoCache() { - // TODO Auto-generated method stub - return noCache; - } - - @Override - public DockerImageURI getBaseImage() { - return image; - } + private boolean noCache; + private DockerImageURI image; + private String contextDir; + + public DockerBuildStrategy(String contextDir, boolean noCache, String baseImage) { + this.contextDir = contextDir; + this.noCache = noCache; + this.image = new DockerImageURI(baseImage); + } + + @Override + public String getType() { + return BuildStrategyType.DOCKER; + } + + @Override + public String getContextDir() { + return contextDir; + } + + @Override + public boolean isNoCache() { + return noCache; + } + + @Override + public DockerImageURI getBaseImage() { + return image; + } } diff --git a/src/main/java/com/openshift/internal/restclient/model/build/GitBuildSource.java b/src/main/java/com/openshift/internal/restclient/model/build/GitBuildSource.java index 8f02adc3..083a8228 100644 --- a/src/main/java/com/openshift/internal/restclient/model/build/GitBuildSource.java +++ b/src/main/java/com/openshift/internal/restclient/model/build/GitBuildSource.java @@ -6,56 +6,54 @@ * * Contributors: Red Hat, Inc. ******************************************************************************/ + package com.openshift.internal.restclient.model.build; import com.openshift.restclient.model.build.BuildSourceType; import com.openshift.restclient.model.build.IGitBuildSource; -/** - * @author Jeff Cantrill - */ public class GitBuildSource implements IGitBuildSource { - private String ref; - private String uri; - private String contextDir; - - public GitBuildSource(String uri, String ref, String contextDir){ - this.ref = ref; - this.uri = uri; - this.contextDir = contextDir; - } - - @Override - public String getType() { - return BuildSourceType.GIT; - } - - @Override - public String getURI() { - return uri; - } - - public void setURI(String uri) { - this.uri = uri; - } - - @Override - public String getRef() { - return ref; - } - - public void setRef(String ref) { - this.ref = ref; - } - - @Override - public String getContextDir() { - return contextDir; - } - - public void setContextDir(String contextDir) { - this.contextDir = contextDir; - } + private String ref; + private String uri; + private String contextDir; + + public GitBuildSource(String uri, String ref, String contextDir) { + this.ref = ref; + this.uri = uri; + this.contextDir = contextDir; + } + + @Override + public String getType() { + return BuildSourceType.GIT; + } + + @Override + public String getURI() { + return uri; + } + + public void setURI(String uri) { + this.uri = uri; + } + + @Override + public String getRef() { + return ref; + } + + public void setRef(String ref) { + this.ref = ref; + } + + @Override + public String getContextDir() { + return contextDir; + } + + public void setContextDir(String contextDir) { + this.contextDir = contextDir; + } } diff --git a/src/main/java/com/openshift/internal/restclient/model/build/ImageChangeTrigger.java b/src/main/java/com/openshift/internal/restclient/model/build/ImageChangeTrigger.java index 1d2c878c..6eee76ff 100644 --- a/src/main/java/com/openshift/internal/restclient/model/build/ImageChangeTrigger.java +++ b/src/main/java/com/openshift/internal/restclient/model/build/ImageChangeTrigger.java @@ -6,89 +6,97 @@ * * Contributors: Red Hat, Inc. ******************************************************************************/ + package com.openshift.internal.restclient.model.build; import static org.apache.commons.lang.StringUtils.isNotBlank; + import com.openshift.restclient.images.DockerImageURI; import com.openshift.restclient.model.build.BuildTriggerType; import com.openshift.restclient.model.build.IImageChangeTrigger; -/** - * @author Jeff Cantrill - */ public class ImageChangeTrigger implements IImageChangeTrigger { - private String tag; - private DockerImageURI image; - private DockerImageURI from; - private final String type; + private String tag; + private DockerImageURI image; + private DockerImageURI from; + private final String type; + + public ImageChangeTrigger(String image, String from, String tag) { + this(BuildTriggerType.IMAGE_CHANGE, image, from, tag); + } + + public ImageChangeTrigger(String type, String image, String from, String tag) { + this.type = type; + this.tag = tag; + this.image = isNotBlank(image) ? new DockerImageURI(image) : null; + this.from = isNotBlank(from) ? new DockerImageURI(from) : null; + } - public ImageChangeTrigger(String image, String from, String tag) { - this(BuildTriggerType.IMAGE_CHANGE, image, from, tag); - } - - public ImageChangeTrigger(String type, String image, String from, String tag) { - this.type = type; - this.tag = tag; - this.image = isNotBlank(image) ? new DockerImageURI(image) : null; - this.from = isNotBlank(from) ? new DockerImageURI(from) : null; - } + @Override + public String getType() { + return type; + } - @Override - public String getType() { - return type; - } + @Override + public DockerImageURI getImage() { + return image; + } - @Override - public DockerImageURI getImage() { - return image; - } + @Override + public DockerImageURI getFrom() { + return from; + } - @Override - public DockerImageURI getFrom() { - return from; - } + @Override + public String getTag() { + return this.tag; + } - @Override - public String getTag() { - return this.tag; - } + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + ((from == null) ? 0 : from.hashCode()); + result = prime * result + ((image == null) ? 0 : image.hashCode()); + result = prime * result + ((tag == null) ? 0 : tag.hashCode()); + return result; + } - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = prime * result + ((from == null) ? 0 : from.hashCode()); - result = prime * result + ((image == null) ? 0 : image.hashCode()); - result = prime * result + ((tag == null) ? 0 : tag.hashCode()); - return result; - } + @Override + public boolean equals(Object obj) { + if (this == obj) { + return true; + } + if (obj == null) { + return false; + } + if (getClass() != obj.getClass()) { + return false; + } + ImageChangeTrigger other = (ImageChangeTrigger) obj; + if (from == null) { + if (other.from != null) { + return false; + } + } else if (!from.equals(other.from)) { + return false; + } + if (image == null) { + if (other.image != null) { + return false; + } + } else if (!image.equals(other.image)) { + return false; + } + if (tag == null) { + if (other.tag != null) { + return false; + } + } else if (!tag.equals(other.tag)) { + return false; + } + return true; + } - @Override - public boolean equals(Object obj) { - if (this == obj) - return true; - if (obj == null) - return false; - if (getClass() != obj.getClass()) - return false; - ImageChangeTrigger other = (ImageChangeTrigger) obj; - if (from == null) { - if (other.from != null) - return false; - } else if (!from.equals(other.from)) - return false; - if (image == null) { - if (other.image != null) - return false; - } else if (!image.equals(other.image)) - return false; - if (tag == null) { - if (other.tag != null) - return false; - } else if (!tag.equals(other.tag)) - return false; - return true; - } - } diff --git a/src/main/java/com/openshift/internal/restclient/model/build/JenkinsPipelineStrategy.java b/src/main/java/com/openshift/internal/restclient/model/build/JenkinsPipelineStrategy.java new file mode 100644 index 00000000..434a7404 --- /dev/null +++ b/src/main/java/com/openshift/internal/restclient/model/build/JenkinsPipelineStrategy.java @@ -0,0 +1,90 @@ +/******************************************************************************* + * Copyright (c) 2017 Red Hat, Inc. + * Distributed under license by Red Hat, Inc. All rights reserved. + * This program is made available under the terms of the + * Eclipse Public License v1.0 which accompanies this distribution, + * and is available at http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Red Hat, Inc. - initial API and implementation + ******************************************************************************/ + +package com.openshift.internal.restclient.model.build; + +import static com.openshift.internal.util.JBossDmrExtentions.asString; +import static com.openshift.internal.util.JBossDmrExtentions.set; + +import java.util.Collection; +import java.util.Collections; +import java.util.Map; +import java.util.stream.Collectors; + +import org.jboss.dmr.ModelNode; + +import com.openshift.internal.restclient.model.EnvironmentVariable; +import com.openshift.internal.restclient.model.ModelNodeAdapter; +import com.openshift.internal.restclient.model.properties.ResourcePropertyKeys; +import com.openshift.internal.util.JBossDmrExtentions; +import com.openshift.restclient.model.IEnvironmentVariable; +import com.openshift.restclient.model.build.BuildStrategyType; +import com.openshift.restclient.model.build.IJenkinsPipelineStrategy; + +/** + * @author Andre Dietisheim + */ +public class JenkinsPipelineStrategy extends ModelNodeAdapter + implements IJenkinsPipelineStrategy, ResourcePropertyKeys { + + public JenkinsPipelineStrategy(ModelNode node, Map propertyKeys) { + super(node, propertyKeys); + set(node, propertyKeys, TYPE, BuildStrategyType.JENKINS_PIPELINE); + } + + @Override + public String getType() { + return asString(getNode(), getPropertyKeys(), TYPE); + } + + @Override + public void setJenkinsfilePath(String filePath) { + set(getNode(), getPropertyKeys(), JENKINS_FILE_PATH, filePath); + } + + @Override + public String getJenkinsfilePath() { + return asString(getNode(), getPropertyKeys(), JENKINS_FILE_PATH); + } + + @Override + public void setJenkinsfile(String file) { + set(getNode(), getPropertyKeys(), JENKINS_FILE, file); + } + + @Override + public String getJenkinsfile() { + return asString(getNode(), getPropertyKeys(), JENKINS_FILE); + } + + @Override + public Collection getEnvVars() { + String[] path = JBossDmrExtentions.getPath(getPropertyKeys(), ENV); + ModelNode envNode = getNode().get(path); + if (envNode.isDefined()) { + return envNode.asList().stream().map(n -> new EnvironmentVariable(n, getPropertyKeys())) + .collect(Collectors.toList()); + } + return Collections.emptyList(); + } + + @Override + public void setEnvVars(Collection envVars) { + if (envVars == null) { + return; + } + String[] path = JBossDmrExtentions.getPath(getPropertyKeys(), ENV); + ModelNode envNode = getNode().get(path); + envNode.clear(); + envVars.forEach(v -> envNode.add(ModelNode.fromJSONString(v.toJson()))); + } + +} diff --git a/src/main/java/com/openshift/internal/restclient/model/build/STIBuildStrategy.java b/src/main/java/com/openshift/internal/restclient/model/build/STIBuildStrategy.java index 97d884fc..dc394e84 100644 --- a/src/main/java/com/openshift/internal/restclient/model/build/STIBuildStrategy.java +++ b/src/main/java/com/openshift/internal/restclient/model/build/STIBuildStrategy.java @@ -6,6 +6,7 @@ * * Contributors: Red Hat, Inc. ******************************************************************************/ + package com.openshift.internal.restclient.model.build; import java.util.Map; @@ -14,52 +15,49 @@ import com.openshift.restclient.model.build.BuildStrategyType; import com.openshift.restclient.model.build.ISTIBuildStrategy; -/** - * @author Jeff Cantrill - */ @Deprecated -public class STIBuildStrategy implements ISTIBuildStrategy{ - - private DockerImageURI image; - private String scriptsLocation; - private boolean incremental; - private Map envVars; - - public STIBuildStrategy(String image, String scriptsLocation, boolean incremental, Map envVars) { - this.image = new DockerImageURI(image); - this.scriptsLocation = scriptsLocation; - this.incremental = incremental; - this.envVars = envVars; - } - - @Override - public String getType() { - return BuildStrategyType.STI; - } - - @Override - public DockerImageURI getImage() { - return image; - } - - @Override - public String getScriptsLocation() { - return scriptsLocation; - } - - @Override - public Map getEnvironmentVariables() { - return envVars; - } - - @Override - public boolean incremental() { - return incremental; - } - - @Override - public boolean forceClean() { - return !incremental; - } +public class STIBuildStrategy implements ISTIBuildStrategy { + + private DockerImageURI image; + private String scriptsLocation; + private boolean incremental; + private Map envVars; + + public STIBuildStrategy(String image, String scriptsLocation, boolean incremental, Map envVars) { + this.image = new DockerImageURI(image); + this.scriptsLocation = scriptsLocation; + this.incremental = incremental; + this.envVars = envVars; + } + + @Override + public String getType() { + return BuildStrategyType.STI; + } + + @Override + public DockerImageURI getImage() { + return image; + } + + @Override + public String getScriptsLocation() { + return scriptsLocation; + } + + @Override + public Map getEnvironmentVariables() { + return envVars; + } + + @Override + public boolean incremental() { + return incremental; + } + + @Override + public boolean forceClean() { + return !incremental; + } } diff --git a/src/main/java/com/openshift/internal/restclient/model/build/SourceBuildStrategy.java b/src/main/java/com/openshift/internal/restclient/model/build/SourceBuildStrategy.java index 40995bfb..ae18a929 100644 --- a/src/main/java/com/openshift/internal/restclient/model/build/SourceBuildStrategy.java +++ b/src/main/java/com/openshift/internal/restclient/model/build/SourceBuildStrategy.java @@ -8,9 +8,12 @@ * Contributors: * Red Hat, Inc. - initial API and implementation ******************************************************************************/ + package com.openshift.internal.restclient.model.build; -import static com.openshift.internal.util.JBossDmrExtentions.*; +import static com.openshift.internal.util.JBossDmrExtentions.asBoolean; +import static com.openshift.internal.util.JBossDmrExtentions.asString; +import static com.openshift.internal.util.JBossDmrExtentions.set; import java.util.Collection; import java.util.Collections; @@ -31,127 +34,121 @@ import com.openshift.restclient.model.build.BuildStrategyType; import com.openshift.restclient.model.build.ISourceBuildStrategy; -/** - * - * @author Jeff Cantrill - * - */ -public class SourceBuildStrategy extends ModelNodeAdapter implements ISourceBuildStrategy, ResourcePropertyKeys{ - - public static final String FROM_IMAGE = "sourceStrategy.from.name"; - public static final String FROM_KIND = "sourceStrategy.from.kind"; - public static final String FROM_NAMESPACE = "sourceStrategy.from.namespace"; - public static final String SCRIPTS = "sourceStrategy.scripts"; - public static final String INCREMENTAL = "sourceStrategy.incremental"; - public static final String ENV = "sourceStrategy.env"; - - public SourceBuildStrategy(ModelNode node, Map propertyKeys) { - super(node, propertyKeys); - set(node, propertyKeys, TYPE, BuildStrategyType.SOURCE); - } - - @Override - public String getType() { - return asString(getNode(), getPropertyKeys(), TYPE); - } - - @Override - public String getFromNamespace() { - return asString(getNode(), getPropertyKeys(), FROM_NAMESPACE); - } - - @Override - public void setFromNamespace(String namespace) { - set(getNode(), getPropertyKeys(), FROM_NAMESPACE, namespace); - } - - @Override - public String getFromKind() { - return asString(getNode(),getPropertyKeys(), FROM_KIND); - } - - @Override - public void setFromKind(String kind) { - set(getNode(),getPropertyKeys(), FROM_KIND, kind); - } - - @Override - public DockerImageURI getImage() { - return new DockerImageURI(asString(getNode(), getPropertyKeys(), FROM_IMAGE)); - } - - @Override - public void setImage(DockerImageURI image) { - set(getNode(), getPropertyKeys(), FROM_IMAGE, image.toString()); - } - - @Override - public String getScriptsLocation() { - return asString(getNode(), getPropertyKeys(), SCRIPTS); - } - - @Override - public void setScriptsLocation(String location) { - set(getNode(), getPropertyKeys(), SCRIPTS, location); - } - - @Override - public Collection getEnvVars() { - String [] path = JBossDmrExtentions.getPath(getPropertyKeys(), ENV); - ModelNode envNode = getNode().get(path); - if(envNode.isDefined()) { - return envNode.asList() - .stream() - .map(n-> new EnvironmentVariable(n, getPropertyKeys())) - .collect(Collectors.toList()); - } - return Collections.emptyList(); - } - - @Override - public void setEnvVars(Collection envVars) { - if(envVars == null) return; - String [] path = JBossDmrExtentions.getPath(getPropertyKeys(), ENV); - ModelNode envNode = getNode().get(path); - envNode.clear(); - envVars.forEach(v->envNode.add(ModelNode.fromJSONString(v.toJson()))); - } - - @Override - public Map getEnvironmentVariables() { - String [] path = JBossDmrExtentions.getPath(getPropertyKeys(), ENV); - ModelNode env = getNode().get(path); - Map values = new HashMap<>(); - if(env.getType() == ModelType.LIST){ - for (ModelNode value : env.asList()) { - values.put(value.get(NAME).asString(), value.get(VALUE).asString()); - } - } - return values; - } - - @Override - public void setEnvironmentVariables(Map envVars) { - String [] path = JBossDmrExtentions.getPath(getPropertyKeys(), ENV); - ModelNode env = getNode().get(path); - env.clear(); - for (Entry entry : envVars.entrySet()) { - ModelNode var = new ModelNode(); - var.get(NAME).set(entry.getKey()); - var.get(VALUE).set(entry.getValue()); - env.add(var); - } - } - - @Override - public boolean incremental() { - return asBoolean(getNode(), getPropertyKeys(), INCREMENTAL); - } - - @Override - public void setIncremental(boolean isIncremental) { - set(getNode(), getPropertyKeys(), INCREMENTAL, isIncremental); - } - - +public class SourceBuildStrategy extends ModelNodeAdapter implements ISourceBuildStrategy, ResourcePropertyKeys { + + public static final String FROM_IMAGE = "sourceStrategy.from.name"; + public static final String FROM_KIND = "sourceStrategy.from.kind"; + public static final String FROM_NAMESPACE = "sourceStrategy.from.namespace"; + public static final String SCRIPTS = "sourceStrategy.scripts"; + public static final String INCREMENTAL = "sourceStrategy.incremental"; + public static final String ENV = "sourceStrategy.env"; + + public SourceBuildStrategy(ModelNode node, Map propertyKeys) { + super(node, propertyKeys); + set(node, propertyKeys, TYPE, BuildStrategyType.SOURCE); + } + + @Override + public String getType() { + return asString(getNode(), getPropertyKeys(), TYPE); + } + + @Override + public String getFromNamespace() { + return asString(getNode(), getPropertyKeys(), FROM_NAMESPACE); + } + + @Override + public void setFromNamespace(String namespace) { + set(getNode(), getPropertyKeys(), FROM_NAMESPACE, namespace); + } + + @Override + public String getFromKind() { + return asString(getNode(), getPropertyKeys(), FROM_KIND); + } + + @Override + public void setFromKind(String kind) { + set(getNode(), getPropertyKeys(), FROM_KIND, kind); + } + + @Override + public DockerImageURI getImage() { + return new DockerImageURI(asString(getNode(), getPropertyKeys(), FROM_IMAGE)); + } + + @Override + public void setImage(DockerImageURI image) { + set(getNode(), getPropertyKeys(), FROM_IMAGE, image.toString()); + } + + @Override + public String getScriptsLocation() { + return asString(getNode(), getPropertyKeys(), SCRIPTS); + } + + @Override + public void setScriptsLocation(String location) { + set(getNode(), getPropertyKeys(), SCRIPTS, location); + } + + @Override + public Collection getEnvVars() { + String[] path = JBossDmrExtentions.getPath(getPropertyKeys(), ENV); + ModelNode envNode = getNode().get(path); + if (envNode.isDefined()) { + return envNode.asList().stream().map(n -> new EnvironmentVariable(n, getPropertyKeys())) + .collect(Collectors.toList()); + } + return Collections.emptyList(); + } + + @Override + public void setEnvVars(Collection envVars) { + if (envVars == null) { + return; + } + String[] path = JBossDmrExtentions.getPath(getPropertyKeys(), ENV); + ModelNode envNode = getNode().get(path); + envNode.clear(); + envVars.forEach(v -> envNode.add(ModelNode.fromJSONString(v.toJson()))); + } + + @Override + public Map getEnvironmentVariables() { + String[] path = JBossDmrExtentions.getPath(getPropertyKeys(), ENV); + ModelNode env = getNode().get(path); + Map values = new HashMap<>(); + if (env.getType() == ModelType.LIST) { + for (ModelNode value : env.asList()) { + values.put(value.get(NAME).asString(), value.get(VALUE).asString()); + } + } + return values; + } + + @Override + public void setEnvironmentVariables(Map envVars) { + String[] path = JBossDmrExtentions.getPath(getPropertyKeys(), ENV); + ModelNode env = getNode().get(path); + env.clear(); + for (Entry entry : envVars.entrySet()) { + ModelNode var = new ModelNode(); + var.get(NAME).set(entry.getKey()); + var.get(VALUE).set(entry.getValue()); + env.add(var); + } + } + + @Override + public boolean incremental() { + return asBoolean(getNode(), getPropertyKeys(), INCREMENTAL); + } + + @Override + public void setIncremental(boolean isIncremental) { + set(getNode(), getPropertyKeys(), INCREMENTAL, isIncremental); + } + } diff --git a/src/main/java/com/openshift/internal/restclient/model/build/WebhookTrigger.java b/src/main/java/com/openshift/internal/restclient/model/build/WebhookTrigger.java index b7457157..cfe48a9f 100644 --- a/src/main/java/com/openshift/internal/restclient/model/build/WebhookTrigger.java +++ b/src/main/java/com/openshift/internal/restclient/model/build/WebhookTrigger.java @@ -6,75 +6,76 @@ * * Contributors: Red Hat, Inc. ******************************************************************************/ + package com.openshift.internal.restclient.model.build; import org.apache.commons.lang.StringUtils; + import com.openshift.restclient.model.build.IWebhookTrigger; -/** - * @author Jeff Cantrill - */ public class WebhookTrigger implements IWebhookTrigger { - private String type; - private String secret; - private String baseURL; + private String type; + private String secret; + private String baseURL; + + public WebhookTrigger(String triggerType, String secret, String baseURL) { + this.type = triggerType; + this.secret = secret; + this.baseURL = baseURL; + } + + @Override + public String getType() { + return type; + } - public WebhookTrigger(String triggerType, String secret, String baseURL) { - this.type = triggerType; - this.secret = secret; - this.baseURL = baseURL; - } + @Override + public String getSecret() { + return secret; + } - @Override - public String getType() { - return type; - } + @Override + public String getWebhookURL() { + if (StringUtils.isBlank(baseURL)) { + return ""; + } - @Override - public String getSecret() { - return secret; - } + return String.format("%s/webhooks/%s/%s", baseURL, secret, type.toLowerCase()); + } - @Override - public String getWebhookURL() { - if(StringUtils.isBlank(baseURL)){ - return ""; - } - - return String.format("%s/webhooks/%s/%s", - baseURL, - secret, - type.toLowerCase() - ); - } + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + ((secret == null) ? 0 : secret.hashCode()); + result = prime * result + ((type == null) ? 0 : type.hashCode()); + return result; + } - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = prime * result + ((secret == null) ? 0 : secret.hashCode()); - result = prime * result + ((type == null) ? 0 : type.hashCode()); - return result; - } + @Override + public boolean equals(Object obj) { + if (this == obj) { + return true; + } + if (obj == null) { + return false; + } + if (getClass() != obj.getClass()) { + return false; + } + WebhookTrigger other = (WebhookTrigger) obj; + if (secret == null) { + if (other.secret != null) { + return false; + } + } else if (!secret.equals(other.secret)) { + return false; + } + if (type != other.type) { + return false; + } + return true; + } - @Override - public boolean equals(Object obj) { - if (this == obj) - return true; - if (obj == null) - return false; - if (getClass() != obj.getClass()) - return false; - WebhookTrigger other = (WebhookTrigger) obj; - if (secret == null) { - if (other.secret != null) - return false; - } else if (!secret.equals(other.secret)) - return false; - if (type != other.type) - return false; - return true; - } - } diff --git a/src/main/java/com/openshift/internal/restclient/model/deploy/ConfigChangeTrigger.java b/src/main/java/com/openshift/internal/restclient/model/deploy/ConfigChangeTrigger.java index dfe21567..29f47a53 100644 --- a/src/main/java/com/openshift/internal/restclient/model/deploy/ConfigChangeTrigger.java +++ b/src/main/java/com/openshift/internal/restclient/model/deploy/ConfigChangeTrigger.java @@ -8,6 +8,7 @@ * Contributors: * Red Hat, Inc. - initial API and implementation ******************************************************************************/ + package com.openshift.internal.restclient.model.deploy; import java.util.Map; @@ -18,8 +19,8 @@ public class ConfigChangeTrigger extends DeploymentTrigger implements IDeploymentConfigChangeTrigger { - public ConfigChangeTrigger(ModelNode node, Map propertyKeys) { - super(node, propertyKeys); - } + public ConfigChangeTrigger(ModelNode node, Map propertyKeys) { + super(node, propertyKeys); + } } diff --git a/src/main/java/com/openshift/internal/restclient/model/deploy/DeploymentRequest.java b/src/main/java/com/openshift/internal/restclient/model/deploy/DeploymentRequest.java new file mode 100644 index 00000000..1fabcc70 --- /dev/null +++ b/src/main/java/com/openshift/internal/restclient/model/deploy/DeploymentRequest.java @@ -0,0 +1,69 @@ +/******************************************************************************* + * Copyright (c) 2016 Red Hat, Inc. + * Distributed under license by Red Hat, Inc. All rights reserved. + * This program is made available under the terms of the + * Eclipse Public License v1.0 which accompanies this distribution, + * and is available at http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Red Hat, Inc. - initial API and implementation + ******************************************************************************/ + +package com.openshift.internal.restclient.model.deploy; + +import static com.openshift.internal.util.JBossDmrExtentions.asBoolean; +import static com.openshift.internal.util.JBossDmrExtentions.asString; +import static com.openshift.internal.util.JBossDmrExtentions.set; + +import java.util.Map; + +import org.jboss.dmr.ModelNode; + +import com.openshift.internal.restclient.api.models.TypeMeta; +import com.openshift.restclient.model.deploy.IDeploymentRequest; + +/** + * + * @author Gabe Montero + * + */ +public class DeploymentRequest extends TypeMeta implements IDeploymentRequest { + + private static final String LATEST = "latest"; + private static final String FORCE = "force"; + + public DeploymentRequest(ModelNode node, Map overrideProperties) { + super(node, overrideProperties); + } + + @Override + public void setLatest(boolean latest) { + set(getNode(), getPropertyKeys(), LATEST, latest); + } + + @Override + public boolean isLatest() { + return asBoolean(getNode(), getPropertyKeys(), LATEST); + } + + @Override + public void setForce(boolean force) { + set(getNode(), getPropertyKeys(), FORCE, force); + } + + @Override + public boolean isForce() { + return asBoolean(getNode(), getPropertyKeys(), FORCE); + } + + @Override + public String getName() { + return asString(getNode(), getPropertyKeys(), NAME); + } + + @Override + public void setName(String name) { + set(getNode(), getPropertyKeys(), NAME, name); + } + +} diff --git a/src/main/java/com/openshift/internal/restclient/model/deploy/DeploymentTrigger.java b/src/main/java/com/openshift/internal/restclient/model/deploy/DeploymentTrigger.java index 8abe271b..b47abaac 100644 --- a/src/main/java/com/openshift/internal/restclient/model/deploy/DeploymentTrigger.java +++ b/src/main/java/com/openshift/internal/restclient/model/deploy/DeploymentTrigger.java @@ -8,9 +8,11 @@ * Contributors: * Red Hat, Inc. - initial API and implementation ******************************************************************************/ + package com.openshift.internal.restclient.model.deploy; -import static com.openshift.internal.util.JBossDmrExtentions.*; +import static com.openshift.internal.util.JBossDmrExtentions.asString; + import java.util.Map; import org.jboss.dmr.ModelNode; @@ -18,31 +20,26 @@ import com.openshift.internal.restclient.model.properties.ResourcePropertyKeys; import com.openshift.restclient.model.deploy.IDeploymentTrigger; -/** - * - * @author Jeff Cantrill - * - */ public class DeploymentTrigger implements IDeploymentTrigger, ResourcePropertyKeys { - - final private ModelNode node; - final private Map propertyKeys; - - public DeploymentTrigger(ModelNode node, Map propertyKeys) { - this.node = node; - this.propertyKeys = propertyKeys; - } - - @Override - public String getType() { - return asString(node, propertyKeys, TYPE); - } - - protected ModelNode getNode() { - return node; - } - - protected Map getPropertyKeys(){ - return this.propertyKeys; - } + + private final ModelNode node; + private final Map propertyKeys; + + public DeploymentTrigger(ModelNode node, Map propertyKeys) { + this.node = node; + this.propertyKeys = propertyKeys; + } + + @Override + public String getType() { + return asString(node, propertyKeys, TYPE); + } + + protected ModelNode getNode() { + return node; + } + + protected Map getPropertyKeys() { + return this.propertyKeys; + } } diff --git a/src/main/java/com/openshift/internal/restclient/model/deploy/ImageChangeTrigger.java b/src/main/java/com/openshift/internal/restclient/model/deploy/ImageChangeTrigger.java index 1fecf320..4f98db2d 100644 --- a/src/main/java/com/openshift/internal/restclient/model/deploy/ImageChangeTrigger.java +++ b/src/main/java/com/openshift/internal/restclient/model/deploy/ImageChangeTrigger.java @@ -8,9 +8,13 @@ * Contributors: * Red Hat, Inc. - initial API and implementation ******************************************************************************/ + package com.openshift.internal.restclient.model.deploy; -import static com.openshift.internal.util.JBossDmrExtentions.*; +import static com.openshift.internal.util.JBossDmrExtentions.asBoolean; +import static com.openshift.internal.util.JBossDmrExtentions.asString; +import static com.openshift.internal.util.JBossDmrExtentions.get; +import static com.openshift.internal.util.JBossDmrExtentions.set; import java.util.ArrayList; import java.util.Arrays; @@ -25,85 +29,84 @@ import com.openshift.restclient.model.deploy.IDeploymentImageChangeTrigger; public class ImageChangeTrigger extends DeploymentTrigger implements IDeploymentImageChangeTrigger { - - private static final String DEPLOYMENTCONFIG_TRIGGER_IMAGECHANGE_AUTO = "imageChangeParams.automatic"; - private static final String DEPLOYMENTCONFIG_TRIGGER_CONTAINERS = "imageChangeParams.containerNames"; - private static final String DEPLOYMENTCONFIG_TRIGGER_FROM = "imageChangeParams.from.name"; - private static final String DEPLOYMENTCONFIG_TRIGGER_FROM_KIND = "imageChangeParams.from.kind"; - private static final String FROM_NAMESPACE = "imageChangeParams.from.namespace"; - - public ImageChangeTrigger(ModelNode node, Map propertyKeys) { - super(node, propertyKeys); - } - - @Override - public DockerImageURI getFrom() { - return new DockerImageURI(asString(getNode(), getPropertyKeys(), DEPLOYMENTCONFIG_TRIGGER_FROM)); - } - - @Override - public void setFrom(DockerImageURI fromImage) { - if(StringUtils.isBlank(asString(getNode(), getPropertyKeys(), DEPLOYMENTCONFIG_TRIGGER_FROM_KIND))) { - setKind(ResourceKind.IMAGE_STREAM_TAG); - } - set(getNode(), getPropertyKeys(), DEPLOYMENTCONFIG_TRIGGER_FROM, fromImage.getAbsoluteUri()); - } - - @Override - public void setNamespace(String namespace) { - set(getNode(), getPropertyKeys(), FROM_NAMESPACE, namespace); - } - - @Override - public String getNamespace() { - return asString(getNode(), getPropertyKeys(), FROM_NAMESPACE); - } - - @Override - public void setKind(String kind) { - set(getNode(), getPropertyKeys(), DEPLOYMENTCONFIG_TRIGGER_FROM_KIND, kind); - } - - @Override - public String getKind() { - return asString(getNode(), getPropertyKeys(), DEPLOYMENTCONFIG_TRIGGER_FROM_KIND); - } - - @Override - public boolean isAutomatic() { - return asBoolean(getNode(), getPropertyKeys(), DEPLOYMENTCONFIG_TRIGGER_IMAGECHANGE_AUTO); - } - - @Override - public void setAutomatic(boolean auto) { - set(getNode(), getPropertyKeys(), DEPLOYMENTCONFIG_TRIGGER_IMAGECHANGE_AUTO, auto); - } - - @Override - public Collection getContainerNames() { - Collection containers = new ArrayList<>(); - ModelNode containerNode = get(getNode(), getPropertyKeys(),DEPLOYMENTCONFIG_TRIGGER_CONTAINERS); - if(containerNode.isDefined()) { - for (ModelNode node : containerNode.asList()) { - containers.add(node.asString()); - } - } - return containers ; - } - - @Override - public void setContainerNames(Collection names) { - ModelNode containerNode = get(getNode(), getPropertyKeys(),DEPLOYMENTCONFIG_TRIGGER_CONTAINERS); - containerNode.clear(); - for (String name : names) { - containerNode.add(name); - } - } - - @Override - public void setContainerName(String name) { - setContainerNames(Arrays.asList(name)); - } - - + + private static final String DEPLOYMENTCONFIG_TRIGGER_IMAGECHANGE_AUTO = "imageChangeParams.automatic"; + private static final String DEPLOYMENTCONFIG_TRIGGER_CONTAINERS = "imageChangeParams.containerNames"; + private static final String DEPLOYMENTCONFIG_TRIGGER_FROM = "imageChangeParams.from.name"; + private static final String DEPLOYMENTCONFIG_TRIGGER_FROM_KIND = "imageChangeParams.from.kind"; + private static final String FROM_NAMESPACE = "imageChangeParams.from.namespace"; + + public ImageChangeTrigger(ModelNode node, Map propertyKeys) { + super(node, propertyKeys); + } + + @Override + public DockerImageURI getFrom() { + return new DockerImageURI(asString(getNode(), getPropertyKeys(), DEPLOYMENTCONFIG_TRIGGER_FROM)); + } + + @Override + public void setFrom(DockerImageURI fromImage) { + if (StringUtils.isBlank(asString(getNode(), getPropertyKeys(), DEPLOYMENTCONFIG_TRIGGER_FROM_KIND))) { + setKind(ResourceKind.IMAGE_STREAM_TAG); + } + set(getNode(), getPropertyKeys(), DEPLOYMENTCONFIG_TRIGGER_FROM, fromImage.getAbsoluteUri()); + } + + @Override + public void setNamespace(String namespace) { + set(getNode(), getPropertyKeys(), FROM_NAMESPACE, namespace); + } + + @Override + public String getNamespace() { + return asString(getNode(), getPropertyKeys(), FROM_NAMESPACE); + } + + @Override + public void setKind(String kind) { + set(getNode(), getPropertyKeys(), DEPLOYMENTCONFIG_TRIGGER_FROM_KIND, kind); + } + + @Override + public String getKind() { + return asString(getNode(), getPropertyKeys(), DEPLOYMENTCONFIG_TRIGGER_FROM_KIND); + } + + @Override + public boolean isAutomatic() { + return asBoolean(getNode(), getPropertyKeys(), DEPLOYMENTCONFIG_TRIGGER_IMAGECHANGE_AUTO); + } + + @Override + public void setAutomatic(boolean auto) { + set(getNode(), getPropertyKeys(), DEPLOYMENTCONFIG_TRIGGER_IMAGECHANGE_AUTO, auto); + } + + @Override + public Collection getContainerNames() { + Collection containers = new ArrayList<>(); + ModelNode containerNode = get(getNode(), getPropertyKeys(), DEPLOYMENTCONFIG_TRIGGER_CONTAINERS); + if (containerNode.isDefined()) { + for (ModelNode node : containerNode.asList()) { + containers.add(node.asString()); + } + } + return containers; + } + + @Override + public void setContainerNames(Collection names) { + ModelNode containerNode = get(getNode(), getPropertyKeys(), DEPLOYMENTCONFIG_TRIGGER_CONTAINERS); + containerNode.clear(); + for (String name : names) { + containerNode.add(name); + } + } + + @Override + public void setContainerName(String name) { + setContainerNames(Arrays.asList(name)); + } + } diff --git a/src/main/java/com/openshift/internal/restclient/model/image/ImageStreamImport.java b/src/main/java/com/openshift/internal/restclient/model/image/ImageStreamImport.java index d5568969..38882fb0 100644 --- a/src/main/java/com/openshift/internal/restclient/model/image/ImageStreamImport.java +++ b/src/main/java/com/openshift/internal/restclient/model/image/ImageStreamImport.java @@ -8,6 +8,7 @@ * Contributors: * Red Hat, Inc. - initial API and implementation ******************************************************************************/ + package com.openshift.internal.restclient.model.image; import java.util.ArrayList; @@ -25,74 +26,64 @@ import com.openshift.restclient.model.IStatus; import com.openshift.restclient.model.image.IImageStreamImport; -/** - * - * @author jeff.cantrill - * - */ public class ImageStreamImport extends KubernetesResource implements IImageStreamImport { - private static final String FROM_KIND = "from.kind"; - public static final String IMAGE_DOCKER_IMAGE_REFERENCE = "image.dockerImageReference"; - private static final String SPEC_IMAGES = "spec.images"; - private static final String SPEC_IMPORT = "spec.import"; - private static final String STATUS = "status"; - public static final String STATUS_IMAGES = "status.images"; - private static final String TAG = "tag"; + private static final String FROM_KIND = "from.kind"; + public static final String IMAGE_DOCKER_IMAGE_REFERENCE = "image.dockerImageReference"; + private static final String SPEC_IMAGES = "spec.images"; + private static final String SPEC_IMPORT = "spec.import"; + private static final String STATUS = "status"; + public static final String STATUS_IMAGES = "status.images"; + private static final String TAG = "tag"; - public ImageStreamImport(ModelNode node, IClient client, Map overrideProperties) { - super(node, client, overrideProperties); - } + public ImageStreamImport(ModelNode node, IClient client, Map overrideProperties) { + super(node, client, overrideProperties); + } - @Override - public void setImport(boolean importTags) { - set(SPEC_IMPORT, importTags); - } + @Override + public void setImport(boolean importTags) { + set(SPEC_IMPORT, importTags); + } - @Override - public boolean isImport() { - return asBoolean(SPEC_IMPORT); - } + @Override + public boolean isImport() { + return asBoolean(SPEC_IMPORT); + } - @Override - public void addImage(String fromKind, DockerImageURI imageUri) { - ModelNode image = new ModelNode(); - set(image, FROM_KIND, fromKind); - set(image, "from.name", imageUri.getAbsoluteUri()); - get(SPEC_IMAGES).add(image); - } + @Override + public void addImage(String fromKind, DockerImageURI imageUri) { + ModelNode image = new ModelNode(); + set(image, FROM_KIND, fromKind); + set(image, "from.name", imageUri.getAbsoluteUri()); + get(SPEC_IMAGES).add(image); + } - @Override - public Collection getImageStatus() { - Collection status = new ArrayList<>(); - ModelNode images = get(STATUS_IMAGES); - if(images.isDefined()) { - images.asList() - .stream() - .filter(n->get(n,STATUS).isDefined()) - .forEach(n->status.add(new Status(get(n,STATUS), getClient(), getPropertyKeys()))); - } - return status; - } + @Override + public Collection getImageStatus() { + Collection status = new ArrayList<>(); + ModelNode images = get(STATUS_IMAGES); + if (images.isDefined()) { + images.asList().stream().filter(n -> get(n, STATUS).isDefined()) + .forEach(n -> status.add(new Status(get(n, STATUS), getClient(), getPropertyKeys()))); + } + return status; + } - @Override - public String getImageJsonFor(DockerImageURI uri) { - return getImageJsonFor(uri.getTag()); - } + @Override + public String getImageJsonFor(DockerImageURI uri) { + return getImageJsonFor(uri.getTag()); + } - @Override - public String getImageJsonFor(String tag) { - ModelNode images = get(STATUS_IMAGES); - if(images.isDefined() && StringUtils.isNotBlank(tag)) { - Optional node = images.asList() - .stream() - .filter(n->tag.equals(asString(n,TAG))) - .findFirst(); - if(node.isPresent()) { - return node.get().toJSONString(true); - } - } - return null; - } + @Override + public String getImageJsonFor(String tag) { + ModelNode images = get(STATUS_IMAGES); + if (images.isDefined() && StringUtils.isNotBlank(tag)) { + Optional node = images.asList().stream().filter(n -> tag.equals(asString(n, TAG))).findFirst(); + if (node.isPresent()) { + return node.get().toJSONString(true); + } + } + return null; + } } diff --git a/src/main/java/com/openshift/internal/restclient/model/image/TagReference.java b/src/main/java/com/openshift/internal/restclient/model/image/TagReference.java index cca64ae9..1c99db29 100644 --- a/src/main/java/com/openshift/internal/restclient/model/image/TagReference.java +++ b/src/main/java/com/openshift/internal/restclient/model/image/TagReference.java @@ -8,9 +8,13 @@ * Contributors: * Red Hat, Inc. - initial API and implementation ******************************************************************************/ + package com.openshift.internal.restclient.model.image; -import static com.openshift.internal.util.JBossDmrExtentions.*; +import static com.openshift.internal.util.JBossDmrExtentions.asMap; +import static com.openshift.internal.util.JBossDmrExtentions.asString; +import static com.openshift.internal.util.JBossDmrExtentions.get; +import static com.openshift.internal.util.JBossDmrExtentions.set; import java.util.HashMap; import java.util.Map; @@ -25,61 +29,63 @@ public class TagReference extends ModelNodeAdapter implements ITagReference, ResourcePropertyKeys { - private static final String TAG_ANNOTATIONS = "annotations"; - - public TagReference(String name, String fromKind, String fromName) { - super(new ModelNode(), new HashMap<>()); - setName(name); - ObjectReference from = (ObjectReference) getFrom(); - from.setKind(fromKind); - from.setName(fromName); - } - - public TagReference(String name, String fromKind, String fromName, String fromNamespace) { - this(name, fromKind, fromName); - ObjectReference from = (ObjectReference) getFrom(); - from.setNamespace(fromNamespace); - } - - public TagReference(ModelNode node, Map propertyKeys) { - super(node, propertyKeys); - } - - @Override - public boolean isAnnotatedWith(String key) { - return getAnnotations().containsKey(key); - } - - @Override - public String getAnnotation(String key) { - return getAnnotations().get(key); - } - - @Override - public void setAnnotation(String key, String value) { - if(value == null) return; - ModelNode annotations = get(getNode(), getPropertyKeys(), TAG_ANNOTATIONS); - annotations.get(key).set(value); - } - - @Override - public Map getAnnotations() { - return asMap(getNode(), getPropertyKeys(), TAG_ANNOTATIONS); - } - - @Override - public String getName() { - return asString(getNode(),getPropertyKeys(), NAME); - } - - public void setName(String name) { - set(getNode(),getPropertyKeys(), NAME, name); - } - - @Override - public IObjectReference getFrom() { - ModelNode from = get(getNode(), getPropertyKeys(), FROM); - return new ObjectReference(from); - } - + private static final String TAG_ANNOTATIONS = "annotations"; + + public TagReference(String name, String fromKind, String fromName) { + super(new ModelNode(), new HashMap<>()); + setName(name); + ObjectReference from = (ObjectReference) getFrom(); + from.setKind(fromKind); + from.setName(fromName); + } + + public TagReference(String name, String fromKind, String fromName, String fromNamespace) { + this(name, fromKind, fromName); + ObjectReference from = (ObjectReference) getFrom(); + from.setNamespace(fromNamespace); + } + + public TagReference(ModelNode node, Map propertyKeys) { + super(node, propertyKeys); + } + + @Override + public boolean isAnnotatedWith(String key) { + return getAnnotations().containsKey(key); + } + + @Override + public String getAnnotation(String key) { + return getAnnotations().get(key); + } + + @Override + public void setAnnotation(String key, String value) { + if (value == null) { + return; + } + ModelNode annotations = get(getNode(), getPropertyKeys(), TAG_ANNOTATIONS); + annotations.get(key).set(value); + } + + @Override + public Map getAnnotations() { + return asMap(getNode(), getPropertyKeys(), TAG_ANNOTATIONS); + } + + @Override + public String getName() { + return asString(getNode(), getPropertyKeys(), NAME); + } + + public void setName(String name) { + set(getNode(), getPropertyKeys(), NAME, name); + } + + @Override + public IObjectReference getFrom() { + ModelNode from = get(getNode(), getPropertyKeys(), FROM); + return new ObjectReference(from); + } + } diff --git a/src/main/java/com/openshift/internal/restclient/model/kubeclient/Cluster.java b/src/main/java/com/openshift/internal/restclient/model/kubeclient/Cluster.java index 99d1ac4d..4fbe6f44 100644 --- a/src/main/java/com/openshift/internal/restclient/model/kubeclient/Cluster.java +++ b/src/main/java/com/openshift/internal/restclient/model/kubeclient/Cluster.java @@ -8,44 +8,46 @@ * Contributors: * Red Hat, Inc. - initial API and implementation ******************************************************************************/ + package com.openshift.internal.restclient.model.kubeclient; import java.util.HashMap; import java.util.Map; + import com.openshift.restclient.model.kubeclient.ICluster; public class Cluster implements ICluster { - private static final String SERVER = "server"; - private static final String INSECURE_SKIP_TLS_VERIFY = "insecure-skip-tls-verify"; - private String name; - private Map cluster = new HashMap<>(); - - public void setCluster(Map cluster) { - this.cluster.clear(); - this.cluster.putAll(cluster); - } - - @Override - public String getName() { - return this.name; - } - - public void setName(String name) { - this.name = name; - } - - @Override - public String getServer() { - return (String) cluster.get(SERVER); - } - - @Override - public boolean isInsecureSkipTLSVerify() { - if(cluster.containsKey(INSECURE_SKIP_TLS_VERIFY)) { - return (Boolean) cluster.get(INSECURE_SKIP_TLS_VERIFY); - } - return false; - } + private static final String SERVER = "server"; + private static final String INSECURE_SKIP_TLS_VERIFY = "insecure-skip-tls-verify"; + private String name; + private Map cluster = new HashMap<>(); + + public void setCluster(Map cluster) { + this.cluster.clear(); + this.cluster.putAll(cluster); + } + + @Override + public String getName() { + return this.name; + } + + public void setName(String name) { + this.name = name; + } + + @Override + public String getServer() { + return (String) cluster.get(SERVER); + } + + @Override + public boolean isInsecureSkipTLSVerify() { + if (cluster.containsKey(INSECURE_SKIP_TLS_VERIFY)) { + return (Boolean) cluster.get(INSECURE_SKIP_TLS_VERIFY); + } + return false; + } } diff --git a/src/main/java/com/openshift/internal/restclient/model/kubeclient/Context.java b/src/main/java/com/openshift/internal/restclient/model/kubeclient/Context.java index 049df17e..9ee34b18 100644 --- a/src/main/java/com/openshift/internal/restclient/model/kubeclient/Context.java +++ b/src/main/java/com/openshift/internal/restclient/model/kubeclient/Context.java @@ -8,6 +8,7 @@ * Contributors: * Red Hat, Inc. - initial API and implementation ******************************************************************************/ + package com.openshift.internal.restclient.model.kubeclient; import java.util.HashMap; @@ -18,41 +19,42 @@ /** * KubeConfig context - * @author jeff.cantrill * */ -public class Context implements IContext, ResourcePropertyKeys{ - - private static final String USER = "user"; - private static final String CLUSTER = "cluster"; - private Map context = new HashMap<>(); - private String name; - - public void setContext(Map context) { - this.context.clear(); - this.context.putAll(context); - } - @Override - public String getCluster() { - return context.get(CLUSTER); - } - - @Override - public String getUser() { - return context.get(USER); - } - - @Override - public String getNamespace() { - return context.get(NAMESPACE); - } - @Override - public String getName() { - return this.name; - } - - public void setName(String name) { - this.name = name; - } - +public class Context implements IContext, ResourcePropertyKeys { + + private static final String USER = "user"; + private static final String CLUSTER = "cluster"; + private Map context = new HashMap<>(); + private String name; + + public void setContext(Map context) { + this.context.clear(); + this.context.putAll(context); + } + + @Override + public String getCluster() { + return context.get(CLUSTER); + } + + @Override + public String getUser() { + return context.get(USER); + } + + @Override + public String getNamespace() { + return context.get(NAMESPACE); + } + + @Override + public String getName() { + return this.name; + } + + public void setName(String name) { + this.name = name; + } + } diff --git a/src/main/java/com/openshift/internal/restclient/model/kubeclient/KubeClientConfig.java b/src/main/java/com/openshift/internal/restclient/model/kubeclient/KubeClientConfig.java index 308e19b5..b0dad58f 100644 --- a/src/main/java/com/openshift/internal/restclient/model/kubeclient/KubeClientConfig.java +++ b/src/main/java/com/openshift/internal/restclient/model/kubeclient/KubeClientConfig.java @@ -8,6 +8,7 @@ * Contributors: * Red Hat, Inc. - initial API and implementation ******************************************************************************/ + package com.openshift.internal.restclient.model.kubeclient; import java.util.ArrayList; @@ -21,52 +22,54 @@ /** * Kube Client config impl * - * @author jeff.cantrill * */ public class KubeClientConfig implements IKubeClientConfig { - private Collection clusters = new ArrayList<>(); - private Collection contexts = new ArrayList<>(); - private String currentContext = ""; - private Collection users = new ArrayList<>(); - - public void setApiVersion(String apiVersion) { - - } - - @Override - public Collection< ICluster> getClusters() { - return clusters; - } - - public void setClusters(Collection clusters) { - this.clusters = clusters; - } - - @Override - public Collection getContexts() { - return contexts; - } - public void setContexts(Collection contexts) { - this.contexts = contexts; - } - - @Override - public String getCurrentContext() { - // TODO Auto-generated method stub - return currentContext; - } - public void setCurrentContext(String currentContext) { - this.currentContext = currentContext; - } - @Override - public Collection getUsers() { - return users; - } - - public void setUsers(Collection users) { - this.users = users; - } + private Collection clusters = new ArrayList<>(); + private Collection contexts = new ArrayList<>(); + private String currentContext = ""; + private Collection users = new ArrayList<>(); + + public void setApiVersion(String apiVersion) { + + } + + @Override + public Collection getClusters() { + return clusters; + } + + public void setClusters(Collection clusters) { + this.clusters = clusters; + } + + @Override + public Collection getContexts() { + return contexts; + } + + public void setContexts(Collection contexts) { + this.contexts = contexts; + } + + @Override + public String getCurrentContext() { + // TODO Auto-generated method stub + return currentContext; + } + + public void setCurrentContext(String currentContext) { + this.currentContext = currentContext; + } + + @Override + public Collection getUsers() { + return users; + } + + public void setUsers(Collection users) { + this.users = users; + } } diff --git a/src/main/java/com/openshift/internal/restclient/model/kubeclient/KubeClientConfigConstructor.java b/src/main/java/com/openshift/internal/restclient/model/kubeclient/KubeClientConfigConstructor.java index 36a050fd..c02d7b89 100644 --- a/src/main/java/com/openshift/internal/restclient/model/kubeclient/KubeClientConfigConstructor.java +++ b/src/main/java/com/openshift/internal/restclient/model/kubeclient/KubeClientConfigConstructor.java @@ -8,6 +8,7 @@ * Contributors: * Red Hat, Inc. - initial API and implementation ******************************************************************************/ + package com.openshift.internal.restclient.model.kubeclient; import org.yaml.snakeyaml.TypeDescription; @@ -15,21 +16,21 @@ import org.yaml.snakeyaml.introspector.PropertyUtils; public class KubeClientConfigConstructor extends Constructor { - - private static final String USERS = "users"; - private static final String CLUSTERS = "clusters"; - private static final String CONTEXTS = "contexts"; - - public KubeClientConfigConstructor(PropertyUtils propertyUtils) { - super(KubeClientConfig.class); - - TypeDescription configTypeDesc = new TypeDescription(KubeClientConfig.class); - configTypeDesc.putListPropertyType(CONTEXTS, Context.class); - configTypeDesc.putListPropertyType(CLUSTERS, Cluster.class); - configTypeDesc.putListPropertyType(USERS, User.class); - addTypeDescription(configTypeDesc); - - setPropertyUtils(propertyUtils); - } + + private static final String USERS = "users"; + private static final String CLUSTERS = "clusters"; + private static final String CONTEXTS = "contexts"; + + public KubeClientConfigConstructor(PropertyUtils propertyUtils) { + super(KubeClientConfig.class); + + TypeDescription configTypeDesc = new TypeDescription(KubeClientConfig.class); + configTypeDesc.addPropertyParameters(CONTEXTS, Context.class); + configTypeDesc.addPropertyParameters(CLUSTERS, Cluster.class); + configTypeDesc.addPropertyParameters(USERS, User.class); + addTypeDescription(configTypeDesc); + + setPropertyUtils(propertyUtils); + } } diff --git a/src/main/java/com/openshift/internal/restclient/model/kubeclient/User.java b/src/main/java/com/openshift/internal/restclient/model/kubeclient/User.java index f2fcc20d..0fbf8925 100644 --- a/src/main/java/com/openshift/internal/restclient/model/kubeclient/User.java +++ b/src/main/java/com/openshift/internal/restclient/model/kubeclient/User.java @@ -8,6 +8,7 @@ * Contributors: * Red Hat, Inc. - initial API and implementation ******************************************************************************/ + package com.openshift.internal.restclient.model.kubeclient; import java.util.Map; @@ -16,25 +17,25 @@ public class User implements IUser { - private String name; - private Map user; - - public void setUser(Map user) { - this.user = user; - } - @Override - public String getToken() { - return user.get("token"); - } - - @Override - public String getName() { - return this.name; - } - - public void setName(String name) { - this.name = name; - } - - + private String name; + private Map user; + + public void setUser(Map user) { + this.user = user; + } + + @Override + public String getToken() { + return user.get("token"); + } + + @Override + public String getName() { + return this.name; + } + + public void setName(String name) { + this.name = name; + } + } diff --git a/src/main/java/com/openshift/internal/restclient/model/oauth/OAuthAccessToken.java b/src/main/java/com/openshift/internal/restclient/model/oauth/OAuthAccessToken.java index e409f472..cda92d9f 100644 --- a/src/main/java/com/openshift/internal/restclient/model/oauth/OAuthAccessToken.java +++ b/src/main/java/com/openshift/internal/restclient/model/oauth/OAuthAccessToken.java @@ -8,6 +8,7 @@ * Contributors: * Red Hat, Inc. - initial API and implementation ******************************************************************************/ + package com.openshift.internal.restclient.model.oauth; import java.util.Map; @@ -18,16 +19,10 @@ import com.openshift.restclient.IClient; import com.openshift.restclient.model.oauth.IOAuthAccessToken; -/** - * - * @author Jeff Cantrill - * - */ public class OAuthAccessToken extends KubernetesResource implements IOAuthAccessToken { - public OAuthAccessToken(ModelNode node, IClient client, Map propertyKeys) { - super(node, client, propertyKeys); - // TODO Auto-generated constructor stub - } + public OAuthAccessToken(ModelNode node, IClient client, Map propertyKeys) { + super(node, client, propertyKeys); + } } diff --git a/src/main/java/com/openshift/internal/restclient/model/oauth/OAuthAuthorizeToken.java b/src/main/java/com/openshift/internal/restclient/model/oauth/OAuthAuthorizeToken.java index c5331e29..53a6840e 100644 --- a/src/main/java/com/openshift/internal/restclient/model/oauth/OAuthAuthorizeToken.java +++ b/src/main/java/com/openshift/internal/restclient/model/oauth/OAuthAuthorizeToken.java @@ -8,6 +8,7 @@ * Contributors: * Red Hat, Inc. - initial API and implementation ******************************************************************************/ + package com.openshift.internal.restclient.model.oauth; import java.util.Map; @@ -18,16 +19,10 @@ import com.openshift.restclient.IClient; import com.openshift.restclient.model.oauth.IOAuthAuthorizeToken; -/** - * - * @author Jeff Cantrill - * - */ public class OAuthAuthorizeToken extends KubernetesResource implements IOAuthAuthorizeToken { - public OAuthAuthorizeToken(ModelNode node, IClient client, Map propertyKeys) { - super(node, client, propertyKeys); - // TODO Auto-generated constructor stub - } + public OAuthAuthorizeToken(ModelNode node, IClient client, Map propertyKeys) { + super(node, client, propertyKeys); + } } diff --git a/src/main/java/com/openshift/internal/restclient/model/oauth/OAuthClient.java b/src/main/java/com/openshift/internal/restclient/model/oauth/OAuthClient.java index a0c96f41..9954348c 100644 --- a/src/main/java/com/openshift/internal/restclient/model/oauth/OAuthClient.java +++ b/src/main/java/com/openshift/internal/restclient/model/oauth/OAuthClient.java @@ -8,6 +8,7 @@ * Contributors: * Red Hat, Inc. - initial API and implementation ******************************************************************************/ + package com.openshift.internal.restclient.model.oauth; import java.util.Map; @@ -18,16 +19,10 @@ import com.openshift.restclient.IClient; import com.openshift.restclient.model.oauth.IOAuthClient; -/** - * - * @author Jeff Cantrill - * - */ public class OAuthClient extends KubernetesResource implements IOAuthClient { - public OAuthClient(ModelNode node, IClient client, Map propertyKeys) { - super(node, client, propertyKeys); - // TODO Auto-generated constructor stub - } + public OAuthClient(ModelNode node, IClient client, Map propertyKeys) { + super(node, client, propertyKeys); + } } diff --git a/src/main/java/com/openshift/internal/restclient/model/oauth/OAuthClientAuthorization.java b/src/main/java/com/openshift/internal/restclient/model/oauth/OAuthClientAuthorization.java index 20f2fd73..9a5c3460 100644 --- a/src/main/java/com/openshift/internal/restclient/model/oauth/OAuthClientAuthorization.java +++ b/src/main/java/com/openshift/internal/restclient/model/oauth/OAuthClientAuthorization.java @@ -8,6 +8,7 @@ * Contributors: * Red Hat, Inc. - initial API and implementation ******************************************************************************/ + package com.openshift.internal.restclient.model.oauth; import java.util.Map; @@ -20,9 +21,8 @@ public class OAuthClientAuthorization extends KubernetesResource implements IOAuthClientAuthorization { - public OAuthClientAuthorization(ModelNode node, IClient client, Map propertyKeys) { - super(node, client, propertyKeys); - // TODO Auto-generated constructor stub - } + public OAuthClientAuthorization(ModelNode node, IClient client, Map propertyKeys) { + super(node, client, propertyKeys); + } } diff --git a/src/main/java/com/openshift/internal/restclient/model/probe/Probe.java b/src/main/java/com/openshift/internal/restclient/model/probe/Probe.java new file mode 100644 index 00000000..eab2519f --- /dev/null +++ b/src/main/java/com/openshift/internal/restclient/model/probe/Probe.java @@ -0,0 +1,88 @@ +/******************************************************************************* + * Copyright (c) 2017 Red Hat, Inc. + * Distributed under license by Red Hat, Inc. All rights reserved. + * This program is made available under the terms of the + * Eclipse Public License v1.0 which accompanies this distribution, + * and is available at http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Red Hat, Inc. - initial API and implementation + ******************************************************************************/ + +package com.openshift.internal.restclient.model.probe; + +import static com.openshift.internal.util.JBossDmrExtentions.asInt; +import static com.openshift.internal.util.JBossDmrExtentions.set; + +import java.util.HashMap; + +import org.jboss.dmr.ModelNode; + +import com.openshift.internal.restclient.model.ModelNodeAdapter; +import com.openshift.restclient.model.probe.IProbe; + +/** + * @author Andre Dietisheim + */ +public class Probe extends ModelNodeAdapter implements IProbe { + + private static final String INITIAL_DELAY_SECONDS = "initialDelaySeconds"; + private static final String TIMEOUT_SECONDS = "timeoutSeconds"; + private static final String PERIOD_SECONDS = "periodSeconds"; + private static final String SUCCESS_THRESHOLD = "successThreshold"; + private static final String FAILURE_THRESHOLD = "failureThreshold"; + + public Probe(ModelNode node) { + super(node, new HashMap()); + } + + @Override + public void setInitialDelaySeconds(int delay) { + set(getNode(), getPropertyKeys(), INITIAL_DELAY_SECONDS, delay); + } + + @Override + public int getInitialDelaySeconds() { + return asInt(getNode(), getPropertyKeys(), INITIAL_DELAY_SECONDS); + } + + @Override + public void setPeriodSeconds(int period) { + set(getNode(), getPropertyKeys(), PERIOD_SECONDS, period); + } + + @Override + public int getPeriodSeconds() { + return asInt(getNode(), getPropertyKeys(), PERIOD_SECONDS); + } + + @Override + public void setSuccessThreshold(int threshold) { + set(getNode(), getPropertyKeys(), SUCCESS_THRESHOLD, threshold); + } + + @Override + public int getSuccessThreshold() { + return asInt(getNode(), getPropertyKeys(), SUCCESS_THRESHOLD); + } + + @Override + public void setFailureThreshold(int failureThreshold) { + set(getNode(), getPropertyKeys(), FAILURE_THRESHOLD, failureThreshold); + } + + @Override + public int getFailureThreshold() { + return asInt(getNode(), getPropertyKeys(), FAILURE_THRESHOLD); + } + + @Override + public void setTimeoutSeconds(int timeout) { + set(getNode(), getPropertyKeys(), TIMEOUT_SECONDS, timeout); + } + + @Override + public int getTimeoutSeconds() { + return asInt(getNode(), getPropertyKeys(), TIMEOUT_SECONDS); + } +} diff --git a/src/main/java/com/openshift/internal/restclient/model/project/OpenshiftProjectRequest.java b/src/main/java/com/openshift/internal/restclient/model/project/OpenshiftProjectRequest.java index bb09814e..cb1a3caf 100644 --- a/src/main/java/com/openshift/internal/restclient/model/project/OpenshiftProjectRequest.java +++ b/src/main/java/com/openshift/internal/restclient/model/project/OpenshiftProjectRequest.java @@ -8,6 +8,7 @@ * Contributors: * Red Hat, Inc. - initial API and implementation ******************************************************************************/ + package com.openshift.internal.restclient.model.project; import java.util.Map; @@ -20,31 +21,31 @@ public class OpenshiftProjectRequest extends KubernetesResource implements IProjectRequest { - private static final String DISPLAYNAME = "displayName"; - private static final String DESCRIPTION = "description"; + private static final String DISPLAYNAME = "displayName"; + private static final String DESCRIPTION = "description"; - public OpenshiftProjectRequest(ModelNode node, IClient client, Map propertyKeys) { - super(node, client, propertyKeys); - } + public OpenshiftProjectRequest(ModelNode node, IClient client, Map propertyKeys) { + super(node, client, propertyKeys); + } - @Override - public void setDisplayName(String name) { - set(DISPLAYNAME, name); - } + @Override + public void setDisplayName(String name) { + set(DISPLAYNAME, name); + } - @Override - public String getDisplayName() { - return asString(DISPLAYNAME); - } + @Override + public String getDisplayName() { + return asString(DISPLAYNAME); + } - @Override - public void setDescription(String description) { - set(DESCRIPTION, description); - } + @Override + public void setDescription(String description) { + set(DESCRIPTION, description); + } - @Override - public String getDescription() { - return asString(DESCRIPTION); - } + @Override + public String getDescription() { + return asString(DESCRIPTION); + } } diff --git a/src/main/java/com/openshift/internal/restclient/model/properties/ResourcePropertiesRegistry.java b/src/main/java/com/openshift/internal/restclient/model/properties/ResourcePropertiesRegistry.java index 735a558a..6c88f2a4 100644 --- a/src/main/java/com/openshift/internal/restclient/model/properties/ResourcePropertiesRegistry.java +++ b/src/main/java/com/openshift/internal/restclient/model/properties/ResourcePropertiesRegistry.java @@ -6,6 +6,7 @@ * * Contributors: Red Hat, Inc. ******************************************************************************/ + package com.openshift.internal.restclient.model.properties; import java.util.Arrays; @@ -21,126 +22,129 @@ /** * Registry of paths that override a default - * - * @author Jeff Cantrill */ public class ResourcePropertiesRegistry implements ResourcePropertyKeys { - private static ResourcePropertiesRegistry instance; - - private final Map> versionPropertyMap = new HashMap>(); - - private ResourcePropertiesRegistry(){ - } - - public static final ResourcePropertiesRegistry getInstance(){ - if(instance == null){ - instance = new ResourcePropertiesRegistry(); - } - return instance; - } - - /** - * Retrieve a given resource property map for a given version - * @param apiVersion - * @param kind - * - * @return The set of paths for the properties of the resource - */ - public Map get(final String apiVersion, final String kind) { - final VersionKey key = new VersionKey(apiVersion, kind); - if(!versionPropertyMap.containsKey(key)){ - return new HashMap(); - } - return versionPropertyMap.get(key); - } - - public KubernetesAPIVersion [] getSupportedKubernetesVersions(){ - return new KubernetesAPIVersion[] {KubernetesAPIVersion.v1}; - } - - public OpenShiftAPIVersion[] getSupportedOpenShiftVersions(){ - return new OpenShiftAPIVersion[] {OpenShiftAPIVersion.v1}; - } - - /** - * The maximum Kubernetes API supported by this client - * @return - * @throws IncompatibleApiVersionsException if the client can not support the server - */ - public KubernetesAPIVersion getMaxSupportedKubernetesVersion(List serverVersions) { - return getMaxSupportedVersion(Arrays.asList(getSupportedKubernetesVersions()), serverVersions); - } - - /** - * The maximum OpenShift API supported by this client - * @return - * @throws IncompatibleApiVersionsException if the client can not support the server - */ - public OpenShiftAPIVersion getMaxSupportedOpenShiftVersion(List serverVersions){ - return getMaxSupportedVersion(Arrays.asList(getSupportedOpenShiftVersions()), serverVersions); - } - - private T getMaxSupportedVersion(List clientVersions, List serverVersions) { - Collections.sort(clientVersions, new APIModelVersion.VersionComparitor()); - Collections.sort(serverVersions, new APIModelVersion.VersionComparitor()); - T maxClientVersion = clientVersions.get(clientVersions.size() - 1); - T maxServerVersion = serverVersions.get(serverVersions.size() - 1); - if(serverVersions.contains(maxClientVersion)) { - return maxClientVersion; - } - if(clientVersions.contains(maxServerVersion)) { - return maxServerVersion; - } - throw new IncompatibleApiVersionsException(clientVersions.toString(), serverVersions.toString()); - } - - private static class VersionKey { - private String version; - private String kind; - - VersionKey(APIModelVersion version, String kind){ - this(version.toString(), kind); - } - - VersionKey(String version, String kind){ - this.version = version.toString(); - this.kind = kind; - } - - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = prime * result - + ((kind == null) ? 0 : kind.hashCode()); - result = prime * result - + ((version == null) ? 0 : version.hashCode()); - return result; - } - - @Override - public boolean equals(Object obj) { - if (this == obj) - return true; - if (obj == null) - return false; - if (getClass() != obj.getClass()) - return false; - VersionKey other = (VersionKey) obj; - if (kind == null) { - if (other.kind != null) - return false; - } else if (!kind.equals(other.kind)) - return false; - if (version == null) { - if (other.version != null) - return false; - } else if (!version.equals(other.version)) - return false; - return true; - } - - } + private static ResourcePropertiesRegistry instance; + + private final Map> versionPropertyMap = new HashMap>(); + + private ResourcePropertiesRegistry() { + } + + public static final ResourcePropertiesRegistry getInstance() { + if (instance == null) { + instance = new ResourcePropertiesRegistry(); + } + return instance; + } + + /** + * Retrieve a given resource property map for a given version + * + * @return The set of paths for the properties of the resource + */ + public Map get(final String apiVersion, final String kind) { + final VersionKey key = new VersionKey(apiVersion, kind); + if (!versionPropertyMap.containsKey(key)) { + return new HashMap(); + } + return versionPropertyMap.get(key); + } + + public KubernetesAPIVersion[] getSupportedKubernetesVersions() { + return new KubernetesAPIVersion[] { KubernetesAPIVersion.v1 }; + } + + public OpenShiftAPIVersion[] getSupportedOpenShiftVersions() { + return new OpenShiftAPIVersion[] { OpenShiftAPIVersion.v1 }; + } + + /** + * The maximum Kubernetes API supported by this client + * + * @throws IncompatibleApiVersionsException + * if the client can not support the server + */ + public KubernetesAPIVersion getMaxSupportedKubernetesVersion(List serverVersions) { + return getMaxSupportedVersion(Arrays.asList(getSupportedKubernetesVersions()), serverVersions); + } + + /** + * The maximum OpenShift API supported by this client + * + * @throws IncompatibleApiVersionsException + * if the client can not support the server + */ + public OpenShiftAPIVersion getMaxSupportedOpenShiftVersion(List serverVersions) { + return getMaxSupportedVersion(Arrays.asList(getSupportedOpenShiftVersions()), serverVersions); + } + + private T getMaxSupportedVersion(List clientVersions, List serverVersions) { + Collections.sort(clientVersions, new APIModelVersion.VersionComparitor()); + Collections.sort(serverVersions, new APIModelVersion.VersionComparitor()); + T maxClientVersion = clientVersions.get(clientVersions.size() - 1); + T maxServerVersion = serverVersions.get(serverVersions.size() - 1); + if (serverVersions.contains(maxClientVersion)) { + return maxClientVersion; + } + if (clientVersions.contains(maxServerVersion)) { + return maxServerVersion; + } + throw new IncompatibleApiVersionsException(clientVersions.toString(), serverVersions.toString()); + } + + private static class VersionKey { + private String version; + private String kind; + + VersionKey(APIModelVersion version, String kind) { + this(version.toString(), kind); + } + + VersionKey(String version, String kind) { + this.version = version.toString(); + this.kind = kind; + } + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + ((kind == null) ? 0 : kind.hashCode()); + result = prime * result + ((version == null) ? 0 : version.hashCode()); + return result; + } + + @Override + public boolean equals(Object obj) { + if (this == obj) { + return true; + } + if (obj == null) { + return false; + } + if (getClass() != obj.getClass()) { + return false; + } + VersionKey other = (VersionKey) obj; + if (kind == null) { + if (other.kind != null) { + return false; + } + } else if (!kind.equals(other.kind)) { + return false; + } + if (version == null) { + if (other.version != null) { + return false; + } + } else if (!version.equals(other.version)) { + return false; + } + return true; + } + + } } diff --git a/src/main/java/com/openshift/internal/restclient/model/properties/ResourcePropertyKeys.java b/src/main/java/com/openshift/internal/restclient/model/properties/ResourcePropertyKeys.java index 21f2beb5..483b281e 100644 --- a/src/main/java/com/openshift/internal/restclient/model/properties/ResourcePropertyKeys.java +++ b/src/main/java/com/openshift/internal/restclient/model/properties/ResourcePropertyKeys.java @@ -1,38 +1,41 @@ /******************************************************************************* - * Copyright (c) 2015 Red Hat, Inc. Distributed under license by Red Hat, Inc. + * Copyright (c) 2015-2019 Red Hat, Inc. Distributed under license by Red Hat, Inc. * All rights reserved. This program is made available under the terms of the * Eclipse Public License v1.0 which accompanies this distribution, and is * available at http://www.eclipse.org/legal/epl-v10.html * * Contributors: Red Hat, Inc. ******************************************************************************/ + package com.openshift.internal.restclient.model.properties; /** * Keys used to determine where a given property is for a given resource - * - * @author Jeff Cantrill */ public interface ResourcePropertyKeys { - - static final String APIVERSION = "apiVersion"; - static final String KIND = "kind"; - static final String ANNOTATIONS = "metadata.annotations"; - static final String CREATION_TIMESTAMP = "metadata.creationTimestamp"; - static final String LABELS = "metadata.labels"; - static final String METADATA = "metadata"; - static final String METADATA_NAME = "metadata.name"; - static final String METADATA_RESOURCE_VERSION = "metadata.resourceVersion"; - static final String METADATA_NAMESPACE = "metadata.namespace"; + static final String APIVERSION = "apiVersion"; + static final String KIND = "kind"; + static final String GROUP = "group"; + static final String VERSION = "version"; + + static final String ANNOTATIONS = "metadata.annotations"; + static final String CREATION_TIMESTAMP = "metadata.creationTimestamp"; + static final String LABELS = "metadata.labels"; + static final String METADATA = "metadata"; + static final String METADATA_NAME = "metadata.name"; + static final String METADATA_RESOURCE_VERSION = "metadata.resourceVersion"; + static final String METADATA_NAMESPACE = "metadata.namespace"; + static final String METADATA_UID = "metadata.uid"; - static final String FROM = "from"; - static final String NAME = "name"; - static final String NAMESPACE = "namespace"; - static final String OBJECTS = "objects"; - static final String PORTS = "ports"; - static final String PROTOCOL = "protocol"; - static final String RESOURCE_VERSION = "resourceVersion"; - static final String VALUE = "value"; - static final String TYPE = "type"; + static final String FROM = "from"; + static final String NAME = "name"; + static final String NAMESPACE = "namespace"; + static final String OBJECTS = "objects"; + static final String PORTS = "ports"; + static final String PROTOCOL = "protocol"; + static final String RESOURCE_VERSION = "resourceVersion"; + static final String VALUE = "value"; + static final String TYPE = "type"; + static final String VERBS = "verbs"; } diff --git a/src/main/java/com/openshift/internal/restclient/model/template/Parameter.java b/src/main/java/com/openshift/internal/restclient/model/template/Parameter.java index cbac2ae1..54e9db38 100644 --- a/src/main/java/com/openshift/internal/restclient/model/template/Parameter.java +++ b/src/main/java/com/openshift/internal/restclient/model/template/Parameter.java @@ -6,6 +6,7 @@ * * Contributors: Red Hat, Inc. ******************************************************************************/ + package com.openshift.internal.restclient.model.template; import org.apache.commons.lang.StringUtils; @@ -14,130 +15,126 @@ import com.openshift.restclient.model.template.IParameter; /** - * Parameter implementation for a template - * Foregoing versioned implementation of this type for now since it is unlikely to change - * and it is not a versioned resource in Kubernetes. Update as needed - * - * @author Jeff Cantrill + * Parameter implementation for a template Foregoing versioned implementation of + * this type for now since it is unlikely to change and it is not a versioned + * resource in Kubernetes. Update as needed */ -public class Parameter implements IParameter{ - - private static final String VALUE = "value"; - - private ModelNode node; - - public Parameter(ModelNode node){ - this.node = node; - } - - - @Override - public IParameter clone() { - return new Parameter(node.clone()); - } - - @Override - public String getName() { - return asString("name"); - } - - @Override - public String getDescription() { - return asString("description"); - } - - @Override - public void setValue(String value) { - node.get(VALUE).set(value); - } - - @Override - public String getValue() { - return asString(VALUE); - } - - @Override - public String getGeneratorName() { - return StringUtils.defaultIfEmpty(asString("generate"),asString("generator")); - } - - @Override - public String getFrom() { - return asString("from"); - } - - @Override - public boolean isRequired() { - if(node.hasDefined("required")) { - return node.get("required").asBoolean(); - } - return false; - } - - private String asString(String key) { - ModelNode value = node.get(key); - if(value.isDefined()) - return value.asString(); - return ""; - } - - - - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = prime * result + - ((getFrom() == null) ? 0 : getFrom().hashCode()) - + ((getGeneratorName() == null) ? 0 : getGeneratorName().hashCode()) - + ((getName() == null) ? 0 : getName().hashCode()) - + ((getValue() == null) ? 0 : getValue().hashCode()) - + Boolean.valueOf(isRequired()).hashCode(); - return result; - } - - @Override - public boolean equals(Object obj) { - if (this == obj) - return true; - if (obj == null) - return false; - if (getClass() != obj.getClass()) - return false; - Parameter other = (Parameter) obj; - if (getFrom() == null) { - if (other.getFrom() != null) { - return false; - } - } else if (!getFrom().equals(other.getFrom())) { - return false; - } - if (getGeneratorName() == null) { - if (other.getGeneratorName() != null) { - return false; - } - } else if (!getGeneratorName().equals(other.getGeneratorName())) { - return false; - } - if (getName() == null) { - if (other.getName() != null) { - return false; - } - } else if (!getName().equals(other.getName())) { - return false; - } - if (getValue() == null) { - if (other.getValue() != null) { - return false; - } - } else if (!getValue().equals(other.getValue())) { - return false; - } - if (isRequired() != other.isRequired()) { - return false; - } - return true; - } - +public class Parameter implements IParameter { + + private static final String VALUE = "value"; + + private ModelNode node; + + public Parameter(ModelNode node) { + this.node = node; + } + + @Override + public IParameter clone() { + return new Parameter(node.clone()); + } + + @Override + public String getName() { + return asString("name"); + } + + @Override + public String getDescription() { + return asString("description"); + } + + @Override + public void setValue(String value) { + node.get(VALUE).set(value); + } + + @Override + public String getValue() { + return asString(VALUE); + } + + @Override + public String getGeneratorName() { + return StringUtils.defaultIfEmpty(asString("generate"), asString("generator")); + } + + @Override + public String getFrom() { + return asString("from"); + } + + @Override + public boolean isRequired() { + if (node.hasDefined("required")) { + return node.get("required").asBoolean(); + } + return false; + } + + private String asString(String key) { + ModelNode value = node.get(key); + if (value.isDefined()) { + return value.asString(); + } + return ""; + } + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + ((getFrom() == null) ? 0 : getFrom().hashCode()) + + ((getGeneratorName() == null) ? 0 : getGeneratorName().hashCode()) + + ((getName() == null) ? 0 : getName().hashCode()) + ((getValue() == null) ? 0 : getValue().hashCode()) + + Boolean.valueOf(isRequired()).hashCode(); + return result; + } + + @Override + public boolean equals(Object obj) { + if (this == obj) { + return true; + } + if (obj == null) { + return false; + } + if (getClass() != obj.getClass()) { + return false; + } + Parameter other = (Parameter) obj; + if (getFrom() == null) { + if (other.getFrom() != null) { + return false; + } + } else if (!getFrom().equals(other.getFrom())) { + return false; + } + if (getGeneratorName() == null) { + if (other.getGeneratorName() != null) { + return false; + } + } else if (!getGeneratorName().equals(other.getGeneratorName())) { + return false; + } + if (getName() == null) { + if (other.getName() != null) { + return false; + } + } else if (!getName().equals(other.getName())) { + return false; + } + if (getValue() == null) { + if (other.getValue() != null) { + return false; + } + } else if (!getValue().equals(other.getValue())) { + return false; + } + if (isRequired() != other.isRequired()) { + return false; + } + return true; + } } diff --git a/src/main/java/com/openshift/internal/restclient/model/template/Template.java b/src/main/java/com/openshift/internal/restclient/model/template/Template.java index 4ad5ec31..e131ad44 100644 --- a/src/main/java/com/openshift/internal/restclient/model/template/Template.java +++ b/src/main/java/com/openshift/internal/restclient/model/template/Template.java @@ -6,6 +6,7 @@ * * Contributors: Red Hat, Inc. ******************************************************************************/ + package com.openshift.internal.restclient.model.template; import java.util.ArrayList; @@ -27,103 +28,99 @@ import com.openshift.restclient.model.template.IParameter; import com.openshift.restclient.model.template.ITemplate; -/** - * @author Jeff Cantrill - */ -public class Template extends KubernetesResource implements ITemplate{ - - private static final String TEMPLATE_PARAMETERS = "parameters"; - private static final String TEMPLATE_OBJECT_LABELS = "labels"; - - - public Template(ModelNode node, IClient client, Map overrideProperties) { - super(node, client, overrideProperties); - } - - @Override - public Map getObjectLabels() { - return Collections.unmodifiableMap(asMap(TEMPLATE_OBJECT_LABELS)); - } - - @Override - public void addObjectLabel(String key, String value) { - ModelNode labels = getNode().get(getPath(TEMPLATE_OBJECT_LABELS)); - labels.get(key).set(value); - } - - @Override - public Map getParameters() { - Map params = new HashMap(); - ModelNode modelNode = get(TEMPLATE_PARAMETERS); - if(modelNode.isDefined()) { - Collection nodes = modelNode.asList(); - for (ModelNode node : nodes) { - Parameter p = new Parameter(node); - params.put(p.getName(), p); - } - } - return params; - } - - @Override - public Collection getItems() { - Collection nodes = get(OBJECTS).asList(); - List resources = new ArrayList(nodes.size()); - IResourceFactory factory = getClient().getResourceFactory(); - if(factory != null){ - for (ModelNode node : nodes) { - resources.add(factory.create(node.toJSONString(true))); - } - } - return resources; - } - - @Override - public void updateParameterValues(Collection parameters) { - Map actuals = getParameters(); - for (IParameter param : parameters) { - if(actuals.containsKey(param.getName())) { - actuals.get(param.getName()).setValue(param.getValue()); - } - } - } - - @Override - public void updateParameter(String key, String value) { - Map params = getParameters(); - if(params.containsKey(key)) { - params.get(key).setValue(value); - } - } - - /** - * Returns true if this template contains the given text - * in name or tags. - * - * @param filterText - * @param template - * @return - */ - @Override - public boolean isMatching(final String text) { - if (StringUtils.isBlank(text)) { - return true; - } - if (getName().contains(text)) { - return true; - } - - return accept(new CapabilityVisitor() { - @Override - public Boolean visit(ITags capability) { - for (String tag : capability.getTags()) { - if (tag.contains(text)) { - return true; - } - } - return false; - } - }, false); - } +public class Template extends KubernetesResource implements ITemplate { + + private static final String TEMPLATE_PARAMETERS = "parameters"; + private static final String TEMPLATE_OBJECT_LABELS = "labels"; + + public Template(ModelNode node, IClient client, Map overrideProperties) { + super(node, client, overrideProperties); + } + + @Override + public Map getObjectLabels() { + return Collections.unmodifiableMap(asMap(TEMPLATE_OBJECT_LABELS)); + } + + @Override + public void addObjectLabel(String key, String value) { + ModelNode labels = getNode().get(getPath(TEMPLATE_OBJECT_LABELS)); + labels.get(key).set(value); + } + + @Override + public Map getParameters() { + Map params = new HashMap(); + ModelNode modelNode = get(TEMPLATE_PARAMETERS); + if (modelNode.isDefined()) { + Collection nodes = modelNode.asList(); + for (ModelNode node : nodes) { + Parameter p = new Parameter(node); + params.put(p.getName(), p); + } + } + return params; + } + + @Override + public Collection getObjects() { + if (!getNode().has(OBJECTS)) { + return Collections.emptyList(); + } + Collection nodes = get(OBJECTS).asList(); + List resources = new ArrayList(nodes.size()); + IResourceFactory factory = getClient().getResourceFactory(); + if (factory != null) { + for (ModelNode node : nodes) { + resources.add(factory.create(node.toJSONString(true))); + } + } + return resources; + } + + @Override + public void updateParameterValues(Collection parameters) { + Map actuals = getParameters(); + for (IParameter param : parameters) { + if (actuals.containsKey(param.getName())) { + actuals.get(param.getName()).setValue(param.getValue()); + } + } + } + + @Override + public void updateParameter(String key, String value) { + Map params = getParameters(); + if (params.containsKey(key)) { + params.get(key).setValue(value); + } + } + + /** + * Returns true if this template contains the given text in name or + * tags. + * + */ + @Override + public boolean isMatching(final String text) { + if (StringUtils.isBlank(text)) { + return true; + } + if (getName().contains(text)) { + return true; + } + + return accept(new CapabilityVisitor() { + @Override + public Boolean visit(ITags capability) { + for (String tag : capability.getTags()) { + if (tag.contains(text)) { + return true; + } + } + return false; + } + }, false); + } } diff --git a/src/main/java/com/openshift/internal/restclient/model/user/OpenShiftGroup.java b/src/main/java/com/openshift/internal/restclient/model/user/OpenShiftGroup.java new file mode 100644 index 00000000..bc5d85c8 --- /dev/null +++ b/src/main/java/com/openshift/internal/restclient/model/user/OpenShiftGroup.java @@ -0,0 +1,44 @@ +/******************************************************************************* + * Copyright (c) 2018 Red Hat, Inc. + * + * Distributed under license by Red Hat, Inc. All rights reserved. + * This program is made available under the terms of the + * Eclipse Public License v1.0 which accompanies this distribution, + * and is available at http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Red Hat, Inc. - initial API and implementation + * Roland T. Lichti - implementation of user.openshift.io/v1/groups + ******************************************************************************/ + +package com.openshift.internal.restclient.model.user; + +import java.util.Map; +import java.util.Set; + +import org.jboss.dmr.ModelNode; +import org.jboss.dmr.ModelType; + +import com.openshift.internal.restclient.model.KubernetesResource; +import com.openshift.restclient.IClient; +import com.openshift.restclient.model.user.IGroup; + +public class OpenShiftGroup extends KubernetesResource implements IGroup { + + private static final String USERS = "users"; + + public OpenShiftGroup(ModelNode node, IClient client, Map propertyKeys) { + super(node, client, propertyKeys); + } + + @Override + public String getUID() { + return asString(METADATA_UID); + } + + @Override + public Set getUsers() { + //noinspection unchecked + return (Set) asSet(USERS, ModelType.STRING); + } +} diff --git a/src/main/java/com/openshift/internal/restclient/model/user/OpenShiftIdentity.java b/src/main/java/com/openshift/internal/restclient/model/user/OpenShiftIdentity.java new file mode 100644 index 00000000..2dc21c90 --- /dev/null +++ b/src/main/java/com/openshift/internal/restclient/model/user/OpenShiftIdentity.java @@ -0,0 +1,61 @@ +/******************************************************************************* + * Copyright (c) 2018 Red Hat, Inc. + * + * Distributed under license by Red Hat, Inc. All rights reserved. + * This program is made available under the terms of the + * Eclipse Public License v1.0 which accompanies this distribution, + * and is available at http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Red Hat, Inc. - initial API and implementation + * Roland T. Lichti - implementation of user.openshift.io/v1/identities + ******************************************************************************/ + +package com.openshift.internal.restclient.model.user; + +import java.util.Map; + +import org.jboss.dmr.ModelNode; + +import com.openshift.internal.restclient.model.KubernetesResource; +import com.openshift.internal.restclient.model.ObjectReference; +import com.openshift.restclient.IClient; +import com.openshift.restclient.model.IObjectReference; +import com.openshift.restclient.model.user.IIdentity; + +public class OpenShiftIdentity extends KubernetesResource implements IIdentity { + + private static final String PROVIDER_NAME = "providerName"; + private static final String PROVIDER_USER_NAME = "providerUserName"; + private static final String EXTRA = "extra"; + private static final String USER = "user"; + + public OpenShiftIdentity(ModelNode node, IClient client, Map propertyKeys) { + super(node, client, propertyKeys); + } + + @Override + public String getUserName() { + return asString(PROVIDER_USER_NAME); + } + + @Override + public String getUID() { + return asString(METADATA_UID); + } + + @Override + public String getProviderName() { + return asString(PROVIDER_NAME); + } + + @Override + public Map getExtra() { + return asMap(EXTRA); + } + + @Override + public IObjectReference getUser() { + return new ObjectReference(get(USER)); + } +} diff --git a/src/main/java/com/openshift/internal/restclient/model/user/OpenShiftUser.java b/src/main/java/com/openshift/internal/restclient/model/user/OpenShiftUser.java index 172adddd..89e1f6fe 100644 --- a/src/main/java/com/openshift/internal/restclient/model/user/OpenShiftUser.java +++ b/src/main/java/com/openshift/internal/restclient/model/user/OpenShiftUser.java @@ -8,11 +8,14 @@ * Contributors: * Red Hat, Inc. - initial API and implementation ******************************************************************************/ + package com.openshift.internal.restclient.model.user; import java.util.Map; +import java.util.Set; import org.jboss.dmr.ModelNode; +import org.jboss.dmr.ModelType; import com.openshift.internal.restclient.model.KubernetesResource; import com.openshift.restclient.IClient; @@ -20,15 +23,31 @@ public class OpenShiftUser extends KubernetesResource implements IUser { - private static final String USER_FULLNAME = "fullName"; - - public OpenShiftUser(ModelNode node, IClient client, Map propertyKeys) { - super(node, client, propertyKeys); - } + private static final String USER_FULLNAME = "fullName"; + private static final String GROUPS = "groups"; + private static final String IDENTITES = "identities"; + + public OpenShiftUser(ModelNode node, IClient client, Map propertyKeys) { + super(node, client, propertyKeys); + } + + @Override + public String getFullName() { + return asString(USER_FULLNAME); + } + + @Override + public String getUID() { + return asString(METADATA_UID); + } - @Override - public String getFullName() { - return asString(USER_FULLNAME); - } + @Override + public Set getGroups() { + return asSet(GROUPS, ModelType.STRING); + } + @Override + public Set getIdentities() { + return asSet(IDENTITES, ModelType.STRING); + } } diff --git a/src/main/java/com/openshift/internal/restclient/model/volume/AbstractVolume.java b/src/main/java/com/openshift/internal/restclient/model/volume/AbstractVolume.java index e4a47c40..f8bb6f98 100644 --- a/src/main/java/com/openshift/internal/restclient/model/volume/AbstractVolume.java +++ b/src/main/java/com/openshift/internal/restclient/model/volume/AbstractVolume.java @@ -8,9 +8,12 @@ * Contributors: * Red Hat, Inc. - initial API and implementation ******************************************************************************/ + package com.openshift.internal.restclient.model.volume; -import static com.openshift.internal.util.JBossDmrExtentions.*; +import static com.openshift.internal.util.JBossDmrExtentions.asBoolean; +import static com.openshift.internal.util.JBossDmrExtentions.asString; +import static com.openshift.internal.util.JBossDmrExtentions.set; import java.util.HashMap; @@ -20,69 +23,60 @@ import com.openshift.internal.restclient.model.properties.ResourcePropertyKeys; import com.openshift.restclient.model.volume.IVolume; -/** - * - * @author Jeff Cantrill - * - */ -public abstract class AbstractVolume - extends ModelNodeAdapter - implements IVolume, ResourcePropertyKeys{ - - private static final String READONLY = "readOnly"; - private static final String MOUNT_PATH = "mountPath"; - - public AbstractVolume(ModelNode node) { - super(node, new HashMap()); - } - - @Override - public String getName() { - return asString(getNode(), getPropertyKeys(), NAME); - } - - @Override - public void setName(String name) { - set(getNode(), getPropertyKeys(), NAME, name); - } - - @Override - public void setMountPath(String path) { - set(getNode(), getPropertyKeys(), MOUNT_PATH, path); - } - - @Override - public String getMountPath() { - return asString(getNode(), getPropertyKeys(), MOUNT_PATH); - } - - @Override - public void setReadOnly(boolean readonly) { - set(getNode(), getPropertyKeys(), READONLY, readonly); - } - - @Override - public boolean isReadOnly() { - return asBoolean(getNode(), getPropertyKeys(), READONLY); - } - - @Override - public boolean equals(Object obj) { - if(!(obj instanceof AbstractVolume)) - return false; - AbstractVolume other = (AbstractVolume) obj; - return getName().equals(other.getName()) && - getMountPath().equals(other.getMountPath()) && - isReadOnly() == other.isReadOnly(); - } - - @Override - public int hashCode() { - int code = isReadOnly() ? 1 : 0; - code = code + getName().hashCode(); - return code + getMountPath().hashCode(); - } - - - +public abstract class AbstractVolume extends ModelNodeAdapter implements IVolume, ResourcePropertyKeys { + + private static final String READONLY = "readOnly"; + private static final String MOUNT_PATH = "mountPath"; + + public AbstractVolume(ModelNode node) { + super(node, new HashMap()); + } + + @Override + public String getName() { + return asString(getNode(), getPropertyKeys(), NAME); + } + + @Override + public void setName(String name) { + set(getNode(), getPropertyKeys(), NAME, name); + } + + @Override + public void setMountPath(String path) { + set(getNode(), getPropertyKeys(), MOUNT_PATH, path); + } + + @Override + public String getMountPath() { + return asString(getNode(), getPropertyKeys(), MOUNT_PATH); + } + + @Override + public void setReadOnly(boolean readonly) { + set(getNode(), getPropertyKeys(), READONLY, readonly); + } + + @Override + public boolean isReadOnly() { + return asBoolean(getNode(), getPropertyKeys(), READONLY); + } + + @Override + public boolean equals(Object obj) { + if (!(obj instanceof AbstractVolume)) { + return false; + } + AbstractVolume other = (AbstractVolume) obj; + return getName().equals(other.getName()) && getMountPath().equals(other.getMountPath()) + && isReadOnly() == other.isReadOnly(); + } + + @Override + public int hashCode() { + int code = isReadOnly() ? 1 : 0; + code = code + getName().hashCode(); + return code + getMountPath().hashCode(); + } + } diff --git a/src/main/java/com/openshift/internal/restclient/model/volume/EmptyDirVolume.java b/src/main/java/com/openshift/internal/restclient/model/volume/EmptyDirVolume.java index fb17f056..b8150ccd 100644 --- a/src/main/java/com/openshift/internal/restclient/model/volume/EmptyDirVolume.java +++ b/src/main/java/com/openshift/internal/restclient/model/volume/EmptyDirVolume.java @@ -7,30 +7,27 @@ * * Contributors: * Red Hat, Inc. - initial API and implementation - ******************************************************************************/package com.openshift.internal.restclient.model.volume; + ******************************************************************************/ + +package com.openshift.internal.restclient.model.volume; import org.jboss.dmr.ModelNode; import com.openshift.restclient.model.volume.IVolume; -/** - * - * @author Jeff Cantrill - * - */ public class EmptyDirVolume extends AbstractVolume { - public EmptyDirVolume(ModelNode node, IVolume volume) { - super(node); - if(volume != null) { - setMountPath(volume.getMountPath()); - setReadOnly(volume.isReadOnly()); - setName(volume.getName()); - } - } + public EmptyDirVolume(ModelNode node, IVolume volume) { + super(node); + if (volume != null) { + setMountPath(volume.getMountPath()); + setReadOnly(volume.isReadOnly()); + setName(volume.getName()); + } + } - public EmptyDirVolume(ModelNode node) { - this(node, null); - } + public EmptyDirVolume(ModelNode node) { + this(node, null); + } } diff --git a/src/main/java/com/openshift/internal/restclient/model/volume/EmptyDirVolumeSource.java b/src/main/java/com/openshift/internal/restclient/model/volume/EmptyDirVolumeSource.java index 8bec3b9a..307e1e6d 100644 --- a/src/main/java/com/openshift/internal/restclient/model/volume/EmptyDirVolumeSource.java +++ b/src/main/java/com/openshift/internal/restclient/model/volume/EmptyDirVolumeSource.java @@ -8,15 +8,17 @@ * Contributors: * Red Hat, Inc. - initial API and implementation ******************************************************************************/ -package com.openshift.internal.restclient.model.volume; -import com.openshift.restclient.model.volume.IEmptyDirVolumeSource; -import com.openshift.restclient.model.volume.VolumeType; -import org.jboss.dmr.ModelNode; +package com.openshift.internal.restclient.model.volume; import static com.openshift.internal.util.JBossDmrExtentions.asString; import static com.openshift.internal.util.JBossDmrExtentions.set; +import org.jboss.dmr.ModelNode; + +import com.openshift.restclient.model.volume.IEmptyDirVolumeSource; +import com.openshift.restclient.model.volume.VolumeType; + /** * @author Ulf Lilleengen */ diff --git a/src/main/java/com/openshift/internal/restclient/model/volume/HostPathVolumeSource.java b/src/main/java/com/openshift/internal/restclient/model/volume/HostPathVolumeSource.java new file mode 100644 index 00000000..576829d8 --- /dev/null +++ b/src/main/java/com/openshift/internal/restclient/model/volume/HostPathVolumeSource.java @@ -0,0 +1,43 @@ +/******************************************************************************* + * Copyright (c) 2016 Red Hat, Inc. + * Distributed under license by Red Hat, Inc. All rights reserved. + * This program is made available under the terms of the + * Eclipse Public License v1.0 which accompanies this distribution, + * and is available at http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Red Hat, Inc. - initial API and implementation + ******************************************************************************/ + +package com.openshift.internal.restclient.model.volume; + +import static com.openshift.internal.util.JBossDmrExtentions.asString; +import static com.openshift.internal.util.JBossDmrExtentions.set; + +import org.jboss.dmr.ModelNode; + +import com.openshift.restclient.model.volume.IHostPathVolumeSource; + +/** + * Implementation of a hostpath volume source + * + */ +public class HostPathVolumeSource extends VolumeSource implements IHostPathVolumeSource { + + private static final String PATH = "hostPath.path"; + + public HostPathVolumeSource(ModelNode node) { + super(node); + } + + @Override + public String getPath() { + return asString(getNode(), getPropertyKeys(), PATH); + } + + @Override + public void setPath(String path) { + set(getNode(), getPropertyKeys(), PATH, path); + } + +} diff --git a/src/main/java/com/openshift/internal/restclient/model/volume/PersistentVolume.java b/src/main/java/com/openshift/internal/restclient/model/volume/PersistentVolume.java index 3c7b6dec..cf0034dd 100644 --- a/src/main/java/com/openshift/internal/restclient/model/volume/PersistentVolume.java +++ b/src/main/java/com/openshift/internal/restclient/model/volume/PersistentVolume.java @@ -8,6 +8,7 @@ * Contributors: * Red Hat, Inc. - initial API and implementation ******************************************************************************/ + package com.openshift.internal.restclient.model.volume; import java.util.Map; @@ -19,8 +20,8 @@ import org.jboss.dmr.ModelType; import com.openshift.internal.restclient.model.KubernetesResource; -import com.openshift.internal.restclient.model.volume.property.AbstractPersistentVolumeProperties; import com.openshift.internal.restclient.model.volume.property.HostPathVolumeProperties; +import com.openshift.internal.restclient.model.volume.property.ISettablePersistentVolumeProperties; import com.openshift.internal.restclient.model.volume.property.NfsVolumeProperties; import com.openshift.restclient.IClient; import com.openshift.restclient.model.volume.IPersistentVolume; @@ -30,238 +31,252 @@ import com.openshift.restclient.model.volume.property.IPersistentVolumeProperties; import com.openshift.restclient.utils.MemoryUnit; - public class PersistentVolume extends KubernetesResource implements IPersistentVolume { - private static final String PV_ACCESS_MODES = "spec.accessModes"; - private static final String PV_CAPACITY = "spec.capacity.storage"; - private static final String PV_RECLAIM_POLICY = "spec.persistentVolumeReclaimPolicy"; - private static final String PV_NFS = "spec.nfs"; - private static final String PV_HOST_PATH = "spec.hostPath"; - private static final String PV_SPEC = "spec"; - private static final String SERVER = "server"; - private static final String PATH = "path"; - private static final String READ_ONLY = "readOnly"; + private static final String PV_ACCESS_MODES = "spec.accessModes"; + private static final String PV_CAPACITY = "spec.capacity.storage"; + private static final String PV_RECLAIM_POLICY = "spec.persistentVolumeReclaimPolicy"; + private static final String PV_NFS = "spec.nfs"; + private static final String PV_HOST_PATH = "spec.hostPath"; + private static final String PV_SPEC = "spec"; + private static final String SERVER = "server"; + private static final String PATH = "path"; + private static final String READ_ONLY = "readOnly"; - public PersistentVolume(ModelNode node, IClient client, Map propertyKeys) { - super(node, client, propertyKeys); - } + public PersistentVolume(ModelNode node, IClient client, Map propertyKeys) { + super(node, client, propertyKeys); + } - /** - * @param unit the designated unit. One of "Ki", "Mi", "Gi", "Ti", "Pi", "Ei". - * @return 0, if conversion not possible. Otherwise the capacity in given units. - * @see {@link PersistentVolume#convert(String, MemoryUnit)} - * @throws IllegalArgumentException if not supported {@code unit} given. - */ - @Override - public long getCapacity(String unit) { - String capacity = asString(PV_CAPACITY); - return convert(capacity, MemoryUnit.valueOf(unit)); - } + /** + * @param unit + * the designated unit. One of "Ki", "Mi", "Gi", "Ti", "Pi", "Ei". + * @return 0, if conversion not possible. Otherwise the capacity in given units. + * @see {@link PersistentVolume#convert(String, MemoryUnit)} + * @throws IllegalArgumentException + * if not supported {@code unit} given. + */ + @Override + public long getCapacity(String unit) { + String capacity = asString(PV_CAPACITY); + return convert(capacity, MemoryUnit.valueOf(unit)); + } - /** - * @param unit the designated unit. One of {@link MemoryUnit}'s Ki, Mi, Gi, Ti, Pi, Ei. - * @return 0, if conversion not possible. Otherwise the capacity in given units. - * @see {@link PersistentVolume#convert(String, MemoryUnit)} - * @throws IllegalArgumentException if not supported {@code unit} given. - */ - @Override - public long getCapacity(MemoryUnit unit) { - String capacity = asString(PV_CAPACITY); - return convert(capacity, unit); - } + /** + * @param unit + * the designated unit. One of {@link MemoryUnit}'s Ki, Mi, Gi, Ti, + * Pi, Ei. + * @return 0, if conversion not possible. Otherwise the capacity in given units. + * @see {@link PersistentVolume#convert(String, MemoryUnit)} + * @throws IllegalArgumentException + * if not supported {@code unit} given. + */ + @Override + public long getCapacity(MemoryUnit unit) { + String capacity = asString(PV_CAPACITY); + return convert(capacity, unit); + } - /** - * @return the capacity in bytes. - */ - @Override - public long getCapacity() { - String capacity = asString(PV_CAPACITY); - return Math.multiplyExact(convert(capacity, MemoryUnit.Ki), 1024L); - } + /** + * @return the capacity in bytes. + */ + @Override + public long getCapacity() { + String capacity = asString(PV_CAPACITY); + return Math.multiplyExact(convert(capacity, MemoryUnit.Ki), 1024L); + } - /** - * Sets the capacity. There is no conversion between units. - * @param capacity the capacity - * @param unit the unit - */ - @Override - public void setCapacity(long capacity, MemoryUnit unit) { - set(PV_CAPACITY, capacity + unit.name()); - } + /** + * Sets the capacity. There is no conversion between units. + * + * @param capacity + * the capacity + * @param unit + * the unit + */ + @Override + public void setCapacity(long capacity, MemoryUnit unit) { + set(PV_CAPACITY, capacity + unit.name()); + } - /** - * @return the unit in which the capacity is represent. - * @see {@link MemoryUnit} - */ - @Override - public MemoryUnit getCapacityUnit() { - return parseCapacityUnit(asString(PV_CAPACITY)); - } + /** + * @return the unit in which the capacity is represent. + * @see {@link MemoryUnit} + */ + @Override + public MemoryUnit getCapacityUnit() { + return parseCapacityUnit(asString(PV_CAPACITY)); + } - /** - * @return access modes - * @see {@link com.openshift.restclient.model.volume.PVCAccessModes} - * @see - */ - @Override - public Set getAccessModes() { - return asSet(PV_ACCESS_MODES, ModelType.STRING); - } + /** + * @return access modes + * @see {@link com.openshift.restclient.model.volume.PVCAccessModes} + * @see + */ + @Override + public Set getAccessModes() { + return asSet(PV_ACCESS_MODES, ModelType.STRING); + } - /** - * Sets the access modes. - * If there are any modes present, they are overridden by the {@code modes} parameter. - * @param modes the access modes - */ - @Override - public void setAccessModes(String... modes) { - get(PV_ACCESS_MODES).setEmptyList(); - set(PV_ACCESS_MODES, modes); - } + /** + * Sets the access modes. If there are any modes present, they are overridden by + * the {@code modes} parameter. + * + * @param modes + * the access modes + */ + @Override + public void setAccessModes(String... modes) { + get(PV_ACCESS_MODES).setEmptyList(); + set(PV_ACCESS_MODES, modes); + } - /** - * @return the value of 'spec.persistentVolumeReclaimPolicy' - */ - @Override - public String getReclaimPolicy() { - return asString(PV_RECLAIM_POLICY); - } + /** + * @return the value of 'spec.persistentVolumeReclaimPolicy' + */ + @Override + public String getReclaimPolicy() { + return asString(PV_RECLAIM_POLICY); + } - /** - * Sets the 'spec.persistentVolumeReclaimPolicy' value - * @param policy the policy string - */ - @Override - public void setReclaimPolicy(String policy) { - set(PV_RECLAIM_POLICY, policy); - } + /** + * Sets the 'spec.persistentVolumeReclaimPolicy' value + * + * @param policy + * the policy string + */ + @Override + public void setReclaimPolicy(String policy) { + set(PV_RECLAIM_POLICY, policy); + } - /** - * @return specific persistent volume type - */ - @Override - public IPersistentVolumeProperties getPersistentVolumeProperties() { - IPersistentVolumeProperties properties; - switch(getPVType()) { - case VolumeType.HOST_PATH: - properties = createHostPathVolumeProperties(); - break; - case VolumeType.NFS: - properties = createNFSVolumeProperties(); - break; - default: - properties = null; - break; - } - return properties; - } + /** + * @return specific persistent volume type + */ + @Override + public IPersistentVolumeProperties getPersistentVolumeProperties() { + IPersistentVolumeProperties properties; + switch (getPVType()) { + case VolumeType.HOST_PATH: + properties = createHostPathVolumeProperties(); + break; + case VolumeType.NFS: + properties = createNFSVolumeProperties(); + break; + default: + properties = null; + break; + } + return properties; + } - /** - * Sets the volume type properties. - * @param properties the properties - */ - @Override - public void setPersistentVolumeProperties(IPersistentVolumeProperties properties) { - if(properties instanceof AbstractPersistentVolumeProperties) { - ((AbstractPersistentVolumeProperties) properties).setProperties(getNode()); - } - } + /** + * Sets the volume type properties. + * + * @param properties + * the properties + */ + @Override + public void setPersistentVolumeProperties(IPersistentVolumeProperties properties) { + if (properties instanceof ISettablePersistentVolumeProperties) { + ((ISettablePersistentVolumeProperties) properties).setProperties(getNode()); + } + } - /** - * @return a string value of the type. One of {@link VolumeType}. - */ - public String getPVType() { - final ModelNode spec = get(PV_SPEC); - return VolumeType.getTypes().stream() - .filter(spec::hasDefined) - .findFirst().get(); - } + /** + * @return a string value of the type. One of {@link VolumeType}. + */ + public String getPVType() { + final ModelNode spec = get(PV_SPEC); + return VolumeType.getTypes().stream().filter(spec::hasDefined).findFirst().get(); + } - /** - * @return values of 'spec.nfs' wrapped in {@link INfsVolumeProperties} - */ - private INfsVolumeProperties createNFSVolumeProperties() { - ModelNode node = get(PV_NFS); - String server = asString(node, SERVER); - String path = asString(node, PATH); - boolean readOnly = asBoolean(node, READ_ONLY); - return new NfsVolumeProperties(server, path, readOnly); - } + /** + * @return values of 'spec.nfs' wrapped in {@link INfsVolumeProperties} + */ + private INfsVolumeProperties createNFSVolumeProperties() { + ModelNode node = get(PV_NFS); + String server = asString(node, SERVER); + String path = asString(node, PATH); + boolean readOnly = asBoolean(node, READ_ONLY); + return new NfsVolumeProperties(server, path, readOnly); + } - /** - * @return the value of 'spec.hostPath.path' wrapped in {@link IHostPathVolumeProperties} - */ - private IHostPathVolumeProperties createHostPathVolumeProperties() { - ModelNode node = get(PV_HOST_PATH); - String path = asString(node, PATH); - return new HostPathVolumeProperties(path); - } + /** + * @return the value of 'spec.hostPath.path' wrapped in + * {@link IHostPathVolumeProperties} + */ + private IHostPathVolumeProperties createHostPathVolumeProperties() { + ModelNode node = get(PV_HOST_PATH); + String path = asString(node, PATH); + return new HostPathVolumeProperties(path); + } - /** - * Converts capacity string (i.e. '10Gi') to it's numeric representation. - * The following assumptions are used to compute values: - * One Ki = 2^10 - * One Mi = 2^20 - * One Gi = 2^30 - * One Ti = 2^40 - * One Pi = 2^50 - * One Ei = 2^60 - * - * Java's type long can contain max value of 2^64, enough for a few Exbibytes. - * Following equation is used to convert values: - * - * kubernetesGivenNumber << (10 * i), where << is implicit multiplication by powers of 2 and (10 * i) is the order of magnitude. - * Example: convert 1Ti to Mi = 1Ti << (10*2) = 1 * 2^20 = 2^20 - * - * @param capacity the capacity string - * @param designatedUnit the designated unit of type {@link MemoryUnit}. Possible values 'Ki, Mi, Gi, Ti, Pi, Ei'. - * @return 0 if conversion is not possible, otherwise the numeric representation converted to designatedUnit. - * Conversion is not possible when the designatedUnit cannot contain the unit given by Kubernetes in integral form. - */ - private static long convert(final String capacity, final MemoryUnit designatedUnit) { - long number = parseCapacityValue(capacity); - MemoryUnit currentUnit = parseCapacityUnit(capacity); + /** + * Converts capacity string (i.e. '10Gi') to it's numeric representation. The + * following assumptions are used to compute values: One Ki = 2^10 One Mi = 2^20 + * One Gi = 2^30 One Ti = 2^40 One Pi = 2^50 One Ei = 2^60 + * + * Java's type long can contain max value of 2^64, enough for a few Exbibytes. + * Following equation is used to convert values: + * + * kubernetesGivenNumber << (10 * i), where << is implicit multiplication by + * powers of 2 and (10 * i) is the order of magnitude. Example: convert 1Ti to + * Mi = 1Ti << (10*2) = 1 * 2^20 = 2^20 + * + * @param capacity + * the capacity string + * @param designatedUnit + * the designated unit of type {@link MemoryUnit}. Possible values + * 'Ki, Mi, Gi, Ti, Pi, Ei'. + * @return 0 if conversion is not possible, otherwise the numeric representation + * converted to designatedUnit. Conversion is not possible when the + * designatedUnit cannot contain the unit given by Kubernetes in + * integral form. + */ + private static long convert(final String capacity, final MemoryUnit designatedUnit) { + long number = parseCapacityValue(capacity); + MemoryUnit currentUnit = parseCapacityUnit(capacity); - int operation = currentUnit.compareTo(designatedUnit); - if(operation == 0L) { - return number; - } else if(operation > 0L) { - return safeMultiplicationBy1024(number, operation); //number << (10 * operation); - } else { - return 0L; - } - } + int operation = currentUnit.compareTo(designatedUnit); + if (operation == 0L) { + return number; + } else if (operation > 0L) { + return safeMultiplicationBy1024(number, operation); // number << (10 * operation); + } else { + return 0L; + } + } - /** - * @throws ArithmeticException if computation overflows - */ - private static long safeMultiplicationBy1024(long value, long times) { - long multiplicand = (long) Math.pow(1024L, times); - return Math.multiplyExact(value, multiplicand); - } + /** + * @throws ArithmeticException + * if computation overflows + */ + private static long safeMultiplicationBy1024(long value, long times) { + long multiplicand = (long) Math.pow(1024L, times); + return Math.multiplyExact(value, multiplicand); + } - private static long parseCapacityValue(String capacityString) { - if(capacityString == null) { - return 0L; - } - Pattern pattern = Pattern.compile("(\\d+)(\\w{2})"); - Matcher m = pattern.matcher(capacityString); - if(!m.find()) { - return 0L; - } - return Long.parseLong(m.group(1)); - } + private static long parseCapacityValue(String capacityString) { + if (capacityString == null) { + return 0L; + } + Pattern pattern = Pattern.compile("(\\d+)(\\w{2})"); + Matcher m = pattern.matcher(capacityString); + if (!m.find()) { + return 0L; + } + return Long.parseLong(m.group(1)); + } - private static MemoryUnit parseCapacityUnit(String capacityString) { - if(capacityString == null) { - return null; - } - Pattern pattern = Pattern.compile("(\\d+)(\\w{2})"); - Matcher m = pattern.matcher(capacityString); - if(!m.find()) { - return null; - } - return MemoryUnit.valueOf(m.group(2)); - } + private static MemoryUnit parseCapacityUnit(String capacityString) { + if (capacityString == null) { + return null; + } + Pattern pattern = Pattern.compile("(\\d+)(\\w{2})"); + Matcher m = pattern.matcher(capacityString); + if (!m.find()) { + return null; + } + return MemoryUnit.valueOf(m.group(2)); + } } \ No newline at end of file diff --git a/src/main/java/com/openshift/internal/restclient/model/volume/PersistentVolumeClaim.java b/src/main/java/com/openshift/internal/restclient/model/volume/PersistentVolumeClaim.java index 3779a3a4..b0568540 100644 --- a/src/main/java/com/openshift/internal/restclient/model/volume/PersistentVolumeClaim.java +++ b/src/main/java/com/openshift/internal/restclient/model/volume/PersistentVolumeClaim.java @@ -8,6 +8,7 @@ * Contributors: * Red Hat, Inc. - initial API and implementation ******************************************************************************/ + package com.openshift.internal.restclient.model.volume; import java.util.HashSet; @@ -19,54 +20,62 @@ import com.openshift.internal.restclient.model.KubernetesResource; import com.openshift.restclient.IClient; +import com.openshift.restclient.ResourceKind; import com.openshift.restclient.model.volume.IPersistentVolumeClaim; -/** - * - * @author Jeff Cantrill - * - */ public class PersistentVolumeClaim extends KubernetesResource implements IPersistentVolumeClaim { - private static final String PVC_ACCESS_MODES = "spec.accessModes"; - private static final String PVC_REQUESTED_STORAGE = "spec.resources.requests.storage"; - private static final String STATUS_PHASE = "status.phase"; + private static final String PVC_ACCESS_MODES = "spec.accessModes"; + private static final String PVC_REQUESTED_STORAGE = "spec.resources.requests.storage"; + private static final String STATUS_PHASE = "status.phase"; + private static final String PVC_VOLUME_NAME = "spec.volumeName"; + + public PersistentVolumeClaim(ModelNode node, IClient client, Map propertyKeys) { + super(node, client, propertyKeys); + } - public PersistentVolumeClaim(ModelNode node, IClient client, Map propertyKeys) { - super(node, client, propertyKeys); - } + @Override + public Set getAccessModes() { + Set modes = new HashSet<>(); + ModelNode modelNode = get(PVC_ACCESS_MODES); + if (!modelNode.isDefined() || !modelNode.getType().equals(ModelType.LIST)) { + return modes; + } + for (ModelNode node : modelNode.asList()) { + modes.add(node.asString()); + } + return modes; + } - @Override - public Set getAccessModes() { - Set modes = new HashSet<>(); - ModelNode modelNode = get(PVC_ACCESS_MODES); - if(!modelNode.isDefined() || !modelNode.getType().equals(ModelType.LIST)) return modes; - for (ModelNode node : modelNode.asList()) { - modes.add(node.asString()); - } - return modes; - } + @Override + public void setAccessModes(Set accessModes) { + ModelNode modelNode = get(PVC_ACCESS_MODES); + modelNode.clear(); + accessModes.stream().forEach(modelNode::add); + } - @Override - public void setAccessModes(Set accessModes) { - ModelNode modelNode = get(PVC_ACCESS_MODES); - modelNode.clear(); - accessModes.stream().forEach(modelNode::add); - } + @Override + public String getRequestedStorage() { + return asString(PVC_REQUESTED_STORAGE); + } - @Override - public String getRequestedStorage() { - return asString(PVC_REQUESTED_STORAGE); - } + @Override + public void setRequestedStorage(String requestedStorage) { + set(PVC_REQUESTED_STORAGE, requestedStorage); + } - @Override - public void setRequestedStorage(String requestedStorage) { - set(PVC_REQUESTED_STORAGE, requestedStorage); - } + @Override + public String getKind() { + return ResourceKind.PVC; + } - @Override - public String getStatus() { - return asString(STATUS_PHASE); - } + @Override + public String getStatus() { + return asString(STATUS_PHASE); + } + @Override + public String getVolumeName() { + return asString(PVC_VOLUME_NAME); + } } diff --git a/src/main/java/com/openshift/internal/restclient/model/volume/PersistentVolumeClaimVolumeSource.java b/src/main/java/com/openshift/internal/restclient/model/volume/PersistentVolumeClaimVolumeSource.java index 865e9ce7..2c6a5bba 100644 --- a/src/main/java/com/openshift/internal/restclient/model/volume/PersistentVolumeClaimVolumeSource.java +++ b/src/main/java/com/openshift/internal/restclient/model/volume/PersistentVolumeClaimVolumeSource.java @@ -8,17 +8,18 @@ * Contributors: * Red Hat, Inc. - initial API and implementation ******************************************************************************/ -package com.openshift.internal.restclient.model.volume; -import com.openshift.restclient.model.volume.IPersistentVolumeClaimVolumeSource; -import com.openshift.restclient.model.volume.IVolumeSource; -import com.openshift.restclient.model.volume.VolumeType; -import org.jboss.dmr.ModelNode; +package com.openshift.internal.restclient.model.volume; import static com.openshift.internal.util.JBossDmrExtentions.asBoolean; import static com.openshift.internal.util.JBossDmrExtentions.asString; import static com.openshift.internal.util.JBossDmrExtentions.set; +import org.jboss.dmr.ModelNode; + +import com.openshift.restclient.model.volume.IPersistentVolumeClaimVolumeSource; +import com.openshift.restclient.model.volume.VolumeType; + /** * @author Ulf Lilleengen */ diff --git a/src/main/java/com/openshift/internal/restclient/model/volume/SecretVolumeSource.java b/src/main/java/com/openshift/internal/restclient/model/volume/SecretVolumeSource.java index c05be612..c51b9331 100644 --- a/src/main/java/com/openshift/internal/restclient/model/volume/SecretVolumeSource.java +++ b/src/main/java/com/openshift/internal/restclient/model/volume/SecretVolumeSource.java @@ -8,15 +8,17 @@ * Contributors: * Red Hat, Inc. - initial API and implementation ******************************************************************************/ -package com.openshift.internal.restclient.model.volume; -import com.openshift.restclient.model.volume.ISecretVolumeSource; -import com.openshift.restclient.model.volume.VolumeType; -import org.jboss.dmr.ModelNode; +package com.openshift.internal.restclient.model.volume; import static com.openshift.internal.util.JBossDmrExtentions.asString; import static com.openshift.internal.util.JBossDmrExtentions.set; +import org.jboss.dmr.ModelNode; + +import com.openshift.restclient.model.volume.ISecretVolumeSource; +import com.openshift.restclient.model.volume.VolumeType; + /** * @author Ulf Lilleengen */ diff --git a/src/main/java/com/openshift/internal/restclient/model/volume/VolumeMount.java b/src/main/java/com/openshift/internal/restclient/model/volume/VolumeMount.java index 080782a8..79a40cbc 100644 --- a/src/main/java/com/openshift/internal/restclient/model/volume/VolumeMount.java +++ b/src/main/java/com/openshift/internal/restclient/model/volume/VolumeMount.java @@ -8,9 +8,12 @@ * Contributors: * Red Hat, Inc. - initial API and implementation ******************************************************************************/ + package com.openshift.internal.restclient.model.volume; -import static com.openshift.internal.util.JBossDmrExtentions.*; +import static com.openshift.internal.util.JBossDmrExtentions.asBoolean; +import static com.openshift.internal.util.JBossDmrExtentions.asString; +import static com.openshift.internal.util.JBossDmrExtentions.set; import java.util.HashMap; @@ -21,78 +24,69 @@ import com.openshift.restclient.model.volume.IVolume; import com.openshift.restclient.model.volume.IVolumeMount; -/** - * - * @author Jeff Cantrill - * - */ -public class VolumeMount - extends ModelNodeAdapter - implements IVolumeMount, IVolume, ResourcePropertyKeys{ - - private static final String READONLY = "readOnly"; - private static final String MOUNT_PATH = "mountPath"; - - public VolumeMount(ModelNode node) { - this(node, null); - } - - public VolumeMount(ModelNode node, IVolumeMount source) { - super(node, new HashMap()); - if(source != null) { - setMountPath(source.getMountPath()); - setReadOnly(source.isReadOnly()); - setName(source.getName()); - } - } - - @Override - public String getName() { - return asString(getNode(), getPropertyKeys(), NAME); - } - - @Override - public void setName(String name) { - set(getNode(), getPropertyKeys(), NAME, name); - } - - @Override - public void setMountPath(String path) { - set(getNode(), getPropertyKeys(), MOUNT_PATH, path); - } - - @Override - public String getMountPath() { - return asString(getNode(), getPropertyKeys(), MOUNT_PATH); - } - - @Override - public void setReadOnly(boolean readonly) { - set(getNode(), getPropertyKeys(), READONLY, readonly); - } - - @Override - public boolean isReadOnly() { - return asBoolean(getNode(), getPropertyKeys(), READONLY); - } - - @Override - public boolean equals(Object obj) { - if(!(obj instanceof VolumeMount)) - return false; - VolumeMount other = (VolumeMount) obj; - return getName().equals(other.getName()) && - getMountPath().equals(other.getMountPath()) && - isReadOnly() == other.isReadOnly(); - } - - @Override - public int hashCode() { - int code = isReadOnly() ? 1 : 0; - code = code + getName().hashCode(); - return code + getMountPath().hashCode(); - } - - - +public class VolumeMount extends ModelNodeAdapter implements IVolumeMount, IVolume, ResourcePropertyKeys { + + private static final String READONLY = "readOnly"; + private static final String MOUNT_PATH = "mountPath"; + + public VolumeMount(ModelNode node) { + this(node, null); + } + + public VolumeMount(ModelNode node, IVolumeMount source) { + super(node, new HashMap()); + if (source != null) { + setMountPath(source.getMountPath()); + setReadOnly(source.isReadOnly()); + setName(source.getName()); + } + } + + @Override + public String getName() { + return asString(getNode(), getPropertyKeys(), NAME); + } + + @Override + public void setName(String name) { + set(getNode(), getPropertyKeys(), NAME, name); + } + + @Override + public void setMountPath(String path) { + set(getNode(), getPropertyKeys(), MOUNT_PATH, path); + } + + @Override + public String getMountPath() { + return asString(getNode(), getPropertyKeys(), MOUNT_PATH); + } + + @Override + public void setReadOnly(boolean readonly) { + set(getNode(), getPropertyKeys(), READONLY, readonly); + } + + @Override + public boolean isReadOnly() { + return asBoolean(getNode(), getPropertyKeys(), READONLY); + } + + @Override + public boolean equals(Object obj) { + if (!(obj instanceof VolumeMount)) { + return false; + } + VolumeMount other = (VolumeMount) obj; + return getName().equals(other.getName()) && getMountPath().equals(other.getMountPath()) + && isReadOnly() == other.isReadOnly(); + } + + @Override + public int hashCode() { + int code = isReadOnly() ? 1 : 0; + code = code + getName().hashCode(); + return code + getMountPath().hashCode(); + } + } diff --git a/src/main/java/com/openshift/internal/restclient/model/volume/VolumeSource.java b/src/main/java/com/openshift/internal/restclient/model/volume/VolumeSource.java index 80233cbc..98aea8c4 100644 --- a/src/main/java/com/openshift/internal/restclient/model/volume/VolumeSource.java +++ b/src/main/java/com/openshift/internal/restclient/model/volume/VolumeSource.java @@ -8,37 +8,32 @@ * Contributors: * Red Hat, Inc. - initial API and implementation ******************************************************************************/ + package com.openshift.internal.restclient.model.volume; -import static com.openshift.internal.util.JBossDmrExtentions.*; +import static com.openshift.internal.util.JBossDmrExtentions.asString; +import static com.openshift.internal.util.JBossDmrExtentions.set; import java.util.HashMap; -import com.openshift.restclient.model.volume.VolumeType; import org.apache.commons.lang.StringUtils; import org.jboss.dmr.ModelNode; import com.openshift.internal.restclient.model.ModelNodeAdapter; import com.openshift.internal.restclient.model.properties.ResourcePropertyKeys; import com.openshift.restclient.model.volume.IVolumeSource; +import com.openshift.restclient.model.volume.VolumeType; -/** - * - * @author Jeff Cantrill - * - */ -public abstract class VolumeSource - extends ModelNodeAdapter - implements IVolumeSource, ResourcePropertyKeys { +public abstract class VolumeSource extends ModelNodeAdapter implements IVolumeSource, ResourcePropertyKeys { - public VolumeSource(ModelNode node) { - super(node, new HashMap()); - } + public VolumeSource(ModelNode node) { + super(node, new HashMap()); + } - @Override - public String getName() { - return asString(getNode(), getPropertyKeys(), NAME); - } + @Override + public String getName() { + return asString(getNode(), getPropertyKeys(), NAME); + } @Override public void setName(String name) { @@ -60,8 +55,11 @@ public static IVolumeSource create(ModelNode node) { return new SecretVolumeSource(node); } else if (node.has(VolumeType.PERSISTENT_VOLUME_CLAIM)) { return new PersistentVolumeClaimVolumeSource(node); + } else if (node.has(VolumeType.HOST_PATH)) { + return new HostPathVolumeSource(node); } else { - return new VolumeSource(node) {}; + return new VolumeSource(node) { + }; } } } diff --git a/src/main/java/com/openshift/internal/restclient/model/volume/property/AbstractPersistentVolumeProperties.java b/src/main/java/com/openshift/internal/restclient/model/volume/property/AbstractPersistentVolumeProperties.java deleted file mode 100644 index bd2ae78d..00000000 --- a/src/main/java/com/openshift/internal/restclient/model/volume/property/AbstractPersistentVolumeProperties.java +++ /dev/null @@ -1,11 +0,0 @@ -package com.openshift.internal.restclient.model.volume.property; - -import org.jboss.dmr.ModelNode; - -import com.openshift.restclient.model.volume.property.IPersistentVolumeProperties; - -abstract public class AbstractPersistentVolumeProperties implements IPersistentVolumeProperties { - - public abstract void setProperties(ModelNode node); - -} diff --git a/src/main/java/com/openshift/internal/restclient/model/volume/property/HostPathVolumeProperties.java b/src/main/java/com/openshift/internal/restclient/model/volume/property/HostPathVolumeProperties.java index f638c593..e29a925a 100644 --- a/src/main/java/com/openshift/internal/restclient/model/volume/property/HostPathVolumeProperties.java +++ b/src/main/java/com/openshift/internal/restclient/model/volume/property/HostPathVolumeProperties.java @@ -8,6 +8,7 @@ * Contributors: * Red Hat, Inc. - initial API and implementation ******************************************************************************/ + package com.openshift.internal.restclient.model.volume.property; import java.util.Objects; @@ -16,52 +17,53 @@ import com.openshift.restclient.model.volume.property.IHostPathVolumeProperties; +public class HostPathVolumeProperties implements ISettablePersistentVolumeProperties, IHostPathVolumeProperties { -public class HostPathVolumeProperties extends AbstractPersistentVolumeProperties implements IHostPathVolumeProperties { - - private static final String PV_SPEC = "spec"; - private static final String PV_HOST_PATH = "hostPath"; - private static final String PATH = "path"; + private static final String PV_SPEC = "spec"; + private static final String PV_HOST_PATH = "hostPath"; + private static final String PATH = "path"; - private String path; + private String path; - public HostPathVolumeProperties(String path) { - this.path = path; - } + public HostPathVolumeProperties(String path) { + this.path = path; + } - @Override - public void setProperties(ModelNode node) { - ModelNode hostPath = node.get(PV_SPEC, PV_HOST_PATH); - hostPath.set(PATH, path); - } + @Override + public void setProperties(ModelNode node) { + ModelNode hostPath = node.get(PV_SPEC, PV_HOST_PATH); + hostPath.set(PATH, path); + } - @Override - public String getPath() { - return path; - } + @Override + public String getPath() { + return path; + } - @Override - public void setPath(String path) { - this.path = path; - } + @Override + public void setPath(String path) { + this.path = path; + } - @Override - public boolean equals(Object o) { - if (this == o) return true; - if (o == null || getClass() != o.getClass()) return false; - HostPathVolumeProperties that = (HostPathVolumeProperties) o; - return Objects.equals(path, that.path); - } + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + HostPathVolumeProperties that = (HostPathVolumeProperties) o; + return Objects.equals(path, that.path); + } - @Override - public int hashCode() { - return Objects.hash(path); - } + @Override + public int hashCode() { + return Objects.hash(path); + } - @Override - public String toString() { - return "HostPathVolumeProperties{" + - "path='" + path + '\'' + - '}'; - } + @Override + public String toString() { + return "HostPathVolumeProperties{" + "path='" + path + '\'' + '}'; + } } diff --git a/src/main/java/com/openshift/internal/restclient/model/volume/property/ISettablePersistentVolumeProperties.java b/src/main/java/com/openshift/internal/restclient/model/volume/property/ISettablePersistentVolumeProperties.java new file mode 100644 index 00000000..879367ab --- /dev/null +++ b/src/main/java/com/openshift/internal/restclient/model/volume/property/ISettablePersistentVolumeProperties.java @@ -0,0 +1,22 @@ +/******************************************************************************* + * Copyright (c) 2015-2019 Red Hat, Inc. + * Distributed under license by Red Hat, Inc. All rights reserved. + * This program is made available under the terms of the + * Eclipse Public License v1.0 which accompanies this distribution, + * and is available at http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Red Hat, Inc. - initial API and implementation + ******************************************************************************/ + +package com.openshift.internal.restclient.model.volume.property; + +import org.jboss.dmr.ModelNode; + +import com.openshift.restclient.model.volume.property.IPersistentVolumeProperties; + +public interface ISettablePersistentVolumeProperties extends IPersistentVolumeProperties { + + void setProperties(ModelNode node); + +} diff --git a/src/main/java/com/openshift/internal/restclient/model/volume/property/NfsVolumeProperties.java b/src/main/java/com/openshift/internal/restclient/model/volume/property/NfsVolumeProperties.java index 2c4fc756..36cab962 100644 --- a/src/main/java/com/openshift/internal/restclient/model/volume/property/NfsVolumeProperties.java +++ b/src/main/java/com/openshift/internal/restclient/model/volume/property/NfsVolumeProperties.java @@ -8,6 +8,7 @@ * Contributors: * Red Hat, Inc. - initial API and implementation ******************************************************************************/ + package com.openshift.internal.restclient.model.volume.property; import java.util.Objects; @@ -16,78 +17,77 @@ import com.openshift.restclient.model.volume.property.INfsVolumeProperties; - -public class NfsVolumeProperties extends AbstractPersistentVolumeProperties implements INfsVolumeProperties { - - private static final String PV_SPEC = "spec"; - private static final String PV_NFS = "nfs"; - private static final String SERVER = "server"; - private static final String PATH = "path"; - private static final String READ_ONLY = "readOnly"; - - private String server; - private String path; - private boolean readOnly; - - public NfsVolumeProperties(String server, String path, boolean readOnly) { - this.server = server; - this.path = path; - this.readOnly = readOnly; - } - - public String getServer() { - return server; - } - - public void setServer(String server) { - this.server = server; - } - - public String getPath() { - return path; - } - - public void setPath(String path) { - this.path = path; - } - - public boolean isReadOnly() { - return readOnly; - } - - public void setReadOnly(boolean readOnly) { - this.readOnly = readOnly; - } - - @Override - public void setProperties(ModelNode node) { - ModelNode nfs = node.get(PV_SPEC, PV_NFS); - nfs.get(SERVER).set(server); - nfs.get(PATH).set(path); - nfs.get(READ_ONLY).set(readOnly); - } - - @Override - public boolean equals(Object o) { - if (this == o) return true; - if (o == null || getClass() != o.getClass()) return false; - NfsVolumeProperties nfsVolumeProperties = (NfsVolumeProperties) o; - return Objects.equals(readOnly, nfsVolumeProperties.readOnly) && - Objects.equals(server, nfsVolumeProperties.server) && - Objects.equals(path, nfsVolumeProperties.path); - } - - @Override - public int hashCode() { - return Objects.hash(server, path, readOnly); - } - - @Override - public String toString() { - return "NfsVolumeProperties{" + - "server='" + server + '\'' + - ", path='" + path + '\'' + - ", readOnly=" + readOnly + - '}'; - } +public class NfsVolumeProperties implements ISettablePersistentVolumeProperties, INfsVolumeProperties { + + private static final String PV_SPEC = "spec"; + private static final String PV_NFS = "nfs"; + private static final String SERVER = "server"; + private static final String PATH = "path"; + private static final String READ_ONLY = "readOnly"; + + private String server; + private String path; + private boolean readOnly; + + public NfsVolumeProperties(String server, String path, boolean readOnly) { + this.server = server; + this.path = path; + this.readOnly = readOnly; + } + + public String getServer() { + return server; + } + + public void setServer(String server) { + this.server = server; + } + + public String getPath() { + return path; + } + + public void setPath(String path) { + this.path = path; + } + + public boolean isReadOnly() { + return readOnly; + } + + public void setReadOnly(boolean readOnly) { + this.readOnly = readOnly; + } + + @Override + public void setProperties(ModelNode node) { + ModelNode nfs = node.get(PV_SPEC, PV_NFS); + nfs.get(SERVER).set(server); + nfs.get(PATH).set(path); + nfs.get(READ_ONLY).set(readOnly); + } + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + NfsVolumeProperties nfsVolumeProperties = (NfsVolumeProperties) o; + return Objects.equals(readOnly, nfsVolumeProperties.readOnly) + && Objects.equals(server, nfsVolumeProperties.server) && Objects.equals(path, nfsVolumeProperties.path); + } + + @Override + public int hashCode() { + return Objects.hash(server, path, readOnly); + } + + @Override + public String toString() { + return "NfsVolumeProperties{" + "server='" + server + '\'' + ", path='" + path + '\'' + ", readOnly=" + readOnly + + '}'; + } } diff --git a/src/main/java/com/openshift/internal/restclient/okhttp/AuthenticatorInterceptor.java b/src/main/java/com/openshift/internal/restclient/okhttp/AuthenticatorInterceptor.java new file mode 100644 index 00000000..c88b3916 --- /dev/null +++ b/src/main/java/com/openshift/internal/restclient/okhttp/AuthenticatorInterceptor.java @@ -0,0 +1,166 @@ +/******************************************************************************* + * Copyright (c) 2019-2020 Red Hat, Inc. + * Distributed under license by Red Hat, Inc. All rights reserved. + * This program is made available under the terms of the + * Eclipse Public License v1.0 which accompanies this distribution, + * and is available at http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Red Hat, Inc. - initial API and implementation + ******************************************************************************/ + +package com.openshift.internal.restclient.okhttp; + +import java.io.IOException; +import java.net.URL; +import java.util.Map; + +import org.apache.commons.lang.StringUtils; + +import com.openshift.internal.restclient.AuthorizationEndpoints; +import com.openshift.internal.restclient.DefaultClient; +import com.openshift.internal.restclient.authorization.AuthorizationDetails; +import com.openshift.internal.util.URIUtils; +import com.openshift.restclient.IClient; +import com.openshift.restclient.authorization.IAuthorizationContext; +import com.openshift.restclient.authorization.IAuthorizationDetails; +import com.openshift.restclient.authorization.UnauthorizedException; +import com.openshift.restclient.http.IHttpConstants; + +import okhttp3.Headers; +import okhttp3.Interceptor; +import okhttp3.OkHttpClient; +import okhttp3.Request; +import okhttp3.Request.Builder; +import okhttp3.Response; + +/** + * Adds authorization means to every request. Authorizes and retrieves the token + * if it's not present yet. + */ +public class AuthenticatorInterceptor implements Interceptor, IHttpConstants { + + public static final String ACCESS_TOKEN = "access_token"; + private static final String CSRF_TOKEN = "X-CSRF-Token"; + private static final String ERROR = "error"; + private static final String ERROR_DETAILS = "error_details"; + + private IClient client; + + @Override + public Response intercept(Chain chain) throws IOException { + Request request = chain.request(); + String url = request.url().toString(); + if (AuthAttempHeader.isContainedIn(request.headers()) + || isUrlWithoutAuthorization(url)) { + return chain.proceed(request); + } + IAuthorizationContext authorizationContext = client.getAuthorizationContext(); + if (StringUtils.isBlank(authorizationContext.getToken())) { + request = createAuthorizationRequest(request, url, authorizationContext); + } + return chain.proceed(request); + } + + private Request createAuthorizationRequest(Request request, String url, IAuthorizationContext authorizationContext) throws IOException { + try (Response authResponse = authenticate()) { + if (authResponse != null) { + if (!authResponse.isSuccessful()) { + throw new UnauthorizedException(getAuthorizationDetails(url), + ResponseCodeInterceptor.getStatus(authResponse.body().string())); + } + String token = getToken(authResponse); + setToken(token, client.getAuthorizationContext()); + request = new OpenShiftRequestBuilder(request.newBuilder()).acceptJson() + .authorization(authorizationContext) + .build(); + } + return request; + } + } + + private boolean isUrlWithoutAuthorization(String url) { + return url.endsWith(DefaultClient.PATH_OPENSHIFT_VERSION) + || url.endsWith(DefaultClient.PATH_KUBERNETES_VERSION) + || url.endsWith(DefaultClient.PATH_HEALTH_CHECK) + || url.endsWith(AuthorizationEndpoints.PATH_OAUTH_AUTHORIZATION_SERVER) + || isAuthorizationEndpoint(url, client.getAuthorizationEndpoint()); + } + + private boolean isAuthorizationEndpoint(String url, URL authEndpoint) { + return authEndpoint != null + && url.startsWith(authEndpoint.toString()); + } + + private Response authenticate() throws IOException { + OkHttpClient okClient = client.adapt(OkHttpClient.class); + if (okClient == null) { + return null; + } + URL endpoint = client.getAuthorizationEndpoint(); + if (endpoint == null) { + return null; + } + Request authRequest = appendAuthorization( + client.getAuthorizationContext(), + new Request.Builder() + .addHeader(CSRF_TOKEN, "1") + .url(new URL(endpoint.toExternalForm() + + "?response_type=token&client_id=openshift-challenging-client").toString())); + return okClient.newBuilder() + .followRedirects(false) + .build() + .newCall(authRequest) + .execute(); + } + + private IAuthorizationDetails getAuthorizationDetails(String url) { + IAuthorizationDetails details = null; + Map pairs = URIUtils.splitFragment(url); + if (pairs.containsKey(ERROR)) { + details = new AuthorizationDetails(pairs.get(ERROR), pairs.get(ERROR_DETAILS)); + } + return details; + } + + private String getToken(Response response) { + if (response == null) { + return null; + } + String token = null; + Map pairs = URIUtils.splitFragment(response.header(PROPERTY_LOCATION)); + if (pairs.containsKey(ACCESS_TOKEN)) { + token = pairs.get(ACCESS_TOKEN); + } + return token; + } + + private void setToken(String token, IAuthorizationContext authorizationContext) { + if (authorizationContext != null) { + authorizationContext.setToken(token); + } + } + + public void setClient(IClient client) { + this.client = client; + } + + private Request appendAuthorization(IAuthorizationContext context, Builder builder) { + AuthAttempHeader.add(builder); + return new BasicChallengeHandler(context).handleChallenge(builder).build(); + } + + private static class AuthAttempHeader { + + private static final String AUTH_ATTEMPTS = "X-OPENSHIFT-AUTH-ATTEMPTS"; + + public static void add(Builder builder) { + builder.header(AUTH_ATTEMPTS, "1"); + } + + public static boolean isContainedIn(Headers headers) { + return headers != null + && headers.get(AUTH_ATTEMPTS) != null; + } + } +} diff --git a/src/main/java/com/openshift/internal/restclient/okhttp/BasicChallengeHandler.java b/src/main/java/com/openshift/internal/restclient/okhttp/BasicChallengeHandler.java new file mode 100644 index 00000000..6dbaa3bc --- /dev/null +++ b/src/main/java/com/openshift/internal/restclient/okhttp/BasicChallengeHandler.java @@ -0,0 +1,46 @@ +/******************************************************************************* + * Copyright (c) 2016 Red Hat, Inc. + * Distributed under license by Red Hat, Inc. All rights reserved. + * This program is made available under the terms of the + * Eclipse Public License v1.0 which accompanies this distribution, + * and is available at http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Red Hat, Inc. - initial API and implementation + ******************************************************************************/ + +package com.openshift.internal.restclient.okhttp; + +import org.apache.commons.lang.StringUtils; + +import com.openshift.restclient.authorization.IAuthorizationContext; +import com.openshift.restclient.http.IHttpConstants; + +import okhttp3.Credentials; +import okhttp3.Headers; +import okhttp3.Request.Builder; + +public class BasicChallengeHandler implements IChallengeHandler { + + private IAuthorizationContext context; + + public BasicChallengeHandler(IAuthorizationContext context) { + this.context = context; + } + + @Override + public boolean canHandle(Headers headers) { + String header = headers.get(IHttpConstants.PROPERTY_WWW_AUTHENTICATE); + return StringUtils.isNotEmpty(header) + && header.toLowerCase().startsWith(IHttpConstants.AUTHORIZATION_BASIC.toLowerCase()); + } + + @Override + public Builder handleChallenge(Builder builder) { + return builder.header(IHttpConstants.PROPERTY_AUTHORIZATION, + Credentials.basic( + StringUtils.defaultIfBlank(context.getUserName(), ""), + StringUtils.defaultIfBlank(context.getPassword(), ""))); + } + +} \ No newline at end of file diff --git a/src/main/java/com/openshift/internal/restclient/okhttp/IChallengeHandler.java b/src/main/java/com/openshift/internal/restclient/okhttp/IChallengeHandler.java new file mode 100644 index 00000000..eddda45f --- /dev/null +++ b/src/main/java/com/openshift/internal/restclient/okhttp/IChallengeHandler.java @@ -0,0 +1,39 @@ +/******************************************************************************* + * Copyright (c) 2016-2019 Red Hat, Inc. + * Distributed under license by Red Hat, Inc. All rights reserved. + * This program is made available under the terms of the + * Eclipse Public License v1.0 which accompanies this distribution, + * and is available at http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Red Hat, Inc. - initial API and implementation + ******************************************************************************/ + +package com.openshift.internal.restclient.okhttp; + +import okhttp3.Headers; +import okhttp3.Request; +import okhttp3.Request.Builder; + +/** + * A challenge handler that can retrieve a token + * + */ +interface IChallengeHandler { + + /** + * Is able to handle a challange given the auth mechanism provided in the header + * + * @param headers the headers + * @return true if can handle, false otherwise + */ + boolean canHandle(Headers headers); + + /** + * Handle the challange + * + * @param builder + * @return + */ + Request.Builder handleChallenge(Builder builder); +} \ No newline at end of file diff --git a/src/main/java/com/openshift/internal/restclient/okhttp/OpenShiftRequestBuilder.java b/src/main/java/com/openshift/internal/restclient/okhttp/OpenShiftRequestBuilder.java new file mode 100644 index 00000000..4765eb80 --- /dev/null +++ b/src/main/java/com/openshift/internal/restclient/okhttp/OpenShiftRequestBuilder.java @@ -0,0 +1,103 @@ +/******************************************************************************* + * Copyright (c) 2019 Red Hat, Inc. + * Distributed under license by Red Hat, Inc. All rights reserved. + * This program is made available under the terms of the + * Eclipse Public License v1.0 which accompanies this distribution, + * and is available at http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Red Hat, Inc. - initial API and implementation + ******************************************************************************/ + +package com.openshift.internal.restclient.okhttp; + +import static com.openshift.restclient.http.IHttpConstants.MEDIATYPE_APPLICATION_JSON; +import static com.openshift.restclient.http.IHttpConstants.PROPERTY_ACCEPT; + +import java.net.URL; + +import org.apache.commons.lang.StringUtils; + +import com.openshift.restclient.authorization.IAuthorizationContext; +import com.openshift.restclient.http.IHttpConstants; + +import okhttp3.Request; +import okhttp3.Request.Builder; +import okhttp3.RequestBody; + +public class OpenShiftRequestBuilder { + + private Builder builder; + + public OpenShiftRequestBuilder() { + this(new Builder()); + } + + public OpenShiftRequestBuilder(Builder builder) { + this.builder = builder; + } + + public OpenShiftRequestBuilder accept(String mediaType) { + builder.header(PROPERTY_ACCEPT, mediaType); + return this; + } + + public OpenShiftRequestBuilder acceptJson() { + builder.header(PROPERTY_ACCEPT, MEDIATYPE_APPLICATION_JSON); + return this; + } + + public OpenShiftRequestBuilder authorization(IAuthorizationContext authorizationContext) { + String token = null; + if (authorizationContext != null + && StringUtils.isNotBlank(authorizationContext.getToken())) { + token = authorizationContext.getToken(); + } + return authorization(token); + } + + public OpenShiftRequestBuilder authorization(String token) { + if (!StringUtils.isBlank(token)) { + builder.header(IHttpConstants.PROPERTY_AUTHORIZATION, IHttpConstants.AUTHORIZATION_BEARER + " " + token); + } + return this; + } + + public OpenShiftRequestBuilder url(URL url) { + builder.url(url); + return this; + } + + public OpenShiftRequestBuilder url(String url) { + builder.url(url); + return this; + } + + public OpenShiftRequestBuilder method(String method, RequestBody body) { + builder.method(method, body); + return this; + } + + public OpenShiftRequestBuilder addHeader(String key, String value) { + builder.addHeader(key, value); + return this; + } + + public OpenShiftRequestBuilder header(String key, String value) { + builder.header(key, value); + return this; + } + + public OpenShiftRequestBuilder tag(Object tag) { + builder.tag(tag); + return this; + } + + public Builder builder() { + return builder; + } + + public Request build() { + return builder.build(); + } +} diff --git a/src/main/java/com/openshift/internal/restclient/okhttp/ResponseCodeInterceptor.java b/src/main/java/com/openshift/internal/restclient/okhttp/ResponseCodeInterceptor.java new file mode 100644 index 00000000..0c151e14 --- /dev/null +++ b/src/main/java/com/openshift/internal/restclient/okhttp/ResponseCodeInterceptor.java @@ -0,0 +1,156 @@ +/******************************************************************************* + * Copyright (c) 2016 Red Hat, Inc. + * Distributed under license by Red Hat, Inc. All rights reserved. + * This program is made available under the terms of the + * Eclipse Public License v1.0 which accompanies this distribution, + * and is available at http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Red Hat, Inc. - initial API and implementation + ******************************************************************************/ + +package com.openshift.internal.restclient.okhttp; + +import java.io.IOException; + +import org.apache.commons.lang.StringUtils; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.openshift.internal.restclient.DefaultClient; +import com.openshift.internal.restclient.authorization.AuthorizationDetails; +import com.openshift.internal.restclient.model.Status; +import com.openshift.internal.util.URIUtils; +import com.openshift.restclient.BadRequestException; +import com.openshift.restclient.IClient; +import com.openshift.restclient.NotFoundException; +import com.openshift.restclient.OpenShiftException; +import com.openshift.restclient.authorization.ResourceForbiddenException; +import com.openshift.restclient.authorization.UnauthorizedException; +import com.openshift.restclient.http.IHttpConstants; +import com.openshift.restclient.model.IStatus; + +import okhttp3.Interceptor; +import okhttp3.Response; + +/** + * Interpret response codes and handle accordingly + * + */ +public class ResponseCodeInterceptor implements Interceptor, IHttpConstants { + + private static final Logger LOGGER = LoggerFactory.getLogger(ResponseCodeInterceptor.class); + + public static final String X_OPENSHIFT_IGNORE_RCI = "X-OPENSHIFT-IGNORE-RCI"; + + private IClient client; + + /** + * If a request tag() implements this interface, HTTP errors will not throw + * OpenShift exceptions. + */ + public interface Ignore { + } + + @Override + public Response intercept(Chain chain) throws IOException { + Response response = chain.proceed(chain.request()); + if (!response.isSuccessful() + && StringUtils.isBlank(response.request().header(X_OPENSHIFT_IGNORE_RCI))) { + switch (response.code()) { + case STATUS_UPGRADE_PROTOCOL: + case STATUS_MOVED_PERMANENTLY: + break; + case STATUS_MOVED_TEMPORARILY: + response = makeSuccessIfAuthorized(response); + break; + default: + if (!isIgnoreTagged(response)) { + throw createOpenShiftException(client, response, null); + } + } + } + return response; + } + + private boolean isIgnoreTagged(Response response) { + return response.request().tag() instanceof Ignore; + } + + private Response makeSuccessIfAuthorized(final Response response) { + Response returnedResponse = response; + String location = response.header(PROPERTY_LOCATION); + if (StringUtils.isNotBlank(location) + && URIUtils.splitFragment(location).containsKey(IHttpConstants.PROPERTY_ACCESS_TOKEN)) { + returnedResponse = response.newBuilder() + .request(response.request()) + .code(STATUS_OK) + .headers(response.headers()) + .build(); + response.close(); + } + return returnedResponse; + } + + public void setClient(DefaultClient client) { + this.client = client; + } + + public static IStatus getStatus(String response) { + if (response != null && response.startsWith("{")) { + return new Status(response); + } + return null; + } + + private static OpenShiftException createOpenShiftException(IClient client, Response response, Throwable e) + throws IOException { + LOGGER.debug(response.toString(), e); + IStatus status = getStatus(response.body().string()); + int responseCode = response.code(); + if (status != null && status.getCode() != 0) { + responseCode = status.getCode(); + } + switch (responseCode) { + case STATUS_BAD_REQUEST: + return new BadRequestException(e, status, response.request().url().toString()); + case STATUS_FORBIDDEN: + return new ResourceForbiddenException( + status != null ? status.getMessage() : "Resource Forbidden", status, e); + case STATUS_UNAUTHORIZED: + String link = String.format("%s/oauth/token/request", client.getBaseURL()); + AuthorizationDetails details = new AuthorizationDetails(response.headers(), link); + return new UnauthorizedException(details, status); + case IHttpConstants.STATUS_NOT_FOUND: + return new NotFoundException(e, status, status == null ? "Not Found" : status.getMessage()); + default: + return new OpenShiftException(e, status, "Exception trying to %s %s response code: %s", + response.request().method(), response.request().url().toString(), responseCode); + } + } + + public static OpenShiftException createOpenShiftException(IClient client, int responseCode, String message, + String response, Throwable e) { + LOGGER.debug(response, e); + IStatus status = getStatus(response); + if (status != null && status.getCode() != 0) { + responseCode = status.getCode(); + } + switch (responseCode) { + case STATUS_BAD_REQUEST: + return new BadRequestException(e, status, response); + case STATUS_FORBIDDEN: + return new ResourceForbiddenException(status != null ? status.getMessage() : "Resource Forbidden", status, + e); + case STATUS_UNAUTHORIZED: + return new UnauthorizedException( + client.getAuthorizationContext().getAuthorizationDetails(), status); + case IHttpConstants.STATUS_NOT_FOUND: + return new NotFoundException(status == null ? "Not Found" : status.getMessage()); + default: + return new OpenShiftException(e, status, "Exception trying to fetch %s response code: %s", response, + responseCode); + } + } + +} diff --git a/src/main/java/com/openshift/internal/restclient/okhttp/WatchClient.java b/src/main/java/com/openshift/internal/restclient/okhttp/WatchClient.java new file mode 100644 index 00000000..8ab9721d --- /dev/null +++ b/src/main/java/com/openshift/internal/restclient/okhttp/WatchClient.java @@ -0,0 +1,200 @@ +/******************************************************************************* + * Copyright (c) 2016-2018 Red Hat, Inc. + * Distributed under license by Red Hat, Inc. All rights reserved. + * This program is made available under the terms of the + * Eclipse Public License v1.0 which accompanies this distribution, + * and is available at http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Red Hat, Inc. - initial API and implementation + ******************************************************************************/ + +package com.openshift.internal.restclient.okhttp; + +import java.io.IOException; +import java.net.ProtocolException; +import java.util.ArrayList; +import java.util.Collection; +import java.util.Collections; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.concurrent.atomic.AtomicReference; + +import org.apache.commons.lang.StringUtils; +import org.jboss.dmr.ModelNode; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.openshift.internal.restclient.DefaultClient; +import com.openshift.internal.restclient.URLBuilder; +import com.openshift.internal.restclient.model.properties.ResourcePropertyKeys; +import com.openshift.restclient.IApiTypeMapper; +import com.openshift.restclient.IClient; +import com.openshift.restclient.IOpenShiftWatchListener; +import com.openshift.restclient.IOpenShiftWatchListener.ChangeType; +import com.openshift.restclient.IWatcher; +import com.openshift.restclient.http.IHttpConstants; +import com.openshift.restclient.model.IList; +import com.openshift.restclient.model.IResource; + +import okhttp3.OkHttpClient; +import okhttp3.Request; +import okhttp3.Response; +import okhttp3.WebSocket; +import okhttp3.WebSocketListener; + +public class WatchClient implements IWatcher, IHttpConstants { + + private static final Logger LOGGER = LoggerFactory.getLogger(WatchClient.class); + private DefaultClient client; + private OkHttpClient okClient; + private AtomicReference status = new AtomicReference<>(Status.Stopped); + private IApiTypeMapper typeMappings; + private Map endpointMap = Collections.synchronizedMap(new HashMap<>()); + + private enum Status { + Started, Starting, Stopped, Stopping + } + + public WatchClient(DefaultClient client, IApiTypeMapper typeMapper, OkHttpClient okClient) { + this.client = client; + this.typeMappings = typeMapper; + this.okClient = okClient; + } + + @Override + public void stop() { + if (status.compareAndSet(Status.Started, Status.Stopping)) { + Map endpoints = new HashMap<>(endpointMap); + endpointMap.clear(); + endpoints.values().forEach(w -> w.close()); + status.set(Status.Stopped); + } + } + + public IWatcher watch(Collection kinds, String namespace, IOpenShiftWatchListener listener) { + + if (status.compareAndSet(Status.Stopped, Status.Starting)) { + try { + for (String kind : kinds) { + WatchEndpoint socket = new WatchEndpoint(client, listener, kind); + final String resourceVersion = getResourceVersion(kind, namespace, socket); + + final String endpoint = new URLBuilder(client.getBaseURL(), this.typeMappings) + .kind(kind) + .namespace(namespace) + .watch() + .addParmeter(ResourcePropertyKeys.RESOURCE_VERSION, resourceVersion).websocket(); + Request request = new OpenShiftRequestBuilder() + .url(endpoint) + .acceptJson() + .authorization(client.getAuthorizationContext()) + .header(PROPERTY_ORIGIN, client.getBaseURL().toString()) + .header(PROPERTY_USER_AGENT, "openshift-restclient-java") + .build(); + okClient.newWebSocket(request, socket); + endpointMap.put(kind, socket); + } + status.set(Status.Started); + } catch (Exception e) { + endpointMap.clear(); + status.set(Status.Stopped); + throw ResponseCodeInterceptor.createOpenShiftException(client, 0, + String.format("Could not watch resources in namespace %s: %s", namespace, e.getMessage()), null, + e); + } + } + return this; + } + + private String getResourceVersion(String kind, String namespace, WatchEndpoint endpoint) throws Exception { + IList list = client.get(kind, namespace); + Collection items = list.getItems(); + List resources = new ArrayList<>(items.size()); + resources.addAll(items); + endpoint.setResources(resources); + return list.getResourceVersion(); + } + + static class WatchEndpoint extends WebSocketListener { + + private IOpenShiftWatchListener listener; + private List resources; + private final String kind; + private final IClient client; + private WebSocket wsClient; + + public WatchEndpoint(IClient client, IOpenShiftWatchListener listener, String kind) { + this.listener = listener; + this.kind = kind; + this.client = client; + } + + void close() { + try { + if (wsClient != null) { + wsClient.close(STATUS_NORMAL_STOP, "Client was asked to stop."); + wsClient = null; + } + listener.disconnected(); + } catch (Exception e) { + LOGGER.debug("Unable to stop the watch client", e); + } finally { + wsClient = null; + } + } + + public void setResources(List resources) { + this.resources = resources; + } + + @Override + public void onClosing(WebSocket socket, int statusCode, String reason) { + LOGGER.debug("WatchSocket closed for kind: {}, code: {}, reason: {}", + new Object[] { kind, statusCode, reason }); + listener.disconnected(); + } + + @Override + public void onFailure(WebSocket socket, Throwable err, Response response) { + LOGGER.debug("WatchSocket Error for kind {}: {}", kind, err); + try { + if (response == null) { + listener.error(ResponseCodeInterceptor.createOpenShiftException(client, 0, "", "", err)); + } else if (response.code() == IHttpConstants.STATUS_OK && err instanceof ProtocolException) { + // Just swallow it. Means the feature isn't supported in this OS server version + // yet. + // WebSocket creates error "Expected HTTP 101 response but was '200 OK'" + // This is described in the web socket specification. + LOGGER.debug("The feature isn't supported", err); + } else { + listener.error(ResponseCodeInterceptor.createOpenShiftException(client, response.code(), + response.body().string(), response.request().url().toString(), err)); + } + } catch (IOException e) { + LOGGER.error("IOException trying to notify listener of specific OpenShiftException", err); + listener.error(err); + } + } + + @Override + public void onMessage(WebSocket socket, String body) { + LOGGER.debug(body); + ModelNode node = ModelNode.fromJSONString(body); + IOpenShiftWatchListener.ChangeType event = new ChangeType(node.get("type").asString()); + IResource resource = client.getResourceFactory().create(node.get("object").toJSONString(true)); + if (StringUtils.isEmpty(resource.getKind())) { + LOGGER.error("Unable to determine resource kind from: " + node.get("object").toJSONString(false)); + } + listener.received(resource, event); + } + + @Override + public void onOpen(WebSocket socket, Response response) { + LOGGER.debug("WatchSocket connected for {}", kind); + wsClient = socket; + listener.connected(resources); + } + } +} diff --git a/src/main/java/com/openshift/internal/util/Assert.java b/src/main/java/com/openshift/internal/util/Assert.java index 11ea4a1d..b2f53186 100644 --- a/src/main/java/com/openshift/internal/util/Assert.java +++ b/src/main/java/com/openshift/internal/util/Assert.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2011 Red Hat, Inc. + * Copyright (c) 2011-2019 Red Hat, Inc. * Distributed under license by Red Hat, Inc. All rights reserved. * This program is made available under the terms of the * Eclipse Public License v1.0 which accompanies this distribution, @@ -8,40 +8,42 @@ * Contributors: * Red Hat, Inc. - initial API and implementation ******************************************************************************/ -package com.openshift.internal.util; - +package com.openshift.internal.util; /** * @author André Dietisheim */ public class Assert { - public static final class AssertionFailedException extends RuntimeException { - - private static final long serialVersionUID = 1L; - - public AssertionFailedException() { - super(); - } - - } - - public static V notNull(V value) { - if (value == null) { - throw new AssertionFailedException(); - } - return value; - } - - public static void notEmpty(String value) { - notNull(value); - isTrue(!value.isEmpty()); - } - - public static void isTrue(boolean assertion) { - if (!assertion) { - throw new AssertionFailedException(); - } - } + public static final class AssertionFailedException extends RuntimeException { + + private static final long serialVersionUID = 1L; + + public AssertionFailedException() { + super(); + } + + } + + private Assert() { + } + + public static V notNull(V value) { + if (value == null) { + throw new AssertionFailedException(); + } + return value; + } + + public static void notEmpty(String value) { + notNull(value); + isTrue(!value.isEmpty()); + } + + public static void isTrue(boolean assertion) { + if (!assertion) { + throw new AssertionFailedException(); + } + } } diff --git a/src/main/java/com/openshift/internal/util/JBossDmrExtentions.java b/src/main/java/com/openshift/internal/util/JBossDmrExtentions.java index 1823f0d6..8cc7d26b 100644 --- a/src/main/java/com/openshift/internal/util/JBossDmrExtentions.java +++ b/src/main/java/com/openshift/internal/util/JBossDmrExtentions.java @@ -6,6 +6,7 @@ * * Contributors: Red Hat, Inc. ******************************************************************************/ + package com.openshift.internal.util; import java.io.PrintWriter; @@ -24,244 +25,275 @@ import org.jboss.dmr.ModelType; /** - * Helper extensions to those provided - * by JBoss DMR library + * Helper extensions to those provided by JBoss DMR library * - * @author Jeff Cantrill */ public class JBossDmrExtentions { - - private JBossDmrExtentions (){ - } - - /** - * Serialize a node and sanitize the output - * by removing nulls - * @param node - * @param compact - * @return - */ - public static String toJsonString(ModelNode node, boolean compact) { - sanitize(node); - StringWriter writer = new StringWriter(); - node.writeJSONString(new PrintWriter(writer,true), compact); - return writer.toString(); - } - - private static void sanitize(ModelNode node) { - if(node.getType() == ModelType.OBJECT) { - Collection emptyKeys = new ArrayList<>(node.keys().size()); - for (String key : node.keys()) { - ModelNode child = node.get(key); - if(child.getType() == ModelType.UNDEFINED) { - emptyKeys.add(key); - }else { - sanitize(child); - } - if(child.getType() == ModelType.LIST) { - List entries = child.asList(); - if(entries.isEmpty()) { - emptyKeys.add(key); - } else { - final int listSize = entries.size(); - List nulls = new ArrayList<>(listSize); - for (int i=0; i < listSize; ++i) { - ModelNode e = entries.get(i); - if(!e.isDefined()) { - nulls.add(i); - }else { - sanitize(e); - } - } - Collections.reverse(nulls); - nulls.stream().forEach((i)->child.remove(i)); - if(child.asList().size() == 0) { - emptyKeys.add(key); - } - } - - } - } - emptyKeys.stream().forEach((key)->node.remove(key)); - } - } - - public static void set(ModelNode node, Map propertyKeys, String key, boolean value){ - if(propertyKeys == null) return; - ModelNode modelNode = node.get(getPath(propertyKeys, key)); - modelNode.set(value); - } - public static void set(ModelNode node, Map propertyKeys, String key, String value){ - if(propertyKeys == null) return; - set(node, getPath(propertyKeys, key), value); - } + private JBossDmrExtentions() { + } + + /** + * Serialize a node and sanitize the output by removing nulls + * + */ + public static String toJsonString(ModelNode node, boolean compact) { + sanitize(node); + StringWriter writer = new StringWriter(); + node.writeJSONString(new PrintWriter(writer, true), compact); + return writer.toString(); + } + + private static void sanitize(ModelNode node) { + if (node.getType() == ModelType.OBJECT) { + Collection emptyKeys = new ArrayList<>(node.keys().size()); + for (String key : node.keys()) { + ModelNode child = node.get(key); + if (child.getType() == ModelType.UNDEFINED) { + emptyKeys.add(key); + } else { + sanitize(child); + } + if (child.getType() == ModelType.LIST) { + List entries = child.asList(); + if (entries.isEmpty()) { + emptyKeys.add(key); + } else { + final int listSize = entries.size(); + List nulls = new ArrayList<>(listSize); + for (int i = 0; i < listSize; ++i) { + ModelNode e = entries.get(i); + if (!e.isDefined()) { + nulls.add(i); + } else { + sanitize(e); + } + } + Collections.reverse(nulls); + nulls.stream().forEach((i) -> child.remove(i)); + if (child.asList().size() == 0) { + emptyKeys.add(key); + } + } + + } + } + emptyKeys.stream().forEach((key) -> node.remove(key)); + } + } + + public static void set(ModelNode node, Map propertyKeys, String key, boolean value) { + if (propertyKeys == null) { + return; + } + ModelNode modelNode = node.get(getPath(propertyKeys, key)); + modelNode.set(value); + } + + public static void set(ModelNode node, Map propertyKeys, String key, String value) { + if (propertyKeys == null) { + return; + } + set(node, getPath(propertyKeys, key), value); + } + + public static void set(ModelNode node, String[] path, String value) { + if (value == null) { + return; + } + ModelNode modelNode = node.get(path); + modelNode.set(value); + } + + public static void set(ModelNode node, Map propertyKeys, String key, int value) { + if (propertyKeys == null) { + return; + } + ModelNode modelNode = node.get(getPath(propertyKeys, key)); + modelNode.set(value); + } + + public static void set(ModelNode node, Map propertyKeys, String key, Map values) { + if (propertyKeys == null) { + return; + } + ModelNode modelNode = node.get(getPath(propertyKeys, key)); + for (Entry entry : values.entrySet()) { + modelNode.get(entry.getKey()).set(entry.getValue()); + } + } + + public static void set(ModelNode root, Map propertyKeys, String key, Set values) { + String[] path = getPath(propertyKeys, key); + ModelNode node = root.get(path); + for (String entry : values) { + node.add(entry); + } + } + + public static void set(ModelNode root, Map propertyKeys, String key, String... values) { + String[] path = getPath(propertyKeys, key); + ModelNode node = root.get(path); + for (String value : values) { + node.add(value); + } + } + + /** + * + * @throws UnregisteredPropertyException + * if the property is not found in the property map + */ + public static Map asMap(ModelNode root, Map propertyKeys, String key) { + HashMap map = new HashMap(); + if (propertyKeys != null) { + String[] path = getPath(propertyKeys, key); + if (root.has(path)) { + ModelNode node = root.get(path); + if (!node.isDefined()) { + return map; + } + for (String k : node.keys()) { + map.put(k, node.get(k).asString()); + } + } + } + return map; + } + + /** + * T the type to return which are valid DMR types (e.g. asString()). String is + * currently only supported. Add more as needed + * + */ + @SuppressWarnings({ "rawtypes", "unchecked" }) + public static Set asSet(ModelNode root, Map propertyKeys, String key, ModelType type) { + Set set = new HashSet(); + String[] path = getPath(propertyKeys, key); + if (root.has(path)) { + ModelNode node = root.get(path); + if (!node.isDefined()) { + return set; + } + for (ModelNode entry : node.asList()) { + Object instance = null; + switch (type) { + case STRING: + instance = entry.asString(); + break; + case BOOLEAN: + instance = entry.asBoolean(); + break; + case INT: + instance = entry.asInt(); + break; + default: + } + set.add(instance); + } + } + return set; + } + + /** + * T Returns an ordered List for items that need to be ordered such as command + * Args for containers. + * + */ + @SuppressWarnings({ "rawtypes", "unchecked" }) + public static List asList(ModelNode root, Map propertyKeys, String key, ModelType type) { + List list = new ArrayList(); + String[] path = getPath(propertyKeys, key); + if (root.has(path)) { + ModelNode node = root.get(path); + if (!node.isDefined()) { + return list; + } + for (ModelNode entry : node.asList()) { + Object instance = null; + switch (type) { + case STRING: + instance = entry.asString(); + break; + case BOOLEAN: + instance = entry.asBoolean(); + break; + case INT: + instance = entry.asInt(); + break; + default: + } + list.add(instance); + } + } + return list; + } + + + /** + * + * @throws UnregisteredPropertyException + * if the property is not found in the property map + */ + public static int asInt(ModelNode node, Map propertyKeys, String key) { + String[] path = getPath(propertyKeys, key); + if (node.has(path)) { + ModelNode modelNode = node.get(path); + if (!modelNode.isDefined()) { + return 0; + } + return modelNode.asInt(); + } + return 0; + } - public static void set(ModelNode node, String [] path, String value){ - if(value == null) return; - ModelNode modelNode = node.get(path); - modelNode.set(value); - } - - public static void set(ModelNode node, Map propertyKeys, String key, int value) { - if(propertyKeys == null) return; - ModelNode modelNode = node.get(getPath(propertyKeys, key)); - modelNode.set(value); - } + /** + * + * @throws UnregisteredPropertyException + * if the property is not found in the property map + */ + public static String asString(ModelNode node, Map propertyKeys, String key) { + String[] path = getPath(propertyKeys, key); + if (!node.has(path)) { + return ""; + } + ModelNode modelNode = node.get(path); + if (!modelNode.isDefined()) { + return ""; + } + return modelNode.asString(); + } - public static void set(ModelNode node, Map propertyKeys, String key, Map values) { - if(propertyKeys == null) return; - ModelNode modelNode = node.get(getPath(propertyKeys, key)); - for (Entry entry : values.entrySet()) { - modelNode.get(entry.getKey()).set(entry.getValue()); - } - } + /** + * + * @throws UnregisteredPropertyException + * if the property is not found in the property map + */ + public static boolean asBoolean(ModelNode node, Map propertyKeys, String key) { + String[] path = getPath(propertyKeys, key); + if (!node.has(path)) { + return false; + } + ModelNode modelNode = node.get(path); + if (!modelNode.isDefined()) { + return false; + } + return modelNode.asBoolean(); + } - /** - * - * @param root - * @param propertyKeys - * @param key - * @return - * @throws UnregisteredPropertyException if the property is not found in the property map - */ - public static Map asMap(ModelNode root, Map propertyKeys, String key){ - HashMap map = new HashMap(); - if(propertyKeys != null){ - String [] path = getPath(propertyKeys, key); - if(root.has(path)) { - ModelNode node = root.get(path); - if( !node.isDefined()) - return map; - for (String k : node.keys()) { - map.put(k, node.get(k).asString()); - } - } - } - return map; - } + public static ModelNode get(ModelNode node, Map propertyKeys, String key) { + return node.get(getPath(propertyKeys, key)); + } - /** - * the type to return which are valid DMR types (e.g. asString()). - * String is currently only supported. Add more as needed - * @param root - * @param propertyKeys - * @param key - * @param type - * @return - */ - @SuppressWarnings({ "rawtypes", "unchecked" }) - public static Set asSet(ModelNode root, Map propertyKeys, String key, ModelType type){ - Set set = new HashSet(); - String [] path = getPath(propertyKeys, key); - if(root.has(path)){ - ModelNode node = root.get(path); - if( !node.isDefined()) - return set; - for (ModelNode entry : node.asList()) { - Object instance = null; - switch(type) { - case STRING: - instance = entry.asString(); - break; - case BOOLEAN: - instance = entry.asBoolean(); - break; - case INT: - instance = entry.asInt(); - default: - } - set.add(instance); - } - } - return set; - } - - public static void set(ModelNode root, Map propertyKeys, String key, Set values) { - String [] path = getPath(propertyKeys, key); - ModelNode node = root.get(path); - for (String entry : values) { - node.add(entry); - } - } + public static String[] getPath(Map propertyKeys, String key) { + if (propertyKeys != null && propertyKeys.containsKey(key)) { + return propertyKeys.get(key); // allow override + } + return key.split("\\."); + } - public static void set(ModelNode root, Map propertyKeys, String key, String... values) { - String [] path = getPath(propertyKeys, key); - ModelNode node = root.get(path); - for (String value : values) { - node.add(value); - } - } - - /** - * - * @param node - * @param propertyKeys - * @param key - * @return - * @throws UnregisteredPropertyException if the property is not found in the property map - */ - public static int asInt(ModelNode node, Map propertyKeys, String key){ - String [] path = getPath(propertyKeys, key); - if(node.has(path)) { - ModelNode modelNode = node.get(path); - if( !modelNode.isDefined()){ - return 0; - } - return modelNode.asInt(); - } - return 0; - } - - /** - * - * @param node - * @param propertyKeys - * @param key - * @return - * @throws UnregisteredPropertyException if the property is not found in the property map - */ - public static String asString(ModelNode node, Map propertyKeys, String key){ - String[] path = getPath(propertyKeys, key); - if(!node.has(path)) return ""; - ModelNode modelNode = node.get(path); - if( !modelNode.isDefined()){ - return ""; - } - return modelNode.asString(); - } - - /** - * - * @param node - * @param propertyKeys - * @param key - * @return - * @throws UnregisteredPropertyException if the property is not found in the property map - */ - public static boolean asBoolean(ModelNode node, Map propertyKeys, String key) { - String [] path = getPath(propertyKeys, key); - if(!node.has(path)) return false; - ModelNode modelNode = node.get(path); - if( !modelNode.isDefined()){ - return false; - } - return modelNode.asBoolean(); - } - - public static ModelNode get(ModelNode node, Map propertyKeys, String key){ - return node.get(getPath(propertyKeys,key)); - } - - public static String[] getPath(Map propertyKeys, String key) { - if(propertyKeys != null && propertyKeys.containsKey(key)) { - return propertyKeys.get(key); //allow override - } - return key.split("\\."); - } - - @SuppressWarnings("unchecked") - public static String[] getPath(String key) { - return getPath(Collections.EMPTY_MAP, key); - } + @SuppressWarnings("unchecked") + public static String[] getPath(String key) { + return getPath(Collections.EMPTY_MAP, key); + } } diff --git a/src/main/java/com/openshift/internal/util/StringSplitter.java b/src/main/java/com/openshift/internal/util/StringSplitter.java new file mode 100644 index 00000000..80bb347f --- /dev/null +++ b/src/main/java/com/openshift/internal/util/StringSplitter.java @@ -0,0 +1,55 @@ +/******************************************************************************* + * Copyright (c) 2018 Red Hat, Inc. + * Distributed under license by Red Hat, Inc. All rights reserved. + * This program is made available under the terms of the + * Eclipse Public License v1.0 which accompanies this distribution, + * and is available at http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Red Hat, Inc. - initial API and implementation + ******************************************************************************/ + +package com.openshift.internal.util; + +import java.util.ArrayList; +import java.util.List; + +public class StringSplitter { + private StringSplitter() { + } + + public static List split(String str, List result) { + boolean inQuote = false; + StringBuilder builder = new StringBuilder(); + + for (int i = 0; i < str.length(); ++i) { + char c = str.charAt(i); + if (inQuote) { + if (c == '"') { + inQuote = false; + } else { + builder.append(c); + } + } else if (c == '"') { + inQuote = true; + } else if (c == ' ') { + if (builder.length() > 0) { + result.add(builder.toString()); + builder = new StringBuilder(); + } + } else { + builder.append(c); + } + } + if (builder.length() > 0) { + result.add(builder.toString()); + } + return result; + } + + public static List split(String str) { + List result = new ArrayList<>(); + return split(str, result); + } + +} diff --git a/src/main/java/com/openshift/internal/util/URIUtils.java b/src/main/java/com/openshift/internal/util/URIUtils.java index 60539769..b238e3a9 100644 --- a/src/main/java/com/openshift/internal/util/URIUtils.java +++ b/src/main/java/com/openshift/internal/util/URIUtils.java @@ -6,48 +6,65 @@ * * Contributors: Red Hat, Inc. ******************************************************************************/ + package com.openshift.internal.util; +import java.io.UnsupportedEncodingException; import java.net.URI; import java.net.URISyntaxException; +import java.net.URLDecoder; import java.nio.charset.StandardCharsets; +import java.util.Collections; import java.util.HashMap; import java.util.Map; -import org.apache.http.NameValuePair; -import org.apache.http.client.utils.URLEncodedUtils; +import org.apache.commons.lang.StringUtils; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; /** * Helper methods for manipulating URIs * - * @author Jeff Cantrill */ public class URIUtils { - - private URIUtils(){ - } - - public static Map splitFragment(String location){ - URI uri = null; - try { - uri = new URI(location); - } catch (URISyntaxException e) { - throw new RuntimeException(e); - } - return splitFragment(uri); - } - - public static Map splitFragment(URI uri){ - return splitQuery(uri.getFragment()); - } - - public static Map splitQuery(String q) { - HashMap params = new HashMap(); - if (q != null) { - for (NameValuePair pair : URLEncodedUtils.parse(q, StandardCharsets.UTF_8)) { - params.put(pair.getName(), pair.getValue()); - } - } - return params; - } + private static final Logger LOG = LoggerFactory.getLogger(URIUtils.class); + + private URIUtils() { + } + + public static Map splitFragment(String location) { + if (StringUtils.isEmpty(location)) { + return Collections.emptyMap(); + } + URI uri = null; + try { + uri = new URI(location); + } catch (URISyntaxException e) { + throw new RuntimeException(e); + } + return splitFragment(uri); + } + + public static Map splitFragment(URI uri) { + return splitQuery(uri.getFragment()); + } + + public static Map splitQuery(String q) { + HashMap params = new HashMap(); + if (q != null) { + try { + String decoded = URLDecoder.decode(q, StandardCharsets.UTF_8.toString()); + String[] split = decoded.split("&"); + for (String pair : split) { + String[] keyValue = pair.split("="); + if (keyValue.length >= 2) { + params.put(keyValue[0], keyValue[1]); + } + } + } catch (UnsupportedEncodingException e) { + LOG.error("Unable to decode " + q, e); + } + } + return params; + } } diff --git a/src/main/java/com/openshift/internal/util/URLUtils.java b/src/main/java/com/openshift/internal/util/URLUtils.java index e38055a3..c79fdb34 100644 --- a/src/main/java/com/openshift/internal/util/URLUtils.java +++ b/src/main/java/com/openshift/internal/util/URLUtils.java @@ -8,6 +8,7 @@ * Contributors: * Red Hat, Inc. - initial API and implementation ******************************************************************************/ + package com.openshift.internal.util; import java.net.URL; @@ -18,61 +19,57 @@ */ public class URLUtils { - private static final Pattern URL_PATTERN = Pattern - .compile("(https?|ftp)://[-a-zA-Z0-9+&@#/%?=~_|!:,.;]*[-a-zA-Z0-9+&@#/%=~_|]"); + private static final Pattern URL_PATTERN = Pattern + .compile("(https?|ftp)://[-a-zA-Z0-9+&@#/%?=~_|!:,.;]*[-a-zA-Z0-9+&@#/%=~_|]"); + + private static final String HTTPS = "https"; + private static final String HTTP = "http"; + private static final String SCHEMA_SEPARATOR = "://"; - private static final String HTTPS = "https"; - private static final String HTTP = "http"; - private static final String SCHEMA_SEPARATOR = "://"; + public static final String SCHEME_HTTP = HTTP + SCHEMA_SEPARATOR; + public static final String SCHEME_HTTPS = HTTPS + SCHEMA_SEPARATOR; + public static final char USERNAME_SEPARATOR = '@'; - public static final String SCHEME_HTTP = HTTP + SCHEMA_SEPARATOR; - public static final String SCHEME_HTTPS = HTTPS + SCHEMA_SEPARATOR; - public static final char USERNAME_SEPARATOR = '@'; + private URLUtils() { + // inhibit instantiation + } - private URLUtils() { - // inhibit instantiation - } + public static String ensureStartsWithHttps(String url) { + if (url == null || url.isEmpty()) { + return url; + } - public static String ensureStartsWithHttps(String url) { - if (url == null - || url.isEmpty()) { - return url; - } + if (url.indexOf(SCHEMA_SEPARATOR) > 0) { + return url; + } - if (url.indexOf(SCHEMA_SEPARATOR) > 0) { - return url; - } + return new StringBuilder(HTTPS).append(SCHEMA_SEPARATOR).append(url).toString(); + } - return new StringBuilder(HTTPS) - .append(SCHEMA_SEPARATOR) - .append(url) - .toString(); - } + public static boolean isUrl(String string) { + return URL_PATTERN.matcher(string).matches(); + } - public static boolean isUrl(String string) { - return URL_PATTERN.matcher(string).matches(); - } + public static String appendPath(String parent, String child) { + if (parent.charAt(parent.length() - 1) == '/') { + if (child.charAt(0) == '/') { + return parent + child.substring(1); + } else { + return parent + child; + } + } else { + if (child.charAt(0) == '/') { + return parent + child; + } else { + return new StringBuilder(parent).append('/').append(child).toString(); + } + } + } - public static String appendPath(String parent, String child) { - if (parent.charAt(parent.length() - 1) == '/') { - if (child.charAt(0) == '/') { - return parent + child.substring(1); - } else { - return parent + child; - } - } else { - if (child.charAt(0) == '/') { - return parent + child; - } else { - return new StringBuilder(parent).append('/').append(child).toString(); - } - } - } - - public static String toString(URL url) { - if (url == null) { - return null; - } - return url.toString(); - } + public static String toString(URL url) { + if (url == null) { + return null; + } + return url.toString(); + } } diff --git a/src/main/java/com/openshift/internal/util/UnregisteredPropertyException.java b/src/main/java/com/openshift/internal/util/UnregisteredPropertyException.java index cc66fa6a..8a845345 100644 --- a/src/main/java/com/openshift/internal/util/UnregisteredPropertyException.java +++ b/src/main/java/com/openshift/internal/util/UnregisteredPropertyException.java @@ -8,17 +8,13 @@ * Contributors: * Red Hat, Inc. - initial API and implementation ******************************************************************************/ + package com.openshift.internal.util; -/** - * - * @author Jeff Cantrill - * - */ @SuppressWarnings("serial") public class UnregisteredPropertyException extends RuntimeException { - public UnregisteredPropertyException(String property) { - super(String.format("No path was found for property '%s' in the property map.", property)); - } + public UnregisteredPropertyException(String property) { + super(String.format("No path was found for property '%s' in the property map.", property)); + } } diff --git a/src/main/java/com/openshift/restclient/BadRequestException.java b/src/main/java/com/openshift/restclient/BadRequestException.java new file mode 100644 index 00000000..a259f6f0 --- /dev/null +++ b/src/main/java/com/openshift/restclient/BadRequestException.java @@ -0,0 +1,32 @@ +/******************************************************************************* + * Copyright (c) 2016 Red Hat, Inc. + * Distributed under license by Red Hat, Inc. All rights reserved. + * This program is made available under the terms of the + * Eclipse Public License v1.0 which accompanies this distribution, + * and is available at http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Red Hat, Inc. - initial API and implementation + ******************************************************************************/ + +package com.openshift.restclient; + +import com.openshift.restclient.model.IStatus; + +/** + * The exception thrown when the client is trying to submit a request to with + * parameters that are not accepted by the server + * + */ +public class BadRequestException extends OpenShiftException { + + /** + * + */ + private static final long serialVersionUID = -333562634088784896L; + + public BadRequestException(Throwable e, IStatus status, String endpoint) { + super(e, status, "%s", endpoint); + } + +} diff --git a/src/main/java/com/openshift/restclient/ClientBuilder.java b/src/main/java/com/openshift/restclient/ClientBuilder.java index 5571f611..62ea8dcf 100644 --- a/src/main/java/com/openshift/restclient/ClientBuilder.java +++ b/src/main/java/com/openshift/restclient/ClientBuilder.java @@ -8,123 +8,387 @@ * Contributors: * Red Hat, Inc. - initial API and implementation ******************************************************************************/ + package com.openshift.restclient; -import java.net.MalformedURLException; +import java.io.IOException; +import java.net.Proxy; +import java.net.ProxySelector; import java.net.URL; +import java.security.KeyManagementException; +import java.security.KeyStore; +import java.security.KeyStoreException; +import java.security.NoSuchAlgorithmException; +import java.security.cert.CertificateException; import java.security.cert.X509Certificate; +import java.util.Collection; +import java.util.concurrent.TimeUnit; +import javax.net.ssl.SSLContext; +import javax.net.ssl.TrustManager; +import javax.net.ssl.TrustManagerFactory; +import javax.net.ssl.X509TrustManager; + +import org.apache.commons.lang.ObjectUtils; +import org.apache.commons.lang.StringUtils; import com.openshift.internal.restclient.DefaultClient; import com.openshift.internal.restclient.ResourceFactory; -import com.openshift.restclient.authorization.IAuthorizationStrategy; +import com.openshift.internal.restclient.authorization.AuthorizationContext; +import com.openshift.internal.restclient.okhttp.AuthenticatorInterceptor; +import com.openshift.internal.restclient.okhttp.ResponseCodeInterceptor; +import com.openshift.restclient.http.IHttpConstants; +import com.openshift.restclient.utils.SSLUtils; + +import okhttp3.Authenticator; +import okhttp3.Dispatcher; +import okhttp3.Interceptor; +import okhttp3.OkHttp; +import okhttp3.OkHttpClient; +import okhttp3.Request; +import okhttp3.Response; /** * Builder to create IClient instances. - * @author jeff.cantrill * */ public class ClientBuilder { - - private String baseUrl; - private ISSLCertificateCallback sslCertificateCallback; - private X509Certificate certificate; - private String certificateAlias; - private IResourceFactory resourceFactory; - private IAuthorizationStrategy authStrategy; - private String withUserName; - private Object token; - private int connectTimeoutMillies; - - public ClientBuilder() { - this(null); - } - - public ClientBuilder(String baseUrl) { - this.baseUrl = baseUrl; - } - - public ClientBuilder sslCertificateCallback(ISSLCertificateCallback callback) { - this.sslCertificateCallback = callback; - return this; - } - - public ClientBuilder sslCertificate(String alias, X509Certificate cert) { - this.certificateAlias = alias; - this.certificate = cert; - return this; - } - - public ClientBuilder resourceFactory(IResourceFactory factory) { - this.resourceFactory = factory; - return this; - } - - @Deprecated - public ClientBuilder resourceFactory(IAuthorizationStrategy authStrategy) { - this.authStrategy = authStrategy; - return this; - } - - public ClientBuilder authorizationStrategy(IAuthorizationStrategy authStrategy) { - this.authStrategy = authStrategy; - return this; - } - - public ClientBuilder toCluster(String baseUrl) { - this.baseUrl = baseUrl; - return this; - } - - public ClientBuilder withUserName(String userName) { - this.withUserName = userName; - return this; - } - - public ClientBuilder usingToken(String userName) { - this.token = token; - return this; - } - - /** - * The connect timeout parameter used for establishing - * the connection to a remote server - * @param connectInMillis A value in milliseconds - * @return - */ - public ClientBuilder withConnectTimeout(int connectInMillis) { - this.connectTimeoutMillies = connectInMillis; - return this; - } - - /** - * Build a client using the config loading rules defined http://janetkuo.github.io/kubernetes/v1.0/docs/user-guide/kubeconfig-file.html. Brief summary - * of loading order: - * - * 1. use explicit values set in builder - * a. username/token - * b. authStrategy - * 2. currentContext of config file located at $KUBECONFIG - * 3. currentContext of config file located at ~/.kube/config - * - * @return - */ - public IClient build() { - try { - ISSLCertificateCallback sslCallback = defaultIfNull(this.sslCertificateCallback, new NoopSSLCertificateCallback()); - IResourceFactory factory = defaultIfNull(resourceFactory, new ResourceFactory(null)); - DefaultClient client = new DefaultClient(new URL(this.baseUrl), null, sslCallback, factory, certificateAlias, certificate, connectTimeoutMillies); - - client.setAuthorizationStrategy(authStrategy); - - return client; - } catch (MalformedURLException e) { - throw new OpenShiftException(e, ""); - } - } - - private T defaultIfNull(T value, T aDefault) { - if(value != null) - return value; - return aDefault; - } + + private String baseUrl; + private ISSLCertificateCallback sslCertificateCallback = new NoopSSLCertificateCallback(); + private boolean sslCertCallbackWithDefaultHostnameVerifier = false; + private X509Certificate certificate; + private Collection certificateCollection; + private String certificateAlias; + private IResourceFactory resourceFactory; + private String userName; + private String token; + private String password; + private String userAgentPrefix; + + private Proxy proxy; + private ProxySelector proxySelector; + private Authenticator proxyAuthenticator; + + private int maxRequests = 64; + private int maxRequestsPerHost = 10; + + private int readTimeout = IHttpConstants.DEFAULT_READ_TIMEOUT; + private TimeUnit readTimeoutUnit = TimeUnit.MILLISECONDS; + private int connectTimeout = IHttpConstants.DEFAULT_READ_TIMEOUT; + private TimeUnit connectTimeoutUnit = TimeUnit.MILLISECONDS; + private int writeTimeout = IHttpConstants.DEFAULT_READ_TIMEOUT; + private TimeUnit writeTimeoutUnit = TimeUnit.MILLISECONDS; + private int pingInterval = 0; + private TimeUnit pingIntervalUnit = TimeUnit.MILLISECONDS; + + public ClientBuilder() { + this(null); + } + + public ClientBuilder(String baseUrl) { + this.baseUrl = baseUrl; + } + + public ClientBuilder sslCertificateCallback(ISSLCertificateCallback callback) { + this.sslCertificateCallback = callback == null ? new NoopSSLCertificateCallback() : callback; + return this; + } + + public ClientBuilder sslCertCallbackWithDefaultHostnameVerifier(boolean b) { + this.sslCertCallbackWithDefaultHostnameVerifier = b; + return this; + } + + public ClientBuilder sslCertificate(String alias, X509Certificate cert) { + this.certificateAlias = alias; + this.certificate = cert; + return this; + } + + public ClientBuilder sslCertificateCollection(String alias, Collection certs) { + this.certificateAlias = alias; + this.certificateCollection = certs; + return this; + } + + public ClientBuilder resourceFactory(IResourceFactory factory) { + this.resourceFactory = factory; + return this; + } + + public ClientBuilder toCluster(String baseUrl) { + this.baseUrl = baseUrl; + return this; + } + + public ClientBuilder withUserName(String userName) { + this.userName = userName; + return this; + } + + public ClientBuilder withPassword(String password) { + this.password = password; + return this; + } + + public ClientBuilder usingToken(String token) { + this.token = token; + return this; + } + + public ClientBuilder usingUserAgentPrefix(String prefix) { + this.userAgentPrefix = prefix; + return this; + } + + public ClientBuilder withConnectTimeout(int timeout, TimeUnit unit) { + this.connectTimeout = timeout; + this.connectTimeoutUnit = unit; + return this; + } + + /** + * The connect timeout parameter used for establishing the connection to a + * remote server + * + * @param connectInMillis + * A value in milliseconds + */ + public ClientBuilder withConnectTimeout(int connectInMillis) { + this.connectTimeout = connectInMillis; + return this; + } + + public ClientBuilder withReadTimeout(int timeout, TimeUnit unit) { + this.readTimeout = timeout; + this.readTimeoutUnit = unit; + return this; + } + + public ClientBuilder withWriteTimeout(int timeout, TimeUnit unit) { + this.writeTimeout = timeout; + this.writeTimeoutUnit = unit; + return this; + } + + public ClientBuilder withPingInterval(int pingInterval, TimeUnit unit) { + this.pingInterval = pingInterval; + this.pingIntervalUnit = unit; + return this; + } + + public ClientBuilder proxy(Proxy proxy) { + this.proxy = proxy; + return this; + } + + public ClientBuilder proxySelector(ProxySelector proxySelector) { + this.proxySelector = proxySelector; + return this; + } + + + public ClientBuilder proxyAuthenticator(Authenticator proxyAuthenticator) { + this.proxyAuthenticator = proxyAuthenticator; + return this; + } + + + /** + * The maximum concurrent requests for this client. + * + * @param maxRequests + * the maximum number of concurrent requests + * @return the client builder + */ + public ClientBuilder withMaxRequests(int maxRequests) { + this.maxRequests = maxRequests; + return this; + } + + /** + * The maximum concurrent request for this client for a single host. + * + * @param maxRequestsPerHost + * the maximum number of concurrent requests for a single host + * @return the client builder + */ + public ClientBuilder withMaxRequestsPerHost(int maxRequestsPerHost) { + this.maxRequestsPerHost = maxRequestsPerHost; + return this; + } + + /** + * Build a client + * + * @throws KeyManagementException an exception + */ + public IClient build() { + try { + TrustManagerFactory trustManagerFactory = initTrustManagerFactory(certificateAlias, certificate, + certificateCollection); + X509TrustManager trustManager = getCurrentTrustManager(trustManagerFactory); + SSLContext sslContext = SSLUtils.getSSLContext(trustManager); + + AuthenticatorInterceptor authenticatorInterceptor = new AuthenticatorInterceptor(); + ResponseCodeInterceptor responseCodeInterceptor = new ResponseCodeInterceptor(); + Dispatcher dispatcher = createDispatcher(); + + OkHttpClient okClient = + createOkHttpClient(trustManager, sslContext, authenticatorInterceptor, responseCodeInterceptor, dispatcher); + + IResourceFactory factory = (IResourceFactory) ObjectUtils.defaultIfNull(resourceFactory, new ResourceFactory(null)); + AuthorizationContext authContext = new AuthorizationContext(token, userName, password); + DefaultClient client = new DefaultClient(new URL(this.baseUrl), okClient, factory, null, authContext); + + authContext.setClient(client); + authenticatorInterceptor.setClient(client); + responseCodeInterceptor.setClient(client); + factory.setClient(client); + return client; + } catch (KeyManagementException | NoSuchAlgorithmException | KeyStoreException | CertificateException + | IOException e) { + throw new OpenShiftException(e, "Unable to initialize client"); + } + } + + private Dispatcher createDispatcher() { + Dispatcher dispatcher = new Dispatcher(); + + // hiding these for now to since not certain + // if we need to really expose them. + dispatcher.setMaxRequests(maxRequests); + dispatcher.setMaxRequestsPerHost(maxRequestsPerHost); + return dispatcher; + } + + private OkHttpClient createOkHttpClient(X509TrustManager trustManager, SSLContext sslContext, + AuthenticatorInterceptor authenticatorInterceptor, ResponseCodeInterceptor responseCodeInterceptor, Dispatcher dispatcher) { + OkHttpClient.Builder builder = new OkHttpClient.Builder() + .addNetworkInterceptor(new UserAgentInterceptor(userAgentPrefix)) + .addInterceptor(responseCodeInterceptor) + .addInterceptor(authenticatorInterceptor) + .dispatcher(dispatcher) + .readTimeout(readTimeout, readTimeoutUnit) + .writeTimeout(writeTimeout, writeTimeoutUnit) + .connectTimeout(connectTimeout, connectTimeoutUnit) + .pingInterval(pingInterval, pingIntervalUnit) + .sslSocketFactory(sslContext.getSocketFactory(), trustManager); + + if (!this.sslCertCallbackWithDefaultHostnameVerifier) { + builder.hostnameVerifier(sslCertificateCallback); + } + + if (proxy != null) { + builder.proxy(proxy); + } + + if (proxySelector != null) { + builder.proxySelector(proxySelector); + } + + if (proxyAuthenticator != null) { + builder.proxyAuthenticator(proxyAuthenticator); + } + + return builder.build(); + } + + private X509TrustManager getCurrentTrustManager(TrustManagerFactory trustManagerFactory) + throws NoSuchAlgorithmException, KeyStoreException { + for (TrustManager trustManager : trustManagerFactory.getTrustManagers()) { + if (trustManager instanceof X509TrustManager) { + X509TrustManager x509TrustManager = (X509TrustManager) trustManager; + return new CallbackTrustManager(x509TrustManager, this.sslCertificateCallback); + } + } + return null; + + } + + private TrustManagerFactory initTrustManagerFactory(String alias, X509Certificate cert, + Collection certs) + throws NoSuchAlgorithmException, KeyStoreException, CertificateException, IOException { + TrustManagerFactory trustManagerFactory = TrustManagerFactory + .getInstance(TrustManagerFactory.getDefaultAlgorithm()); + if (alias != null && (cert != null || certs != null)) { + KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType()); + // need this load to initialize the key store, and allow for the subsequent set + // certificate entry + ks.load(null, null); + if (cert != null) { + cert.checkValidity(); + ks.setCertificateEntry(alias, cert); + } + if (certs != null) { + int i = 0; + for (X509Certificate x509 : certs) { + x509.checkValidity(); + ks.setCertificateEntry(alias + i, x509); + i++; + } + } + + // testing has proven that you can only call init() once for a + // TrustManagerFactory wrt loading certs + // from the KeyStore ... subsequent KeyStore.setCertificateEntry / + // TrustManagerFactory.init calls are + // ignored. + // So if a specific cert is required to validate this connection's communication + // with the server, add it up front + // in the ctor. + trustManagerFactory.init(ks); + } else { + trustManagerFactory.init((KeyStore) null); + } + return trustManagerFactory; + } + + private static class CallbackTrustManager implements X509TrustManager { + + private X509TrustManager trustManager; + private ISSLCertificateCallback callback; + + private CallbackTrustManager(X509TrustManager currentTrustManager, ISSLCertificateCallback callback) + throws NoSuchAlgorithmException, KeyStoreException { + this.trustManager = currentTrustManager; + this.callback = callback; + } + + public X509Certificate[] getAcceptedIssuers() { + return trustManager.getAcceptedIssuers(); + } + + public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException { + try { + trustManager.checkServerTrusted(chain, authType); + } catch (CertificateException e) { + if (!callback.allowCertificate(chain)) { + throw e; + } + } + } + + public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException { + trustManager.checkServerTrusted(chain, authType); + } + } + + private static class UserAgentInterceptor implements Interceptor { + + private final String userAgent; + + public UserAgentInterceptor(String userAgentPrefix) { + this.userAgent = StringUtils.join( + new String[]{ userAgentPrefix, "openshift-restclient-java", "okhttp/" + OkHttp.VERSION }, "/"); + } + + + @Override + public Response intercept(Chain chain) throws IOException { + Request agent = chain.request().newBuilder().header("User-Agent", userAgent).build(); + return chain.proceed(agent); + } + } + } diff --git a/src/main/java/com/openshift/restclient/ClientFactory.java b/src/main/java/com/openshift/restclient/ClientFactory.java deleted file mode 100644 index 60868d9b..00000000 --- a/src/main/java/com/openshift/restclient/ClientFactory.java +++ /dev/null @@ -1,36 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2015 Red Hat, Inc. Distributed under license by Red Hat, Inc. - * All rights reserved. This program is made available under the terms of the - * Eclipse Public License v1.0 which accompanies this distribution, and is - * available at http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: Red Hat, Inc. - ******************************************************************************/ -package com.openshift.restclient; - - -/** - * Factory class for creating clients to an OpenShift server - * - * @author Jeff Cantrill - */ -@Deprecated -public final class ClientFactory { - - /** - * Creates a client for the given base url and ssl certificate callback. - * - * @param baseUrl - * The OpenShift server URL - * @param sslCertCallback - * The callback handler for SSL Cert challanges - * @return an implementation of IClient - * @throws OpenShiftException - * if the baseURL is malformed - */ - public final IClient create(String baseUrl, ISSLCertificateCallback sslCertCallback){ - return new ClientBuilder(baseUrl) - .sslCertificateCallback(sslCertCallback) - .build(); - } -} diff --git a/src/main/java/com/openshift/restclient/IApiTypeMapper.java b/src/main/java/com/openshift/restclient/IApiTypeMapper.java index 5b1976b0..1fa0c4da 100644 --- a/src/main/java/com/openshift/restclient/IApiTypeMapper.java +++ b/src/main/java/com/openshift/restclient/IApiTypeMapper.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2016 Red Hat, Inc. + * Copyright (c) 2016-2019 Red Hat, Inc. * Distributed under license by Red Hat, Inc. All rights reserved. * This program is made available under the terms of the * Eclipse Public License v1.0 which accompanies this distribution, @@ -8,6 +8,7 @@ * Contributors: * Red Hat, Inc. - initial API and implementation ******************************************************************************/ + package com.openshift.restclient; import java.util.Collection; @@ -16,142 +17,191 @@ /** * Determine the supported api endpoints by the cluster - * - * @author jeff.cantrill * */ public interface IApiTypeMapper { - - /** - * return the versioned endpoint for the given kind - * @param version the apiVersion, null or empty is best guess - * @param kind - * @return - * @throws OpenShiftException if unable to determine the endpoint for the given kind - */ - IVersionedApiResource getEndpointFor(String apiVersion, String kind); - - /** - * Using the kind and apiVersion, determine - * if the cluster is able to consume the - * given resource - * - * @param resource - * @return true if supported; false otherwise - */ - boolean isSupported(IResource resource); - - /** - * Using the kind determine - * if the cluster is able to consume the - * given resource - * - * @param kind the resource kind - * @return true if supported; false otherwise - */ - boolean isSupported(String kind); - - /** - * Using the kind and apiVersion, determine - * if the cluster is able to consume the - * given resource - * - * @param version the apiVersion, null or empty is best guess - * @param kind the resource kind - * @return true if supported; false otherwise - */ - boolean isSupported(String version, String kind); - - /** - * The api group for a given set of resources - * and the versions it supports. - * @author jeff.cantrill - * - */ - interface IApiGroup{ - - /** - * The prefix for this api group (e.g. api, oapi, apis) - * @return - */ - String getPrefix(); - - /** - * The name of the api group - * @return - */ - String getName(); - - /** - * The list of supported versions for the group. - * @return - */ - Collection getVersions(); - - /** - * The prefered version for the group - * @return - */ - String getPreferedVersion(); - - /** - * Get the endpoint path for the given version - * @param version - * @return - */ - String pathFor(String version); - } - - /** - * A description of an endpoint for - * a given resource and the capabilities - * it supports - * - * @author jeff.cantrill - */ - interface IVersionedApiResource{ - - /** - * The prefix for this api group (e.g. api, oapi, apis) - * @return - */ - String getPrefix(); - - /** - * The groupname of the resource (e.g. extensions of extensions/v1beta1) - * @return - */ - String getApiGroupName(); - - /** - * The version of the resource (e.g. v1) - * @return - */ - String getVersion(); - - /** - * get resource name this group supports - * @return - */ - String getName(); - - /** - * the kind used with this resource - * @return - */ - String getKind(); - - /** - * @return true if the associated resource is namespaced - */ - boolean isNamespaced(); - - /** - * Determine if the capability is supported - * (e.g. builds/webhooks) - * @return true if the capability is supported. - */ - boolean isSupported(String capability); - - } + + static final String KUBE_API = "api"; + static final String OS_API = "oapi"; + static final String API_GROUPS_API = "apis"; + static final String FWD_SLASH = "/"; + static final char DOT = '.'; + + String getPreferedVersionFor(String endpoint); + + /** + * return the versioned endpoint for the given kind + * + * @param version + * the apiVersion, null or empty is best guess + * @throws UnsupportedEndpointException + * if unable to determine the endpoint for the given kind + */ + IVersionedApiResource getEndpointFor(String apiVersion, String kind); + + /** + * Using the kind and apiVersion, determine if the cluster is able to consume + * the given resource + * + * @return true if supported; false otherwise + */ + boolean isSupported(IResource resource); + + /** + * Using the kind determine if the cluster is able to consume the given resource + * + * @param kind + * the resource kind + * @return true if supported; false otherwise + */ + boolean isSupported(String kind); + + /** + * Using the kind and apiVersion, determine if the cluster is able to consume + * the given resource + * + * @param version + * the apiVersion, null or empty is best guess + * @param kind + * the resource kind + * @return true if supported; false otherwise + */ + boolean isSupported(String version, String kind); + + /** + * Get the type information best matching the version and kind arguments + * + * @param apiVersion the optional version (with or without group) + * @param kind the type kind + * @return the registered type or null + */ + IVersionedType getType(String apiVersion, String kind); + + /** + * The api group for a given set of resources and the versions it supports. + * + * @author jeff.cantrill + * + */ + interface IApiGroup { + + /** + * The prefix for this api group (e.g. api, oapi, apis) + * + */ + String getPrefix(); + + /** + * The name of the api group + * + */ + String getName(); + + /** + * The list of supported versions for the group. + * + */ + Collection getVersions(); + + /** + * The prefered version for the group + * + */ + String getPreferedVersion(); + + /** + * Get the endpoint path for the given version + * + */ + String pathFor(String version); + } + + /** + * A description of an endpoint for a given resource and the capabilities it + * supports + * + * @author jeff.cantrill + */ + interface IVersionedApiResource { + + /** + * The prefix for this api group (e.g. api, oapi, apis) + * + */ + String getPrefix(); + + /** + * The groupname of the resource (e.g. extensions of extensions/v1beta1) + * + */ + String getApiGroupName(); + + /** + * The version of the resource (e.g. v1) + * + */ + String getVersion(); + + /** + * get resource name this group supports + * + */ + String getName(); + + /** + * the kind used with this resource + * + */ + String getKind(); + + /** + * @return true if the associated resource is namespaced + */ + boolean isNamespaced(); + + /** + * Determine if the capability is supported (e.g. builds/webhooks) + * + * @return true if the capability is supported. + */ + boolean isSupported(String capability); + + } + + interface IVersionedType { + /** + * The prefix of the resource type (e.g. extensions of extensions/v1beta1) + * + */ + String getPrefix(); + + /** + * The groupname of the resource type (e.g. extensions of extensions/v1beta1) + * + */ + String getApiGroupName(); + + /** + * The version of the resource type (e.g. v1) + * + */ + String getVersion(); + + /** + * The optional groupname and version of the resource type (e.g. extensions of extensions/v1beta1) + * + */ + default String getApiGroupNameAndVersion() { + if (getApiGroupName() != null) { + return getApiGroupName() + IApiTypeMapper.FWD_SLASH + getVersion(); + } + return getVersion(); + } + + /** + * the kind used with this resource type + * + */ + String getKind(); + } } diff --git a/src/main/java/com/openshift/restclient/IClient.java b/src/main/java/com/openshift/restclient/IClient.java index 013ba76e..6346b3b5 100644 --- a/src/main/java/com/openshift/restclient/IClient.java +++ b/src/main/java/com/openshift/restclient/IClient.java @@ -1,173 +1,391 @@ /******************************************************************************* - * Copyright (c) 2015 Red Hat, Inc. Distributed under license by Red Hat, Inc. + * Copyright (c) 2015-2019 Red Hat, Inc. Distributed under license by Red Hat, Inc. * All rights reserved. This program is made available under the terms of the * Eclipse Public License v1.0 which accompanies this distribution, and is * available at http://www.eclipse.org/legal/epl-v10.html * * Contributors: Red Hat, Inc. ******************************************************************************/ + package com.openshift.restclient; +import java.io.InputStream; import java.net.URL; import java.util.Collection; import java.util.List; import java.util.Map; -import com.openshift.restclient.authorization.IAuthorizationClient; -import com.openshift.restclient.authorization.IAuthorizationStrategy; +import com.openshift.internal.restclient.KubernetesVersion; +import com.openshift.restclient.api.ITypeFactory; +import com.openshift.restclient.authorization.IAuthorizationContext; import com.openshift.restclient.capability.ICapable; import com.openshift.restclient.model.IList; import com.openshift.restclient.model.IResource; -import com.openshift.restclient.model.user.IUser; +import com.openshift.restclient.model.JSONSerializeable; /** * Client is the the simplest interface for interacting with the OpenShift * master server. - * - * @author Jeff Cantrill * */ -public interface IClient extends ICapable, IAuthorizationClient{ - - IWatcher watch(String namespace, IOpenShiftWatchListener listener, String...kinds); - - /** - * Lists all possible resources of the given kind in the default namespace - * @param kind - * @return - */ - List list(String kind); - - - /** - * Lists the given given resource kind scoping it to a specific namespace - * - * @param kind - * @param namespace The namespace to scope the possible results of this list - * @return - */ - List list(String kind, String namespace); - - /** - * Lists the given given resource kind scoping it to a specific namespace - * - * @param kind - * @param namespace The namespace to scope the possible results of this list - * @param labels The label used to filter the resource - * @return - */ - List list(String kind, String namespace, Map labels); - - /** - * - * @param service - * @param name - * @return - * @throws OpenShiftException if operation not supported for resource type - */ - T get(String kind, String name, String namespace); - - /** - * - * @return A raw list of the kind in the given namespace (e.g. ServiceList) - */ - IList get(String kind, String namespace); - - /** - * Creates the given resource in the namespace defined on the - * resource or the default namspace if undefined - * @param resource - * @return - * @throws UnsupportedOperationException if the resource is a list - */ - T create(T resource); - - /** - * Creates the given resource in the given namespace - * @param resource - * @param namespace - * @return - */ - T create(T resource, String namespace); - - /** - * Creates the given resource in the given namespace using the subresource - * @param kind - * @param namespace - * @param name - * @param subresource - * @param payload - * @return - */ - T create(String kind, String namespace, String name, String subresource, IResource payload); - - /** - * Creates a list of resources in the given namespace - * @param list The resource definitions - * @param namespace the namespace for the resources - * @return A collection of the resources created or the status - * instance of why the creation failed. - * @throws OpenShiftException if a status can not be determined from - * the exception - */ - Collection create(IList list, String namespace); - - /** - * Updates the given resource - * @param resource - * @return - * @throws UnsupportedOperationException if the resource is a list - */ - T update(T resource); - - /** - * Deletes the given resource. - * @param resource - * @throws UnsupportedOperationException if the resource is a list - */ - void delete(T resource); - - /** - * - * @return the base URL of this endpoint - */ - URL getBaseURL(); - - /** - * - * @param resource - * @return the uri to the resource (e.g. for crafting webhooks) - */ - String getResourceURI(IResource resource); - - /** - * Returns the OpenShift API version for this client - * @return - * @throws UnsupportedVersionException - * @throws {@link UnauthorizedException} - */ - String getOpenShiftAPIVersion() throws UnsupportedVersionException; - - /** - * Sets the authorization strategy for the client when - * making requests to the server - * @param strategy - */ - void setAuthorizationStrategy(IAuthorizationStrategy strategy); - - IAuthorizationStrategy getAuthorizationStrategy(); - - /** - * Returns the resource factory used to create resources based on the - * response from the server - * @return - */ - IResourceFactory getResourceFactory(); - - /** - * @return the user associated with the current session - */ - IUser getCurrentUser(); +public interface IClient extends ICapable, Cloneable { + + /* + * Watch for changes scoped to a specific namespace + * + * @param namespace The namespace to watch for changes in + * + * @param listener The listener to be notified on events + * + * @param kids The kinds to watch for + * + */ + IWatcher watch(String namespace, IOpenShiftWatchListener listener, String... kinds); + + /* + * Watch for changes in the default namespace + * + * @param listener The listener to be notified on events + * + * @param kids The kinds to watch for + */ + IWatcher watch(IOpenShiftWatchListener listener, String... kinds); + + /** + * Lists all possible resources of the given kind in the default namespace + * + * @param kind + * @return + */ + List list(String kind); + + /** + * Lists the given given resource kind in the default namespace + * + * @param kind + * @param labels + * The label used to filter the resource + * @return + */ + List list(String kind, Map labels); + + /** + * Lists the given given resource kind scoping it to a specific namespace + * + * @param kind + * @param namespace + * The namespace to scope the possible results of this list + * @return + */ + List list(String kind, String namespace); + + /** + * Lists the given given resource kind scoping it to a specific namespace + * + * @param kind + * @param namespace + * The namespace to scope the possible results of this list + * @param labels + * The label used to filter the resource + * @return + */ + List list(String kind, String namespace, Map labels); + + /** + * Lists the given given resource kind scoping it to a specific namespace + * + * @param kind + * @param namespace + * The namespace to scope the possible results of this list + * @param labelQuery + * The label used to filter the resource + * @return + */ + List list(String kind, String namespace, String labelQuery); + + /** + * + * @param kind + * @param name + * @param namespace + * @return + * @throws OpenShiftException + * if operation not supported for resource type + */ + T get(String kind, String name, String namespace); + + /** + * + * @return A raw list of the kind in the given namespace (e.g. ServiceList) + */ + IList get(String kind, String namespace); + + /** + * Creates the given resource in the namespace defined on the resource or the + * default namspace if undefined + * + * @param resource + * @return + * @throws UnsupportedOperationException + * if the resource is a list + */ + T create(T resource); + + /** + * Creates the given resource in the given namespace + * + * @param resource + * @param namespace + * @return + */ + T create(T resource, String namespace); + + /** + * Creates the given resource in the given namespace using the subresource + * + * @param kind + * @param namespace + * @param name + * @param subresource + * @param payload + * @return + */ + T create(String kind, String namespace, String name, String subresource, IResource payload); + + /** + * Creates the given resource in the given namespace using the subresource + * + * @param kind + * @param version + * @param namespace + * @param name + * @param subresource + * @param payload + * @return + */ + T create(String kind, String version, String namespace, String name, String subresource, InputStream payload); + + /** + * Creates the given resource in the given namespace using the subresource + * + * @param kind + * @param version + * @param namespace + * @param name + * @param subresource + * @param payload + * @param parameters + * @return + */ + T create(String kind, String version, String namespace, String name, String subresource, InputStream payload, Map parameters); + + /** + * Creates a list of resources in the given namespace + * + * @param list + * The resource definitions + * @param namespace + * the namespace for the resources + * @return A collection of the resources created or the status instance of why + * the creation failed. + * @throws OpenShiftException + * if a status can not be determined from the exception + */ + Collection create(IList list, String namespace); + + /** + * Updates the given resource + * + * @param resource + * @return + * @throws UnsupportedOperationException + * if the resource is a list + */ + T update(T resource); + + /** + * Deletes the given resource. + * + * @param resource + * @throws UnsupportedOperationException + * if the resource is a list + */ + void delete(T resource); + + /** + * Deletes a resource of given name and kind in the given namespace. + * + * @param kind the kind of resource + * @param namespace the namespace + * @param name the name of the resource + * @throws UnsupportedOperationException + * if the resource is a list + */ + void delete(String kind, String namespace, String name); + + /** + * Raw execution of a request + * + * @param httpMethod + * HttpMethod (e.g. POST) + * @param kind + * @param namespace + * @param name + * @param subresource + * subresource or capability + * @param payload + * the payload to sumit. only valid on non-get operations + * @return + * + */ + T execute(String httpMethod, String kind, String namespace, String name, String subresource, + IResource payload); + + T execute(String method, String kind, String version, String namespace, String name, String subresource, InputStream payload); + + T execute(String method, String kind, String version, String namespace, String name, + String subresource, InputStream payload, Map parameters); + + /** + * Raw execution of a request + * + * @param httpMethod + * HttpMethod (e.g. POST) + * @param kind + * @param namespace + * @param name + * @param subresource + * subresource or capability + * @param payload + * the payload to sumit. only valid on non-get operations + * @param params + * map of query parameters + * @return + * + */ + T execute(String httpMethod, String kind, String namespace, String name, String subresource, + IResource payload, Map params); + + /** + * Raw execution of a request + * + * @param httpMethod + * HttpMethod (e.g. POST) + * @param kind + * @param namespace + * @param name + * @param subresource + * subresource or capability + * @param subcontext + * additional subContext (e.g. jolokia endpoint) Raw execution of a + * request that requires consumers to handle the response + * @return + */ + T execute(String httpMethod, String kind, String namespace, String name, String subresource, + IResource payload, String subcontext); + + + + /** + * @param factory + * The factory to use for interpreting the response + * @param httpMethod + * HttpMethod (e.g. POST) + * @param kind + * @param namespace + * @param name + * @param subresource + * subresource or capability + * @param payload + * the payload to sumit. only valid on non-get operations + * @param subContext + * additional subContext + * @param params + * @return the raw payload string + */ + T execute(ITypeFactory factory, String httpMethod, String kind, String namespace, String name, + String subresource, String subContext, JSONSerializeable payload, Map params); + + /** + * + * @return the base URL of this endpoint + */ + URL getBaseURL(); + + /** + * @return the authentication endpoint to be used when login + * @throws OpenShiftException if endpoint retrieval fails + */ + URL getAuthorizationEndpoint(); + + /** + * @return the token endpoint to be used when login + * @throws OpenShiftException if endpoint retrieval fails + */ + URL getTokenEndpoint(); + + /** + * + * @return the uri to the resource (e.g. for crafting webhooks) + */ + String getResourceURI(IResource resource); + + /** + * Returns the OpenShift API version for this client + * + * @throws {@link + * UnauthorizedException} + */ + String getOpenShiftAPIVersion() throws UnsupportedVersionException; + + /** + * The authorization context for this client. + * + * @return The context which will never be null + */ + IAuthorizationContext getAuthorizationContext(); + + /** + * Returns the resource factory used to create resources based on the response + * from the server + * + */ + IResourceFactory getResourceFactory(); + + /** + * Adapt this class to the given type + * + * @return an instance of the class or null if it can not + */ + default T adapt(Class klass) { + return null; + } + + /** + * Query the server to determine if it is ready + * + */ + String getServerReadyStatus(); + + /** + * Query the server to determine the Openshift version + * + */ + String getOpenshiftMasterVersion(); + /** + * Query the server to determine the Kubernetes version + * + */ + String getKubernetesMasterVersion(); + IClient clone(); + + /** + * Returns the major version for OpenShift or + * {@link KubernetesVersion#NO_VERSION} if it could not be detected. + * + * @return the major version of openshift that this client talks to. + */ + int getOpenShiftMajorVersion(); } diff --git a/src/main/java/com/openshift/restclient/IOpenShiftWatchListener.java b/src/main/java/com/openshift/restclient/IOpenShiftWatchListener.java index 16196a5e..8d1c2ac1 100644 --- a/src/main/java/com/openshift/restclient/IOpenShiftWatchListener.java +++ b/src/main/java/com/openshift/restclient/IOpenShiftWatchListener.java @@ -8,6 +8,7 @@ * Contributors: * Red Hat, Inc. - initial API and implementation ******************************************************************************/ + package com.openshift.restclient; import java.util.List; @@ -15,102 +16,108 @@ import com.openshift.restclient.model.IResource; /** - * Handler to receive notification when a resource - * changes - * @author Jeff Cantrill + * Handler to receive notification when a resource changes * */ public interface IOpenShiftWatchListener { - - /** - * Called when an endpoint connects - * The initial set of resources returned when determining - * the resourceVersion to watch - * @param resources an Unmodifiable List - */ - void connected(List resources); - - /** - * Called when and endpoint disconnects - */ - void disconnected(); - - /** - * - * @param resource the resource that changed - * @param change the change type - */ - void received(IResource resource, ChangeType change); - - public class ChangeType { - - public static final ChangeType ADDED = new ChangeType("ADDED"); - public static final ChangeType MODIFIED = new ChangeType("MODIFIED"); - public static final ChangeType DELETED = new ChangeType("DELETED"); - - private String value; - - public ChangeType(String value) { - if (value != null) { - value = value.toUpperCase(); - } - this.value = value; - } - - public String getValue() { - return value; - } - - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = prime * result + ((getValue() == null) ? 0 : getValue().hashCode()); - return result; - } - - @Override - public boolean equals(Object obj) { - if (this == obj) - return true; - if (obj == null) - return false; - if (getClass() != obj.getClass()) - return false; - ChangeType other = (ChangeType) obj; - if (value == null) { - if (other.value != null) - return false; - } else if (!getValue().equals(other.getValue())) - return false; - return true; - } - } - - void error(Throwable err); - - /** - * Convenience class for implementing watch callbacks - * @author jeff.cantrill - * - */ - static class OpenShiftWatchListenerAdapter implements IOpenShiftWatchListener{ - - @Override - public void connected(List resources) { - } - - @Override - public void disconnected() { - } - - @Override - public void received(IResource resource, ChangeType change) { - } - - @Override - public void error(Throwable err) { - } - - } + + /** + * Called when an endpoint connects The initial set of resources returned when + * determining the resourceVersion to watch + * + * @param resources + * an Unmodifiable List + */ + void connected(List resources); + + /** + * Called when and endpoint disconnects + */ + void disconnected(); + + /** + * + * @param resource + * the resource that changed + * @param change + * the change type + */ + void received(IResource resource, ChangeType change); + + public class ChangeType { + + public static final ChangeType ADDED = new ChangeType("ADDED"); + public static final ChangeType MODIFIED = new ChangeType("MODIFIED"); + public static final ChangeType DELETED = new ChangeType("DELETED"); + + private String value; + + public ChangeType(String value) { + if (value != null) { + value = value.toUpperCase(); + } + this.value = value; + } + + public String getValue() { + return value; + } + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + ((getValue() == null) ? 0 : getValue().hashCode()); + return result; + } + + @Override + public boolean equals(Object obj) { + if (this == obj) { + return true; + } + if (obj == null) { + return false; + } + if (getClass() != obj.getClass()) { + return false; + } + ChangeType other = (ChangeType) obj; + if (value == null) { + if (other.value != null) { + return false; + } + } else if (!getValue().equals(other.getValue())) { + return false; + } + return true; + } + } + + void error(Throwable err); + + /** + * Convenience class for implementing watch callbacks + * + * + */ + static class OpenShiftWatchListenerAdapter implements IOpenShiftWatchListener { + + @Override + public void connected(List resources) { + } + + @Override + public void disconnected() { + } + + @Override + public void received(IResource resource, ChangeType change) { + } + + @Override + public void error(Throwable err) { + } + + } } diff --git a/src/main/java/com/openshift/restclient/IResourceFactory.java b/src/main/java/com/openshift/restclient/IResourceFactory.java index 0fca1253..5a0bea73 100644 --- a/src/main/java/com/openshift/restclient/IResourceFactory.java +++ b/src/main/java/com/openshift/restclient/IResourceFactory.java @@ -6,86 +6,94 @@ * * Contributors: Red Hat, Inc. ******************************************************************************/ + package com.openshift.restclient; import java.io.InputStream; import java.util.List; +import com.openshift.restclient.api.ITypeFactory; import com.openshift.restclient.model.IResource; /** - * Factory class for creating resources from a - * response string + * Factory class for creating resources from a response string * - * @author Jeff Cantrill */ -public interface IResourceFactory { - - /** - * Create a list of resources of the given kind - * from a response string - * @param json - * @param kind - * @return - * @throws ResourceFactoryException if it is unable to create resources - */ - List createList(String json, String kind); - - /** - * Create a resource from a response string - * @param response - * @return - * @throws ResourceFactoryException if it is unable to create resources - */ - T create(String response) ; +public interface IResourceFactory extends ITypeFactory { + + /** + * Create a list of resources of the given kind from a response string + * + * @throws ResourceFactoryException + * if it is unable to create resources + */ + List createList(String json, String kind); + + /** + * Create a resource from a response string + * + * @param response + * @return + * @throws ResourceFactoryException + * if it is unable to create resources + */ + T create(String response); - @Deprecated - IResource create(String response, boolean strict) ; + /** + * Create a resource from a response string + * + * @param input + * Read the given input stream which assumes the input is parsable + * JSON representing a valid resource + * @return + * @throws ResourceFactoryException + * if it is unable to create resources + */ + T create(InputStream input); - /** - * Create a resource from a response string - * @param input Read the given input stream which assumes the input - * is parsable JSON representing a valid resource - * @return - * @throws ResourceFactoryException if it is unable to create resources - */ - T create(InputStream input) ; + /** + * Create(or stub) a resource for a given version and kind + * + * @param version + * @param kind + * @return + */ + T create(String version, String kind); - @Deprecated - IResource create(InputStream input, boolean strict) ; + /** + * Create(or stub) a resource for a given version and kind and name + * + * @param version + * @param kind + * @param name + * + * @return + */ + T create(String version, String kind, String name); - /** - * Create(or stub) a resource for a given version and kind - * @param version - * @param kind - * @return - */ - T create(String version, String kind); + /** + * Stub out the given resource kind using a version determined by the factory + * + * @param kind + * @param name + * @return + */ + T stub(String kind, String name); - @Deprecated - IResource create(String version, String kind, boolean strict); + /** + * Stub out the given resource kind using a version determined by the factory + * + * @param kind + * @param name + * @param namespace + * @return + */ + T stub(String kind, String name, String namespace); - /** - * Stub out the given resource kind using a version determined by the factory - * @param kind - * @param name - * @return - */ - T stub(String kind, String name); + /** + * The client given to resources when they are created + * + */ + void setClient(IClient client); - /** - * Stub out the given resource kind using a version determined by the factory - * @param kind - * @param name - * @param namespace - * @return - */ - T stub(String kind, String name, String namespace); - - /** - * The client given to resources when they are created - * @param client - */ - void setClient(IClient client); - } diff --git a/src/main/java/com/openshift/restclient/ISSLCertificateCallback.java b/src/main/java/com/openshift/restclient/ISSLCertificateCallback.java index 9ed1d7b7..dd63767e 100644 --- a/src/main/java/com/openshift/restclient/ISSLCertificateCallback.java +++ b/src/main/java/com/openshift/restclient/ISSLCertificateCallback.java @@ -6,18 +6,23 @@ * * Contributors: Red Hat, Inc. ******************************************************************************/ + package com.openshift.restclient; import java.security.cert.X509Certificate; - +import javax.net.ssl.HostnameVerifier; import javax.net.ssl.SSLSession; /** * @author Andre Dietisheim */ -public interface ISSLCertificateCallback { - - boolean allowCertificate(X509Certificate[] chain); +public interface ISSLCertificateCallback extends HostnameVerifier { + + boolean allowCertificate(X509Certificate[] chain); + + boolean allowHostname(String hostname, SSLSession session); - boolean allowHostname(String hostname, SSLSession session); + default boolean verify(String hostname, SSLSession session) { + return allowHostname(hostname, session); + } } diff --git a/src/main/java/com/openshift/restclient/IWatcher.java b/src/main/java/com/openshift/restclient/IWatcher.java index c6ce012d..4f080047 100644 --- a/src/main/java/com/openshift/restclient/IWatcher.java +++ b/src/main/java/com/openshift/restclient/IWatcher.java @@ -8,9 +8,10 @@ * Contributors: * Red Hat, Inc. - initial API and implementation ******************************************************************************/ + package com.openshift.restclient; public interface IWatcher { - - void stop(); + + void stop(); } diff --git a/src/main/java/com/openshift/restclient/IncompatibleApiVersionsException.java b/src/main/java/com/openshift/restclient/IncompatibleApiVersionsException.java index 61112880..fa8a58bd 100644 --- a/src/main/java/com/openshift/restclient/IncompatibleApiVersionsException.java +++ b/src/main/java/com/openshift/restclient/IncompatibleApiVersionsException.java @@ -6,23 +6,25 @@ * * Contributors: Red Hat, Inc. ******************************************************************************/ + package com.openshift.restclient; import java.util.Collection; import com.openshift.internal.restclient.KubernetesAPIVersion; -/** - * @author Jeff Cantrill - */ public class IncompatibleApiVersionsException extends OpenShiftException { - - private static final long serialVersionUID = 1L; - public IncompatibleApiVersionsException(Collection clientVersions,Collection serverVersions ){ - super(String.format("The client %s and server %s do not have compatible API versions.", clientVersions, serverVersions)); - } - public IncompatibleApiVersionsException(String clientVersions, String serverVersions ){ - super(String.format("The client %s and server %s do not have compatible API versions.", clientVersions, serverVersions)); - } + private static final long serialVersionUID = 1L; + + public IncompatibleApiVersionsException(Collection clientVersions, + Collection serverVersions) { + super(String.format("The client %s and server %s do not have compatible API versions.", clientVersions, + serverVersions)); + } + + public IncompatibleApiVersionsException(String clientVersions, String serverVersions) { + super(String.format("The client %s and server %s do not have compatible API versions.", clientVersions, + serverVersions)); + } } diff --git a/src/main/java/com/openshift/restclient/NoopSSLCertificateCallback.java b/src/main/java/com/openshift/restclient/NoopSSLCertificateCallback.java index 50b45f76..f432b77d 100644 --- a/src/main/java/com/openshift/restclient/NoopSSLCertificateCallback.java +++ b/src/main/java/com/openshift/restclient/NoopSSLCertificateCallback.java @@ -8,10 +8,10 @@ * Contributors: * Red Hat, Inc. - initial API and implementation ******************************************************************************/ + package com.openshift.restclient; import java.security.cert.X509Certificate; - import javax.net.ssl.SSLSession; /** @@ -19,14 +19,14 @@ */ public class NoopSSLCertificateCallback implements ISSLCertificateCallback { - @Override - public boolean allowCertificate(X509Certificate[] chain) { - return true; - } + @Override + public boolean allowCertificate(X509Certificate[] chain) { + return true; + } - @Override - public boolean allowHostname(String hostname, SSLSession session) { - return true; - } + @Override + public boolean allowHostname(String hostname, SSLSession session) { + return true; + } } diff --git a/src/main/java/com/openshift/restclient/NotFoundException.java b/src/main/java/com/openshift/restclient/NotFoundException.java index 63fd3a22..c279b205 100644 --- a/src/main/java/com/openshift/restclient/NotFoundException.java +++ b/src/main/java/com/openshift/restclient/NotFoundException.java @@ -7,25 +7,29 @@ * * Contributors: * Red Hat, Inc. - initial API and implementation - ******************************************************************************/ + ******************************************************************************/ + package com.openshift.restclient; -/** - * @author jeff.cantrill - */ +import com.openshift.restclient.model.IStatus; + public class NotFoundException extends OpenShiftException { - private static final long serialVersionUID = 1L; + private static final long serialVersionUID = 1L; + + public NotFoundException(String message, Throwable cause) { + super(message, cause); + } - public NotFoundException(String message, Throwable cause) { - super(message, cause); - } + public NotFoundException(String message) { + super(message); + } - public NotFoundException(String message) { - super(message); - } + public NotFoundException(Throwable cause) { + super(cause, ""); + } - public NotFoundException(Throwable cause) { - super(cause, ""); - } + public NotFoundException(Throwable cause, IStatus status, String message, Object... arguments) { + super(cause, status, message, arguments); + } } diff --git a/src/main/java/com/openshift/restclient/OpenShiftContext.java b/src/main/java/com/openshift/restclient/OpenShiftContext.java index 2a53f4cf..ee91b1d8 100644 --- a/src/main/java/com/openshift/restclient/OpenShiftContext.java +++ b/src/main/java/com/openshift/restclient/OpenShiftContext.java @@ -6,13 +6,14 @@ * * Contributors: Red Hat, Inc. ******************************************************************************/ + package com.openshift.restclient; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; /** - * OpenShift Context. + * OpenShift Context. * * @author Fred Bricon * @@ -20,44 +21,42 @@ */ public class OpenShiftContext { - private Map context = new ConcurrentHashMap<>(); - - private static ThreadLocal threadLocalBinary = new ThreadLocal() { - protected OpenShiftContext initialValue() { - return new OpenShiftContext(); - }; - }; - - private OpenShiftContext() { - } - - /** - * Returns the {@link OpenShiftContext} instance for the current {@link Thread}. - * - * @return an {@link OpenShiftContext} - */ - public static OpenShiftContext get() { - return threadLocalBinary.get(); - } - - public void put(String key, Object value) { - context.put(key, value); - } - - @SuppressWarnings("unchecked") - public T get(String key) { - T value = (T) context.get(key); - return value; - } - - public void remove(String key) { - context.remove(key); - } - - public void clear() { - context.clear(); - } - - - + private Map context = new ConcurrentHashMap<>(); + + private static ThreadLocal threadLocalBinary = new ThreadLocal() { + protected OpenShiftContext initialValue() { + return new OpenShiftContext(); + } + }; + + private OpenShiftContext() { + } + + /** + * Returns the {@link OpenShiftContext} instance for the current {@link Thread}. + * + * @return an {@link OpenShiftContext} + */ + public static OpenShiftContext get() { + return threadLocalBinary.get(); + } + + @SuppressWarnings("unchecked") + public T get(String key) { + T value = (T) context.get(key); + return value; + } + + public void put(String key, Object value) { + context.put(key, value); + } + + public void remove(String key) { + context.remove(key); + } + + public void clear() { + context.clear(); + } + } diff --git a/src/main/java/com/openshift/restclient/OpenShiftException.java b/src/main/java/com/openshift/restclient/OpenShiftException.java index 07be8820..1b7c28dd 100644 --- a/src/main/java/com/openshift/restclient/OpenShiftException.java +++ b/src/main/java/com/openshift/restclient/OpenShiftException.java @@ -6,8 +6,11 @@ * * Contributors: Red Hat, Inc. ******************************************************************************/ + package com.openshift.restclient; +import org.apache.commons.lang.StringUtils; + import com.openshift.restclient.model.IStatus; /** @@ -15,23 +18,36 @@ */ public class OpenShiftException extends RuntimeException { - private static final long serialVersionUID = -7076942050102006278L; - private IStatus status; - - public OpenShiftException(Throwable cause, String message, Object... arguments) { - super(String.format(message, arguments), cause); - } - - public OpenShiftException(String message, Object... arguments) { - this(null, null, message, arguments); - } - - public OpenShiftException(Throwable cause, IStatus status, String message, Object... arguments ) { - super(String.format(message, arguments), cause); - this.status = status; - } - - public IStatus getStatus(){ - return this.status; - } + private static final long serialVersionUID = -7076942050102006278L; + private IStatus status; + + public OpenShiftException(Throwable cause, String message, Object... arguments) { + super(String.format(message, arguments), cause); + } + + public OpenShiftException(String message, Object... arguments) { + this(null, null, message, arguments); + } + + public OpenShiftException(Throwable cause, IStatus status, String message, Object... arguments) { + super(String.format(StringUtils.defaultIfBlank(message, ""), arguments), cause); + this.status = status; + } + + public IStatus getStatus() { + return this.status; + } + + public boolean hasStatus() { + return this.status != null; + } + + @Override + public String getMessage() { + if (hasStatus()) { + return super.getMessage() + " " + status.getMessage(); + } + return super.getMessage(); + } + } diff --git a/src/main/java/com/openshift/restclient/ResourceFactoryException.java b/src/main/java/com/openshift/restclient/ResourceFactoryException.java index 69800270..7acb343b 100644 --- a/src/main/java/com/openshift/restclient/ResourceFactoryException.java +++ b/src/main/java/com/openshift/restclient/ResourceFactoryException.java @@ -6,16 +6,14 @@ * * Contributors: Red Hat, Inc. - initial API and implementation ******************************************************************************/ + package com.openshift.restclient; -/** - * @author Jeff Cantrill - */ public class ResourceFactoryException extends OpenShiftException { - private static final long serialVersionUID = 4215359575300693464L; + private static final long serialVersionUID = 4215359575300693464L; - public ResourceFactoryException(Throwable e, String message, Object... arguments) { - super(e, message, arguments); - } + public ResourceFactoryException(Throwable e, String message, Object... arguments) { + super(e, message, arguments); + } } diff --git a/src/main/java/com/openshift/restclient/ResourceKind.java b/src/main/java/com/openshift/restclient/ResourceKind.java index 82d20a8b..d0b0ecfb 100644 --- a/src/main/java/com/openshift/restclient/ResourceKind.java +++ b/src/main/java/com/openshift/restclient/ResourceKind.java @@ -1,11 +1,12 @@ /******************************************************************************* - * Copyright (c) 2015 Red Hat, Inc. Distributed under license by Red Hat, Inc. + * Copyright (c) 2015-2019 Red Hat, Inc. Distributed under license by Red Hat, Inc. * All rights reserved. This program is made available under the terms of the * Eclipse Public License v1.0 which accompanies this distribution, and is * available at http://www.eclipse.org/legal/epl-v10.html * * Contributors: Red Hat, Inc. ******************************************************************************/ + package com.openshift.restclient; import java.util.Collection; @@ -16,134 +17,162 @@ import org.apache.commons.lang.StringUtils; /** - * ResourceKind are the various types of Kubernetes - * resources that are of interest + * ResourceKind are the various types of Kubernetes resources that are of + * interest * */ public final class ResourceKind { - - //OpenShift Kinds - public static final String BUILD = "Build"; - public static final String BUILD_CONFIG = "BuildConfig"; - public static final String DEPLOYMENT_CONFIG = "DeploymentConfig"; - public static final String IMAGE_STREAM = "ImageStream"; - public static final String IMAGE_STREAM_TAG = "ImageStreamTag"; - public static final String IMAGE_STREAM_IMPORT = "ImageStreamImport"; - public static final String OAUTH_ACCESS_TOKEN = "OAuthAccessToken"; - public static final String OAUTH_AUTHORIZE_TOKEN = "OAuthAuthorizeToken"; - public static final String OAUTH_CLIENT = "OAuthClient"; - public static final String OAUTH_CLIENT_AUTHORIZATION = "OAuthClientAuthorization"; - public static final String POLICY = "Policy"; - public static final String POLICY_BINDING = "PolicyBinding"; - public static final String PROJECT = "Project"; - public static final String PROJECT_REQUEST = "ProjectRequest"; - public static final String ROLE = "Role"; - public static final String ROLE_BINDING = "RoleBinding"; - public static final String ROUTE = "Route"; - public static final String TEMPLATE = "Template"; - public static final String USER = "User"; - - //Kubernetes Kinds - public static final String EVENT = "Event"; - public static final String LIMIT_RANGE = "LimitRange"; - public static final String POD = "Pod"; - public static final String PVC = "PersistentVolumeClaim"; - public static final String PERSISTENT_VOLUME = "PersistentVolume"; - public static final String REPLICATION_CONTROLLER = "ReplicationController"; - public static final String RESOURCE_QUOTA = "ResourceQuota"; - public static final String SERVICE = "Service"; - public static final String SECRET = "Secret"; - public static final String SERVICE_ACCOUNT = "ServiceAccount"; - public static final String CONFIG_MAP = "ConfigMap"; - /* - * These are not true resources that can be used (mostly) in - * RESTful operations - */ - public static final String BUILD_REQUEST = "BuildRequest"; - @Deprecated - public static final String CONFIG = "Config";//not rest resource; - public static final String LIST = "List"; - public static final String STATUS = "Status";//not rest resource - public static final String PROCESSED_TEMPLATES = "ProcessedTemplates";//mechanism for processing templates - - /** - * The default if we haven't implemented the kind yet - */ - public static final String UNRECOGNIZED = "Unrecognized"; - - private static final Collection values; - - public static Collection values() { - return values; - } - - public static String pluralize(String kind) { - return pluralize(kind, false, false); - } - public static String pluralize(String kind, boolean lowercase, boolean uncapitalize) { - if(StringUtils.isBlank(kind)) return ""; - if(kind.endsWith("y")) - kind = kind.substring(0, kind.length()-1).concat("ies"); - else if(!kind.endsWith("s")) { - kind = kind.concat("s"); - } - if(lowercase) { - kind = kind.toLowerCase(); - } - if(uncapitalize) { - kind = StringUtils.uncapitalize(kind); - } - return kind; - } - - static { - Set set = new HashSet(); - //OpenShift Kinds - set.add(BUILD); - set.add(BUILD_CONFIG); - set.add(DEPLOYMENT_CONFIG); - set.add(IMAGE_STREAM ); - set.add(IMAGE_STREAM_TAG); - set.add(IMAGE_STREAM_IMPORT); - set.add(OAUTH_ACCESS_TOKEN); - set.add(OAUTH_AUTHORIZE_TOKEN); - set.add(OAUTH_CLIENT); - set.add(OAUTH_CLIENT_AUTHORIZATION); - set.add(POLICY); - set.add(POLICY_BINDING); - set.add(PROJECT ); - set.add(PROJECT_REQUEST); - set.add(ROLE); - set.add(ROLE_BINDING); - set.add(ROUTE); - set.add(TEMPLATE); - set.add(USER); - - //Kubernetes Kinds - set.add(EVENT); - set.add(LIMIT_RANGE); - set.add(POD); - set.add(PVC); - set.add(PERSISTENT_VOLUME); - set.add(REPLICATION_CONTROLLER); - set.add(RESOURCE_QUOTA); - set.add(SERVICE); - set.add(SECRET); - set.add(SERVICE_ACCOUNT); - set.add(CONFIG_MAP); - - /* - * These are not true resources that can be used (mostly) in - * RESTful operations - */ - set.add(BUILD_REQUEST); - set.add(CONFIG); - set.add(LIST); - set.add(STATUS); - set.add("ProcessedTemplates"); - values = Collections.unmodifiableCollection(set); - } - - private ResourceKind() { - } + + // OpenShift Kinds + public static final String BUILD = "Build"; + public static final String BUILD_CONFIG = "BuildConfig"; + public static final String DEPLOYMENT_CONFIG = "DeploymentConfig"; + public static final String IMAGE_STREAM = "ImageStream"; + public static final String IMAGE_STREAM_TAG = "ImageStreamTag"; + public static final String IMAGE_STREAM_IMPORT = "ImageStreamImport"; + public static final String NAMESPACE = "Namespace"; + public static final String OAUTH_ACCESS_TOKEN = "OAuthAccessToken"; + public static final String OAUTH_AUTHORIZE_TOKEN = "OAuthAuthorizeToken"; + public static final String OAUTH_CLIENT = "OAuthClient"; + public static final String OAUTH_CLIENT_AUTHORIZATION = "OAuthClientAuthorization"; + public static final String POLICY = "Policy"; + public static final String POLICY_BINDING = "PolicyBinding"; + public static final String PROJECT = "Project"; + public static final String PROJECT_REQUEST = "ProjectRequest"; + public static final String ROLE = "Role"; + public static final String ROLE_BINDING = "RoleBinding"; + public static final String ROUTE = "Route"; + public static final String TEMPLATE = "Template"; + public static final String USER = "User"; + public static final String GROUP = "Group"; + public static final String IDENTITY = "Identity"; + + // Kubernetes Kinds + public static final String ENDPOINTS = "Endpoints"; + public static final String EVENT = "Event"; + public static final String LIMIT_RANGE = "LimitRange"; + public static final String POD = "Pod"; + public static final String PVC = "PersistentVolumeClaim"; + public static final String PERSISTENT_VOLUME = "PersistentVolume"; + public static final String REPLICATION_CONTROLLER = "ReplicationController"; + public static final String RESOURCE_QUOTA = "ResourceQuota"; + public static final String SERVICE = "Service"; + public static final String SECRET = "Secret"; + public static final String SERVICE_ACCOUNT = "ServiceAccount"; + public static final String CONFIG_MAP = "ConfigMap"; + /* + * These are not true resources that can be used (mostly) in RESTful operations + */ + public static final String BUILD_REQUEST = "BuildRequest"; + + @Deprecated + public static final String CONFIG = "Config";// not rest resource; + public static final String LIST = "List"; + public static final String STATUS = "Status";// not rest resource + public static final String PROCESSED_TEMPLATES = "ProcessedTemplates";// mechanism for processing templates + + /** + * The default if we haven't implemented the kind yet + */ + public static final String UNRECOGNIZED = "Unrecognized"; + + private static final Collection values; + + public static Collection values() { + return values; + } + + public static String pluralize(String kind) { + return pluralize(kind, false, false); + } + + public static String pluralize(String kind, boolean lowercase, boolean uncapitalize) { + if (StringUtils.isBlank(kind)) { + return ""; + } + if (kind.endsWith("y")) { + kind = kind.substring(0, kind.length() - 1).concat("ies"); + } else if (!kind.endsWith("s")) { + kind = kind.concat("s"); + } + if (lowercase) { + kind = kind.toLowerCase(); + } + if (uncapitalize) { + kind = StringUtils.uncapitalize(kind); + } + return kind; + } + + static { + Set set = new HashSet(); + // OpenShift Kinds + set.add(BUILD); + set.add(BUILD_CONFIG); + set.add(DEPLOYMENT_CONFIG); + set.add(IMAGE_STREAM); + set.add(IMAGE_STREAM_TAG); + set.add(IMAGE_STREAM_IMPORT); + set.add(OAUTH_ACCESS_TOKEN); + set.add(OAUTH_AUTHORIZE_TOKEN); + set.add(OAUTH_CLIENT); + set.add(OAUTH_CLIENT_AUTHORIZATION); + set.add(POLICY); + set.add(POLICY_BINDING); + set.add(PROJECT); + set.add(PROJECT_REQUEST); + set.add(ROLE); + set.add(ROLE_BINDING); + set.add(ROUTE); + set.add(TEMPLATE); + set.add(USER); + set.add(GROUP); + set.add(IDENTITY); + + // Kubernetes Kinds + set.add(EVENT); + set.add(LIMIT_RANGE); + set.add(POD); + set.add(PVC); + set.add(PERSISTENT_VOLUME); + set.add(REPLICATION_CONTROLLER); + set.add(RESOURCE_QUOTA); + set.add(SERVICE); + set.add(SECRET); + set.add(SERVICE_ACCOUNT); + set.add(CONFIG_MAP); + + /* + * These are not true resources that can be used (mostly) in RESTful operations + */ + set.add(BUILD_REQUEST); + set.add(CONFIG); + set.add(LIST); + set.add(STATUS); + set.add("ProcessedTemplates"); + values = Collections.unmodifiableCollection(set); + } + + private ResourceKind() { + } + + public static String[] parse(String kind) { + String[] result = new String[2]; + result[0] = ""; + if (kind.contains(IApiTypeMapper.FWD_SLASH)) { + result[0] = kind.substring(0, kind.indexOf(IApiTypeMapper.FWD_SLASH)); + kind = kind.substring(kind.indexOf(IApiTypeMapper.FWD_SLASH) + 1); + } + if (kind.indexOf(IApiTypeMapper.DOT) != (-1)) { + String version = kind.substring(0, kind.indexOf(IApiTypeMapper.DOT)); + if (!result[0].isEmpty()) { + result[0] += IApiTypeMapper.FWD_SLASH + version; + } else { + result[0] = version; + } + kind = kind.substring(kind.indexOf(IApiTypeMapper.DOT) + 1); + } + result[1] = kind; + return result; + } } diff --git a/src/main/java/com/openshift/restclient/UnsupportedEndpointException.java b/src/main/java/com/openshift/restclient/UnsupportedEndpointException.java index d710bd97..41cd11cb 100644 --- a/src/main/java/com/openshift/restclient/UnsupportedEndpointException.java +++ b/src/main/java/com/openshift/restclient/UnsupportedEndpointException.java @@ -8,25 +8,24 @@ * Contributors: * Red Hat, Inc. - initial API and implementation ******************************************************************************/ + package com.openshift.restclient; /** - * The exception thrown when the client is trying to submit a request - * to an unrecognized endpoint. This usually occurs when a newer client - * is trying to utilize a feature that is unavailable to an older server - * - * @author jeff.cantrill + * The exception thrown when the client is trying to submit a request to an + * unrecognized endpoint. This usually occurs when a newer client is trying to + * utilize a feature that is unavailable to an older server * */ public class UnsupportedEndpointException extends OpenShiftException { - /** - * - */ - private static final long serialVersionUID = -9004398690965821552L; + /** + * + */ + private static final long serialVersionUID = -9004398690965821552L; - public UnsupportedEndpointException(String message, Object... arguments) { - super(message, arguments); - } + public UnsupportedEndpointException(String message, Object... arguments) { + super(message, arguments); + } } diff --git a/src/main/java/com/openshift/restclient/UnsupportedOperationException.java b/src/main/java/com/openshift/restclient/UnsupportedOperationException.java index 89dd5195..afd8d199 100644 --- a/src/main/java/com/openshift/restclient/UnsupportedOperationException.java +++ b/src/main/java/com/openshift/restclient/UnsupportedOperationException.java @@ -6,18 +6,16 @@ * * Contributors: Red Hat, Inc. ******************************************************************************/ + package com.openshift.restclient; -/** - * @author Jeff Cantrill - */ // TODO: replace with a unique name (UnsupportedResourceOperationException?) // since there's an identical exception in jdk (which is a runtime exception, too) public class UnsupportedOperationException extends RuntimeException { - - private static final long serialVersionUID = 1L; - public UnsupportedOperationException(String message){ - super(message); - } + private static final long serialVersionUID = 1L; + + public UnsupportedOperationException(String message) { + super(message); + } } diff --git a/src/main/java/com/openshift/restclient/UnsupportedVersionException.java b/src/main/java/com/openshift/restclient/UnsupportedVersionException.java index b89256eb..140d0c34 100644 --- a/src/main/java/com/openshift/restclient/UnsupportedVersionException.java +++ b/src/main/java/com/openshift/restclient/UnsupportedVersionException.java @@ -6,20 +6,18 @@ * * Contributors: Red Hat, Inc. ******************************************************************************/ + package com.openshift.restclient; -/** - * @author Jeff Cantrill - */ public class UnsupportedVersionException extends OpenShiftException { - - private static final long serialVersionUID = 1L; - public UnsupportedVersionException(String version){ - super(String.format("OpenShift API version '%s' is not supported by this client", version)); - } + private static final long serialVersionUID = 1L; + + public UnsupportedVersionException(String version) { + super(String.format("OpenShift API version '%s' is not supported by this client", version)); + } - public UnsupportedVersionException(String message, Object... arguments) { - super(message, arguments); - } + public UnsupportedVersionException(String message, Object... arguments) { + super(message, arguments); + } } diff --git a/src/main/java/com/openshift/restclient/api/ITypeFactory.java b/src/main/java/com/openshift/restclient/api/ITypeFactory.java new file mode 100644 index 00000000..bad1a828 --- /dev/null +++ b/src/main/java/com/openshift/restclient/api/ITypeFactory.java @@ -0,0 +1,46 @@ +/******************************************************************************* + * Copyright (c) 2016 Red Hat, Inc. + * Distributed under license by Red Hat, Inc. All rights reserved. + * This program is made available under the terms of the + * Eclipse Public License v1.0 which accompanies this distribution, + * and is available at http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Red Hat, Inc. - initial API and implementation + ******************************************************************************/ + +package com.openshift.restclient.api; + +import java.util.Optional; + +import com.openshift.restclient.ResourceFactoryException; + +/** + * A factory that is able of producing types from a response + * + */ +public interface ITypeFactory { + + /** + * Create a resource from a response string + * + * @throws ResourceFactoryException + * if it is unable to create resources + */ + Object createInstanceFrom(String response); + + /** + * Stub out the given resource kind using a version determined by the factory + * + * @param kind + * - Required. For arg types it may be in the form of + * apigroup/version.kind + * @param name + * - The name of the kind which may only be significant for instances + * that can be persisted by the server (e.g. Service) + * @param namespace + * - The namespace of the kind which may only be significant for + * instance that can be persisted + */ + Object stubKind(String kind, Optional name, Optional namespace); +} diff --git a/src/main/java/com/openshift/restclient/api/capabilities/IPodExec.java b/src/main/java/com/openshift/restclient/api/capabilities/IPodExec.java new file mode 100644 index 00000000..43b773b4 --- /dev/null +++ b/src/main/java/com/openshift/restclient/api/capabilities/IPodExec.java @@ -0,0 +1,150 @@ +/******************************************************************************* + * Copyright (c) 2016-2018 Red Hat, Inc. + * Distributed under license by Red Hat, Inc. All rights reserved. + * This program is made available under the terms of the + * Eclipse Public License v1.0 which accompanies this distribution, + * and is available at http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Red Hat, Inc. - initial API and implementation + ******************************************************************************/ + +package com.openshift.restclient.api.capabilities; + +import java.util.Collections; +import java.util.HashMap; +import java.util.Map; + +import com.openshift.restclient.capability.ICapability; +import com.openshift.restclient.capability.IStoppable; + +/** + * Runs container exec + */ +public interface IPodExec extends ICapability { + + /** + * Execute a command on a named container in this pod + * + * @param listener + * Listener for command output + * @param options + * Options for the exec + * @param commands + * A command to run and any arguments + * @return A Handle to allow termination of the connection + */ + IStoppable start(IPodExecOutputListener listener, Options options, String... commands); + + /** + * A callback for exec output + * + */ + interface IPodExecOutputListener { + + /** + * Callback received on initial connection + */ + void onOpen(); + + /** + * Exec received stdout message + * + */ + void onStdOut(String message); + + /** + * Exec received stderr message + * + */ + void onStdErr(String message); + + /** + * Exec (channel 3) error message + * + */ + void onExecErr(String message); + + /** + * Called by lower level errors + * + * @param t + * Exception causing failure + */ + void onFailure(Throwable t); + + /** + * Callback received when the connection to the pod is terminated from the + * server-side + * + * @param code + * a valid http response code + * @param reason + * a reason for termination, may be null + */ + void onClose(int code, String reason); + } + + /** + * Options for exec + */ + class Options { + + public static final String CONTAINER = "container"; + public static final String STDOUT = "stdout"; + public static final String STDERR = "stderr"; + private Map options = new HashMap<>(); + private Map secondaries = new HashMap<>(); + + private Options storeSecondary(String key, Object v) { + secondaries.put(key, v.toString()); + return this; + } + + /** + * The container from which to retrieve logs + * + */ + public Options container(String container) { + return storeSecondary(CONTAINER, container); + } + + /** + * Enable stdout + * + */ + public Options stdOut(boolean value) { + return storeSecondary(STDOUT, value); + } + + /** + * Enable stderr + * + */ + public Options stdErr(boolean value) { + return storeSecondary(STDERR, value); + } + + /** + * Add an option that is not explicitly defined. These will override any + * explicit options if there are collisions + * + */ + public Options parameter(String name, String value) { + options.put(name, value); + return this; + } + + /** + * The collective options + * + * @return a map of all the options + */ + public Map getMap() { + HashMap combined = new HashMap<>(secondaries); + combined.putAll(options); + return Collections.unmodifiableMap(combined); + } + } + +} diff --git a/src/main/java/com/openshift/restclient/api/capabilities/IScalable.java b/src/main/java/com/openshift/restclient/api/capabilities/IScalable.java new file mode 100644 index 00000000..49691597 --- /dev/null +++ b/src/main/java/com/openshift/restclient/api/capabilities/IScalable.java @@ -0,0 +1,31 @@ +/******************************************************************************* + * Copyright (c) 2016 Red Hat, Inc. + * Distributed under license by Red Hat, Inc. All rights reserved. + * This program is made available under the terms of the + * Eclipse Public License v1.0 which accompanies this distribution, + * and is available at http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Red Hat, Inc. - initial API and implementation + ******************************************************************************/ + +package com.openshift.restclient.api.capabilities; + +import com.openshift.restclient.OpenShiftException; +import com.openshift.restclient.apis.autoscaling.models.IScale; +import com.openshift.restclient.capability.ICapability; + +/** + * Allow a resource to scale + * + */ +public interface IScalable extends ICapability { + + /** + * Scale to the desired replicas. Value less then 0 will scale to 0 + * + * @throws OpenShiftException + * if there are errors + */ + IScale scaleTo(int replicas); +} diff --git a/src/main/java/com/openshift/restclient/api/models/IAnnotatable.java b/src/main/java/com/openshift/restclient/api/models/IAnnotatable.java new file mode 100644 index 00000000..87fefae9 --- /dev/null +++ b/src/main/java/com/openshift/restclient/api/models/IAnnotatable.java @@ -0,0 +1,47 @@ +/******************************************************************************* + * Copyright (c) 2016 Red Hat, Inc. + * Distributed under license by Red Hat, Inc. All rights reserved. + * This program is made available under the terms of the + * Eclipse Public License v1.0 which accompanies this distribution, + * and is available at http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Red Hat, Inc. - initial API and implementation + ******************************************************************************/ + +package com.openshift.restclient.api.models; + +import java.util.Map; + +/** + * A resource that can be annotated + * + */ +public interface IAnnotatable { + + /** + * Returns true if the resource is annotated with the given key + * + * @return true if the annotation key exists + */ + boolean isAnnotatedWith(String key); + + /** + * Retrieves the annotated value for the given key + * + */ + String getAnnotation(String key); + + /** + * Set the resource annotation + * + */ + void setAnnotation(String key, String value); + + /** + * Retrieves the annotations associated with the resource + * + */ + Map getAnnotations(); + +} diff --git a/src/main/java/com/openshift/internal/restclient/http/BadRequestException.java b/src/main/java/com/openshift/restclient/api/models/IApiVersionable.java similarity index 55% rename from src/main/java/com/openshift/internal/restclient/http/BadRequestException.java rename to src/main/java/com/openshift/restclient/api/models/IApiVersionable.java index baca5ca9..f13ae548 100644 --- a/src/main/java/com/openshift/internal/restclient/http/BadRequestException.java +++ b/src/main/java/com/openshift/restclient/api/models/IApiVersionable.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2011 Red Hat, Inc. + * Copyright (c) 2016 Red Hat, Inc. * Distributed under license by Red Hat, Inc. All rights reserved. * This program is made available under the terms of the * Eclipse Public License v1.0 which accompanies this distribution, @@ -7,21 +7,19 @@ * * Contributors: * Red Hat, Inc. - initial API and implementation - ******************************************************************************/ -package com.openshift.internal.restclient.http; + ******************************************************************************/ + +package com.openshift.restclient.api.models; /** - * @author André Dietisheim + * A model that can be versioned + * */ -public class BadRequestException extends HttpClientException { - - private static final long serialVersionUID = 1L; - - public BadRequestException(String message, Throwable cause) { - super(message, cause); - } +public interface IApiVersionable { - public BadRequestException(Throwable cause) { - super(cause); - } + /** + * The api version of the resource as found at apiVersion + * + */ + String getApiVersion(); } diff --git a/src/main/java/com/openshift/restclient/api/models/IEndpoints.java b/src/main/java/com/openshift/restclient/api/models/IEndpoints.java new file mode 100644 index 00000000..3e08ab6b --- /dev/null +++ b/src/main/java/com/openshift/restclient/api/models/IEndpoints.java @@ -0,0 +1,60 @@ +/******************************************************************************* + * Copyright (c) 2016 Red Hat, Inc. + * Distributed under license by Red Hat, Inc. All rights reserved. + * This program is made available under the terms of the + * Eclipse Public License v1.0 which accompanies this distribution, + * and is available at http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Red Hat, Inc. - initial API and implementation + ******************************************************************************/ + +package com.openshift.restclient.api.models; + +import java.util.List; + +import com.openshift.restclient.model.IObjectReference; +import com.openshift.restclient.model.IResource; + +/** + * Endpoint representation 'api/Endpoint' + * + * @author jeff.cantrill + * + */ +public interface IEndpoints extends IResource { + + List getSubSets(); + + interface IEndpointSubset { + + List getAddresses(); + + List getNotReadyAddresses(); + + List getPorts(); + } + + interface IEndpointAddress { + + String getIP(); + + String getHostName(); + + String getNodeName(); + + String getName(); + + IObjectReference getTargetRef(); + } + + interface IEndpointPort { + + String getName(); + + int getPort(); + + String getProtocol(); + } + +} diff --git a/src/main/java/com/openshift/restclient/api/models/IKindable.java b/src/main/java/com/openshift/restclient/api/models/IKindable.java new file mode 100644 index 00000000..bdc55eb8 --- /dev/null +++ b/src/main/java/com/openshift/restclient/api/models/IKindable.java @@ -0,0 +1,27 @@ +/******************************************************************************* + * Copyright (c) 2016 Red Hat, Inc. + * Distributed under license by Red Hat, Inc. All rights reserved. + * This program is made available under the terms of the + * Eclipse Public License v1.0 which accompanies this distribution, + * and is available at http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Red Hat, Inc. - initial API and implementation + ******************************************************************************/ + +package com.openshift.restclient.api.models; + +/** + * A resource that can describe itself by the kind it is + * + * @author jeff.cantrill + * + */ +public interface IKindable { + + /** + * The kind of the resource as would be found at kind + * + */ + String getKind(); +} diff --git a/src/main/java/com/openshift/internal/restclient/http/StringParameter.java b/src/main/java/com/openshift/restclient/api/models/ILabelable.java similarity index 55% rename from src/main/java/com/openshift/internal/restclient/http/StringParameter.java rename to src/main/java/com/openshift/restclient/api/models/ILabelable.java index e0fa6361..18914a95 100644 --- a/src/main/java/com/openshift/internal/restclient/http/StringParameter.java +++ b/src/main/java/com/openshift/restclient/api/models/ILabelable.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2013 Red Hat, Inc. + * Copyright (c) 2016 Red Hat, Inc. * Distributed under license by Red Hat, Inc. All rights reserved. * This program is made available under the terms of the * Eclipse Public License v1.0 which accompanies this distribution, @@ -8,24 +8,27 @@ * Contributors: * Red Hat, Inc. - initial API and implementation ******************************************************************************/ -package com.openshift.internal.restclient.http; + +package com.openshift.restclient.api.models; + +import java.util.Map; /** - * @author Andre Dietisheim + * A resource that can be labeled + * */ -public class StringParameter extends Parameter { - - public StringParameter(final String name, final String value) { - super(name, new StringValue(value)); - } +public interface ILabelable { - @Override - public String toString() { - return "StringParameter [" - + "name=" + getName() - + ", value=" + getValue() - + "]"; - } + /** + * Retrieves the labels associated with the resource + * + */ + Map getLabels(); + /** + * Add or update a label; + * + */ + void addLabel(String key, String value); } diff --git a/src/main/java/com/openshift/restclient/api/models/INameSetable.java b/src/main/java/com/openshift/restclient/api/models/INameSetable.java new file mode 100644 index 00000000..df8a92f5 --- /dev/null +++ b/src/main/java/com/openshift/restclient/api/models/INameSetable.java @@ -0,0 +1,26 @@ +/******************************************************************************* + * Copyright (c) 2016 Red Hat, Inc. + * Distributed under license by Red Hat, Inc. All rights reserved. + * This program is made available under the terms of the + * Eclipse Public License v1.0 which accompanies this distribution, + * and is available at http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Red Hat, Inc. - initial API and implementation + ******************************************************************************/ + +package com.openshift.restclient.api.models; + +/** + * A resource where the client can define the name on the object (e.g. + * ObjectRef) + * + */ +public interface INameSetable { + + /** + * The name of the resource + * + */ + void setName(String name); +} diff --git a/src/main/java/com/openshift/restclient/api/models/INamespaceSetable.java b/src/main/java/com/openshift/restclient/api/models/INamespaceSetable.java new file mode 100644 index 00000000..6b5bc4ea --- /dev/null +++ b/src/main/java/com/openshift/restclient/api/models/INamespaceSetable.java @@ -0,0 +1,26 @@ +/******************************************************************************* + * Copyright (c) 2016 Red Hat, Inc. + * Distributed under license by Red Hat, Inc. All rights reserved. + * This program is made available under the terms of the + * Eclipse Public License v1.0 which accompanies this distribution, + * and is available at http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Red Hat, Inc. - initial API and implementation + ******************************************************************************/ + +package com.openshift.restclient.api.models; + +/** + * A resource where the client can define the namespace on the object (e.g. + * ObjectRef) + * + */ +public interface INamespaceSetable { + + /** + * The namespace for the object ref + * + */ + void setNamespace(String namespace); +} diff --git a/src/main/java/com/openshift/restclient/api/models/IObjectMeta.java b/src/main/java/com/openshift/restclient/api/models/IObjectMeta.java new file mode 100644 index 00000000..b3ddaf92 --- /dev/null +++ b/src/main/java/com/openshift/restclient/api/models/IObjectMeta.java @@ -0,0 +1,42 @@ +/******************************************************************************* + * Copyright (c) 2016 Red Hat, Inc. + * Distributed under license by Red Hat, Inc. All rights reserved. + * This program is made available under the terms of the + * Eclipse Public License v1.0 which accompanies this distribution, + * and is available at http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Red Hat, Inc. - initial API and implementation + ******************************************************************************/ + +package com.openshift.restclient.api.models; + +/** + * ObjectMeta info as defined by the server + */ +public interface IObjectMeta extends ILabelable, IAnnotatable { + + /** + * Returns the identifier for this resource + * + */ + String getName(); + + /** + * Returns the timestamp of when this resource was created + * + */ + String getCreationTimeStamp(); + + /** + * Returns the scope of this resource + * + */ + String getNamespace(); + + /** + * A value that represents the version of this resource + * + */ + String getResourceVersion(); +} diff --git a/src/main/java/com/openshift/internal/restclient/http/StringValue.java b/src/main/java/com/openshift/restclient/api/models/ITypeMeta.java similarity index 58% rename from src/main/java/com/openshift/internal/restclient/http/StringValue.java rename to src/main/java/com/openshift/restclient/api/models/ITypeMeta.java index 7cc6bc7b..c5e5f727 100644 --- a/src/main/java/com/openshift/internal/restclient/http/StringValue.java +++ b/src/main/java/com/openshift/restclient/api/models/ITypeMeta.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2011 Red Hat, Inc. + * Copyright (c) 2016 Red Hat, Inc. * Distributed under license by Red Hat, Inc. All rights reserved. * This program is made available under the terms of the * Eclipse Public License v1.0 which accompanies this distribution, @@ -7,23 +7,17 @@ * * Contributors: * Red Hat, Inc. - initial API and implementation - ******************************************************************************/ -package com.openshift.internal.restclient.http; + ******************************************************************************/ + +package com.openshift.restclient.api.models; + +import com.openshift.restclient.model.JSONSerializeable; /** - * @author Andre Dietisheim + * Marker interface to kubernetes TypeMeta + * + * */ -public class StringValue extends ParameterValue { +public interface ITypeMeta extends IApiVersionable, IKindable, JSONSerializeable { - public StringValue(String value) { - super(value); - } - - @Override - public String toString() { - return "StringValue [" - + "value=" + getValue() - + "]"; - } } - diff --git a/src/main/java/com/openshift/restclient/apis/autoscaling/models/IScale.java b/src/main/java/com/openshift/restclient/apis/autoscaling/models/IScale.java new file mode 100644 index 00000000..4126ad0f --- /dev/null +++ b/src/main/java/com/openshift/restclient/apis/autoscaling/models/IScale.java @@ -0,0 +1,36 @@ +/******************************************************************************* + * Copyright (c) 2016 Red Hat, Inc. + * Distributed under license by Red Hat, Inc. All rights reserved. + * This program is made available under the terms of the + * Eclipse Public License v1.0 which accompanies this distribution, + * and is available at http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Red Hat, Inc. - initial API and implementation + ******************************************************************************/ + +package com.openshift.restclient.apis.autoscaling.models; + +import com.openshift.restclient.api.models.INameSetable; +import com.openshift.restclient.api.models.INamespaceSetable; +import com.openshift.restclient.api.models.IObjectMeta; +import com.openshift.restclient.api.models.ITypeMeta; + +/** + * Scale object payload to scalable resources + * + */ +public interface IScale extends ITypeMeta, IObjectMeta, INamespaceSetable, INameSetable { + + /** + * The number of desired replicas + * + */ + int getSpecReplicas(); + + /** + * Set the number of desired replicas + * + */ + void setSpecReplicas(int replicas); +} diff --git a/src/main/java/com/openshift/restclient/authorization/AbstractAuthorizationStrategy.java b/src/main/java/com/openshift/restclient/authorization/AbstractAuthorizationStrategy.java deleted file mode 100644 index 70042385..00000000 --- a/src/main/java/com/openshift/restclient/authorization/AbstractAuthorizationStrategy.java +++ /dev/null @@ -1,54 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2016 Red Hat, Inc. Distributed under license by Red Hat, Inc. - * All rights reserved. This program is made available under the terms of the - * Eclipse Public License v1.0 which accompanies this distribution, and is - * available at http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: Red Hat, Inc. - ******************************************************************************/ -package com.openshift.restclient.authorization; - -/** - * Base Authorization stategy - * - * @author Andre Dietisheim - */ -public abstract class AbstractAuthorizationStrategy implements IAuthorizationStrategy { - - private final String username; - - public AbstractAuthorizationStrategy(String username) { - this.username = username; - } - - @Override - public String getUsername() { - return username; - } - - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = prime * result + ((username == null) ? 0 : username.hashCode()); - return result; - } - - @Override - public boolean equals(Object obj) { - if (this == obj) - return true; - if (obj == null) - return false; - if (getClass() != obj.getClass()) - return false; - AbstractAuthorizationStrategy other = (AbstractAuthorizationStrategy) obj; - if (username == null) { - if (other.username != null) - return false; - } else if (!username.equals(other.username)) - return false; - return true; - } - -} diff --git a/src/main/java/com/openshift/restclient/authorization/AuthorizationClientFactory.java b/src/main/java/com/openshift/restclient/authorization/AuthorizationClientFactory.java deleted file mode 100644 index 85963056..00000000 --- a/src/main/java/com/openshift/restclient/authorization/AuthorizationClientFactory.java +++ /dev/null @@ -1,60 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2015 Red Hat, Inc. Distributed under license by Red Hat, Inc. - * All rights reserved. This program is made available under the terms of the - * Eclipse Public License v1.0 which accompanies this distribution, and is - * available at http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: Red Hat, Inc. - ******************************************************************************/ -package com.openshift.restclient.authorization; - -import com.openshift.internal.restclient.authorization.AuthorizationClient; -import com.openshift.restclient.IClient; - -/** - * @author Jeff Cantrill - */ -@Deprecated -public class AuthorizationClientFactory { - - /** - * Create an authorization client - * @param client the OpenShift client to use when retrieving a user - * @return - */ - public IAuthorizationClient create(IClient client){ - return new AuthorizationClient(client); - } - - /** - * Leaving here until we find a usecase to make it 'public' outside of - * the internal packages. - * - * @author jeff.cantrill - * - */ - public static class AuthorizationClientBuilder{ - - private int connectTimeoutMillis; - private IClient client; - - public AuthorizationClientBuilder withClient(IClient client) { - this.client = client; - return this; - } - - /** - * The connect timeout in millis - * @param connectTimeoutMillis - * @return - */ - public AuthorizationClientBuilder withConnectTimeout(int connectTimeoutMillis) { - this.connectTimeoutMillis = connectTimeoutMillis; - return this; - } - - public IAuthorizationClient build() { - return new AuthorizationClient(this.client, connectTimeoutMillis); - } - } -} diff --git a/src/main/java/com/openshift/restclient/authorization/BasicAuthorizationStrategy.java b/src/main/java/com/openshift/restclient/authorization/BasicAuthorizationStrategy.java deleted file mode 100644 index a1c52d07..00000000 --- a/src/main/java/com/openshift/restclient/authorization/BasicAuthorizationStrategy.java +++ /dev/null @@ -1,55 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2015 Red Hat, Inc. Distributed under license by Red Hat, Inc. - * All rights reserved. This program is made available under the terms of the - * Eclipse Public License v1.0 which accompanies this distribution, and is - * available at http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: Red Hat, Inc. - ******************************************************************************/ -package com.openshift.restclient.authorization; - -import com.openshift.restclient.http.IHttpConstants; -import com.openshift.restclient.utils.Base64Coder; - -/** - * Authorization strategy for basic authorization - * - * @author Jeff Cantrill - */ -public class BasicAuthorizationStrategy extends AbstractAuthorizationStrategy { - - private final String password; - private final String token; - - /** - * - * @param username - * @param password - * @param token optionally a token to use before trying to auth with username/password - */ - public BasicAuthorizationStrategy(String username, String password, String token) { - super(username); - this.password = password; - this.token = token; - } - - public String getPassword() { - return password; - } - - @Override - public String getToken() { - return token; - } - - @Override - public void authorize(IRequest request) { - String value = IHttpConstants.AUTHORIZATION_BASIC + " " + Base64Coder.encode(String.format("%s:%s", getUsername(), password)); - request.setProperty(IHttpConstants.PROPERTY_AUTHORIZATION, value); - } - - @Override - public void accept(IAuthorizationStrategyVisitor visitor) { - visitor.visit(this); - } -} diff --git a/src/main/java/com/openshift/restclient/authorization/IAuthorizationClient.java b/src/main/java/com/openshift/restclient/authorization/IAuthorizationClient.java deleted file mode 100644 index 1df636eb..00000000 --- a/src/main/java/com/openshift/restclient/authorization/IAuthorizationClient.java +++ /dev/null @@ -1,40 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2015 Red Hat, Inc. Distributed under license by Red Hat, Inc. - * All rights reserved. This program is made available under the terms of the - * Eclipse Public License v1.0 which accompanies this distribution, and is - * available at http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: Red Hat, Inc. - ******************************************************************************/ -package com.openshift.restclient.authorization; - -import com.openshift.restclient.ISSLCertificateCallback; - -/** - * @author Jeff Cantrill - */ -public interface IAuthorizationClient { - - /** - * Retrieve a token for OpenShift. - * - * @param baseURL - * @return - * @throws UnauthorizedException - */ - IAuthorizationContext getContext(final String baseURL); - - /** - * Retrieve the authorization details for a server - * - * @param baseURL - * @return - */ - IAuthorizationDetails getAuthorizationDetails(String baseURL); - - /** - * Set the callback handler to use for certificate trust issues. - * @param callback - */ - void setSSLCertificateCallback(ISSLCertificateCallback callback); -} diff --git a/src/main/java/com/openshift/restclient/authorization/IAuthorizationContext.java b/src/main/java/com/openshift/restclient/authorization/IAuthorizationContext.java index ee79263e..a73dd2a2 100644 --- a/src/main/java/com/openshift/restclient/authorization/IAuthorizationContext.java +++ b/src/main/java/com/openshift/restclient/authorization/IAuthorizationContext.java @@ -6,48 +6,91 @@ * * Contributors: Red Hat, Inc. ******************************************************************************/ + package com.openshift.restclient.authorization; import com.openshift.restclient.model.user.IUser; -/** - * @author Jeff Cantrill - */ public interface IAuthorizationContext { - - public static final String AUTHSCHEME_BASIC = "Basic"; - public static final String AUTHSCHEME_OAUTH = "OAuth"; - - /** - * The authorized user if it can be found for this token - * @return return the user for the token or null if not authorized - */ - IUser getUser(); - - /** - * - * @return true if the token is non-null; false otherwise - */ - boolean isAuthorized(); - - /** - * The authorization scope if it can be determined. - * @return the scope or null if unknown - */ - String getAuthScheme(); - - /** - * Token to use for authentication. Will return non-null - * value if authorized - * @return - */ - String getToken(); - - /** - * Time in ?? when the token expires. Will return - * non-null value if authorized - * @return - */ - String getExpiresIn(); + public static final String AUTHSCHEME_BASIC = "Basic"; + public static final String AUTHSCHEME_OAUTH = "OAuth"; + + /** + * The authorized user if it can be found for this token + * + * @return return the user for the token or null if not authorized + */ + IUser getUser(); + + /** + * This can trigger a remote call if a user has not attempted to authorize + * previously + * + * @return true if authorized; false otherwise + */ + boolean isAuthorized(); + + /** + * The authorization scope if it can be determined. + * + * @return the scope or null if unknown + */ + String getAuthScheme(); + + /** + * Token to use for authentication. Will return non-null value if authorized + * + */ + String getToken(); + + /** + * The token to try and use for communication to the apiserver + * + */ + void setToken(String token); + + /** + * A username to use for authenticating + * + */ + void setUserName(String userName); + + /** + * A username to use for authenticating + * + * @return userName + */ + String getUserName(); + + /** + * Password to use to authenticate to retrieve a token + * + */ + void setPassword(String password); + + /** + * Password to use to authenticate to retrieve a token + * + * @return password + */ + String getPassword(); + + /** + * Time in ?? when the token expires. Will return non-null value if authorized + * + */ + String getExpiresIn(); + + /** + * Retrieve the authorization details for a server + * + */ + IAuthorizationDetails getAuthorizationDetails(); + + /** + * Invalidates this context which forces re-authentication. The context gets unauthenticated, + * User and token are cleared. + */ + void invalidate(); } diff --git a/src/main/java/com/openshift/restclient/authorization/IAuthorizationDetails.java b/src/main/java/com/openshift/restclient/authorization/IAuthorizationDetails.java index 4f233dad..3668202c 100644 --- a/src/main/java/com/openshift/restclient/authorization/IAuthorizationDetails.java +++ b/src/main/java/com/openshift/restclient/authorization/IAuthorizationDetails.java @@ -8,35 +8,34 @@ * Contributors: * Red Hat, Inc. - initial API and implementation ******************************************************************************/ + package com.openshift.restclient.authorization; /** - * The details about how to manually obtain - * a request token - * - * @author Jeff Cantrill + * The details about how to manually obtain a request token + * */ public interface IAuthorizationDetails { - - /** - * The message returned from the server - * for being unauthorized if provided - * @return the message or empty string - */ - String getMessage(); - - /** - * The link to visit to request a valid - * token that can be used to access - * the server if provided - * @return the link or null if not provided - */ - String getRequestTokenLink(); - - /** - * The authentication scheme - * @return - */ - String getScheme(); - + + /** + * The message returned from the server for being unauthorized if provided + * + * @return the message or empty string + */ + String getMessage(); + + /** + * The link to visit to request a valid token that can be used to access the + * server if provided + * + * @return the link or null if not provided + */ + String getRequestTokenLink(); + + /** + * The authentication scheme + * + */ + String getScheme(); + } diff --git a/src/main/java/com/openshift/restclient/authorization/IAuthorizationStrategy.java b/src/main/java/com/openshift/restclient/authorization/IAuthorizationStrategy.java deleted file mode 100644 index 23e2a1bf..00000000 --- a/src/main/java/com/openshift/restclient/authorization/IAuthorizationStrategy.java +++ /dev/null @@ -1,40 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2015 Red Hat, Inc. Distributed under license by Red Hat, Inc. - * All rights reserved. This program is made available under the terms of the - * Eclipse Public License v1.0 which accompanies this distribution, and is - * available at http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: Red Hat, Inc. - ******************************************************************************/ -package com.openshift.restclient.authorization; - -/** - * Authorization interface to provide various authorization mechanisms - * to an OpenShift server - * - * @author Jeff Cantrill - * - */ -public interface IAuthorizationStrategy{ - - /** - * Authorizes the given request - * @param request - */ - void authorize(IRequest request); - - - void accept(IAuthorizationStrategyVisitor visitor); - - /** - * Return the token that is used for authentication - * @return - */ - String getToken(); - - /** - * Returns the username for this strategy. - * @return - */ - String getUsername(); -} diff --git a/src/main/java/com/openshift/restclient/authorization/IRequest.java b/src/main/java/com/openshift/restclient/authorization/IRequest.java deleted file mode 100644 index 84bdfbab..00000000 --- a/src/main/java/com/openshift/restclient/authorization/IRequest.java +++ /dev/null @@ -1,27 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2015 Red Hat, Inc. Distributed under license by Red Hat, Inc. - * All rights reserved. This program is made available under the terms of the - * Eclipse Public License v1.0 which accompanies this distribution, and is - * available at http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: Red Hat, Inc. - ******************************************************************************/ -package com.openshift.restclient.authorization; - -/** - * A type to decouple an IAuthorizationStrategy from - * the underlying connection stream - * - * @author Jeff Cantrill - */ -public interface IRequest { - - /** - * Add the property with the given name and - * value to the underlying request - * - * @param name - * @param value - */ - void setProperty(String name, String value); -} diff --git a/src/main/java/com/openshift/restclient/authorization/ResourceForbiddenException.java b/src/main/java/com/openshift/restclient/authorization/ResourceForbiddenException.java index 12b8e039..2e81715e 100644 --- a/src/main/java/com/openshift/restclient/authorization/ResourceForbiddenException.java +++ b/src/main/java/com/openshift/restclient/authorization/ResourceForbiddenException.java @@ -6,26 +6,22 @@ * * Contributors: Red Hat, Inc. - initial API and implementation ******************************************************************************/ + package com.openshift.restclient.authorization; import com.openshift.restclient.OpenShiftException; import com.openshift.restclient.model.IStatus; -/** - * @author Jeff Cantrill - */ public class ResourceForbiddenException extends OpenShiftException { - private static final long serialVersionUID = 6998191096256199081L; + private static final long serialVersionUID = 6998191096256199081L; - public ResourceForbiddenException(String message, Throwable e) { - super(message, e); - } + public ResourceForbiddenException(String message, Throwable e) { + super(message, e); + } - public ResourceForbiddenException(String message, IStatus status, Throwable e) { - super(e, status, message); - } - - + public ResourceForbiddenException(String message, IStatus status, Throwable e) { + super(e, status, message); + } } diff --git a/src/main/java/com/openshift/restclient/authorization/TokenAuthorizationStrategy.java b/src/main/java/com/openshift/restclient/authorization/TokenAuthorizationStrategy.java deleted file mode 100644 index 48544bdf..00000000 --- a/src/main/java/com/openshift/restclient/authorization/TokenAuthorizationStrategy.java +++ /dev/null @@ -1,46 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2015 Red Hat, Inc. Distributed under license by Red Hat, Inc. - * All rights reserved. This program is made available under the terms of the - * Eclipse Public License v1.0 which accompanies this distribution, and is - * available at http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: Red Hat, Inc. - ******************************************************************************/ -package com.openshift.restclient.authorization; - -import com.openshift.restclient.http.IHttpConstants; - -/** - * Authorization stategy to add a Bearer Token to a request - * - * @author Jeff Cantrill - * @author Andre Dietisheim - */ -public class TokenAuthorizationStrategy extends AbstractAuthorizationStrategy { - - private final String token; - - public TokenAuthorizationStrategy(String token) { - this(token, null); - } - - public TokenAuthorizationStrategy(String token, String username) { - super(username); - this.token = token; - } - - @Override - public void authorize(IRequest request) { - request.setProperty(IHttpConstants.PROPERTY_AUTHORIZATION, String.format("%s %s", IHttpConstants.AUTHORIZATION_BEARER, token)); - } - - @Override - public String getToken(){ - return this.token; - } - - @Override - public void accept(IAuthorizationStrategyVisitor visitor) { - visitor.visit(this); - } -} diff --git a/src/main/java/com/openshift/restclient/authorization/URLConnectionRequest.java b/src/main/java/com/openshift/restclient/authorization/URLConnectionRequest.java deleted file mode 100644 index ca084353..00000000 --- a/src/main/java/com/openshift/restclient/authorization/URLConnectionRequest.java +++ /dev/null @@ -1,29 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2015 Red Hat, Inc. Distributed under license by Red Hat, Inc. - * All rights reserved. This program is made available under the terms of the - * Eclipse Public License v1.0 which accompanies this distribution, and is - * available at http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: Red Hat, Inc. - ******************************************************************************/ -package com.openshift.restclient.authorization; - -import java.net.URLConnection; - -/** - * @author Jeff Cantrill - */ -public class URLConnectionRequest implements IRequest { - - private final URLConnection connection; - - public URLConnectionRequest(URLConnection connection) { - this.connection = connection; - } - - @Override - public void setProperty(String name, String value) { - connection.setRequestProperty(name, value); - } - -} diff --git a/src/main/java/com/openshift/restclient/authorization/UnauthorizedException.java b/src/main/java/com/openshift/restclient/authorization/UnauthorizedException.java index c22e40d1..49e165e2 100644 --- a/src/main/java/com/openshift/restclient/authorization/UnauthorizedException.java +++ b/src/main/java/com/openshift/restclient/authorization/UnauthorizedException.java @@ -1,11 +1,12 @@ /******************************************************************************* - * Copyright (c) 2015 Red Hat, Inc. Distributed under license by Red Hat, Inc. + * Copyright (c) 2015-2019 Red Hat, Inc. Distributed under license by Red Hat, Inc. * All rights reserved. This program is made available under the terms of the * Eclipse Public License v1.0 which accompanies this distribution, and is * available at http://www.eclipse.org/legal/epl-v10.html * * Contributors: Red Hat, Inc. - initial API and implementation ******************************************************************************/ + package com.openshift.restclient.authorization; import org.apache.commons.lang.StringUtils; @@ -13,44 +14,47 @@ import com.openshift.restclient.OpenShiftException; import com.openshift.restclient.model.IStatus; -/** - * @author Jeff Cantrill - */ public class UnauthorizedException extends OpenShiftException { - private static final long serialVersionUID = -3999801367045252906L; - private static final String MSG_BASE = "Unauthorized to access resource."; - private IAuthorizationDetails details; - private IStatus status; - - public UnauthorizedException(IAuthorizationDetails details) { - this(details, null); - } - - public UnauthorizedException(IAuthorizationDetails details, IStatus status) { - super(String.format("%s See the authorization details for additional information or contact your system administrator.", MSG_BASE)); - this.details = details; - this.status = status; - } - - public IAuthorizationDetails getAuthorizationDetails() { - return details; - } - - @Override - public String getMessage() { - String scheme = details.getScheme(); - if(StringUtils.isNotBlank(scheme)){ - return String.format("%s You can access the server using %s authentication.", MSG_BASE, scheme); - } - return StringUtils.defaultIfEmpty(details.getMessage(), super.getMessage()); - } - - @Override - public IStatus getStatus() { - return this.status; - } - - + private static final long serialVersionUID = -3999801367045252906L; + private static final String MSG_BASE = "Unauthorized to access resource."; + private final String message; + private final IStatus status; + private final IAuthorizationDetails details; + + public UnauthorizedException(IAuthorizationDetails details) { + this(details, null); + } + + public UnauthorizedException(IAuthorizationDetails details, IStatus status) { + super(MSG_BASE + + " See the authorization details for additional information or contact your system administrator."); + this.status = status; + this.details = details; + if (details != null) { + if (StringUtils.isNotBlank(details.getScheme())) { + message = String.format("%s You can access the server using %s authentication.", MSG_BASE, + details.getScheme()); + } else { + message = details.getMessage(); + } + } else { + message = super.getMessage(); + } + } + + public IAuthorizationDetails getAuthorizationDetails() { + return details; + } + + @Override + public String getMessage() { + return message; + } + + @Override + public IStatus getStatus() { + return this.status; + } } diff --git a/src/main/java/com/openshift/restclient/capability/CapabilityVisitor.java b/src/main/java/com/openshift/restclient/capability/CapabilityVisitor.java index 2b7c26d9..c76d1c2b 100644 --- a/src/main/java/com/openshift/restclient/capability/CapabilityVisitor.java +++ b/src/main/java/com/openshift/restclient/capability/CapabilityVisitor.java @@ -6,42 +6,44 @@ * * Contributors: Red Hat, Inc. ******************************************************************************/ + package com.openshift.restclient.capability; -import java.lang.reflect.Type; import java.lang.reflect.ParameterizedType; +import java.lang.reflect.Type; /** * A visitor used to access a resources capability - * @param The capability type - * @param A context significant to the visitor * - * @author Jeff Cantrill + * @param + * The capability type + * @param + * A context significant to the visitor + * */ public abstract class CapabilityVisitor { - - private Type type; - - /** - * Visits the capability - * @param capability - * @return A return type that is significant to the caller - */ - public abstract R visit(T capability); - - /** - * Gets the Capability type - * @return - */ - public final Type getCapabilityType(){ - if(type == null) { - Type superclass = getClass().getGenericSuperclass(); - if (superclass instanceof Class) { - throw new RuntimeException("Missing type parameter."); - } - this.type = ((ParameterizedType) superclass).getActualTypeArguments()[0]; - } + + private Type type; + + /** + * Visits the capability + * + */ + public abstract R visit(T capability); + + /** + * Gets the Capability type + * + */ + public final Type getCapabilityType() { + if (type == null) { + Type superclass = getClass().getGenericSuperclass(); + if (superclass instanceof Class) { + throw new RuntimeException("Missing type parameter."); + } + this.type = ((ParameterizedType) superclass).getActualTypeArguments()[0]; + } return type; - } - + } + } diff --git a/src/main/java/com/openshift/restclient/capability/IBinaryCapability.java b/src/main/java/com/openshift/restclient/capability/IBinaryCapability.java index dcb3da98..dbb7db74 100644 --- a/src/main/java/com/openshift/restclient/capability/IBinaryCapability.java +++ b/src/main/java/com/openshift/restclient/capability/IBinaryCapability.java @@ -6,27 +6,31 @@ * * Contributors: Red Hat, Inc. ******************************************************************************/ + package com.openshift.restclient.capability; /** * @author Andre Dietisheim */ public interface IBinaryCapability extends ICapability { - - /** - * Optional arguments to pass when running the {@code oc} command. - */ - public enum OpenShiftBinaryOption { - /** option to skip verifying the certificates during TLS connection establishment. */ - SKIP_TLS_VERIFY, - /** option to exclude the {@code .git} folder in the list of files/folders to synchronize. */ - EXCLUDE_GIT_FOLDER, - /** option to not transfer file permissions. */ - NO_PERMS, - /** option to delete delete extraneous files from destination directories**/ - DELETE - } - - static final String OPENSHIFT_BINARY_LOCATION = "openshift.restclient.oc.location"; + + static final OpenShiftBinaryOption SKIP_TLS_VERIFY = new SkipTlsVerify(); + + /** + * Skips the SSL/TLS Verification when using a binary capability + */ + static class SkipTlsVerify implements OpenShiftBinaryOption { + + @Override + public void append(StringBuilder commandLine) { + commandLine.append(" --insecure-skip-tls-verify=true"); + } + } + + static interface OpenShiftBinaryOption { + void append(StringBuilder builder); + } + + static final String OPENSHIFT_BINARY_LOCATION = "openshift.restclient.oc.location"; } diff --git a/src/main/java/com/openshift/restclient/capability/ICapability.java b/src/main/java/com/openshift/restclient/capability/ICapability.java index 8d467ab7..520a015b 100644 --- a/src/main/java/com/openshift/restclient/capability/ICapability.java +++ b/src/main/java/com/openshift/restclient/capability/ICapability.java @@ -6,25 +6,22 @@ * * Contributors: Red Hat, Inc. ******************************************************************************/ + package com.openshift.restclient.capability; -/** - * @author Jeff Cantrill - */ public interface ICapability { - - /** - * Allow the implementation of the capability to determine - * if it is supported on the OpenShift server. Implementations - * should return false if they can not - * - * @return true if the capability exists - */ - boolean isSupported(); - - /** - * Well known name of the capability - * @return - */ - String getName(); + + /** + * Allow the implementation of the capability to determine if it is supported on + * the OpenShift server. Implementations should return false if they can not + * + * @return true if the capability exists + */ + boolean isSupported(); + + /** + * Well known name of the capability + * + */ + String getName(); } diff --git a/src/main/java/com/openshift/restclient/capability/ICapable.java b/src/main/java/com/openshift/restclient/capability/ICapable.java index ff24d336..df3cf42b 100644 --- a/src/main/java/com/openshift/restclient/capability/ICapable.java +++ b/src/main/java/com/openshift/restclient/capability/ICapable.java @@ -6,40 +6,41 @@ * * Contributors: Red Hat, Inc. ******************************************************************************/ + package com.openshift.restclient.capability; /** - * ICapable allows a source to be queried and identify its - * capabilities + * ICapable allows a source to be queried and identify its capabilities * - * @author Jeff Cantrill */ public interface ICapable { - /** - * Gets the capability of the desired type - * - * @param capability - * @return an implementation of the given capability - */ - T getCapability(Class capability); - - /** - * Determines if the client supports the desired capability - * - * @param capability - * @return true if the client is able to offer this capability - */ - boolean supports(Class capability); - - /** - * Uses the given visitor to access the desired capability if it - * is supported - * - * @param visitor A visitor looking for a given Capability type - * @param visitor A capability visitor - * @param unsupportedCapabililityValue The value to return when the capability is not supported - * @return A type that is expected by the caller - */ - R accept(CapabilityVisitor visitor, R unsupportedCapabililityValue); + /** + * Gets the capability of the desired type + * + * @param capability + * @return an implementation of the given capability + */ + T getCapability(Class capability); + + /** + * Determines if the client supports the desired capability + * + * @return true if the client is able to offer this capability + */ + boolean supports(Class capability); + + /** + * Uses the given visitor to access the desired capability if it is supported + * + * @param visitor + * A visitor looking for a given Capability type + * @param + * visitor A capability visitor + * @param + * unsupportedCapabililityValue The value to return when the + * capability is not supported + * @return A type that is expected by the caller + */ + R accept(CapabilityVisitor visitor, R unsupportedCapabililityValue); } diff --git a/src/main/java/com/openshift/restclient/capability/IStoppable.java b/src/main/java/com/openshift/restclient/capability/IStoppable.java new file mode 100644 index 00000000..2556a31c --- /dev/null +++ b/src/main/java/com/openshift/restclient/capability/IStoppable.java @@ -0,0 +1,25 @@ +/******************************************************************************* + * Copyright (c) 2016 Red Hat, Inc. + * Distributed under license by Red Hat, Inc. All rights reserved. + * This program is made available under the terms of the + * Eclipse Public License v1.0 which accompanies this distribution, + * and is available at http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Red Hat, Inc. - initial API and implementation + ******************************************************************************/ + +package com.openshift.restclient.capability; + +/** + * Handle to something that can be explicitly stopped or terminated + * + * + */ +public interface IStoppable { + + /** + * Stop the process + */ + void stop(); +} diff --git a/src/main/java/com/openshift/restclient/capability/resources/IBinaryBuildTriggerable.java b/src/main/java/com/openshift/restclient/capability/resources/IBinaryBuildTriggerable.java new file mode 100644 index 00000000..c7ac6bca --- /dev/null +++ b/src/main/java/com/openshift/restclient/capability/resources/IBinaryBuildTriggerable.java @@ -0,0 +1,131 @@ +/******************************************************************************* + * Copyright (c) 2018 Red Hat, Inc. + * Distributed under license by Red Hat, Inc. All rights reserved. + * This program is made available under the terms of the + * Eclipse Public License v1.0 which accompanies this distribution, + * and is available at http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Red Hat, Inc. - initial API and implementation + ******************************************************************************/ + +package com.openshift.restclient.capability.resources; + +import java.io.InputStream; + +import com.openshift.restclient.capability.ICapability; +import com.openshift.restclient.model.IBuild; + +/** + * Capability to trigger a binary build based on the build configuration + * + */ +public interface IBinaryBuildTriggerable extends ICapability { + + /** + * Trigger a binary build based on a build config + * + * @param payload the binary payload process by build + * @return The build that was triggered + */ + IBuild triggerBinary(InputStream payload); + + /** + * Set the asFile parameter + * + * @param asFile the asFile + */ + void setAsFile(String asFile); + + /** + * Get the asFile parameter + * + * @return the asFile parameter + */ + String getAsFile(); + + /** + * Set the SCM commit + * + * @param commit + * the SCM commit string + */ + void setCommit(String commit); + + /** + * Get the SCM commit + * + * @return the SCM commit string + */ + String getCommit(); + + /** + * Set the author email + * + * @param authorEmail the author email + */ + void setAuthorEmail(String authorEmail); + + /** + * Get the author email + * + * @return the author email + */ + String getAuthorEmail(); + + /** + * Set the author name + * + * @param authorName the author name + */ + void setAuthorName(String authorName); + + /** + * Get the author name + * + * @return the author name + */ + String getAuthorName(); + + /** + * Set the committer email + * + * @param committerEmail the committer email + */ + void setCommitterEmail(String committerEmail); + + /** + * Get the committer email + * + * @return the committer email + */ + String getCommitterEmail(); + + /** + * Set the committer name + * + * @param committerName the committer name + */ + void setCommitterName(String committerName); + + /** + * Get the committer name + * + * @return the committer name + */ + String getCommitterName(); + + /** + * Set the message + * + * @param message the message + */ + void setMessage(String message); + + /** + * Get the message + * + * @return the message + */ + String getMessage(); +} diff --git a/src/main/java/com/openshift/restclient/capability/resources/IBuildCancelable.java b/src/main/java/com/openshift/restclient/capability/resources/IBuildCancelable.java index b70832bb..d2a70879 100644 --- a/src/main/java/com/openshift/restclient/capability/resources/IBuildCancelable.java +++ b/src/main/java/com/openshift/restclient/capability/resources/IBuildCancelable.java @@ -1,10 +1,31 @@ +/******************************************************************************* + * Copyright (c) 2016 Red Hat, Inc. + * Distributed under license by Red Hat, Inc. All rights reserved. + * This program is made available under the terms of the + * Eclipse Public License v1.0 which accompanies this distribution, + * and is available at http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Red Hat, Inc. - initial API and implementation + ******************************************************************************/ + package com.openshift.restclient.capability.resources; import com.openshift.restclient.capability.ICapability; import com.openshift.restclient.model.IBuild; +/** + * Capability to cancel a build that is running + * + * @author jeff.cantrill + * + */ public interface IBuildCancelable extends ICapability { - - IBuild cancel(); + + /** + * Cancel the build + * + */ + IBuild cancel(); } diff --git a/src/main/java/com/openshift/restclient/capability/resources/IBuildTriggerable.java b/src/main/java/com/openshift/restclient/capability/resources/IBuildTriggerable.java index d2802186..3083300d 100644 --- a/src/main/java/com/openshift/restclient/capability/resources/IBuildTriggerable.java +++ b/src/main/java/com/openshift/restclient/capability/resources/IBuildTriggerable.java @@ -8,29 +8,77 @@ * Contributors: * Red Hat, Inc. - initial API and implementation ******************************************************************************/ + package com.openshift.restclient.capability.resources; +import java.util.List; + import com.openshift.restclient.capability.ICapability; import com.openshift.restclient.model.IBuild; /** * Capability to trigger a build based on the build configuration - * @author Jeff Cantrill * */ public interface IBuildTriggerable extends ICapability { - - /** - * Trigger a build based on a build config - * @return The build that was triggered - */ - IBuild trigger(); - - /** - * Trigger a build with the given source level commit id - * @param commitId - * @return The build that was triggered - */ - IBuild trigger(String commitId); + + /** + * Trigger a build based on a build config + * + * @return The build that was triggered + */ + IBuild trigger(); + + /** + * Trigger a build with the given source level commit id + * + * @return The build that was triggered + * @deprecated Replaced by calling {@link #setCommitId(String)}, followed by + * {@link #trigger()}. + */ + IBuild trigger(String commitId); + + /** + * Set the commit level for the SCM extraction of the source code the build + * operates against + * + * @param commitId + * the specific hexadecimal commit ID associated with a SCM log level + */ + void setCommitId(String commitId); + + /** + * Get the commit level for the SCM extraction of the source code the build + * operates against + * + * @return the specific hexadecimal commit ID associated with a SCM log level + */ + String getCommitId(); + + /** + * Add a human readable short explanation of why this build request was issued + * + * @param cause + * the description to add to the list of causes for this request + */ + void addBuildCause(String cause); + + /** + * Get the list of human readable short explanations of why this build request + * was issued + * + * @return list of reasons for the build + */ + List getBuildCauses(); + + /** + * Sets an environment variable for this build request + * + * @param name + * The name of the environment variable + * @param value + * The value of the environment variable + */ + void setEnvironmentVariable(String name, String value); } diff --git a/src/main/java/com/openshift/restclient/capability/resources/IClientCapability.java b/src/main/java/com/openshift/restclient/capability/resources/IClientCapability.java index c48d6d2b..2653d524 100644 --- a/src/main/java/com/openshift/restclient/capability/resources/IClientCapability.java +++ b/src/main/java/com/openshift/restclient/capability/resources/IClientCapability.java @@ -8,6 +8,7 @@ * Contributors: * Red Hat, Inc. - initial API and implementation ******************************************************************************/ + package com.openshift.restclient.capability.resources; import com.openshift.restclient.IClient; @@ -15,10 +16,9 @@ /** * The capability to retrieve the client from a resource - * @author Jeff Cantrill * */ public interface IClientCapability extends ICapability { - - IClient getClient(); + + IClient getClient(); } diff --git a/src/main/java/com/openshift/restclient/capability/resources/IDeployCapability.java b/src/main/java/com/openshift/restclient/capability/resources/IDeployCapability.java index 0a1b0d61..90a77449 100644 --- a/src/main/java/com/openshift/restclient/capability/resources/IDeployCapability.java +++ b/src/main/java/com/openshift/restclient/capability/resources/IDeployCapability.java @@ -8,22 +8,24 @@ * Contributors: * Red Hat, Inc. - initial API and implementation ******************************************************************************/ + package com.openshift.restclient.capability.resources; import com.openshift.restclient.capability.ICapability; /** - * Capability to trigger a new deployment of a deploymentconfig - * (e.g. oc deploy foo) - * @author jeff.cantrill + * Capability to trigger a new deployment of a deploymentconfig (e.g. oc deploy + * foo) * */ public interface IDeployCapability extends ICapability { - /** - * Deploy the latest deployment - * @throws an OpenShiftException if there is an error (e.g. 404) - */ - void deploy(); - + /** + * Deploy the latest deployment + * + * @throws an + * OpenShiftException if there is an error (e.g. 404) + */ + void deploy(); + } diff --git a/src/main/java/com/openshift/restclient/capability/resources/IDeploymentConfigTraceability.java b/src/main/java/com/openshift/restclient/capability/resources/IDeploymentConfigTraceability.java index ce2fe06c..36fbb0a8 100644 --- a/src/main/java/com/openshift/restclient/capability/resources/IDeploymentConfigTraceability.java +++ b/src/main/java/com/openshift/restclient/capability/resources/IDeploymentConfigTraceability.java @@ -6,20 +6,18 @@ * * Contributors: Red Hat, Inc. ******************************************************************************/ + package com.openshift.restclient.capability.resources; import com.openshift.restclient.capability.ICapability; import com.openshift.restclient.model.IDeploymentConfig; -/** - * @author Jeff Cantrill - */ public interface IDeploymentConfigTraceability extends ICapability { - - /** - * Get the deployment configuration for a resource - * @return - */ - IDeploymentConfig getDeploymentConfig(); + + /** + * Get the deployment configuration for a resource + * + */ + IDeploymentConfig getDeploymentConfig(); } diff --git a/src/main/java/com/openshift/restclient/capability/resources/IDeploymentTraceability.java b/src/main/java/com/openshift/restclient/capability/resources/IDeploymentTraceability.java index ecd7a278..e2e1cba7 100644 --- a/src/main/java/com/openshift/restclient/capability/resources/IDeploymentTraceability.java +++ b/src/main/java/com/openshift/restclient/capability/resources/IDeploymentTraceability.java @@ -6,24 +6,23 @@ * * Contributors: Red Hat, Inc. ******************************************************************************/ + package com.openshift.restclient.capability.resources; import com.openshift.restclient.capability.ICapability; import com.openshift.restclient.model.IReplicationController; /** - * Trace the source of what caused a resource - * to be deployed + * Trace the source of what caused a resource to be deployed * - * @author Jeff Cantrill */ public interface IDeploymentTraceability extends ICapability { - /** - * Get the deployment of a resource. The value returned when - * the capability is not supported is not guaranteed. - * - * @return IReplicationController if the capability is supported. - */ - IReplicationController getDeployment(); + /** + * Get the deployment of a resource. The value returned when the capability is + * not supported is not guaranteed. + * + * @return IReplicationController if the capability is supported. + */ + IReplicationController getDeployment(); } diff --git a/src/main/java/com/openshift/restclient/capability/resources/IDeploymentTriggerable.java b/src/main/java/com/openshift/restclient/capability/resources/IDeploymentTriggerable.java new file mode 100644 index 00000000..75a43eb0 --- /dev/null +++ b/src/main/java/com/openshift/restclient/capability/resources/IDeploymentTriggerable.java @@ -0,0 +1,62 @@ +/******************************************************************************* + * Copyright (c) 2015 Red Hat, Inc. + * Distributed under license by Red Hat, Inc. All rights reserved. + * This program is made available under the terms of the + * Eclipse Public License v1.0 which accompanies this distribution, + * and is available at http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Red Hat, Inc. - initial API and implementation + ******************************************************************************/ + +package com.openshift.restclient.capability.resources; + +import com.openshift.restclient.capability.ICapability; +import com.openshift.restclient.model.IDeploymentConfig; + +/** + * Capability to trigger a deployment via the instantiate endpoint + * @author gmontero + */ +public interface IDeploymentTriggerable extends ICapability { + + /** + * Trigger a deployment based on a deployment config + * @return The updated deployment config after the deployment was triggered + */ + IDeploymentConfig trigger(); + + /** + * If set the true latest will update the deployment config with the latest state from all triggers. + */ + void setLatest(boolean latest); + + /** + * Returns the current setting of the latest flag. + */ + boolean isLatest(); + + /** + * If set to try force will try to force a new deployment to run. If the deployment config is paused, + * then setting this to true will return an Invalid error. + */ + void setForce(boolean force); + + /** + * Returns the latest setting of the force flag. + */ + boolean isForce(); + + /** + * The name of the deployment config; note, the name in the corresponding oapi type + * is not in the k8s metadata object + * @param name of the deployment config + */ + void setResourceName(String name); + + /** + * Returns the name of the deployment config seeded into the deployment request + */ + String getResourceName(); + +} diff --git a/src/main/java/com/openshift/restclient/capability/resources/IImageStreamImportCapability.java b/src/main/java/com/openshift/restclient/capability/resources/IImageStreamImportCapability.java index 4b7655c9..a11acff4 100644 --- a/src/main/java/com/openshift/restclient/capability/resources/IImageStreamImportCapability.java +++ b/src/main/java/com/openshift/restclient/capability/resources/IImageStreamImportCapability.java @@ -8,6 +8,7 @@ * Contributors: * Red Hat, Inc. - initial API and implementation ******************************************************************************/ + package com.openshift.restclient.capability.resources; import com.openshift.restclient.capability.ICapability; @@ -17,17 +18,14 @@ /** * Import tags from a repository for an image * - * @author jeff.cantrill * */ public interface IImageStreamImportCapability extends ICapability { - /** - * Import docker image metadata - * @param uri - * @return - * @throws OpenShiftException - */ - IImageStreamImport importImageMetadata(DockerImageURI uri); - + /** + * Import docker image metadata + * + */ + IImageStreamImport importImageMetadata(DockerImageURI uri); + } diff --git a/src/main/java/com/openshift/restclient/capability/resources/IPodLogRetrieval.java b/src/main/java/com/openshift/restclient/capability/resources/IPodLogRetrieval.java index 15bcb3a2..c63b4640 100644 --- a/src/main/java/com/openshift/restclient/capability/resources/IPodLogRetrieval.java +++ b/src/main/java/com/openshift/restclient/capability/resources/IPodLogRetrieval.java @@ -8,55 +8,52 @@ * Contributors: * Red Hat, Inc. - initial API and implementation ******************************************************************************/ + package com.openshift.restclient.capability.resources; import java.io.InputStream; -import com.openshift.restclient.capability.ICapability; import com.openshift.restclient.capability.IBinaryCapability.OpenShiftBinaryOption; +import com.openshift.restclient.capability.ICapability; -/** - * - * @author Jeff Cantrill - * - */ public interface IPodLogRetrieval extends ICapability { - - - /** - * Return the logs from the pod, optionally following them. - * - * @param follow - * true if following. Default: false - * @param options - * the options to pass to the underlying {@code oc} command - * @return the log output stream - */ - InputStream getLogs(boolean follow, OpenShiftBinaryOption... options); - - /** - * Return the logs from the pod, optionally following them - * - * @param follow - * true; if following, Default: false - * @param container - * the name of the container in the pod to get logs uses the - * first container if empty - * @param options - * the options to pass to the underlying {@code oc} command - * @return the log output stream - */ - InputStream getLogs(boolean follow, String container, OpenShiftBinaryOption... options); - - /** - * Stop retrieving logs for all containers - */ - void stop(); - - /** - * Stop retrieving logs for a specific container - * @param container the name of the container - */ - void stop(String container); + + /** + * Return the logs from the pod, optionally following them. + * + * @param follow + * true if following. Default: false + * @param options + * the options to pass to the underlying {@code oc} command + * @return the log output stream + */ + InputStream getLogs(boolean follow, OpenShiftBinaryOption... options); + + /** + * Return the logs from the pod, optionally following them + * + * @param follow + * true; if following, Default: false + * @param container + * the name of the container in the pod to get logs uses the first + * container if empty + * @param options + * the options to pass to the underlying {@code oc} command + * @return the log output stream + */ + InputStream getLogs(boolean follow, String container, OpenShiftBinaryOption... options); + + /** + * Stop retrieving logs for all containers + */ + void stop(); + + /** + * Stop retrieving logs for a specific container + * + * @param container + * the name of the container + */ + void stop(String container); } diff --git a/src/main/java/com/openshift/restclient/capability/resources/IPodLogRetrievalAsync.java b/src/main/java/com/openshift/restclient/capability/resources/IPodLogRetrievalAsync.java new file mode 100644 index 00000000..d4149ddb --- /dev/null +++ b/src/main/java/com/openshift/restclient/capability/resources/IPodLogRetrievalAsync.java @@ -0,0 +1,151 @@ +/******************************************************************************* + * Copyright (c) 2016-2018 Red Hat, Inc. + * Distributed under license by Red Hat, Inc. All rights reserved. + * This program is made available under the terms of the + * Eclipse Public License v1.0 which accompanies this distribution, + * and is available at http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Red Hat, Inc. - initial API and implementation + ******************************************************************************/ + +package com.openshift.restclient.capability.resources; + +import java.util.Collections; +import java.util.HashMap; +import java.util.Map; + +import org.apache.commons.lang.StringUtils; + +import com.openshift.restclient.capability.ICapability; +import com.openshift.restclient.capability.IStoppable; + +/** + * Retrieve logs in an async call + * + * + */ +public interface IPodLogRetrievalAsync extends ICapability { + + /** + * Start retrieving logs using the given listener and options + * + * @return A Handle to allow termination of log streaming + */ + IStoppable start(IPodLogListener listener); + + /** + * Start retrieving logs using the given listener and options + * + * @param options + * options for retrieving logs + * @return A Handle to allow termination of log streaming + */ + IStoppable start(IPodLogListener listener, Options options); + + /** + * A callback for log messages + * + * @author jeff.cantrill + * + */ + interface IPodLogListener { + + /** + * Callback received on initial connection + */ + void onOpen(); + + /** + * A log message + * + */ + void onMessage(String message); + + /** + * Callback received when the connection to the pod is terminated from the + * server-side + * + * @param code + * a valid http response code + * @param reason + * a reason for termination, may be null + */ + void onClose(int code, String reason); + + /** + * Callback received when the web socket connection fails + * + * @param t + * the exception which occurred + */ + void onFailure(Throwable t); + + } + + /** + * Options for retrieving logs using a fluent builder style + * + * @author jeff.cantrill + * + */ + public static class Options { + + private static final String CONTAINER = "container"; + private static final String FOLLOW = "follow"; + private boolean follow = false; + private String container = null; + private Map options = new HashMap<>(); + + /** + * The container from which to retrieve logs + * + */ + public Options container(String container) { + this.container = container; + return this; + } + + /** + * follow the logs, defaults to false + * + */ + public Options follow() { + return follow(true); + } + + /** + * follow the logs + * + */ + public Options follow(boolean value) { + this.follow = value; + return this; + } + + /** + * Add an option that is not explicitly defined. These will override any + * explicit options if there are collisions + * + */ + public Options parameter(String name, String value) { + options.put(name, value); + return this; + } + + /** + * The collective options + * + * @return a map of all the options + */ + public Map getMap() { + if (!options.containsKey(FOLLOW) && follow) { + options.put(FOLLOW, "true"); + } + if (!options.containsKey(CONTAINER) && StringUtils.isNotBlank(container)) { + options.put(CONTAINER, container); + } + return Collections.unmodifiableMap(options); + } + } +} diff --git a/src/main/java/com/openshift/restclient/capability/resources/IPortForwardable.java b/src/main/java/com/openshift/restclient/capability/resources/IPortForwardable.java index 2f075ee7..62e3bbd4 100644 --- a/src/main/java/com/openshift/restclient/capability/resources/IPortForwardable.java +++ b/src/main/java/com/openshift/restclient/capability/resources/IPortForwardable.java @@ -8,6 +8,7 @@ * Contributors: * Red Hat, Inc. - initial API and implementation ******************************************************************************/ + package com.openshift.restclient.capability.resources; import java.util.Collection; @@ -18,113 +19,120 @@ /** * Defines if a pod can support port forwarding - * @author Jeff Cantrill * */ public interface IPortForwardable extends IBinaryCapability { - /** - * Forward the ports to a pod. This is a non-blocking call - * @param pairs the pairs of local/remote ports to link together - * @param options - * the options to pass to the underlying {@code oc} command - * @throws OpenShiftException if unable to forward ports - */ - void forwardPorts(Collection pairs, OpenShiftBinaryOption...options); - - /** - * The port pairs. - * @return The pairs when forwarding or an empty array; - */ - Collection getPortPairs(); - - /** - * Stop forwarding ports, forcibly if necessary - */ - void stop(); - - /** - * - * @return true if forwarding; false otherwise - */ - boolean isForwarding(); - - /** - * Pairing a local port to the remote port of a container. - * - * @author Jeff Cantrill - */ - static class PortPair { - private int localPort = -1; - private IPort remotePort; - - /** - * Forward traffic to/from the specified port - * @param remotePort - */ - public PortPair(IPort remotePort) { - this(remotePort.getContainerPort(), remotePort); - } - - /** - * Forward traffic on the local port to the remote port. Set localPort - * to '0' to listen on a random local port - * @param localPort - * @param remotePort - */ - public PortPair(int localPort, IPort remotePort) { - this.localPort = localPort; - this.remotePort = remotePort; - } - - public int getLocalPort() { - return localPort; - } - - public void setLocalPort(int port) { - this.localPort = port; - } - - public int getRemotePort() { - return remotePort.getContainerPort(); - } - - public String getName() { - return remotePort.getName(); - } - - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = prime * result + localPort; - result = prime * result + ((remotePort == null) ? 0 : remotePort.hashCode()); - return result; - } - - @Override - public boolean equals(Object obj) { - if (this == obj) - return true; - if (obj == null) - return false; - if (getClass() != obj.getClass()) - return false; - PortPair other = (PortPair) obj; - if (localPort != other.localPort) - return false; - if (remotePort == null) { - if (other.remotePort != null) - return false; - } else if (!remotePort.equals(other.remotePort)) - return false; - return true; - } - - @Override - public String toString() { - return getName() + ": " + this.localPort + "->" + this.getRemotePort(); - } - - } + /** + * Forward the ports to a pod. This is a non-blocking call + * + * @param pairs + * the pairs of local/remote ports to link together + * @param options + * the options to pass to the underlying {@code oc} command + * @throws OpenShiftException + * if unable to forward ports + */ + void forwardPorts(Collection pairs, OpenShiftBinaryOption... options); + + /** + * The port pairs. + * + * @return The pairs when forwarding or an empty array; + */ + Collection getPortPairs(); + + /** + * Stop forwarding ports, forcibly if necessary + */ + void stop(); + + /** + * + * @return true if forwarding; false otherwise + */ + boolean isForwarding(); + + /** + * Pairing a local port to the remote port of a container. + * + */ + static class PortPair { + private int localPort = -1; + private IPort remotePort; + + /** + * Forward traffic to/from the specified port + * + */ + public PortPair(IPort remotePort) { + this(remotePort.getContainerPort(), remotePort); + } + + /** + * Forward traffic on the local port to the remote port. Set localPort to '0' to + * listen on a random local port + * + */ + public PortPair(int localPort, IPort remotePort) { + this.localPort = localPort; + this.remotePort = remotePort; + } + + public int getLocalPort() { + return localPort; + } + + public void setLocalPort(int port) { + this.localPort = port; + } + + public int getRemotePort() { + return remotePort.getContainerPort(); + } + + public String getName() { + return remotePort.getName(); + } + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + localPort; + result = prime * result + ((remotePort == null) ? 0 : remotePort.hashCode()); + return result; + } + + @Override + public boolean equals(Object obj) { + if (this == obj) { + return true; + } + if (obj == null) { + return false; + } + if (getClass() != obj.getClass()) { + return false; + } + PortPair other = (PortPair) obj; + if (localPort != other.localPort) { + return false; + } + if (remotePort == null) { + if (other.remotePort != null) { + return false; + } + } else if (!remotePort.equals(other.remotePort)) { + return false; + } + return true; + } + + @Override + public String toString() { + return getName() + ": " + this.localPort + "->" + this.getRemotePort(); + } + + } } diff --git a/src/main/java/com/openshift/restclient/capability/resources/IProjectTemplateList.java b/src/main/java/com/openshift/restclient/capability/resources/IProjectTemplateList.java index 08d1c828..491fc9de 100644 --- a/src/main/java/com/openshift/restclient/capability/resources/IProjectTemplateList.java +++ b/src/main/java/com/openshift/restclient/capability/resources/IProjectTemplateList.java @@ -6,6 +6,7 @@ * * Contributors: Red Hat, Inc. - initial API and implementation ******************************************************************************/ + package com.openshift.restclient.capability.resources; import java.util.Collection; @@ -14,20 +15,28 @@ import com.openshift.restclient.model.template.ITemplate; /** - * Get the list of templates available for this project. This list includes - * the templates from the default namespace "openshift" + * Get the list of templates available for this project. This list includes the + * templates from the default namespace "openshift" */ public interface IProjectTemplateList extends ICapability { - /** - * Retrieve the templates associated with a specific project - * @return - */ - Collection getTemplates(); - - /** - * Retrieve the common templates from the server (e.g. 'openshift' namespace) - * @return - */ - Collection getCommonTemplates(); + /** + * Retrieve the templates associated with a specific project + * + */ + Collection getTemplates(); + + /** + * Retrieve the common templates from the server (e.g. 'openshift' namespace) + * + */ + Collection getCommonTemplates(); + + /** + * Retrieve the common templates from the server (e.g. 'openshift' namespace) + * + */ + default Collection getCommonTemplates(String clusterNamespace) { + throw new UnsupportedOperationException(); + } } diff --git a/src/main/java/com/openshift/restclient/capability/resources/IProjectTemplateProcessing.java b/src/main/java/com/openshift/restclient/capability/resources/IProjectTemplateProcessing.java index 20a0f9b9..20b7128c 100644 --- a/src/main/java/com/openshift/restclient/capability/resources/IProjectTemplateProcessing.java +++ b/src/main/java/com/openshift/restclient/capability/resources/IProjectTemplateProcessing.java @@ -6,6 +6,7 @@ * * Contributors: Red Hat, Inc. - initial API and implementation ******************************************************************************/ + package com.openshift.restclient.capability.resources; import java.util.Collection; @@ -16,20 +17,19 @@ public interface IProjectTemplateProcessing extends ICapability { - /** - * Processes a template to substitute the parameters - * where necessary for project - * - * @param template The template to process - * @return a config of resources - */ - ITemplate process(ITemplate template); - - /** - * Apply the objects defined in the template to the server - * @param config - * @return - */ - Collection apply(ITemplate template); - + /** + * Processes a template to substitute the parameters where necessary for project + * + * @param template + * The template to process + * @return a config of resources + */ + ITemplate process(ITemplate template); + + /** + * Apply the objects defined in the template to the server + * + */ + Collection apply(ITemplate template); + } diff --git a/src/main/java/com/openshift/restclient/capability/resources/IPropertyAccessCapability.java b/src/main/java/com/openshift/restclient/capability/resources/IPropertyAccessCapability.java index 7acada7c..82dbd2d6 100644 --- a/src/main/java/com/openshift/restclient/capability/resources/IPropertyAccessCapability.java +++ b/src/main/java/com/openshift/restclient/capability/resources/IPropertyAccessCapability.java @@ -8,6 +8,7 @@ * Contributors: * Red Hat, Inc. - initial API and implementation ******************************************************************************/ + package com.openshift.restclient.capability.resources; import java.util.Map; @@ -15,51 +16,46 @@ import com.openshift.restclient.capability.ICapability; /** - * A mechanism to access the underlying content of a json - * structure + * A mechanism to access the underlying content of a json structure * - * Relies on a dot delimited path to indentify the root of the entity - * being returned (e.g. 'metadata.labels'). This does not provide - * a mechanism to retrieve properties across an array kind. + * Relies on a dot delimited path to indentify the root of the entity being + * returned (e.g. 'metadata.labels'). This does not provide a mechanism to + * retrieve properties across an array kind. * - * @author jeff.cantrill * */ public interface IPropertyAccessCapability extends ICapability { - /** - * - * @param path - * @return - * - * @throws @{@link UnresolvablePathException} when the path - * does not resolve to an existing node - */ - Map asMap(String path); - - /** - * Return the string value to the path - * @param path - * @return - * @throws @{@link UnresolvablePathException} when the path - * does not resolve to an existing node - */ - String asString(String path); - - /** - * The exception thrown when a path given to the capability is - * unresolvable - * - * @author jeff.cantrill - * - */ - public static class UnresolvablePathException extends RuntimeException{ + /** + * + * + * @throws @{@link + * UnresolvablePathException} when the path does not resolve to an + * existing node + */ + Map asMap(String path); + + /** + * Return the string value to the path + * + * @throws @{@link + * UnresolvablePathException} when the path does not resolve to an + * existing node + */ + String asString(String path); + + /** + * The exception thrown when a path given to the capability is unresolvable + * + * @author jeff.cantrill + * + */ + public static class UnresolvablePathException extends RuntimeException { - /** - * - */ - private static final long serialVersionUID = 2422016683166925224L; + /** + * + */ + private static final long serialVersionUID = 2422016683166925224L; - - } + } } diff --git a/src/main/java/com/openshift/restclient/capability/resources/IRSyncable.java b/src/main/java/com/openshift/restclient/capability/resources/IRSyncable.java index 7e84411b..4557ba32 100644 --- a/src/main/java/com/openshift/restclient/capability/resources/IRSyncable.java +++ b/src/main/java/com/openshift/restclient/capability/resources/IRSyncable.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2015 Red Hat, Inc. + * Copyright (c) 2015-2018 Red Hat, Inc. * Distributed under license by Red Hat, Inc. All rights reserved. * This program is made available under the terms of the * Eclipse Public License v1.0 which accompanies this distribution, @@ -8,125 +8,206 @@ * Contributors: * Red Hat, Inc. - initial API and implementation ******************************************************************************/ + package com.openshift.restclient.capability.resources; import java.io.InputStream; +import org.apache.commons.lang.ArrayUtils; + import com.openshift.restclient.capability.IBinaryCapability; import com.openshift.restclient.model.IPod; -/** - * Defines if a pod can support port forwarding - * @author Andre Dietisheim - * - */ public interface IRSyncable extends IBinaryCapability { - /** - * Synchronize the give {@code destination} with the given {@code source} - * @param source the source of the rsync - * @param destination the destination of the rsync - * @param options the options to pass to the underlying {@code oc rsync} command - * @return the underlying {@link Process} streams to be displayed in a console. - */ - InputStream sync(Peer source, Peer destination, OpenShiftBinaryOption... options); - - /** - * Stop rsync'ing, forcibly if necessary. - */ - void stop(); - - public class PodPeer extends Peer { - - private static final char NAMESPACE_POD_SEPARATOR = '/'; - private static final char POD_PATH_SEPARATOR = ':'; - - private IPod pod; - - public PodPeer(String location, IPod pod) { - super(location); - this.pod = pod; - } - - @Override - public String getParameter() { - return new StringBuilder() - .append(pod.getName()) - .append(POD_PATH_SEPARATOR) - .append(super.getParameter()) - .append(" -n ") - .append(pod.getNamespace()) - .toString(); - } - - @Override - public String getLocation() { - return new StringBuilder() - .append(pod.getNamespace()) - .append(NAMESPACE_POD_SEPARATOR) - .append(pod.getName()) - .append(POD_PATH_SEPARATOR) - .append(super.getParameter()) - .toString(); - } - - @Override - public boolean isPod() { - return true; - } - } - - public class LocalPeer extends Peer { - - public LocalPeer(String location) { - super(location); - } - - public boolean isPod() { - return false; - } - } - - public abstract class Peer { - - private String location; - - private Peer(String location) { - this.location = location; - } - - public String getParameter() { - return location; - } - - public String getLocation() { - return getParameter(); - } - - public abstract boolean isPod(); - } - - /** - * Indicates if the {@link Process} completed or not - * - * @return true if the {@link Process} completed, - * false otherwise. - */ - boolean isDone(); - - /** - * @return the {@link Process} exit value when it completed, {@code -1} if - * it's still running - */ - int exitValue(); - - /** - * Blocks until the process is done. - * - * @throws InterruptedException - * if the current thread is interrupted while waiting - */ - void await() throws InterruptedException; - - + /** + * option to skip verifying the certificates during TLS connection + * establishment. + */ + static final OpenShiftBinaryOption EXCLUDE_GIT_FOLDER = new GitFolderExclude(); + + /** option to exclude files/folders that match the given expressions **/ + static OpenShiftBinaryOption exclude(String... expressions) { + return new Exclude(expressions); + } + + /** option to not transfer file permissions. */ + static final OpenShiftBinaryOption NO_PERMS = new NoPerms(); + + /** option to delete delete extraneous files from destination directories **/ + static final OpenShiftBinaryOption DELETE = new Delete(); + + /** + * Excludes some files/directories that match the given patterns when rsync'ing + * the remote pod and the local deployment directory. + * + * @see {@link https://github.com/openshift/origin/issues/8223} + */ + static class Exclude implements OpenShiftBinaryOption { + + private String[] expressions; + + public Exclude(String... expressions) { + this.expressions = expressions; + } + + @Override + public void append(StringBuilder arguments) { + if (ArrayUtils.isEmpty(expressions)) { + return; + } + for (String expression : expressions) { + arguments.append(" --exclude=").append(expression); + } + } + } + + /** + * Does not sync .git folders when rsync'ing + */ + static class GitFolderExclude extends Exclude { + + public GitFolderExclude() { + super(".git"); + } + } + + /** + * Avoids transferring file permissions when rsync'ing + */ + static class NoPerms implements OpenShiftBinaryOption { + + @Override + public void append(StringBuilder arguments) { + arguments.append(" --no-perms=true"); + } + } + + /** + * Deletes extraneous files from destination directories when rsync'ing. + */ + static class Delete implements OpenShiftBinaryOption { + + @Override + public void append(StringBuilder arguments) { + arguments.append(" --delete"); + } + } + + static class PodPeer extends Peer { + + private static final char POD_PATH_SEPARATOR = ':'; + + private IPod pod; + + public PodPeer(String location, IPod pod) { + super(location); + this.pod = pod; + } + + @Override + public boolean isPod() { + return true; + } + + public IPod getPod() { + return pod; + } + + @Override + protected String getParameter() { + return new StringBuilder().append('"').append(pod.getName()).append(POD_PATH_SEPARATOR) + .append(getLocation()).append('"').toString(); + } + } + + static class LocalPeer extends Peer { + + public LocalPeer(String location) { + super(location); + } + + @Override + public boolean isPod() { + return false; + } + + @Override + public IPod getPod() { + return null; + } + + protected String getParameter() { + return new StringBuilder().append('"').append(getLocation()).append('"').toString(); + } + } + + abstract static class Peer implements OpenShiftBinaryOption { + + private String location; + + private Peer(String path) { + this.location = path; + } + + protected String getLocation() { + return location; + } + + protected abstract String getParameter(); + + public abstract boolean isPod(); + + public abstract IPod getPod(); + + @Override + public void append(StringBuilder commandLine) { + commandLine.append(" ").append(getParameter()); + } + + @Override + public String toString() { + return getParameter(); + } + } + + /** + * Synchronizes the give {@code destination} with the given {@code source} + * + * @param source + * the source of the rsync + * @param destination + * the destination of the rsync + * @param options + * the options to pass to the underlying {@code oc rsync} command + * @return the underlying {@link Process} streams to be displayed in a console. + */ + InputStream sync(Peer source, Peer destination, OpenShiftBinaryOption... options); + + /** + * Stops rsync'ing, forcibly if necessary. + */ + void stop(); + + /** + * Indicates if the {@link Process} completed or not + * + * @return true if the {@link Process} completed, + * false otherwise. + */ + boolean isDone(); + + /** + * @return the {@link Process} exit value when it completed, {@code -1} if it's + * still running + */ + int exitValue(); + + /** + * Blocks until the process is done. + * + * @throws InterruptedException + * if the current thread is interrupted while waiting + */ + void await() throws InterruptedException; } diff --git a/src/main/java/com/openshift/restclient/capability/resources/ITags.java b/src/main/java/com/openshift/restclient/capability/resources/ITags.java index 83653e80..514e2d29 100644 --- a/src/main/java/com/openshift/restclient/capability/resources/ITags.java +++ b/src/main/java/com/openshift/restclient/capability/resources/ITags.java @@ -6,6 +6,7 @@ * * Contributors: Red Hat, Inc. ******************************************************************************/ + package com.openshift.restclient.capability.resources; import java.util.Collection; @@ -13,15 +14,13 @@ import com.openshift.restclient.capability.ICapability; /** - * Determine if resource is tagged with categories - * of technologies it includes + * Determine if resource is tagged with categories of technologies it includes * - * @author Jeff Cantrill */ public interface ITags extends ICapability { - - /** - * The list of tags - */ - Collection getTags(); + + /** + * The list of tags + */ + Collection getTags(); } diff --git a/src/main/java/com/openshift/restclient/capability/resources/ITemplateTraceability.java b/src/main/java/com/openshift/restclient/capability/resources/ITemplateTraceability.java index 23b225cc..0ad5c37a 100644 --- a/src/main/java/com/openshift/restclient/capability/resources/ITemplateTraceability.java +++ b/src/main/java/com/openshift/restclient/capability/resources/ITemplateTraceability.java @@ -6,6 +6,7 @@ * * Contributors: Red Hat, Inc. ******************************************************************************/ + package com.openshift.restclient.capability.resources; import com.openshift.restclient.capability.ICapability; @@ -13,15 +14,13 @@ /** * Trace the source template that defined the resource * - * @author Jeff Cantrill */ public interface ITemplateTraceability extends ICapability { - /** - * Get the name of the template if any associated - * with this resource - * @return - */ - String getTemplateName(); + /** + * Get the name of the template if any associated with this resource + * + */ + String getTemplateName(); } \ No newline at end of file diff --git a/src/main/java/com/openshift/restclient/capability/resources/IUpdatable.java b/src/main/java/com/openshift/restclient/capability/resources/IUpdatable.java index 0a8104da..182b80e6 100644 --- a/src/main/java/com/openshift/restclient/capability/resources/IUpdatable.java +++ b/src/main/java/com/openshift/restclient/capability/resources/IUpdatable.java @@ -8,6 +8,7 @@ * Contributors: * Red Hat, Inc. - initial API and implementation ******************************************************************************/ + package com.openshift.restclient.capability.resources; import com.openshift.restclient.capability.ICapability; @@ -15,10 +16,9 @@ /** * Allow a resource to be updated from another - * @author jeff.cantrill - * + * */ public interface IUpdatable extends ICapability { - void updateFrom(IResource source); + void updateFrom(IResource source); } diff --git a/src/main/java/com/openshift/restclient/capability/resources/LocationNotFoundException.java b/src/main/java/com/openshift/restclient/capability/resources/LocationNotFoundException.java index d7df3cb9..71c952b2 100644 --- a/src/main/java/com/openshift/restclient/capability/resources/LocationNotFoundException.java +++ b/src/main/java/com/openshift/restclient/capability/resources/LocationNotFoundException.java @@ -8,20 +8,16 @@ * Contributors: * Red Hat, Inc. - initial API and implementation ******************************************************************************/ + package com.openshift.restclient.capability.resources; import com.openshift.restclient.OpenShiftException; -/** - * @author Jeff Cantrill - * - */ @SuppressWarnings("serial") public class LocationNotFoundException extends OpenShiftException { - public LocationNotFoundException(String message) { - super(message, (Object [])null); - } + public LocationNotFoundException(String message) { + super(message, (Object[]) null); + } - } diff --git a/src/main/java/com/openshift/restclient/capability/server/IConsole.java b/src/main/java/com/openshift/restclient/capability/server/IConsole.java new file mode 100644 index 00000000..ba59989b --- /dev/null +++ b/src/main/java/com/openshift/restclient/capability/server/IConsole.java @@ -0,0 +1,33 @@ +/******************************************************************************* + * Copyright (c) 2019 Red Hat, Inc. Distributed under license by Red Hat, Inc. + * All rights reserved. This program is made available under the terms of the + * Eclipse Public License v1.0 which accompanies this distribution, and is + * available at http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: Red Hat, Inc. + ******************************************************************************/ + +package com.openshift.restclient.capability.server; + +import com.openshift.restclient.capability.ICapability; +import com.openshift.restclient.model.IResource; + +/** + * Identifies an OpenShift server as capable of hosting a (web) console + */ +public interface IConsole extends ICapability { + + /** + * Returns the console url + * + * @return the console url (e.g. https://console-openshift-console.apps.com) + */ + String getConsoleUrl(); + + /** + * Returns the url in the console for the given resource + * + * @return the console url (e.g. https://console-openshift-console.apps.com) + */ + String getConsoleUrl(R resource); +} diff --git a/src/main/java/com/openshift/restclient/capability/server/IImageRegistryHosting.java b/src/main/java/com/openshift/restclient/capability/server/IImageRegistryHosting.java index 7db95315..43906942 100644 --- a/src/main/java/com/openshift/restclient/capability/server/IImageRegistryHosting.java +++ b/src/main/java/com/openshift/restclient/capability/server/IImageRegistryHosting.java @@ -6,21 +6,21 @@ * * Contributors: Red Hat, Inc. ******************************************************************************/ + package com.openshift.restclient.capability.server; import com.openshift.restclient.capability.ICapability; /** - * Identifies an OpenShift server as capable of - * hosting images via its own registry - * - * @author Jeff Cantrill + * Identifies an OpenShift server as capable of hosting images via its own + * registry */ -public interface IImageRegistryHosting extends ICapability{ - - /** - * Gets the Image Registry URI - * @return the registry URI (e.g. 172.121.17.212:5001) - */ - String getRegistryUri(); +public interface IImageRegistryHosting extends ICapability { + + /** + * Gets the Image Registry URI + * + * @return the registry URI (e.g. 172.121.17.212:5001) + */ + String getRegistryUri(); } diff --git a/src/main/java/com/openshift/restclient/capability/server/ITemplateProcessing.java b/src/main/java/com/openshift/restclient/capability/server/ITemplateProcessing.java index 13c461dd..3be422b9 100644 --- a/src/main/java/com/openshift/restclient/capability/server/ITemplateProcessing.java +++ b/src/main/java/com/openshift/restclient/capability/server/ITemplateProcessing.java @@ -6,26 +6,26 @@ * * Contributors: Red Hat, Inc. ******************************************************************************/ + package com.openshift.restclient.capability.server; import com.openshift.restclient.capability.ICapability; -import com.openshift.restclient.model.IResource; import com.openshift.restclient.model.template.ITemplate; /** * Add capability to process a template * - * @author Jeff Cantrill */ public interface ITemplateProcessing extends ICapability { - - /** - * Processes the template to substitute the parameters - * where necessary - * - * @param template The template to process - * @param namespace The namespace to use when processing the template - * @return ITemplate - */ - T process(ITemplate template, String namespace); + + /** + * Processes the template to substitute the parameters where necessary + * + * @param template + * The template to process + * @param namespace + * The namespace to use when processing the template + * @return ITemplate + */ + ITemplate process(ITemplate template, String namespace); } diff --git a/src/main/java/com/openshift/restclient/http/IHttpClient.java b/src/main/java/com/openshift/restclient/http/IHttpClient.java deleted file mode 100755 index b2a35f19..00000000 --- a/src/main/java/com/openshift/restclient/http/IHttpClient.java +++ /dev/null @@ -1,62 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2011-2014 Red Hat, Inc. - * Distributed under license by Red Hat, Inc. All rights reserved. - * This program is made available under the terms of the - * Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * Red Hat, Inc. - initial API and implementation - ******************************************************************************/ -package com.openshift.restclient.http; - -import java.net.SocketTimeoutException; -import java.net.URL; - -import com.openshift.internal.restclient.http.EncodingException; -import com.openshift.internal.restclient.http.HttpClientException; -import com.openshift.restclient.ISSLCertificateCallback; -import com.openshift.restclient.authorization.IAuthorizationStrategy; -import com.openshift.restclient.model.IResource; - -/** - * @author André Dietisheim - * @author Nicolas Spano - * @author Corey Daley - * @author Sean Kavanagh - * @deprecated This interface and its supporting classes to be deprecated in the near future. - */ -@Deprecated -public interface IHttpClient { - - public static final String SYSPROP_OPENSHIFT_CONNECT_TIMEOUT = "com.openshift.httpclient.connect.timeout"; - public static final String SYSPROP_OPENSHIFT_READ_TIMEOUT = "com.openshift.httpclient.read.timeout"; - public static final String SYSPROP_DEFAULT_CONNECT_TIMEOUT = "sun.net.client.defaultConnectTimeout"; - public static final String SYSPROP_DEFAULT_READ_TIMEOUT = "sun.net.client.defaultReadTimeout"; - - public static final int DEFAULT_READ_TIMEOUT = 2 * 60 * 1000; - public static final int NO_TIMEOUT = -1; - - public String get(URL url, int timeout) throws HttpClientException, SocketTimeoutException; - - public String head(URL url, int timeout) throws HttpClientException, SocketTimeoutException; - - public String post(URL url, int timeout, IResource resource) throws HttpClientException, SocketTimeoutException, EncodingException; - - public String put(URL url, int timeout, IResource resource) throws HttpClientException, SocketTimeoutException, EncodingException; - - public String delete(URL url, int timeout) throws HttpClientException, SocketTimeoutException, EncodingException; - - public void setUserAgent(String userAgent); - - public void setAcceptVersion(String version); - - public void setAcceptedMediaType(String acceptedMediaType); - - public void setAuthorizationStrategy(IAuthorizationStrategy strategy); - - public void setSSLCertificateCallback(ISSLCertificateCallback callback); - - public ISSLCertificateCallback getSSLCertificateCallback(); - -} diff --git a/src/main/java/com/openshift/restclient/http/IHttpConstants.java b/src/main/java/com/openshift/restclient/http/IHttpConstants.java index 8874bef1..4a9cfee1 100644 --- a/src/main/java/com/openshift/restclient/http/IHttpConstants.java +++ b/src/main/java/com/openshift/restclient/http/IHttpConstants.java @@ -1,11 +1,12 @@ /******************************************************************************* - * Copyright (c) 2015 Red Hat, Inc. Distributed under license by Red Hat, Inc. + * Copyright (c) 2015-2018 Red Hat, Inc. Distributed under license by Red Hat, Inc. * All rights reserved. This program is made available under the terms of the * Eclipse Public License v1.0 which accompanies this distribution, and is * available at http://www.eclipse.org/legal/epl-v10.html * * Contributors: Red Hat, Inc. - initial API and implementation ******************************************************************************/ + package com.openshift.restclient.http; /** @@ -15,43 +16,57 @@ * @author Andre Dietisheim * */ + public interface IHttpConstants { - public static final int STATUS_OK = 200; - public static final int STATUS_INTERNAL_SERVER_ERROR = 500; - public static final int STATUS_BAD_REQUEST = 400; - public static final int STATUS_UNAUTHORIZED = 401; - public static final int STATUS_FORBIDDEN = 403; - public static final int STATUS_NOT_FOUND = 404; - - public static final String PROPERTY_CONTENT_TYPE = "Content-Type"; - public static final String PROPERTY_AUTHORIZATION = "Authorization"; - public static final String PROPERTY_ACCEPT = "Accept"; - public static final String PROPERTY_USER_AGENT = "User-Agent"; - public static final String PROPERTY_WWW_AUTHENTICATE = "Www-Authenticate"; - - public static final String PROPERTY_AUTHKEY = "broker_auth_key"; - public static final String PROPERTY_AUTHIV = "broker_auth_iv"; - - public static final String MEDIATYPE_APPLICATION_JSON = "application/json"; - public static final String MEDIATYPE_APPLICATION_XML = "application/xml"; - public static final String MEDIATYPE_APPLICATION_FORMURLENCODED = "application/x-www-form-urlencoded"; - - public static final String AUTHORIZATION_BASIC = "Basic"; - public static final String AUTHORIZATION_BEARER = "Bearer"; - - public static final String VERSION = "version"; - - public static final char SPACE = ' '; - public static final char COLON = ':'; - public static final char COMMA = ','; - public static final char SEMICOLON = ';'; - public static final char AMPERSAND = '&'; - public static final char EQUALS = '='; - public static final char SLASH = '/'; - public static final char QUESTION_MARK = '?'; - + public static final int STATUS_UPGRADE_PROTOCOL = 101; + public static final int STATUS_OK = 200; + public static final int STATUS_MOVED_PERMANENTLY = 301; + public static final int STATUS_MOVED_TEMPORARILY = 302; + public static final int STATUS_INTERNAL_SERVER_ERROR = 500; + public static final int STATUS_BAD_REQUEST = 400; + public static final int STATUS_UNAUTHORIZED = 401; + public static final int STATUS_FORBIDDEN = 403; + public static final int STATUS_NOT_FOUND = 404; + + public static final int STATUS_NORMAL_STOP = 1000; + + public static final String PROPERTY_CONTENT_TYPE = "Content-Type"; + public static final String PROPERTY_AUTHORIZATION = "Authorization"; + public static final String PROPERTY_ACCEPT = "Accept"; + public static final String PROPERTY_ORIGIN = "Origin"; + public static final String PROPERTY_LOCATION = "Location"; + public static final String PROPERTY_USER_AGENT = "User-Agent"; + public static final String PROPERTY_WWW_AUTHENTICATE = "WWW-Authenticate"; + + public static final String PROPERTY_AUTHKEY = "broker_auth_key"; + public static final String PROPERTY_AUTHIV = "broker_auth_iv"; + static final String PROPERTY_ACCESS_TOKEN = "access_token"; + + public static final String MEDIATYPE_ANY = "*/*"; + public static final String MEDIATYPE_APPLICATION_JSON = "application/json;charset=utf-8"; + public static final String MEDIATYPE_APPLICATION_XML = "application/xml"; + public static final String MEDIATYPE_APPLICATION_FORMURLENCODED = "application/x-www-form-urlencoded"; + public static final String MEDIATYPE_APPLICATION_OCTET_STREAM = "application/octet-stream"; + + public static final String AUTHORIZATION_BASIC = "Basic"; + public static final String AUTHORIZATION_BEARER = "Bearer"; + + public static final String VERSION = "version"; + + public static final char SPACE = ' '; + public static final char COLON = ':'; + public static final char COMMA = ','; + public static final char SEMICOLON = ';'; + public static final char AMPERSAND = '&'; + public static final char EQUALS = '='; + public static final char SLASH = '/'; + public static final char QUESTION_MARK = '?'; + public static final int DEFAULT_READ_TIMEOUT = 2 * 60 * 1000; - public static final int NO_TIMEOUT = -1; + public static final int NO_TIMEOUT = -1; + + static final String PUT = "PUT"; + static final String POST = "POST"; } diff --git a/src/main/java/com/openshift/restclient/images/DockerImageDescriptor.java b/src/main/java/com/openshift/restclient/images/DockerImageDescriptor.java index 5328f55c..4cf3d328 100644 --- a/src/main/java/com/openshift/restclient/images/DockerImageDescriptor.java +++ b/src/main/java/com/openshift/restclient/images/DockerImageDescriptor.java @@ -6,27 +6,25 @@ * * Contributors: Red Hat, Inc. ******************************************************************************/ + package com.openshift.restclient.images; -/** - * @author Jeff Cantrill - */ -public class DockerImageDescriptor{ - - private final String description; - private final DockerImageURI name; +public class DockerImageDescriptor { + + private final String description; + private final DockerImageURI name; + + public DockerImageDescriptor(DockerImageURI name, String description) { + this.name = name; + this.description = description; + } + + public String getDescription() { + return description; + } - public DockerImageDescriptor(DockerImageURI name, String description){ - this.name = name; - this.description = description; - } + public DockerImageURI getImageUri() { + return name; + } - public String getDescription() { - return description; - } - - public DockerImageURI getImageUri() { - return name; - } - } \ No newline at end of file diff --git a/src/main/java/com/openshift/restclient/images/DockerImageURI.java b/src/main/java/com/openshift/restclient/images/DockerImageURI.java index 0c46b3d0..fd0c7a00 100644 --- a/src/main/java/com/openshift/restclient/images/DockerImageURI.java +++ b/src/main/java/com/openshift/restclient/images/DockerImageURI.java @@ -6,186 +6,199 @@ * * Contributors: Red Hat, Inc. ******************************************************************************/ + package com.openshift.restclient.images; /** - * ImageUri is an immutable representation of a full image tag in accordance with - * with Docker conventions [REGISTRYHOST/][USERNAME/]NAME[:TAG] - * - * @author Jeff Cantrill + * ImageUri is an immutable representation of a full image tag in accordance + * with with Docker conventions [REGISTRYHOST/][USERNAME/]NAME[:TAG] */ public class DockerImageURI { - - public static final String LATEST = "latest"; - private String registryHost; - private String userName; - private String name; - private String tag; - - public DockerImageURI(String registryHost, String userName, String name){ - this(registryHost, userName, name, LATEST); - } - public DockerImageURI(String registryHost, String userName, String name, String imageTag){ - this.registryHost = registryHost; - this.userName = userName; - this.name = name; - this.tag = imageTag; - } - - public DockerImageURI(String tag){ - if(tag != null) { - String[] segments = tag.split("/"); - switch (segments.length) { - case 3: - registryHost = segments[0]; - userName = segments[1]; - setNameAndTag(segments[2]); - break; - case 2: - userName = segments[0]; - setNameAndTag(segments[1]); - break; - default: - setNameAndTag(segments[0]); - break; - } - } - } - - private void setNameAndTag(String nameAndTag){ - String [] nameTag = nameAndTag.split(":"); - if(nameTag.length == 2){ - name = nameTag[0]; - tag = nameTag[1]; - } - else{ - name =nameTag[0]; - tag = LATEST; - } - } - - @Override - public String toString() { - return getAbsoluteUri(); - } - - public String getName() { - return this.name; - } - - public String getTag() { - return this.tag; - } - - public String getUserName() { - return this.userName; - } - - public String getRepositoryHost() { - return this.registryHost; - } - - /** - * Get the docker tag as repo:9999/username/name:tag - * @return - */ - public String getAbsoluteUri() { - return buildUri(registryHost, userName, name, tag); - } - - /** - * Get the docker tag as username/name:tag only - * @return - */ - public String getBaseUri() { - return buildUri(null, userName, name, tag); - } - - /** - * Get the docker tag as username/name only - * @return - */ - public String getUriUserNameAndName() { - return buildUri(null, userName, name, null); - } - - /** - * Get the docker tag as repo:9999/username/name only - * @return - */ - public String getUriWithoutTag() { - return buildUri(registryHost, userName, name, null); - } - - /** - * Get the docker tag as username/name:tag only - * @return - */ - public String getUriWithoutHost() { - return buildUri(null, userName, name, tag); - } - - /** - * Get the docker tag as name:tag only - * @return - */ - public String getNameAndTag() { - return buildUri(null, null, name, tag); - } - - private String buildUri(String host, String user, String name, String tag){ - StringBuilder b = new StringBuilder(); - if(host != null) b.append(host).append("/"); - if(user != null) b.append(user).append("/"); - b.append(name); - if(tag != null)b.append(":").append(tag); - return b.toString(); - } - - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = prime * result + ((name == null) ? 0 : name.hashCode()); - result = prime * result - + ((registryHost == null) ? 0 : registryHost.hashCode()); - result = prime * result + ((tag == null) ? 0 : tag.hashCode()); - result = prime * result - + ((userName == null) ? 0 : userName.hashCode()); - return result; - } - - @Override - public boolean equals(Object obj) { - if (this == obj) - return true; - if (obj == null) - return false; - if (getClass() != obj.getClass()) - return false; - DockerImageURI other = (DockerImageURI) obj; - if (name == null) { - if (other.name != null) - return false; - } else if (!name.equals(other.name)) - return false; - if (registryHost == null) { - if (other.registryHost != null) - return false; - } else if (!registryHost.equals(other.registryHost)) - return false; - if (tag == null) { - if (other.tag != null) - return false; - } else if (!tag.equals(other.tag)) - return false; - if (userName == null) { - if (other.userName != null) - return false; - } else if (!userName.equals(other.userName)) - return false; - return true; - } - - + + public static final String LATEST = "latest"; + private String registryHost; + private String userName; + private String name; + private String tag; + + public DockerImageURI(String registryHost, String userName, String name) { + this(registryHost, userName, name, LATEST); + } + + public DockerImageURI(String registryHost, String userName, String name, String imageTag) { + this.registryHost = registryHost; + this.userName = userName; + this.name = name; + this.tag = imageTag; + } + + public DockerImageURI(String tag) { + if (tag != null) { + String[] segments = tag.split("/"); + switch (segments.length) { + case 3: + registryHost = segments[0]; + userName = segments[1]; + setNameAndTag(segments[2]); + break; + case 2: + userName = segments[0]; + setNameAndTag(segments[1]); + break; + default: + setNameAndTag(segments[0]); + break; + } + } + } + + private void setNameAndTag(String nameAndTag) { + String[] nameTag = nameAndTag.split(":"); + if (nameTag.length == 2) { + name = nameTag[0]; + tag = nameTag[1]; + } else { + name = nameTag[0]; + tag = LATEST; + } + } + + @Override + public String toString() { + return getAbsoluteUri(); + } + + public String getName() { + return this.name; + } + + public String getTag() { + return this.tag; + } + + public String getUserName() { + return this.userName; + } + + public String getRepositoryHost() { + return this.registryHost; + } + + /** + * Get the docker tag as repo:9999/username/name:tag + * + */ + public String getAbsoluteUri() { + return buildUri(registryHost, userName, name, tag); + } + + /** + * Get the docker tag as username/name:tag only + * + */ + public String getBaseUri() { + return buildUri(null, userName, name, tag); + } + + /** + * Get the docker tag as username/name only + * + */ + public String getUriUserNameAndName() { + return buildUri(null, userName, name, null); + } + + /** + * Get the docker tag as repo:9999/username/name only + * + */ + public String getUriWithoutTag() { + return buildUri(registryHost, userName, name, null); + } + + /** + * Get the docker tag as username/name:tag only + * + */ + public String getUriWithoutHost() { + return buildUri(null, userName, name, tag); + } + + /** + * Get the docker tag as name:tag only + * + */ + public String getNameAndTag() { + return buildUri(null, null, name, tag); + } + + private String buildUri(String host, String user, String name, String tag) { + StringBuilder b = new StringBuilder(); + if (host != null) { + b.append(host).append("/"); + } + if (user != null) { + b.append(user).append("/"); + } + b.append(name); + if (tag != null) { + b.append(":").append(tag); + } + return b.toString(); + } + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + ((name == null) ? 0 : name.hashCode()); + result = prime * result + ((registryHost == null) ? 0 : registryHost.hashCode()); + result = prime * result + ((tag == null) ? 0 : tag.hashCode()); + result = prime * result + ((userName == null) ? 0 : userName.hashCode()); + return result; + } + + @Override + public boolean equals(Object obj) { + if (this == obj) { + return true; + } + if (obj == null) { + return false; + } + if (getClass() != obj.getClass()) { + return false; + } + DockerImageURI other = (DockerImageURI) obj; + if (name == null) { + if (other.name != null) { + return false; + } + } else if (!name.equals(other.name)) { + return false; + } + if (registryHost == null) { + if (other.registryHost != null) { + return false; + } + } else if (!registryHost.equals(other.registryHost)) { + return false; + } + if (tag == null) { + if (other.tag != null) { + return false; + } + } else if (!tag.equals(other.tag)) { + return false; + } + if (userName == null) { + if (other.userName != null) { + return false; + } + } else if (!userName.equals(other.userName)) { + return false; + } + return true; + } + } diff --git a/src/main/java/com/openshift/restclient/model/Annotatable.java b/src/main/java/com/openshift/restclient/model/Annotatable.java index ad6937c4..f0a9a41f 100644 --- a/src/main/java/com/openshift/restclient/model/Annotatable.java +++ b/src/main/java/com/openshift/restclient/model/Annotatable.java @@ -8,38 +8,18 @@ * Contributors: * Red Hat, Inc. - initial API and implementation ******************************************************************************/ -package com.openshift.restclient.model; -import java.util.Map; +package com.openshift.restclient.model; -public interface Annotatable { - - /** - * Returns true if the resource is annotated with - * the given key - * @param key - * @return true if the annotation key exists - */ - boolean isAnnotatedWith(String key); - - /** - * Retrieves the annotated value for the given key - * @param key - * @return - */ - String getAnnotation(String key); - - /** - * Set the resource annotation - * @param key - * @param value - */ - void setAnnotation(String key, String value); - - /** - * Retrieves the annotations associated with the resource - * @return - */ - Map getAnnotations(); +import com.openshift.restclient.api.models.IAnnotatable; +/** + * + * @author jeff.cantrill + * + * @deprecated + * {@link IAnnotatable} +*/ +@Deprecated +public interface Annotatable extends IAnnotatable{ } diff --git a/src/main/java/com/openshift/restclient/model/IBuild.java b/src/main/java/com/openshift/restclient/model/IBuild.java index b5029e16..0c1dd4ba 100644 --- a/src/main/java/com/openshift/restclient/model/IBuild.java +++ b/src/main/java/com/openshift/restclient/model/IBuild.java @@ -6,6 +6,7 @@ * * Contributors: Red Hat, Inc. ******************************************************************************/ + package com.openshift.restclient.model; import com.openshift.restclient.images.DockerImageURI; @@ -13,46 +14,43 @@ import com.openshift.restclient.model.build.IBuildStatus; import com.openshift.restclient.model.build.IBuildStrategy; -/** - * @author Jeff Cantrill - */ public interface IBuild extends IResource { - /** - * Returns the status of the buld - * @return - */ - String getStatus(); - - /** - * Returns the details about the status of this build - * @return - */ - String getMessage(); - - /** - * Returns the name of the pod running the build - * @return - */ - @Deprecated - String getPodName(); - - /** - * Cancels a build if its status is not "Complete", - * "Failed", or "Cancelled" - * @return if the build state was in fact changed - */ - boolean cancel(); - - DockerImageURI getOutputTo(); - - String getOutputKind(); - - T getBuildSource(); - - T getBuildStrategy(); - - String getPushSecret(); - - IBuildStatus getBuildStatus(); + /** + * Returns the status of the buld + * + */ + String getStatus(); + + /** + * Returns the details about the status of this build + * + */ + String getMessage(); + + /** + * Returns the name of the pod running the build + * + */ + @Deprecated + String getPodName(); + + /** + * Cancels a build if its status is not "Complete", "Failed", or "Cancelled" + * + * @return if the build state was in fact changed + */ + boolean cancel(); + + DockerImageURI getOutputTo(); + + String getOutputKind(); + + T getBuildSource(); + + T getBuildStrategy(); + + String getPushSecret(); + + IBuildStatus getBuildStatus(); } diff --git a/src/main/java/com/openshift/restclient/model/IBuildConfig.java b/src/main/java/com/openshift/restclient/model/IBuildConfig.java index 72bf4b5a..8cf6feca 100644 --- a/src/main/java/com/openshift/restclient/model/IBuildConfig.java +++ b/src/main/java/com/openshift/restclient/model/IBuildConfig.java @@ -6,6 +6,7 @@ * * Contributors: Red Hat, Inc. ******************************************************************************/ + package com.openshift.restclient.model; import java.util.List; @@ -14,69 +15,66 @@ import com.openshift.restclient.model.build.IBuildStrategy; import com.openshift.restclient.model.build.IBuildTrigger; -/** - * @author Jeff Cantrill - */ -public interface IBuildConfig extends IResource{ - - /** - * To defines an optional location to push the output of this build to. - * Kind must be one of 'ImageStreamTag' or 'DockerImage'. - * @return - */ - IObjectReference getBuildOutputReference(); - - /** - * Returns the source URL for a build - * @return - */ - String getSourceURI(); - - /** - * Returns the policies which will trigger a build - * @return - */ - List getBuildTriggers(); - - /** - * Add a trigger to the list of triggers for this build. - * - * @param trigger - */ - void addBuildTrigger(IBuildTrigger trigger); +public interface IBuildConfig extends IResource { + + /** + * To defines an optional location to push the output of this build to. Kind + * must be one of 'ImageStreamTag' or 'DockerImage'. + * + * @return a mutable object reference + */ + IObjectReference getBuildOutputReference(); + + /** + * Returns the source URL for a build + * + */ + String getSourceURI(); + + /** + * Returns the policies which will trigger a build + * + */ + List getBuildTriggers(); + + /** + * Add a trigger to the list of triggers for this build. + * + */ + void addBuildTrigger(IBuildTrigger trigger); + + /** + * Returns the source info of the build + * + * @return + */ + T getBuildSource(); - /** - * Returns the source info of the build - * @return - */ - T getBuildSource(); + /** + * Set the source for the build. + * + */ + void setBuildSource(IBuildSource source); - /** - * Set the source for the build. - * - * @param source - */ - void setBuildSource(IBuildSource source); + /** + * Returns the strategy to for building the source + * + * @return + */ + T getBuildStrategy(); - /** - * Returns the strategy to for building the source - * @return - */ - T getBuildStrategy(); + /** + * Set the strategy for how the build should be built.
+ * Depending on the strategies available on the server this could be 'source', + * 'docker' or 'custom'. + * + */ + void setBuildStrategy(IBuildStrategy strategy); - /** - * Set the strategy for how the build should be built.
- * Depending on the strategies available on the server this - * could be 'source', 'docker' or 'custom'. - * - * @param strategy - */ - void setBuildStrategy(IBuildStrategy strategy); - - /** - * Retrieves the name of the repository where the - * resulting build image will be pushed - * @return - */ - String getOutputRepositoryName(); + /** + * Retrieves the name of the repository where the resulting build image will be + * pushed + * + */ + String getOutputRepositoryName(); } diff --git a/src/main/java/com/openshift/restclient/model/IConfig.java b/src/main/java/com/openshift/restclient/model/IConfig.java index 3e1ca01d..42a8589e 100644 --- a/src/main/java/com/openshift/restclient/model/IConfig.java +++ b/src/main/java/com/openshift/restclient/model/IConfig.java @@ -6,12 +6,12 @@ * * Contributors: Red Hat, Inc. ******************************************************************************/ + package com.openshift.restclient.model; /** * A Config which is a list of resources. * - * @author Jeff Cantrill * @deprecated ??? in later model versions in favor of List? */ @Deprecated diff --git a/src/main/java/com/openshift/restclient/model/IConfigMapKeySelector.java b/src/main/java/com/openshift/restclient/model/IConfigMapKeySelector.java index e1a86bc6..bd5d198a 100644 --- a/src/main/java/com/openshift/restclient/model/IConfigMapKeySelector.java +++ b/src/main/java/com/openshift/restclient/model/IConfigMapKeySelector.java @@ -8,14 +8,15 @@ * Contributors: * Red Hat, Inc. - initial API and implementation ******************************************************************************/ + package com.openshift.restclient.model; import com.openshift.restclient.model.IEnvironmentVariable.IEnvVarSource; public interface IConfigMapKeySelector extends IEnvVarSource { - - String getName(); - - String getKey(); + + String getName(); + + String getKey(); } diff --git a/src/main/java/com/openshift/restclient/model/IContainer.java b/src/main/java/com/openshift/restclient/model/IContainer.java index 18e0b99b..89023ee3 100644 --- a/src/main/java/com/openshift/restclient/model/IContainer.java +++ b/src/main/java/com/openshift/restclient/model/IContainer.java @@ -8,61 +8,104 @@ * Contributors: * Red Hat, Inc. - initial API and implementation ******************************************************************************/ + package com.openshift.restclient.model; +import java.util.List; import java.util.Map; import java.util.Set; +import com.openshift.restclient.api.models.INameSetable; import com.openshift.restclient.images.DockerImageURI; +import com.openshift.restclient.model.probe.IProbe; import com.openshift.restclient.model.volume.IVolume; import com.openshift.restclient.model.volume.IVolumeMount; -public interface IContainer { - - void setName(String name); - String getName(); - - void setImage(DockerImageURI tag); - DockerImageURI getImage(); - - /** - * replace the env vars - * @param vars - */ - void setEnvVars(Map vars); - /** - * - * @return an unmodifiable map of env vars - */ - Map getEnvVars(); - - void addEnvVar(String key, String value); - - /** - * replaces the set of ports - * @param ports - */ - void setPorts(Set ports); - - /** - * - * @return an unmodifiable set of the container ports - */ - Set getPorts(); - - void setImagePullPolicy(String policy); - String getImagePullPolicy(); - - void setLifecycle(String lifecycle); - String getLifecycle(); - - @Deprecated - void setVolumes(Set volumes); - @Deprecated - Set getVolumes(); - - void setVolumeMounts(Set volumes); - Set getVolumeMounts(); - - String toJSONString(); +public interface IContainer extends INameSetable, JSONSerializeable { + + String getName(); + + void setImage(DockerImageURI tag); + + DockerImageURI getImage(); + + /** + * replace the env vars + * + */ + void setEnvVars(Map vars); + + /** + * + * @return an unmodifiable map of env vars + */ + Map getEnvVars(); + + void addEnvVar(String key, String value); + + /** + * replaces the set of ports + * + */ + void setPorts(Set ports); + + /** + * + * @return an unmodifiable set of the container ports + */ + Set getPorts(); + + void setImagePullPolicy(String policy); + + String getImagePullPolicy(); + + void setLifecycle(ILifecycle lifecycle); + + ILifecycle getLifecycle(); + + void setCommand(List command); + + List getCommand(); + + void setCommandArgs(List args); + + List getCommandArgs(); + + @Deprecated + void setVolumes(Set volumes); + + @Deprecated + Set getVolumes(); + + void setVolumeMounts(Set volumes); + + Set getVolumeMounts(); + + /** + * Add a volumemount with the given name + * + * @return IVolumeMount + */ + IVolumeMount addVolumeMount(String name); + + String getRequestsCPU(); + + void setRequestsCPU(String requestsCPU); + + String getRequestsMemory(); + + void setRequestsMemory(String requestsMemory); + + String getLimitsCPU(); + + void setLimitsCPU(String limitsCPU); + + String getLimitsMemory(); + + void setLimitsMemory(String limitsMemory); + + IProbe getReadinessProbe(); + + IProbe getLivenessProbe(); + } diff --git a/src/main/java/com/openshift/restclient/model/IDeploymentConfig.java b/src/main/java/com/openshift/restclient/model/IDeploymentConfig.java index 740fc973..1265f3be 100644 --- a/src/main/java/com/openshift/restclient/model/IDeploymentConfig.java +++ b/src/main/java/com/openshift/restclient/model/IDeploymentConfig.java @@ -6,86 +6,83 @@ * * Contributors: Red Hat, Inc. ******************************************************************************/ + package com.openshift.restclient.model; import java.util.Collection; import com.openshift.restclient.model.deploy.IDeploymentTrigger; -/** - * @author Jeff Cantrill - */ public interface IDeploymentConfig extends IReplicationController { - - - /** - * Get the list of deployment triggers - * @return a collection of trigger types - */ - Collection getTriggerTypes(); - /** - * Returns the trigger of the given type - * or null if it doesn not exist - * @param type - * @return - */ - Collection getTriggers(); - - /** - * Convenience method to get the deployment - * strategy type - * @return the type as a string - */ - String getDeploymentStrategyType(); - - /** - * Add a trigger of the given type - * or null if the type is unrecognized - * - * @param type - * @return - */ - IDeploymentTrigger addTrigger(String type); - - /** - * Get the latest version number - * @return - */ - int getLatestVersionNumber(); - - /** - * Set the latest version number - * @param new version number - * - */ - void setLatestVersionNumber(int newVersionNumber); - - /** - * Return whether deployments have fired because of triggers - * @return - */ - boolean haveTriggersFired(); - - /** - * Return whether deployments have fired based on an image trigger - * for a particular image - * @param imageNameTag the image name:tag associated with an image trigger - * @return - */ - boolean didImageTrigger(String imageNameTag); - - /** - * Get the image hexadecimal ID for the image tag used with the - * latest image change trigger - * @param imageNameTag the image name:tag associated with an image trigger - * @return - */ - String getImageHexIDForImageNameAndTag(String imageNameTag); - - /** - * Get the image name:tag from a image change trigger firing - * @return - */ - String getImageNameAndTagForTriggeredDeployment(); + /** + * Get the list of deployment triggers + * + * @return a collection of trigger types + */ + Collection getTriggerTypes(); + + /** + * Returns the trigger of the given type or null if it doesn not exist + * + */ + Collection getTriggers(); + + /** + * Convenience method to get the deployment strategy type + * + * @return the type as a string + */ + String getDeploymentStrategyType(); + + /** + * Add a trigger of the given type or null if the type is unrecognized + * + */ + IDeploymentTrigger addTrigger(String type); + + /** + * Get the latest version number + * + */ + int getLatestVersionNumber(); + + /** + * Set the latest version number + * + * @param new + * version number + * + */ + void setLatestVersionNumber(int newVersionNumber); + + /** + * Return whether deployments have fired because of triggers + * + */ + boolean haveTriggersFired(); + + /** + * Return whether deployments have fired based on an image trigger for a + * particular image + * + * @param imageNameTag + * the image name:tag associated with an image trigger + */ + boolean didImageTrigger(String imageNameTag); + + /** + * Get the image hexadecimal ID for the image tag used with the latest image + * change trigger + * + * @param imageNameTag + * the image name:tag associated with an image trigger + */ + String getImageHexIDForImageNameAndTag(String imageNameTag); + + /** + * Get the image name:tag from a image change trigger firing + * + */ + String getImageNameAndTagForTriggeredDeployment(); } diff --git a/src/main/java/com/openshift/restclient/model/IEnvironmentVariable.java b/src/main/java/com/openshift/restclient/model/IEnvironmentVariable.java index db10232b..22fdc56d 100644 --- a/src/main/java/com/openshift/restclient/model/IEnvironmentVariable.java +++ b/src/main/java/com/openshift/restclient/model/IEnvironmentVariable.java @@ -8,51 +8,46 @@ * Contributors: * Red Hat, Inc. - initial API and implementation ******************************************************************************/ -package com.openshift.restclient.model; -import com.openshift.internal.restclient.model.JSONSerializeable; +package com.openshift.restclient.model; /** - * Environment variable representation to - * allow more complex values then - * name/value pairs. An environmentVariable - * will have either a value or valueFrom - * but not both. + * Environment variable representation to allow more complex values then + * name/value pairs. An environmentVariable will have either a value or + * valueFrom but not both. * - * @author jeff.cantrill * */ -public interface IEnvironmentVariable extends JSONSerializeable{ - - /** - * The name of the env var - * @return - */ - String getName(); - - /** - * The value of the environment variable or null if not - * defined. - * @return - */ - String getValue(); - - /** - * The ref value or null if not defined - * @return - */ - IEnvVarSource getValueFrom(); - - /** - * Marker interface for sources of environment variables - * @author jeff.cantrill - * - */ - static interface IEnvVarSource{ - - } - - @Override - String toJson(); - +public interface IEnvironmentVariable extends JSONSerializeable { + + /** + * The name of the env var + * + */ + String getName(); + + /** + * The value of the environment variable or null if not defined. + * + */ + String getValue(); + + /** + * The ref value or null if not defined + * + */ + IEnvVarSource getValueFrom(); + + /** + * Marker interface for sources of environment variables + * + * + */ + static interface IEnvVarSource { + + } + + @Override + String toJson(); + } diff --git a/src/main/java/com/openshift/restclient/model/IEvent.java b/src/main/java/com/openshift/restclient/model/IEvent.java index c7772b9d..c03b0340 100644 --- a/src/main/java/com/openshift/restclient/model/IEvent.java +++ b/src/main/java/com/openshift/restclient/model/IEvent.java @@ -8,13 +8,77 @@ * Contributors: * Red Hat, Inc. - initial API and implementation ******************************************************************************/ -package com.openshift.restclient.model; -import com.openshift.restclient.model.IResource; +package com.openshift.restclient.model; -/** - * @author Jeff Cantrill - */ public interface IEvent extends IResource { + /** + * The reason for the event + * + */ + String getReason(); + + /** + * The additional message associated with the event + * + */ + String getMessage(); + + /** + * A reference to the Object that was involved in this event + * + */ + IObjectReference getInvolvedObject(); + + /** + * The first time this event was recorded + * + */ + String getFirstSeenTimestamp(); + + /** + * The last time this event was recorded + * + */ + String getLastSeenTimestamp(); + + /** + * The number of times this event has occured + * + */ + int getCount(); + + /** + * The type of this event (e.g. Normal, Warning) + * + */ + String getType(); + + /** + * Optional information of the component reporting this event + * + */ + IEventSource getEventSource(); + + /** + * Event source information + * + * @author jeff.cantrill + * + */ + static interface IEventSource { + + /** + * The component from which this event was generated + * + */ + String getComponent(); + + /** + * The host name on which this event was generated + * + */ + String getHost(); + } } diff --git a/src/main/java/com/openshift/internal/restclient/model/JSONSerializeable.java b/src/main/java/com/openshift/restclient/model/IExecAction.java similarity index 66% rename from src/main/java/com/openshift/internal/restclient/model/JSONSerializeable.java rename to src/main/java/com/openshift/restclient/model/IExecAction.java index 31b74057..ec462f00 100644 --- a/src/main/java/com/openshift/internal/restclient/model/JSONSerializeable.java +++ b/src/main/java/com/openshift/restclient/model/IExecAction.java @@ -8,9 +8,18 @@ * Contributors: * Red Hat, Inc. - initial API and implementation ******************************************************************************/ -package com.openshift.internal.restclient.model; -public interface JSONSerializeable { - - String toJson(); +package com.openshift.restclient.model; + +/** + * @author Ulf Lilleengen + */ +public interface IExecAction extends IHandler { + java.util.List getCommand(); + + interface IBuilder { + IBuilder command(String command); + + IExecAction build(); + } } diff --git a/src/main/java/com/openshift/internal/restclient/http/EncodingException.java b/src/main/java/com/openshift/restclient/model/IHandler.java similarity index 55% rename from src/main/java/com/openshift/internal/restclient/http/EncodingException.java rename to src/main/java/com/openshift/restclient/model/IHandler.java index bfc4fb32..e3a546de 100644 --- a/src/main/java/com/openshift/internal/restclient/http/EncodingException.java +++ b/src/main/java/com/openshift/restclient/model/IHandler.java @@ -1,24 +1,23 @@ /******************************************************************************* - * Copyright (c) 2011 Red Hat, Inc. + * Copyright (c) 2016 Red Hat, Inc. * Distributed under license by Red Hat, Inc. All rights reserved. * This program is made available under the terms of the * Eclipse Public License v1.0 which accompanies this distribution, * and is available at http://www.eclipse.org/legal/epl-v10.html * * Contributors: - * Red Hat, Inc. - initial API and implementation + * Red Hat, Inc. - initial API and implementation ******************************************************************************/ -package com.openshift.internal.restclient.http; +package com.openshift.restclient.model; /** - * @author Ioannis Canellos + * @author Ulf Lilleengen */ -public class EncodingException extends HttpClientException { +public interface IHandler extends JSONSerializeable { + static final String EXEC = "exec"; + static final String HTTP = "httpGet"; + static final String TCP = "tcpSocket"; - private static final long serialVersionUID = 1L; - - public EncodingException(String message, Throwable t) { - super(message, t); - } + String getType(); } diff --git a/src/main/java/com/openshift/restclient/model/IImageStream.java b/src/main/java/com/openshift/restclient/model/IImageStream.java index b8f18cc1..36af3340 100644 --- a/src/main/java/com/openshift/restclient/model/IImageStream.java +++ b/src/main/java/com/openshift/restclient/model/IImageStream.java @@ -6,6 +6,7 @@ * * Contributors: Red Hat, Inc. ******************************************************************************/ + package com.openshift.restclient.model; import java.util.Collection; @@ -13,78 +14,67 @@ import com.openshift.restclient.images.DockerImageURI; import com.openshift.restclient.model.image.ITagReference; -/** - * @author Jeff Cantrill - */ -public interface IImageStream extends IResource{ +public interface IImageStream extends IResource { + + /** + * Get the image repository uri abstracted by this image stream + * + */ + DockerImageURI getDockerImageRepository(); + + /** + * Set the image repository uri abstracted by this image stream + * + */ + void setDockerImageRepository(DockerImageURI imageUri); + + /** + * Set the image repository uri abstracted by this image stream + * + */ + void setDockerImageRepository(String imageUri); + + /** + * Sets a new tag in an image stream + * + * @param newTag + * the new tag to create + * @param fromTag + * existing tag the new tag is based from + */ + void setTag(String newTag, String fromTag); + + /** + * Add a tag to the list with the given name, and reference to the given kind + * and name. + * + */ + ITagReference addTag(String name, String fromKind, String fromName); + + /** + * Add a tag to the list with the given name, namespace, and reference to the + * given kind, namespace, and name. + * + */ + ITagReference addTag(String name, String fromKind, String fromName, String fromNamespace); - /** - * Get the image repository uri abstracted by this - * image stream - * @return - */ - DockerImageURI getDockerImageRepository(); - - /** - * Set the image repository uri abstracted by this - * image stream - * @return - */ - void setDockerImageRepository(DockerImageURI imageUri); - - /** - * Set the image repository uri abstracted by this - * image stream - * @return - */ - void setDockerImageRepository(String imageUri); + /** + * Gets the long imagae id for the provided tag + * + * @param tagName + * name of the image stream tag to interrogate + */ + String getImageId(String tagName); - /** - * Sets a new tag in an image stream - * - * @param newTag the new tag to create - * @param fromTag existing tag the new tag is based from - */ - void setTag(String newTag, String fromTag); - - /** - * Add a tag to the list with the given name, and reference - * to the given kind and name. - * @param name - * @param fromKind - * @param fromName - * @return - */ - ITagReference addTag(String name, String fromKind, String fromName); - - /** - * Add a tag to the list with the given name, namespace, and reference - * to the given kind, namespace, and name. - * @param name - * @param fromKind - * @param fromName - * @param fromNamespace - * @return - */ - ITagReference addTag(String name, String fromKind, String fromName, String fromNamespace); - - /** - * Gets the long imagae id for the provided tag - * @param tagName name of the image stream tag to interrogate - * @return - */ - String getImageId(String tagName); + /** + * The collection of tag references for this imagestream + * + */ + Collection getTags(); - /** - * The collection of tag references for this imagestream - * @return - */ - Collection getTags(); - - /** - * The collection of tag names as listed - * in status.tags - * @return - */ - Collection getTagNames(); + /** + * The collection of tag names as listed in status.tags + * + */ + Collection getTagNames(); } diff --git a/src/main/java/com/openshift/restclient/model/ILifecycle.java b/src/main/java/com/openshift/restclient/model/ILifecycle.java new file mode 100644 index 00000000..34a0e7d1 --- /dev/null +++ b/src/main/java/com/openshift/restclient/model/ILifecycle.java @@ -0,0 +1,31 @@ +/******************************************************************************* + * Copyright (c) 2016 Red Hat, Inc. + * Distributed under license by Red Hat, Inc. All rights reserved. + * This program is made available under the terms of the + * Eclipse Public License v1.0 which accompanies this distribution, + * and is available at http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Red Hat, Inc. - initial API and implementation + ******************************************************************************/ + +package com.openshift.restclient.model; + +import java.util.Optional; + +/** + * @author Ulf Lilleengen + */ +public interface ILifecycle extends JSONSerializeable { + Optional getPostStart(); + + Optional getPreStop(); + + interface IBuilder { + IBuilder preStop(IHandler handler); + + IBuilder postStart(IHandler handler); + + ILifecycle build(); + } +} diff --git a/src/main/java/com/openshift/restclient/model/ILimitRange.java b/src/main/java/com/openshift/restclient/model/ILimitRange.java index cb899cb5..8f9b8be4 100644 --- a/src/main/java/com/openshift/restclient/model/ILimitRange.java +++ b/src/main/java/com/openshift/restclient/model/ILimitRange.java @@ -8,13 +8,9 @@ * Contributors: * Red Hat, Inc. - initial API and implementation ******************************************************************************/ -package com.openshift.restclient.model; -import com.openshift.restclient.model.IResource; +package com.openshift.restclient.model; -/** - * @author Jeff Cantrill - */ public interface ILimitRange extends IResource { } diff --git a/src/main/java/com/openshift/restclient/model/IList.java b/src/main/java/com/openshift/restclient/model/IList.java index 5f54f46e..a9f62794 100644 --- a/src/main/java/com/openshift/restclient/model/IList.java +++ b/src/main/java/com/openshift/restclient/model/IList.java @@ -6,6 +6,7 @@ * * Contributors: Red Hat, Inc. ******************************************************************************/ + package com.openshift.restclient.model; import java.util.Collection; @@ -13,18 +14,17 @@ /** * A list of resources. * - * @author Jeff Cantrill */ -public interface IList extends IResource{ - /** - * Retrieve the list of resources for this config - * @return - */ - Collection getItems(); +public interface IList extends IResource { + /** + * Retrieve the list of resources for this config + * + */ + Collection getItems(); - /** - * Add all of the given resources to the list - * @param items - */ - void addAll(Collection items); + /** + * Add all of the given resources to the list + * + */ + void addAll(Collection items); } diff --git a/src/main/java/com/openshift/restclient/model/INamespace.java b/src/main/java/com/openshift/restclient/model/INamespace.java new file mode 100644 index 00000000..bb0e97a1 --- /dev/null +++ b/src/main/java/com/openshift/restclient/model/INamespace.java @@ -0,0 +1,39 @@ +/******************************************************************************* + * Copyright (c) 2015 Red Hat, Inc. Distributed under license by Red Hat, Inc. + * All rights reserved. This program is made available under the terms of the + * Eclipse Public License v1.0 which accompanies this distribution, and is + * available at http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: Red Hat, Inc. + ******************************************************************************/ + +package com.openshift.restclient.model; + +import java.util.List; + +/** + * @author Thomas Krause + */ +public interface INamespace extends IResource { + + /** + * Retrieves resource of the given kind that are scoped to this project + * + * @param kind + * the resource kind to retrieve + * @return a list of {@link INamespace}s + */ + List getResources(String kind); + + String getDisplayName(); + + void setDisplayName(String displayName); + + String getDescription(); + + void setDescription(String description); + + String getRequester(); + + void setRequest(String requester); +} diff --git a/src/main/java/com/openshift/restclient/model/IObjectFieldSelector.java b/src/main/java/com/openshift/restclient/model/IObjectFieldSelector.java index afb33039..142d6316 100644 --- a/src/main/java/com/openshift/restclient/model/IObjectFieldSelector.java +++ b/src/main/java/com/openshift/restclient/model/IObjectFieldSelector.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2016 Red Hat, Inc. + * Copyright (c) 2016-2020 Red Hat, Inc. * Distributed under license by Red Hat, Inc. All rights reserved. * This program is made available under the terms of the * Eclipse Public License v1.0 which accompanies this distribution, @@ -8,13 +8,12 @@ * Contributors: * Red Hat, Inc. - initial API and implementation ******************************************************************************/ + package com.openshift.restclient.model; import com.openshift.restclient.model.IEnvironmentVariable.IEnvVarSource; public interface IObjectFieldSelector extends IEnvVarSource { - - String getApiVersion(); - - String getFieldPath(); + + String getFieldPath(); } diff --git a/src/main/java/com/openshift/restclient/model/IObjectReference.java b/src/main/java/com/openshift/restclient/model/IObjectReference.java index 815594aa..4cea9c9d 100644 --- a/src/main/java/com/openshift/restclient/model/IObjectReference.java +++ b/src/main/java/com/openshift/restclient/model/IObjectReference.java @@ -8,49 +8,66 @@ * Contributors: * Red Hat, Inc. - initial API and implementation ******************************************************************************/ + package com.openshift.restclient.model; /** - * An OpenShift object reference to an - * OpenShift object - * @author Jeff Cantrill + * An OpenShift object reference to an OpenShift object * */ public interface IObjectReference { - /** - * Returns the resource kind - * @return - */ - String getKind(); - - /** - * returns the api version of this resource - * @return - */ - String getApiVersion(); - - /** - * returns the resource version of this resource - * @return - */ - String getResourceVersion(); - - /** - * Returns the identifier for this resource - * @return - */ - String getName(); - - /** - * Returns the scope of this resource - * @return - */ - String getNamespace(); - - String getFieldPath(); - - String getUID(); - - String toJson(); + /** + * Returns the resource kind + * + */ + String getKind(); + + /** + * The obj ref kind + * + */ + void setKind(String kind); + + /** + * returns the api version of this resource + * + */ + String getApiVersion(); + + /** + * returns the resource version of this resource + * + */ + String getResourceVersion(); + + /** + * Returns the identifier for this resource + * + */ + String getName(); + + /** + * The name of the obj ref + * + */ + void setName(String name); + + /** + * Returns the scope of this resource + * + */ + String getNamespace(); + + /** + * The namespace for the object ref + * + */ + void setNamespace(String namespace); + + String getFieldPath(); + + String getUID(); + + String toJson(); } diff --git a/src/main/java/com/openshift/restclient/model/IPod.java b/src/main/java/com/openshift/restclient/model/IPod.java index a4026090..8d281324 100644 --- a/src/main/java/com/openshift/restclient/model/IPod.java +++ b/src/main/java/com/openshift/restclient/model/IPod.java @@ -1,67 +1,86 @@ /******************************************************************************* - * Copyright (c) 2015 Red Hat, Inc. Distributed under license by Red Hat, Inc. + * Copyright (c) 2015-2018 Red Hat, Inc. Distributed under license by Red Hat, Inc. * All rights reserved. This program is made available under the terms of the * Eclipse Public License v1.0 which accompanies this distribution, and is * available at http://www.eclipse.org/legal/epl-v10.html * * Contributors: Red Hat, Inc. ******************************************************************************/ + package com.openshift.restclient.model; import java.util.Collection; import java.util.Set; -/** - * @author Jeff Cantrill - */ public interface IPod extends IResource { - /** - * Gets the IP of the Pod - * @return - */ - String getIP(); - - /** - * Gets the name of the host on which - * the pod is running - * @return - */ - String getHost(); - - /** - * Gets the collection of image names - * for the pod containers - * @return - */ - Collection getImages(); - - /** - * Gets the status of the pod - * @return - */ - String getStatus(); - - /** - * Retrieve the set of ports that the - * containers are using - */ - Set getContainerPorts(); - - /** - * Add a container with the given name. This is - * useful if creating a pod directly without a - * resource controller - * - * @param name - * @return - */ - IContainer addContainer(String name); - - /** - * Retrieve all the containers spec'd - * for the pod - * @return collection of containers - */ - Collection getContainers(); + /** + * Returns the IP of this pod. + * + * @return ip of this pod. + */ + String getIP(); + + /** + * Returns the hostname of the host on which the pod is running. + * + * @return the hostname of this pod. + * + */ + String getHost(); + + /** + * Returns the names of the images that the containers of this pod are using. + * + * @return the image names for the containers of this pod. + */ + Collection getImages(); + + /** + * Returns the status of the pod. The pod status is derived from the status of + * all it's containers. The current implementation is limited to the status of + * the 1st container though. The string that's returned is built out of + * different properties of the container: + *
    + *
  • state.waiting.reason
  • + *
  • state.terminated.reason
  • , + *
  • state.terminated.signal
  • + *
  • state.terminated.exitCode
  • + *
+ * + * @return the status of this pod + */ + String getStatus(); + + /** + * Returns the ports that the containers of this pod are using. + * + * @returns the ports of the containers for this pod. + */ + Set getContainerPorts(); + + /** + * Adds a container with the given name. This is useful if creating a pod + * directly without a resource controller. Returns the container for the given name. + * + * @param the name of the container + * + * @return the container that was added. + */ + IContainer addContainer(String name); + + /** + * Returns all the containers for this pod. + * + * @return the containers for this pod. + */ + Collection getContainers(); + + /** + * Returns {@code true} if all containers of this pod are ready. {@code false} + * otherwise. + * + * @return true if all containers are ready, false otherwise. + */ + boolean isReady(); } diff --git a/src/main/java/com/openshift/restclient/model/IPort.java b/src/main/java/com/openshift/restclient/model/IPort.java index 37c43655..fd107f21 100644 --- a/src/main/java/com/openshift/restclient/model/IPort.java +++ b/src/main/java/com/openshift/restclient/model/IPort.java @@ -8,23 +8,23 @@ * Contributors: * Red Hat, Inc. - initial API and implementation ******************************************************************************/ + package com.openshift.restclient.model; /** * Port details. - * @author Jeff Cantrill * */ public interface IPort { - - /** - * The name of the port - * - * @return the name or null if undefined. - */ - String getName(); - - int getContainerPort(); - - String getProtocol(); + + /** + * The name of the port + * + * @return the name or null if undefined. + */ + String getName(); + + int getContainerPort(); + + String getProtocol(); } diff --git a/src/main/java/com/openshift/restclient/model/IProject.java b/src/main/java/com/openshift/restclient/model/IProject.java index 1f27f41a..db19c5b7 100644 --- a/src/main/java/com/openshift/restclient/model/IProject.java +++ b/src/main/java/com/openshift/restclient/model/IProject.java @@ -6,29 +6,29 @@ * * Contributors: Red Hat, Inc. ******************************************************************************/ + package com.openshift.restclient.model; import java.util.List; -/** - * @author Jeff Cantrill - */ public interface IProject extends IResource { - /** - * Retrieves resource of the given kind that are scoped to - * this project - * @param kind - * @return List - */ - List getResources(String kind); - - String getDisplayName(); - - void setDisplayName(String name); - - String getDescription(); - - void setDescription(String value); - + /** + * Retrieves resource of the given kind that are scoped to this project + * + * @param kind + * @return List + */ + List getResources(String kind); + + String getDisplayName(); + + void setDisplayName(String name); + + String getDescription(); + + void setDescription(String value); + + String getStatus(); + } diff --git a/src/main/java/com/openshift/restclient/model/IReplicationController.java b/src/main/java/com/openshift/restclient/model/IReplicationController.java index 9a0d4581..84aa6e04 100644 --- a/src/main/java/com/openshift/restclient/model/IReplicationController.java +++ b/src/main/java/com/openshift/restclient/model/IReplicationController.java @@ -6,6 +6,7 @@ * * Contributors: Red Hat, Inc. ******************************************************************************/ + package com.openshift.restclient.model; import java.util.Collection; @@ -14,180 +15,210 @@ import java.util.Set; import com.openshift.restclient.images.DockerImageURI; -import com.openshift.restclient.model.volume.IVolume; import com.openshift.restclient.model.volume.IVolumeSource; -/** - * @author Jeff Cantrill - */ -public interface IReplicationController extends IResource{ - - static final String DEPLOYMENT_PHASE = "openshift.io/deployment.phase"; - - /** - * Set an environment variable to the given name and - * value on the first container in the list of containers - * - * @param name - * @param value - */ - void setEnvironmentVariable(String name, String value); - - /** - * Set an environment variable to the given name and - * value on the given container. Returns silently - * if the containerName is not found - * - * @param containerName - * @param name - * @param value - */ - void setEnvironmentVariable(String containerName, String name, String value); - - /** - * Removes an environment variable with the given name. - * Returns silently if the name is not found - * - * @throws IllegalArgumentException if name is null - * - * @param name - */ - public void removeEnvironmentVariable(String name); - - /** - * Removes an environment variable with the given name and - * value on the given container. Returns silently - * if the containerName or the name is not found - * - * @throws IllegalArgumentException if name is null - * - * @param containerName - * @param name - */ - public void removeEnvironmentVariable(String containerName, String name); - - /** - * Return the list of env vars of the first container - * @return - */ - Collection getEnvironmentVariables(); - - /** - * Return the list of env vars for the given container or an empty list - * if the container is not found - * @param containerName - * @return - */ - Collection getEnvironmentVariables(String containerName); - - /** - * Returns the desired number of replicas - * @return - */ - int getDesiredReplicaCount(); - int getReplicas(); - - void setReplicas(int count); - - /** - * Sets a new desired number of replicas - * @param new number of replicas - */ - void setDesiredReplicaCount(int numOfReplicas); - - /** - * Returns the current number of replicas - * @return - */ - int getCurrentReplicaCount(); - - /** - * Returns the selector used by the controller - * @return - */ - Map getReplicaSelector(); - - /** - * Set the selector using the map of values - * @param selector - */ - void setReplicaSelector(Map selector); - void setReplicaSelector(String key, String value); - - /** - * Retrieves the list of images deployed in the - * pod containers from this controller - * @return - */ - Collection getImages(); - - /** - * Add a container to the pod that will be spun up as - * part of this deployment. - * - * @param name the name of the container - * @param tag the docker uri - * @param containerPorts the container ports - * @param volumes the set of emptyDir volumes to add to the config - */ - IContainer addContainer(String name, DockerImageURI tag, Set containerPorts, Map envVars, List volumes); - - /** - * Add a container to the pod that will be spun up as - * part of this deployment, defaulting the name to the image name - * - * @param tag the docker uri - * @param containerPorts the container ports - */ - IContainer addContainer(DockerImageURI tag, Set containerPorts, Map envVars); - - /** - * Add a container with the given name - * @param name - * @return - */ - IContainer addContainer(String name); - - /** - * Retrieve a container by name or null if it is not found - * @param name - * @return the container or null if not found - */ - IContainer getContainer(String name); - - /** - * Retrieve the containers defined in spec - * @param name - * @return collection of containers or empty collection - */ - Collection getContainers(); - - /** - * Add or update a label to the template spec; - * @param key - * @param value - */ - void addTemplateLabel(String key, String value); - - /** - * The volumes associated with the pod spec - * @return - */ - Set getVolumes(); - - /** - * Adds a volume to the pod spec. If a volume with the same name already exists, the volume is not added. - * - * @param volumeSource The volume to add to the pod spec - */ - void addVolume(IVolumeSource volumeSource); - - /** - * Sets the volumes associated with the pod spec. Existing volumes will be overwritten. - * - * @param volumes The volumes to assign to the pod spec. - */ - void setVolumes(Set volumes); - - void setContainers(Collection containers); +public interface IReplicationController extends IResource { + + static final String DEPLOYMENT_PHASE = "openshift.io/deployment.phase"; + + /** + * Set an environment variable to the given name and value on the first + * container in the list of containers + * + */ + void setEnvironmentVariable(String name, String value); + + /** + * Set an environment variable to the given name and value on the given + * container. Returns silently if the containerName is not found + * + */ + void setEnvironmentVariable(String containerName, String name, String value); + + /** + * Removes an environment variable with the given name. Returns silently if the + * name is not found + * + * @throws IllegalArgumentException + * if name is null + * + */ + public void removeEnvironmentVariable(String name); + + /** + * Removes an environment variable with the given name and value on the given + * container. Returns silently if the containerName or the name is not found + * + * @throws IllegalArgumentException + * if name is null + * + */ + public void removeEnvironmentVariable(String containerName, String name); + + /** + * Return the list of env vars of the first container + * + */ + Collection getEnvironmentVariables(); + + /** + * Return the list of env vars for the given container or an empty list if the + * container is not found + * + */ + Collection getEnvironmentVariables(String containerName); + + /** + * Returns the desired number of replicas + * + */ + int getDesiredReplicaCount(); + + int getReplicas(); + + void setReplicas(int count); + + /** + * Sets a new desired number of replicas + * + * @param new + * number of replicas + */ + void setDesiredReplicaCount(int numOfReplicas); + + /** + * Returns the current number of replicas + * + */ + int getCurrentReplicaCount(); + + /** + * Returns the selector used by the controller + * + */ + Map getReplicaSelector(); + + /** + * Set the selector using the map of values + * + */ + void setReplicaSelector(Map selector); + + void setReplicaSelector(String key, String value); + + /** + * Retrieves the list of images deployed in the pod containers from this + * controller + * + */ + Collection getImages(); + + /** + * Add a container to the pod that will be spun up as part of this deployment. + * + * @param name + * the name of the container + * @param tag + * the docker uri + * @param containerPorts + * the container ports + * @param volumes + * the set of emptyDir volumes to add to the config + */ + IContainer addContainer(String name, DockerImageURI tag, Set containerPorts, Map envVars, + List volumes); + + /** + * Add a container to the pod that will be spun up as part of this deployment, + * defaulting the name to the image name + * + * @param tag + * the docker uri + * @param containerPorts + * the container ports + */ + IContainer addContainer(DockerImageURI tag, Set containerPorts, Map envVars); + + /** + * Add a container with the given name + * + */ + IContainer addContainer(String name); + + /** + * Retrieve a container by name or null if it is not found + * + * @return the container or null if not found + */ + IContainer getContainer(String name); + + /** + * Retrieve the containers defined in spec + * + * @return collection of containers or empty collection + */ + Collection getContainers(); + + /** + * Returns the labels for the template in this replication controller + * + */ + Map getTemplateLabels(); + + /** + * Add or update a label to the template spec; + * + */ + void addTemplateLabel(String key, String value); + + /** + * The volumes associated with the pod spec + * + */ + Set getVolumes(); + + /** + * Adds a volume to the pod spec. If a volume with the same name already exists, + * the volume is not added. + * + * @param volumeSource + * The volume to add to the pod spec + */ + void addVolume(IVolumeSource volumeSource); + + /** + * Add a volume source of the given type with the given name. Unimplemented + * types will return a generic volumesource impl + * + * @param volumetype + * @param name + * @return + */ + T addVolume(String volumetype, String name); + + /** + * Sets the volumes associated with the pod spec. Existing volumes will be + * overwritten. + * + * @param volumes + * The volumes to assign to the pod spec. + */ + void setVolumes(Set volumes); + + void setContainers(Collection containers); + + /** + * Sets the service account to run this replication controller under. + * + * @param volumes + * The service account to assign to the spec. + */ + void setServiceAccountName(String serviceAccount); + + /** + * Retrieves the service account used by the controller + * + */ + String getServiceAccountName(); + } diff --git a/src/main/java/com/openshift/restclient/model/IResource.java b/src/main/java/com/openshift/restclient/model/IResource.java index 8b51fb51..2c0bd789 100644 --- a/src/main/java/com/openshift/restclient/model/IResource.java +++ b/src/main/java/com/openshift/restclient/model/IResource.java @@ -6,123 +6,104 @@ * * Contributors: Red Hat, Inc. ******************************************************************************/ + package com.openshift.restclient.model; import java.util.Map; import java.util.Set; +import com.openshift.restclient.api.models.IAnnotatable; +import com.openshift.restclient.api.models.ITypeMeta; import com.openshift.restclient.capability.ICapability; import com.openshift.restclient.capability.ICapable; /** - * IResource is a representation of a Kubernetes resource (e.g. Service, Pod, ReplicationController) + * IResource is a representation of a Kubernetes resource (e.g. Service, Pod, + * ReplicationController) * - * @author Jeff Cantrill */ -public interface IResource extends ICapable, Annotatable { - - Map getMetadata(); - - /** - * @return the list of capabilities supported by this resource - */ - Set> getCapabilities(); - - /** - * @return the resource kind - */ - String getKind(); - - /** - * @return the version of this resource - */ - String getApiVersion(); - - /** - * Returns the timestamp of when this resource - * was created - * @return - */ - String getCreationTimeStamp(); - - /** - * Returns the identifier for this resource - * @return - */ - String getName(); - - /** - * Returns the scope of this resource - * @return - */ - String getNamespace(); - - /** - * Return the project of the resource which - * corresponds to the namespace - * @return - */ - IProject getProject(); - - /** - * Retrieves the labels associated with the resource - * @return - */ - Map getLabels(); - - /** - * Add or update a label; - * @param key - * @param value - */ - void addLabel(String key, String value); - - /** - * Returns true if the resource is annotated with - * the given key - * @param key - * @return true if the annotation key exists - */ - boolean isAnnotatedWith(String key); - - /** - * Retrieves the annotated value for the given key - * @param key - * @return - */ - String getAnnotation(String key); - - /** - * Set the resource annotation - * @param key - * @param value - */ - void setAnnotation(String key, String value); - - /** - * Removes the resource annotation - * @param key - */ - void removeAnnotation(String key); - - /** - * Retrieves the annotations associated with the resource - * @return - */ - Map getAnnotations(); - - String getResourceVersion(); - - /** - * - * @return the json string representing the resource - */ - String toJson(); - - /** - * - * @param compact true if the string should be compact; default: false - * @return the json string representing the resource - */ - String toJson(boolean compact); +public interface IResource extends ICapable, Annotatable, IAnnotatable, JSONSerializeable, ITypeMeta { + + Map getMetadata(); + + /** + * @return the list of capabilities supported by this resource + */ + Set> getCapabilities(); + + /** + * Returns the timestamp of when this resource was created + * + */ + String getCreationTimeStamp(); + + /** + * Returns the identifier for this resource + * + */ + String getName(); + + /** + * Returns the scope of this resource + * + */ + String getNamespaceName(); + + /** + * Return the project of the resource + * + */ + IProject getProject(); + + /** + * Return the namespace of the resource + * + */ + INamespace getNamespace(); + + /** + * Retrieves the labels associated with the resource + * + */ + Map getLabels(); + + /** + * Add or update a label; + * + */ + void addLabel(String key, String value); + + /** + * Returns true if the resource is annotated with the given key + * + * @return true if the annotation key exists + */ + boolean isAnnotatedWith(String key); + + /** + * Retrieves the annotated value for the given key + * + */ + String getAnnotation(String key); + + /** + * Set the resource annotation + * + */ + void setAnnotation(String key, String value); + + /** + * Removes the resource annotation + * + */ + void removeAnnotation(String key); + + /** + * Retrieves the annotations associated with the resource + * + */ + Map getAnnotations(); + + String getResourceVersion(); + } diff --git a/src/main/java/com/openshift/restclient/model/IResourceBuilder.java b/src/main/java/com/openshift/restclient/model/IResourceBuilder.java index 38baf7b8..1a43732c 100644 --- a/src/main/java/com/openshift/restclient/model/IResourceBuilder.java +++ b/src/main/java/com/openshift/restclient/model/IResourceBuilder.java @@ -8,24 +8,28 @@ * Contributors: * Red Hat, Inc. - initial API and implementation ******************************************************************************/ + package com.openshift.restclient.model; +import java.util.Map; + /** * A builder for building up resources - * @author jeff.cantrill * - * @param */ @SuppressWarnings("rawtypes") public interface IResourceBuilder { - - B named(String name); - B inNamespace(String name); - - T build(); - - interface Endable{ - - IResourceBuilder end(); - } + + B named(String name); + + B inNamespace(String name); + + B withLabels(Map labels); + + T build(); + + interface Endable { + + IResourceBuilder end(); + } } diff --git a/src/main/java/com/openshift/restclient/model/IResourceQuota.java b/src/main/java/com/openshift/restclient/model/IResourceQuota.java index 4806dcfc..c0ce547d 100644 --- a/src/main/java/com/openshift/restclient/model/IResourceQuota.java +++ b/src/main/java/com/openshift/restclient/model/IResourceQuota.java @@ -8,13 +8,9 @@ * Contributors: * Red Hat, Inc. - initial API and implementation ******************************************************************************/ -package com.openshift.restclient.model; -import com.openshift.restclient.model.IResource; +package com.openshift.restclient.model; -/** - * @author Jeff Cantrill - */ public interface IResourceQuota extends IResource { } diff --git a/src/main/java/com/openshift/restclient/model/ISecretKeySelector.java b/src/main/java/com/openshift/restclient/model/ISecretKeySelector.java index 6a2c2373..db0e817f 100644 --- a/src/main/java/com/openshift/restclient/model/ISecretKeySelector.java +++ b/src/main/java/com/openshift/restclient/model/ISecretKeySelector.java @@ -8,14 +8,15 @@ * Contributors: * Red Hat, Inc. - initial API and implementation ******************************************************************************/ + package com.openshift.restclient.model; import com.openshift.restclient.model.IEnvironmentVariable.IEnvVarSource; public interface ISecretKeySelector extends IEnvVarSource { - String getName(); - - String getKey(); + String getName(); + + String getKey(); } diff --git a/src/main/java/com/openshift/restclient/model/IService.java b/src/main/java/com/openshift/restclient/model/IService.java index fc939996..cae6c189 100644 --- a/src/main/java/com/openshift/restclient/model/IService.java +++ b/src/main/java/com/openshift/restclient/model/IService.java @@ -6,6 +6,7 @@ * * Contributors: Red Hat, Inc. ******************************************************************************/ + package com.openshift.restclient.model; import java.util.List; @@ -14,82 +15,93 @@ /** * Kubernetes Service to access a Pod * - * @author Jeff Cantrill */ -public interface IService extends IResource{ - - /** - * Sets the container port exposed by the image - * @param port - */ - void setTargetPort(int port); - - /** - * Sets the exposed port that is mapped to a - * running image - * @param port - */ - void setPort(int port); - - /** - * Returns the first exposed port that is mapped to - * a running image - * @return - */ - int getPort(); - - IServicePort addPort(int port, int targetPort); - - /** - * Sets the container name that the service - * routes traffic to. - * @param selector - */ - void setSelector(Map selector); - - /** - * Convenience method for setting a selector that has - * a singular key/value pair. - * @param key - * @param value - */ - void setSelector(String key, String value); - - /** - * Returns the selector used to find the Pod - * to which this service is routing - * @return - */ - Map getSelector(); - - /** - * The port this service targets on the - * pod - * @return - */ - String getTargetPort(); - - /** - * Returns the IP of the service. - * @return - */ - String getPortalIP(); - - /** - * Retrieves the pods for this service - * @return - */ - List getPods(); - - /** - * Get the collection of ports for the service - * @return - */ - List getPorts(); - - /** - * Set the collection of ports for the service - */ - void setPorts(List ports); +public interface IService extends IResource { + + /** + * Sets the container port exposed by the image + * + */ + void setTargetPort(int port); + + /** + * Sets the exposed port that is mapped to a running image + * + */ + void setPort(int port); + + /** + * Returns the first exposed port that is mapped to a running image + * + */ + int getPort(); + + IServicePort addPort(int port, int targetPort); + + IServicePort addPort(int port, int targetPort, String name); + + /** + * Sets the container name that the service routes traffic to. + * + */ + void setSelector(Map selector); + + /** + * Convenience method for setting a selector that has a singular key/value pair. + * + */ + void setSelector(String key, String value); + + /** + * Returns the selector used to find the Pod to which this service is routing + * + */ + Map getSelector(); + + /** + * The port this service targets on the pod + * + */ + String getTargetPort(); + + /** + * Returns the IP of the service. + * + */ + @Deprecated + String getPortalIP(); + + /** + * Returns the IP of the service. + * + */ + String getClusterIP(); + + /** + * Retrieves the pods for this service + * + */ + List getPods(); + + /** + * Get the collection of ports for the service + * + */ + List getPorts(); + + /** + * Set the collection of ports for the service + */ + void setPorts(List ports); + + /** + * Returns the type of the service. + * + */ + String getType(); + /** + * Sets the type of the service. + */ + void setType(String type); } diff --git a/src/main/java/com/openshift/restclient/model/IServicePort.java b/src/main/java/com/openshift/restclient/model/IServicePort.java index e87a6cef..14e6b027 100644 --- a/src/main/java/com/openshift/restclient/model/IServicePort.java +++ b/src/main/java/com/openshift/restclient/model/IServicePort.java @@ -8,38 +8,52 @@ * Contributors: * Red Hat, Inc. - initial API and implementation ******************************************************************************/ + package com.openshift.restclient.model; public interface IServicePort { - /** - * The name of the port - * - * @return the name or null if undefined. - */ - String getName(); - void setName(String name); - - /** - * Port exposed by the service - * @return - */ - int getPort(); - void setPort(int port); - - /** - * The target port on the pod it services. An integer - * or named port on the pod spec - * @return - */ - String getTargetPort(); - void setTargetPort(int port); - void setTargetPort(String name); - - /** - * IP protocol (TCP, UDP) - * @return - */ - String getProtocol(); - void setProtocol(String proto); + /** + * The name of the port + * + * @return the name or null if undefined. + */ + String getName(); + + void setName(String name); + + /** + * Port exposed by the service + * + */ + int getPort(); + + void setPort(int port); + + /** + * The target port on the pod it services. An integer or named port on the pod + * spec + * + */ + String getTargetPort(); + + void setTargetPort(int port); + + void setTargetPort(String name); + + /** + * IP protocol (TCP, UDP) + * + */ + String getProtocol(); + + void setProtocol(String proto); + + /** + * External service port + */ + + String getNodePort(); + + void setNodePort(String nodePort); } diff --git a/src/main/java/com/openshift/restclient/model/IStatus.java b/src/main/java/com/openshift/restclient/model/IStatus.java index 596f28d0..c00a0bed 100644 --- a/src/main/java/com/openshift/restclient/model/IStatus.java +++ b/src/main/java/com/openshift/restclient/model/IStatus.java @@ -6,47 +6,47 @@ * * Contributors: Red Hat, Inc. ******************************************************************************/ + package com.openshift.restclient.model; /** - * Status message resulting from trying to manipulate an - * OpenShift resource and an error occurs + * Status message resulting from trying to manipulate an OpenShift resource and + * an error occurs * - * @author Jeff Cantrill */ public interface IStatus extends IResource { - public static final String SUCCESS = "Success"; - public static final String FAILURE = "Failure"; - - /** - * Returns the status message - * @return - */ - String getMessage(); - - /** - * The HTTP status code - * @return an int - */ - int getCode(); - - /** - * The status info of the status - * @return - */ - String getStatus(); - - /** - * Determine if this status is indicates - * a failure - * @return - */ - boolean isFailure(); - - /** - * Returns {@code true} if this status represent success} - * @return - */ - boolean isSuccess(); + public static final String SUCCESS = "Success"; + public static final String FAILURE = "Failure"; + + /** + * Returns the status message + * + */ + String getMessage(); + + /** + * The HTTP status code + * + * @return an int + */ + int getCode(); + + /** + * The status info of the status + * + */ + String getStatus(); + + /** + * Determine if this status is indicates a failure + * + */ + boolean isFailure(); + + /** + * Returns {@code true} if this status represent success} + * + */ + boolean isSuccess(); } diff --git a/src/main/java/com/openshift/restclient/model/JSONSerializeable.java b/src/main/java/com/openshift/restclient/model/JSONSerializeable.java new file mode 100644 index 00000000..90193365 --- /dev/null +++ b/src/main/java/com/openshift/restclient/model/JSONSerializeable.java @@ -0,0 +1,35 @@ +/******************************************************************************* + * Copyright (c) 2016 Red Hat, Inc. + * Distributed under license by Red Hat, Inc. All rights reserved. + * This program is made available under the terms of the + * Eclipse Public License v1.0 which accompanies this distribution, + * and is available at http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Red Hat, Inc. - initial API and implementation + ******************************************************************************/ + +package com.openshift.restclient.model; + +/** + * Something that can be serialized to JSON + * + */ +public interface JSONSerializeable { + + /** + * The JSON representation + * + */ + String toJson(); + + /** + * The JSON representation + * + * @param compact + * true if it should be compact; false otherwise + */ + default String toJson(boolean compact) { + return toJson(); + } +} diff --git a/src/main/java/com/openshift/restclient/model/authorization/IPolicy.java b/src/main/java/com/openshift/restclient/model/authorization/IPolicy.java index 442f36c0..85040026 100644 --- a/src/main/java/com/openshift/restclient/model/authorization/IPolicy.java +++ b/src/main/java/com/openshift/restclient/model/authorization/IPolicy.java @@ -8,13 +8,11 @@ * Contributors: * Red Hat, Inc. - initial API and implementation ******************************************************************************/ + package com.openshift.restclient.model.authorization; import com.openshift.restclient.model.IResource; -/** - * @author Jeff Cantrill - */ public interface IPolicy extends IResource { } diff --git a/src/main/java/com/openshift/restclient/model/authorization/IPolicyBinding.java b/src/main/java/com/openshift/restclient/model/authorization/IPolicyBinding.java index c55fae2a..19014405 100644 --- a/src/main/java/com/openshift/restclient/model/authorization/IPolicyBinding.java +++ b/src/main/java/com/openshift/restclient/model/authorization/IPolicyBinding.java @@ -8,13 +8,12 @@ * Contributors: * Red Hat, Inc. - initial API and implementation ******************************************************************************/ + package com.openshift.restclient.model.authorization; import com.openshift.restclient.model.IResource; -/** - * @author Jeff Cantrill - */ + public interface IPolicyBinding extends IResource { } diff --git a/src/main/java/com/openshift/restclient/model/authorization/IRole.java b/src/main/java/com/openshift/restclient/model/authorization/IRole.java index 2bfd4e45..098f7418 100644 --- a/src/main/java/com/openshift/restclient/model/authorization/IRole.java +++ b/src/main/java/com/openshift/restclient/model/authorization/IRole.java @@ -8,13 +8,11 @@ * Contributors: * Red Hat, Inc. - initial API and implementation ******************************************************************************/ + package com.openshift.restclient.model.authorization; import com.openshift.restclient.model.IResource; -/** - * @author Jeff Cantrill - */ public interface IRole extends IResource { } diff --git a/src/main/java/com/openshift/restclient/model/authorization/IRoleBinding.java b/src/main/java/com/openshift/restclient/model/authorization/IRoleBinding.java index d11097f5..005dcf03 100644 --- a/src/main/java/com/openshift/restclient/model/authorization/IRoleBinding.java +++ b/src/main/java/com/openshift/restclient/model/authorization/IRoleBinding.java @@ -8,6 +8,7 @@ * Contributors: * Red Hat, Inc. - initial API and implementation ******************************************************************************/ + package com.openshift.restclient.model.authorization; import java.util.Set; @@ -15,22 +16,25 @@ import com.openshift.restclient.model.IObjectReference; import com.openshift.restclient.model.IResource; -/** - * @author Jeff Cantrill - */ public interface IRoleBinding extends IResource { - void setUserNames(Set names); - Set getUserNames(); - void addUserName(String name); - - void setGroupNames(Set names); - Set getGroupNames(); - void addGroupName(String name); - - void setSubjects(Set subjects); - Set getSubjects(); - - IObjectReference getRoleRef(); - void setRoleRef(IObjectReference roleRef); + void setUserNames(Set names); + + Set getUserNames(); + + void addUserName(String name); + + void setGroupNames(Set names); + + Set getGroupNames(); + + void addGroupName(String name); + + void setSubjects(Set subjects); + + Set getSubjects(); + + IObjectReference getRoleRef(); + + void setRoleRef(IObjectReference roleRef); } diff --git a/src/main/java/com/openshift/restclient/model/build/BuildSourceType.java b/src/main/java/com/openshift/restclient/model/build/BuildSourceType.java index dbbff607..d1020d9b 100644 --- a/src/main/java/com/openshift/restclient/model/build/BuildSourceType.java +++ b/src/main/java/com/openshift/restclient/model/build/BuildSourceType.java @@ -1,18 +1,18 @@ /******************************************************************************* - * Copyright (c) 2015 Red Hat, Inc. Distributed under license by Red Hat, Inc. + * Copyright (c) 2015-2018 Red Hat, Inc. Distributed under license by Red Hat, Inc. * All rights reserved. This program is made available under the terms of the * Eclipse Public License v1.0 which accompanies this distribution, and is * available at http://www.eclipse.org/legal/epl-v10.html * * Contributors: Red Hat, Inc. ******************************************************************************/ + package com.openshift.restclient.model.build; -/** - * @author Jeff Cantrill - */ public interface BuildSourceType { - - static final String GIT = "Git"; - + + static final String GIT = "Git"; + + static final String BINARY = "Binary"; + } diff --git a/src/main/java/com/openshift/restclient/model/build/BuildStrategyType.java b/src/main/java/com/openshift/restclient/model/build/BuildStrategyType.java index a8c2dd79..29a73abb 100644 --- a/src/main/java/com/openshift/restclient/model/build/BuildStrategyType.java +++ b/src/main/java/com/openshift/restclient/model/build/BuildStrategyType.java @@ -6,21 +6,22 @@ * * Contributors: Red Hat, Inc. ******************************************************************************/ + package com.openshift.restclient.model.build; /** - * The build strategies supported - * by OpenShift + * The build strategies supported by OpenShift */ public interface BuildStrategyType { - - static final String DOCKER = "Docker"; - - @Deprecated - static final String STI = "STI"; - - static final String SOURCE = "Source"; - static final String CUSTOM = "Custom"; + + static final String DOCKER = "Docker"; + + @Deprecated + static final String STI = "STI"; + + static final String SOURCE = "Source"; + static final String CUSTOM = "Custom"; + static final String JENKINS_PIPELINE = "JenkinsPipeline"; } diff --git a/src/main/java/com/openshift/restclient/model/build/BuildTriggerType.java b/src/main/java/com/openshift/restclient/model/build/BuildTriggerType.java index 6d318243..eb7d2e35 100644 --- a/src/main/java/com/openshift/restclient/model/build/BuildTriggerType.java +++ b/src/main/java/com/openshift/restclient/model/build/BuildTriggerType.java @@ -6,24 +6,22 @@ * * Contributors: Red Hat, Inc. ******************************************************************************/ + package com.openshift.restclient.model.build; -/** - * @author Jeff Cantrill - */ public interface BuildTriggerType { - @Deprecated - static final String generic = "generic"; - - @Deprecated - static final String github = "github"; - - @Deprecated - static final String imageChange = "imageChange"; + @Deprecated + static final String generic = "generic"; + + @Deprecated + static final String github = "github"; + + @Deprecated + static final String imageChange = "imageChange"; + + static final String CONFIG_CHANGE = "ConfigChange"; + static final String GENERIC = "Generic"; + static final String GITHUB = "GitHub"; + static final String IMAGE_CHANGE = "ImageChange"; - static final String CONFIG_CHANGE = "ConfigChange"; - static final String GENERIC = "Generic"; - static final String GITHUB = "GitHub"; - static final String IMAGE_CHANGE = "ImageChange"; - } diff --git a/src/main/java/com/openshift/restclient/authorization/IAuthorizationStrategyVisitor.java b/src/main/java/com/openshift/restclient/model/build/IBinaryBuildSource.java similarity index 50% rename from src/main/java/com/openshift/restclient/authorization/IAuthorizationStrategyVisitor.java rename to src/main/java/com/openshift/restclient/model/build/IBinaryBuildSource.java index 0242d346..b64bc585 100644 --- a/src/main/java/com/openshift/restclient/authorization/IAuthorizationStrategyVisitor.java +++ b/src/main/java/com/openshift/restclient/model/build/IBinaryBuildSource.java @@ -1,19 +1,15 @@ /******************************************************************************* - * Copyright (c) 2015 Red Hat, Inc. Distributed under license by Red Hat, Inc. + * Copyright (c) 2018 Red Hat, Inc. Distributed under license by Red Hat, Inc. * All rights reserved. This program is made available under the terms of the * Eclipse Public License v1.0 which accompanies this distribution, and is * available at http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: Red Hat, Inc. - initial API and implementation + * + * Contributors: Red Hat, Inc. ******************************************************************************/ -package com.openshift.restclient.authorization; -/** - * @author Jeff Cantrill - */ -public interface IAuthorizationStrategyVisitor { - - void visit(BasicAuthorizationStrategy strategy); +package com.openshift.restclient.model.build; - void visit(TokenAuthorizationStrategy tokenAuthorizationStrategy); +public interface IBinaryBuildSource extends IBuildSource { + + String getAsFile(); } diff --git a/src/main/java/com/openshift/restclient/model/build/IBuildConfigBuilder.java b/src/main/java/com/openshift/restclient/model/build/IBuildConfigBuilder.java index dfd22bc0..a2b03d21 100644 --- a/src/main/java/com/openshift/restclient/model/build/IBuildConfigBuilder.java +++ b/src/main/java/com/openshift/restclient/model/build/IBuildConfigBuilder.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2016 Red Hat, Inc. + * Copyright (c) 2016-2018 Red Hat, Inc. * Distributed under license by Red Hat, Inc. All rights reserved. * This program is made available under the terms of the * Eclipse Public License v1.0 which accompanies this distribution, @@ -8,6 +8,7 @@ * Contributors: * Red Hat, Inc. - initial API and implementation ******************************************************************************/ + package com.openshift.restclient.model.build; import java.util.List; @@ -19,38 +20,69 @@ public interface IBuildConfigBuilder extends IResourceBuilder, ICapability { - ISourceStrategyBuilder usingSourceStrategy(); - IGitSourceBuilder fromGitSource(); - IBuildConfigBuilder toImageStreamTag(String tag); - IBuildConfigBuilder buildOnSourceChange(boolean onSourceChange); - IBuildConfigBuilder buildOnImageChange(boolean onImageChange); - IBuildConfigBuilder buildOnConfigChange(boolean onConfigChange); - - interface IGitSourceBuilder extends Endable{ - - IBuildConfigBuilder end(); - - IGitSourceBuilder fromGitUrl(String url); - IGitSourceBuilder usingGitReference(String ref); - IGitSourceBuilder inContextDir(String contextDir); - - } - - interface ISourceStrategyBuilder extends Endable{ - - IBuildConfigBuilder end(); - - /** - * The imagestream tag in form of 'name:tag" - * @param tag - * @return - */ - ISourceStrategyBuilder fromImageStreamTag(String tag); - - ISourceStrategyBuilder inNamespace(String namespace); - - ISourceStrategyBuilder withEnvVars(List envVars); - - } - + ISourceStrategyBuilder usingSourceStrategy(); + + IJenkinsPipelineStrategyBuilder usingJenkinsPipelineStrategy(); + + IGitSourceBuilder fromGitSource(); + + IBinarySourceBuilder fromBinarySource(); + + IBuildConfigBuilder toImageStreamTag(String tag); + + IBuildConfigBuilder buildOnSourceChange(boolean onSourceChange); + + IBuildConfigBuilder buildOnImageChange(boolean onImageChange); + + IBuildConfigBuilder buildOnConfigChange(boolean onConfigChange); + + interface ISourceBuilder extends Endable { + IBuildConfigBuilder end(); + + T inContextDir(String contextDir); + } + + interface IGitSourceBuilder extends ISourceBuilder { + IGitSourceBuilder fromGitUrl(String url); + + IGitSourceBuilder usingGitReference(String ref); + } + + interface IBinarySourceBuilder extends ISourceBuilder { + IBinarySourceBuilder fromAsFile(String asFile); + } + + interface ISourceStrategyBuilder extends Endable { + + IBuildConfigBuilder end(); + + /** + * The imagestream tag in form of 'name:tag" + * + * @param tag + * 'name:tag' + */ + ISourceStrategyBuilder fromImageStreamTag(String tag); + + ISourceStrategyBuilder inNamespace(String namespace); + + ISourceStrategyBuilder withEnvVars(List envVars); + + /** + * @param tag + * docker pullspec + */ + ISourceStrategyBuilder fromDockerImage(String tag); + + } + + interface IJenkinsPipelineStrategyBuilder extends Endable { + + IBuildConfigBuilder end(); + + IJenkinsPipelineStrategyBuilder usingFile(String file); + + IJenkinsPipelineStrategyBuilder usingFilePath(String filePath); + } + } diff --git a/src/main/java/com/openshift/restclient/model/build/IBuildRequest.java b/src/main/java/com/openshift/restclient/model/build/IBuildRequest.java index c71b04f1..d6e82f52 100644 --- a/src/main/java/com/openshift/restclient/model/build/IBuildRequest.java +++ b/src/main/java/com/openshift/restclient/model/build/IBuildRequest.java @@ -8,21 +8,59 @@ * Contributors: * Red Hat, Inc. - initial API and implementation ******************************************************************************/ + package com.openshift.restclient.model.build; +import java.util.List; import com.openshift.restclient.model.IResource; /** * Resource payload for triggering a build - * @author Jeff Cantrill * */ public interface IBuildRequest extends IResource { - /** - * Set the commit level for the git clone extraction - * of the source code the build operates against - * @param commitId the specific hexadecimal commit ID associated with a git log level - */ - void setCommitId(String commitId); + /** + * Set the commit level for the git clone extraction of the source code the + * build operates against + * + * @param commitId + * the specific hexadecimal commit ID associated with a git log level + */ + void setCommitId(String commitId); + + /** + * Get the commit level for the git clone extraction of the source code the + * build operates against + * + * @return the specific hexadecimal commit ID associated with a git log level + */ + String getCommitId(); + + /** + * Add a human readable short explanation of why this build request was issued + * + * @param cause + * the description to add to the list of causes for this request + */ + void addBuildCause(String cause); + + /** + * Get the list of human readable short explanations of why this build request + * was issued + * + * @return list of reasons for the build + */ + List getBuildCauses(); + + /** + * Sets an environment variable in this build request + * + * @param name + * The name of the environment variable to set + * @param value + * The value of the variable + */ + void setEnvironmentVariable(String name, String value); + } diff --git a/src/main/java/com/openshift/restclient/model/build/IBuildSource.java b/src/main/java/com/openshift/restclient/model/build/IBuildSource.java index 3bfb621a..de9e08de 100644 --- a/src/main/java/com/openshift/restclient/model/build/IBuildSource.java +++ b/src/main/java/com/openshift/restclient/model/build/IBuildSource.java @@ -1,35 +1,28 @@ /******************************************************************************* - * Copyright (c) 2015 Red Hat, Inc. Distributed under license by Red Hat, Inc. + * Copyright (c) 2015-2018 Red Hat, Inc. Distributed under license by Red Hat, Inc. * All rights reserved. This program is made available under the terms of the * Eclipse Public License v1.0 which accompanies this distribution, and is * available at http://www.eclipse.org/legal/epl-v10.html * * Contributors: Red Hat, Inc. ******************************************************************************/ + package com.openshift.restclient.model.build; -/** - * @author Jeff Cantrill - */ public interface IBuildSource { - - /** - * The BuildSourceType - * @return {@link BuildSourceType} - */ - String getType(); - - /** - * The URI to the source repo - * @return - */ - String getURI(); - /** - * The sub-directory relative to the repo root where the source code for the application exists. - * This allows to have buildable sources in directory other than root of repository. - * - * @return - */ - String getContextDir(); + /** + * The BuildSourceType + * + * @return {@link BuildSourceType} + */ + String getType(); + + /** + * The sub-directory relative to the repo root where the source code for the + * application exists. This allows to have buildable sources in directory other + * than root of repository. + * + */ + String getContextDir(); } diff --git a/src/main/java/com/openshift/restclient/model/build/IBuildStatus.java b/src/main/java/com/openshift/restclient/model/build/IBuildStatus.java index e4f184e0..52f832dc 100644 --- a/src/main/java/com/openshift/restclient/model/build/IBuildStatus.java +++ b/src/main/java/com/openshift/restclient/model/build/IBuildStatus.java @@ -8,21 +8,22 @@ * Contributors: * Red Hat, Inc. - initial API and implementation ******************************************************************************/ + package com.openshift.restclient.model.build; import com.openshift.restclient.images.DockerImageURI; public interface IBuildStatus { - - String getPhase(); - - String getStartTime(); - - /** - * The duration of the build in nanoseconds - * @return - */ - long getDuration(); - - DockerImageURI getOutputDockerImage(); + + String getPhase(); + + String getStartTime(); + + /** + * The duration of the build in nanoseconds + * + */ + long getDuration(); + + DockerImageURI getOutputDockerImage(); } diff --git a/src/main/java/com/openshift/restclient/model/build/IBuildStrategy.java b/src/main/java/com/openshift/restclient/model/build/IBuildStrategy.java index 6c48f77c..41643f8a 100644 --- a/src/main/java/com/openshift/restclient/model/build/IBuildStrategy.java +++ b/src/main/java/com/openshift/restclient/model/build/IBuildStrategy.java @@ -6,16 +6,15 @@ * * Contributors: Red Hat, Inc. ******************************************************************************/ + package com.openshift.restclient.model.build; -/** - * @author Jeff Cantrill - */ public interface IBuildStrategy { - - /** - * The type of build Strategy - * @return {@link BuildStrategyType} - */ - String getType(); + + /** + * The type of build Strategy + * + * @return {@link BuildStrategyType} + */ + String getType(); } diff --git a/src/main/java/com/openshift/restclient/model/build/IBuildTrigger.java b/src/main/java/com/openshift/restclient/model/build/IBuildTrigger.java index 1ebded57..b513a941 100644 --- a/src/main/java/com/openshift/restclient/model/build/IBuildTrigger.java +++ b/src/main/java/com/openshift/restclient/model/build/IBuildTrigger.java @@ -6,12 +6,10 @@ * * Contributors: Red Hat, Inc. ******************************************************************************/ + package com.openshift.restclient.model.build; -/** - * @author Jeff Cantrill - */ public interface IBuildTrigger { - - String getType(); + + String getType(); } diff --git a/src/main/java/com/openshift/restclient/model/build/ICustomBuildStrategy.java b/src/main/java/com/openshift/restclient/model/build/ICustomBuildStrategy.java index 6dab8dbf..1120766a 100644 --- a/src/main/java/com/openshift/restclient/model/build/ICustomBuildStrategy.java +++ b/src/main/java/com/openshift/restclient/model/build/ICustomBuildStrategy.java @@ -6,20 +6,18 @@ * * Contributors: Red Hat, Inc. ******************************************************************************/ + package com.openshift.restclient.model.build; import java.util.Map; import com.openshift.restclient.images.DockerImageURI; -/** - * @author Jeff Cantrill - */ public interface ICustomBuildStrategy extends IBuildStrategy { - - Map getEnvironmentVariables(); - - boolean exposeDockerSocket(); - - DockerImageURI getImage(); + + Map getEnvironmentVariables(); + + boolean exposeDockerSocket(); + + DockerImageURI getImage(); } diff --git a/src/main/java/com/openshift/restclient/model/build/IDockerBuildStrategy.java b/src/main/java/com/openshift/restclient/model/build/IDockerBuildStrategy.java index d4f29a07..447610c0 100644 --- a/src/main/java/com/openshift/restclient/model/build/IDockerBuildStrategy.java +++ b/src/main/java/com/openshift/restclient/model/build/IDockerBuildStrategy.java @@ -6,18 +6,16 @@ * * Contributors: Red Hat, Inc. ******************************************************************************/ + package com.openshift.restclient.model.build; import com.openshift.restclient.images.DockerImageURI; -/** - * @author Jeff Cantrill - */ public interface IDockerBuildStrategy extends IBuildStrategy { - - String getContextDir(); - - boolean isNoCache(); - - DockerImageURI getBaseImage(); + + String getContextDir(); + + boolean isNoCache(); + + DockerImageURI getBaseImage(); } diff --git a/src/main/java/com/openshift/restclient/model/build/IGitBuildSource.java b/src/main/java/com/openshift/restclient/model/build/IGitBuildSource.java index fdef9e1b..3b9b8a3c 100644 --- a/src/main/java/com/openshift/restclient/model/build/IGitBuildSource.java +++ b/src/main/java/com/openshift/restclient/model/build/IGitBuildSource.java @@ -1,21 +1,25 @@ /******************************************************************************* - * Copyright (c) 2015 Red Hat, Inc. Distributed under license by Red Hat, Inc. + * Copyright (c) 2015-2018 Red Hat, Inc. Distributed under license by Red Hat, Inc. * All rights reserved. This program is made available under the terms of the * Eclipse Public License v1.0 which accompanies this distribution, and is * available at http://www.eclipse.org/legal/epl-v10.html * * Contributors: Red Hat, Inc. ******************************************************************************/ + package com.openshift.restclient.model.build; -/** - * @author Jeff Cantrill - */ public interface IGitBuildSource extends IBuildSource { - - /** - * The branch/tag/ref to build - * @return - */ - String getRef(); + + /** + * The branch/tag/ref to build + * + */ + String getRef(); + + /** + * The URI to the source repo + * + */ + String getURI(); } diff --git a/src/main/java/com/openshift/restclient/model/build/IImageChangeTrigger.java b/src/main/java/com/openshift/restclient/model/build/IImageChangeTrigger.java index 2c97ada9..802f421a 100644 --- a/src/main/java/com/openshift/restclient/model/build/IImageChangeTrigger.java +++ b/src/main/java/com/openshift/restclient/model/build/IImageChangeTrigger.java @@ -6,28 +6,25 @@ * * Contributors: Red Hat, Inc. ******************************************************************************/ + package com.openshift.restclient.model.build; import com.openshift.restclient.images.DockerImageURI; -/** - * @author Jeff Cantrill - */ public interface IImageChangeTrigger extends IBuildTrigger { - - - DockerImageURI getImage(); - - /** - * Returns the name of the docker image repo to watch - * @return - */ - DockerImageURI getFrom(); - - /** - * Returns the tag to watch in the image repository - * @return - */ - String getTag(); - + + DockerImageURI getImage(); + + /** + * Returns the name of the docker image repo to watch + * + */ + DockerImageURI getFrom(); + + /** + * Returns the tag to watch in the image repository + * + */ + String getTag(); + } diff --git a/src/main/java/com/openshift/restclient/model/build/IJenkinsPipelineStrategy.java b/src/main/java/com/openshift/restclient/model/build/IJenkinsPipelineStrategy.java new file mode 100644 index 00000000..13c94dcc --- /dev/null +++ b/src/main/java/com/openshift/restclient/model/build/IJenkinsPipelineStrategy.java @@ -0,0 +1,36 @@ +/******************************************************************************* + * Copyright (c) 2015 Red Hat, Inc. Distributed under license by Red Hat, Inc. + * All rights reserved. This program is made available under the terms of the + * Eclipse Public License v1.0 which accompanies this distribution, and is + * available at http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: Red Hat, Inc. + ******************************************************************************/ + +package com.openshift.restclient.model.build; + +import java.util.Collection; + +import com.openshift.restclient.model.IEnvironmentVariable; + +/** + * @author Andre Dietisheim + */ +public interface IJenkinsPipelineStrategy extends IBuildStrategy { + + static final String JENKINS_FILE = "jenkinsPipelineStrategy.jenkinsfile"; + static final String JENKINS_FILE_PATH = "jenkinsPipelineStrategy.jenkinsfilePath"; + static final String ENV = "jenkinsPipelineStrategy.env"; + + void setJenkinsfilePath(String filePath); + + String getJenkinsfilePath(); + + void setJenkinsfile(String jenkinsFile); + + String getJenkinsfile(); + + Collection getEnvVars(); + + void setEnvVars(Collection envVars); +} diff --git a/src/main/java/com/openshift/restclient/model/build/ISTIBuildStrategy.java b/src/main/java/com/openshift/restclient/model/build/ISTIBuildStrategy.java index 2ac2f001..090208ab 100644 --- a/src/main/java/com/openshift/restclient/model/build/ISTIBuildStrategy.java +++ b/src/main/java/com/openshift/restclient/model/build/ISTIBuildStrategy.java @@ -6,31 +6,28 @@ * * Contributors: Red Hat, Inc. ******************************************************************************/ + package com.openshift.restclient.model.build; import java.util.Map; import com.openshift.restclient.images.DockerImageURI; -/** - * @author Jeff Cantrill - */ @Deprecated public interface ISTIBuildStrategy extends IBuildStrategy { - - /** - * Returns the Builder Image used to execute the build - */ - DockerImageURI getImage(); - - String getScriptsLocation(); - - Map getEnvironmentVariables(); - - boolean incremental(); - - @Deprecated - boolean forceClean(); - - + + /** + * Returns the Builder Image used to execute the build + */ + DockerImageURI getImage(); + + String getScriptsLocation(); + + Map getEnvironmentVariables(); + + boolean incremental(); + + @Deprecated + boolean forceClean(); + } diff --git a/src/main/java/com/openshift/restclient/model/build/ISourceBuildStrategy.java b/src/main/java/com/openshift/restclient/model/build/ISourceBuildStrategy.java index 50861d46..402a672b 100644 --- a/src/main/java/com/openshift/restclient/model/build/ISourceBuildStrategy.java +++ b/src/main/java/com/openshift/restclient/model/build/ISourceBuildStrategy.java @@ -8,6 +8,7 @@ * Contributors: * Red Hat, Inc. - initial API and implementation ******************************************************************************/ + package com.openshift.restclient.model.build; import java.util.Collection; @@ -16,41 +17,42 @@ import com.openshift.restclient.images.DockerImageURI; import com.openshift.restclient.model.IEnvironmentVariable; -/** - * - * @author Jeff Cantrill - * - */ -public interface ISourceBuildStrategy extends IBuildStrategy{ - - /** - * Returns the Builder Image used to execute the build - */ - DockerImageURI getImage(); - void setImage(DockerImageURI image); - - String getFromKind(); - void setFromKind(String kind); - - String getFromNamespace(); - void setFromNamespace(String namespace); - - String getScriptsLocation(); - void setScriptsLocation(String location); - - Map getEnvironmentVariables(); - void setEnvironmentVariables(Map envVars); - - Collection getEnvVars(); - - /** - * Setting using a null collection will early return without - * modification to the strategy - * @param envVars - */ - void setEnvVars(Collection envVars); - - boolean incremental(); - void setIncremental(boolean isIncremental); +public interface ISourceBuildStrategy extends IBuildStrategy { + + /** + * Returns the Builder Image used to execute the build + */ + DockerImageURI getImage(); + + void setImage(DockerImageURI image); + + String getFromKind(); + + void setFromKind(String kind); + + String getFromNamespace(); + + void setFromNamespace(String namespace); + + String getScriptsLocation(); + + void setScriptsLocation(String location); + + Map getEnvironmentVariables(); + + void setEnvironmentVariables(Map envVars); + + Collection getEnvVars(); + + /** + * Setting using a null collection will early return without modification to the + * strategy + * + */ + void setEnvVars(Collection envVars); + + boolean incremental(); + + void setIncremental(boolean isIncremental); } diff --git a/src/main/java/com/openshift/restclient/model/build/IWebhookTrigger.java b/src/main/java/com/openshift/restclient/model/build/IWebhookTrigger.java index e7dc7d78..bb56d743 100644 --- a/src/main/java/com/openshift/restclient/model/build/IWebhookTrigger.java +++ b/src/main/java/com/openshift/restclient/model/build/IWebhookTrigger.java @@ -6,18 +6,17 @@ * * Contributors: Red Hat, Inc. ******************************************************************************/ + package com.openshift.restclient.model.build; -/** - * @author Jeff Cantrill - */ public interface IWebhookTrigger extends IBuildTrigger { - - String getSecret(); - - /** - * Returns the URL to trigger the build for the resource - * @return the URL or empty if the resource is not configured with an IClient - */ - String getWebhookURL(); + + String getSecret(); + + /** + * Returns the URL to trigger the build for the resource + * + * @return the URL or empty if the resource is not configured with an IClient + */ + String getWebhookURL(); } diff --git a/src/main/java/com/openshift/restclient/model/deploy/DeploymentTriggerType.java b/src/main/java/com/openshift/restclient/model/deploy/DeploymentTriggerType.java index 0925437e..ee02c585 100644 --- a/src/main/java/com/openshift/restclient/model/deploy/DeploymentTriggerType.java +++ b/src/main/java/com/openshift/restclient/model/deploy/DeploymentTriggerType.java @@ -8,14 +8,10 @@ * Contributors: * Red Hat, Inc. - initial API and implementation ******************************************************************************/ + package com.openshift.restclient.model.deploy; -/** - * - * @author Jeff Cantrill - * - */ public interface DeploymentTriggerType { - static final String CONFIG_CHANGE = "ConfigChange"; - static final String IMAGE_CHANGE = "ImageChange"; + static final String CONFIG_CHANGE = "ConfigChange"; + static final String IMAGE_CHANGE = "ImageChange"; } diff --git a/src/main/java/com/openshift/restclient/model/deploy/IDeploymentConfigChangeTrigger.java b/src/main/java/com/openshift/restclient/model/deploy/IDeploymentConfigChangeTrigger.java index 2c0749c3..61adb2f9 100644 --- a/src/main/java/com/openshift/restclient/model/deploy/IDeploymentConfigChangeTrigger.java +++ b/src/main/java/com/openshift/restclient/model/deploy/IDeploymentConfigChangeTrigger.java @@ -8,13 +8,9 @@ * Contributors: * Red Hat, Inc. - initial API and implementation ******************************************************************************/ + package com.openshift.restclient.model.deploy; -/** - * - * @author Jeff Cantrill - * - */ public interface IDeploymentConfigChangeTrigger extends IDeploymentTrigger { } diff --git a/src/main/java/com/openshift/restclient/model/deploy/IDeploymentImageChangeTrigger.java b/src/main/java/com/openshift/restclient/model/deploy/IDeploymentImageChangeTrigger.java index 2e865230..9274b700 100644 --- a/src/main/java/com/openshift/restclient/model/deploy/IDeploymentImageChangeTrigger.java +++ b/src/main/java/com/openshift/restclient/model/deploy/IDeploymentImageChangeTrigger.java @@ -8,63 +8,58 @@ * Contributors: * Red Hat, Inc. - initial API and implementation ******************************************************************************/ + package com.openshift.restclient.model.deploy; import java.util.Collection; import com.openshift.restclient.images.DockerImageURI; -/** - * - * @author Jeff Cantrill - * - */ public interface IDeploymentImageChangeTrigger extends IDeploymentTrigger { - /** - * Returns the name of the docker image repo to watch - * @return - */ - DockerImageURI getFrom(); + /** + * Returns the name of the docker image repo to watch + * + */ + DockerImageURI getFrom(); + + /** + * Automatically sets kind to "ImageStreamTag" if kind is empty + * + */ + void setFrom(DockerImageURI fromImage); + + /** + * The namespace of the ImageStreamTag + * + */ + void setNamespace(String namespace); + + /** + * @return The namespace of the ImageStreamTag + * + */ + String getNamespace(); + + void setKind(String kind); + + String getKind(); + + boolean isAutomatic(); - /** - * Automatically sets kind to "ImageStreamTag" if kind is empty - * @param fromImage - */ - void setFrom(DockerImageURI fromImage); - - /** - * The namespace of the ImageStreamTag - * @param namespace - */ - void setNamespace(String namespace); + void setAutomatic(boolean auto); - /** - * @return The namespace of the ImageStreamTag - * - */ - String getNamespace(); + /** + * The container names for this trigger + * + */ + Collection getContainerNames(); - void setKind(String kind); - - String getKind(); - - boolean isAutomatic(); - - void setAutomatic(boolean auto); - - /** - * The container names for this trigger - * @return - */ - Collection getContainerNames(); - - void setContainerNames(Collection names); + void setContainerNames(Collection names); - /** - * Convenience method for setting - * a single container name - * @param names - */ - void setContainerName(String names); + /** + * Convenience method for setting a single container name + * + */ + void setContainerName(String names); } diff --git a/src/main/java/com/openshift/restclient/model/deploy/IDeploymentRequest.java b/src/main/java/com/openshift/restclient/model/deploy/IDeploymentRequest.java new file mode 100644 index 00000000..b9a59205 --- /dev/null +++ b/src/main/java/com/openshift/restclient/model/deploy/IDeploymentRequest.java @@ -0,0 +1,57 @@ +/******************************************************************************* + * Copyright (c) 2016 Red Hat, Inc. + * Distributed under license by Red Hat, Inc. All rights reserved. + * This program is made available under the terms of the + * Eclipse Public License v1.0 which accompanies this distribution, + * and is available at http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Red Hat, Inc. - initial API and implementation + ******************************************************************************/ + +package com.openshift.restclient.model.deploy; + +import com.openshift.restclient.api.models.INameSetable; +import com.openshift.restclient.api.models.ITypeMeta; + +/** + * Resource payload for triggering a deployment via the instantiate endpoint + * @author gmontero + * + */ +public interface IDeploymentRequest extends ITypeMeta, INameSetable { + + /** + * If set the true latest will update the deployment config with the latest state from all triggers. + */ + void setLatest(boolean latest); + + /** + * Returns the current setting of the latest flag. + */ + boolean isLatest(); + + /** + * If set to try force will try to force a new deployment to run. If the deployment config is paused, + * then setting this to true will return an Invalid error. + */ + void setForce(boolean force); + + /** + * Returns the latest setting of the force flag. + */ + boolean isForce(); + + /** + * The name of the deployment config; note, the name in the corresponding oapi type + * is not in the k8s metadata object + * @param name of the deployment config + */ + void setName(String name); + + /** + * Returns the name of the deployment config seeded into the deployment request + */ + String getName(); + +} diff --git a/src/main/java/com/openshift/restclient/model/deploy/IDeploymentTrigger.java b/src/main/java/com/openshift/restclient/model/deploy/IDeploymentTrigger.java index 3417c3d2..4996bed3 100644 --- a/src/main/java/com/openshift/restclient/model/deploy/IDeploymentTrigger.java +++ b/src/main/java/com/openshift/restclient/model/deploy/IDeploymentTrigger.java @@ -8,18 +8,14 @@ * Contributors: * Red Hat, Inc. - initial API and implementation ******************************************************************************/ + package com.openshift.restclient.model.deploy; -/** - * - * @author Jeff Cantrill - * - */ public interface IDeploymentTrigger { - - /** - * - * @return {@link DeploymentTriggerType} - */ - String getType(); + + /** + * + * @return {@link DeploymentTriggerType} + */ + String getType(); } diff --git a/src/main/java/com/openshift/restclient/model/image/IImageStreamImport.java b/src/main/java/com/openshift/restclient/model/image/IImageStreamImport.java index 757b4596..4dedd2bf 100644 --- a/src/main/java/com/openshift/restclient/model/image/IImageStreamImport.java +++ b/src/main/java/com/openshift/restclient/model/image/IImageStreamImport.java @@ -8,6 +8,7 @@ * Contributors: * Red Hat, Inc. - initial API and implementation ******************************************************************************/ + package com.openshift.restclient.model.image; import java.util.Collection; @@ -16,57 +17,52 @@ import com.openshift.restclient.model.IResource; import com.openshift.restclient.model.IStatus; -/** - * - * @author jeff.cantrill - * - */ public interface IImageStreamImport extends IResource { - /** - * Set to true to import tags for the imagestream; false to just retrieve - * @param importTags - */ - void setImport(boolean importTags); - - /** - * Are the tags to be imported for the imagestream - * @return true if import; false otherwise - */ - boolean isImport(); + /** + * Set to true to import tags for the imagestream; false to just retrieve + * + */ + void setImport(boolean importTags); + + /** + * Are the tags to be imported for the imagestream + * + * @return true if import; false otherwise + */ + boolean isImport(); + + /** + * Add image info those being imorted + * + * @param fromKind + * The indirection of where to find the image. Typically is + * DockerImage, ImageStreamTag + */ + void addImage(String fromKind, DockerImageURI imageUri); - /** - * Add image info those being imorted - * @param fromKind The indirection of where to find the image. - * Typically is DockerImage, ImageStreamTag - * @param uriWithoutTag - */ - void addImage(String fromKind, DockerImageURI imageUri); + /** + * The status of the image retrieval + * + */ + Collection getImageStatus(); - /** - * The status of the image retrieval - * @return - */ - Collection getImageStatus(); - - /** - * Get the raw json docker metadata for - * the given uir. Tries to match uri without tag - * to the beginning of image.dockerImageReference - * - * @param uri - * @return json string or null if not matched. - */ - @Deprecated - String getImageJsonFor(DockerImageURI uri); + /** + * Get the raw json docker metadata for the given uir. Tries to match uri + * without tag to the beginning of image.dockerImageReference + * + * @return json string or null if not matched. + */ + @Deprecated + String getImageJsonFor(DockerImageURI uri); - /** - * Get the raw json docker metadata for - * the given tag. Assumes the result was - * success - * - * @param tag a tag for the image - * @return json string or null if not matched. - */ - String getImageJsonFor(String tag); + /** + * Get the raw json docker metadata for the given tag. Assumes the result was + * success + * + * @param tag + * a tag for the image + * @return json string or null if not matched. + */ + String getImageJsonFor(String tag); } diff --git a/src/main/java/com/openshift/restclient/model/image/ITagReference.java b/src/main/java/com/openshift/restclient/model/image/ITagReference.java index 41490743..c6135451 100644 --- a/src/main/java/com/openshift/restclient/model/image/ITagReference.java +++ b/src/main/java/com/openshift/restclient/model/image/ITagReference.java @@ -8,25 +8,26 @@ * Contributors: * Red Hat, Inc. - initial API and implementation ******************************************************************************/ + package com.openshift.restclient.model.image; import com.openshift.restclient.model.Annotatable; import com.openshift.restclient.model.IObjectReference; public interface ITagReference extends Annotatable { - - /** - * Returns the identifier for this reference - * @return - */ - String getName(); - - /** - * if specified, a reference to another image that this tag should point to. - * Valid values are ImageStreamTag, ImageStreamImage, and DockerImage. - * @return - */ - IObjectReference getFrom(); - - String toJson(); + + /** + * Returns the identifier for this reference + * + */ + String getName(); + + /** + * if specified, a reference to another image that this tag should point to. + * Valid values are ImageStreamTag, ImageStreamImage, and DockerImage. + * + */ + IObjectReference getFrom(); + + String toJson(); } diff --git a/src/main/java/com/openshift/restclient/model/kubeclient/ICluster.java b/src/main/java/com/openshift/restclient/model/kubeclient/ICluster.java index 2ea4c9e8..c63c3933 100644 --- a/src/main/java/com/openshift/restclient/model/kubeclient/ICluster.java +++ b/src/main/java/com/openshift/restclient/model/kubeclient/ICluster.java @@ -8,17 +8,19 @@ * Contributors: * Red Hat, Inc. - initial API and implementation ******************************************************************************/ + package com.openshift.restclient.model.kubeclient; public interface ICluster { - - String getName(); - /** - * The server url - * @return - */ - String getServer(); - - boolean isInsecureSkipTLSVerify(); - + + String getName(); + + /** + * The server url + * + */ + String getServer(); + + boolean isInsecureSkipTLSVerify(); + } \ No newline at end of file diff --git a/src/main/java/com/openshift/restclient/model/kubeclient/IContext.java b/src/main/java/com/openshift/restclient/model/kubeclient/IContext.java index 70676025..a4b031cb 100644 --- a/src/main/java/com/openshift/restclient/model/kubeclient/IContext.java +++ b/src/main/java/com/openshift/restclient/model/kubeclient/IContext.java @@ -8,34 +8,34 @@ * Contributors: * Red Hat, Inc. - initial API and implementation ******************************************************************************/ + package com.openshift.restclient.model.kubeclient; public interface IContext { - - /** - * The name of the cluster - * @return - */ - String getCluster(); - /** - * Returns the user info in the form of: - * / - * @return the user info - */ - String getUser(); - - /** - * default namespace to use - * on unspecified requests - * @return - */ - String getNamespace(); + /** + * The name of the cluster + * + */ + String getCluster(); + + /** + * Returns the user info in the form of: USERNAME/URL + * + * @return the user info + */ + String getUser(); + + /** + * default namespace to use on unspecified requests + * + */ + String getNamespace(); + + /** + * The name of the context + * + */ + String getName(); - /** - * The name of the context - * @return - */ - String getName(); - } \ No newline at end of file diff --git a/src/main/java/com/openshift/restclient/model/kubeclient/IKubeClientConfig.java b/src/main/java/com/openshift/restclient/model/kubeclient/IKubeClientConfig.java index 9dd94c91..8d5c4463 100644 --- a/src/main/java/com/openshift/restclient/model/kubeclient/IKubeClientConfig.java +++ b/src/main/java/com/openshift/restclient/model/kubeclient/IKubeClientConfig.java @@ -8,33 +8,33 @@ * Contributors: * Red Hat, Inc. - initial API and implementation ******************************************************************************/ + package com.openshift.restclient.model.kubeclient; import java.util.Collection; /** - * Configuration type for connecting to a Kubernetes client config - * ref: client/unversioned/clientcmd/api/types.go + * Configuration type for connecting to a Kubernetes client config ref: + * client/unversioned/clientcmd/api/types.go * - * @author jeff.cantrill * */ public interface IKubeClientConfig { - - /** - * A map of userinfo to cluster info where the key - * is // - * @return - */ - Collection getClusters(); - Collection getContexts(); - - /** - * The name of the current cluster context - * @return - */ - String getCurrentContext(); - - Collection getUsers(); + /** + * A map of userinfo to cluster info where the key is + * NAMESPACE/URL/USERNAME + * + */ + Collection getClusters(); + + Collection getContexts(); + + /** + * The name of the current cluster context + * + */ + String getCurrentContext(); + + Collection getUsers(); } diff --git a/src/main/java/com/openshift/restclient/model/kubeclient/IUser.java b/src/main/java/com/openshift/restclient/model/kubeclient/IUser.java index bf72914e..07230acc 100644 --- a/src/main/java/com/openshift/restclient/model/kubeclient/IUser.java +++ b/src/main/java/com/openshift/restclient/model/kubeclient/IUser.java @@ -8,11 +8,12 @@ * Contributors: * Red Hat, Inc. - initial API and implementation ******************************************************************************/ + package com.openshift.restclient.model.kubeclient; public interface IUser { - - String getToken(); - - String getName(); + + String getToken(); + + String getName(); } \ No newline at end of file diff --git a/src/main/java/com/openshift/restclient/model/kubeclient/KubeClientConfigSerializer.java b/src/main/java/com/openshift/restclient/model/kubeclient/KubeClientConfigSerializer.java index 0a5aa8a9..5068c2bf 100644 --- a/src/main/java/com/openshift/restclient/model/kubeclient/KubeClientConfigSerializer.java +++ b/src/main/java/com/openshift/restclient/model/kubeclient/KubeClientConfigSerializer.java @@ -8,9 +8,9 @@ * Contributors: * Red Hat, Inc. - initial API and implementation ******************************************************************************/ + package com.openshift.restclient.model.kubeclient; -import java.beans.IntrospectionException; import java.io.Reader; import org.yaml.snakeyaml.Yaml; @@ -22,27 +22,22 @@ import com.openshift.internal.restclient.model.kubeclient.KubeClientConfigConstructor; import com.openshift.restclient.utils.BeanUtils; -/** - * - * @author jeff.cantrill - * - */ public class KubeClientConfigSerializer { - public IKubeClientConfig loadKubeClientConfig(Reader reader) { - Representer representer = new Representer(); - Yaml parser = new Yaml(new KubeClientConfigConstructor(new YamlPropertyUtils()), representer); - representer.getPropertyUtils().setSkipMissingProperties(true); - return parser.loadAs(reader, KubeClientConfig.class); - } - - private static class YamlPropertyUtils extends PropertyUtils { - @Override - public Property getProperty(Class type, String name) throws IntrospectionException { - if (name.indexOf('-') > -1) { - name = BeanUtils.toCamelCase(name, "-"); - } - return super.getProperty(type, name); - } - } + public IKubeClientConfig loadKubeClientConfig(Reader reader) { + Representer representer = new Representer(); + Yaml parser = new Yaml(new KubeClientConfigConstructor(new YamlPropertyUtils()), representer); + representer.getPropertyUtils().setSkipMissingProperties(true); + return parser.loadAs(reader, KubeClientConfig.class); + } + + private static class YamlPropertyUtils extends PropertyUtils { + @Override + public Property getProperty(Class type, String name) { + if (name.indexOf('-') > -1) { + name = BeanUtils.toCamelCase(name, "-"); + } + return super.getProperty(type, name); + } + } } diff --git a/src/main/java/com/openshift/restclient/model/oauth/IOAuthAccessToken.java b/src/main/java/com/openshift/restclient/model/oauth/IOAuthAccessToken.java index a099884e..a3f5de79 100644 --- a/src/main/java/com/openshift/restclient/model/oauth/IOAuthAccessToken.java +++ b/src/main/java/com/openshift/restclient/model/oauth/IOAuthAccessToken.java @@ -8,13 +8,11 @@ * Contributors: * Red Hat, Inc. - initial API and implementation ******************************************************************************/ + package com.openshift.restclient.model.oauth; import com.openshift.restclient.model.IResource; -/** - * @author Jeff Cantrill - */ public interface IOAuthAccessToken extends IResource { } diff --git a/src/main/java/com/openshift/restclient/model/oauth/IOAuthAuthorizeToken.java b/src/main/java/com/openshift/restclient/model/oauth/IOAuthAuthorizeToken.java index 79a5d339..b9407a8f 100644 --- a/src/main/java/com/openshift/restclient/model/oauth/IOAuthAuthorizeToken.java +++ b/src/main/java/com/openshift/restclient/model/oauth/IOAuthAuthorizeToken.java @@ -8,13 +8,11 @@ * Contributors: * Red Hat, Inc. - initial API and implementation ******************************************************************************/ + package com.openshift.restclient.model.oauth; import com.openshift.restclient.model.IResource; -/** - * @author Jeff Cantrill - */ public interface IOAuthAuthorizeToken extends IResource { } diff --git a/src/main/java/com/openshift/restclient/model/oauth/IOAuthClient.java b/src/main/java/com/openshift/restclient/model/oauth/IOAuthClient.java index 8877943e..79ee17ea 100644 --- a/src/main/java/com/openshift/restclient/model/oauth/IOAuthClient.java +++ b/src/main/java/com/openshift/restclient/model/oauth/IOAuthClient.java @@ -8,13 +8,11 @@ * Contributors: * Red Hat, Inc. - initial API and implementation ******************************************************************************/ + package com.openshift.restclient.model.oauth; import com.openshift.restclient.model.IResource; -/** - * @author Jeff Cantrill - */ public interface IOAuthClient extends IResource { } diff --git a/src/main/java/com/openshift/restclient/model/oauth/IOAuthClientAuthorization.java b/src/main/java/com/openshift/restclient/model/oauth/IOAuthClientAuthorization.java index 1952b4ec..ae457e18 100644 --- a/src/main/java/com/openshift/restclient/model/oauth/IOAuthClientAuthorization.java +++ b/src/main/java/com/openshift/restclient/model/oauth/IOAuthClientAuthorization.java @@ -8,13 +8,11 @@ * Contributors: * Red Hat, Inc. - initial API and implementation ******************************************************************************/ + package com.openshift.restclient.model.oauth; import com.openshift.restclient.model.IResource; -/** - * @author Jeff Cantrill - */ public interface IOAuthClientAuthorization extends IResource { } diff --git a/src/main/java/com/openshift/restclient/model/probe/IProbe.java b/src/main/java/com/openshift/restclient/model/probe/IProbe.java new file mode 100644 index 00000000..a42473e6 --- /dev/null +++ b/src/main/java/com/openshift/restclient/model/probe/IProbe.java @@ -0,0 +1,38 @@ +/******************************************************************************* + * Copyright (c) 2017 Red Hat, Inc. + * Distributed under license by Red Hat, Inc. All rights reserved. + * This program is made available under the terms of the + * Eclipse Public License v1.0 which accompanies this distribution, + * and is available at http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Red Hat, Inc. - initial API and implementation + ******************************************************************************/ + +package com.openshift.restclient.model.probe; + +/** + * @author Andre Dietisheim + */ +public interface IProbe { + + void setInitialDelaySeconds(int delay); + + int getInitialDelaySeconds(); + + void setPeriodSeconds(int period); + + int getPeriodSeconds(); + + void setSuccessThreshold(int threshold); + + int getSuccessThreshold(); + + void setFailureThreshold(int failureThreshold); + + int getFailureThreshold(); + + void setTimeoutSeconds(int timeout); + + int getTimeoutSeconds(); +} diff --git a/src/main/java/com/openshift/restclient/model/project/IProjectRequest.java b/src/main/java/com/openshift/restclient/model/project/IProjectRequest.java index 68bae29e..0dc794ee 100644 --- a/src/main/java/com/openshift/restclient/model/project/IProjectRequest.java +++ b/src/main/java/com/openshift/restclient/model/project/IProjectRequest.java @@ -8,21 +8,19 @@ * Contributors: * Red Hat, Inc. - initial API and implementation ******************************************************************************/ + package com.openshift.restclient.model.project; import com.openshift.restclient.model.IResource; -/** - * @author Jeff Cantrill - */ public interface IProjectRequest extends IResource { - - void setDisplayName(String name); - - String getDisplayName(); - - void setDescription(String name); - - String getDescription(); + + void setDisplayName(String name); + + String getDisplayName(); + + void setDescription(String name); + + String getDescription(); } diff --git a/src/main/java/com/openshift/restclient/model/route/IRoute.java b/src/main/java/com/openshift/restclient/model/route/IRoute.java index e3963309..34d499c6 100644 --- a/src/main/java/com/openshift/restclient/model/route/IRoute.java +++ b/src/main/java/com/openshift/restclient/model/route/IRoute.java @@ -6,6 +6,7 @@ * * Contributors: Red Hat, Inc. ******************************************************************************/ + package com.openshift.restclient.model.route; import com.openshift.restclient.model.IResource; @@ -13,78 +14,88 @@ /** * OpenShift route to Service * - * @author Jeff Cantrill */ public interface IRoute extends IResource { - /** - * Retrieves the externally available hostname that can be used to access - * service. - * - * @return Route hostname. - */ - String getHost(); + /** + * Retrieves the externally available hostname that can be used to access + * service. + * + * @return Route hostname. + */ + String getHost(); + + /** + * Sets the externally available hostname that can be used to access service. + * + * @param host + * hostname to use + */ + void setHost(String host); + + /** + * Retrieves the path that the router watches for, to route traffic for to the + * service. + * + * @return Route path. + */ + String getPath(); + + /** + * Sets the path that the router watches for, to route traffic for to the + * service. + * + * @param path + * route path + */ + void setPath(String path); + + /** + * Retrieves the name of the service this route leads to. + * + * @return Name of the service for this route. + */ + String getServiceName(); - /** - * Sets the externally available hostname that can be used to access - * service. - * - * @param host - * hostname to use - */ - void setHost(String host); + /** + * Sets the name of the service this route should lead to. + * + * @param serviceName + * Name of the service this route should lead to. + */ + void setServiceName(String serviceName); - /** - * Retrieves the path that the router watches for, to route traffic for to - * the service. - * - * @return Route path. - */ - String getPath(); + /** + * Retrieves the TLS configuration of this route. + * + * @return TLS configuration or null if there is not one + */ + ITLSConfig getTLSConfig(); - /** - * Sets the path that the router watches for, to route traffic for to the - * service. - * - * @param path - * route path - */ - void setPath(String path); + /** + * Create a tls config if one is not defined or return the existing one + * + */ + ITLSConfig createTLSConfig(); - /** - * Retrieves the name of the service this route leads to. - * - * @return Name of the service for this route. - */ - String getServiceName(); + /** + * Return a URL representation of this route. Assumes the protocol is https if + * the route includes TLS Config + * + * @return java.lang.String The route url + */ + String getURL(); - /** - * Sets the name of the service this route should lead to. - * - * @param serviceName - * Name of the service this route should lead to. - */ - void setServiceName(String serviceName); + /** + * Retrieves the target port of this route. + * + * @return target port or null if there is not one + */ + ITargetPort getPort(); - /** - * Retrieves the TLS configuration of this route. - * - * @return TLS configuration or null if there is not one - */ - ITLSConfig getTLSConfig(); - - /** - * Create a tls config if one is not defined or return - * the existing one - * @return - */ - ITLSConfig createTLSConfig(); - - - /** - * Return a URL representation of this route. Assumes - * the protocol is https if the route includes TLS Config - * @return java.lang.String The route url - */ - String getURL(); + /** + * Create a target port if one is not defined or return the existing one + * + */ + ITargetPort createPort(); } diff --git a/src/main/java/com/openshift/restclient/model/route/ITLSConfig.java b/src/main/java/com/openshift/restclient/model/route/ITLSConfig.java index a9312bd1..e99f31f8 100644 --- a/src/main/java/com/openshift/restclient/model/route/ITLSConfig.java +++ b/src/main/java/com/openshift/restclient/model/route/ITLSConfig.java @@ -6,96 +6,110 @@ * * Contributors: Red Hat, Inc. ******************************************************************************/ + package com.openshift.restclient.model.route; /** * TLS configuration for routes. * - * @author Jeff Cantrill */ public interface ITLSConfig { - - /** - * Returns the termination type. If termination type is not set, - * any termination config will be ignored. - * - * @return Termination type. - */ - String getTerminationType(); - /** - * Sets the termination type to this config. - * Termination indicates termination type. If termination type is not set, - * any termination config will be ignored. - * - * @param type - * termination type - */ - void setTerminationType(String type); + /** + * Returns the termination type. If termination type is not set, any termination + * config will be ignored. + * + * @return Termination type. + */ + String getTerminationType(); + + /** + * Sets the termination type to this config. Termination indicates termination + * type. If termination type is not set, any termination config will be ignored. + * + * @param type + * termination type + */ + void setTerminationType(String type); + + /** + * Retrieves the certificate contents. + * + * @return Certificate contents. + */ + String getCertificate(); + + /** + * Sets the certificate contents. + * + * @param certificate + * certificate contents + */ + void setCertificate(String certificate); - /** - * Retrieves the certificate contents. - * - * @return Certificate contents. - */ - String getCertificate(); + /** + * Retrieves the key file contents. + * + * @return Key file contents. + */ + String getKey(); - /** - * Sets the certificate contents. - * - * @param certificate - * certificate contents - */ - void setCertificate(String certificate); + /** + * Sets the key file contents. + * + * @param key + * key file contents + */ + void setKey(String key); - /** - * Retrieves the key file contents. - * - * @return Key file contents. - */ - String getKey(); + /** + * Retrieves the certification authority certificate contents. + * + * @return CA certificate contents. + */ + String getCACertificate(); - /** - * Sets the key file contents. - * - * @param key - * key file contents - */ - void setKey(String key); + /** + * Sets the certification authority certificate contents. + * + * @param caCertificate + * CA certificate contents + */ + void setCACertificate(String caCertificate); - /** - * Retrieves the certification authority certificate contents. - * - * @return CA certificate contents. - */ - String getCACertificate(); + /** + * DestinationCACertificate provides the contents of the CA certificate of the + * final destination. When using reencrypt termination this file should be + * provided in order to have routers use it for health checks on the secure + * connection. + * + * @return Contents of CA certificate of the final destination. + */ + String getDestinationCertificate(); - /** - * Sets the certification authority certificate contents. - * - * @param caCertificate - * CA certificate contents - */ - void setCACertificate(String caCertificate); + /** + * DestinationCACertificate provides the contents of the CA certificate of the + * final destination. When using reencrypt termination this file should be + * provided in order to have routers use it for health checks on the secure + * connection. + * + * @param destinationCertificate + * contents of CA certificate of the final destination + */ + void setDestinationCertificate(String destinationCertificate); - /** - * DestinationCACertificate provides the contents of the CA certificate of - * the final destination. When using reencrypt termination this file should - * be provided in order to have routers use it for health checks on the - * secure connection. - * - * @return Contents of CA certificate of the final destination. - */ - String getDestinationCertificate(); + /** + * Retrieves InsecureEdgeTerminationPolicy + * + * @return InsecureEdgeTerminationPolicy + */ + String getInsecureEdgeTerminationPolicy(); - /** - * DestinationCACertificate provides the contents of the CA certificate of - * the final destination. When using reencrypt termination this file should - * be provided in order to have routers use it for health checks on the - * secure connection. - * - * @param destinationCertificate - * contents of CA certificate of the final destination - */ - void setDestinationCertificate(String destinationCertificate); + /** + * Sets insecureEdgeTerminationPolicy + * + * @param insecureEdgeTerminationPolicy + * insecureEdgeTerminationPolicy + */ + void setInsecureEdgeTerminationPolicy(String insecureEdgeTerminationPolicy); } diff --git a/src/main/java/com/openshift/restclient/model/route/ITargetPort.java b/src/main/java/com/openshift/restclient/model/route/ITargetPort.java new file mode 100644 index 00000000..7b625a92 --- /dev/null +++ b/src/main/java/com/openshift/restclient/model/route/ITargetPort.java @@ -0,0 +1,49 @@ +/******************************************************************************* + * Copyright (c) 2016 Red Hat, Inc. Distributed under license by Red Hat, Inc. + * All rights reserved. This program is made available under the terms of the + * Eclipse Public License v1.0 which accompanies this distribution, and is + * available at http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: Red Hat, Inc. + ******************************************************************************/ + +package com.openshift.restclient.model.route; + +/** + * Target port for routes. If both attributes are present, then name is + * preferred. + * + * @author Jeff Maury + */ +public interface ITargetPort { + + /** + * Returns the target port name. + * + * @return target port name. + */ + String getTargetPortName(); + + /** + * Sets the target port name. + * + * @param portName + * target port name + */ + void setTargetPortName(String portName); + + /** + * Returns the target port value. + * + * @return target port value. + */ + Integer getTargetPort(); + + /** + * Sets the target port value. + * + * @param portName + * target port value + */ + void setTargetPort(Integer port); +} diff --git a/src/main/java/com/openshift/restclient/model/route/TLSTerminationType.java b/src/main/java/com/openshift/restclient/model/route/TLSTerminationType.java index fa089392..fd83f555 100644 --- a/src/main/java/com/openshift/restclient/model/route/TLSTerminationType.java +++ b/src/main/java/com/openshift/restclient/model/route/TLSTerminationType.java @@ -8,15 +8,11 @@ * Contributors: * Red Hat, Inc. - initial API and implementation ******************************************************************************/ + package com.openshift.restclient.model.route; -/** - * - * @author Jeff Cantrill - * - */ public interface TLSTerminationType { - static final String EDGE = "edge"; - static final String PASSTHROUGH = "passthrough"; - static final String REENCRYPT = "reencrypt"; + static final String EDGE = "edge"; + static final String PASSTHROUGH = "passthrough"; + static final String REENCRYPT = "reencrypt"; } \ No newline at end of file diff --git a/src/main/java/com/openshift/restclient/model/secret/ISecret.java b/src/main/java/com/openshift/restclient/model/secret/ISecret.java index 4f8331dc..93bf457f 100644 --- a/src/main/java/com/openshift/restclient/model/secret/ISecret.java +++ b/src/main/java/com/openshift/restclient/model/secret/ISecret.java @@ -6,6 +6,7 @@ * * Contributors: Red Hat, Inc. ******************************************************************************/ + package com.openshift.restclient.model.secret; import java.io.InputStream; @@ -13,42 +14,44 @@ import com.openshift.restclient.model.IResource; /** - * Kubernetes Secret object to inject/mount sensitive data into containers + * Kubernetes Secret object to inject/mount sensitive data into containers * * @author Jiri Pechanec */ public interface ISecret extends IResource { - /** - * Sets the container port exposed by the image - * @param key - the name under which the data are mount in container - * @param data - */ - void addData(String key, InputStream data); - - /** - * Sets the container port exposed by the image - * @param key - the name under which the data are mount in container - * @param data - */ - void addData(String key, byte[] data); - - /** - * Get the data stored under the key - * @param key - * @return byte representation of the stored data - */ - byte[] getData(String key); - - /** - * Sets the type of Secrete - default Opaque - * @param type - */ - void setType(String type); - - /** - * Returns the type of Secrete - default Opaque - * return - */ - String getType(); + /** + * Sets the container port exposed by the image + * + * @param key + * - the name under which the data are mount in container + */ + void addData(String key, InputStream data); + + /** + * Sets the container port exposed by the image + * + * @param key + * - the name under which the data are mount in container + */ + void addData(String key, byte[] data); + + /** + * Get the data stored under the key + * + * @param key + * @return byte representation of the stored data + */ + byte[] getData(String key); + + /** + * Sets the type of Secrete - default Opaque + * + */ + void setType(String type); + + /** + * Returns the type of Secrete - default Opaque return + */ + String getType(); } diff --git a/src/main/java/com/openshift/restclient/model/serviceaccount/IServiceAccount.java b/src/main/java/com/openshift/restclient/model/serviceaccount/IServiceAccount.java index e1358717..69a18088 100644 --- a/src/main/java/com/openshift/restclient/model/serviceaccount/IServiceAccount.java +++ b/src/main/java/com/openshift/restclient/model/serviceaccount/IServiceAccount.java @@ -1,36 +1,40 @@ package com.openshift.restclient.model.serviceaccount; -import com.openshift.restclient.model.IResource; - import java.util.Collection; +import com.openshift.restclient.model.IResource; + /** * @author David Simansky | dsimansk@redhat.com */ public interface IServiceAccount extends IResource { - /** - * Get the collection of all secrets - * @return - */ - Collection getSecrets(); - - /** - * Add new secret name - * @param secret - secret name - */ - void addSecret(String secret); - - /** - * Get the collection of all imagePullSecrets - * @return - */ - Collection getImagePullSecrets(); - - /** - * Add new imagePullSecret name - * @param imagePullSecret - imagePullSecretName - */ - void addImagePullSecret(String imagePullSecret); + /** + * Get the collection of all secrets + * + */ + Collection getSecrets(); + + /** + * Add new secret name + * + * @param secret + * - secret name + */ + void addSecret(String secret); + + /** + * Get the collection of all imagePullSecrets + * + */ + Collection getImagePullSecrets(); + + /** + * Add new imagePullSecret name + * + * @param imagePullSecret + * - imagePullSecretName + */ + void addImagePullSecret(String imagePullSecret); } diff --git a/src/main/java/com/openshift/restclient/model/template/IParameter.java b/src/main/java/com/openshift/restclient/model/template/IParameter.java index b7055c02..5bedaac3 100644 --- a/src/main/java/com/openshift/restclient/model/template/IParameter.java +++ b/src/main/java/com/openshift/restclient/model/template/IParameter.java @@ -6,59 +6,57 @@ * * Contributors: Red Hat, Inc. ******************************************************************************/ + package com.openshift.restclient.model.template; /** * A parameter for a template * - * @author Jeff Cantrill */ public interface IParameter extends Cloneable { - - /** - * Returns the name of the parameter that is substituted - * in the template - * @return - */ - String getName(); - - /** - * Returns the description - * @return - */ - String getDescription(); - - /** - * Returns the value to use - * @return - */ - String getValue(); - - /** - * Sets the value to use - * @param value - */ - void setValue(String value); - - /** - * Returns the generator name which will use the value - * from 'getFrom' if set - * @return - */ - String getGeneratorName(); - - /** - * Returns the input to the generator - * @return - */ - String getFrom(); - - /** - * Returns true if parameter is required; false otherwise - * @return - */ - boolean isRequired(); - - IParameter clone(); - + + /** + * Returns the name of the parameter that is substituted in the template + * + */ + String getName(); + + /** + * Returns the description + * + */ + String getDescription(); + + /** + * Returns the value to use + * + */ + String getValue(); + + /** + * Sets the value to use + * + */ + void setValue(String value); + + /** + * Returns the generator name which will use the value from 'getFrom' if set + * + */ + String getGeneratorName(); + + /** + * Returns the input to the generator + * + */ + String getFrom(); + + /** + * Returns true if parameter is required; false otherwise + * + */ + boolean isRequired(); + + IParameter clone(); + } diff --git a/src/main/java/com/openshift/restclient/model/template/ITemplate.java b/src/main/java/com/openshift/restclient/model/template/ITemplate.java index 1fbfeee8..e0537f4b 100644 --- a/src/main/java/com/openshift/restclient/model/template/ITemplate.java +++ b/src/main/java/com/openshift/restclient/model/template/ITemplate.java @@ -6,6 +6,7 @@ * * Contributors: Red Hat, Inc. ******************************************************************************/ + package com.openshift.restclient.model.template; import java.util.Collection; @@ -16,63 +17,53 @@ /** * Representation of a set of pre-configured parameterized set of resources * - * @author Jeff Cantrill */ public interface ITemplate extends IResource { - - /** - * Retrieves the list of resources this template - * creates - * @return - */ - Collection getItems(); - - /** - * Returns a map of parameter names to parameters. - * @return - */ - Map getParameters(); - - /** - * Update the template's parameter values, with the values from the - * collection if a parameter with the same name is found - * - * @param parameters - */ - void updateParameterValues(Collection parameters); - - - /** - * Update a parameter if it exists - * @param key - * @param value - */ - void updateParameter(String key, String value); - - /** - * Retrieves the labels that are applied to the objects of the - * template when it is processed. - * - * @return Unmodifiable map of the item labels - */ - Map getObjectLabels(); - - /** - * Add or update a label that is applied to the objects of the - * template when it is processed - * - * @param key - * @param value - */ - void addObjectLabel(String key, String value); - /** - * Returns true if the given resource contains the given text - * in name or tags. - * - * @param filterText - * @param template - * @return - */ - public boolean isMatching(final String filterText); + /** + * Retrieves the list of resources this template creates + * + */ + Collection getObjects(); + + /** + * Returns a map of parameter names to parameters. + * + */ + Map getParameters(); + + /** + * Update the template's parameter values, with the values from the collection + * if a parameter with the same name is found + * + */ + void updateParameterValues(Collection parameters); + + /** + * Update a parameter if it exists + * + */ + void updateParameter(String key, String value); + + /** + * Retrieves the labels that are applied to the objects of the template when it + * is processed. + * + * @return Unmodifiable map of the item labels + */ + Map getObjectLabels(); + + /** + * Add or update a label that is applied to the objects of the template when it + * is processed + * + */ + void addObjectLabel(String key, String value); + + /** + * Returns true if the given resource contains the given text in + * name or tags. + * + */ + public boolean isMatching(final String filterText); } diff --git a/src/main/java/com/openshift/restclient/model/user/IGroup.java b/src/main/java/com/openshift/restclient/model/user/IGroup.java new file mode 100644 index 00000000..93dbf9a7 --- /dev/null +++ b/src/main/java/com/openshift/restclient/model/user/IGroup.java @@ -0,0 +1,36 @@ +/******************************************************************************* + * Copyright (c) 2018 Red Hat, Inc. + * + * Distributed under license by Red Hat, Inc. All rights reserved. + * This program is made available under the terms of the + * Eclipse Public License v1.0 which accompanies this distribution, + * and is available at http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Red Hat, Inc. - initial API and implementation + * Roland T. Lichti - implementation of user.openshift.io/v1/groups + ******************************************************************************/ + +package com.openshift.restclient.model.user; + +import java.util.Set; + +import com.openshift.restclient.model.IResource; + +/** + * The group definition within OpenShift. + */ +public interface IGroup extends IResource { + + /** + * + * @return the group uid as specified in the metadata + */ + String getUID(); + + /** + * + * @return the users of this group + */ + Set getUsers(); +} diff --git a/src/main/java/com/openshift/restclient/model/user/IIdentity.java b/src/main/java/com/openshift/restclient/model/user/IIdentity.java new file mode 100644 index 00000000..378daa47 --- /dev/null +++ b/src/main/java/com/openshift/restclient/model/user/IIdentity.java @@ -0,0 +1,55 @@ +/******************************************************************************* + * Copyright (c) 2018 Red Hat, Inc. + * + * Distributed under license by Red Hat, Inc. All rights reserved. + * This program is made available under the terms of the + * Eclipse Public License v1.0 which accompanies this distribution, + * and is available at http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Red Hat, Inc. - initial API and implementation + * Roland T. Lichti - implementation of user.openshift.io/v1/identities + ******************************************************************************/ + +package com.openshift.restclient.model.user; + +import java.util.Map; + +import com.openshift.restclient.model.IObjectReference; +import com.openshift.restclient.model.IResource; + +/** + * The identity as specified by the identity provider. + */ +public interface IIdentity extends IResource { + + /** + * + * @return the username as specified by the idententity provider. + */ + String getUserName(); + + /** + * + * @return the identity uid as specified in the metadata + */ + String getUID(); + + /** + * + * @return the name of the identity provider + */ + String getProviderName(); + + /** + * + * @return a map of the identity provider specific data. + */ + Map getExtra(); + + /** + * + * @return A resource link to the user. + */ + IObjectReference getUser(); +} diff --git a/src/main/java/com/openshift/restclient/model/user/IUser.java b/src/main/java/com/openshift/restclient/model/user/IUser.java index 1bf0df52..a78434c8 100644 --- a/src/main/java/com/openshift/restclient/model/user/IUser.java +++ b/src/main/java/com/openshift/restclient/model/user/IUser.java @@ -8,19 +8,36 @@ * Contributors: * Red Hat, Inc. - initial API and implementation ******************************************************************************/ + package com.openshift.restclient.model.user; +import java.util.Set; + import com.openshift.restclient.model.IResource; -/** - * @author Jeff Cantrill - */ public interface IUser extends IResource { - /** - * The full name of this user - * @return - */ - String getFullName(); + /** + * The full name of this user + * + */ + String getFullName(); + + /** + * Returns the user uid as specified in the metadata + * + */ + String getUID(); + + /** + * Returns the name of the groups this user belongs to + * + */ + Set getGroups(); + /** + * Returns the identities that point to this user + * + */ + Set getIdentities(); } diff --git a/src/main/java/com/openshift/restclient/model/volume/IEmptyDirVolumeSource.java b/src/main/java/com/openshift/restclient/model/volume/IEmptyDirVolumeSource.java index 3e747e63..7b13429e 100644 --- a/src/main/java/com/openshift/restclient/model/volume/IEmptyDirVolumeSource.java +++ b/src/main/java/com/openshift/restclient/model/volume/IEmptyDirVolumeSource.java @@ -5,5 +5,6 @@ */ public interface IEmptyDirVolumeSource extends IVolumeSource { String getMedium(); + void setMedium(String medium); } diff --git a/src/main/java/com/openshift/internal/restclient/http/NotFoundException.java b/src/main/java/com/openshift/restclient/model/volume/IHostPathVolumeSource.java similarity index 55% rename from src/main/java/com/openshift/internal/restclient/http/NotFoundException.java rename to src/main/java/com/openshift/restclient/model/volume/IHostPathVolumeSource.java index 89b8c4c3..142a5125 100644 --- a/src/main/java/com/openshift/internal/restclient/http/NotFoundException.java +++ b/src/main/java/com/openshift/restclient/model/volume/IHostPathVolumeSource.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2011 Red Hat, Inc. + * Copyright (c) 2016 Red Hat, Inc. * Distributed under license by Red Hat, Inc. All rights reserved. * This program is made available under the terms of the * Eclipse Public License v1.0 which accompanies this distribution, @@ -7,21 +7,22 @@ * * Contributors: * Red Hat, Inc. - initial API and implementation - ******************************************************************************/ -package com.openshift.internal.restclient.http; + ******************************************************************************/ + +package com.openshift.restclient.model.volume; /** - * @author André Dietisheim + * VolumeSource for hostpath volumes of a pod + * + * */ -public class NotFoundException extends HttpClientException { - - private static final long serialVersionUID = 1L; +public interface IHostPathVolumeSource extends IVolumeSource { - public NotFoundException(String message, Throwable cause) { - super(message, cause); - } + /** + * Host path mapped into a pod + * + */ + String getPath(); - public NotFoundException(String message) { - super(message); - } + void setPath(String path); } diff --git a/src/main/java/com/openshift/restclient/model/volume/IPersistentVolume.java b/src/main/java/com/openshift/restclient/model/volume/IPersistentVolume.java index 1e56661d..2cc4c440 100644 --- a/src/main/java/com/openshift/restclient/model/volume/IPersistentVolume.java +++ b/src/main/java/com/openshift/restclient/model/volume/IPersistentVolume.java @@ -8,6 +8,7 @@ * Contributors: * Red Hat, Inc. - initial API and implementation ******************************************************************************/ + package com.openshift.restclient.model.volume; import java.util.Set; @@ -17,77 +18,90 @@ import com.openshift.restclient.model.volume.property.IPersistentVolumeProperties; import com.openshift.restclient.utils.MemoryUnit; - public interface IPersistentVolume extends IResource { - /** - * @param unit the designated unit. One of "Ki", "Mi", "Gi", "Ti", "Pi", "Ei". - * @return 0, if conversion not possible. Otherwise the capacity in given units. - * @see {@link PersistentVolume#convert(String, MemoryUnit)} - * @throws IllegalArgumentException if not supported {@code unit} given. - */ - long getCapacity(String unit); - - /** - * @param unit the designated unit. One of {@link MemoryUnit}'s Ki, Mi, Gi, Ti, Pi, Ei. - * @return 0, if conversion not possible. Otherwise the capacity in given units. - * @see {@link PersistentVolume#convert(String, MemoryUnit)} - * @throws IllegalArgumentException if not supported {@code unit} given. - */ - long getCapacity(MemoryUnit unit); - - /** - * @return the capacity in bytes. - */ - long getCapacity(); - - /** - * @return the unit in which the capacity is represent. - * @see {@link MemoryUnit} - */ - MemoryUnit getCapacityUnit(); - - /** - * Sets the capacity. There is no conversion between units. - * @param capacity the capacity - * @param unit the unit - */ - void setCapacity(long capacity, MemoryUnit unit); - - /** - * @return access modes - * @see {@link com.openshift.restclient.model.volume.PVCAccessModes} - * @see - */ - Set getAccessModes(); - - /** - * Sets the access modes. - * If there are any modes present, they are overridden by the {@code modes} parameter. - * @param modes the access modes - */ - void setAccessModes(String... modes); - - /** - * @return the value of 'spec.persistentVolumeReclaimPolicy' - */ - String getReclaimPolicy(); - - /** - * Sets the 'spec.persistentVolumeReclaimPolicy' value - * @param policy the policy string - */ - void setReclaimPolicy(String policy); - - /** - * @return specific persistent volume type properties - */ - IPersistentVolumeProperties getPersistentVolumeProperties(); - - /** - * Sets the volume type properties. - * @param properties the properties - */ - void setPersistentVolumeProperties(IPersistentVolumeProperties properties); + /** + * @param unit + * the designated unit. One of "Ki", "Mi", "Gi", "Ti", "Pi", "Ei". + * @return 0, if conversion not possible. Otherwise the capacity in given units. + * @see {@link PersistentVolume#convert(String, MemoryUnit)} + * @throws IllegalArgumentException + * if not supported {@code unit} given. + */ + long getCapacity(String unit); + + /** + * @param unit + * the designated unit. One of {@link MemoryUnit}'s Ki, Mi, Gi, Ti, + * Pi, Ei. + * @return 0, if conversion not possible. Otherwise the capacity in given units. + * @see {@link PersistentVolume#convert(String, MemoryUnit)} + * @throws IllegalArgumentException + * if not supported {@code unit} given. + */ + long getCapacity(MemoryUnit unit); + + /** + * @return the capacity in bytes. + */ + long getCapacity(); + + /** + * @return the unit in which the capacity is represent. + * @see {@link MemoryUnit} + */ + MemoryUnit getCapacityUnit(); + + /** + * Sets the capacity. There is no conversion between units. + * + * @param capacity + * the capacity + * @param unit + * the unit + */ + void setCapacity(long capacity, MemoryUnit unit); + + /** + * @return access modes + * @see {@link com.openshift.restclient.model.volume.PVCAccessModes} + * @see + */ + Set getAccessModes(); + + /** + * Sets the access modes. If there are any modes present, they are overridden by + * the {@code modes} parameter. + * + * @param modes + * the access modes + */ + void setAccessModes(String... modes); + + /** + * @return the value of 'spec.persistentVolumeReclaimPolicy' + */ + String getReclaimPolicy(); + + /** + * Sets the 'spec.persistentVolumeReclaimPolicy' value + * + * @param policy + * the policy string + */ + void setReclaimPolicy(String policy); + + /** + * @return specific persistent volume type properties + */ + IPersistentVolumeProperties getPersistentVolumeProperties(); + + /** + * Sets the volume type properties. + * + * @param properties + * the properties + */ + void setPersistentVolumeProperties(IPersistentVolumeProperties properties); } diff --git a/src/main/java/com/openshift/restclient/model/volume/IPersistentVolumeClaim.java b/src/main/java/com/openshift/restclient/model/volume/IPersistentVolumeClaim.java index 20d34f36..82749c36 100644 --- a/src/main/java/com/openshift/restclient/model/volume/IPersistentVolumeClaim.java +++ b/src/main/java/com/openshift/restclient/model/volume/IPersistentVolumeClaim.java @@ -8,48 +8,51 @@ * Contributors: * Red Hat, Inc. - initial API and implementation ******************************************************************************/ + package com.openshift.restclient.model.volume; import java.util.Set; import com.openshift.restclient.model.IResource; -/** - * - * @author Jeff Cantrill - * - */ public interface IPersistentVolumeClaim extends IResource { - /** - * - * @return the {@link PVCAccessModes} - */ - Set getAccessModes(); + /** + * + * @return the {@link PVCAccessModes} + */ + Set getAccessModes(); - /** - * Set the access modes for this claim. - * - * @param accessModes The access modes to set + /** + * Set the access modes for this claim. + * + * @param accessModes + * The access modes to set */ - void setAccessModes(Set accessModes); - - /** - * The requested storage - * @return - */ - String getRequestedStorage(); - - /** - * Set the requested storage of the claim - * - * @param requestedStorage The requested storage capacity + void setAccessModes(Set accessModes); + + /** + * The requested storage + * */ - void setRequestedStorage(String requestedStorage); + String getRequestedStorage(); - /** - * The status of the claim - * @return - */ - String getStatus(); + /** + * Set the requested storage of the claim + * + * @param requestedStorage + * The requested storage capacity + */ + void setRequestedStorage(String requestedStorage); + + /** + * The status of the claim + * + */ + String getStatus(); + + /** + * The volume name + */ + String getVolumeName(); } diff --git a/src/main/java/com/openshift/restclient/model/volume/IPersistentVolumeClaimVolumeSource.java b/src/main/java/com/openshift/restclient/model/volume/IPersistentVolumeClaimVolumeSource.java index 08c5f159..37ff5bb9 100644 --- a/src/main/java/com/openshift/restclient/model/volume/IPersistentVolumeClaimVolumeSource.java +++ b/src/main/java/com/openshift/restclient/model/volume/IPersistentVolumeClaimVolumeSource.java @@ -5,7 +5,10 @@ */ public interface IPersistentVolumeClaimVolumeSource extends IVolumeSource { String getClaimName(); + void setClaimName(String claimName); + boolean isReadOnly(); + void setReadOnly(boolean readOnly); } diff --git a/src/main/java/com/openshift/restclient/model/volume/ISecretVolumeSource.java b/src/main/java/com/openshift/restclient/model/volume/ISecretVolumeSource.java index c50e8692..4be2cf4c 100644 --- a/src/main/java/com/openshift/restclient/model/volume/ISecretVolumeSource.java +++ b/src/main/java/com/openshift/restclient/model/volume/ISecretVolumeSource.java @@ -5,5 +5,6 @@ */ public interface ISecretVolumeSource extends IVolumeSource { String getSecretName(); + void setSecretName(String secretName); } diff --git a/src/main/java/com/openshift/restclient/model/volume/IVolume.java b/src/main/java/com/openshift/restclient/model/volume/IVolume.java index 54c886e0..45135713 100644 --- a/src/main/java/com/openshift/restclient/model/volume/IVolume.java +++ b/src/main/java/com/openshift/restclient/model/volume/IVolume.java @@ -8,23 +8,26 @@ * Contributors: * Red Hat, Inc. - initial API and implementation ******************************************************************************/ + package com.openshift.restclient.model.volume; /** * - * @author Jeff Cantrill * @deprecated see {@link IVolumeMount} * */ @Deprecated public interface IVolume { - String getName(); - void setName(String name); - - void setMountPath(String path); - String getMountPath(); - - void setReadOnly(boolean readonly); - boolean isReadOnly(); + String getName(); + + void setName(String name); + + void setMountPath(String path); + + String getMountPath(); + + void setReadOnly(boolean readonly); + + boolean isReadOnly(); } diff --git a/src/main/java/com/openshift/restclient/model/volume/IVolumeMount.java b/src/main/java/com/openshift/restclient/model/volume/IVolumeMount.java index 168a971b..2c50ec9a 100644 --- a/src/main/java/com/openshift/restclient/model/volume/IVolumeMount.java +++ b/src/main/java/com/openshift/restclient/model/volume/IVolumeMount.java @@ -8,22 +8,24 @@ * Contributors: * Red Hat, Inc. - initial API and implementation ******************************************************************************/ + package com.openshift.restclient.model.volume; /** - * The volumes that are mounted - * in a container - * @author jeff.cantrill + * The volumes that are mounted in a container * */ public interface IVolumeMount { - String getName(); - void setName(String name); - - void setMountPath(String path); - String getMountPath(); - - void setReadOnly(boolean readonly); - boolean isReadOnly(); + String getName(); + + void setName(String name); + + void setMountPath(String path); + + String getMountPath(); + + void setReadOnly(boolean readonly); + + boolean isReadOnly(); } diff --git a/src/main/java/com/openshift/restclient/model/volume/IVolumeSource.java b/src/main/java/com/openshift/restclient/model/volume/IVolumeSource.java index 94e60c17..d3211553 100644 --- a/src/main/java/com/openshift/restclient/model/volume/IVolumeSource.java +++ b/src/main/java/com/openshift/restclient/model/volume/IVolumeSource.java @@ -8,17 +8,17 @@ * Contributors: * Red Hat, Inc. - initial API and implementation ******************************************************************************/ + package com.openshift.restclient.model.volume; /** * Persisent storage found on a pod - * @author jeff.cantrill * */ public interface IVolumeSource { - String getName(); + String getName(); - void setName(String name); + void setName(String name); - String toJSONString(); + String toJSONString(); } diff --git a/src/main/java/com/openshift/restclient/model/volume/PVCAccessModes.java b/src/main/java/com/openshift/restclient/model/volume/PVCAccessModes.java index 67da5a80..7f2cff28 100644 --- a/src/main/java/com/openshift/restclient/model/volume/PVCAccessModes.java +++ b/src/main/java/com/openshift/restclient/model/volume/PVCAccessModes.java @@ -8,12 +8,13 @@ * Contributors: * Red Hat, Inc. - initial API and implementation ******************************************************************************/ + package com.openshift.restclient.model.volume; public interface PVCAccessModes { - static final String READ_WRITE_ONCE = "ReadWriteOnce"; - static final String READ_ONLY_MANY = "ReadOnlyMany"; - static final String READ_WRITE_MANY = "ReadWriteMany"; + static final String READ_WRITE_ONCE = "ReadWriteOnce"; + static final String READ_ONLY_MANY = "ReadOnlyMany"; + static final String READ_WRITE_MANY = "ReadWriteMany"; } diff --git a/src/main/java/com/openshift/restclient/model/volume/VolumeType.java b/src/main/java/com/openshift/restclient/model/volume/VolumeType.java index 07b65532..6a9e4d39 100644 --- a/src/main/java/com/openshift/restclient/model/volume/VolumeType.java +++ b/src/main/java/com/openshift/restclient/model/volume/VolumeType.java @@ -8,6 +8,7 @@ * Contributors: * Red Hat, Inc. - initial API and implementation ******************************************************************************/ + package com.openshift.restclient.model.volume; import java.util.Arrays; @@ -15,33 +16,28 @@ /** * - * @author Jeff Cantrill * - * @see Persistent volume types + * @see Persistent + * volume types * */ public interface VolumeType { - static final String EMPTY_DIR = "emptyDir"; - static final String HOST_PATH = "hostPath"; - static final String NFS = "nfs"; - static final String GCE_PERSISTENT_DISK = "gcePersistentDisk"; - static final String AWS_ELASTIC_BLOCK_STORAGE = "awsElasticBlockStore"; - static final String GLUSTERFS = "glusterfs"; - static final String ISCSI = "iscsi"; - static final String RBD = "rbd"; - static final String SECRET = "secret"; - static final String PERSISTENT_VOLUME_CLAIM = "persistentVolumeClaim"; + static final String EMPTY_DIR = "emptyDir"; + static final String HOST_PATH = "hostPath"; + static final String NFS = "nfs"; + static final String GCE_PERSISTENT_DISK = "gcePersistentDisk"; + static final String AWS_ELASTIC_BLOCK_STORAGE = "awsElasticBlockStore"; + static final String GLUSTERFS = "glusterfs"; + static final String ISCSI = "iscsi"; + static final String RBD = "rbd"; + static final String SECRET = "secret"; + static final String PERSISTENT_VOLUME_CLAIM = "persistentVolumeClaim"; - static List getTypes() { - return Arrays.asList(EMPTY_DIR, - HOST_PATH, - NFS, - GCE_PERSISTENT_DISK, - AWS_ELASTIC_BLOCK_STORAGE, - GLUSTERFS, - ISCSI, - RBD); - } + static List getTypes() { + return Arrays.asList(EMPTY_DIR, HOST_PATH, NFS, GCE_PERSISTENT_DISK, AWS_ELASTIC_BLOCK_STORAGE, GLUSTERFS, + ISCSI, RBD); + } } diff --git a/src/main/java/com/openshift/restclient/model/volume/property/IHostPathVolumeProperties.java b/src/main/java/com/openshift/restclient/model/volume/property/IHostPathVolumeProperties.java index 8a04c3ea..b84d24d0 100644 --- a/src/main/java/com/openshift/restclient/model/volume/property/IHostPathVolumeProperties.java +++ b/src/main/java/com/openshift/restclient/model/volume/property/IHostPathVolumeProperties.java @@ -8,12 +8,13 @@ * Contributors: * Red Hat, Inc. - initial API and implementation ******************************************************************************/ -package com.openshift.restclient.model.volume.property; +package com.openshift.restclient.model.volume.property; public interface IHostPathVolumeProperties extends IPersistentVolumeProperties { - String getPath(); - void setPath(String path); + String getPath(); + + void setPath(String path); } diff --git a/src/main/java/com/openshift/restclient/model/volume/property/INfsVolumeProperties.java b/src/main/java/com/openshift/restclient/model/volume/property/INfsVolumeProperties.java index f7562aa6..b15fd7d6 100644 --- a/src/main/java/com/openshift/restclient/model/volume/property/INfsVolumeProperties.java +++ b/src/main/java/com/openshift/restclient/model/volume/property/INfsVolumeProperties.java @@ -8,17 +8,21 @@ * Contributors: * Red Hat, Inc. - initial API and implementation ******************************************************************************/ -package com.openshift.restclient.model.volume.property; +package com.openshift.restclient.model.volume.property; public interface INfsVolumeProperties extends IPersistentVolumeProperties { - String getPath(); - String getServer(); - boolean isReadOnly(); + String getPath(); + + String getServer(); + + boolean isReadOnly(); + + void setPath(String path); + + void setServer(String path); - void setPath(String path); - void setServer(String path); - void setReadOnly(boolean isReadOnly); + void setReadOnly(boolean isReadOnly); } diff --git a/src/main/java/com/openshift/restclient/model/volume/property/IPersistentVolumeProperties.java b/src/main/java/com/openshift/restclient/model/volume/property/IPersistentVolumeProperties.java index 1eec0603..dac42e21 100644 --- a/src/main/java/com/openshift/restclient/model/volume/property/IPersistentVolumeProperties.java +++ b/src/main/java/com/openshift/restclient/model/volume/property/IPersistentVolumeProperties.java @@ -8,6 +8,7 @@ * Contributors: * Red Hat, Inc. - initial API and implementation ******************************************************************************/ + package com.openshift.restclient.model.volume.property; diff --git a/src/main/java/com/openshift/restclient/utils/Base64Coder.java b/src/main/java/com/openshift/restclient/utils/Base64Coder.java index efb62c25..bb8a1b91 100644 --- a/src/main/java/com/openshift/restclient/utils/Base64Coder.java +++ b/src/main/java/com/openshift/restclient/utils/Base64Coder.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2013 Red Hat, Inc. +4 * Copyright (c) 2013-2018 Red Hat, Inc. * Distributed under license by Red Hat, Inc. All rights reserved. * This program is made available under the terms of the * Eclipse Public License v1.0 which accompanies this distribution, @@ -8,10 +8,13 @@ * Contributors: * Red Hat, Inc. - initial API and implementation ******************************************************************************/ + package com.openshift.restclient.utils; -import javax.xml.bind.DatatypeConverter; -import org.apache.commons.lang.StringUtils; +import java.nio.charset.Charset; +import java.util.Base64; + +import org.apache.commons.lang.ArrayUtils; /** * A utility class that offers methods to encode and decode strings from and to @@ -21,73 +24,93 @@ */ public class Base64Coder { - private Base64Coder() { - // inhibit instantiation - } + private Base64Coder() { + // inhibit instantiation + } + + /** + * Encodes the given byte array to a base64 encoded String. returns {@code null} + * if the given byte array is null, empty string if the given byte array is + * empty. + * + * @param unencoded the array of unencoded bytes that shall get encoded + * @return the encoded string created using the platform standard charset + * + * @see Charset#defaultCharset + */ + public static String encode(byte[] unencoded) { + return encode(unencoded, Charset.defaultCharset()); + } + + /** + * Encodes the given byte array to a base64 encoded String. returns {@code null} + * if the given byte array is null, empty string if the given byte array is + * empty. + * + * @param unencoded the array of unencoded bytes that shall get encoded + * @return the encoded string created using the platform standard charset + * + * @see Charset#defaultCharset + */ + public static String encode(byte[] unencoded, Charset charset) { + if (unencoded == null) { + return null; + } else if (unencoded.length == 0) { + return ""; + } + return new String(Base64.getEncoder().encode(unencoded), charset); + } - /** - * Encodes the given byte array to a base64 encoded String - * - * @param unencoded - * the array of unencoded bytes that shall get encoded - * @return the encoded string - */ - public static String encode(byte[] unencoded) { - if (unencoded == null) { - return null; - } else if (unencoded.length == 0) { - return new String(); - } - return DatatypeConverter.printBase64Binary(unencoded); - } + /** + * Encodes the given string to a base64 encoded string. Returns + * null if the given string is null. + * + */ + public static String encode(String unencoded) { + if (unencoded == null) { + return null; + } + return encode(unencoded.getBytes(), Charset.defaultCharset()); + } - /** - * Encodes the given string to a base64 encoded string. Returns - * null if the given string is null. - * - * @param unencoded - * @return - */ - public static String encode(String unencoded) { - if (StringUtils.isEmpty(unencoded)) { - return unencoded; - } - return encode(unencoded.getBytes()); - } + public static String encode(String unencoded, Charset charset) { + if (unencoded == null) { + return null; + } + return encode(unencoded.getBytes(), charset); + } - public static String decode(byte[] encoded) { - if (encoded == null - || encoded.length == 0) { - return new String(); - } - return decode(new String(encoded)); - } + public static String decode(byte[] encoded, Charset charset) { + if (ArrayUtils.isEmpty(encoded)) { + return ""; + } + return new String(Base64.getDecoder().decode(encoded), charset); + } - /** - * Decodes the given base64 encoded string. Returns null if the - * given string is null. - * - * @param encoded - * the base64 encoded string - * @return the decoded string - */ - public static String decode(String encoded) { - byte[] encodedBytes = decodeBinary(encoded); - return (encodedBytes == null) ? encoded : new String(DatatypeConverter.parseBase64Binary(encoded)); - } + /** + * Decodes the given base64 encoded string assuming the default charset. Returns null if the + * given string is null. + * + * @param encoded + * the base64 encoded string + * @return the decoded string + */ + public static String decode(String encoded) { + if (encoded == null) { + return null; + } + return decode(encoded.getBytes(Charset.defaultCharset()), Charset.defaultCharset()); + } - /** - * Decodes the given base64 encoded string. Returns null if the - * given string is null. - * - * @param encoded - * the base64 encoded string - * @return the decoded binary data - */ - public static byte[] decodeBinary(String encoded) { - if (StringUtils.isEmpty(encoded)) { - return null; - } - return DatatypeConverter.parseBase64Binary(encoded); - } + /** + * Decodes the given base64 encoded string using the default charset. Returns + * null if the given string is null. + * + * @param encoded the base64 encoded string + * @return the decoded binary data + */ + public static byte[] decodeBinary(String encoded) { + Charset charset = Charset.defaultCharset(); + return decode(encoded.getBytes(charset), charset).getBytes(charset); + } } diff --git a/src/main/java/com/openshift/restclient/utils/BeanUtils.java b/src/main/java/com/openshift/restclient/utils/BeanUtils.java index 08342725..65922a70 100644 --- a/src/main/java/com/openshift/restclient/utils/BeanUtils.java +++ b/src/main/java/com/openshift/restclient/utils/BeanUtils.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2016 Red Hat, Inc. + * Copyright (c) 2016-2019 Red Hat, Inc. * Distributed under license by Red Hat, Inc. All rights reserved. * This program is made available under the terms of the * Eclipse Public License v1.0 which accompanies this distribution, @@ -8,6 +8,7 @@ * Contributors: * Red Hat, Inc. - initial API and implementation ******************************************************************************/ + package com.openshift.restclient.utils; import java.util.List; @@ -18,18 +19,23 @@ public class BeanUtils { - private BeanUtils() { - } - - /** - * Convert a delimited string to camelcase (e.g. foo-bar -> fooBar) - * @param name the string to convert - * @param delimiter the delimiter to use - * @return the delimited string camelcased - */ - public static String toCamelCase(String name, String delimiter) { - String[] parts = name.split("-"); - List capitalized = Stream.of(parts).map(p->StringUtils.capitalize(p)).collect(Collectors.toList()); - return StringUtils.uncapitalize(StringUtils.join(capitalized, "")); - } + private BeanUtils() { + } + + /** + * Convert a delimited string to camelcase (e.g. foo-bar -> fooBar) + * + * @param name + * the string to convert + * @param delimiter + * the delimiter to use + * @return the delimited string camelcased + */ + public static String toCamelCase(String name, String delimiter) { + String[] parts = name.split("-"); + List capitalized = Stream.of(parts) + .map(StringUtils::capitalize) + .collect(Collectors.toList()); + return StringUtils.uncapitalize(StringUtils.join(capitalized, "")); + } } diff --git a/src/main/java/com/openshift/restclient/utils/EnvironmentVariableUtils.java b/src/main/java/com/openshift/restclient/utils/EnvironmentVariableUtils.java new file mode 100644 index 00000000..80d17668 --- /dev/null +++ b/src/main/java/com/openshift/restclient/utils/EnvironmentVariableUtils.java @@ -0,0 +1,37 @@ +/******************************************************************************* + * Copyright (c) 2017 Red Hat, Inc. Distributed under license by Red Hat, Inc. + * All rights reserved. This program is made available under the terms of the + * Eclipse Public License v1.0 which accompanies this distribution, and is + * available at http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: Red Hat, Inc. + ******************************************************************************/ + +package com.openshift.restclient.utils; + +import java.util.Collection; +import java.util.Collections; +import java.util.Map; +import java.util.stream.Collectors; + +import com.openshift.restclient.model.IEnvironmentVariable; + +/** + * @author Andre Dietisheim + */ +public class EnvironmentVariableUtils { + + private EnvironmentVariableUtils() { + } + + public static Map toMapOfStrings(Collection envVars) { + if (envVars == null) { + return null; + } + if (envVars.isEmpty()) { + return Collections.emptyMap(); + } + + return envVars.stream().collect(Collectors.toMap(envVar -> envVar.getName(), envVar -> envVar.getValue())); + } +} diff --git a/src/main/java/com/openshift/restclient/utils/MemoryUnit.java b/src/main/java/com/openshift/restclient/utils/MemoryUnit.java index 0b520d00..fd6c0809 100644 --- a/src/main/java/com/openshift/restclient/utils/MemoryUnit.java +++ b/src/main/java/com/openshift/restclient/utils/MemoryUnit.java @@ -8,10 +8,11 @@ * Contributors: * Red Hat, Inc. - initial API and implementation ******************************************************************************/ + package com.openshift.restclient.utils; public enum MemoryUnit { - Ki, Mi, Gi, Ti, Pi, Ei; + Ki, Mi, Gi, Ti, Pi, Ei; } diff --git a/src/main/java/com/openshift/restclient/utils/ResourceStatus.java b/src/main/java/com/openshift/restclient/utils/ResourceStatus.java new file mode 100644 index 00000000..0eba70b4 --- /dev/null +++ b/src/main/java/com/openshift/restclient/utils/ResourceStatus.java @@ -0,0 +1,8 @@ +package com.openshift.restclient.utils; + +public interface ResourceStatus { + + public static final String ACTIVE = "Active"; + public static final String TERMINATING = "Terminating"; + +} diff --git a/src/main/java/com/openshift/restclient/utils/SSLUtils.java b/src/main/java/com/openshift/restclient/utils/SSLUtils.java index d9c88c48..79a2e93b 100644 --- a/src/main/java/com/openshift/restclient/utils/SSLUtils.java +++ b/src/main/java/com/openshift/restclient/utils/SSLUtils.java @@ -8,6 +8,7 @@ * Contributors: * Red Hat, Inc. - initial API and implementation ******************************************************************************/ + package com.openshift.restclient.utils; import java.security.AlgorithmParameterGenerator; @@ -16,7 +17,6 @@ import java.security.NoSuchAlgorithmException; import java.util.ArrayList; import java.util.List; - import javax.net.ssl.SSLContext; import javax.net.ssl.TrustManager; @@ -25,71 +25,69 @@ */ public class SSLUtils { - private static final String SSL_CONTEXT_NAME = "SSL"; - public static final String CIPHER_DHE_REGEX = ".*_DHE_.*"; - private static final String CIPHER_DHE_NAME = "DiffieHellman"; - private static final int CIPHER_DHE_MINSIZE = 512; - private static final int CIPHER_DHE_MAXSIZE = 16384; - private static final int CIPHER_DHE_MODULO = 64; + private static final String SSL_CONTEXT_NAME = "SSL"; + public static final String CIPHER_DHE_REGEX = ".*_DHE_.*"; + private static final String CIPHER_DHE_NAME = "DiffieHellman"; + private static final int CIPHER_DHE_MINSIZE = 512; + private static final int CIPHER_DHE_MAXSIZE = 16384; + private static final int CIPHER_DHE_MODULO = 64; - private SSLUtils() { - // inhibit instantiation - } + private SSLUtils() { + // inhibit instantiation + } - /** - * Returns true if the jdk supports DEH cipher keys in the - * given length. - * inspired by http://stackoverflow.com/a/18254095/231357 - * - * @param length - * @return - * - */ - public static boolean supportsDHECipherKeysOf(int length) { - try { - return isMaxKeysize(length, CIPHER_DHE_MINSIZE, CIPHER_DHE_MAXSIZE, CIPHER_DHE_MODULO, - AlgorithmParameterGenerator.getInstance(CIPHER_DHE_NAME)); - } catch (NoSuchAlgorithmException e1) { - return false; - } - } + /** + * Returns true if the jdk supports DEH cipher keys in the given + * length. inspired by http://stackoverflow.com/a/18254095/231357 + * + * @return + * + */ + public static boolean supportsDHECipherKeysOf(int length) { + try { + return isMaxKeysize(length, CIPHER_DHE_MINSIZE, CIPHER_DHE_MAXSIZE, CIPHER_DHE_MODULO, + AlgorithmParameterGenerator.getInstance(CIPHER_DHE_NAME)); + } catch (NoSuchAlgorithmException e1) { + return false; + } + } - private static boolean isMaxKeysize(int length, int minSize, int maxSize, int modulo, - AlgorithmParameterGenerator algorithmParamGen) { - int maxLength = 0; - for (int i = minSize; i <= maxSize; i += modulo) { - try { - algorithmParamGen.init(i); - } catch (InvalidParameterException e) { - break; - } - maxLength = i; - } - return maxLength >= length; - } + private static boolean isMaxKeysize(int length, int minSize, int maxSize, int modulo, + AlgorithmParameterGenerator algorithmParamGen) { + int maxLength = 0; + for (int i = minSize; i <= maxSize; i += modulo) { + try { + algorithmParamGen.init(i); + } catch (InvalidParameterException e) { + break; + } + maxLength = i; + } + return maxLength >= length; + } - public static final String[] filterCiphers(String excludedCipherRegex, String[] ciphers) { - if (excludedCipherRegex == null - || ciphers == null) { - return ciphers; - } + public static final String[] filterCiphers(String excludedCipherRegex, String[] ciphers) { + if (excludedCipherRegex == null || ciphers == null) { + return ciphers; + } - List filteredCiphers = new ArrayList(); - for (String cipher : ciphers) { - if (!cipher.matches(excludedCipherRegex)) { - filteredCiphers.add(cipher); - } - } - return filteredCiphers.toArray(new String[filteredCiphers.size()]); - } + List filteredCiphers = new ArrayList(); + for (String cipher : ciphers) { + if (!cipher.matches(excludedCipherRegex)) { + filteredCiphers.add(cipher); + } + } + return filteredCiphers.toArray(new String[filteredCiphers.size()]); + } - public static SSLContext getSSLContext(TrustManager trustManager) throws NoSuchAlgorithmException, KeyManagementException { - TrustManager[] trustManagers = null; - if (trustManager != null) { - trustManagers = new TrustManager[] { trustManager }; - } - SSLContext sslContext = SSLContext.getInstance(SSL_CONTEXT_NAME); - sslContext.init(null, trustManagers, null); - return sslContext; - } + public static SSLContext getSSLContext(TrustManager trustManager) + throws NoSuchAlgorithmException, KeyManagementException { + TrustManager[] trustManagers = null; + if (trustManager != null) { + trustManagers = new TrustManager[] { trustManager }; + } + SSLContext sslContext = SSLContext.getInstance(SSL_CONTEXT_NAME); + sslContext.init(null, trustManagers, null); + return sslContext; + } } diff --git a/src/main/resources/k8stypes.properties b/src/main/resources/k8stypes.properties new file mode 100644 index 00000000..7e909ed1 --- /dev/null +++ b/src/main/resources/k8stypes.properties @@ -0,0 +1,44 @@ +# Dynamic K8S types registration +# +# Syntax is: +# classname=kind1,kind2,... +# ex: +# com.openshift.internal.restclient.model.Build=v1.Build,build.openshift.io/v1.Build +# +# Kubernetes API +com.openshift.internal.restclient.model.ConfigMap=v1.ConfigMap +com.openshift.internal.restclient.api.models.Endpoints=v1.Endpoints +com.openshift.internal.restclient.model.KubernetesEvent=v1.Event,events.k8s.io/v1beta1.Event +com.openshift.internal.restclient.model.LimitRange=v1.LimitRange +com.openshift.internal.restclient.model.Namespace=v1.Namespace +com.openshift.internal.restclient.model.volume.PersistentVolume=v1.PersistentVolume +com.openshift.internal.restclient.model.volume.PersistentVolumeClaim=v1.PersistentVolumeClaim +com.openshift.internal.restclient.model.Pod=v1.Pod +com.openshift.internal.restclient.model.ReplicationController=v1.ReplicationController +com.openshift.internal.restclient.model.ResourceQuota=v1.ResourceQuota +com.openshift.internal.restclient.model.Secret=v1.Secret +com.openshift.internal.restclient.model.Service=v1.Service +com.openshift.internal.restclient.model.ServiceAccount=v1.ServiceAccount +com.openshift.internal.restclient.model.Status=v1.Status + +# OpenShift API +com.openshift.internal.restclient.model.Build=v1.Build,build.openshift.io/v1.Build +com.openshift.internal.restclient.model.BuildConfig=v1.BuildConfig,build.openshift.io/v1.BuildConfig +com.openshift.internal.restclient.model.build.BuildRequest=v1.BuildRequest,build.openshift.io/v1.BuildRequest +com.openshift.internal.restclient.model.DeploymentConfig=v1.DeploymentConfig,apps.openshift.io/v1.DeploymentConfig +com.openshift.internal.restclient.model.ImageStream=v1.ImageStream,image.openshift.io/v1.ImageStream +com.openshift.internal.restclient.model.image.ImageStreamImport=v1.ImageStreamImport,image.openshift.io/v1.ImageStreamImport +com.openshift.internal.restclient.model.oauth.OAuthAccessToken=v1.OAuthAccessToken,oauth.openshift.io/v1.OAuthAccessToken +com.openshift.internal.restclient.model.oauth.OAuthAuthorizeToken=v1.OAuthAuthorizeToken,oauth.openshift.io/v1.OAuthAuthorizeToken +com.openshift.internal.restclient.model.oauth.OAuthClient=v1.OAuthClient,oauth.openshift.io/v1.OAuthClient +com.openshift.internal.restclient.model.oauth.OAuthClientAuthorization=v1.OAuthClientAuthorization,oauth.openshift.io/v1.OAuthClientAuthorization +com.openshift.internal.restclient.model.user.OpenShiftIdentity=v1.Identity,user.openshift.io/v1.Identity +com.openshift.internal.restclient.model.project.OpenshiftProjectRequest=v1.ProjectRequest,project.openshift.io/v1.ProjectRequest +com.openshift.internal.restclient.model.authorization.OpenshiftRole=v1.Role,authorization.openshift.io/v1.Role +com.openshift.internal.restclient.model.user.OpenShiftUser=v1.User,user.openshift.io/v1.User +com.openshift.internal.restclient.model.Project=v1.Project,project.openshift.io/v1.Project +com.openshift.internal.restclient.model.authorization.RoleBinding=v1.RoleBinding,authorization.openshift.io/v1.RoleBinding,rbac.authorization.k8s.io/v1.RoleBinding +com.openshift.internal.restclient.model.Route=v1.Route,route.openshift.io/v1.Route +com.openshift.internal.restclient.model.template.Template=v1.Template,template.openshift.io/v1.Template +com.openshift.internal.restclient.model.deploy.DeploymentRequest=v1.DeploymentRequest,apps.openshift.io/v1.DeploymentRequest +com.openshift.internal.restclient.apis.autoscaling.models.Scale=autoscaling/v1.Scale,extensions/v1beta1.Scale diff --git a/src/test/java/OpenshiftBinaryRSyncRetrievalIntegrationTest.java b/src/test/java/OpenshiftBinaryRSyncRetrievalIntegrationTest.java deleted file mode 100644 index 1e394ca0..00000000 --- a/src/test/java/OpenshiftBinaryRSyncRetrievalIntegrationTest.java +++ /dev/null @@ -1,74 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2015 Red Hat, Inc. - * Distributed under license by Red Hat, Inc. All rights reserved. - * This program is made available under the terms of the - * Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * Red Hat, Inc. - initial API and implementation - ******************************************************************************/ - - - -import java.io.BufferedInputStream; - -import org.junit.Before; -import org.junit.Test; - -import com.openshift.internal.restclient.IntegrationTestHelper; -import com.openshift.internal.restclient.authorization.AuthorizationClient; -import com.openshift.restclient.IClient; -import com.openshift.restclient.ResourceKind; -import com.openshift.restclient.authorization.BasicAuthorizationStrategy; -import com.openshift.restclient.authorization.IAuthorizationClient; -import com.openshift.restclient.authorization.IAuthorizationContext; -import com.openshift.restclient.authorization.TokenAuthorizationStrategy; -import com.openshift.restclient.capability.CapabilityVisitor; -import com.openshift.restclient.capability.IBinaryCapability; -import com.openshift.restclient.capability.IBinaryCapability.OpenShiftBinaryOption; -import com.openshift.restclient.capability.resources.IPodLogRetrieval; -import com.openshift.restclient.model.IPod; - -/** - * - * @author Jeff Cantrill - * - */ -public class OpenshiftBinaryRSyncRetrievalIntegrationTest { - - private IntegrationTestHelper helper = new IntegrationTestHelper(); - @Before - public void setUp() throws Exception { - } - - @Test - public void testLogRetrieval() { - System.setProperty(IBinaryCapability.OPENSHIFT_BINARY_LOCATION, helper.getOpenShiftLocation()); - IClient client = helper.createClient(); - client.setAuthorizationStrategy(new BasicAuthorizationStrategy("admin", "admin", "")); - IAuthorizationClient authClient = new AuthorizationClient(client); - IAuthorizationContext context = authClient.getContext(client.getBaseURL().toString()); - client.setAuthorizationStrategy(new TokenAuthorizationStrategy(context.getToken())); - client.get(ResourceKind.POD, "hello-openshift", "openshift-dev"); - IPod pod = client.get(ResourceKind.POD, "hello-openshift", "openshift-dev"); - - pod.accept(new CapabilityVisitor() { - - @Override - public Object visit(IPodLogRetrieval cap) { - try { - BufferedInputStream os = new BufferedInputStream(cap.getLogs(true, OpenShiftBinaryOption.SKIP_TLS_VERIFY)); - int c; - while((c = os.read()) != -1) { - System.out.print((char)c); - } - } catch (Exception e) { - e.printStackTrace(); - } - return null; - } - - }, new Object()); - } -} diff --git a/src/test/java/com/openshift/internal/restclient/APIModelVersionTest.java b/src/test/java/com/openshift/internal/restclient/APIModelVersionTest.java index 9f044a15..cb84f23f 100644 --- a/src/test/java/com/openshift/internal/restclient/APIModelVersionTest.java +++ b/src/test/java/com/openshift/internal/restclient/APIModelVersionTest.java @@ -8,27 +8,22 @@ * Contributors: * Red Hat, Inc. - initial API and implementation ******************************************************************************/ + package com.openshift.internal.restclient; -import static org.junit.Assert.*; +import static org.junit.Assert.assertEquals; -import org.junit.Before; import org.junit.Test; import com.openshift.internal.restclient.APIModelVersion.VersionComparitor; -/** - * - * @author Jeff Cantrill - * - */ public class APIModelVersionTest { - @Test - public void testVersionComparitor() { - VersionComparitor comparitor = new APIModelVersion.VersionComparitor(); - int result = comparitor.compare(OpenShiftAPIVersion.v1, OpenShiftAPIVersion.v1beta3); - assertEquals("Exp. v1 to be greater then v1beta3", 1,result); - } + @Test + public void testVersionComparitor() { + VersionComparitor comparitor = new APIModelVersion.VersionComparitor(); + int result = comparitor.compare(OpenShiftAPIVersion.v1, OpenShiftAPIVersion.v1beta3); + assertEquals("Exp. v1 to be greater then v1beta3", 1, result); + } } diff --git a/src/test/java/com/openshift/internal/restclient/ApiTypeMapperTest.java b/src/test/java/com/openshift/internal/restclient/ApiTypeMapperTest.java index 1e017e84..a9a6d897 100644 --- a/src/test/java/com/openshift/internal/restclient/ApiTypeMapperTest.java +++ b/src/test/java/com/openshift/internal/restclient/ApiTypeMapperTest.java @@ -8,82 +8,81 @@ * Contributors: * Red Hat, Inc. - initial API and implementation ******************************************************************************/ -package com.openshift.internal.restclient; -import static org.junit.Assert.*; -import static org.mockito.Matchers.anyInt; -import static org.mockito.Matchers.eq; -import static org.mockito.Mockito.*; +package com.openshift.internal.restclient; -import java.net.URL; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; import org.junit.Test; import org.junit.runner.RunWith; -import org.mockito.runners.MockitoJUnitRunner; +import org.mockito.junit.MockitoJUnitRunner; import com.openshift.restclient.IApiTypeMapper.IVersionedApiResource; import com.openshift.restclient.ResourceKind; -import com.openshift.restclient.http.IHttpClient; import com.openshift.restclient.model.IBuildConfig; import com.openshift.restclient.model.IResource; import com.openshift.restclient.model.IService; import com.openshift.restclient.model.MocksFactory; - @RunWith(MockitoJUnitRunner.class) public class ApiTypeMapperTest extends TypeMapperFixture { - private MocksFactory factory = new MocksFactory(); - - @Test - public void testKubernetesResourceIsSupportedAfterInitiallyErrorIsThrown() throws Exception { - IService resource = factory.stub(ResourceKind.SERVICE); - try { - when(getHttpClient().get(eq(new URL(super.base + "/api")), anyInt())).thenThrow(new RuntimeException()); - assertTrue("Exp. Kube support", mapper.isSupported(resource)); - }catch(RuntimeException e) { - when(getHttpClient().get(eq(new URL(base + "/api")), anyInt())).thenReturn(super.VERSIONS); - assertTrue("Exp. Kube support", mapper.isSupported(resource)); - } - } - - @Test - public void testKubernetesResourceIsSupported() { - IService resource = factory.stub(ResourceKind.SERVICE); - assertTrue("Exp. Kube support", mapper.isSupported(resource)); - - IVersionedApiResource endpoint = mapper.getEndpointFor("v1", ResourceKind.SERVICE); - assertTrue("Exp. services to be namespaces", endpoint.isNamespaced()); - } - - @Test - public void testOpenShiftResourceIsSupported() { - IBuildConfig resource = factory.mock(IBuildConfig.class); - //check subresource or action first - when(resource.getKind()).thenReturn("buildconfigs/webhooks"); - assertFalse("Exp. ApiGroups to not recognize 'action' as a resource", mapper.isSupported(resource)); - - resource = factory.stub(IBuildConfig.class); - assertTrue("Exp. OpenShift support", mapper.isSupported(resource)); - } + private MocksFactory factory = new MocksFactory(); + + @Test + public void testKubernetesResourceIsSupportedAfterInitiallyErrorIsThrown() throws Exception { + IService resource = factory.stub(ResourceKind.SERVICE); + try { + getHttpClient().whenRequestTo(TypeMapperFixture.base + "/api").thenThrow(new RuntimeException()); + assertFalse("Exp. Kube support", mapper.isSupported(resource)); + } catch (RuntimeException e) { + getHttpClient().whenRequestTo(TypeMapperFixture.base + "/api") + .thenReturn(responseOf(TypeMapperFixture.VERSIONS)); + assertTrue("Exp. Kube support", mapper.isSupported(resource)); + } + } + + @Test + public void testKubernetesResourceIsSupported() { + IService resource = factory.stub(ResourceKind.SERVICE); + assertTrue("Exp. Kube support", mapper.isSupported(resource)); + + IVersionedApiResource endpoint = mapper.getEndpointFor("v1", ResourceKind.SERVICE); + assertTrue("Exp. services to be namespaces", endpoint.isNamespaced()); + } + + @Test + public void testOpenShiftResourceIsSupported() { + IBuildConfig resource = factory.mock(IBuildConfig.class); + // check subresource or action first + when(resource.getKind()).thenReturn("buildconfigs/webhooks"); + assertFalse("Exp. ApiGroups to not recognize 'action' as a resource", mapper.isSupported(resource)); + + resource = factory.stub(IBuildConfig.class); + assertTrue("Exp. OpenShift support", mapper.isSupported(resource)); + } + + @Test + public void testRandomResourceIsNotSupported() { + IResource resource = factory.mock(IResource.class); + assertFalse("Exp. no random supported kinds", mapper.isSupported(resource)); + } - @Test - public void testRandomResourceIsNotSupported() { - IResource resource = factory.mock(IResource.class); - assertFalse("Exp. no random supported kinds",mapper.isSupported(resource)); - } + @Test + public void testApiGroupResourceIsSupported() { + IResource resource = mock(IResource.class); + when(resource.getKind()).thenReturn("DaemonSet"); + when(resource.getApiVersion()).thenReturn("extensions/v1beta1"); + assertTrue("Exp. extension to be supported", mapper.isSupported(resource)); - @Test - public void testApiGroupResourceIsSupported() { - IResource resource = mock(IResource.class); - when(resource.getKind()).thenReturn("DaemonSet"); - when(resource.getApiVersion()).thenReturn("extensions/v1beta1"); - assertTrue("Exp. extension to be supported",mapper.isSupported(resource)); - - IVersionedApiResource endpoint = mapper.getEndpointFor("extensions/v1beta1", "DaemonSet"); - assertEquals("daemonsets", endpoint.getName()); - assertTrue(endpoint.isNamespaced()); - assertTrue(endpoint.isSupported("status")); - } + IVersionedApiResource endpoint = mapper.getEndpointFor("extensions/v1beta1", "DaemonSet"); + assertEquals("daemonsets", endpoint.getName()); + assertTrue(endpoint.isNamespaced()); + assertTrue(endpoint.isSupported("status")); + } } diff --git a/src/test/java/com/openshift/internal/restclient/AuthorizationEndpointsTest.java b/src/test/java/com/openshift/internal/restclient/AuthorizationEndpointsTest.java new file mode 100644 index 00000000..5d98d713 --- /dev/null +++ b/src/test/java/com/openshift/internal/restclient/AuthorizationEndpointsTest.java @@ -0,0 +1,139 @@ +/******************************************************************************* + * Copyright (c) 2019-2020 Red Hat, Inc. + * Distributed under license by Red Hat, Inc. All rights reserved. + * This program is made available under the terms of the + * Eclipse Public License v1.0 which accompanies this distribution, + * and is available at http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Red Hat, Inc. - initial API and implementation + *******************************************************************************/ + +package com.openshift.internal.restclient; + +import static org.assertj.core.api.Assertions.assertThat; + +import java.net.URL; + +import org.junit.Test; + +import com.openshift.internal.restclient.authorization.AuthorizationContext; +import com.openshift.restclient.IApiTypeMapper; +import com.openshift.restclient.IClient; +import com.openshift.restclient.IResourceFactory; +import com.openshift.restclient.utils.Samples; + +import okhttp3.OkHttpClient; + +public class AuthorizationEndpointsTest extends TypeMapperFixture { + + @Test + public void shouldRetrieveAuthorizationEndpoint() throws Exception { + getHttpClient().whenRequestTo(base + '/' + AuthorizationEndpoints.PATH_OAUTH_AUTHORIZATION_SERVER, + responseOf(Samples.WELL_KNOW_OAUTH_AUTHORIZATION_SERVER.getContentAsString())); + + URL authorizationEndpoint = getIClient().getAuthorizationEndpoint(); + assertThat(authorizationEndpoint).isNotNull(); + assertThat(authorizationEndpoint.toExternalForm()).isEqualTo( + "https://api.rh-us-east-1.openshift.com/oauth/authorize"); + } + + @Test + public void shouldRetrieveTokenEndpoint() throws Exception { + getHttpClient().whenRequestTo(base + '/' + AuthorizationEndpoints.PATH_OAUTH_AUTHORIZATION_SERVER, + responseOf(Samples.WELL_KNOW_OAUTH_AUTHORIZATION_SERVER.getContentAsString())); + + URL tokenEndpoint = getIClient().getTokenEndpoint(); + assertThat(tokenEndpoint).isNotNull(); + assertThat(tokenEndpoint.toExternalForm()).isEqualTo( + "https://api.rh-us-east-1.openshift.com/oauth/token"); + } + + @Test + public void shouldReturnNullifAuthorizationEndpoint404AndNoDefault() throws Exception { + // given + getHttpClient().whenRequestTo(base + '/' + AuthorizationEndpoints.PATH_OAUTH_AUTHORIZATION_SERVER, + responseOf(404, "something wrong")); + DefaultClient client = new DefaultableEndpointsClient(null, null, getIClient()); + // when + URL authEndpoint = client.getAuthorizationEndpoint(); + URL tokenEndpoint = client.getTokenEndpoint(); + // then + assertThat(authEndpoint).isEqualTo(null); + assertThat(tokenEndpoint).isEqualTo(null); + } + + @Test + public void shouldReturnDefaultsIfAuthorizationEndpoint404() throws Exception { + // given + getHttpClient().whenRequestTo(base + '/' + AuthorizationEndpoints.PATH_OAUTH_AUTHORIZATION_SERVER, + responseOf(404, "something wrong")); + URL defaultAuthEndpoint = new URL("https://www.redhat.com"); + URL defaultTokenEndpoint = new URL("https://www.openshift.com"); + DefaultClient client = new DefaultableEndpointsClient(defaultAuthEndpoint, defaultTokenEndpoint, getIClient()); + // when + URL authEndpoint = client.getAuthorizationEndpoint(); + URL tokenEndpoint = client.getTokenEndpoint(); + // then + assertThat(authEndpoint).isEqualTo(defaultAuthEndpoint); + assertThat(tokenEndpoint).isEqualTo(defaultTokenEndpoint); + } + + @Test + public void shouldReturnNullifAuthorizationEndpointInvalidJsonAndNoDefault() throws Exception { + // given + getHttpClient().whenRequestTo(base + '/' + AuthorizationEndpoints.PATH_OAUTH_AUTHORIZATION_SERVER, + responseOf("{bogus")); + DefaultClient client = new DefaultableEndpointsClient(null, null, getIClient()); + // when + URL authEndpoint = client.getAuthorizationEndpoint(); + URL tokenEndpoint = client.getTokenEndpoint(); + // then + assertThat(authEndpoint).isEqualTo(null); + assertThat(tokenEndpoint).isEqualTo(null); + } + + @Test + public void shouldReturnDefaultsifAuthorizationEndpointInvalidJson() throws Exception { + // given + getHttpClient().whenRequestTo(base + '/' + AuthorizationEndpoints.PATH_OAUTH_AUTHORIZATION_SERVER, + responseOf("{bogus")); + URL defaultAuthEndpoint = new URL("https://www.redhat.com"); + URL defaultTokenEndpoint = new URL("https://www.openshift.com"); + DefaultClient client = new DefaultableEndpointsClient(defaultAuthEndpoint, defaultTokenEndpoint, getIClient()); + // when + URL authEndpoint = client.getAuthorizationEndpoint(); + URL tokenEndpoint = client.getTokenEndpoint(); + // then + assertThat(authEndpoint).isEqualTo(defaultAuthEndpoint); + assertThat(tokenEndpoint).isEqualTo(defaultTokenEndpoint); + } + + private static class DefaultableEndpointsClient extends DefaultClient { + + private URL defaultAuthorizationEndpoint; + private URL defaultTokenEndpoint; + + public DefaultableEndpointsClient(URL defaultAuthorizationEndpoint, URL defaultTokenEndpoint, IClient client) { + super(client.getBaseURL(), + client.adapt(OkHttpClient.class), + client.adapt(IResourceFactory.class), + client.adapt(IApiTypeMapper.class), + (AuthorizationContext) client.getAuthorizationContext()); + this.defaultAuthorizationEndpoint = defaultAuthorizationEndpoint; + this.defaultTokenEndpoint = defaultTokenEndpoint; + } + + @Override + public URL getDefaultAuthorizationEndpoint() { + return defaultAuthorizationEndpoint; + } + + @Override + public URL getDefaultTokenEndpoint() { + return defaultTokenEndpoint; + } + + } + +} diff --git a/src/test/java/com/openshift/internal/restclient/ClusterVersionsTest.java b/src/test/java/com/openshift/internal/restclient/ClusterVersionsTest.java new file mode 100644 index 00000000..65ab4b5c --- /dev/null +++ b/src/test/java/com/openshift/internal/restclient/ClusterVersionsTest.java @@ -0,0 +1,61 @@ +/******************************************************************************* + * Copyright (c) 2019-2020 Red Hat, Inc. + * Distributed under license by Red Hat, Inc. All rights reserved. + * This program is made available under the terms of the + * Eclipse Public License v1.0 which accompanies this distribution, + * and is available at http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Red Hat, Inc. - initial API and implementation + ******************************************************************************/ + +package com.openshift.internal.restclient; + +import static org.assertj.core.api.Assertions.assertThat; + +import org.junit.Test; + +import com.openshift.restclient.utils.Samples; + +public class ClusterVersionsTest extends TypeMapperFixture { + @Test + public void testKubernetesMasterVersionOk() throws Exception { + getHttpClient().whenRequestTo(base + "/version", + responseOf(Samples.KUBERNETES_VERSION.getContentAsString())); + + assertThat(getIClient().getKubernetesMasterVersion()).isEqualTo("v1.6.1+5115d708d7"); + } + + @Test + public void testKubernetesMasterVersion404() throws Exception { + getHttpClient().whenRequestTo(base + "/version", + responseOf(404, "something wrong")); + + assertThat(getIClient().getKubernetesMasterVersion()).isEqualTo(""); + } + + @Test + public void testOpenShiftMasterVersionOk() throws Exception { + getHttpClient().whenRequestTo(base + "/version/openshift", + responseOf(Samples.OPENSHIFT_VERSION.getContentAsString())); + + assertThat(getIClient().getOpenshiftMasterVersion()).isEqualTo("v3.6.0-alpha.2+3c221d5"); + } + + @Test + public void testOpenShiftMasterVersion404() throws Exception { + getHttpClient().whenRequestTo(base + "/version/openshift", + responseOf(404, "something wrong")); + + assertThat(getIClient().getOpenshiftMasterVersion()).isEqualTo(""); + } + + @Test + public void testOpenShiftMasterVersionIllegalJson() throws Exception { + getHttpClient().whenRequestTo(base + "/version/openshift", + responseOf("{bogus")); + + assertThat(getIClient().getOpenshiftMasterVersion()).isEqualTo(null); + } + +} diff --git a/src/test/java/com/openshift/internal/restclient/DefaultClientFilterIntegrationTest.java b/src/test/java/com/openshift/internal/restclient/DefaultClientFilterIntegrationTest.java new file mode 100644 index 00000000..f328be6d --- /dev/null +++ b/src/test/java/com/openshift/internal/restclient/DefaultClientFilterIntegrationTest.java @@ -0,0 +1,134 @@ +/******************************************************************************* +* Copyright (c) 2015-2019 Red Hat, Inc. Distributed under license by Red Hat, Inc. +* All rights reserved. This program is made available under the terms of the +* Eclipse Public License v1.0 which accompanies this distribution, and is +* available at http://www.eclipse.org/legal/epl-v10.html +* +* Contributors: Red Hat, Inc. +******************************************************************************/ + +package com.openshift.internal.restclient; + +import static com.openshift.restclient.ResourceKind.BUILD_CONFIG; +import static org.assertj.core.api.Assertions.assertThat; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; + +import java.util.Collection; +import java.util.HashMap; +import java.util.List; +import java.util.Set; +import java.util.stream.Collectors; + +import org.junit.AfterClass; +import org.junit.BeforeClass; +import org.junit.Test; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.openshift.restclient.IClient; +import com.openshift.restclient.model.IBuildConfig; +import com.openshift.restclient.model.IProject; +import com.openshift.restclient.model.IResource; + +public class DefaultClientFilterIntegrationTest { + + private static final Logger LOG = LoggerFactory.getLogger(DefaultClientFilterIntegrationTest.class); + + private static IClient client; + private static IProject project; + private static Collection bcs; + private static IntegrationTestHelper helper = new IntegrationTestHelper(); + + @BeforeClass + public static void setup() { + client = helper.createClientForBasicAuth(); + project = helper.getOrCreateIntegrationTestProject(client); + bcs = helper.createResources(client, + helper.stubBuildConfig(client, project.getNamespaceName(), "build1", null, new HashMap() {{ + put("foo", "yes"); + put("bar", "no"); + put("baz", "no"); + } + }), + helper.stubBuildConfig(client, project.getNamespaceName(), "build2", null, new HashMap() {{ + put("foo", "no"); + put("bar", "yes"); + } + }), + helper.stubBuildConfig(client, project.getNamespaceName(), "build3", null, new HashMap() {{ + put("foo", "yes"); + put("bar", "yes"); + } + }), + helper.stubBuildConfig(client, project.getNamespaceName(), "build4", null, new HashMap<>())); + + } + + @AfterClass + public static void cleanup() { + helper.cleanUpResources(client, bcs); + } + + @Test + public void testFilteringWithOneLabel() { + List list = client.list(BUILD_CONFIG, project.getNamespaceName(), new HashMap() { + { + put("foo", "yes"); + } + }); + + assertEquals(2, list.size()); + Set names = list.stream().map(IResource::getName).collect(Collectors.toSet()); + assertTrue("Should contain build1", names.contains("build1")); + assertTrue("Should contain build3", names.contains("build3")); + } + + @Test + public void testFilteringWithTwoLabel() { + List list = client.list(BUILD_CONFIG, project.getNamespaceName(), new HashMap() { + { + put("foo", "yes"); + put("bar", "no"); + } + }); + + assertEquals(1, list.size()); + IBuildConfig bc = list.get(0); + assertEquals("build1", bc.getName()); + } + + @Test + public void testFilteringWithLabelExist() { + List list = client.list(BUILD_CONFIG, project.getNamespaceName(), "baz"); + + assertEquals(1, list.size()); + IBuildConfig bc = list.get(0); + assertEquals("build1", bc.getName()); + } + + @Test + public void testFilteringWithLabelNotExist() { + List list = client.list(BUILD_CONFIG, project.getNamespaceName(), "!baz"); + + Set names = list.stream().map(IResource::getName).collect(Collectors.toSet()); + + assertThat(names).contains("build2", "build3", "build4").doesNotContain("build1"); + } + + @Test + public void testFilteringWithLabelNotEqualTo() { + List list = client.list(BUILD_CONFIG, project.getNamespaceName(), "foo != yes"); + + Set names = list.stream().map(IResource::getName).collect(Collectors.toSet()); + + assertThat(names).contains("build2", "build4").doesNotContain("build1", "build3"); + } + + @Test + public void testFilteringWithLabelCombinedLabelQuery() { + List list = client.list(BUILD_CONFIG, project.getNamespaceName(), "foo,bar=no"); + + assertThat(list).allMatch(bc -> "build1".equals(bc.getName())); + } +} diff --git a/src/test/java/com/openshift/internal/restclient/DefaultClientIntegrationTest.java b/src/test/java/com/openshift/internal/restclient/DefaultClientIntegrationTest.java index 6074e1ae..b2d340a8 100644 --- a/src/test/java/com/openshift/internal/restclient/DefaultClientIntegrationTest.java +++ b/src/test/java/com/openshift/internal/restclient/DefaultClientIntegrationTest.java @@ -1,154 +1,201 @@ - /******************************************************************************* - * Copyright (c) 2015 Red Hat, Inc. Distributed under license by Red Hat, Inc. - * All rights reserved. This program is made available under the terms of the - * Eclipse Public License v1.0 which accompanies this distribution, and is - * available at http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: Red Hat, Inc. - ******************************************************************************/ +/******************************************************************************* +* Copyright (c) 2015-2019 Red Hat, Inc. Distributed under license by Red Hat, Inc. +* All rights reserved. This program is made available under the terms of the +* Eclipse Public License v1.0 which accompanies this distribution, and is +* available at http://www.eclipse.org/legal/epl-v10.html +* +* Contributors: Red Hat, Inc. +******************************************************************************/ + package com.openshift.internal.restclient; +import static com.openshift.internal.restclient.IntegrationTestHelper.MILLISECONDS_PER_SECOND; +import static org.assertj.core.api.Assertions.assertThat; import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; -import java.net.MalformedURLException; +import java.util.Collections; import java.util.List; +import org.apache.commons.lang.StringUtils; import org.junit.Before; import org.junit.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import com.openshift.internal.restclient.model.Project; -import com.openshift.internal.restclient.model.Service; import com.openshift.internal.restclient.model.template.Template; import com.openshift.restclient.IClient; import com.openshift.restclient.IResourceFactory; import com.openshift.restclient.ResourceKind; +import com.openshift.restclient.authorization.UnauthorizedException; +import com.openshift.restclient.model.IBuildConfig; import com.openshift.restclient.model.IProject; import com.openshift.restclient.model.IResource; +import com.openshift.restclient.model.IService; import com.openshift.restclient.model.template.ITemplate; -import com.openshift.restclient.utils.Samples; -/** - * @author Jeff Cantrill - */ public class DefaultClientIntegrationTest { - private static final String VERSION = "v1"; - - private static final Logger LOG = LoggerFactory.getLogger(DefaultClientIntegrationTest.class); - - private IClient client; - private IntegrationTestHelper helper = new IntegrationTestHelper(); - - private IResourceFactory factory; - - @Before - public void setup () { - client = helper.createClientForBasicAuth(); - factory = new ResourceFactory(client); - } - - @Test - public void testListTemplates(){ - Template template = null; - Project project = null; - - try { - project = factory.create(VERSION, ResourceKind.PROJECT); - project.setName(helper.generateNamespace()); - template = factory.create(Samples.V1_TEMPLATE.getContentAsString()); - template.setNamespace(project.getName()); - - project = client.create(project); - template = client.create(template, project.getNamespace()); - - List list = client.list(ResourceKind.TEMPLATE, project.getName()); - assertEquals(1, list.size()); - for (ITemplate t : list) { - LOG.debug(t.toString()); - } - } finally { - cleanUpResource(client, template); - cleanUpResource(client, project); - } - } - - @Test - public void testResourceLifeCycle() throws MalformedURLException { - - - IProject project = factory.create(VERSION, ResourceKind.PROJECT); - ((Project) project).setName(helper.generateNamespace()); - LOG.debug(String.format("Stubbing project: %s", project)); - - IProject other = factory.create(VERSION, ResourceKind.PROJECT); - ((Project) other).setName(helper.generateNamespace()); - LOG.debug(String.format("Stubbing project: %s", project)); - - Service service = factory.create(VERSION, ResourceKind.SERVICE); - service.setNamespace(project.getName()); //this will be the project's namespace - service.setName("some-service"); - service.setTargetPort(6767); - service.setPort(6767); - service.setSelector("name", "barpod"); - LOG.debug(String.format("Stubbing service: %s", service)); - - Service otherService = factory.create(VERSION, ResourceKind.SERVICE); - otherService.setNamespace(other.getName()); //this will be the project's namespace - otherService.setName("some-other-service"); - otherService.setTargetPort(8787); - otherService.setPort(8787); - otherService.setSelector("name", "foopod"); - - LOG.debug(String.format("Stubbing service: %s", otherService)); - - try{ - project = client.create(project); - LOG.debug(String.format("Created project: %s", project)); - - other = client.create(other); - LOG.debug(String.format("Created project: %s", project)); - - LOG.debug(String.format("Creating service: %s", service)); - service = client.create(service); - LOG.debug(String.format("Created service: %s", service)); - - LOG.debug(String.format("Creating service: %s", otherService)); - otherService = client.create(otherService); - LOG.debug(String.format("Created service: %s", otherService)); - - LOG.debug("Listing projects"); - List projects = client.list(ResourceKind.PROJECT); - LOG.debug(String.format("Listed projects: %s", projects)); - - LOG.debug(String.format("Listing services with namespace: %s", project.getNamespace())); - List services = client.list(ResourceKind.SERVICE, project.getNamespace()); - LOG.debug(String.format("Listed services: %s", services)); - - LOG.debug(String.format("Getting service: %s", otherService.getName())); - Service s = client.get(ResourceKind.SERVICE, otherService.getName(), otherService.getNamespace()); - LOG.debug(String.format("Retrieved service: %s", s.getName())); - - assertEquals("Expected there to be only one service returned", 1, services.size()); - assertEquals("Expected to get the service with the correct name", service.getName(), services.get(0).getName()); - }finally{ - cleanUpResource(client, project); - cleanUpResource(client, other); - cleanUpResource(client, service); - cleanUpResource(client, otherService); - } - - } - - private void cleanUpResource(IClient client, IResource resource){ - try{ - Thread.sleep(1000); - LOG.debug(String.format("Deleting resource: %s", resource)); -// client.delete(resource); - }catch(Exception e){ - LOG.error("Exception deleting", e); - } - } + private static final Logger LOG = LoggerFactory.getLogger(DefaultClientIntegrationTest.class); + + private IntegrationTestHelper helper = new IntegrationTestHelper(); + private IClient client; + private IResourceFactory factory; + private IProject project; + + @Before + public void setup() { + this.client = helper.createClientForBasicAuth(); + this.factory = new ResourceFactory(client); + this.project = helper.getOrCreateIntegrationTestProject(client); + } + + @Test + public void testAuthContextIsAuthorizedWithValidUserNameAndPassword() { + client = helper.createClient(); + client.getAuthorizationContext().setUserName(helper.getDefaultClusterAdminUser()); + client.getAuthorizationContext().setPassword(helper.getDefaultClusterAdminPassword()); + assertThat(client.getAuthorizationContext().isAuthorized()).isTrue(); + } + + @Test(expected = UnauthorizedException.class) + public void testAuthContextIsAuthorizedWithoutPasswordThrows() { + client = helper.createClient(); + client.getAuthorizationContext().setUserName(helper.getDefaultClusterAdminUser()); + client.getAuthorizationContext().isAuthorized(); + } + + @Test + public void testListprojects() { + assertTrue(client.list(ResourceKind.PROJECT, IntegrationTestHelper.getDefaultNamespace()).size() > 0); + } + + @Test + public void testReady() { + client.getServerReadyStatus(); + } + + @Test + public void testListTemplates() { + Template template = null; + IProject project = helper.getOrCreateIntegrationTestProject(client); + + try { + template = factory.stub(ResourceKind.TEMPLATE, "mytemplate"); + template = client.create(template, project.getNamespaceName()); + + assertNotNull("Exp. the template to be found but was not", helper.waitForResource(client, ResourceKind.TEMPLATE, + project.getName(), template.getName(), 5 * MILLISECONDS_PER_SECOND)); + + List list = client.list(ResourceKind.TEMPLATE, project.getName()); + assertEquals(1, list.size()); + for (ITemplate t : list) { + LOG.debug(t.toString()); + } + } finally { + helper.cleanUpResource(client, template); + } + } + + @Test + public void testResourceLifeCycle() { + IService service = null; + IService otherService = null; + IBuildConfig bc = null; + try { + IService stub = helper.stubService(client, + project.getNamespaceName(), + IntegrationTestHelper.appendRandom("some-service"), + 6767, 6767, + "barpod"); + service = createAndAssert(stub); + assertServiceEquals(stub, service); + + IService otherStub = helper.stubService(client, + project.getNamespaceName(), + IntegrationTestHelper.appendRandom("some-other-service"), + 8787, 8787, + "foopod"); + otherService = createAndAssert(otherStub); + + bc = client.create( + helper.stubBuildConfig(client, + project.getNamespaceName(), + "test", + "https://github.com/openshift/origin.git", + Collections.emptyMap())); + LOG.debug(String.format("Created bc: %s", bc.getName())); + LOG.debug(String.format("Trying to delete bc: %s", bc.getName())); + client.delete(bc); + bc = null; + } finally { + helper.cleanUpResources(client, service, otherService, bc); + } + } + + private R createAndAssert(R stub) { + // given + int numberOfServices = client.list(stub.getKind(), project.getNamespaceName()).size(); + // when + R resource = client.create(stub); + // then + List resources = client.list(stub.getKind(), project.getNamespaceName()); + assertNotNull(resources); + int newNumberOfServices = resources.size(); + assertEquals(numberOfServices + 1, newNumberOfServices); + assertTrue(resources.contains(resource)); + R queriedResource = client.get(stub.getKind(), stub.getName(), stub.getNamespaceName()); + assertEquals("Expected to get the service with the correct name", + stub.getName(), + queriedResource.getName()); + return resource; + } + + private void assertServiceEquals(IService stub, IService service) { + assertEquals(stub.getName(), service.getName()); + assertEquals(stub.getNamespace(), service.getNamespace()); + assertEquals(stub.getSelector(), service.getSelector()); + assertEquals(stub.getPort(), service.getPort()); + } + + @Test + public void shouldHaveOpenShiftMasterVersion() { + // given + // when + int osMajorVersion = client.getOpenShiftMajorVersion(); + // then + assertThat(osMajorVersion).isNotEqualTo(KubernetesVersion.NO_VERSION); + } + + @Test + public void shouldDetectCorrectOpenShiftMasterVersion() { + // given + String osVersion = client.getOpenshiftMasterVersion(); + String k8Version = client.getKubernetesMasterVersion(); + // when + int osMajorVersion = client.getOpenShiftMajorVersion(); + // then + assertOpenShiftVersion(osMajorVersion, osVersion, k8Version); + } + + private void assertOpenShiftVersion(int osMajorVersion, String osVersion, String k8Version) { + if (StringUtils.length(osVersion) > 1) { + int guessedOSMajorVersion = Integer.parseInt(osVersion.charAt(1) + ""); + assertThat(osMajorVersion).isEqualTo(guessedOSMajorVersion); + } else if (!StringUtils.isEmpty(k8Version)) { + int guessedOSMajorVersion = KubernetesVersion.NO_VERSION; + int guessedK8MinorVersion = Integer.parseInt(k8Version.split("\\.")[1]); + if (guessedK8MinorVersion <= 11) { + guessedOSMajorVersion = 3; + } else { + guessedOSMajorVersion = 4; + } + assertThat(osMajorVersion).isEqualTo(guessedOSMajorVersion); + } else { + fail("Could not guess OpenShift version, neither /version/openshift nor /version are available."); + } + } } diff --git a/src/test/java/com/openshift/internal/restclient/DefaultClientTest.java b/src/test/java/com/openshift/internal/restclient/DefaultClientTest.java index bb550f66..a6ca35cf 100644 --- a/src/test/java/com/openshift/internal/restclient/DefaultClientTest.java +++ b/src/test/java/com/openshift/internal/restclient/DefaultClientTest.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2014-2016 Red Hat, Inc. + * Copyright (c) 2014-2019 Red Hat, Inc. * Distributed under license by Red Hat, Inc. All rights reserved. * This program is made available under the terms of the * Eclipse Public License v1.0 which accompanies this distribution, @@ -8,246 +8,305 @@ * Contributors: * Red Hat, Inc. - initial API and implementation ******************************************************************************/ + package com.openshift.internal.restclient; -import static org.fest.assertions.Assertions.assertThat; -import static org.junit.Assert.assertEquals; -import static org.mockito.Matchers.*; -import static org.mockito.Mockito.*; +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.ArgumentMatchers.anyBoolean; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.Mockito.doReturn; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.spy; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; -import java.net.MalformedURLException; +import java.io.IOException; import java.net.URL; -import java.security.cert.X509Certificate; -import java.util.HashMap; -import java.util.List; +import java.util.AbstractMap; +import java.util.Arrays; import java.util.Map; +import org.apache.commons.io.output.ByteArrayOutputStream; import org.jboss.dmr.ModelNode; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; -import org.mockito.runners.MockitoJUnitRunner; +import org.mockito.ArgumentCaptor; +import org.mockito.junit.MockitoJUnitRunner; +import com.openshift.internal.restclient.DefaultClient.HttpMethod; +import com.openshift.internal.restclient.authorization.AuthorizationContext; import com.openshift.internal.restclient.model.Pod; +import com.openshift.internal.restclient.okhttp.OpenShiftRequestBuilder; import com.openshift.restclient.IResourceFactory; import com.openshift.restclient.ResourceKind; -import com.openshift.restclient.authorization.BasicAuthorizationStrategy; -import com.openshift.restclient.authorization.IAuthorizationStrategy; -import com.openshift.restclient.authorization.TokenAuthorizationStrategy; -import com.openshift.restclient.http.IHttpClient; -import com.openshift.restclient.model.IPod; +import com.openshift.restclient.api.ITypeFactory; +import com.openshift.restclient.model.JSONSerializeable; + +import okhttp3.Request.Builder; +import okhttp3.RequestBody; +import okio.Buffer; +import okio.BufferedSink; +import okio.Okio; +import okio.Source; /** * @author Jeff Cantrill * @author Andre Dietisheim */ @RunWith(MockitoJUnitRunner.class) -public class DefaultClientTest extends TypeMapperFixture{ - - private static final String VERSION = "v1"; - - private DefaultClient client; -// private IHttpClient httpClient; - private ModelNode response; - private Pod podFrontEnd; - private Pod podBackEnd; - private IResourceFactory factory; - private URL baseUrl; - - - @Before - public void setUp() throws Exception{ - super.setUp(); - this.baseUrl = new URL("http://myopenshift"); - givenAClient(); - givenAPodList(); - when(getHttpClient().get(eq(new URL("http://myopenshift/api/v1/namespaces/aNamespace/pods")), anyInt())) - .thenReturn(response.toJSONString(false)); - } - - private void givenAClient() throws MalformedURLException{ - factory = new ResourceFactory(null); - client = new DefaultClient(baseUrl, getHttpClient(), null, factory, null, null, getApiTypeMapper(), IHttpClient.NO_TIMEOUT); - } - - private void givenAPodList(){ - this.podFrontEnd = factory.create(VERSION, ResourceKind.POD); - podFrontEnd.setName("frontend"); - podFrontEnd.setNamespace("aNamespace"); - podFrontEnd.addLabel("name", "frontend"); - podFrontEnd.addLabel("env", "production"); - - this.podBackEnd = factory.create(VERSION, ResourceKind.POD); - podBackEnd.setName("backend"); - podBackEnd.setNamespace("aNamespace"); - podBackEnd.addLabel("name", "backend"); - podBackEnd.addLabel("env", "production"); - - Pod otherPod = factory.create(VERSION, ResourceKind.POD); - otherPod.setName("other"); - otherPod.setNamespace("aNamespace"); - otherPod.addLabel("env", "production"); - - this.response = new ModelNode(); - response.get("apiVersion").set(VERSION); - response.get("kind").set("PodList"); - ModelNode items = response.get("items"); - items.add(podFrontEnd.getNode()); - items.add(otherPod.getNode()); - items.add(podBackEnd.getNode()); - } - - @SuppressWarnings("serial") - @Test - public void testListResourceFilteringWithExactMatch() throws Exception { - Map labels = new HashMap(){{ - put("name","backend"); - put("env","production"); - }}; - List pods = client.list(ResourceKind.POD, "aNamespace", labels); - assertEquals("Expected 1 pod to be returned", 1, pods.size()); - assertEquals("Expected the frontend pod", podBackEnd, pods.get(0)); - } - - @Test - public void testSetAuthStrategySetsIHttpClientAuthStrategy(){ - IAuthorizationStrategy strategy = mock(IAuthorizationStrategy.class); - client.setAuthorizationStrategy(strategy ); - - verify(getHttpClient()).setAuthorizationStrategy(eq(strategy)); - } - - @Test - public void testListResourceFilteringNoMatch() throws Exception { - Map labels = new HashMap(); - labels.put("foo", "bar"); - List pods = client.list(ResourceKind.POD, "aNamespace", labels); - assertEquals("Expected no pod to be returned", 0, pods.size()); - } - - @SuppressWarnings("serial") - @Test - public void testListResourceFilteringWithPartialMatch() throws Exception { - Map labels = new HashMap(){{ - put("name","frontend"); - }}; - List pods = client.list(ResourceKind.POD, "aNamespace", labels); - assertEquals("Expected 1 pod to be returned", 1, pods.size()); - assertEquals("Expected the backend pod", podFrontEnd, pods.get(0)); - } - - @SuppressWarnings("serial") - @Test - public void testListResourceFilteringSingleLabel() throws Exception { - Map labels = new HashMap(){{ - put("env","production"); - }}; - List pods = client.list(ResourceKind.POD, "aNamespace", labels); - assertEquals("Expected all pods to be returned", 3, pods.size()); - } - - @Test - public void clientShouldEqualClientWithSameUrl() throws Exception { - assertThat(new DefaultClient(baseUrl, null, null, null)) - .isEqualTo(new DefaultClient(baseUrl, null, null, null)); - } - - @Test - public void clientShouldNotEqualClientWithDifferentUrl() throws Exception { - assertThat(new DefaultClient(baseUrl, null, null, null)) - .isNotEqualTo(new DefaultClient(new URL("http://localhost:8443"), null, null, null)); - } - - public void client_should_equal_client_with_same_TokenAuthStrategy_with_different_token() throws Exception { - DefaultClient tokenClientOne = new DefaultClient(baseUrl, null, null, null); - tokenClientOne.setAuthorizationStrategy(new TokenAuthorizationStrategy("tokenOne", "aUser")); - - DefaultClient tokenClientTwo = new DefaultClient(baseUrl, null, null, null); - tokenClientTwo.setAuthorizationStrategy(new TokenAuthorizationStrategy("tokenTwo", "aUser")); - - assertThat(tokenClientOne).isEqualTo(tokenClientTwo); - } - - @Test - public void client_should_not_equal_client_with_same_TokenAuthStrategy_with_different_username() throws Exception { - DefaultClient tokenClientOne = new DefaultClient(baseUrl, null, null, null); - tokenClientOne.setAuthorizationStrategy(new TokenAuthorizationStrategy("aToken", "aUser")); - - DefaultClient tokenClientTwo = new DefaultClient(baseUrl, null, null, null); - tokenClientTwo.setAuthorizationStrategy(new TokenAuthorizationStrategy("aToken", "differentUser")); - - assertThat(tokenClientOne).isNotEqualTo(tokenClientTwo); - } - - @Test - public void client_should_not_equal_client_with_same_BasicAuthStrategy_with_different_username() throws Exception { - DefaultClient tokenClientOne = new DefaultClient(baseUrl, null, null, null); - tokenClientOne.setAuthorizationStrategy(new BasicAuthorizationStrategy("aUser", "aPassword", "aToken")); - - DefaultClient tokenClientTwo = new DefaultClient(baseUrl, null, null, null); - tokenClientTwo.setAuthorizationStrategy(new BasicAuthorizationStrategy("differentUser", "aPassword", "aToken")); - - assertThat(tokenClientOne).isNotEqualTo(tokenClientTwo); - } - - @Test - public void client_should_equal_client_with_same_BasicAuthStrategy_with_different_password_and_different_token() throws Exception { - DefaultClient tokenClientOne = new DefaultClient(baseUrl, null, null, null); - tokenClientOne.setAuthorizationStrategy(new BasicAuthorizationStrategy("aUser", "aPassword", "aToken")); - - DefaultClient tokenClientTwo = new DefaultClient(baseUrl, null, null, null); - tokenClientTwo.setAuthorizationStrategy(new BasicAuthorizationStrategy("aUser", "differentPassword", "differentToken")); - - assertThat(tokenClientOne).isEqualTo(tokenClientTwo); - } - - @Test - public void tokenAuthClient_should_equal_basicAuthclient_with_same_username() throws Exception { - DefaultClient tokenClient = new DefaultClient(baseUrl, null, null, null); - tokenClient.setAuthorizationStrategy(new TokenAuthorizationStrategy("aToken", "aUser")); - - DefaultClient basicAuthClient = new DefaultClient(baseUrl, null, null, null); - basicAuthClient.setAuthorizationStrategy(new BasicAuthorizationStrategy("aUser", "aPassword", "differentToken")); - - assertThat(tokenClient).isEqualTo(basicAuthClient); - } - - @Test - public void tokenAuthClient_should_not_equal_basicAuthclient_with_different_username() throws Exception { - DefaultClient tokenClient = new DefaultClient(baseUrl, null, null, null); - tokenClient.setAuthorizationStrategy(new TokenAuthorizationStrategy("aToken", "aUser")); - - DefaultClient basicAuthClient = new DefaultClient(baseUrl, null, null, null); - basicAuthClient.setAuthorizationStrategy(new BasicAuthorizationStrategy("differentUser", "aPassword", "aToken")); - - assertThat(tokenClient).isNotEqualTo(basicAuthClient); - } - - @Test - public void basicAuthClient_should_equal_tokenClient_with_same_username() throws Exception { - DefaultClient basicAuthClient = new DefaultClient(baseUrl, null, null, null); - basicAuthClient.setAuthorizationStrategy(new BasicAuthorizationStrategy("aUser", "aPassword", "differentToken")); - - DefaultClient tokenClient = new DefaultClient(baseUrl, null, null, null); - tokenClient.setAuthorizationStrategy(new TokenAuthorizationStrategy("aToken", "aUser")); - - assertThat(basicAuthClient).isEqualTo(tokenClient); - } - - @Test - public void clientShouldEqualClientWithDifferentCert() throws Exception { - X509Certificate certOne = mock(X509Certificate.class); - when(certOne.getSigAlgName()).thenReturn("sig1"); - DefaultClient certClientOne = new DefaultClient(baseUrl, null, null, null, "cert1", certOne, IHttpClient.NO_TIMEOUT); - - X509Certificate certTwo = mock(X509Certificate.class); - when(certTwo.getSigAlgName()).thenReturn("sig2"); - DefaultClient certClientTwo = new DefaultClient(baseUrl, null, null, null, "cert2", certTwo, IHttpClient.NO_TIMEOUT); - - assertThat(certClientTwo).isEqualTo(certClientOne); - } - - - +public class DefaultClientTest extends TypeMapperFixture { + + private static final String VERSION = "v1"; + + private DefaultClient client; + private ModelNode response; + private Pod podFrontEnd; + private Pod podBackEnd; + private IResourceFactory factory; + private URL baseUrl; + private String podsResourceUrl = TypeMapperFixture.base + "/api/v1/namespaces/aNamespace/pods"; + private String podFrontEndResourceUrl = TypeMapperFixture.base + "/api/v1/namespaces/aNamespace/pods/frontend"; + + @Before + public void setUp() throws Exception { + super.setUp(); + this.baseUrl = new URL(TypeMapperFixture.base); + givenAClient(); + givenAPodListResponse(); + getHttpClient().whenRequestTo(podsResourceUrl) + .thenReturn(responseOf(response.toJSONString(false))); + } + + private void givenAClient() throws Exception { + this.client = (DefaultClient) getIClient(); + this.factory = client.getResourceFactory(); + } + + private void givenAPodListResponse() { + this.response = new ModelNode(); + response.get("apiVersion").set(VERSION); + response.get("kind").set("PodList"); + ModelNode items = response.get("items"); + + this.podFrontEnd = givenAPod("frontend", "aNamespace", + new AbstractMap.SimpleEntry("name", "frontend"), + new AbstractMap.SimpleEntry("env", "production")); + items.add(podFrontEnd.getNode()); + + Pod otherPod = givenAPod("other", "aNamespace", + new AbstractMap.SimpleEntry("env", "production")); + items.add(otherPod.getNode()); + + this.podBackEnd = givenAPod("backend", "aNamespace", + new AbstractMap.SimpleEntry("name", "backend"), + new AbstractMap.SimpleEntry("env", "production")); + items.add(podBackEnd.getNode()); + } + + @SafeVarargs + private final Pod givenAPod(final String name, final String namespace, final Map.Entry... labels) { + Pod pod = factory.create(VERSION, ResourceKind.POD); + pod.setName(name); + pod.setNamespace(namespace); + if (labels != null) { + Arrays.stream(labels).forEach(entry -> pod.addLabel(entry.getKey(), entry.getValue())); + } + return pod; + } + + private DefaultClient givenClient(URL baseUrl, String token, String user) { + DefaultClient client = new DefaultClient(baseUrl, getHttpClient(), null, null, + new AuthorizationContext(token, user, null)); + return client; + } + + private ITypeFactory givenTypeFactory() { + return mock(ITypeFactory.class); + } + + private JSONSerializeable givenJsonPayload(String string) { + JSONSerializeable json = mock(JSONSerializeable.class); + when(json.toJson(anyBoolean())).thenReturn(string); + return json; + } + + @Test + public void clientShouldEqualClientWithSameUrl() throws Exception { + assertThat(givenClient(baseUrl, null, null)).isEqualTo(givenClient(baseUrl, null, null)); + } + + @Test + public void clientShouldNotEqualClientWithDifferentUrl() throws Exception { + assertThat(givenClient(baseUrl, null, null)) + .isNotEqualTo(givenClient(new URL("http://localhost:8443"), null, null)); + } + + @Test + public void client_should_equal_client_with_same_user_with_different_token() throws Exception { + DefaultClient tokenClientOne = givenClient(baseUrl, "tokenOne", "aUser"); + + DefaultClient tokenClientTwo = givenClient(baseUrl, "tokenTwo", "aUser"); + + assertThat(tokenClientOne).isEqualTo(tokenClientTwo); + } + + @Test + public void client_should_not_equal_client_with_different_username() throws Exception { + DefaultClient tokenClientOne = givenClient(baseUrl, "aToken", "aUser"); + + DefaultClient tokenClientTwo = givenClient(baseUrl, "aToken", "differentUser"); + + assertThat(tokenClientOne).isNotEqualTo(tokenClientTwo); + } + + @Test + public void should_use_payload_in_delete_request() throws IOException { + // given + DefaultClient client = spy(this.client); + + Builder builder = givenRequestBuilder(client); + ArgumentCaptor builderCaptor = ArgumentCaptor.forClass(RequestBody.class); + String payload = "{prop1:\"val1\"}"; + + // when + client.execute(givenTypeFactory(), HttpMethod.DELETE.toString(), + ResourceKind.BUILD, null, null, null, null, + givenJsonPayload(payload), null); + + // then + String requestBodyPayload = getPayload(builder, builderCaptor); + assertThat(requestBodyPayload).isEqualTo(payload); + } + + @Test + public void should_use_payload_in_post_request() throws IOException { + // given + DefaultClient client = spy(this.client); + + Builder builder = givenRequestBuilder(client); + ArgumentCaptor builderCaptor = ArgumentCaptor.forClass(RequestBody.class); + String payload = "{prop1:\"val1\"}"; + + // when + client.execute(givenTypeFactory(), HttpMethod.POST.toString(), + ResourceKind.BUILD, null, null, null, null, + givenJsonPayload(payload), null); + + // then + String requestBodyPayload = getPayload(builder, builderCaptor); + assertThat(requestBodyPayload).isEqualTo(payload); + } + + @Test + public void should_use_payload_in_put_request() throws IOException { + // given + DefaultClient client = spy(this.client); + + Builder builder = givenRequestBuilder(client); + ArgumentCaptor builderCaptor = ArgumentCaptor.forClass(RequestBody.class); + String payload = "{prop1:\"val1\"}"; + + // when + client.execute(givenTypeFactory(), HttpMethod.PUT.toString(), + ResourceKind.BUILD, null, null, null, null, + givenJsonPayload(payload), null); + + // then + String requestBodyPayload = getPayload(builder, builderCaptor); + assertThat(requestBodyPayload).isEqualTo(payload); + } + + @Test + public void should_not_use_payload_in_get_request() throws IOException { + // given + DefaultClient client = spy(this.client); + + Builder builder = givenRequestBuilder(client); + ArgumentCaptor bodyCaptor = ArgumentCaptor.forClass(RequestBody.class); + + // when + client.execute(givenTypeFactory(), HttpMethod.GET.toString(), + ResourceKind.BUILD, null, null, null, null, + givenJsonPayload("{prop1:\"val1\"}"), null); + + // then + verify(builder).method(anyString(), bodyCaptor.capture()); + assertThat(bodyCaptor.getValue()).isNull(); + } + + @Test + public void should_not_use_payload_in_head_request() throws IOException { + // given + DefaultClient client = spy(this.client); + + Builder builder = givenRequestBuilder(client); + ArgumentCaptor bodyCaptor = ArgumentCaptor.forClass(RequestBody.class); + + // when + client.execute(givenTypeFactory(), HttpMethod.HEAD.toString(), + ResourceKind.BUILD, null, null, null, null, + givenJsonPayload("{prop1:\"val1\"}"), null); + + // then + verify(builder).method(anyString(), bodyCaptor.capture()); + assertThat(bodyCaptor.getValue()).isNull(); + } + + @Test + public void should_not_send_resource_payload_when_deleting() throws IOException { + // given + DefaultClient client = spy(this.client); + getHttpClient() + .whenRequestTo(podFrontEndResourceUrl) + .thenReturn(responseOf(response.toJSONString(false))); + + Builder builder = givenRequestBuilder(client); + ArgumentCaptor bodyCaptor = ArgumentCaptor.forClass(RequestBody.class); + + // when + client.delete(this.podFrontEnd); + + // then + verify(builder).method(anyString(), bodyCaptor.capture()); + assertThat(bodyCaptor.getValue().contentLength()).isEqualTo(0); + } + + @Test + public void should_transform_input_to_empty_string_when_payload_is_null() throws IOException { + // given + DefaultClient client = spy(this.client); + RequestBody payload = client.getPayload(null, HttpMethod.DELETE.name()); + + BufferedSink bufferedSink = mock(BufferedSink.class); + ArgumentCaptor bodyCaptor = ArgumentCaptor.forClass(Source.class); + + // when + payload.writeTo(bufferedSink); + + // then + verify(bufferedSink).writeAll(bodyCaptor.capture()); + String actualPayload = Okio.buffer(bodyCaptor.getValue()).readUtf8(); + + assertThat(actualPayload).isEqualTo(""); + } + + private String getPayload(Builder builder, ArgumentCaptor builderCaptor) throws IOException { + verify(builder).method(anyString(), builderCaptor.capture()); + RequestBody requestBody = builderCaptor.getValue(); + assertThat(requestBody).isNotNull(); + Buffer buffer = new Buffer(); + requestBody.writeTo(buffer); + ByteArrayOutputStream out = new ByteArrayOutputStream(); + buffer.copyTo(out); + return new String(out.toByteArray()); + } + + private Builder givenRequestBuilder(DefaultClient client) { + Builder builder = spy(new Builder()); + final OpenShiftRequestBuilder osBuilder = spy(new OpenShiftRequestBuilder(builder)); + doReturn(osBuilder).when(client).newRequestBuilder(); + return builder; + } } diff --git a/src/test/java/com/openshift/internal/restclient/IntegrationTestHelper.java b/src/test/java/com/openshift/internal/restclient/IntegrationTestHelper.java index a59bdfef..7af793ae 100644 --- a/src/test/java/com/openshift/internal/restclient/IntegrationTestHelper.java +++ b/src/test/java/com/openshift/internal/restclient/IntegrationTestHelper.java @@ -1,137 +1,539 @@ /******************************************************************************* - * Copyright (c) 2015 Red Hat, Inc. Distributed under license by Red Hat, Inc. + * Copyright (c) 2015-2019 Red Hat, Inc. Distributed under license by Red Hat, Inc. * All rights reserved. This program is made available under the terms of the * Eclipse Public License v1.0 which accompanies this distribution, and is * available at http://www.eclipse.org/legal/epl-v10.html * * Contributors: Red Hat, Inc. ******************************************************************************/ + package com.openshift.internal.restclient; -import java.io.FileNotFoundException; +import static org.junit.Assert.fail; + import java.io.IOException; -import java.net.MalformedURLException; -import java.net.URL; +import java.security.cert.CertificateException; +import java.security.cert.X509Certificate; +import java.util.Collection; +import java.util.Collections; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Optional; import java.util.Properties; import java.util.Random; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.Future; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.TimeoutException; +import java.util.function.Supplier; +import java.util.stream.Collectors; +import java.util.stream.Stream; +import javax.net.ssl.SSLContext; +import javax.net.ssl.SSLSocketFactory; +import javax.net.ssl.TrustManager; +import javax.net.ssl.X509TrustManager; +import org.apache.commons.lang.ArrayUtils; +import org.apache.commons.lang.StringUtils; +import org.jboss.dmr.ModelNode; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import com.openshift.internal.restclient.model.ModelNodeBuilder; +import com.openshift.internal.restclient.model.Pod; +import com.openshift.internal.restclient.model.ReplicationController; +import com.openshift.internal.restclient.model.Service; +import com.openshift.internal.restclient.model.build.BuildConfigBuilder; +import com.openshift.internal.restclient.model.properties.ResourcePropertyKeys; import com.openshift.restclient.ClientBuilder; import com.openshift.restclient.IClient; +import com.openshift.restclient.IWatcher; import com.openshift.restclient.NoopSSLCertificateCallback; -import com.openshift.restclient.authorization.AuthorizationClientFactory; -import com.openshift.restclient.authorization.BasicAuthorizationStrategy; -import com.openshift.restclient.authorization.IAuthorizationClient; -import com.openshift.restclient.authorization.IAuthorizationContext; -import com.openshift.restclient.authorization.IAuthorizationDetails; -import com.openshift.restclient.authorization.TokenAuthorizationStrategy; +import com.openshift.restclient.NotFoundException; +import com.openshift.restclient.ResourceKind; +import com.openshift.restclient.authorization.ResourceForbiddenException; +import com.openshift.restclient.capability.IBinaryCapability; +import com.openshift.restclient.images.DockerImageURI; +import com.openshift.restclient.model.IBuildConfig; +import com.openshift.restclient.model.IDeploymentConfig; +import com.openshift.restclient.model.IPod; +import com.openshift.restclient.model.IProject; +import com.openshift.restclient.model.IReplicationController; import com.openshift.restclient.model.IResource; +import com.openshift.restclient.model.IService; +import com.openshift.restclient.model.deploy.DeploymentTriggerType; -import static org.junit.Assert.fail; +import okhttp3.OkHttpClient; + +public class IntegrationTestHelper implements ResourcePropertyKeys { + + public static final String IMAGE_HELLO_OPENSHIFT_ALPINE = "adietish/hello-openshift-alpine:0.3"; + public static final String IMAGE_HELLO_OPENSHIFT = "openshift/hello-openshift"; + + public static final String POD_NAME_DEFAULT = "test-pod"; + + public static final long TEST_TIMEOUT = 6 * 1000; + public static final long TEST_LONG_TIMEOUT = 3 * 60 * 1000; + + public static final long MILLISECONDS_PER_SECOND = 1000; + public static final long MILLISECONDS_PER_MIN = MILLISECONDS_PER_SECOND * 60; + + private static final String KEY_INTEGRATION_TEST_PROJECT = "integrationtest.project"; + private static final String KEY_SERVER_URL = "serverURL"; + private static final String KEY_PASSWORD = "default.clusteradmin.password"; + private static final String KEY_USER = "default.clusteradmin.user"; + private static final String KEY_OPENSHIFT_LOCATION = "ocbinary.location"; + + private static final String INTEGRATIONTEST_PROPERTIES = "/openshiftv3IntegrationTest.properties"; + + private static final Logger LOG = LoggerFactory.getLogger(IntegrationTestHelper.class); + private static final String POD_NAME_DEPLOY = "deploy"; + private static final String POD_DOCKER_REGISTRY = "docker-registry"; + private static final String DEFAULT_PROJECT = "default"; + private static final String OPENSHIFT4_REGISTRY_PROJECT = "openshift-image-registry"; + private static final String POD_IMAGE_REGISTRY = "image-registry"; + + private final Properties prop; + + public IntegrationTestHelper() { + this.prop = loadProperties(INTEGRATIONTEST_PROPERTIES); + } + + public IClient createClient() { + return new ClientBuilder(getServer()).build(); + } + + private String getServer() { + return prop.getProperty(KEY_SERVER_URL); + } + + public IClient createClientForBasicAuth() { + return new ClientBuilder(getServer()) + .withUserName(getDefaultClusterAdminUser()) + .withPassword(getDefaultClusterAdminPassword()) + .build(); + } + + public String getIntegrationTestNamespace() { + return prop.getProperty(KEY_INTEGRATION_TEST_PROJECT); + } + + public static String getDefaultNamespace() { + return DEFAULT_PROJECT; + } + + public IProject createProject(String name, IClient client) { + IResource request = client.getResourceFactory().stub(ResourceKind.PROJECT_REQUEST, name); + return (IProject) client.create(request); + } + + public IProject getOrCreateIntegrationTestProject(IClient client) { + return getOrCreateProject(getIntegrationTestNamespace(), client); + } + + /** + * Returns the existing project if it is present. If not, it'll create a new project and return + * it. + * + * @param name the name of the project + * @param client the client to be used + * @return the existing/new project + */ + public IProject getOrCreateProject(String name, IClient client) { + return getOrCreateResource( + () -> client.get(ResourceKind.PROJECT, name, ""), + () -> createProject(name, client)); + } + + private R getOrCreateResource(Supplier supplier, Supplier factory) { + R resource = null; + try { + resource = supplier.get(); + } catch (NotFoundException | ResourceForbiddenException e) { + // OS3: NotFoundException + // OS4: ResourceForbiddenException + resource = factory.get(); + } + return resource; + } + + public static String appendRandom(String string) { + return String.format("%s-%s", string, new Random().nextInt(9999)); + } + + public static boolean isDockerRegistry(IPod pod, String podPrefix) { + return pod != null + && pod.getName().startsWith(podPrefix); + } + + private Optional getDockerRegistryPod(IClient client, String project, String podPrefix) { + try { + List pods = client.list(ResourceKind.POD, project); + return pods.stream() + .filter(p -> isDockerRegistry(p, podPrefix)) + .findFirst(); + } catch (ResourceForbiddenException e) { + return Optional.empty(); + } + } + + public IPod getDockerRegistryPod(IClient client) { + Optional pod = getDockerRegistryPod(client, DEFAULT_PROJECT, POD_DOCKER_REGISTRY); + if (!pod.isPresent()) { + pod = getDockerRegistryPod(client, OPENSHIFT4_REGISTRY_PROJECT, POD_IMAGE_REGISTRY); + } + return pod.orElse(null); + } + + public Collection createResources(IClient client, R... resources) { + if (ArrayUtils.isEmpty(resources)) { + return Collections.emptyList(); + } + return Stream.of(resources) + .map(r -> client.create(r)) + .filter(r -> r != null) + .collect(Collectors.toList()); + } + + public R createResource(IClient client, R resource) { + if (resource == null) { + return null; + } + return client.create(resource); + } + + public IPod getPod(IClient client, String namespace, String name) { + return client.get(ResourceKind.POD, name, namespace); + } + + public IPod createPod(IClient client, String namespace, String name, String image) { + return client.create(stubPod(client, namespace, name, image)); + } + + public IPod getOrCreatePod(IClient client, String namespace, String image) { + return getOrCreatePod(client, namespace, POD_NAME_DEFAULT, image); + } + + public IPod getOrCreatePod(IClient client, String namespace, String name, String image) { + return getOrCreateResource( + () -> getPod(client, namespace, name), + () -> createPod(client, namespace, name, image)); + } + + public boolean waitForPodReady(IClient client, String namespace, String name, int timeout) throws InterruptedException, ExecutionException, TimeoutException { + ExecutorService executor = Executors.newSingleThreadExecutor(); + Future podReady = executor.submit(() -> { + IPod pod = null; + try { + while (pod == null + || !pod.isReady()) { + pod = getPod(client, namespace, name); + Thread.sleep(2 * 1000); + } + } catch (InterruptedException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + return pod.isReady(); + }); + return podReady.get(timeout, TimeUnit.SECONDS); + } + + /** + * Stub a pod definition to the openshift/hello-openshift image for purposes of + * testing. + * + * @param client the client to use + * @param namespace the namespace to stub the pod for + * @param name the name of the pod + * + * @return a pod definition that needs to be further created using the client + */ + private IPod stubPod(IClient client, String namespace, String name, String image) { + ModelNode builder = new ModelNodeBuilder().set(ResourcePropertyKeys.KIND, ResourceKind.POD) + .set(ResourcePropertyKeys.METADATA_NAME, name) + .set(ResourcePropertyKeys.METADATA_NAMESPACE, namespace) + .add("spec.containers", + new ModelNodeBuilder().set(ResourcePropertyKeys.NAME, name) + .set("image", image) + .add("ports", new ModelNodeBuilder().set("containerPort", 8080).set("protocol", "TCP"))) + .build(); + return new Pod(builder, client, new HashMap<>()); + } + + public IDeploymentConfig stubDeploymentConfig(IClient client, String namespace, String name) { + IDeploymentConfig dc = (IDeploymentConfig) new ResourceFactory(client).stubKind(ResourceKind.DEPLOYMENT_CONFIG, Optional.of(name), Optional.of(namespace)); + dc.setReplicas(1); + dc.setReplicaSelector("foo", "bar"); + dc.addContainer(dc.getName(), + new DockerImageURI("openshift/hello-openshift"), + new HashSet<>(), + Collections.emptyMap(), + Collections.emptyList()); + dc.addTrigger(DeploymentTriggerType.CONFIG_CHANGE); + return dc; + } + + public IReplicationController stubReplicationController(IClient client, String namespace, String name) { + IReplicationController rc = new ResourceFactory(client).create("v1", ResourceKind.REPLICATION_CONTROLLER); + ((ReplicationController) rc).setName(name); + ((ReplicationController) rc).setNamespace(namespace); + rc.setReplicas(1); + rc.setReplicaSelector("foo", "bar"); + rc.addContainer(rc.getName(), + new DockerImageURI("openshift/hello-openshift"), + new HashSet<>(), + Collections.emptyMap(), + Collections.emptyList()); + return rc; + } + + public IBuildConfig stubBuildConfig(IClient client, String namespace, String name, String gitUrl, Map labels) { + BuildConfigBuilder builder = new BuildConfigBuilder(client); + builder.named(name) + .inNamespace(namespace); + if (!StringUtils.isEmpty(gitUrl)) { + builder + .fromGitSource() + .fromGitUrl(gitUrl) + .end(); + } + builder.usingSourceStrategy() + .fromDockerImage("centos/ruby-22-centos7:latest") + .end() + .toImageStreamTag("ruby-hello-world:latest") + .withLabels(labels); + return builder.build(); + } + + public IService stubService(IClient client, String namespace, String name, int remotePort, int port, String selector) { + Service service = client.getResourceFactory().create("v1", ResourceKind.SERVICE); + service.setName(name); + service.setNamespace(namespace); + service.setTargetPort(remotePort); + service.setPort(port); + service.setSelector("name", selector); + return service; + } + + /** + * Loads the properties from the given {@code propertyFileName}, then overrides + * from the System properties if any was given (this is a convenient way to + * override the default settings and avoid conflicting with the properties file + * in git) + * + * @return the properties to use in the test + * @throws IOException an io exception + */ + private Properties loadProperties(final String propertyFileName) { + final Properties properties = new Properties(); + try { + properties.load(IntegrationTestHelper.class.getResourceAsStream(propertyFileName)); + } catch (IOException e) { + e.printStackTrace(); + fail("Failed to load properties from file " + INTEGRATIONTEST_PROPERTIES + ": " + e.getMessage()); + } + overrideIfExists(properties, KEY_SERVER_URL); + overrideIfExists(properties, KEY_INTEGRATION_TEST_PROJECT); + overrideIfExists(properties, KEY_OPENSHIFT_LOCATION); + overrideIfExists(properties, KEY_USER); + overrideIfExists(properties, KEY_PASSWORD); + return properties; + } + + private void overrideIfExists(final Properties properties, final String propertyName) { + // then override with the VM arguments (if any) + final String propertyValue = System.getProperty(propertyName); + if (propertyValue != null) { + properties.setProperty(propertyName, propertyValue); + } + } + + public String getOpenShiftLocation() { + return prop.getProperty(KEY_OPENSHIFT_LOCATION); + } + + public void setOpenShiftBinarySystemProperty() { + System.setProperty(IBinaryCapability.OPENSHIFT_BINARY_LOCATION, getOpenShiftLocation()); + } + + public String getDefaultClusterAdminUser() { + return prop.getProperty(KEY_USER); + } + + public String getDefaultClusterAdminPassword() { + return prop.getProperty(KEY_PASSWORD); + } + + public String getServerUrl() { + return getServer(); + } + + public void cleanUpResources(IClient client, R... resources) { + if (ArrayUtils.isEmpty(resources)) { + return; + } + Stream.of(resources).forEach(resource -> cleanUpResource(client, resource)); + } + + public void cleanUpResources(IClient client, Collection resources) { + if (resources == null || resources.isEmpty()) { + return; + } + resources.forEach(resource -> cleanUpResource(client, resource)); + } + + public void cleanUpResource(IClient client, R resource) { + if (client == null || resource == null) { + LOG.debug("Skipping cleanup as client to {} or resource {} are null", + client == null ? "" : client.getBaseURL(), + resource == null ? "" : resource.getName()); + return; + } + LOG.debug(String.format("Deleting resource: %s", resource)); + cleanUpResource(client, resource.getKind(), resource.getNamespaceName(), resource.getName()); + } + + public void cleanUpResource(IClient client, String kind, String namespace, String name) { + if (client == null || StringUtils.isEmpty(name) || StringUtils.isEmpty(namespace)) { + LOG.debug("Skipping cleanup as client to {} or resource {} are null", + client == null ? "" : client.getBaseURL(), + StringUtils.isEmpty(name) ? "" : name); + return; + } + try { + LOG.debug(String.format("Deleting resource: %s", name)); + client.delete(kind, namespace, name); + } catch (Exception e) { + LOG.warn("Exception deleting", e); + } + } + + /** + * Wait for the resource to exist for cases where the test is faster then the + * server in reconciling its existence; + * + * @return The resource or null if the maxWaitMillis was exceeded or the + * resource doesnt exist + */ + public IResource waitForResource(IClient client, String kind, String namespace, String name, + long maxWaitMillis) { + return waitForResource(client, kind, namespace, name, maxWaitMillis, new ReadyConditional() { + @Override + public boolean isReady(IResource resource) { + return resource != null; + } + + }); + } + + public R waitForResource(IClient client, R resource, + long maxWaitMillis, ReadyConditional conditional) { + return waitForResource(client, resource.getKind(), resource.getNamespaceName(), resource.getName(), maxWaitMillis, conditional); + } + + /** + * Wait for the resource to exist for cases where the test is faster then the + * server in reconciling its existence; + * + */ + public R waitForResource(IClient client, String kind, String namespace, String name, + long maxWaitMillis, ReadyConditional conditional) { + R resource = null; + final long timeout = System.currentTimeMillis() + maxWaitMillis; + do { + try { + resource = client.get(kind, name, namespace); + if (resource != null && conditional != null) { + if (conditional.isReady(resource)) { + return resource; + } + resource = null; + } + } catch (NotFoundException e) { + try { + Thread.sleep(1000); + } catch (InterruptedException e1) { + throw new RuntimeException(e1); + } + } + } while (resource == null && System.currentTimeMillis() <= timeout); + return resource; + } + + /** + * Interface that can evaluate a resource to determine if its ready + */ + public static interface ReadyConditional { + + /** + * + * @return true if the resource is 'ready' + */ + boolean isReady(IResource resource); + } + + public boolean waitForDisappearance(IClient client, IResource resource, long maxWaitMillis) { + final long timeout = System.currentTimeMillis() + maxWaitMillis; + do { + try { + resource = client.get(resource.getKind(), resource.getName(), resource.getNamespaceName()); + Thread.sleep(1000); + } catch (NotFoundException e) { + return true; + } catch (InterruptedException e) { + return false; + } + } while (resource == null && System.currentTimeMillis() <= timeout); + return false; + } + + public void stopWatcher(IWatcher watcher) { + if (watcher != null) { + watcher.stop(); + } + } + + public boolean isDeployPod(IPod pod) { + return pod.getName().endsWith(POD_NAME_DEPLOY); + } + + public OkHttpClient createTrustAllOkHttpClient() { + try { + TrustManager trustAllManager = new TrustAllTrustManager(); + final TrustManager[] trustAllCerts = new TrustManager[] { trustAllManager }; + final SSLContext sslContext = SSLContext.getInstance("SSL"); + sslContext.init(null, trustAllCerts, new java.security.SecureRandom()); + final SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory(); + + return new OkHttpClient.Builder() + .sslSocketFactory(sslSocketFactory, (X509TrustManager) trustAllManager) + .hostnameVerifier(new NoopSSLCertificateCallback()) + .build(); + + } catch (Exception e) { + throw new RuntimeException(e); + } + } + + private static class TrustAllTrustManager implements X509TrustManager { + @Override + public void checkClientTrusted(java.security.cert.X509Certificate[] chain, String authType) + throws CertificateException { + } + + @Override + public void checkServerTrusted(java.security.cert.X509Certificate[] chain, String authType) + throws CertificateException { + } -/** - * @author Jeff Cantrill - */ -public class IntegrationTestHelper { - - private static final String KEY_DEFAULT_PROJECT = "default.project"; - private static final String KEY_SERVER_URL = "serverURL"; - private static final String KEY_PASSWORD = "default.clusteradmin.password"; - private static final String KEY_USER = "default.clusteradmin.user"; - private static final String KEY_OPENSHIFT_LOCATION = "default.openshift.location"; - - private static final String INTEGRATIONTEST_PROPERTIES = "/openshiftv3IntegrationTest.properties"; - - private static final Logger LOG = LoggerFactory.getLogger(IntegrationTestHelper.class); - - private final Properties prop; - - public IntegrationTestHelper() { - this.prop = loadProperties(INTEGRATIONTEST_PROPERTIES); - } - - public IClient createClient(){ - return new ClientBuilder(prop.getProperty(KEY_SERVER_URL)).build(); - } - - public IClient createClientForBasicAuth() { - IClient client = createClient(); - final String user = getDefaultClusterAdminUser(); - final String password = getDefaultClusterAdminPassword(); - client.setAuthorizationStrategy(new BasicAuthorizationStrategy(user, password, "")); - IAuthorizationClient authClient = new AuthorizationClientFactory().create(client); - IAuthorizationContext context = authClient.getContext(client.getBaseURL().toString()); - client.setAuthorizationStrategy(new TokenAuthorizationStrategy(context.getToken())); - return client; - } - - public String getDefaultNamespace(){ - return prop.getProperty(KEY_DEFAULT_PROJECT); - } - - public String generateNamespace() { - return String.format("%s-%s",getDefaultNamespace(), new Random().nextInt(9999)); - } - - /** - * Loads the properties from the given {@code propertyFileName}, then - * overrides from the System properties if any was given (this is a convenient way to - * override the default settings and avoid conflicting with the properties file in git) - * - * @return the properties to use in the test - * @throws IOException - */ - private static Properties loadProperties(final String propertyFileName) { - final Properties properties = new Properties(); - try { - properties.load(IntegrationTestHelper.class.getResourceAsStream(propertyFileName)); - } catch (IOException e) { - e.printStackTrace(); - fail("Failed to load properties from file " + INTEGRATIONTEST_PROPERTIES + ": " + e.getMessage()); - } - overrideIfExists(properties, KEY_SERVER_URL); - overrideIfExists(properties, KEY_DEFAULT_PROJECT); - overrideIfExists(properties, KEY_OPENSHIFT_LOCATION); - overrideIfExists(properties, KEY_USER); - overrideIfExists(properties, KEY_PASSWORD); - return properties; - } - - - private static void overrideIfExists(final Properties properties, final String propertyName){ - // then override with the VM arguments (if any) - final String propertyValue = System.getProperty(propertyName); - if (propertyValue != null) { - properties.setProperty(propertyName, propertyValue); - } - } - - public static void cleanUpResource(IClient client, IResource resource) { - try { - Thread.sleep(1000); - LOG.debug(String.format("Deleting resource: %s", resource)); - client.delete(resource); - } catch (Exception e) { - LOG.error("Exception deleting", e); - } - } - - public String getOpenShiftLocation() { - return prop.getProperty(KEY_OPENSHIFT_LOCATION); - } - - public String getDefaultClusterAdminUser() { - return prop.getProperty(KEY_USER); - } - - public String getDefaultClusterAdminPassword() { - return prop.getProperty(KEY_PASSWORD); - } - - public String getServerUrl() { - return prop.getProperty(KEY_SERVER_URL); - } - + @Override + public java.security.cert.X509Certificate[] getAcceptedIssuers() { + return new X509Certificate[0]; + } + } } diff --git a/src/test/java/com/openshift/internal/restclient/KubernetesVersionTest.java b/src/test/java/com/openshift/internal/restclient/KubernetesVersionTest.java new file mode 100644 index 00000000..dbbb26b9 --- /dev/null +++ b/src/test/java/com/openshift/internal/restclient/KubernetesVersionTest.java @@ -0,0 +1,99 @@ +/******************************************************************************* + * Copyright (c) 2019 Red Hat, Inc. Distributed under license by Red Hat, Inc. + * All rights reserved. This program is made available under the terms of the + * Eclipse Public License v1.0 which accompanies this distribution, and is + * available at http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: Red Hat, Inc. + ******************************************************************************/ + +package com.openshift.internal.restclient; + + +import static org.assertj.core.api.Assertions.assertThat; + +import org.junit.Test; + +public class KubernetesVersionTest { + + @Test + public void shouldReturnNotDetectedIfNullVersionString() { + // given + KubernetesVersion version = new KubernetesVersion(null); + // when + boolean isDetected = version.isDetected(); + // then + assertThat(isDetected).isFalse(); + } + + @Test + public void shouldReturnNotDetectedIfEmptyVersionString() { + // given + KubernetesVersion version = new KubernetesVersion(""); + // when + boolean isDetected = version.isDetected(); + // then + assertThat(isDetected).isFalse(); + } + + @Test + public void shouldReturnNotDetectedIfDoesntStartWithV() { + // given + KubernetesVersion version = new KubernetesVersion("3"); + // when + boolean isDetected = version.isDetected(); + // then + assertThat(isDetected).isFalse(); + } + + @Test + public void shouldNotParseIfOnlyMajorPresent() { + // given + KubernetesVersion version = new KubernetesVersion("v3"); + // when + // then + assertThat(version.isDetected()).isFalse(); + assertVersions(KubernetesVersion.NO_VERSION, KubernetesVersion.NO_VERSION, KubernetesVersion.NO_VERSION, null, + version); + } + + @Test + public void shouldNotParseIfOnlyMajorAndMinorVersion() { + // given + KubernetesVersion version = new KubernetesVersion("v3.2"); + // when + // then + assertThat(version.isDetected()).isFalse(); + assertVersions(KubernetesVersion.NO_VERSION, KubernetesVersion.NO_VERSION, KubernetesVersion.NO_VERSION, null, + version); + } + + @Test + public void shouldParseIfNoPatchVersion() { + // given + KubernetesVersion version = new KubernetesVersion("v3.2.1"); + // when + // then + assertThat(version.isDetected()).isTrue(); + assertVersions(3,2,1, null, + version); + } + + @Test + public void shouldMajorAndMinorAndPatchAndGitVersion() { + // given + KubernetesVersion version = new KubernetesVersion("v3.2.1+d42"); + // when + // then + assertThat(version.isDetected()).isTrue(); + assertVersions(3, 2, 1, "d42", version); + } + + private void assertVersions(int major, int minor, int patch, String git, KubernetesVersion version) { + assertThat(version.getMajor()).isEqualTo(major); + assertThat(version.getMinor()).isEqualTo(minor); + assertThat(version.getPatch()).isEqualTo(patch); + assertThat(version.getGit()).isEqualTo(git); + } + +} diff --git a/src/test/java/com/openshift/internal/restclient/OpenShiftVersionTest.java b/src/test/java/com/openshift/internal/restclient/OpenShiftVersionTest.java new file mode 100644 index 00000000..d61ee189 --- /dev/null +++ b/src/test/java/com/openshift/internal/restclient/OpenShiftVersionTest.java @@ -0,0 +1,92 @@ +/******************************************************************************* + * Copyright (c) 2019 Red Hat, Inc. Distributed under license by Red Hat, Inc. + * All rights reserved. This program is made available under the terms of the + * Eclipse Public License v1.0 which accompanies this distribution, and is + * available at http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: Red Hat, Inc. + ******************************************************************************/ + +package com.openshift.internal.restclient; + + +import static org.assertj.core.api.Assertions.assertThat; + +import org.junit.Test; + +public class OpenShiftVersionTest { + + @Test + public void shouldNotDetectedIfNullVersionStrings() { + // given + OpenShiftMajorVersion version = new OpenShiftMajorVersion(null, null); + // when + boolean isDetected = version.isDetected(); + int majorVersion = version.get(); + // then + assertThat(isDetected).isFalse(); + assertThat(majorVersion).isEqualTo(KubernetesVersion.NO_VERSION); + } + + @Test + public void shouldNotDetectedIfEmptyVersionStrings() { + // given + OpenShiftMajorVersion version = new OpenShiftMajorVersion("", ""); + // when + boolean isDetected = version.isDetected(); + int majorVersion = version.get(); + // then + assertThat(isDetected).isFalse(); + assertThat(majorVersion).isEqualTo(KubernetesVersion.NO_VERSION); + } + + @Test + public void shouldReturnVersionDetectedInOpenShiftString() { + // given + OpenShiftMajorVersion version = new OpenShiftMajorVersion("v3.11.43", "v1.11.0+d4cacc0"); + // when + int majorVersion = version.get(); + // then + assertThat(majorVersion).isEqualTo(3); + } + + @Test + public void shouldReturnVersion3ForKubernetes1_11() { + // given + OpenShiftMajorVersion version = new OpenShiftMajorVersion(null, "v1.11.0+d4cacc0"); + // when + int majorVersion = version.get(); + // then + assertThat(majorVersion).isEqualTo(3); + } + + @Test + public void shouldReturnVersion4ForKubernetes1_13() { + // given + OpenShiftMajorVersion version = new OpenShiftMajorVersion(null, "v1.13.4+f61b934"); + // when + int majorVersion = version.get(); + // then + assertThat(majorVersion).isEqualTo(4); + } + + @Test + public void shouldReturnVersion3IndependentlyOfKubernetesVersion() { + // given + OpenShiftMajorVersion version = new OpenShiftMajorVersion("v3.11.43", "v1.13.4+f61b934"); + // when + int majorVersion = version.get(); + // then + assertThat(majorVersion).isEqualTo(3); + } + + @Test + public void shouldReturnVersion4ByKubernetesIfOpenShiftVersionIsNotDetected() { + // given + OpenShiftMajorVersion version = new OpenShiftMajorVersion("smurf_version", "v1.13.4+f61b934"); + // when + int majorVersion = version.get(); + // then + assertThat(majorVersion).isEqualTo(4); + } +} diff --git a/src/test/java/com/openshift/internal/restclient/PodStatusRunningConditional.java b/src/test/java/com/openshift/internal/restclient/PodStatusRunningConditional.java new file mode 100644 index 00000000..3d05e13f --- /dev/null +++ b/src/test/java/com/openshift/internal/restclient/PodStatusRunningConditional.java @@ -0,0 +1,35 @@ +/******************************************************************************* + * Copyright (c) 2016 Red Hat, Inc. + * Distributed under license by Red Hat, Inc. All rights reserved. + * This program is made available under the terms of the + * Eclipse Public License v1.0 which accompanies this distribution, + * and is available at http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Red Hat, Inc. - initial API and implementation + ******************************************************************************/ + +package com.openshift.internal.restclient; + +import com.openshift.internal.restclient.IntegrationTestHelper.ReadyConditional; +import com.openshift.restclient.model.IPod; +import com.openshift.restclient.model.IResource; + +/** + * Conditional to determin if a pod has acheived Running Status + * + */ +public class PodStatusRunningConditional implements ReadyConditional { + + @Override + public boolean isReady(IResource resource) { + if (resource == null) { + return false; + } + if (!(resource instanceof IPod)) { + return false; + } + IPod pod = (IPod) resource; + return "Running".equals(pod.getStatus()); + } +} diff --git a/src/test/java/com/openshift/internal/restclient/ResourceFactoryTest.java b/src/test/java/com/openshift/internal/restclient/ResourceFactoryTest.java index 6cbca45d..3a636c8e 100644 --- a/src/test/java/com/openshift/internal/restclient/ResourceFactoryTest.java +++ b/src/test/java/com/openshift/internal/restclient/ResourceFactoryTest.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2015 Red Hat, Inc. + * Copyright (c) 2015-2019 Red Hat, Inc. * Distributed under license by Red Hat, Inc. All rights reserved. * This program is made available under the terms of the * Eclipse Public License v1.0 which accompanies this distribution, @@ -8,57 +8,70 @@ * Contributors: * Red Hat, Inc. - initial API and implementation ******************************************************************************/ -package com.openshift.internal.restclient; -import static org.mockito.Mockito.*; -import static junit.framework.Assert.*; +package com.openshift.internal.restclient; -import java.util.Arrays; -import java.util.List; +import static org.junit.Assert.assertEquals; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; import org.junit.Before; import org.junit.Test; +import com.openshift.restclient.IApiTypeMapper; +import com.openshift.restclient.IApiTypeMapper.IVersionedType; import com.openshift.restclient.IClient; import com.openshift.restclient.ResourceKind; import com.openshift.restclient.model.IService; -/** - * @author Jeff Cantrill - */ public class ResourceFactoryTest { - private ResourceFactory factory; + private ResourceFactory factory; + + @Before + public void setup() { + IClient client = mock(IClient.class); + IApiTypeMapper mapper = mock(IApiTypeMapper.class); + when(client.getOpenShiftAPIVersion()).thenReturn(OpenShiftAPIVersion.v1.toString()); + when(client.adapt(IApiTypeMapper.class)).thenReturn(mapper); + when(mapper.getType(anyString(), eq(ResourceKind.SERVICE))).thenReturn(new IVersionedType() { + + @Override + public String getVersion() { + return "v1"; + } + + @Override + public String getPrefix() { + return null; + } + + @Override + public String getKind() { + return ResourceKind.SERVICE; + } + + @Override + public String getApiGroupName() { + return null; + } + }); + factory = new ResourceFactory(client); + } + + @Test + public void testStubWithNamespace() { + IService service = factory.stub(ResourceKind.SERVICE, "foo", "bar"); + assertEquals("foo", service.getName()); + assertEquals("bar", service.getNamespaceName()); + } - @Before - public void setup() { - IClient client = mock(IClient.class); - when(client.getOpenShiftAPIVersion()).thenReturn(OpenShiftAPIVersion.v1.toString()); - factory = new ResourceFactory(client); - } - - /* - * Validate the implementation classes implemented the expected constructor - */ - @Test - public void testV1Beta3Implementations() { - List v1beta3Exlusions = Arrays.asList(new String [] { - ResourceKind.CONFIG, - ResourceKind.PROCESSED_TEMPLATES - }); - final String version = OpenShiftAPIVersion.v1beta3.toString(); - for (String kind : ResourceKind.values()) { - if(!v1beta3Exlusions.contains(kind)) { - factory.create(version, kind); - } - } - } - - @Test - public void testStubWithNamespace() { - IService service = factory.stub(ResourceKind.SERVICE, "foo", "bar"); - assertEquals("foo", service.getName()); - assertEquals("bar", service.getNamespace()); - } + @Test + public void testCreateWithKindAndName() { + IService service = factory.create("v1", ResourceKind.SERVICE, "foo"); + assertEquals("foo", service.getName()); + } } diff --git a/src/test/java/com/openshift/internal/restclient/TypeMapperFixture.java b/src/test/java/com/openshift/internal/restclient/TypeMapperFixture.java index 02f2bbd8..d4e12ffe 100644 --- a/src/test/java/com/openshift/internal/restclient/TypeMapperFixture.java +++ b/src/test/java/com/openshift/internal/restclient/TypeMapperFixture.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2016 Red Hat, Inc. + * Copyright (c) 2016-2019 Red Hat, Inc. * Distributed under license by Red Hat, Inc. All rights reserved. * This program is made available under the terms of the * Eclipse Public License v1.0 which accompanies this distribution, @@ -8,46 +8,141 @@ * Contributors: * Red Hat, Inc. - initial API and implementation ******************************************************************************/ + package com.openshift.internal.restclient; -import static org.mockito.Matchers.anyInt; -import static org.mockito.Matchers.eq; +import static org.mockito.ArgumentMatchers.argThat; +import static org.mockito.Mockito.doReturn; +import static org.mockito.Mockito.lenient; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.spy; import static org.mockito.Mockito.when; +import java.io.IOException; import java.net.URL; +import java.util.function.Supplier; import org.junit.Before; -import org.mockito.Mock; +import org.mockito.ArgumentCaptor; +import org.mockito.ArgumentMatcher; +import org.mockito.stubbing.OngoingStubbing; import com.openshift.restclient.IApiTypeMapper; -import com.openshift.restclient.http.IHttpClient; +import com.openshift.restclient.IClient; +import com.openshift.restclient.http.IHttpConstants; import com.openshift.restclient.utils.Samples; +import okhttp3.Call; +import okhttp3.Callback; +import okhttp3.OkHttpClient; +import okhttp3.Protocol; +import okhttp3.Request; +import okhttp3.Response; +import okhttp3.ResponseBody; + public class TypeMapperFixture { - - protected static final String VERSIONS = "{ \"versions\": [\"v1\"]}"; - protected static final String base = "https://localhost:8443"; - - @Mock - private IHttpClient client; - protected IApiTypeMapper mapper; - - protected IApiTypeMapper getApiTypeMapper() { - return mapper; - } - - protected IHttpClient getHttpClient() { - return client; - } - - @Before - public void setUp() throws Exception { - when(client.get(eq(new URL(base + "/api")), anyInt())).thenReturn(VERSIONS); - when(client.get(eq(new URL(base + "/oapi")), anyInt())).thenReturn(VERSIONS); - when(client.get(eq(new URL(base + "/apis")), anyInt())).thenReturn(Samples.GROUP_ENDPONT_APIS.getContentAsString()); - when(client.get(eq(new URL(base + "/api/v1")), anyInt())).thenReturn(Samples.GROUP_ENDPONT_API_V1.getContentAsString()); - when(client.get(eq(new URL(base + "/oapi/v1")), anyInt())).thenReturn(Samples.GROUP_ENDPONT_OAPI_V1.getContentAsString()); - when(client.get(eq(new URL(base + "/apis/extensions/v1beta1")), anyInt())).thenReturn(Samples.GROUP_ENDPONT_APIS_EXTENSIONS.getContentAsString()); - mapper = new ApiTypeMapper(base, client); - } + + protected static final String VERSIONS = "{ \"versions\": [\"v1\"]}"; + protected static final String base = "https://localhost:8443"; + protected static final String ANY_URL = "--any--"; + private TestOkHttpClient client = spy(new TestOkHttpClient()); + + protected IApiTypeMapper mapper; + + protected IApiTypeMapper getApiTypeMapper() { + return mapper; + } + + protected TestOkHttpClient getHttpClient() { + return client; + } + + protected IClient getIClient() throws Exception { + return new DefaultClient(new URL(base), client, new ResourceFactory(null), mapper, null); + } + + @Before + public void setUp() throws Exception { + client.whenRequestTo(ANY_URL).thenReturn(responseOf("")); + client.whenRequestTo(base + "/api").thenReturn(responseOf(VERSIONS)); + client.whenRequestTo(base + "/oapi").thenReturn(responseOf(VERSIONS)); + client.whenRequestTo(base + "/apis").thenReturn(responseOf(Samples.GROUP_ENDPONT_APIS.getContentAsString())); + client.whenRequestTo(base + "/api/v1") + .thenReturn(responseOf(Samples.GROUP_ENDPONT_API_V1.getContentAsString())); + client.whenRequestTo(base + "/oapi/v1") + .thenReturn(responseOf(Samples.GROUP_ENDPONT_OAPI_V1.getContentAsString())); + client.whenRequestTo(base + "/apis/extensions/v1beta1") + .thenReturn(responseOf(Samples.GROUP_ENDPONT_APIS_EXTENSIONS.getContentAsString())); + client.mockAsyncRequest(base + "/version", + () -> responseOf(Samples.KUBERNETES_VERSION.getContentAsString())); + client.mockAsyncRequest(base + "/version/openshift", + () -> responseOf(Samples.OPENSHIFT_VERSION.getContentAsString())); + mapper = new ApiTypeMapper(base, client, null); + } + + protected static class TestOkHttpClient extends OkHttpClient { + + public void whenRequestTo(String url, Response response) throws IOException { + Call call = mock(Call.class); + doReturn(response).when(call).execute(); + doReturn(call).when(this).newCall(requestTo(url)); + } + + OngoingStubbing whenRequestTo(String url) throws IOException { + Call call = mock(Call.class); + doReturn(call).when(this).newCall(requestTo(url)); + return when(call.execute()); + } + + void mockAsyncRequest(String url, Supplier response) throws IOException { + Call call = mock(Call.class); + lenient().doReturn(call).when(this).newCall(requestTo(url)); + + ArgumentCaptor argumentCaptor = ArgumentCaptor.forClass(Callback.class); + lenient().doAnswer(invocation -> { + Callback callback = argumentCaptor.getValue(); + callback.onResponse(call, response.get()); + return null; + }).when(call).enqueue(argumentCaptor.capture()); + } + } + + static Request requestTo(String url) { + return argThat(new RequestMatcher(url)); + } + + protected static Response responseOf(String response) { + return responseOf(IHttpConstants.STATUS_OK, response); + } + + protected static Response responseOf(int statusCode, String response) { + return new Response.Builder() + .request(new Request.Builder().url("https://someurlfortesting").build()) + .protocol(Protocol.HTTP_1_1) + .code(statusCode) + .message("") + .body(ResponseBody.create(null, response)) + .build(); + } + + static class RequestMatcher implements ArgumentMatcher { + + private final String url; + + public RequestMatcher(String url) { + this.url = url; + } + + @Override + public boolean matches(Request argument) { + if (ANY_URL.equals(this.url)) { + return true; + } + if (argument == null) { + return false; + } + return ((Request) argument).url().toString().equals(url); + } + + } } diff --git a/src/test/java/com/openshift/internal/restclient/URLBuilderTest.java b/src/test/java/com/openshift/internal/restclient/URLBuilderTest.java index b5a442bc..0ed152eb 100644 --- a/src/test/java/com/openshift/internal/restclient/URLBuilderTest.java +++ b/src/test/java/com/openshift/internal/restclient/URLBuilderTest.java @@ -8,91 +8,106 @@ * Contributors: * Red Hat, Inc. - initial API and implementation ******************************************************************************/ + package com.openshift.internal.restclient; -import static org.junit.Assert.*; -import static org.mockito.Mockito.*; +import static org.junit.Assert.assertEquals; +import static org.mockito.Mockito.lenient; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + import java.net.MalformedURLException; import java.net.URL; +import java.util.HashMap; +import java.util.Map; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; -import org.mockito.runners.MockitoJUnitRunner; +import org.mockito.junit.MockitoJUnitRunner; import com.openshift.restclient.ResourceKind; import com.openshift.restclient.model.IResource; -/** - * @author Jeff Cantrill - */ @RunWith(MockitoJUnitRunner.class) -public class URLBuilderTest extends TypeMapperFixture{ - - private static final String BASE_URL = "https://localhost:8443"; - private URLBuilder builder; - - @Before - public void setup() throws MalformedURLException { - builder = new URLBuilder(new URL(BASE_URL), mapper); - } - - @Test - public void testBuildingURLForAWatchService() throws Exception { - IResource resource = givenAResource(ResourceKind.SERVICE, KubernetesAPIVersion.v1,"foo"); - - String url = builder. - resource(resource) - .watch() - .addParmeter("resourceVersion", "123") - .build().toString(); - assertEquals(String.format("%s/api/v1/namespaces/foo/services?watch=true&resourceVersion=123", BASE_URL),url.toString()); - } - - @Test - public void testBuildingURLForAProjectUsingResource() throws Exception { - IResource resource = givenAResource(ResourceKind.PROJECT, KubernetesAPIVersion.v1,"foo"); - - String url = builder. - resource(resource) - .name("foo") - .build().toString(); - assertEquals(String.format("%s/oapi/v1/projects/foo", BASE_URL),url.toString()); - } - - @Test - public void testBaseURLWithTrailingSlash() throws Exception { - builder = new URLBuilder(new URL(BASE_URL + "///"), mapper); - IResource resource = givenAResource(ResourceKind.SERVICE, KubernetesAPIVersion.v1,"foo"); - - String url = whenBuildingTheURLFor(resource, "foo"); - assertEquals(String.format("%s/api/v1/namespaces/foo/services/bar", BASE_URL),url.toString()); - } - - @Test - public void testAddingASubResource() { - IResource resource = givenAResource(ResourceKind.REPLICATION_CONTROLLER, KubernetesAPIVersion.v1, "foo"); - String url = builder. - resource(resource) - .name("bar") - .subresource("status") - .build().toString(); - assertEquals(String.format("%s/api/v1/namespaces/foo/replicationcontrollers/bar/status", BASE_URL),url.toString()); - } - - private String whenBuildingTheURLFor(IResource resource, String namespace) { - return builder. - resource(resource) - .namespace(namespace) - .name("bar") - .build().toString(); - } - - private IResource givenAResource(String kind, KubernetesAPIVersion version, String namespace) { - IResource resource = mock(IResource.class); - when(resource.getApiVersion()).thenReturn(version.toString()); - when(resource.getKind()).thenReturn(kind); - when(resource.getNamespace()).thenReturn(namespace); - return resource; - } +public class URLBuilderTest extends TypeMapperFixture { + + private static final String BASE_URL = "https://localhost:8443"; + private URLBuilder builder; + + @Before + public void setup() throws MalformedURLException { + builder = new URLBuilder(new URL(BASE_URL), mapper); + } + + @Test + public void testBuildingURLForAWatchService() throws Exception { + IResource resource = givenAResource(ResourceKind.SERVICE, KubernetesAPIVersion.v1, "foo"); + + Map params = new HashMap<>(); + params.put("foo", "bar"); + + String url = builder.resource(resource).watch().addParmeter("resourceVersion", "123").addParameters(params) + .build().toString(); + assertEquals( + String.format("%s/api/v1/namespaces/foo/services?watch=true&resourceVersion=123&foo=bar", BASE_URL), + url.toString()); + } + + @Test + public void testDuplicateParameters() throws Exception { + IResource resource = givenAResource(ResourceKind.SERVICE, KubernetesAPIVersion.v1, "foo"); + String url = builder.resource(resource).watch().addParmeter("resourceVersion", "123").addParmeter("x", "1") + .addParmeter("x", "2").build().toString(); + assertEquals( + String.format("%s/api/v1/namespaces/foo/services?watch=true&resourceVersion=123&x=1&x=2", BASE_URL), + url.toString()); + } + + @Test + public void testBuildingURLForAProjectUsingResource() throws Exception { + IResource resource = givenAResource(ResourceKind.PROJECT, KubernetesAPIVersion.v1, "foo"); + + String url = builder.resource(resource).name("foo").build().toString(); + assertEquals(String.format("%s/oapi/v1/projects/foo", BASE_URL), url.toString()); + } + + @Test + public void testBaseURLWithTrailingSlash() throws Exception { + builder = new URLBuilder(new URL(BASE_URL + "///"), mapper); + IResource resource = givenAResource(ResourceKind.SERVICE, KubernetesAPIVersion.v1, "foo"); + + String url = whenBuildingTheURLFor(resource, "foo"); + assertEquals(String.format("%s/api/v1/namespaces/foo/services/bar", BASE_URL), url.toString()); + } + + @Test + public void testAddingASubResource() { + IResource resource = givenAResource(ResourceKind.REPLICATION_CONTROLLER, KubernetesAPIVersion.v1, "foo"); + String url = builder.resource(resource).name("bar").subresource("status").build().toString(); + assertEquals(String.format("%s/api/v1/namespaces/foo/replicationcontrollers/bar/status", BASE_URL), + url.toString()); + } + + @Test + public void testAddingASubContext() { + IResource resource = givenAResource(ResourceKind.POD, KubernetesAPIVersion.v1, "https:demo-app-8-3gehi:8778"); + String url = builder.resource(resource).name("bar").subresource("proxy") + .subContext("jolokia/exec/java.util.logging:type=Logging/getLoggerLevel/abc").build().toString(); + assertEquals(String.format( + "%s/api/v1/namespaces/https:demo-app-8-3gehi:8778/pods/bar/proxy/jolokia/exec/java.util.logging:type=Logging/getLoggerLevel/abc", + BASE_URL), url.toString()); + } + + private String whenBuildingTheURLFor(IResource resource, String namespace) { + return builder.resource(resource).namespace(namespace).name("bar").build().toString(); + } + + private IResource givenAResource(String kind, KubernetesAPIVersion version, String namespace) { + IResource resource = mock(IResource.class); + lenient().when(resource.getApiVersion()).thenReturn(version.toString()); + when(resource.getKind()).thenReturn(kind); + when(resource.getNamespaceName()).thenReturn(namespace); + return resource; + } } diff --git a/src/test/java/com/openshift/internal/restclient/WatchClientTest.java b/src/test/java/com/openshift/internal/restclient/WatchClientTest.java deleted file mode 100644 index d8b68298..00000000 --- a/src/test/java/com/openshift/internal/restclient/WatchClientTest.java +++ /dev/null @@ -1,43 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2015 Red Hat, Inc. - * Distributed under license by Red Hat, Inc. All rights reserved. - * This program is made available under the terms of the - * Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * Red Hat, Inc. - initial API and implementation - ******************************************************************************/ -package com.openshift.internal.restclient; - -import static org.hamcrest.CoreMatchers.equalTo; -import static org.hamcrest.CoreMatchers.not; -import static org.junit.Assert.assertThat; - -import org.junit.Test; - -import com.openshift.restclient.IOpenShiftWatchListener.ChangeType; - -/** - * @author Andre Dietisheim - */ -public class WatchClientTest { - - @Test - public void changeTypeShouldEqualSameChangeType() { - assertThat(ChangeType.ADDED, - equalTo(ChangeType.ADDED)); - } - - @Test - public void changeTypeShouldNotEqualDifferentChangeType() { - assertThat(ChangeType.ADDED, - not(equalTo(ChangeType.DELETED))); - } - - @Test - public void changeTypeShouldEqualSameChangeTypeInLowercase() { - assertThat(ChangeType.ADDED, - equalTo(new ChangeType(ChangeType.ADDED.getValue().toLowerCase()))); - } -} diff --git a/src/test/java/com/openshift/internal/restclient/api/capabilities/PodExecIntegrationTest.java b/src/test/java/com/openshift/internal/restclient/api/capabilities/PodExecIntegrationTest.java new file mode 100644 index 00000000..023edb1f --- /dev/null +++ b/src/test/java/com/openshift/internal/restclient/api/capabilities/PodExecIntegrationTest.java @@ -0,0 +1,219 @@ +/******************************************************************************* + * Copyright (c) 2015-2019 Red Hat, Inc. + * Distributed under license by Red Hat, Inc. All rights reserved. + * This program is made available under the terms of the + * Eclipse Public License v1.0 which accompanies this distribution, + * and is available at http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Red Hat, Inc. - initial API and implementation + ******************************************************************************/ + +package com.openshift.internal.restclient.api.capabilities; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicBoolean; + +import org.junit.Before; +import org.junit.Test; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.openshift.internal.restclient.IntegrationTestHelper; +import com.openshift.restclient.IClient; +import com.openshift.restclient.api.capabilities.IPodExec; +import com.openshift.restclient.capability.CapabilityVisitor; +import com.openshift.restclient.capability.IStoppable; +import com.openshift.restclient.model.IPod; +import com.openshift.restclient.model.IProject; + +public class PodExecIntegrationTest { + + private static final int TIMEOUT_POD_READY = 30; + + private IntegrationTestHelper helper = new IntegrationTestHelper(); + private IProject project; + private IPod pod; + private IClient client; + + public static class TestExecListener implements IPodExec.IPodExecOutputListener { + + private static final Logger LOG = LoggerFactory.getLogger(PodExecIntegrationTest.class); + + public final CountDownLatch testDone = new CountDownLatch(1); + public final AtomicBoolean openCalled = new AtomicBoolean(false); + public final AtomicBoolean closeCalled = new AtomicBoolean(false); + public final AtomicBoolean failureCalled = new AtomicBoolean(false); + public final AtomicBoolean execErrCalled = new AtomicBoolean(false); + public final List messages = Collections.synchronizedList(new ArrayList()); + + @Override + public void onOpen() { + assertTrue(openCalled.compareAndSet(false, true)); + } + + @Override + public void onStdOut(String message) { + LOG.debug("onStdOut: " + message); + message = message.trim(); + if (!message.isEmpty()) { // Observing that actual output appears after empty newline + messages.add(PodExec.CHANNEL_STDOUT + message); + } + } + + @Override + public void onStdErr(String message) { + LOG.debug("onStdErr: " + message); + message = message.trim(); + if (!message.isEmpty()) { + messages.add(PodExec.CHANNEL_STDERR + message); + } + } + + @Override + public void onExecErr(String message) { + LOG.debug("onExecError: " + message); + execErrCalled.set(true); + message = message.trim(); + if (!message.isEmpty()) { + messages.add(PodExec.CHANNEL_EXECERR + message); + } + } + + @Override + public void onClose(int code, String reason) { + assertTrue(closeCalled.compareAndSet(false, true)); + testDone.countDown(); + } + + @Override + public void onFailure(Throwable t) { + failureCalled.set(true); + LOG.error("Potentially expected error occurred", t); + testDone.countDown(); + } + + } + + @Before + public void setUp() throws Exception { + this.client = helper.createClientForBasicAuth(); + this.project = helper.getOrCreateIntegrationTestProject(client); + this.pod = helper.getOrCreatePod(client, + project.getNamespaceName(), + IntegrationTestHelper.IMAGE_HELLO_OPENSHIFT_ALPINE); + assertNotNull("Could not create a pod to test against.", pod); + helper.waitForPodReady(client, pod.getNamespaceName(), pod.getName(), TIMEOUT_POD_READY); + } + + @Test + public void testPodExec() throws Exception { + String[] echoCommand = { "echo", "a", "b", "c" }; + TestExecListener echoListener = new TestExecListener(); + + pod.accept(new CapabilityVisitor() { + @Override + public IStoppable visit(IPodExec capability) { + return capability.start(echoListener, null, echoCommand); + } + }, null); + + echoListener.testDone.await(60, TimeUnit.SECONDS); + assertTrue(echoListener.openCalled.get()); + assertTrue(echoListener.closeCalled.get()); + assertTrue(!echoListener.failureCalled.get()); + assertTrue(!echoListener.execErrCalled.get()); + assertEquals(1, echoListener.messages.size()); + assertEquals("1a b c", echoListener.messages.get(0)); + } + + @Test + public void testPodExecWithContainerSpecified() throws Exception { + String[] echoCommand = { "echo", "a", "b", "c" }; + TestExecListener echoListener = new TestExecListener(); + + final String container = pod.getContainers().iterator().next().getName(); + IPodExec.Options options = new IPodExec.Options(); + options.container(container); + + pod.accept(new CapabilityVisitor() { + @Override + public IStoppable visit(IPodExec capability) { + return capability.start(echoListener, options, echoCommand); + } + }, null); + + echoListener.testDone.await(60, TimeUnit.SECONDS); + assertTrue(echoListener.openCalled.get()); + assertTrue(echoListener.closeCalled.get()); + assertTrue(!echoListener.failureCalled.get()); + assertTrue(!echoListener.execErrCalled.get()); + assertEquals(1, echoListener.messages.size()); + assertEquals("1a b c", echoListener.messages.get(0)); + } + + @Test + public void testCommandNotFound() throws Exception { + String[] badCommand = { "/bin/doesnotexist" }; + TestExecListener badListener = new TestExecListener(); + + pod.accept(new CapabilityVisitor() { + @Override + public IStoppable visit(IPodExec capability) { + return capability.start(badListener, null, badCommand); + } + }, null); + + badListener.testDone.await(60, TimeUnit.SECONDS); + assertTrue(badListener.openCalled.get()); + assertTrue(badListener.closeCalled.get()); + assertTrue(badListener.execErrCalled.get()); + // both execErr and stdErr will be called + assertEquals(2, badListener.messages.size()); + } + + @Test + public void testPodExecStop() throws Exception { + String[] longCommand = { "sleep", "500" }; + TestExecListener longListener = new TestExecListener(); + + IStoppable stopLong = pod.accept(new CapabilityVisitor() { + @Override + public IStoppable visit(IPodExec capability) { + return capability.start(longListener, null, longCommand); + } + }, null); + + // Trigger a cancel on the web socket before long delay can complete + stopLong.stop(); + longListener.testDone.await(60, TimeUnit.SECONDS); + assertTrue(longListener.failureCalled.get()); + } + + @Test + public void testContainerDoesNotExist() throws Exception { + String[] dateCommand = { "date" }; + TestExecListener dateListener = new TestExecListener(); + IPodExec.Options options = new IPodExec.Options(); + options.container("will-not-exist-in-docker-registry-pod"); + + pod.accept(new CapabilityVisitor() { + @Override + public IStoppable visit(IPodExec capability) { + return capability.start(dateListener, options, dateCommand); + } + }, null); + + dateListener.testDone.await(60, TimeUnit.SECONDS); + assertTrue(dateListener.failureCalled.get()); + } + +} diff --git a/src/test/java/com/openshift/internal/restclient/api/capabilities/PodExecTest.java b/src/test/java/com/openshift/internal/restclient/api/capabilities/PodExecTest.java new file mode 100644 index 00000000..6c972c22 --- /dev/null +++ b/src/test/java/com/openshift/internal/restclient/api/capabilities/PodExecTest.java @@ -0,0 +1,119 @@ +/******************************************************************************* + * Copyright (c) 2016-2019 Red Hat, Inc. + * Distributed under license by Red Hat, Inc. All rights reserved. + * This program is made available under the terms of the + * Eclipse Public License v1.0 which accompanies this distribution, + * and is available at http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Red Hat, Inc. - initial API and implementation + ******************************************************************************/ + +package com.openshift.internal.restclient.api.capabilities; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import java.net.URL; + +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.Mock; +import org.mockito.junit.MockitoJUnitRunner; + +import com.openshift.internal.restclient.DefaultClient; +import com.openshift.internal.restclient.TypeMapperFixture; +import com.openshift.internal.restclient.capability.resources.PodLogRetrievalAsync; +import com.openshift.restclient.IApiTypeMapper; +import com.openshift.restclient.api.capabilities.IPodExec; +import com.openshift.restclient.model.IPod; +import com.openshift.restclient.model.MocksFactory; + +@RunWith(MockitoJUnitRunner.class) +public class PodExecTest extends TypeMapperFixture { + + private DefaultClient client; + @Mock + private IApiTypeMapper mapper; + private PodLogRetrievalAsync capability; + private IPod pod; + private PodExec.ExecOutputListenerAdapter adapter; + + @Mock + private IPodExec.IPodExecOutputListener listener; + + @Before + public void setUp() throws Exception { + super.setUp(); + client = new DefaultClient(new URL("https://localhost"), getHttpClient(), null, getApiTypeMapper(), null); + pod = new MocksFactory().mock(IPod.class); + capability = new PodLogRetrievalAsync(pod, client); + adapter = new PodExec.ExecOutputListenerAdapter(listener); + } + + @Test + public void testIsSupported() { + assertTrue("Exp. capability to be supported because the pod endpoint exists", capability.isSupported()); + } + + @Test + public void testIsNotSupportedWhenEndpointDoesNotExist() { + when(pod.getApiVersion()).thenReturn("somenoneexitentversion"); + assertFalse("Exp. capability to not be supported because the pod endpoint does not exist exists", + capability.isSupported()); + } + + @Test + public void testAdapterCallsListenerCycle() throws Exception { + adapter.onOpen(null, null); + adapter.onOpen(null, null); + verify(listener).onOpen(); + + adapter.deliver(PodExec.CHANNEL_STDOUT, "ImStdOut"); + adapter.deliver(PodExec.CHANNEL_STDERR, "ImStdErr"); + adapter.deliver(PodExec.CHANNEL_EXECERR, "ImExecErr"); + + verify(listener).onStdOut("ImStdOut"); + verify(listener).onStdErr("ImStdErr"); + verify(listener).onExecErr("ImExecErr"); + + adapter.onClosing(null, 1986, "the reason"); + adapter.onClosing(null, 1986, "the reason"); + verify(listener).onClose(1986, "the reason"); + } + + @Test + public void testExecOptions() throws Exception { + IPodExec.Options options = new IPodExec.Options(); + assertEquals(0, options.getMap().size()); + + options.stdErr(false); + options.stdOut(false); + options.container("test"); + + assertEquals(3, options.getMap().size()); + + assertEquals("false", options.getMap().get(IPodExec.Options.STDERR)); + assertEquals("false", options.getMap().get(IPodExec.Options.STDOUT)); + assertEquals("test", options.getMap().get(IPodExec.Options.CONTAINER)); + + options.parameter(IPodExec.Options.STDERR, "true"); + options.parameter(IPodExec.Options.STDOUT, "true"); + options.parameter(IPodExec.Options.CONTAINER, "override"); + + // Re-set these options to ensure they do not override parameter API + options.stdErr(false); + options.stdOut(false); + options.container("test"); + + assertEquals("true", options.getMap().get(IPodExec.Options.STDERR)); + assertEquals("true", options.getMap().get(IPodExec.Options.STDOUT)); + assertEquals("override", options.getMap().get(IPodExec.Options.CONTAINER)); + + } + +} \ No newline at end of file diff --git a/src/test/java/com/openshift/internal/restclient/api/capabilities/ScaleCapabilityIntegrationTest.java b/src/test/java/com/openshift/internal/restclient/api/capabilities/ScaleCapabilityIntegrationTest.java new file mode 100644 index 00000000..deb78286 --- /dev/null +++ b/src/test/java/com/openshift/internal/restclient/api/capabilities/ScaleCapabilityIntegrationTest.java @@ -0,0 +1,133 @@ +/******************************************************************************* + * Copyright (c) 2016-2019 Red Hat, Inc. + * Distributed under license by Red Hat, Inc. All rights reserved. + * This program is made available under the terms of the + * Eclipse Public License v1.0 which accompanies this distribution, + * and is available at http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Red Hat, Inc. - initial API and implementation + ******************************************************************************/ + +package com.openshift.internal.restclient.api.capabilities; + +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; + +import java.util.List; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicBoolean; + +import org.junit.After; +import org.junit.Before; +import org.junit.Test; + +import com.openshift.internal.restclient.IntegrationTestHelper; +import com.openshift.internal.restclient.PodStatusRunningConditional; +import com.openshift.restclient.IClient; +import com.openshift.restclient.IOpenShiftWatchListener; +import com.openshift.restclient.IWatcher; +import com.openshift.restclient.ResourceKind; +import com.openshift.restclient.api.capabilities.IScalable; +import com.openshift.restclient.apis.autoscaling.models.IScale; +import com.openshift.restclient.capability.CapabilityVisitor; +import com.openshift.restclient.model.IPod; +import com.openshift.restclient.model.IProject; +import com.openshift.restclient.model.IReplicationController; +import com.openshift.restclient.model.IResource; + +public class ScaleCapabilityIntegrationTest { + + private static final int REPLICAS = 2; + private IntegrationTestHelper helper = new IntegrationTestHelper(); + private IClient client; + private IProject project; + private IWatcher watch; + private CountDownLatch initializationLatch = new CountDownLatch(2); + private CountDownLatch replicaLatch = new CountDownLatch(1); + private IReplicationController rc; + private AtomicBoolean foundFirstPod = new AtomicBoolean(false); + private PodStatusRunningConditional conditional = new PodStatusRunningConditional(); + + @Before + public void setUp() throws Exception { + this.client = helper.createClientForBasicAuth(); + this.project = helper.getOrCreateIntegrationTestProject(client); + } + + @After + public void teardown() throws Exception { + helper.stopWatcher(watch); + helper.cleanUpResource(client, rc); + // remove all pods that were created by the rc/dc + helper.cleanUpResource(client, client.get(ResourceKind.POD, project.getNamespaceName())); + } + + @Test(timeout = IntegrationTestHelper.TEST_LONG_TIMEOUT) + public void testScalingReplicationController() throws Exception { + this.rc = client.create(helper.stubReplicationController(client, + project.getNamespaceName(), IntegrationTestHelper.appendRandom("test-rc"))); + runTest(); + } + + @Test(timeout = IntegrationTestHelper.TEST_LONG_TIMEOUT) + public void testScalingDeploymentConfig() throws Exception { + this.rc = client.create(helper.stubDeploymentConfig(client, + project.getNamespaceName(), IntegrationTestHelper.appendRandom("test-dc"))); + runTest(); + } + + private void runTest() throws Exception { + this.watch = client.watch(project.getName(), new IOpenShiftWatchListener() { + + @Override + public void connected(List resources) { + initializationLatch.countDown(); + } + + @Override + public void disconnected() { + } + + @Override + public void received(IResource resource, ChangeType change) { + if (!(resource instanceof IPod) + || helper.isDeployPod(((IPod) resource))) { + return; + } + if (ChangeType.MODIFIED.equals(change) + && conditional.isReady(resource)) { + if (foundFirstPod.get()) { + replicaLatch.countDown(); + } else { + foundFirstPod.set(true); + initializationLatch.countDown(); + } + } + } + + @Override + public void error(Throwable err) { + } + + }, ResourceKind.POD); + + if (initializationLatch.await(1, TimeUnit.MINUTES)) { + scaleTo(REPLICAS); + assertTrue("The pods either did not scale to " + REPLICAS + " replicas or the test timed out", + replicaLatch.await(2, TimeUnit.MINUTES)); + } + } + + private void scaleTo(int replicas) { + IScale result = rc.accept(new CapabilityVisitor() { + + @Override + public IScale visit(IScalable capability) { + return capability.scaleTo(replicas); + } + }, null); + assertNotNull("Exp. to receive a non-null result", result); + } +} diff --git a/src/test/java/com/openshift/internal/restclient/apis/TypeMetaFactoryTest.java b/src/test/java/com/openshift/internal/restclient/apis/TypeMetaFactoryTest.java new file mode 100644 index 00000000..b7188979 --- /dev/null +++ b/src/test/java/com/openshift/internal/restclient/apis/TypeMetaFactoryTest.java @@ -0,0 +1,56 @@ +/******************************************************************************* + * Copyright (c) 2016 Red Hat, Inc. + * Distributed under license by Red Hat, Inc. All rights reserved. + * This program is made available under the terms of the + * Eclipse Public License v1.0 which accompanies this distribution, + * and is available at http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Red Hat, Inc. - initial API and implementation + ******************************************************************************/ + +package com.openshift.internal.restclient.apis; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; + +import java.util.Optional; + +import org.junit.Test; + +import com.openshift.restclient.api.ITypeFactory; +import com.openshift.restclient.api.models.ITypeMeta; +import com.openshift.restclient.apis.autoscaling.models.IScale; +import com.openshift.restclient.model.IBuild; +import com.openshift.restclient.utils.Samples; + +public class TypeMetaFactoryTest { + + private final ITypeFactory factory = new TypeMetaFactory(); + + @Test + public void testStubKind() { + Object obj = factory.stubKind("extensions/v1beta1.Scale", Optional.of("foo"), Optional.of("bar")); + assertTrue(obj instanceof IScale); + IScale scale = (IScale) obj; + assertEquals("foo", scale.getName()); + assertEquals("bar", scale.getNamespace()); + assertEquals("Scale", scale.getKind()); + assertEquals("extensions/v1beta1", scale.getApiVersion()); + } + + @Test + public void testExtensionScale() { + Object response = factory.createInstanceFrom(Samples.V1BETA1_API_EXT_SCALE.getContentAsString()); + assertTrue(response instanceof IScale); + } + + @Test + public void testUnrecognized() { + Object response = factory.createInstanceFrom(Samples.V1_BUILD.getContentAsString()); + assertFalse(response instanceof IBuild); + assertTrue(response instanceof ITypeMeta); + } + +} diff --git a/src/test/java/com/openshift/internal/restclient/apis/extensions/model/v1beta1/ScaleTest.java b/src/test/java/com/openshift/internal/restclient/apis/extensions/model/v1beta1/ScaleTest.java new file mode 100644 index 00000000..83c30d9b --- /dev/null +++ b/src/test/java/com/openshift/internal/restclient/apis/extensions/model/v1beta1/ScaleTest.java @@ -0,0 +1,68 @@ +/******************************************************************************* + * Copyright (c) 2016 Red Hat, Inc. + * Distributed under license by Red Hat, Inc. All rights reserved. + * This program is made available under the terms of the + * Eclipse Public License v1.0 which accompanies this distribution, + * and is available at http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Red Hat, Inc. - initial API and implementation + ******************************************************************************/ + +package com.openshift.internal.restclient.apis.extensions.model.v1beta1; + +import static org.junit.Assert.assertEquals; + +import java.util.Collections; + +import org.jboss.dmr.ModelNode; +import org.junit.Before; +import org.junit.Test; + +import com.openshift.internal.restclient.apis.autoscaling.models.Scale; +import com.openshift.restclient.apis.autoscaling.models.IScale; +import com.openshift.restclient.utils.Samples; + +public class ScaleTest { + + private static final String JSON = Samples.V1BETA1_API_EXT_SCALE.getContentAsString(); + IScale scale; + + @Before + public void setUp() throws Exception { + ModelNode node = ModelNode.fromJSONString(JSON); + scale = new Scale(node, Collections.emptyMap()); + } + + @Test + public void testGetSetName() { + assertEquals("logging-kibana", scale.getName()); + scale.setName("other"); + assertEquals("other", scale.getName()); + } + + @Test + public void testGetSetNamespace() { + assertEquals("logging", scale.getNamespace()); + scale.setNamespace("other-ns"); + assertEquals("other-ns", scale.getNamespace()); + } + + @Test + public void testGetApiVersion() { + assertEquals("extensions/v1beta1", scale.getApiVersion()); + } + + @Test + public void testGetKind() { + assertEquals("Scale", scale.getKind()); + } + + @Test + public void testSetGetSpecReplicas() { + assertEquals(2, scale.getSpecReplicas()); + scale.setSpecReplicas(30); + assertEquals(30, scale.getSpecReplicas()); + } + +} diff --git a/src/test/java/com/openshift/internal/restclient/authorization/AuthorizationClientIntegrationTest.java b/src/test/java/com/openshift/internal/restclient/authorization/AuthorizationClientIntegrationTest.java deleted file mode 100644 index a2a8b0ec..00000000 --- a/src/test/java/com/openshift/internal/restclient/authorization/AuthorizationClientIntegrationTest.java +++ /dev/null @@ -1,103 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2015 Red Hat, Inc. Distributed under license by Red Hat, Inc. - * All rights reserved. This program is made available under the terms of the - * Eclipse Public License v1.0 which accompanies this distribution, and is - * available at http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: Red Hat, Inc. - initial API and implementation - ******************************************************************************/ -package com.openshift.internal.restclient.authorization; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNotSame; -import static org.junit.Assert.fail; - -import org.junit.Before; -import org.junit.Test; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import com.openshift.internal.restclient.DefaultClientIntegrationTest; -import com.openshift.internal.restclient.IntegrationTestHelper; -import com.openshift.restclient.IClient; -import com.openshift.restclient.authorization.BasicAuthorizationStrategy; -import com.openshift.restclient.authorization.IAuthorizationContext; -import com.openshift.restclient.authorization.UnauthorizedException; - -/** - * @author Jeff Cantrill - */ -public class AuthorizationClientIntegrationTest { - - - private static final Logger LOG = LoggerFactory.getLogger(DefaultClientIntegrationTest.class); - - private IntegrationTestHelper helper = new IntegrationTestHelper(); - private IClient client; - - @Before - public void setup () { - client = helper.createClient(); - } - - /*---------- These are tests that should pass when server is configured for oauth auth. No expectations regarding others */ - - /* - * Assume Basic Auth, invalid token - */ - @Test - //@Environment(auth=oauth) //lets build this - public void getAuthorizationContextWhenOauthConfigurationAndInvalidToken() { - try { - client = helper.createClientForBasicAuth(); - client.getContext(client.getBaseURL().toString()); - fail("Expected to fail with authorization details"); - }catch(UnauthorizedException e) { - assertNotNull(e.getAuthorizationDetails()); - LOG.info(e.toString()); - } - } - - /* - * Assume Basic Auth, valid token - */ - @Test - //@Environment(auth=oauth) //lets build this - public void getAuthorizationContextWhenOauthConfigurationAndValidToken() { - final String token = "Mzk2MDliYWYtOTA4OC00NzJlLTk2YmQtOGM3ZTAwYTM3ZDU4"; - client = helper.createClient(); - client.setAuthorizationStrategy(new BasicAuthorizationStrategy(helper.getDefaultClusterAdminUser(), helper.getDefaultClusterAdminPassword(), token)); - IAuthorizationContext context = client.getContext(client.getBaseURL().toString()); - assertEquals(token, context.getToken()); - } - - /*---------- These are tests that should pass when server is configured for basic auth. No expectations regarding others */ - - /* - * Assume Basic Auth, valid token - */ - @Test - //@Environment(auth=basic) //lets build this - public void getAuthorizationContextWhenBasicAuthConfiguredAndValidToken() { - final String token = "Mzk2MDliYWYtOTA4OC00NzJlLTk2YmQtOGM3ZTAwYTM3ZDU4"; - client = helper.createClient(); - client.setAuthorizationStrategy(new BasicAuthorizationStrategy(helper.getDefaultClusterAdminUser(), helper.getDefaultClusterAdminPassword(), token)); - IAuthorizationContext context = client.getContext(client.getBaseURL().toString()); - assertEquals(token, context.getToken()); - } - - /* - * Assume Basic Auth, invalid token - */ - @Test - //@Environment(auth=basic) //lets build this - public void getAuthorizationContextWhenBasicAuthConfiguredAndInValidToken() { - final String token = "asdfasd"; - client = helper.createClient(); - client.setAuthorizationStrategy(new BasicAuthorizationStrategy(helper.getDefaultClusterAdminUser(), helper.getDefaultClusterAdminPassword(), token)); - IAuthorizationContext context = client.getContext(client.getBaseURL().toString()); - assertNotSame("Exp. to get a new token using the username and password", token, context.getToken()); - } - -} diff --git a/src/test/java/com/openshift/internal/restclient/authorization/AuthorizationContextTest.java b/src/test/java/com/openshift/internal/restclient/authorization/AuthorizationContextTest.java new file mode 100644 index 00000000..590349c0 --- /dev/null +++ b/src/test/java/com/openshift/internal/restclient/authorization/AuthorizationContextTest.java @@ -0,0 +1,66 @@ +/******************************************************************************* +* Copyright (c) 2020 Red Hat, Inc. Distributed under license by Red Hat, Inc. +* All rights reserved. This program is made available under the terms of the +* Eclipse Public License v1.0 which accompanies this distribution, and is +* available at http://www.eclipse.org/legal/epl-v10.html +* +* Contributors: Red Hat, Inc. +******************************************************************************/ + +package com.openshift.internal.restclient.authorization; + + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.Mockito.doReturn; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; + +import org.jboss.dmr.ModelNode; +import org.junit.Before; +import org.junit.Test; + +import com.openshift.internal.restclient.model.properties.ResourcePropertiesRegistry; +import com.openshift.internal.restclient.model.user.OpenShiftUser; +import com.openshift.restclient.IClient; +import com.openshift.restclient.ResourceKind; +import com.openshift.restclient.model.user.IUser; +import com.openshift.restclient.utils.Samples; + +public class AuthorizationContextTest { + + private static final String VERSION = "v1"; + private static String TOKEN = "42"; + private static String EXPIRES = "84"; + private static String SCHEME = "Scheme"; + private AuthorizationContext context; + private IClient client; + + @Before + public void setup() throws Exception { + IUser user = mock(IUser.class); + this.context = new AuthorizationContext(TOKEN, EXPIRES, user, SCHEME); + this.client = createClient(); + context.setClient(client); + } + + private IClient createClient() { + IClient client = mock(IClient.class); + ModelNode node = ModelNode.fromJSONString(Samples.V1_USER.getContentAsString()); + IUser user = new OpenShiftUser(node, client, + ResourcePropertiesRegistry.getInstance().get(VERSION, ResourceKind.USER)); + doReturn(user).when(client).get(ResourceKind.USER, "~", ""); + return client; + } + + @Test + public void invalidateShouldForceNewUserRequestWhenEventualIsAuthorized() { + // given + assertThat(context.isAuthorized()).isTrue(); + context.invalidate(); + // when + context.isAuthorized(); + // then + verify(client, times(1)).get(ResourceKind.USER, "~", ""); + } +} diff --git a/src/test/java/com/openshift/internal/restclient/authorization/AuthorizationDetailsTest.java b/src/test/java/com/openshift/internal/restclient/authorization/AuthorizationDetailsTest.java index 180ce56d..8d37bcdc 100644 --- a/src/test/java/com/openshift/internal/restclient/authorization/AuthorizationDetailsTest.java +++ b/src/test/java/com/openshift/internal/restclient/authorization/AuthorizationDetailsTest.java @@ -8,78 +8,57 @@ * Contributors: * Red Hat, Inc. - initial API and implementation ******************************************************************************/ -package com.openshift.internal.restclient.authorization; -import static org.junit.Assert.*; +package com.openshift.internal.restclient.authorization; -import java.util.ArrayList; -import java.util.List; +import static org.junit.Assert.assertEquals; -import org.apache.http.Header; -import org.apache.http.HeaderElement; -import org.apache.http.ParseException; +import org.junit.Before; import org.junit.Test; -/** - * @author Jeff Cantrill - */ -public class AuthorizationDetailsTest { - /* - * WWW-Authenticate: OAuth realm= - * WWW-Authenticate: Basic - * Link: ; rel="related" - * Warning: 199 OpenShift "You must obtain an API token by visiting https://127.0.0.1:8443/oauth/token/request" - * code 401 - */ - private List
headers = new ArrayList
(); +import okhttp3.Headers; - @Test - public void testMessageDetailsWithoutAuthorizationHeader() { - givenHeader("Link", "; rel=\"related\""); - givenHeader("Warning", "199 OpenShift \"You must obtain an API token by visiting https://127.0.0.1:8443/oauth/token/request\""); - AuthorizationDetails details = whenCreatingAnAuthorizationScheme(); - assertEquals("https://127.0.0.1:8443/oauth/token/request", details.getRequestTokenLink()); - assertEquals("\"You must obtain an API token by visiting https://127.0.0.1:8443/oauth/token/request\"", details.getMessage()); - } - - @Test - public void testMessageDetailsWithAuthorizationHeader() { - givenHeader("WWW-Authenticate", "Basic realm=\"openshift\""); - givenHeader("Warning", "199 OpenShift \"You must obtain an API token by visiting https://127.0.0.1:8443/oauth/token/request\""); - AuthorizationDetails details = whenCreatingAnAuthorizationScheme(); - assertEquals("Basic", details.getScheme()); - } +public class AuthorizationDetailsTest { + /* + * WWW-Authenticate: OAuth realm= WWW-Authenticate: Basic Link: + * ; rel="related" Warning: 199 + * OpenShift + * "You must obtain an API token by visiting https://127.0.0.1:8443/oauth/token/request" + * code 401 + */ + private Headers.Builder builder = new Headers.Builder(); - private AuthorizationDetails whenCreatingAnAuthorizationScheme() { - return new AuthorizationDetails(headers.toArray(new Header[] {})); - } + @Before + public void setUp() { - private void givenHeader(String name, String value) { - headers.add(new FakeHeader(name, value)); - } + } - private static class FakeHeader implements Header{ - private String name; - private String value; + @Test + public void testMessageDetailsWithoutAuthorizationHeader() { + givenHeader("Link", "; rel=\"related\""); + givenHeader("Warning", + "199 OpenShift \"You must obtain an API token by visiting https://127.0.0.1:8443/oauth/token/request\""); + AuthorizationDetails details = whenCreatingAnAuthorizationScheme(); + assertEquals("https://127.0.0.1:8443/oauth/token/request", details.getRequestTokenLink()); + assertEquals("\"You must obtain an API token by visiting https://127.0.0.1:8443/oauth/token/request\"", + details.getMessage()); + } - FakeHeader(String name, String value){ - this.name = name; - this.value = value; - } - @Override - public String getName() { - return name; - } + @Test + public void testMessageDetailsWithAuthorizationHeader() { + givenHeader("WWW-Authenticate", "Basic realm=\"openshift\""); + givenHeader("Warning", + "199 OpenShift \"You must obtain an API token by visiting https://127.0.0.1:8443/oauth/token/request\""); + AuthorizationDetails details = whenCreatingAnAuthorizationScheme(); + assertEquals("Basic", details.getScheme()); + } - @Override - public String getValue() { - return value; - } + private AuthorizationDetails whenCreatingAnAuthorizationScheme() { + return new AuthorizationDetails(builder.build()); + } - @Override - public HeaderElement[] getElements() throws ParseException { - throw new UnsupportedOperationException("Method not supported in test impl"); - } + private void givenHeader(String name, String value) { + builder.add(name, value); + } - } } diff --git a/src/test/java/com/openshift/internal/restclient/authorization/AuthorizationKindsIntegrationTest.java b/src/test/java/com/openshift/internal/restclient/authorization/AuthorizationKindsIntegrationTest.java new file mode 100644 index 00000000..8581a1e6 --- /dev/null +++ b/src/test/java/com/openshift/internal/restclient/authorization/AuthorizationKindsIntegrationTest.java @@ -0,0 +1,55 @@ +/******************************************************************************* +* Copyright (c) 2016-2019 Red Hat, Inc. Distributed under license by Red Hat, Inc. +* All rights reserved. This program is made available under the terms of the +* Eclipse Public License v1.0 which accompanies this distribution, and is +* available at http://www.eclipse.org/legal/epl-v10.html +* +* Contributors: Red Hat, Inc. +******************************************************************************/ + +package com.openshift.internal.restclient.authorization; + + +import static org.assertj.core.api.Assertions.assertThat; + +import java.util.List; + +import org.junit.Before; +import org.junit.Ignore; +import org.junit.Test; + +import com.openshift.internal.restclient.IntegrationTestHelper; +import com.openshift.restclient.IClient; +import com.openshift.restclient.ResourceKind; +import com.openshift.restclient.model.authorization.IRole; + +public class AuthorizationKindsIntegrationTest { + + private IClient client; + private IntegrationTestHelper helper = new IntegrationTestHelper(); + + @Before + public void setup() { + client = helper.createClientForBasicAuth(); + } + + @Ignore("Role endpoint was deprecated in v1") + @Test + public void testListRolesAssumingClusterAdmin() { + List roles = client.list(ResourceKind.ROLE, IntegrationTestHelper.getDefaultNamespace()); + assertThat(roles).isNotEmpty(); + } + + @Ignore("Policy endpoint was deprecated in v1") + @Test + public void testListPoliciesAssumingClusterAdmin() { + client.list(ResourceKind.POLICY, IntegrationTestHelper.getDefaultNamespace()); + } + + @Ignore("PolicyBinding endpoint was deprecated in v1") + @Test + public void testListPolicyBindingsAssumingClusterAdmin() { + client.list(ResourceKind.POLICY_BINDING, IntegrationTestHelper.getDefaultNamespace()); + } + +} diff --git a/src/test/java/com/openshift/internal/restclient/capability/resources/AnnotationCapabilityTest.java b/src/test/java/com/openshift/internal/restclient/capability/resources/AnnotationCapabilityTest.java index 59dcc428..fb28cb55 100644 --- a/src/test/java/com/openshift/internal/restclient/capability/resources/AnnotationCapabilityTest.java +++ b/src/test/java/com/openshift/internal/restclient/capability/resources/AnnotationCapabilityTest.java @@ -6,52 +6,53 @@ * * Contributors: Red Hat, Inc. ******************************************************************************/ + package com.openshift.internal.restclient.capability.resources; -import static org.junit.Assert.*; -import static org.mockito.Matchers.eq; -import static org.mockito.Mockito.*; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.when; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; -import org.mockito.runners.MockitoJUnitRunner; +import org.mockito.junit.MockitoJUnitRunner; -import com.openshift.internal.restclient.capability.resources.AnnotationCapability; import com.openshift.restclient.model.IResource; -/** - * @author Jeff Cantrill - */ @RunWith(MockitoJUnitRunner.class) public class AnnotationCapabilityTest { - - private AnnotationCapability capability; - @Mock private IResource resource; - - @Before - public void setUp(){ - capability = newCapability(); - } - - private AnnotationCapability newCapability(){ - return new AnnotationCapability("MyCapability", resource) { - @Override - protected String getAnnotationKey() { - return "foobar"; - } - }; - - } - @Test - public void supportedWhenAnnotationsHasKey(){ - when(resource.isAnnotatedWith(eq("foobar"))).thenReturn(true); - assertTrue("Exp. the capability to be supported when the annotation key exists", capability.isSupported()); - } - - @Test - public void unsupportedWhenAnnotationsDoNotHaveADeploymentKey(){ - assertFalse("Exp. the capability to not be supported when annotation key does not exists", capability.isSupported()); - } + + private AnnotationCapability capability; + @Mock + private IResource resource; + + @Before + public void setUp() { + capability = newCapability(); + } + + private AnnotationCapability newCapability() { + return new AnnotationCapability("MyCapability", resource) { + @Override + protected String getAnnotationKey() { + return "foobar"; + } + }; + + } + + @Test + public void supportedWhenAnnotationsHasKey() { + when(resource.isAnnotatedWith(eq("foobar"))).thenReturn(true); + assertTrue("Exp. the capability to be supported when the annotation key exists", capability.isSupported()); + } + + @Test + public void unsupportedWhenAnnotationsDoNotHaveADeploymentKey() { + assertFalse("Exp. the capability to not be supported when annotation key does not exists", + capability.isSupported()); + } } diff --git a/src/test/java/com/openshift/internal/restclient/capability/resources/AssociationCapabilityTest.java b/src/test/java/com/openshift/internal/restclient/capability/resources/AssociationCapabilityTest.java index 29b52af6..62d9176c 100644 --- a/src/test/java/com/openshift/internal/restclient/capability/resources/AssociationCapabilityTest.java +++ b/src/test/java/com/openshift/internal/restclient/capability/resources/AssociationCapabilityTest.java @@ -6,27 +6,23 @@ * * Contributors: Red Hat, Inc. ******************************************************************************/ + package com.openshift.internal.restclient.capability.resources; -import static org.junit.Assert.*; +import static org.junit.Assert.assertFalse; import org.junit.Test; -import com.openshift.internal.restclient.capability.resources.AssociationCapability; - -/** - * @author Jeff Cantrill - */ public class AssociationCapabilityTest { - @Test - public void unsupportedWhenTheClientIsNull(){ - AssociationCapability capability = new AssociationCapability("MyCapability", null, null) { - @Override - protected String getAnnotationKey() { - return "foobar"; - } - }; - assertFalse("Exp. the capability to be unsupported because the IClient is null", capability.isSupported()); - } + @Test + public void unsupportedWhenTheClientIsNull() { + AssociationCapability capability = new AssociationCapability("MyCapability", null, null) { + @Override + protected String getAnnotationKey() { + return "foobar"; + } + }; + assertFalse("Exp. the capability to be unsupported because the IClient is null", capability.isSupported()); + } } diff --git a/src/test/java/com/openshift/internal/restclient/capability/resources/BinaryBuildCapabilitiesIntegrationTest.java b/src/test/java/com/openshift/internal/restclient/capability/resources/BinaryBuildCapabilitiesIntegrationTest.java new file mode 100644 index 00000000..8f740525 --- /dev/null +++ b/src/test/java/com/openshift/internal/restclient/capability/resources/BinaryBuildCapabilitiesIntegrationTest.java @@ -0,0 +1,132 @@ +/******************************************************************************* + * Copyright (c) 2018-2019 Red Hat, Inc. + * Distributed under license by Red Hat, Inc. All rights reserved. + * This program is made available under the terms of the + * Eclipse Public License v1.0 which accompanies this distribution, + * and is available at http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Red Hat, Inc. - initial API and implementation + ******************************************************************************/ + +package com.openshift.internal.restclient.capability.resources; + +import static org.junit.Assert.assertNotNull; + +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.TimeUnit; + +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.openshift.internal.restclient.IntegrationTestHelper; +import com.openshift.restclient.IClient; +import com.openshift.restclient.IOpenShiftWatchListener; +import com.openshift.restclient.ResourceKind; +import com.openshift.restclient.capability.CapabilityVisitor; +import com.openshift.restclient.capability.resources.IBinaryBuildTriggerable; +import com.openshift.restclient.capability.resources.IBuildCancelable; +import com.openshift.restclient.model.IBuild; +import com.openshift.restclient.model.IBuildConfig; +import com.openshift.restclient.model.IImageStream; +import com.openshift.restclient.model.IProject; +import com.openshift.restclient.model.IResource; +import com.openshift.restclient.model.build.IBuildConfigBuilder; + +public class BinaryBuildCapabilitiesIntegrationTest { + + private static final Logger LOG = LoggerFactory.getLogger(BinaryBuildCapabilitiesIntegrationTest.class); + private IntegrationTestHelper helper = new IntegrationTestHelper(); + private IClient client; + private IProject project; + private IImageStream is; + private IBuildConfig bc; + private IBuild build; + + @Before + public void setUp() throws Exception { + client = helper.createClientForBasicAuth(); + project = helper.getOrCreateIntegrationTestProject(client); + + // an output imagestream + IImageStream is = client.getResourceFactory().stub(ResourceKind.IMAGE_STREAM, "rest-spring-boot", + project.getName()); + LOG.debug("Creating imagestream {}", is); + this.is = client.create(is); + LOG.debug("Generated imagestream {}", is); + + // a buildconfig + IBuildConfigBuilder builder = client.adapt(IBuildConfigBuilder.class); + assertNotNull("Exp. the client to be able to use a buildconfigbuilder", builder); + IBuildConfig bcStup = builder.named(IntegrationTestHelper.appendRandom("rest-spring-boot")) + .inNamespace(project.getName()) + .fromBinarySource() + .end() + .usingSourceStrategy() + .fromDockerImage("registry.access.redhat.com/redhat-openjdk-18/openjdk18-openshift").end() + .toImageStreamTag("rest-spring-boot:latest") + .build(); + LOG.debug("Creating BuildConfig {}", bcStup); + this.bc = client.create(bcStup); + LOG.debug("Created BuildConfig {}", bc); + assertNotNull(bc); + } + + @Test + public void testBuildActions() throws InterruptedException { + // trigger the build + LOG.debug("Triggering build from the buildconfig..."); + IBuild build = bc.accept(new CapabilityVisitor() { + @Override + public IBuild visit(IBinaryBuildTriggerable capability) { + return capability.triggerBinary( + BinaryBuildCapabilitiesIntegrationTest.class.getResourceAsStream("/rest-spring-boot.zip")); + } + }, null); + assertNotNull("Exp. to be able to trigger a build from a buildconfig", build); + LOG.debug("Triggered build {}", build); + + LOG.debug("Canceling the build..."); + // cancel the build + build = build.accept(new CapabilityVisitor() { + + @Override + public IBuild visit(IBuildCancelable cap) { + return cap.cancel(); + } + }, null); + assertNotNull("Exp. to be able to cancel a build", build); + LOG.debug("Canceled build {}", build); + + // trigger a new build and wait for completion + this.build = bc.accept(new CapabilityVisitor() { + @Override + public IBuild visit(IBinaryBuildTriggerable capability) { + return capability.triggerBinary( + BinaryBuildCapabilitiesIntegrationTest.class.getResourceAsStream("/rest-spring-boot.zip")); + } + }, null); + assertNotNull("Exp. to be able to trigger a build from a buildconfig", build); + LOG.debug("Triggered build {}", build); + CountDownLatch latch = new CountDownLatch(1); + client.watch(project.getNamespaceName(), new IOpenShiftWatchListener.OpenShiftWatchListenerAdapter() { + @Override + public void received(IResource resource, ChangeType change) { + if ("Complete".equals(((IBuild)resource).getStatus())) { + latch.countDown(); + } + } + + }, ResourceKind.BUILD); + latch.await(10, TimeUnit.MINUTES); + } + + @After + public void tearDown() { + helper.cleanUpResources(client, build, bc, is); + } + +} diff --git a/src/test/java/com/openshift/internal/restclient/capability/resources/BuildCapabilitiesIntegrationTest.java b/src/test/java/com/openshift/internal/restclient/capability/resources/BuildCapabilitiesIntegrationTest.java new file mode 100644 index 00000000..fd9da3a9 --- /dev/null +++ b/src/test/java/com/openshift/internal/restclient/capability/resources/BuildCapabilitiesIntegrationTest.java @@ -0,0 +1,141 @@ +/******************************************************************************* + * Copyright (c) 2015-2019 Red Hat, Inc. + * Distributed under license by Red Hat, Inc. All rights reserved. + * This program is made available under the terms of the + * Eclipse Public License v1.0 which accompanies this distribution, + * and is available at http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Red Hat, Inc. - initial API and implementation + ******************************************************************************/ + +package com.openshift.internal.restclient.capability.resources; + +import static org.junit.Assert.assertNotNull; + +import java.util.Collections; + +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.openshift.internal.restclient.IntegrationTestHelper; +import com.openshift.restclient.IClient; +import com.openshift.restclient.ResourceKind; +import com.openshift.restclient.capability.CapabilityVisitor; +import com.openshift.restclient.capability.resources.IBuildCancelable; +import com.openshift.restclient.capability.resources.IBuildTriggerable; +import com.openshift.restclient.model.IBuild; +import com.openshift.restclient.model.IBuildConfig; +import com.openshift.restclient.model.IImageStream; +import com.openshift.restclient.model.IProject; +import com.openshift.restclient.model.build.IBuildConfigBuilder; + +public class BuildCapabilitiesIntegrationTest { + + private static final Logger LOG = LoggerFactory.getLogger(BuildCapabilitiesIntegrationTest.class); + private IBuildConfig bc; + private IImageStream is; + private IntegrationTestHelper helper = new IntegrationTestHelper(); + private IProject project; + private IClient client; + + @Before + public void setUp() throws Exception { + this.client = helper.createClientForBasicAuth(); + this.project = helper.getOrCreateIntegrationTestProject(client); + + // an output imagestream + IImageStream is = client.getResourceFactory().stub( + ResourceKind.IMAGE_STREAM, IntegrationTestHelper.appendRandom("ruby-hello-world"), project.getName()); + LOG.debug("Creating imagestream {}", is); + this.is = client.create(is); + LOG.debug("Generated imagestream {}", is); + + // a buildconfig + IBuildConfigBuilder builder = client.adapt(IBuildConfigBuilder.class); + assertNotNull("Exp. the client to be able to use a buildconfigbuilder", builder); + LOG.debug("Creating BuildConfig {}", bc); + this.bc = client.create( + helper.stubBuildConfig(client, + project.getNamespaceName(), + IntegrationTestHelper.appendRandom("test-bc"), + "https://github.com/openshift/ruby-hello-world.git", + Collections.emptyMap())); + LOG.debug("Created BuildConfig {}", bc); + assertNotNull(bc); + } + + @After + public void tearDown() { + helper.cleanUpResources(client, bc, is); + } + + @Test + public void shouldTriggerBuild() { + IBuild build = triggerBuild(bc); + assertNotNull("Exp. to be able to trigger a build from a buildconfig", build); + } + + @Test + public void shouldCancelBuild() { + // given + final IBuild build = triggerBuild(bc); + // when + IBuild cancelledBuild = build.accept(new CapabilityVisitor() { + + @Override + public IBuild visit(IBuildCancelable cap) { + // bug in 4.1? build needs to be refreshed + IBuild refreshedBuild = refresh(build); + refreshedBuild.cancel(); + return refreshedBuild; + } + }, null); + assertNotNull("Exp. to be able to cancel a build", cancelledBuild); + } + + @Test + public void shouldTriggerBuildFromBuild() { + // given + IBuild build = triggerBuild(bc); + // when + build = build.accept(new CapabilityVisitor() { + @Override + public IBuild visit(IBuildTriggerable capability) { + return capability.trigger(); + } + }, null); + // when + assertNotNull("Exp. to be able to trigger a build from a build", build); + } + + @Test + public void shouldTriggerBuildWithCause() { + IBuild build = bc.accept(new CapabilityVisitor() { + @Override + public IBuild visit(IBuildTriggerable capability) { + capability.addBuildCause("test cause"); + return capability.trigger(); + } + }, null); + assertNotNull("Exp. to be able to add a build cause for a build", build); + } + + private IBuild refresh(IBuild build) { + return client.get(ResourceKind.BUILD, build.getName(), build.getNamespaceName()); + } + + private IBuild triggerBuild(IBuildConfig bc) { + IBuild build = bc.accept(new CapabilityVisitor() { + @Override + public IBuild visit(IBuildTriggerable capability) { + return capability.trigger(); + } + }, null); + return build; + } + +} diff --git a/src/test/java/com/openshift/internal/restclient/capability/resources/BuildTriggerIntegrationTest.java b/src/test/java/com/openshift/internal/restclient/capability/resources/BuildTriggerIntegrationTest.java deleted file mode 100644 index 1cff1e5d..00000000 --- a/src/test/java/com/openshift/internal/restclient/capability/resources/BuildTriggerIntegrationTest.java +++ /dev/null @@ -1,61 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2015 Red Hat, Inc. - * Distributed under license by Red Hat, Inc. All rights reserved. - * This program is made available under the terms of the - * Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * Red Hat, Inc. - initial API and implementation - ******************************************************************************/ -package com.openshift.internal.restclient.capability.resources; - -import static org.junit.Assert.*; - -import org.junit.Before; -import org.junit.Test; - -import com.openshift.internal.restclient.IntegrationTestHelper; -import com.openshift.restclient.IClient; -import com.openshift.restclient.ResourceKind; -import com.openshift.restclient.authorization.IAuthorizationContext; -import com.openshift.restclient.authorization.TokenAuthorizationStrategy; -import com.openshift.restclient.capability.CapabilityVisitor; -import com.openshift.restclient.capability.resources.IBuildTriggerable; -import com.openshift.restclient.model.IBuild; -import com.openshift.restclient.model.IBuildConfig; - -/** - * - * @author Jeff Cantrill - * - */ -public class BuildTriggerIntegrationTest { - - IBuildConfig config; - - @Before - public void setUp() throws Exception { - //client - IClient client = new IntegrationTestHelper().createClientForBasicAuth(); - IAuthorizationContext auth = client.getContext(client.getBaseURL().toString()); - client.setAuthorizationStrategy(new TokenAuthorizationStrategy(auth.getToken())); - //create buildconfig or retrieve from already initialized server - config = client.get(ResourceKind.BUILD_CONFIG, "ruby-sample-build", "test"); - assertNotNull(config); - } - - @Test - public void testTriggerABuild() { - IBuild build = config.accept(new CapabilityVisitor() { - - @Override - public IBuild visit(IBuildTriggerable capability) { - return capability.trigger(); - } - }, null); - assertNotNull("Exp. to be able to trigger a build", build); - System.out.println(build.toString()); - } - -} diff --git a/src/test/java/com/openshift/internal/restclient/capability/resources/DeployCapabilityTest.java b/src/test/java/com/openshift/internal/restclient/capability/resources/DeployCapabilityTest.java index 129d1049..bb35f4e2 100644 --- a/src/test/java/com/openshift/internal/restclient/capability/resources/DeployCapabilityTest.java +++ b/src/test/java/com/openshift/internal/restclient/capability/resources/DeployCapabilityTest.java @@ -8,19 +8,28 @@ * Contributors: * Red Hat, Inc. - initial API and implementation ******************************************************************************/ + package com.openshift.internal.restclient.capability.resources; +import static com.openshift.restclient.utils.ResourceTestHelper.givenDeployConfigIsVersion; +import static com.openshift.restclient.utils.ResourceTestHelper.givenResourceIsAnnotatedWith; +import static com.openshift.restclient.utils.ResourceTestHelper.thenResourceShouldBeUpdated; +import static com.openshift.restclient.utils.ResourceTestHelper.thenResourceShouldNotBeUpdated; import static org.junit.Assert.assertTrue; -import static org.mockito.Mockito.*; -import static com.openshift.restclient.utils.ResourceTestHelper.*; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; -import org.mockito.runners.MockitoJUnitRunner; +import org.mockito.junit.MockitoJUnitRunner; import com.openshift.restclient.IClient; +import com.openshift.restclient.NotFoundException; import com.openshift.restclient.OpenShiftException; import com.openshift.restclient.capability.resources.IDeployCapability; import com.openshift.restclient.http.IHttpConstants; @@ -31,97 +40,99 @@ @RunWith(MockitoJUnitRunner.class) public class DeployCapabilityTest { - private static final String NAMESPACE = "aNamespace"; - private static final int VERSION = 1986; - private static final String NAME = "aDCName"; - - private IDeployCapability cap; - @Mock private IDeploymentConfig config; - @Mock private IReplicationController deployment; - @Mock private IClient client; - - @Before - public void setUp() throws Exception { - cap = new DeployCapability(config, client); - when(config.getNamespace()).thenReturn(NAMESPACE); - when(config.getName()).thenReturn(NAME); - - givenDeployConfigIsVersion(config, VERSION); - } - - @Test - public void testIsSupported() { - assertTrue("Exp. the capability to be supported", cap.isSupported()); - } - - @SuppressWarnings("unchecked") - @Test(expected=OpenShiftException.class) - public void testThrowsErrorWhenUnableToFindLatestDeployment() { - when(client.get(anyString(), anyString(), anyString())).thenThrow(OpenShiftException.class); - whenDeploying(); - } - - @Test - public void testWhenLatestDeploymentNotFound() { - givenTheLatestDeploymentIsNotFound(); - whenDeploying(); - thenVersionShouldIncrease(config); - thenResourceShouldBeUpdated(client, config); - } - - @Test - public void testConfigNotUpdatedWhenAlreadyInProgress() { - givenTheDeploymentIsRetrieved(); - givenDeploymentStatusIs("New"); - whenDeploying(); - thenResourceShouldNotBeUpdated(client, config); - thenVersionShouldNotBeIncreased(config); - } - - @Test - public void testStartsNewDeploymentWhenPreviousFailed() { - givenTheDeploymentIsRetrieved(); - givenDeploymentStatusIs("Failed"); - whenDeploying(); - thenVersionShouldIncrease(config); - thenResourceShouldBeUpdated(client, config); - } - - @Test - public void testStartsNewDeploymentWhenPreviousComplete() { - givenTheDeploymentIsRetrieved(); - givenDeploymentStatusIs("Complete"); - whenDeploying(); - thenVersionShouldIncrease(config); - thenResourceShouldBeUpdated(client, config); - } - - private void thenVersionShouldIncrease(IDeploymentConfig config) { - int newVersion = config.getLatestVersionNumber()+1; - verify(config, times(1)).setLatestVersionNumber(newVersion); - } - - private void thenVersionShouldNotBeIncreased(IDeploymentConfig config) { - int newVersion = config.getLatestVersionNumber()+1; - verify(config, times(0)).setLatestVersionNumber(newVersion); - } - - private void whenDeploying() { - cap.deploy(); - } - - private void givenDeploymentStatusIs(String status) { - givenResourceIsAnnotatedWith(deployment, IReplicationController.DEPLOYMENT_PHASE, status); - } - - private void givenTheDeploymentIsRetrieved() { - when(client.get(anyString(),anyString(),anyString())).thenReturn(deployment); - } - - private void givenTheLatestDeploymentIsNotFound() { - IStatus status = mock(IStatus.class); - when(status.getCode()).thenReturn(IHttpConstants.STATUS_NOT_FOUND); - OpenShiftException e = new OpenShiftException(new RuntimeException(), status, ""); - when(client.get(anyString(),anyString(),anyString())).thenThrow(e); - } + private static final String NAMESPACE = "aNamespace"; + private static final int VERSION = 1986; + private static final String NAME = "aDCName"; + + private IDeployCapability cap; + @Mock + private IDeploymentConfig config; + @Mock + private IReplicationController deployment; + @Mock + private IClient client; + + @Before + public void setUp() throws Exception { + cap = new DeployCapability(config, client); + when(config.getNamespaceName()).thenReturn(NAMESPACE); + when(config.getName()).thenReturn(NAME); + + givenDeployConfigIsVersion(config, VERSION); + } + + @Test + public void testIsSupported() { + assertTrue("Exp. the capability to be supported", cap.isSupported()); + } + + @Test(expected = OpenShiftException.class) + public void testThrowsErrorWhenUnableToFindLatestDeployment() { + when(client.get(anyString(), anyString(), anyString())).thenThrow(OpenShiftException.class); + whenDeploying(); + } + + @Test + public void testWhenLatestDeploymentNotFound() { + givenTheLatestDeploymentIsNotFound(); + whenDeploying(); + thenVersionShouldIncrease(config); + thenResourceShouldBeUpdated(client, config); + } + + @Test + public void testConfigNotUpdatedWhenAlreadyInProgress() { + givenTheDeploymentIsRetrieved(); + givenDeploymentStatusIs("New"); + whenDeploying(); + thenResourceShouldNotBeUpdated(client, config); + thenVersionShouldNotBeIncreased(config); + } + + @Test + public void testStartsNewDeploymentWhenPreviousFailed() { + givenTheDeploymentIsRetrieved(); + givenDeploymentStatusIs("Failed"); + whenDeploying(); + thenVersionShouldIncrease(config); + thenResourceShouldBeUpdated(client, config); + } + + @Test + public void testStartsNewDeploymentWhenPreviousComplete() { + givenTheDeploymentIsRetrieved(); + givenDeploymentStatusIs("Complete"); + whenDeploying(); + thenVersionShouldIncrease(config); + thenResourceShouldBeUpdated(client, config); + } + + private void thenVersionShouldIncrease(IDeploymentConfig config) { + int newVersion = config.getLatestVersionNumber() + 1; + verify(config, times(1)).setLatestVersionNumber(newVersion); + } + + private void thenVersionShouldNotBeIncreased(IDeploymentConfig config) { + int newVersion = config.getLatestVersionNumber() + 1; + verify(config, times(0)).setLatestVersionNumber(newVersion); + } + + private void whenDeploying() { + cap.deploy(); + } + + private void givenDeploymentStatusIs(String status) { + givenResourceIsAnnotatedWith(deployment, IReplicationController.DEPLOYMENT_PHASE, status); + } + + private void givenTheDeploymentIsRetrieved() { + when(client.get(anyString(), anyString(), anyString())).thenReturn(deployment); + } + + private void givenTheLatestDeploymentIsNotFound() { + IStatus status = mock(IStatus.class); + when(status.getCode()).thenReturn(IHttpConstants.STATUS_NOT_FOUND); + NotFoundException e = new NotFoundException(null, status, "Not Found"); + when(client.get(anyString(), anyString(), anyString())).thenThrow(e); + } } diff --git a/src/test/java/com/openshift/internal/restclient/capability/resources/DeploymentConfigTraceabilityTest.java b/src/test/java/com/openshift/internal/restclient/capability/resources/DeploymentConfigTraceabilityTest.java index 471a07a7..600e7187 100644 --- a/src/test/java/com/openshift/internal/restclient/capability/resources/DeploymentConfigTraceabilityTest.java +++ b/src/test/java/com/openshift/internal/restclient/capability/resources/DeploymentConfigTraceabilityTest.java @@ -6,59 +6,60 @@ * * Contributors: Red Hat, Inc. ******************************************************************************/ + package com.openshift.internal.restclient.capability.resources; -import static org.junit.Assert.*; -import static org.mockito.Matchers.eq; -import static org.mockito.Mockito.*; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNull; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; -import org.mockito.runners.MockitoJUnitRunner; +import org.mockito.junit.MockitoJUnitRunner; -import com.openshift.internal.restclient.capability.resources.DeploymentConfigTraceability; import com.openshift.restclient.IClient; import com.openshift.restclient.ResourceKind; import com.openshift.restclient.model.IDeploymentConfig; import com.openshift.restclient.model.IPod; -/** - * @author Jeff Cantrill - */ @RunWith(MockitoJUnitRunner.class) public class DeploymentConfigTraceabilityTest { - private DeploymentConfigTraceability capability; - - @Mock private IDeploymentConfig config; - @Mock private IPod resource; - @Mock private IClient client; - - @Before - public void setUp(){ - capability = new DeploymentConfigTraceability(resource, client); - - when(resource.getNamespace()).thenReturn("mynamespace"); - - when(client.get(eq(ResourceKind.DEPLOYMENT_CONFIG), eq("foobar"), eq("mynamespace"))) - .thenReturn(config); - } - - @Test - public void supportedWhenAnnotationsHaveADeploymentKey(){ - when(resource.isAnnotatedWith(eq("deploymentconfig"))).thenReturn(true); - when(resource.getAnnotation("deploymentconfig")).thenReturn("foobar"); + private DeploymentConfigTraceability capability; + + @Mock + private IDeploymentConfig config; + @Mock + private IPod resource; + @Mock + private IClient client; + + @Before + public void setUp() { + capability = new DeploymentConfigTraceability(resource, client); + + when(resource.getNamespaceName()).thenReturn("mynamespace"); + + when(client.get(eq(ResourceKind.DEPLOYMENT_CONFIG), eq("foobar"), eq("mynamespace"))).thenReturn(config); + } + + @Test + public void supportedWhenAnnotationsHaveADeploymentKey() { + when(resource.isAnnotatedWith(eq("deploymentconfig"))).thenReturn(true); + when(resource.getAnnotation("deploymentconfig")).thenReturn("foobar"); + + assertEquals("Exp. to get the deploymentConfig", config, capability.getDeploymentConfig()); - assertEquals("Exp. to get the deploymentConfig", config, capability.getDeploymentConfig()); - - verify(client).get(eq(ResourceKind.DEPLOYMENT_CONFIG), eq("foobar"), eq("mynamespace")); - } + verify(client).get(eq(ResourceKind.DEPLOYMENT_CONFIG), eq("foobar"), eq("mynamespace")); + } - @Test - public void unsupportedWhenAnnotationsDoNotHaveADeploymentKey(){ - assertNull("Exp. to get the deploymentConfig", capability.getDeploymentConfig()); - } + @Test + public void unsupportedWhenAnnotationsDoNotHaveADeploymentKey() { + assertNull("Exp. to get the deploymentConfig", capability.getDeploymentConfig()); + } } diff --git a/src/test/java/com/openshift/internal/restclient/capability/resources/DeploymentTraceabilityTest.java b/src/test/java/com/openshift/internal/restclient/capability/resources/DeploymentTraceabilityTest.java index 8da71f80..ec5cd0d6 100644 --- a/src/test/java/com/openshift/internal/restclient/capability/resources/DeploymentTraceabilityTest.java +++ b/src/test/java/com/openshift/internal/restclient/capability/resources/DeploymentTraceabilityTest.java @@ -6,58 +6,61 @@ * * Contributors: Red Hat, Inc. ******************************************************************************/ + package com.openshift.internal.restclient.capability.resources; -import static org.junit.Assert.*; -import static org.mockito.Mockito.*; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNull; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; -import org.mockito.runners.MockitoJUnitRunner; +import org.mockito.junit.MockitoJUnitRunner; -import com.openshift.internal.restclient.capability.resources.DeploymentTraceability; import com.openshift.restclient.IClient; import com.openshift.restclient.ResourceKind; import com.openshift.restclient.model.IPod; import com.openshift.restclient.model.IReplicationController; -/** - * @author Jeff Cantrill - */ @RunWith(MockitoJUnitRunner.class) public class DeploymentTraceabilityTest { - private DeploymentTraceability capability; - - @Mock private IReplicationController deployment; - @Mock private IPod resource; - @Mock private IClient client; - - @Before - public void setUp(){ - capability = new DeploymentTraceability(resource, client); - - when(resource.getNamespace()).thenReturn("mynamespace"); - - when(client.get(eq(ResourceKind.REPLICATION_CONTROLLER), eq("foobar"), eq("mynamespace"))) - .thenReturn(deployment); - } - - @Test - public void supportedWhenAnnotationsHaveADeploymentKey(){ - when(resource.isAnnotatedWith(eq("deployment"))).thenReturn(true); - when(resource.getAnnotation("deployment")).thenReturn("foobar"); - - assertEquals("Exp. to get the deployment", deployment, capability.getDeployment()); - - verify(client).get(eq(ResourceKind.REPLICATION_CONTROLLER), eq("foobar"), eq("mynamespace")); - } - - @Test - public void unsupportedWhenAnnotationsDoNotHaveADeploymentKey(){ - assertNull("Exp. to get the deployment", capability.getDeployment()); - } - + private DeploymentTraceability capability; + + @Mock + private IReplicationController deployment; + @Mock + private IPod resource; + @Mock + private IClient client; + + @Before + public void setUp() { + capability = new DeploymentTraceability(resource, client); + + when(resource.getNamespaceName()).thenReturn("mynamespace"); + + when(client.get(eq(ResourceKind.REPLICATION_CONTROLLER), eq("foobar"), eq("mynamespace"))) + .thenReturn(deployment); + } + + @Test + public void supportedWhenAnnotationsHaveADeploymentKey() { + when(resource.isAnnotatedWith(eq("deployment"))).thenReturn(true); + when(resource.getAnnotation("deployment")).thenReturn("foobar"); + + assertEquals("Exp. to get the deployment", deployment, capability.getDeployment()); + + verify(client).get(eq(ResourceKind.REPLICATION_CONTROLLER), eq("foobar"), eq("mynamespace")); + } + + @Test + public void unsupportedWhenAnnotationsDoNotHaveADeploymentKey() { + assertNull("Exp. to get the deployment", capability.getDeployment()); + } + } diff --git a/src/test/java/com/openshift/internal/restclient/capability/resources/DockerManifestComparatorTest.java b/src/test/java/com/openshift/internal/restclient/capability/resources/DockerManifestComparatorTest.java new file mode 100644 index 00000000..57e900df --- /dev/null +++ b/src/test/java/com/openshift/internal/restclient/capability/resources/DockerManifestComparatorTest.java @@ -0,0 +1,48 @@ +/******************************************************************************* + * Copyright (c) 2016 Red Hat, Inc. + * Distributed under license by Red Hat, Inc. All rights reserved. + * This program is made available under the terms of the + * Eclipse Public License v1.0 which accompanies this distribution, + * and is available at http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Red Hat, Inc. - initial API and implementation + ******************************************************************************/ + +package com.openshift.internal.restclient.capability.resources; + +import static org.junit.Assert.assertEquals; + +import java.util.List; +import java.util.stream.Collectors; + +import org.jboss.dmr.ModelNode; +import org.junit.Before; +import org.junit.Test; + +import com.openshift.internal.restclient.capability.resources.DockerRegistryImageStreamImportCapability.ManifestComparator; +import com.openshift.restclient.utils.Samples; + +public class DockerManifestComparatorTest { + + private ModelNode root; + private ManifestComparator comparator = new ManifestComparator(); + + @Before + public void setUp() throws Exception { + root = ModelNode.fromJSONString(Samples.V1_DOCKER_IMAGE_MANIFEST.getContentAsString()); + } + + @Test + public void testCompareWithMultipleHistoryEntries() { + ModelNode history = root.get("history"); + List entries = history.asList().stream() + .map(n -> ModelNode.fromJSONString(n.get("v1Compatibility").asString())).collect(Collectors.toList()); + entries.sort(comparator); + + ModelNode last = entries.get(entries.size() - 1); + assertEquals("Exp. to retrieve the 'newest' entry with a non-null parent", + "5f162644b2633962f753b9a09c7783d342c8aaebccaf6270fde68404d2af7a8c", last.get("id").asString()); + } + +} diff --git a/src/test/java/com/openshift/internal/restclient/capability/resources/IPodLogRetrievalAsyncOptionsTest.java b/src/test/java/com/openshift/internal/restclient/capability/resources/IPodLogRetrievalAsyncOptionsTest.java new file mode 100644 index 00000000..e375cbdb --- /dev/null +++ b/src/test/java/com/openshift/internal/restclient/capability/resources/IPodLogRetrievalAsyncOptionsTest.java @@ -0,0 +1,63 @@ +/******************************************************************************* + * Copyright (c) 2016 Red Hat, Inc. + * Distributed under license by Red Hat, Inc. All rights reserved. + * This program is made available under the terms of the + * Eclipse Public License v1.0 which accompanies this distribution, + * and is available at http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Red Hat, Inc. - initial API and implementation + ******************************************************************************/ + +package com.openshift.internal.restclient.capability.resources; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNull; + +import org.junit.Before; +import org.junit.Test; + +import com.openshift.restclient.capability.resources.IPodLogRetrievalAsync.Options; + +public class IPodLogRetrievalAsyncOptionsTest { + + private Options options = new Options(); + + @Before + public void setUp() throws Exception { + } + + @Test + public void testFollowDoesNotOverrideParameter() { + assertEquals("false", options.follow().parameter("follow", "false").getMap().get("follow")); + + } + + @Test + public void testFollowIsAddedWhenTrue() { + assertEquals("true", options.follow().getMap().get("follow")); + } + + @Test + public void testFollowIsNotAddedWhenFalse() { + assertNull(options.follow(false).getMap().get("follow")); + } + + @Test + public void testContainerDoesNotOverrideParameter() { + assertEquals("foo", options.container("bar").parameter("container", "foo").getMap().get("container")); + + } + + @Test + public void testContainerAddedWhenNotEmpty() { + assertEquals("bar", options.container("bar").getMap().get("container")); + + } + + @Test + public void testContainerNotAddedWhenEmpty() { + assertNull(options.container(" ").getMap().get("container")); + + } +} diff --git a/src/test/java/com/openshift/internal/restclient/capability/resources/ImageStreamImportCapabilityIntegrationTest.java b/src/test/java/com/openshift/internal/restclient/capability/resources/ImageStreamImportCapabilityIntegrationTest.java index 5374c21b..858e9523 100644 --- a/src/test/java/com/openshift/internal/restclient/capability/resources/ImageStreamImportCapabilityIntegrationTest.java +++ b/src/test/java/com/openshift/internal/restclient/capability/resources/ImageStreamImportCapabilityIntegrationTest.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2016 Red Hat, Inc. + * Copyright (c) 2016-2019 Red Hat, Inc. * Distributed under license by Red Hat, Inc. All rights reserved. * This program is made available under the terms of the * Eclipse Public License v1.0 which accompanies this distribution, @@ -8,61 +8,63 @@ * Contributors: * Red Hat, Inc. - initial API and implementation ******************************************************************************/ + package com.openshift.internal.restclient.capability.resources; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; import org.junit.After; +import org.junit.Assert; import org.junit.Before; import org.junit.Test; import com.openshift.internal.restclient.IntegrationTestHelper; import com.openshift.restclient.IClient; -import com.openshift.restclient.ResourceKind; import com.openshift.restclient.capability.resources.IImageStreamImportCapability; +import com.openshift.restclient.http.IHttpConstants; import com.openshift.restclient.images.DockerImageURI; import com.openshift.restclient.model.IProject; -import com.openshift.restclient.model.IResource; +import com.openshift.restclient.model.IStatus; import com.openshift.restclient.model.image.IImageStreamImport; -import junit.framework.Assert; - -/** - * - * @author jeff.cantrill - * - */ public class ImageStreamImportCapabilityIntegrationTest { - private IImageStreamImportCapability cap; - private IProject project; - private IClient client; - private IntegrationTestHelper helper = new IntegrationTestHelper(); - - @Before - public void setUp() throws Exception { - client = helper.createClientForBasicAuth(); - IResource request = client.getResourceFactory().stub(ResourceKind.PROJECT_REQUEST, helper.generateNamespace()); - project = (IProject) client.create(request); - cap = new ImageStreamImportCapability(project, client); - } - - @After - public void tearDown() { - IntegrationTestHelper.cleanUpResource(client, project); - } + private IImageStreamImportCapability cap; + private IProject project; + private IClient client; + private IntegrationTestHelper helper = new IntegrationTestHelper(); + private IImageStreamImport imageStreamImport; + + @Before + public void setUp() throws Exception { + this.client = helper.createClientForBasicAuth(); + this.project = helper.getOrCreateIntegrationTestProject(client); + this.cap = new ImageStreamImportCapability(project, client); + } + + @After + public void tearDown() { + helper.cleanUpResource(client, imageStreamImport); + } - @Test - public void testImportImageForExistingImage() { - DockerImageURI image = new DockerImageURI("openshift/hello-openshift"); - IImageStreamImport imported = cap.importImageMetadata(image); - Assert.assertNotNull(imported); - } + @Test + public void testImportImageForExistingImage() { + DockerImageURI image = new DockerImageURI("openshift/hello-openshift"); + this.imageStreamImport = cap.importImageMetadata(image); + assertNotNull(imageStreamImport); + IStatus status = imageStreamImport.getImageStatus().iterator().next(); + assertTrue(status.isSuccess()); + } - @Test - public void testImportImageForUnknownImage() { - DockerImageURI image = new DockerImageURI("openshift/hello-openshifts"); - IImageStreamImport imported = cap.importImageMetadata(image); - Assert.assertNotNull(imported); - } + @Test + public void testImportImageForUnknownImage() { + DockerImageURI image = new DockerImageURI("openshift/hello-openshifts"); + this.imageStreamImport = cap.importImageMetadata(image); + Assert.assertNotNull(imageStreamImport); + IStatus status = imageStreamImport.getImageStatus().iterator().next(); + assertEquals(IHttpConstants.STATUS_UNAUTHORIZED, status.getCode()); // exp code when image does not exist + } } diff --git a/src/test/java/com/openshift/internal/restclient/capability/resources/ImageStreamImportCapabilityTest.java b/src/test/java/com/openshift/internal/restclient/capability/resources/ImageStreamImportCapabilityTest.java index e2b2504d..68310d76 100644 --- a/src/test/java/com/openshift/internal/restclient/capability/resources/ImageStreamImportCapabilityTest.java +++ b/src/test/java/com/openshift/internal/restclient/capability/resources/ImageStreamImportCapabilityTest.java @@ -8,10 +8,14 @@ * Contributors: * Red Hat, Inc. - initial API and implementation ******************************************************************************/ + package com.openshift.internal.restclient.capability.resources; -import static org.junit.Assert.*; -import static org.mockito.Mockito.*; +import static org.junit.Assert.assertEquals; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; import java.util.Arrays; @@ -19,7 +23,7 @@ import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; -import org.mockito.runners.MockitoJUnitRunner; +import org.mockito.junit.MockitoJUnitRunner; import com.openshift.restclient.IClient; import com.openshift.restclient.IResourceFactory; @@ -29,49 +33,43 @@ import com.openshift.restclient.model.IStatus; import com.openshift.restclient.model.image.IImageStreamImport; -/** - * - * @author jeff.cantrill - * - */ @RunWith(MockitoJUnitRunner.class) public class ImageStreamImportCapabilityTest { - private IImageStreamImportCapability cap; - @Mock - private IProject project; - @Mock - private IClient client; - @Mock - private IResourceFactory factory; - @Mock - private IImageStreamImport streamImport; - @Mock - private IStatus status; - - @Before - public void setUp() throws Exception { - when(project.getName()).thenReturn("aProjectName"); - when(client.getResourceFactory()).thenReturn(factory); - when(factory.stub(anyString(), anyString(), anyString())).thenReturn(streamImport); - when(client.create(any(IImageStreamImport.class))).thenReturn(streamImport); - - when(status.getStatus()).thenReturn("Success"); - when(streamImport.getImageStatus()).thenReturn(Arrays.asList(status)); - - cap = new ImageStreamImportCapability(project, client); - } + private IImageStreamImportCapability cap; + @Mock + private IProject project; + @Mock + private IClient client; + @Mock + private IResourceFactory factory; + @Mock + private IImageStreamImport streamImport; + @Mock + private IStatus status; + + @Before + public void setUp() throws Exception { + when(project.getName()).thenReturn("aProjectName"); + when(client.getResourceFactory()).thenReturn(factory); + when(factory.stub(anyString(), anyString(), anyString())).thenReturn(streamImport); + when(client.create(any(IImageStreamImport.class))).thenReturn(streamImport); + + when(status.getStatus()).thenReturn("Success"); + when(streamImport.getImageStatus()).thenReturn(Arrays.asList(status)); + + cap = new ImageStreamImportCapability(project, client); + } + + @Test + public void testImportImageInfo() { + DockerImageURI image = new DockerImageURI("foo/hello-world"); + IImageStreamImport imported = cap.importImageMetadata(image); + assertEquals(imported, streamImport); - @Test - public void testImportImageInfo() { - DockerImageURI image = new DockerImageURI("foo/hello-world"); - IImageStreamImport imported = cap.importImageMetadata(image); - assertEquals(imported, streamImport); - - verify(client).create(streamImport); - verify(streamImport).addImage("DockerImage", image); - + verify(client).create(streamImport); + verify(streamImport).addImage("DockerImage", image); - } + } } diff --git a/src/test/java/com/openshift/internal/restclient/capability/resources/OpenShiftBinaryPortForwardingIntegrationTest2.java b/src/test/java/com/openshift/internal/restclient/capability/resources/OpenShiftBinaryPortForwardingIntegrationTest2.java new file mode 100644 index 00000000..9f64d9f3 --- /dev/null +++ b/src/test/java/com/openshift/internal/restclient/capability/resources/OpenShiftBinaryPortForwardingIntegrationTest2.java @@ -0,0 +1,99 @@ +/******************************************************************************* + * Copyright (c) 2015-2019 Red Hat, Inc. + * Distributed under license by Red Hat, Inc. All rights reserved. + * This program is made available under the terms of the + * Eclipse Public License v1.0 which accompanies this distribution, + * and is available at http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Red Hat, Inc. - initial API and implementation + ******************************************************************************/ + +package com.openshift.internal.restclient.capability.resources; + +import static org.junit.Assert.assertNotNull; + +import java.net.HttpURLConnection; +import java.net.URL; +import java.nio.charset.StandardCharsets; +import java.util.Arrays; + +import org.apache.commons.io.IOUtils; +import org.jboss.dmr.ModelNode; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; + +import com.openshift.internal.restclient.IntegrationTestHelper; +import com.openshift.internal.restclient.PodStatusRunningConditional; +import com.openshift.internal.restclient.model.Port; +import com.openshift.internal.restclient.model.properties.ResourcePropertyKeys; +import com.openshift.restclient.IClient; +import com.openshift.restclient.capability.CapabilityVisitor; +import com.openshift.restclient.capability.IBinaryCapability; +import com.openshift.restclient.capability.IBinaryCapability.SkipTlsVerify; +import com.openshift.restclient.capability.resources.IPortForwardable; +import com.openshift.restclient.capability.resources.IPortForwardable.PortPair; +import com.openshift.restclient.model.IPod; +import com.openshift.restclient.model.IProject; + +public class OpenShiftBinaryPortForwardingIntegrationTest2 implements ResourcePropertyKeys { + + private IntegrationTestHelper helper = new IntegrationTestHelper(); + private IClient client; + private IProject project; + private IPod pod; + + @Before + public void setUp() throws Exception { + System.setProperty(IBinaryCapability.OPENSHIFT_BINARY_LOCATION, helper.getOpenShiftLocation()); + this.client = helper.createClientForBasicAuth(); + this.project = helper.getOrCreateIntegrationTestProject(client); + IPod pod = helper.getOrCreatePod(client, project.getNamespaceName(), IntegrationTestHelper.IMAGE_HELLO_OPENSHIFT); + this.pod = helper.waitForResource( + client, + pod, + 5 * IntegrationTestHelper.MILLISECONDS_PER_MIN, + new PodStatusRunningConditional()); + + } + + @After + public void teardown() throws Exception { + helper.cleanUpResource(client, pod); + } + + @Test + public void testPortForwarding() { + assertNotNull("The test timed out before the pod was in a running state", pod); + + final Port port = new Port(new ModelNode()); + port.setProtocol("tcp"); + port.setContainerPort(8080); + pod.accept(new CapabilityVisitor() { + + @Override + public Object visit(IPortForwardable capability) { + capability.forwardPorts(Arrays.asList(new PortPair(8181, port)), new SkipTlsVerify()); + try { + Thread.sleep(5 * IntegrationTestHelper.MILLISECONDS_PER_SECOND); + curl(); + } catch (Exception e) { + e.printStackTrace(); + } + capability.stop(); + return null; + } + }, new Object()); + } + + private void curl() throws Exception { + URL url = new URL("http://localhost:8181"); + HttpURLConnection con = (HttpURLConnection) url.openConnection(); + con.setRequestMethod("GET"); + con.setDoInput(true); + con.connect(); + System.out.println(IOUtils.toString(con.getInputStream(), StandardCharsets.UTF_8)); + con.disconnect(); + } +} diff --git a/src/test/java/com/openshift/internal/restclient/capability/resources/OpenShiftBinaryPortForwardingTest.java b/src/test/java/com/openshift/internal/restclient/capability/resources/OpenShiftBinaryPortForwardingTest.java new file mode 100644 index 00000000..a1afcceb --- /dev/null +++ b/src/test/java/com/openshift/internal/restclient/capability/resources/OpenShiftBinaryPortForwardingTest.java @@ -0,0 +1,99 @@ +/******************************************************************************* + * Copyright (c) 2018 Red Hat, Inc. + * Distributed under license by Red Hat, Inc. All rights reserved. + * This program is made available under the terms of the + * Eclipse Public License v1.0 which accompanies this distribution, + * and is available at http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Red Hat, Inc. - initial API and implementation + ******************************************************************************/ + +package com.openshift.internal.restclient.capability.resources; + +import static com.openshift.internal.restclient.capability.resources.testutils.BinaryCapabilityTestMocks.OC_LOCATION; +import static com.openshift.internal.restclient.capability.resources.testutils.BinaryCapabilityTestMocks.POD_NAME; +import static com.openshift.internal.restclient.capability.resources.testutils.BinaryCapabilityTestMocks.POD_NAMESPACE; +import static com.openshift.internal.restclient.capability.resources.testutils.BinaryCapabilityTestMocks.SERVER_URL; +import static com.openshift.internal.restclient.capability.resources.testutils.BinaryCapabilityTestMocks.TOKEN; +import static com.openshift.internal.restclient.capability.resources.testutils.BinaryCapabilityTestMocks.mockClient; +import static com.openshift.internal.restclient.capability.resources.testutils.BinaryCapabilityTestMocks.mockPod; +import static com.openshift.internal.restclient.capability.resources.testutils.BinaryCapabilityTestMocks.mockPortPair; +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.doReturn; +import static org.mockito.Mockito.spy; +import static org.mockito.Mockito.verify; + +import java.net.MalformedURLException; +import java.util.Arrays; +import java.util.List; + +import org.junit.Before; +import org.junit.Test; +import org.mockito.ArgumentCaptor; + +import com.openshift.restclient.IClient; +import com.openshift.restclient.capability.IBinaryCapability.SkipTlsVerify; +import com.openshift.restclient.capability.resources.IPortForwardable.PortPair; +import com.openshift.restclient.model.IPod; + +public class OpenShiftBinaryPortForwardingTest { + + private static final int LOCAL_PORT1 = 8080; + private static final int REMOTE_PORT1 = 80; + + private static final int LOCAL_PORT2 = 8443; + private static final int REMOTE_PORT2 = 43; + + private IPod pod; + + private OpenShiftBinaryPortForwarding binaryPortForwarding; + + @Before + public void before() throws MalformedURLException { + IClient client = mockClient(); + this.pod = mockPod(); + this.binaryPortForwarding = createBinaryPortForwarding(pod, client); + } + + private OpenShiftBinaryPortForwarding createBinaryPortForwarding(IPod pod, IClient client) { + OpenShiftBinaryPortForwarding portForwarding = spy(new OpenShiftBinaryPortForwarding(pod, client)); + doReturn(OC_LOCATION).when(portForwarding).getOpenShiftBinaryLocation(); + doReturn(null).when(portForwarding).startProcess(any(ProcessBuilder.class)); + return portForwarding; + } + + @Test + public void shouldBuildCommandLineWithoutSkipSSL() { + // given + ArgumentCaptor processBuilderArgument = ArgumentCaptor.forClass(ProcessBuilder.class); + List ports = Arrays.asList(mockPortPair(LOCAL_PORT2, REMOTE_PORT2)); + // when + binaryPortForwarding.forwardPorts(ports); + // then + verify(binaryPortForwarding).startProcess(processBuilderArgument.capture()); + ProcessBuilder builder = processBuilderArgument.getValue(); + assertThat(builder.command()) + .isEqualTo(Arrays.asList(OC_LOCATION, OpenShiftBinaryPortForwarding.PORT_FORWARD_COMMAND, + "--token=" + TOKEN, "--server=" + SERVER_URL.toString(), "-n", POD_NAMESPACE, POD_NAME, + LOCAL_PORT2 + ":" + REMOTE_PORT2)); + } + + @Test + public void shouldBuildCommandLineWith2PortsSkipSSL() { + // given + ArgumentCaptor processBuilderArgument = ArgumentCaptor.forClass(ProcessBuilder.class); + List ports = Arrays.asList(mockPortPair(LOCAL_PORT1, REMOTE_PORT1), + mockPortPair(LOCAL_PORT2, REMOTE_PORT2)); + // when + binaryPortForwarding.forwardPorts(ports, new SkipTlsVerify()); + // then + verify(binaryPortForwarding).startProcess(processBuilderArgument.capture()); + ProcessBuilder builder = processBuilderArgument.getValue(); + assertThat(builder.command()).isEqualTo( + Arrays.asList(OC_LOCATION, OpenShiftBinaryPortForwarding.PORT_FORWARD_COMMAND, "--token=" + TOKEN, + "--server=" + SERVER_URL.toString(), "--insecure-skip-tls-verify=true", "-n", POD_NAMESPACE, + POD_NAME, LOCAL_PORT1 + ":" + REMOTE_PORT1, LOCAL_PORT2 + ":" + REMOTE_PORT2)); + } +} diff --git a/src/test/java/com/openshift/internal/restclient/capability/resources/OpenShiftBinaryRSyncTest.java b/src/test/java/com/openshift/internal/restclient/capability/resources/OpenShiftBinaryRSyncTest.java new file mode 100644 index 00000000..7b633017 --- /dev/null +++ b/src/test/java/com/openshift/internal/restclient/capability/resources/OpenShiftBinaryRSyncTest.java @@ -0,0 +1,115 @@ +/******************************************************************************* + * Copyright (c) 2018 Red Hat, Inc. + * Distributed under license by Red Hat, Inc. All rights reserved. + * This program is made available under the terms of the + * Eclipse Public License v1.0 which accompanies this distribution, + * and is available at http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Red Hat, Inc. - initial API and implementation + ******************************************************************************/ + +package com.openshift.internal.restclient.capability.resources; + +import static com.openshift.internal.restclient.capability.resources.testutils.BinaryCapabilityTestMocks.OC_LOCATION; +import static com.openshift.internal.restclient.capability.resources.testutils.BinaryCapabilityTestMocks.POD_NAME; +import static com.openshift.internal.restclient.capability.resources.testutils.BinaryCapabilityTestMocks.POD_NAMESPACE; +import static com.openshift.internal.restclient.capability.resources.testutils.BinaryCapabilityTestMocks.SERVER_URL; +import static com.openshift.internal.restclient.capability.resources.testutils.BinaryCapabilityTestMocks.TOKEN; +import static com.openshift.internal.restclient.capability.resources.testutils.BinaryCapabilityTestMocks.mockClient; +import static com.openshift.internal.restclient.capability.resources.testutils.BinaryCapabilityTestMocks.mockPod; +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.doReturn; +import static org.mockito.Mockito.spy; +import static org.mockito.Mockito.verify; + +import java.net.MalformedURLException; +import java.util.Arrays; + +import org.junit.Before; +import org.junit.Test; +import org.mockito.ArgumentCaptor; + +import com.openshift.restclient.IClient; +import com.openshift.restclient.capability.IBinaryCapability.SkipTlsVerify; +import com.openshift.restclient.capability.resources.IRSyncable.Exclude; +import com.openshift.restclient.capability.resources.IRSyncable.GitFolderExclude; +import com.openshift.restclient.capability.resources.IRSyncable.LocalPeer; +import com.openshift.restclient.capability.resources.IRSyncable.NoPerms; +import com.openshift.restclient.capability.resources.IRSyncable.Peer; +import com.openshift.restclient.capability.resources.IRSyncable.PodPeer; +import com.openshift.restclient.model.IPod; + +public class OpenShiftBinaryRSyncTest { + + private static final String LOCAL_PATH = "/local/42"; + private static final String POD_PATH = "/deployment/42"; + + private IPod pod; + + private OpenShiftBinaryRSync binaryRsync; + + @Before + public void before() throws MalformedURLException { + IClient client = mockClient(); + this.pod = mockPod(); + this.binaryRsync = createBinaryRSync(client); + } + + private OpenShiftBinaryRSync createBinaryRSync(IClient client) { + OpenShiftBinaryRSync binaryRsync = spy(new OpenShiftBinaryRSync(client)); + doReturn(OC_LOCATION).when(binaryRsync).getOpenShiftBinaryLocation(); + doReturn(null).when(binaryRsync).startProcess(any(ProcessBuilder.class)); + return binaryRsync; + } + + @Test + public void shouldBuildCommandLineWithoutSkipSSL() { + // given + ArgumentCaptor processBuilderArgument = ArgumentCaptor.forClass(ProcessBuilder.class); + Peer localPeer = new LocalPeer(LOCAL_PATH); + PodPeer podPeer = new PodPeer(POD_PATH, pod); + // when + binaryRsync.sync(localPeer, podPeer); + // then + verify(binaryRsync).startProcess(processBuilderArgument.capture()); + ProcessBuilder builder = processBuilderArgument.getValue(); + assertThat(builder.command()).isEqualTo(Arrays.asList(OC_LOCATION, OpenShiftBinaryRSync.RSYNC_COMMAND, + "--token=" + TOKEN, "--server=" + SERVER_URL.toString(), "-n", POD_NAMESPACE, LOCAL_PATH, + POD_NAME + ":" + POD_PATH)); + } + + @Test + public void shouldBuildCommandLineWithSkipSSLNoPermsGitExclude() { + // given + ArgumentCaptor processBuilderArgument = ArgumentCaptor.forClass(ProcessBuilder.class); + Peer localPeer = new LocalPeer(LOCAL_PATH); + PodPeer podPeer = new PodPeer(POD_PATH, pod); + // when + binaryRsync.sync(localPeer, podPeer, new SkipTlsVerify(), new NoPerms(), new GitFolderExclude()); + // then + verify(binaryRsync).startProcess(processBuilderArgument.capture()); + ProcessBuilder builder = processBuilderArgument.getValue(); + assertThat(builder.command()) + .isEqualTo(Arrays.asList(OC_LOCATION, OpenShiftBinaryRSync.RSYNC_COMMAND, "--token=" + TOKEN, + "--server=" + SERVER_URL.toString(), "-n", POD_NAMESPACE, "--insecure-skip-tls-verify=true", + "--no-perms=true", "--exclude=.git", LOCAL_PATH, POD_NAME + ":" + POD_PATH)); + } + + @Test + public void shouldBuildCommandLineWithExcludeDotGitDotNpm() { + // given + ArgumentCaptor processBuilderArgument = ArgumentCaptor.forClass(ProcessBuilder.class); + Peer localPeer = new LocalPeer(LOCAL_PATH); + PodPeer podPeer = new PodPeer(POD_PATH, pod); + // when + binaryRsync.sync(localPeer, podPeer, new Exclude(".git", ".npm")); + // then + verify(binaryRsync).startProcess(processBuilderArgument.capture()); + ProcessBuilder builder = processBuilderArgument.getValue(); + assertThat(builder.command()).isEqualTo(Arrays.asList(OC_LOCATION, OpenShiftBinaryRSync.RSYNC_COMMAND, + "--token=" + TOKEN, "--server=" + SERVER_URL.toString(), "-n", POD_NAMESPACE, "--exclude=.git", + "--exclude=.npm", LOCAL_PATH, POD_NAME + ":" + POD_PATH)); + } +} diff --git a/src/test/java/com/openshift/internal/restclient/capability/resources/OpenshiftBinaryPodLogRetrievalIntegrationTest.java b/src/test/java/com/openshift/internal/restclient/capability/resources/OpenshiftBinaryPodLogRetrievalIntegrationTest.java deleted file mode 100644 index 0a9d4dca..00000000 --- a/src/test/java/com/openshift/internal/restclient/capability/resources/OpenshiftBinaryPodLogRetrievalIntegrationTest.java +++ /dev/null @@ -1,66 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2015 Red Hat, Inc. - * Distributed under license by Red Hat, Inc. All rights reserved. - * This program is made available under the terms of the - * Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * Red Hat, Inc. - initial API and implementation - ******************************************************************************/ -package com.openshift.internal.restclient.capability.resources; - - -import java.io.BufferedInputStream; - -import org.junit.Before; -import org.junit.Test; - -import com.openshift.internal.restclient.IntegrationTestHelper; -import com.openshift.restclient.IClient; -import com.openshift.restclient.ResourceKind; -import com.openshift.restclient.capability.CapabilityVisitor; -import com.openshift.restclient.capability.IBinaryCapability; -import com.openshift.restclient.capability.resources.IPodLogRetrieval; -import com.openshift.restclient.model.IPod; - -/** - * - * @author Jeff Cantrill - * - */ -public class OpenshiftBinaryPodLogRetrievalIntegrationTest { - - private static final String HELLO_OPENSHIFT = "docker-registry-1-uuho4"; - private IntegrationTestHelper helper = new IntegrationTestHelper(); - @Before - public void setUp() throws Exception { - } - - @Test - public void testLogRetrieval() { - System.setProperty(IBinaryCapability.OPENSHIFT_BINARY_LOCATION, helper.getOpenShiftLocation()); - IClient client = helper.createClientForBasicAuth(); - IPod pod = client.get(ResourceKind.POD, HELLO_OPENSHIFT, "default"); - - pod.accept(new CapabilityVisitor() { - - @Override - public Object visit(IPodLogRetrieval cap) { - try { - BufferedInputStream os = new BufferedInputStream(cap.getLogs(false, ""));//HELLO_OPENSHIFT)); - int c; - while((c = os.read()) != -1) { - System.out.print((char)c); - } - } catch (Exception e) { - e.printStackTrace(); - }finally { - cap.stop(); - } - return null; - } - - }, new Object()); - } -} diff --git a/src/test/java/com/openshift/internal/restclient/capability/resources/OpenshiftBinaryPodLogRetrievalIntegrationTest2.java b/src/test/java/com/openshift/internal/restclient/capability/resources/OpenshiftBinaryPodLogRetrievalIntegrationTest2.java new file mode 100644 index 00000000..2ea67a5f --- /dev/null +++ b/src/test/java/com/openshift/internal/restclient/capability/resources/OpenshiftBinaryPodLogRetrievalIntegrationTest2.java @@ -0,0 +1,85 @@ +/******************************************************************************* + * Copyright (c) 2015-2018 Red Hat, Inc. + * Distributed under license by Red Hat, Inc. All rights reserved. + * This program is made available under the terms of the + * Eclipse Public License v1.0 which accompanies this distribution, + * and is available at http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Red Hat, Inc. - initial API and implementation + ******************************************************************************/ + +package com.openshift.internal.restclient.capability.resources; + +import static org.junit.Assert.assertNull; + +import java.io.BufferedInputStream; + +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.openshift.internal.restclient.IntegrationTestHelper; +import com.openshift.internal.restclient.PodStatusRunningConditional; +import com.openshift.restclient.IClient; +import com.openshift.restclient.capability.CapabilityVisitor; +import com.openshift.restclient.capability.IBinaryCapability.SkipTlsVerify; +import com.openshift.restclient.capability.resources.IPodLogRetrieval; +import com.openshift.restclient.model.IPod; +import com.openshift.restclient.model.IProject; + +public class OpenshiftBinaryPodLogRetrievalIntegrationTest2 { + private static final Logger LOG = LoggerFactory.getLogger(OpenshiftBinaryPodLogRetrievalIntegrationTest2.class); + private IntegrationTestHelper helper = new IntegrationTestHelper(); + private IClient client; + private IProject project; + private IPod pod; + + @Before + public void before() { + helper.setOpenShiftBinarySystemProperty(); + this.client = helper.createClientForBasicAuth(); + this.project = helper.getOrCreateIntegrationTestProject(client); + IPod pod = helper.getOrCreatePod(client, project.getNamespaceName(), IntegrationTestHelper.IMAGE_HELLO_OPENSHIFT); + this.pod = helper.waitForResource( + client, + pod, + 5 * IntegrationTestHelper.MILLISECONDS_PER_MIN, + new PodStatusRunningConditional()); + } + + @After + public void after() { + helper.cleanUpResource(client, pod); + } + + @Test + public void testLogRetrieval() { + Exception ex = pod.accept(new CapabilityVisitor() { + + @Override + public Exception visit(IPodLogRetrieval cap) { + StringBuilder builder = new StringBuilder(); + try { + BufferedInputStream os = new BufferedInputStream(cap.getLogs(false, new SkipTlsVerify())); + int c; + while ((c = os.read()) != -1) { + builder.append((char) c); + } + } catch (Exception e) { + LOG.error("There was an error: ", e); + return e; + } finally { + LOG.info(builder.toString()); + cap.stop(); + } + return null; + } + + }, null); + + assertNull("Expected no exception", ex); + } +} diff --git a/src/test/java/com/openshift/internal/restclient/capability/resources/OpenshiftBinaryPortForwardingIntegrationTest.java b/src/test/java/com/openshift/internal/restclient/capability/resources/OpenshiftBinaryPortForwardingIntegrationTest.java deleted file mode 100644 index 36aaf011..00000000 --- a/src/test/java/com/openshift/internal/restclient/capability/resources/OpenshiftBinaryPortForwardingIntegrationTest.java +++ /dev/null @@ -1,85 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2015 Red Hat, Inc. - * Distributed under license by Red Hat, Inc. All rights reserved. - * This program is made available under the terms of the - * Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * Red Hat, Inc. - initial API and implementation - ******************************************************************************/ -package com.openshift.internal.restclient.capability.resources; - - -import java.net.HttpURLConnection; -import java.net.URL; -import java.util.Arrays; - -import org.apache.commons.io.IOUtils; -import org.jboss.dmr.ModelNode; -import org.junit.Before; -import org.junit.Test; - -import com.openshift.internal.restclient.IntegrationTestHelper; -import com.openshift.internal.restclient.model.Pod; -import com.openshift.internal.restclient.model.Port; -import com.openshift.restclient.IClient; -import com.openshift.restclient.IResourceFactory; -import com.openshift.restclient.ResourceKind; -import com.openshift.restclient.capability.CapabilityVisitor; -import com.openshift.restclient.capability.IBinaryCapability; -import com.openshift.restclient.capability.IBinaryCapability.OpenShiftBinaryOption; -import com.openshift.restclient.capability.resources.IPortForwardable; -import com.openshift.restclient.capability.resources.IPortForwardable.PortPair; - -/** - * - * @author Jeff Cantrill - * - */ -public class OpenshiftBinaryPortForwardingIntegrationTest { - - private IntegrationTestHelper helper = new IntegrationTestHelper(); - @Before - public void setUp() throws Exception { - } - - @Test - public void testPortForwarding() { - System.setProperty(IBinaryCapability.OPENSHIFT_BINARY_LOCATION, helper.getOpenShiftLocation()); - IClient client = helper.createClient(); - IResourceFactory resourceFactory = client.getResourceFactory(); - Pod pod = resourceFactory.create("v1", ResourceKind.POD); - final Port port = new Port(new ModelNode()); - port.setProtocol("tcp"); - port.setContainerPort(8080); - pod.setName("hello-openshift"); - pod.setNamespace("test"); - - pod.accept(new CapabilityVisitor() { - - @Override - public Object visit(IPortForwardable capability) { - capability.forwardPorts(Arrays.asList(new PortPair(8181, port)), OpenShiftBinaryOption.SKIP_TLS_VERIFY); - try { - Thread.sleep(5 * 1000); - curl(); - } catch (Exception e) { - e.printStackTrace(); - } - capability.stop(); - return null; - } - }, new Object()); - } - - private void curl() throws Exception { - URL url = new URL("http://localhost:8181"); - HttpURLConnection con = (HttpURLConnection) url.openConnection(); - con.setRequestMethod("GET"); - con.setDoInput(true); - con.connect(); - System.out.println(IOUtils.toString(con.getInputStream())); - con.disconnect(); - } -} diff --git a/src/test/java/com/openshift/internal/restclient/capability/resources/OpenshiftBinaryRSyncRetrievalIntegrationTest.java b/src/test/java/com/openshift/internal/restclient/capability/resources/OpenshiftBinaryRSyncRetrievalIntegrationTest.java index b271c29a..91e725a5 100644 --- a/src/test/java/com/openshift/internal/restclient/capability/resources/OpenshiftBinaryRSyncRetrievalIntegrationTest.java +++ b/src/test/java/com/openshift/internal/restclient/capability/resources/OpenshiftBinaryRSyncRetrievalIntegrationTest.java @@ -1,6 +1,5 @@ -package com.openshift.internal.restclient.capability.resources; /******************************************************************************* - * Copyright (c) 2015 Red Hat, Inc. + * Copyright (c) 2015-2019 Red Hat, Inc. * Distributed under license by Red Hat, Inc. All rights reserved. * This program is made available under the terms of the * Eclipse Public License v1.0 which accompanies this distribution, @@ -10,38 +9,42 @@ * Red Hat, Inc. - initial API and implementation ******************************************************************************/ +package com.openshift.internal.restclient.capability.resources; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; + import java.io.BufferedReader; import java.io.File; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.List; -import java.util.Queue; +import java.util.concurrent.TimeUnit; -import static org.fest.assertions.Assertions.*; +import org.apache.commons.io.IOUtils; +import org.junit.After; import org.junit.Before; +import org.junit.Rule; import org.junit.Test; +import org.junit.rules.TemporaryFolder; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.openshift.internal.restclient.IntegrationTestHelper; -import com.openshift.internal.restclient.ResourceFactory; -import com.openshift.internal.restclient.authorization.AuthorizationClient; -import com.openshift.restclient.ClientBuilder; +import com.openshift.internal.restclient.api.capabilities.PodExecIntegrationTest; import com.openshift.restclient.IClient; -import com.openshift.restclient.NoopSSLCertificateCallback; -import com.openshift.restclient.ResourceKind; -import com.openshift.restclient.authorization.BasicAuthorizationStrategy; -import com.openshift.restclient.authorization.IAuthorizationClient; -import com.openshift.restclient.authorization.IAuthorizationContext; -import com.openshift.restclient.authorization.TokenAuthorizationStrategy; +import com.openshift.restclient.api.capabilities.IPodExec; import com.openshift.restclient.capability.CapabilityVisitor; -import com.openshift.restclient.capability.IBinaryCapability; +import com.openshift.restclient.capability.IBinaryCapability.SkipTlsVerify; +import com.openshift.restclient.capability.IStoppable; import com.openshift.restclient.capability.resources.IRSyncable; import com.openshift.restclient.capability.resources.IRSyncable.LocalPeer; +import com.openshift.restclient.capability.resources.IRSyncable.Peer; import com.openshift.restclient.capability.resources.IRSyncable.PodPeer; import com.openshift.restclient.model.IPod; -import com.openshift.restclient.model.IService; +import com.openshift.restclient.model.IProject; /** * @@ -49,63 +52,147 @@ * */ public class OpenshiftBinaryRSyncRetrievalIntegrationTest { + private static final int TIMEOUT_POD_READY = 30; + + // rsync now reports special characters as octal UTF-8: 'Ă©' -> octal utf8: \\0303\\0251, hex utf8: \u00e9 + private static final String TARGET_FOLDER_WITH_SPECIAL_CHARS = "/tmp/OpenshiftBinaryRSyncRetrievalIntegrationTest/with sp@ce/"; + private static final String FILE_NAME_SPECIAL_CHARS = "test with speci@l characters and spaces"; + private static final String SOURCE_FOLDER_WITH_SPECIAL_CHARS = "with sp@ce in path"; + + private static final String NORMAL_TARGET_TMP = "/tmp/OpenshiftBinaryRSyncRetrievalIntegrationTest/withoutspace/"; + private static final String NORMAL_FILE_NAME = "normalFileName"; + private static final String NORMAL_FOLDER_NAME = "normalFolderName"; + + private static final Logger LOG = LoggerFactory.getLogger(OpenshiftBinaryRSyncRetrievalIntegrationTest.class); + + private IntegrationTestHelper helper = new IntegrationTestHelper(); + private IClient client; + + @Rule + public TemporaryFolder tmpFolder = new TemporaryFolder(); + + private IProject project; + private IPod pod; + private String podFolderToClean; + + @Before + public void setUp() throws Exception { + // given + this.helper.setOpenShiftBinarySystemProperty(); + this.client = helper.createClientForBasicAuth(); + this.project = helper.getOrCreateIntegrationTestProject(client); + this.pod = helper.getOrCreatePod(client, + project.getNamespaceName(), + getClass().getSimpleName().toLowerCase() + "-pod", + IntegrationTestHelper.IMAGE_HELLO_OPENSHIFT_ALPINE); + assertNotNull("Could not create a pod to test against.", pod); + helper.waitForPodReady(client, pod.getNamespaceName(), pod.getName(), TIMEOUT_POD_READY); + } + + @After + public void tearDown() throws Exception { + if (podFolderToClean != null) { + execOnPod(new String[] { "rm", "-r", podFolderToClean }); + } + } + + @Test + public void testRSyncLogRetrieval() throws IOException, InterruptedException { + testRsyncLogRetrieval(NORMAL_FOLDER_NAME, NORMAL_FILE_NAME, NORMAL_TARGET_TMP); + } + + @Test + public void testRSyncLogRetrievalWithSpaceInFolderToSynchronize() throws Exception { + testRsyncLogRetrieval(SOURCE_FOLDER_WITH_SPECIAL_CHARS, NORMAL_FILE_NAME, NORMAL_TARGET_TMP); + } + + @Test + public void testRSyncLogRetrievalWithSpaceInFileToSynchronize() throws Exception { + testRsyncLogRetrieval(NORMAL_FOLDER_NAME, FILE_NAME_SPECIAL_CHARS, NORMAL_TARGET_TMP); + } + + @Test + public void testRSyncLogRetrievalWithSpaceInTargetDirectory() throws Exception { + testRsyncLogRetrieval(NORMAL_FOLDER_NAME, NORMAL_FILE_NAME, TARGET_FOLDER_WITH_SPECIAL_CHARS); + } + + @Test + public void testRSyncLogRetrievalWithSpaceEverywhere() throws Exception { + testRsyncLogRetrieval(SOURCE_FOLDER_WITH_SPECIAL_CHARS, FILE_NAME_SPECIAL_CHARS, + TARGET_FOLDER_WITH_SPECIAL_CHARS); + } + + protected void testRsyncLogRetrieval(String folderToSynchronizeName, String fileNameToSynchronize, + String targetFolderPath) throws IOException, InterruptedException { + podFolderToClean = targetFolderPath; + execOnPod(new String[] { "mkdir", "-p", targetFolderPath }); + File localTempDir = tmpFolder.newFolder(folderToSynchronizeName); + // Create a dummy file locally to be sure there will be something to rsync from + // Local to Remote + File tmpFile = File.createTempFile(fileNameToSynchronize, ".txt", localTempDir); + final String fileName = tmpFile.getName(); + LocalPeer localPeer = new LocalPeer(localTempDir.getAbsolutePath() + File.separator); + PodPeer podPeer = new PodPeer(targetFolderPath, pod); + + // Check Local to Remote + rsyncAndCheck(fileName, localPeer, podPeer); + tmpFile.delete(); + + // Create a dummy file locally to be sure there will be something to rsync from + // Remote to Local + execOnPod(new String[] { "touch", targetFolderPath + "/fileToSynchronizeBackFromPodToLocal.txt" }); + + // Check Remote to Local + rsyncAndCheck("fileToSynchronizeBackFromPodToLocal", podPeer, localPeer); + assertThat(new File(localTempDir, "fileToSynchronizeBackFromPodToLocal.txt").exists()).isTrue(); + } + + protected void execOnPod(String[] commands) throws InterruptedException { + PodExecIntegrationTest.TestExecListener execListener = new PodExecIntegrationTest.TestExecListener(); + final String container = pod.getContainers().iterator().next().getName(); + IPodExec.Options options = new IPodExec.Options(); + options.container(container); + + pod.accept(new CapabilityVisitor() { + + @Override + public IStoppable visit(IPodExec capability) { + return capability.start(execListener, options, commands); + } + + }, null); + execListener.testDone.await(10, TimeUnit.SECONDS); + assertTrue(execListener.openCalled.get()); + assertTrue(execListener.closeCalled.get()); + assertTrue(!execListener.failureCalled.get()); + assertTrue(!execListener.execErrCalled.get()); + } + + protected void rsyncAndCheck(final String fileName, Peer source, Peer destination) { + List logs = pod.accept(new CapabilityVisitor>() { + + @Override + public List visit(IRSyncable cap) { + try { + final BufferedReader reader = new BufferedReader( + new InputStreamReader(cap.sync(source, destination, new SkipTlsVerify()))); + List logs = IOUtils.readLines(reader); + // wait until end of 'rsync' + cap.await(); + return logs; + } catch (Exception e) { + LOG.error("Exception rsyncing to pod:", e); + } + return new ArrayList<>(); + } - /** The usual Logger.*/ - private static final Logger LOGGER = LoggerFactory.getLogger(OpenshiftBinaryRSyncRetrievalIntegrationTest.class); - - private IntegrationTestHelper helper = new IntegrationTestHelper(); - - @Before - public void setUp() throws Exception { - } - - @Test - public void testRSyncLogRetrieval() throws IOException { - // given - System.setProperty(IBinaryCapability.OPENSHIFT_BINARY_LOCATION, helper.getOpenShiftLocation()); - final IClient client = new ClientBuilder(helper.getServerUrl()).resourceFactory(new ResourceFactory(null)) - .sslCertificateCallback(new NoopSSLCertificateCallback()).build(); - client.setAuthorizationStrategy(new BasicAuthorizationStrategy("test-admin", "test-admin", "")); - final IAuthorizationClient authClient = new AuthorizationClient(client); - final IAuthorizationContext context = authClient.getContext(client.getBaseURL().toString()); - client.setAuthorizationStrategy(new TokenAuthorizationStrategy(context.getToken())); - // retrieve the first pod in the 'eap-app' service - final IService service = client.get(ResourceKind.SERVICE, "nodejs-example", "int-test"); - final List pods = service.getPods(); - assertThat(pods).isNotEmpty(); - final IPod pod = pods.get(0); - final String localDir = "/Users/xcoulon/git/nodejs-ex"; - final String targetDir = "/tmp"; - // when - // create a dummy file to be sure there will be something to rsync - final String fileName = File.createTempFile("test", ".txt", new File(localDir)).getName(); - // run the rsync and collect the logs - final List logs = new ArrayList<>(100); - pod.accept(new CapabilityVisitor() { - - @Override - public Object visit(IRSyncable cap) { - try { - System.out.println("**** RSync Logs ****"); - final BufferedReader reader = new BufferedReader(new InputStreamReader( - cap.sync(new LocalPeer(localDir), new PodPeer(targetDir, pod)))); - String line; - while((line = reader.readLine()) != null) { - System.out.println(line); - logs.add(line); - } - // wait until end of 'rsync' - cap.await(); - } catch (Exception e) { - e.printStackTrace(); - } - return null; - } - - }, new Object()); - // then - // verify that the logs contain a message about the dummy file - assertThat(logs).isNotEmpty(); - assertThat(logs.stream().anyMatch(line -> line.contains(fileName))).isTrue(); - } + }, new ArrayList<>()); + if (LOG.isDebugEnabled()) { + LOG.debug("**** RSync Logs ****"); + logs.forEach(l -> LOG.debug(l)); + } + // then verify that the logs contain a message about the dummy file + assertThat(logs).isNotEmpty(); + assertThat(logs.stream().anyMatch(line -> line.contains(fileName))).isTrue(); + } } diff --git a/src/test/java/com/openshift/internal/restclient/capability/resources/PodLogRetrievalAsyncIntegrationTest.java b/src/test/java/com/openshift/internal/restclient/capability/resources/PodLogRetrievalAsyncIntegrationTest.java new file mode 100644 index 00000000..2b5db24d --- /dev/null +++ b/src/test/java/com/openshift/internal/restclient/capability/resources/PodLogRetrievalAsyncIntegrationTest.java @@ -0,0 +1,92 @@ +/******************************************************************************* + * Copyright (c) 2015-2019 Red Hat, Inc. + * Distributed under license by Red Hat, Inc. All rights reserved. + * This program is made available under the terms of the + * Eclipse Public License v1.0 which accompanies this distribution, + * and is available at http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Red Hat, Inc. - initial API and implementation + ******************************************************************************/ + +package com.openshift.internal.restclient.capability.resources; + +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.fail; + +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.TimeUnit; + +import org.junit.Test; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.openshift.internal.restclient.DefaultClient; +import com.openshift.internal.restclient.IntegrationTestHelper; +import com.openshift.restclient.capability.CapabilityVisitor; +import com.openshift.restclient.capability.IStoppable; +import com.openshift.restclient.capability.resources.IPodLogRetrievalAsync; +import com.openshift.restclient.capability.resources.IPodLogRetrievalAsync.IPodLogListener; +import com.openshift.restclient.capability.resources.IPodLogRetrievalAsync.Options; +import com.openshift.restclient.model.IPod; +import com.openshift.restclient.model.IProject; + +public class PodLogRetrievalAsyncIntegrationTest { + + private static final Logger LOG = LoggerFactory.getLogger(PodLogRetrievalAsyncIntegrationTest.class); + + private IntegrationTestHelper helper = new IntegrationTestHelper(); + private CountDownLatch latch; + + @Test + public void testAsyncLogRetrieval() throws Exception { + latch = new CountDownLatch(2); + DefaultClient client = (DefaultClient) helper.createClientForBasicAuth(); + IProject project = helper.getOrCreateIntegrationTestProject(client); + IPod pod = helper.getOrCreatePod(client, + project.getNamespaceName(), + getClass().getSimpleName().toLowerCase() + "-pod", + IntegrationTestHelper.IMAGE_HELLO_OPENSHIFT_ALPINE); + assertNotNull("Could not create a pod to test against.", pod); + + final String container = pod.getContainers().iterator().next().getName(); + + IStoppable stop = pod.accept(new CapabilityVisitor() { + + @Override + public IStoppable visit(IPodLogRetrievalAsync capability) { + return capability.start(new IPodLogListener() { + + @Override + public void onOpen() { + LOG.debug("onOpen"); + latch.countDown(); + } + + @Override + public void onMessage(String message) { + LOG.debug(message); + } + + @Override + public void onClose(int code, String reason) { + LOG.debug("onClose code:{} reason:{}", code, reason); + latch.countDown(); + } + + @Override + public void onFailure(Throwable t) { + LOG.error("Unexpected websocket failure", t); + fail("Unexpected websocket failure"); + } + + }, new Options().follow().container(container)); + } + }, null); + assertNotNull("Exp. to support the capability", stop); + latch.await(10, TimeUnit.SECONDS); + stop.stop(); + latch.await(5, TimeUnit.SECONDS); + } + +} diff --git a/src/test/java/com/openshift/internal/restclient/capability/resources/PodLogRetrievalAsyncTest.java b/src/test/java/com/openshift/internal/restclient/capability/resources/PodLogRetrievalAsyncTest.java new file mode 100644 index 00000000..0c15c98d --- /dev/null +++ b/src/test/java/com/openshift/internal/restclient/capability/resources/PodLogRetrievalAsyncTest.java @@ -0,0 +1,108 @@ +/******************************************************************************* + * Copyright (c) 2016 Red Hat, Inc. + * Distributed under license by Red Hat, Inc. All rights reserved. + * This program is made available under the terms of the + * Eclipse Public License v1.0 which accompanies this distribution, + * and is available at http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Red Hat, Inc. - initial API and implementation + ******************************************************************************/ + +package com.openshift.internal.restclient.capability.resources; + +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import java.net.URL; + +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.Mock; +import org.mockito.junit.MockitoJUnitRunner; + +import com.openshift.internal.restclient.DefaultClient; +import com.openshift.internal.restclient.TypeMapperFixture; +import com.openshift.internal.restclient.capability.resources.PodLogRetrievalAsync.PodLogListenerAdapter; +import com.openshift.restclient.IApiTypeMapper; +import com.openshift.restclient.capability.resources.IPodLogRetrievalAsync.IPodLogListener; +import com.openshift.restclient.http.IHttpConstants; +import com.openshift.restclient.model.IPod; +import com.openshift.restclient.model.MocksFactory; + +import okhttp3.WebSocket; + +@RunWith(MockitoJUnitRunner.class) +public class PodLogRetrievalAsyncTest extends TypeMapperFixture { + + private DefaultClient client; + @Mock + private IApiTypeMapper mapper; + private PodLogRetrievalAsync capability; + private IPod pod; + private PodLogListenerAdapter adapter; + + @Mock + private IPodLogListener listener; + + @Before + public void setUp() throws Exception { + super.setUp(); + client = new DefaultClient(new URL("http://localhost"), getHttpClient(), null, getApiTypeMapper(), null); + pod = new MocksFactory().mock(IPod.class); + capability = new PodLogRetrievalAsync(pod, client); + + adapter = new PodLogListenerAdapter(listener); + } + + @Test + public void testIsSupported() { + assertTrue("Exp. capability to be supported because the pod endpoint exists", capability.isSupported()); + } + + @Test + public void testIsNotSupportedWhenEndpointDoesNotExist() { + when(pod.getApiVersion()).thenReturn("somenoneexitentversion"); + assertFalse("Exp. capability to not be supported because the pod endpoint does not exist exists", + capability.isSupported()); + } + + @Test + public void testAdapterCallsListenerCycle() throws Exception { + adapter.onOpen(null, null); + adapter.onOpen(null, null); + verify(listener).onOpen(); + + adapter.onMessage(null, "a body"); + verify(listener).onMessage("a body"); + + adapter.onClosing(null, 1986, "the reason"); + adapter.onClosing(null, 1986, "the reason"); + verify(listener).onClose(1986, "the reason"); + } + + @Test + public void testStopWhenConnected() throws Exception { + WebSocket socket = mock(WebSocket.class); + adapter.onOpen(socket, null); + + adapter.stop(); + verify(socket).close(eq(IHttpConstants.STATUS_NORMAL_STOP), anyString()); + } + + @Test + public void testStopSwallowsException() throws Exception { + WebSocket socket = mock(WebSocket.class); + adapter.onOpen(socket, null); + + adapter.stop(); + verify(socket).close(eq(IHttpConstants.STATUS_NORMAL_STOP), anyString()); + } + +} diff --git a/src/test/java/com/openshift/internal/restclient/capability/resources/ProjectTemplateProcessingTest.java b/src/test/java/com/openshift/internal/restclient/capability/resources/ProjectTemplateProcessingTest.java index e810df6b..ee93a431 100644 --- a/src/test/java/com/openshift/internal/restclient/capability/resources/ProjectTemplateProcessingTest.java +++ b/src/test/java/com/openshift/internal/restclient/capability/resources/ProjectTemplateProcessingTest.java @@ -1,15 +1,23 @@ /******************************************************************************* - * Copyright (c) 2015 Red Hat, Inc. Distributed under license by Red Hat, Inc. + * Copyright (c) 2015-2019 Red Hat, Inc. Distributed under license by Red Hat, Inc. * All rights reserved. This program is made available under the terms of the * Eclipse Public License v1.0 which accompanies this distribution, and is * available at http://www.eclipse.org/legal/epl-v10.html * * Contributors: Red Hat, Inc. - initial API and implementation ******************************************************************************/ + package com.openshift.internal.restclient.capability.resources; -import static org.junit.Assert.*; -import static org.mockito.Mockito.*; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; import java.util.Collection; @@ -17,10 +25,14 @@ import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; -import org.mockito.runners.MockitoJUnitRunner; +import org.mockito.junit.MockitoJUnitRunner; import com.openshift.internal.restclient.ResourceFactory; +import com.openshift.restclient.IApiTypeMapper; +import com.openshift.restclient.IApiTypeMapper.IVersionedApiResource; +import com.openshift.restclient.IApiTypeMapper.IVersionedType; import com.openshift.restclient.IClient; +import com.openshift.restclient.ResourceKind; import com.openshift.restclient.capability.resources.IProjectTemplateProcessing; import com.openshift.restclient.capability.server.ITemplateProcessing; import com.openshift.restclient.model.IList; @@ -31,63 +43,150 @@ @RunWith(MockitoJUnitRunner.class) public class ProjectTemplateProcessingTest { - - private static final String NAMESPACE = "aProjectNamespace"; - private IProjectTemplateProcessing capability; - @Mock - private ITemplate template; - @Mock - private IClient client; - @Mock - private ITemplateProcessing serverCapability; - @Mock - private IProject project; - - @Before - public void setUp() throws Exception { - when(project.getNamespace()).thenReturn(NAMESPACE); - when(client.supports(eq(ITemplateProcessing.class))).thenReturn(true); - when(client.getCapability(eq(ITemplateProcessing.class))).thenReturn(serverCapability); - - capability = new ProjectTemplateProcessing(project, client); - } - - @Test - public void isSupportedShouldBeFalseForNullClient() { - capability = new ProjectTemplateProcessing(project, null); - assertFalse(capability.isSupported()); - } - - @Test - public void isSupportedShouldBeFalseIfTheClientDoesntSupportTemplates() { - when(client.supports(eq(ITemplateProcessing.class))).thenReturn(false); - capability = new ProjectTemplateProcessing(project, client); - assertFalse(capability.isSupported()); - } - - @Test - public void isSupportedShouldBeTrueIfTheClientSupportTemplates() { - assertTrue(capability.isSupported()); - } - - @Test - public void processTemplateShouldUseTheClientsCapability() { - when(serverCapability.process(any(ITemplate.class), anyString())).thenReturn(template); - - assertEquals(template, capability.process(template)); - verify(serverCapability).process(eq(template), eq(NAMESPACE)); - } - - @Test - public void applyTemplateShouldUseTheClientToCreateTheResources() { - @SuppressWarnings("unchecked") - Collection resources = mock(Collection.class); - when(client.create(any(IList.class), anyString())).thenReturn(resources); - when(client.getResourceFactory()).thenReturn(new ResourceFactory(client) {}); - ITemplate template = new ResourceFactory(client) {}.create(Samples.V1_TEMPLATE.getContentAsString()); - - assertEquals(resources, capability.apply(template)); - verify(client).create(any(IList.class), eq(NAMESPACE)); - } - + + private static final String NAMESPACE = "aProjectNamespace"; + private IProjectTemplateProcessing capability; + @Mock + private ITemplate template; + @Mock + private IClient client; + @Mock + private ITemplateProcessing serverCapability; + @Mock + private IProject project; + + @Before + public void setUp() throws Exception { + when(project.getNamespaceName()).thenReturn(NAMESPACE); + when(client.supports(eq(ITemplateProcessing.class))).thenReturn(true); + when(client.getCapability(eq(ITemplateProcessing.class))).thenReturn(serverCapability); + + capability = new ProjectTemplateProcessing(project, client); + } + + @Test + public void isSupportedShouldBeFalseForNullClient() { + capability = new ProjectTemplateProcessing(project, null); + assertFalse(capability.isSupported()); + } + + @Test + public void isSupportedShouldBeFalseIfTheClientDoesntSupportTemplates() { + when(client.supports(eq(ITemplateProcessing.class))).thenReturn(false); + capability = new ProjectTemplateProcessing(project, client); + assertFalse(capability.isSupported()); + } + + @Test + public void isSupportedShouldBeTrueIfTheClientSupportTemplates() { + assertTrue(capability.isSupported()); + } + + @Test + public void processTemplateShouldUseTheClientsCapability() { + when(serverCapability.process(any(ITemplate.class), anyString())).thenReturn(template); + + assertEquals(template, capability.process(template)); + verify(serverCapability).process(eq(template), eq(NAMESPACE)); + } + + @Test + public void applyTemplateShouldUseTheClientToCreateTheResources() { + @SuppressWarnings("unchecked") + Collection resources = mock(Collection.class); + when(client.create(any(IList.class), anyString())).thenReturn(resources); + when(client.getResourceFactory()).thenReturn(new ResourceFactory(client) { + }); + IApiTypeMapper mapper = mock(IApiTypeMapper.class); + when(client.adapt(IApiTypeMapper.class)).thenReturn(mapper); + when(mapper.getType(anyString(), eq(ResourceKind.TEMPLATE))).thenReturn(new IVersionedType() { + + @Override + public String getVersion() { + return "v1"; + } + + @Override + public String getPrefix() { + return null; + } + + @Override + public String getKind() { + return ResourceKind.TEMPLATE; + } + + @Override + public String getApiGroupName() { + return null; + } + }); + when(mapper.getType(anyString(), eq(ResourceKind.DEPLOYMENT_CONFIG))).thenReturn(new IVersionedType() { + + @Override + public String getVersion() { + return "v1"; + } + + @Override + public String getPrefix() { + return null; + } + + @Override + public String getKind() { + return ResourceKind.DEPLOYMENT_CONFIG; + } + + @Override + public String getApiGroupName() { + return null; + } + }); + when(mapper.getEndpointFor(anyString(), eq(ResourceKind.DEPLOYMENT_CONFIG))).thenReturn(new IVersionedApiResource() { + + @Override + public boolean isSupported(String capability) { + return true; + } + + @Override + public boolean isNamespaced() { + return true; + } + + @Override + public String getVersion() { + return "v1"; + } + + @Override + public String getPrefix() { + return null; + } + + @Override + public String getName() { // TODO Auto-generated method stub + return null; + } + + @Override + public String getKind() { + return ResourceKind.DEPLOYMENT_CONFIG; + } + + @Override + public String getApiGroupName() { + return "v1"; + } + }); + + + ITemplate template = new ResourceFactory(client) { + }.create(Samples.V1_TEMPLATE.getContentAsString()); + + assertEquals(resources, capability.apply(template)); + verify(client).create(any(IList.class), eq(NAMESPACE)); + } + } diff --git a/src/test/java/com/openshift/internal/restclient/capability/resources/PropertyAccessCapabilityTest.java b/src/test/java/com/openshift/internal/restclient/capability/resources/PropertyAccessCapabilityTest.java index 7c1b0e75..bf9768e6 100644 --- a/src/test/java/com/openshift/internal/restclient/capability/resources/PropertyAccessCapabilityTest.java +++ b/src/test/java/com/openshift/internal/restclient/capability/resources/PropertyAccessCapabilityTest.java @@ -8,10 +8,11 @@ * Contributors: * Red Hat, Inc. - initial API and implementation ******************************************************************************/ + package com.openshift.internal.restclient.capability.resources; -import static org.junit.Assert.*; -import static org.mockito.Mockito.*; +import static org.junit.Assert.assertEquals; +import static org.mockito.Mockito.mock; import java.util.HashMap; import java.util.Map; @@ -27,54 +28,55 @@ import com.openshift.restclient.utils.Samples; public class PropertyAccessCapabilityTest { - - private ModelNode node; - private IPropertyAccessCapability cap; - @Before - public void setup() { - IClient client = mock(IClient.class); - node = ModelNode.fromJSONString(Samples.V1_BUILD_CONFIG.getContentAsString()); - node.get(new String[] {"spec", "strategy","sourceStrategy", "xyz"}).set(1986); - BuildConfig config = new BuildConfig(node, client, new HashMap<>()); - cap = new PropertyAccessCapability(config); - } - @Test(expected=UnresolvablePathException.class) - public void testAsMapWhenPathIsNotFound() { - cap.asMap("foo.strategy.sourceStrategy.from"); - } + private ModelNode node; + private IPropertyAccessCapability cap; + + @Before + public void setup() { + IClient client = mock(IClient.class); + node = ModelNode.fromJSONString(Samples.V1_BUILD_CONFIG.getContentAsString()); + node.get(new String[] { "spec", "strategy", "sourceStrategy", "xyz" }).set(1986); + BuildConfig config = new BuildConfig(node, client, new HashMap<>()); + cap = new PropertyAccessCapability(config); + } + + @Test(expected = UnresolvablePathException.class) + public void testAsMapWhenPathIsNotFound() { + cap.asMap("foo.strategy.sourceStrategy.from"); + } + + @Test + public void testAsString() { + assertEquals("1986", cap.asString("spec.strategy.sourceStrategy.xyz")); + } + + @Test(expected = UnresolvablePathException.class) + public void testAsWhenPathIsNotFound() { + cap.asString("spec.strategy.sourceStrategy.xyzzz"); + } - @Test - public void testAsString() { - assertEquals("1986", cap.asString("spec.strategy.sourceStrategy.xyz")); - } + @Test + public void testAsMap() { + Map from = new HashMap<>(); + from.put("kind", "ImageStreamTag"); + from.put("name", "ruby-20-centos7:latest"); + Map exp = new HashMap<>(); + exp.put("from", from); + exp.put("incremental", true); + exp.put("scripts", "aLocation"); + exp.put("xyz", 1986); - @Test(expected=UnresolvablePathException.class) - public void testAsWhenPathIsNotFound() { - cap.asString("spec.strategy.sourceStrategy.xyzzz"); - } - - @Test - public void testAsMap() { - Map from = new HashMap<>(); - from.put("kind","ImageStreamTag"); - from.put("name","ruby-20-centos7:latest"); - Map exp = new HashMap<>(); - exp.put("from", from); - exp.put("incremental", true); - exp.put("scripts", "aLocation"); - exp.put("xyz", 1986); - - // @TODO Why doesnt this validate? -// Map envEntry = new HashMap<>(); -// envEntry.put("name", "foo"); -// envEntry.put("value", "bar"); -// List env = new ArrayList<>(); -// env.add(envEntry); -// -// exp.put("env", env); - Map act = cap.asMap("spec.strategy.sourceStrategy.from"); - assertEquals(from, act); - } + // @TODO Why doesnt this validate? + // Map envEntry = new HashMap<>(); + // envEntry.put("name", "foo"); + // envEntry.put("value", "bar"); + // List env = new ArrayList<>(); + // env.add(envEntry); + // + // exp.put("env", env); + Map act = cap.asMap("spec.strategy.sourceStrategy.from"); + assertEquals(from, act); + } } diff --git a/src/test/java/com/openshift/internal/restclient/capability/resources/TagCapabilityTest.java b/src/test/java/com/openshift/internal/restclient/capability/resources/TagCapabilityTest.java index 2848d5e8..c8923901 100644 --- a/src/test/java/com/openshift/internal/restclient/capability/resources/TagCapabilityTest.java +++ b/src/test/java/com/openshift/internal/restclient/capability/resources/TagCapabilityTest.java @@ -6,38 +6,36 @@ * * Contributors: Red Hat, Inc. ******************************************************************************/ + package com.openshift.internal.restclient.capability.resources; -import static org.junit.Assert.*; -import static org.mockito.Mockito.*; +import static org.junit.Assert.assertArrayEquals; +import static org.mockito.Mockito.when; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; -import org.mockito.runners.MockitoJUnitRunner; +import org.mockito.junit.MockitoJUnitRunner; -import com.openshift.internal.restclient.capability.resources.TagCapability; import com.openshift.restclient.model.IResource; -/** - * @author Jeff Cantrill - */ @RunWith(MockitoJUnitRunner.class) public class TagCapabilityTest { - private TagCapability capability; - @Mock private IResource resource; - - @Before - public void setup(){ - when(resource.getAnnotation("tags")).thenReturn("instant-app,ruby,mysql"); - capability = new TagCapability(resource); - } - - @Test - public void testGetTags() { - assertArrayEquals(new String[]{"instant-app","ruby","mysql"},capability.getTags().toArray()); - } + private TagCapability capability; + @Mock + private IResource resource; + + @Before + public void setup() { + when(resource.getAnnotation("tags")).thenReturn("instant-app,ruby,mysql"); + capability = new TagCapability(resource); + } + + @Test + public void testGetTags() { + assertArrayEquals(new String[] { "instant-app", "ruby", "mysql" }, capability.getTags().toArray()); + } } diff --git a/src/test/java/com/openshift/internal/restclient/capability/resources/TemplateTraceabilityTest.java b/src/test/java/com/openshift/internal/restclient/capability/resources/TemplateTraceabilityTest.java index b18373d3..50df1710 100644 --- a/src/test/java/com/openshift/internal/restclient/capability/resources/TemplateTraceabilityTest.java +++ b/src/test/java/com/openshift/internal/restclient/capability/resources/TemplateTraceabilityTest.java @@ -6,56 +6,60 @@ * * Contributors: Red Hat, Inc. ******************************************************************************/ + package com.openshift.internal.restclient.capability.resources; -import static org.junit.Assert.*; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; +import static org.mockito.Mockito.lenient; import static org.mockito.Mockito.when; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; -import org.mockito.runners.MockitoJUnitRunner; +import org.mockito.junit.MockitoJUnitRunner; -import com.openshift.internal.restclient.capability.resources.TemplateTraceability; import com.openshift.restclient.IClient; import com.openshift.restclient.ResourceKind; import com.openshift.restclient.model.IResource; -/** - * @author Jeff Cantrill - */ @RunWith(MockitoJUnitRunner.class) public class TemplateTraceabilityTest { - private TemplateTraceability capability; - @Mock private IClient client; - @Mock private IResource resource; - - @Before - public void setUp(){ - capability = new TemplateTraceability(resource); - when(resource.getNamespace()).thenReturn("mynamespace"); - when(resource.getKind()).thenReturn(ResourceKind.TEMPLATE); - } - - @Test - public void supportedWhenAnnotationHasTemplateKey(){ - when(resource.isAnnotatedWith("template")).thenReturn(true); - when(resource.getAnnotation("template")).thenReturn("aTemplateName"); - - assertTrue("Exp. the capability to be supported because it has the template annotation", capability.isSupported()); - assertEquals("Exp. to get the template name", "aTemplateName", capability.getTemplateName()); - } - - @Test - public void unsupportedWhenAnnotationDoesNotHasTemplateKey(){ - assertFalse("Exp. the capability to not be supported because it does not have the template annotation", capability.isSupported()); - assertEquals("Exp. to get the template name", "", capability.getTemplateName()); - } - - @Test - public void testGetName(){ - assertEquals("", TemplateTraceability.class.getSimpleName(), capability.getName()); - } + private TemplateTraceability capability; + @Mock + private IClient client; + @Mock + private IResource resource; + + @Before + public void setUp() { + capability = new TemplateTraceability(resource); + lenient().when(resource.getNamespaceName()).thenReturn("mynamespace"); + lenient().when(resource.getKind()).thenReturn(ResourceKind.TEMPLATE); + } + + @Test + public void supportedWhenAnnotationHasTemplateKey() { + when(resource.isAnnotatedWith("template")).thenReturn(true); + when(resource.getAnnotation("template")).thenReturn("aTemplateName"); + + assertTrue("Exp. the capability to be supported because it has the template annotation", + capability.isSupported()); + assertEquals("Exp. to get the template name", "aTemplateName", capability.getTemplateName()); + } + + @Test + public void unsupportedWhenAnnotationDoesNotHasTemplateKey() { + assertFalse("Exp. the capability to not be supported because it does not have the template annotation", + capability.isSupported()); + assertEquals("Exp. to get the template name", "", capability.getTemplateName()); + } + + @Test + public void testGetName() { + assertEquals("", TemplateTraceability.class.getSimpleName(), capability.getName()); + } } diff --git a/src/test/java/com/openshift/internal/restclient/capability/resources/UpdateableCapabilityTest.java b/src/test/java/com/openshift/internal/restclient/capability/resources/UpdateableCapabilityTest.java index a304888f..10a7a761 100644 --- a/src/test/java/com/openshift/internal/restclient/capability/resources/UpdateableCapabilityTest.java +++ b/src/test/java/com/openshift/internal/restclient/capability/resources/UpdateableCapabilityTest.java @@ -1,23 +1,31 @@ /******************************************************************************* - * Copyright (c) 2015 Red Hat, Inc. Distributed under license by Red Hat, Inc. + * Copyright (c) 2015-2019 Red Hat, Inc. Distributed under license by Red Hat, Inc. * All rights reserved. This program is made available under the terms of the * Eclipse Public License v1.0 which accompanies this distribution, and is * available at http://www.eclipse.org/legal/epl-v10.html * * Contributors: Red Hat, Inc. ******************************************************************************/ + package com.openshift.internal.restclient.capability.resources; -import static org.junit.Assert.*; -import static org.mockito.Mockito.*; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotSame; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.lenient; +import static org.mockito.Mockito.when; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; -import org.mockito.runners.MockitoJUnitRunner; +import org.mockito.junit.MockitoJUnitRunner; +import com.openshift.internal.restclient.IntegrationTestHelper; import com.openshift.internal.restclient.ResourceFactory; +import com.openshift.restclient.IApiTypeMapper; +import com.openshift.restclient.IApiTypeMapper.IVersionedType; import com.openshift.restclient.IClient; import com.openshift.restclient.IResourceFactory; import com.openshift.restclient.ResourceKind; @@ -25,40 +33,63 @@ import com.openshift.restclient.capability.resources.IUpdatable; import com.openshift.restclient.model.IService; -/** - * @author Jeff Cantrill - */ @RunWith(MockitoJUnitRunner.class) public class UpdateableCapabilityTest { - @Mock private IClient client; - private IService service; - private IResourceFactory factory; - - @Before - public void setup(){ - when(client.getOpenShiftAPIVersion()).thenReturn("v1"); - factory = new ResourceFactory(client); - service = factory.stub(ResourceKind.SERVICE, "foo", "default"); - service.setAnnotation("foo", "bar"); - } - - @Test - public void testUpdateCapability() { - IService target = factory.stub(ResourceKind.SERVICE, "foo", "default"); - target.setAnnotation("foo", "xyz"); - - service.accept(new CapabilityVisitor() { + @Mock + private IClient client; + @Mock + private IApiTypeMapper mapper; + private IService service; + private IResourceFactory factory; + + @Before + public void setup() { + lenient().when(client.getOpenShiftAPIVersion()).thenReturn("v1"); + when(client.adapt(IApiTypeMapper.class)).thenReturn(mapper); + when(mapper.getType(anyString(), eq(ResourceKind.SERVICE))).thenReturn(new IVersionedType() { + + @Override + public String getVersion() { + return "v1"; + } + + @Override + public String getPrefix() { + return null; + } + + @Override + public String getKind() { + return ResourceKind.SERVICE; + } + + @Override + public String getApiGroupName() { + return null; + } + }); + this.factory = new ResourceFactory(client); + this.service = factory.stub(ResourceKind.SERVICE, "foo", IntegrationTestHelper.getDefaultNamespace()); + service.setAnnotation("foo", "bar"); + } + + @Test + public void testUpdateCapability() { + IService target = factory.stub(ResourceKind.SERVICE, "foo", IntegrationTestHelper.getDefaultNamespace()); + target.setAnnotation("foo", "xyz"); + + service.accept(new CapabilityVisitor() { - @Override - public IService visit(IUpdatable capability) { - capability.updateFrom(target); - return null; - }; - }, null); - assertNotSame("Exp. services to not be the same instance", target, service); - assertEquals("Exp. the annotation to be updated","xyz", service.getAnnotation("foo")); - assertEquals("Exp. the JSON to be the same", target.toJson(), service.toJson()); - } + @Override + public IService visit(IUpdatable capability) { + capability.updateFrom(target); + return null; + } + }, null); + assertNotSame("Exp. services to not be the same instance", target, service); + assertEquals("Exp. the annotation to be updated", "xyz", service.getAnnotation("foo")); + assertEquals("Exp. the JSON to be the same", target.toJson(), service.toJson()); + } } diff --git a/src/test/java/com/openshift/internal/restclient/capability/resources/testutils/BinaryCapabilityTestMocks.java b/src/test/java/com/openshift/internal/restclient/capability/resources/testutils/BinaryCapabilityTestMocks.java new file mode 100644 index 00000000..ddfe7e0b --- /dev/null +++ b/src/test/java/com/openshift/internal/restclient/capability/resources/testutils/BinaryCapabilityTestMocks.java @@ -0,0 +1,62 @@ +/******************************************************************************* + * Copyright (c) 2018 Red Hat, Inc. + * Distributed under license by Red Hat, Inc. All rights reserved. + * This program is made available under the terms of the + * Eclipse Public License v1.0 which accompanies this distribution, + * and is available at http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Red Hat, Inc. - initial API and implementation + ******************************************************************************/ + +package com.openshift.internal.restclient.capability.resources.testutils; + +import static org.mockito.Mockito.doReturn; +import static org.mockito.Mockito.mock; + +import java.net.MalformedURLException; +import java.net.URL; + +import com.openshift.restclient.IClient; +import com.openshift.restclient.authorization.IAuthorizationContext; +import com.openshift.restclient.capability.resources.IPortForwardable.PortPair; +import com.openshift.restclient.model.IPod; + +public class BinaryCapabilityTestMocks { + + public static final String SERVER_URL = "https://localhost:8443"; + public static final String TOKEN = "phWDXIqSspYBZARPQIzqaevHGDIxduQGbhcZuwj48EI"; + + public static final String OC_LOCATION = "/path/to/oc"; + + public static final String POD_NAME = "papa-smurf"; + public static final String POD_NAMESPACE = "the-smurfs"; + + public static IClient mockClient() throws MalformedURLException { + IClient client = mock(IClient.class); + doReturn(new URL(SERVER_URL)).when(client).getBaseURL(); + IAuthorizationContext context = mockAuthorizationContext(); + doReturn(context).when(client).getAuthorizationContext(); + return client; + } + + private static IAuthorizationContext mockAuthorizationContext() { + IAuthorizationContext context = mock(IAuthorizationContext.class); + doReturn(TOKEN).when(context).getToken(); + return context; + } + + public static IPod mockPod() { + IPod pod = mock(IPod.class); + doReturn(POD_NAME).when(pod).getName(); + doReturn(POD_NAMESPACE).when(pod).getNamespaceName(); + return pod; + } + + public static PortPair mockPortPair(int localPort, int remotePort) { + PortPair ports = mock(PortPair.class); + doReturn(localPort).when(ports).getLocalPort(); + doReturn(remotePort).when(ports).getRemotePort(); + return ports; + } +} diff --git a/src/test/java/com/openshift/internal/restclient/capability/server/ConsoleIntegrationTest.java b/src/test/java/com/openshift/internal/restclient/capability/server/ConsoleIntegrationTest.java new file mode 100644 index 00000000..35a34864 --- /dev/null +++ b/src/test/java/com/openshift/internal/restclient/capability/server/ConsoleIntegrationTest.java @@ -0,0 +1,52 @@ +/******************************************************************************* + * Copyright (c) 2019 Red Hat, Inc. Distributed under license by Red Hat, Inc. + * All rights reserved. This program is made available under the terms of the + * Eclipse Public License v1.0 which accompanies this distribution, and is + * available at http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: Red Hat, Inc. + ******************************************************************************/ + +package com.openshift.internal.restclient.capability.server; + + +import static org.assertj.core.api.Assertions.assertThat; + +import java.net.MalformedURLException; + +import org.junit.Before; +import org.junit.Test; + +import com.openshift.internal.restclient.IntegrationTestHelper; +import com.openshift.restclient.IClient; +import com.openshift.restclient.capability.server.IConsole; + +import okhttp3.OkHttpClient; +import okhttp3.Request; +import okhttp3.Response; + +public class ConsoleIntegrationTest { + private IntegrationTestHelper helper = new IntegrationTestHelper(); + private IClient client; + private IConsole console; + private OkHttpClient httpClient; + + @Before + public void before() throws MalformedURLException { + this.client = helper.createClientForBasicAuth(); + this.console = client.adapt(IConsole.class); + this.httpClient = helper.createTrustAllOkHttpClient(); + } + + @Test + public void shouldRetrieveValidConsoleUrl() throws Exception { + // given + // when + String consoleUrl = console.getConsoleUrl(); + // then + assertThat(consoleUrl).isNotNull(); + Request request = new Request.Builder().url(consoleUrl).build(); + Response response = httpClient.newCall(request).execute(); + assertThat(response.isSuccessful()).isTrue(); + } +} diff --git a/src/test/java/com/openshift/internal/restclient/capability/server/DataPair.java b/src/test/java/com/openshift/internal/restclient/capability/server/DataPair.java new file mode 100644 index 00000000..489d288f --- /dev/null +++ b/src/test/java/com/openshift/internal/restclient/capability/server/DataPair.java @@ -0,0 +1,30 @@ +/******************************************************************************* + * Copyright (c) 2019 Red Hat, Inc. Distributed under license by Red Hat, Inc. + * All rights reserved. This program is made available under the terms of the + * Eclipse Public License v1.0 which accompanies this distribution, and is + * available at http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: Red Hat, Inc. + ******************************************************************************/ + +package com.openshift.internal.restclient.capability.server; + +import com.openshift.restclient.model.IResource; + +public class DataPair { + private IResource input; + private String expected; + + public DataPair(IResource input, String expected) { + this.input = input; + this.expected = expected; + } + + public IResource getResource() { + return input; + } + + public String getExpected() { + return expected; + } +} \ No newline at end of file diff --git a/src/test/java/com/openshift/internal/restclient/capability/server/OpenShift3ConsoleTest.java b/src/test/java/com/openshift/internal/restclient/capability/server/OpenShift3ConsoleTest.java new file mode 100644 index 00000000..3ce0cdf7 --- /dev/null +++ b/src/test/java/com/openshift/internal/restclient/capability/server/OpenShift3ConsoleTest.java @@ -0,0 +1,131 @@ +/******************************************************************************* + * Copyright (c) 2019 Red Hat, Inc. Distributed under license by Red Hat, Inc. + * All rights reserved. This program is made available under the terms of the + * Eclipse Public License v1.0 which accompanies this distribution, and is + * available at http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: Red Hat, Inc. + ******************************************************************************/ + +package com.openshift.internal.restclient.capability.server; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; +import static org.mockito.Mockito.doReturn; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +import java.net.MalformedURLException; +import java.net.URL; +import java.util.HashMap; + +import org.junit.Before; +import org.junit.Test; +import org.junit.experimental.theories.DataPoints; +import org.junit.experimental.theories.Theories; +import org.junit.experimental.theories.Theory; +import org.junit.runner.RunWith; + +import com.openshift.restclient.IClient; +import com.openshift.restclient.ResourceKind; +import com.openshift.restclient.capability.server.IConsole; +import com.openshift.restclient.model.IBuild; +import com.openshift.restclient.model.IBuildConfig; +import com.openshift.restclient.model.IDeploymentConfig; +import com.openshift.restclient.model.IEvent; +import com.openshift.restclient.model.IImageStream; +import com.openshift.restclient.model.IPod; +import com.openshift.restclient.model.IProject; +import com.openshift.restclient.model.IReplicationController; +import com.openshift.restclient.model.IResource; +import com.openshift.restclient.model.IService; +import com.openshift.restclient.model.route.IRoute; +import com.openshift.restclient.model.volume.IPersistentVolumeClaim; + +@RunWith(Theories.class) +public class OpenShift3ConsoleTest { + + private static final String NAMESPACE = "namespace"; + + private static final String RESOURCE_NAME = "qwerty"; + + private static final String HOST = "http://openshifthost.testing"; + + @DataPoints + public static DataPair[] dataPoints = new DataPair[] { + new DataPair(mockResource(IBuild.class, ResourceKind.BUILD), + HOST + "/console/project/" + NAMESPACE + "/browse/builds/label/" + RESOURCE_NAME), + new DataPair(mockResource(IBuildConfig.class, ResourceKind.BUILD_CONFIG), + HOST + "/console/project/" + NAMESPACE + "/browse/builds/" + RESOURCE_NAME), + new DataPair(mockResource(IDeploymentConfig.class, ResourceKind.DEPLOYMENT_CONFIG), + HOST + "/console/project/" + NAMESPACE + "/browse/deployments/" + RESOURCE_NAME), + new DataPair(mockResource(IEvent.class, ResourceKind.EVENT), + HOST + "/console/project/" + NAMESPACE + "/browse/events/"), + new DataPair(mockResource(IImageStream.class, ResourceKind.IMAGE_STREAM), + HOST + "/console/project/" + NAMESPACE + "/browse/images/" + RESOURCE_NAME), + new DataPair(mockResource(IPod.class, ResourceKind.POD), + HOST + "/console/project/" + NAMESPACE + "/browse/pods/" + RESOURCE_NAME), + new DataPair(mockResource(IProject.class, ResourceKind.PROJECT), + HOST + "/console/project/" + NAMESPACE), + new DataPair(mockResource(IPersistentVolumeClaim.class, ResourceKind.PVC), + HOST + "/console/project/" + NAMESPACE + "/browse/persistentvolumeclaims/" + RESOURCE_NAME), + new DataPair(mockResource(IReplicationController.class, ResourceKind.REPLICATION_CONTROLLER), + HOST + "/console/project/" + NAMESPACE + "/browse/rc/" + RESOURCE_NAME), + new DataPair(mockResource(IRoute.class, ResourceKind.ROUTE), + HOST + "/console/project/" + NAMESPACE + "/browse/routes/" + RESOURCE_NAME), + new DataPair(mockResource(IService.class, ResourceKind.SERVICE), + HOST + "/console/project/" + NAMESPACE + "/browse/services/" + RESOURCE_NAME), + new DataPair(null, + HOST + "/console"), + // inexistant resource -> show project + new DataPair(mockResource(IResource.class, "INEXISTANT_RESOURCE_TYPE"), + HOST + "/console/project/" + NAMESPACE) + }; + + private IClient client; + private IConsole console; + + @Before + public void setup() throws MalformedURLException { + this.client = mockClient(HOST); + this.console = new Console(client); + } + + private static R mockResource(Class resourceClass, String kind) { + R resource = mock(resourceClass); + when(resource.getNamespaceName()).thenReturn(NAMESPACE); + when(resource.getName()).thenReturn(RESOURCE_NAME); + when(resource.getLabels()).thenReturn(new HashMap() { + { + put("buildconfig", "label"); + } + }); + doReturn(kind).when(resource).getKind(); + return resource; + } + + private IClient mockClient(String host) throws MalformedURLException { + IClient client = mock(IClient.class); + doReturn(3).when(client).getOpenShiftMajorVersion(); + doReturn(new URL(host)).when(client).getBaseURL(); + return client; + } + + @Test + public void shouldBeSupportedForOpenShift3() { + assertTrue("Exp. Console capability should be supported for OpenShift 3 server", console.isSupported()); + } + + @Test + public void shouldReturnConsoleUrlForOpenShift3() { + assertThat(console.getConsoleUrl()).isEqualTo(HOST + "/console"); + } + + @Theory + public void shouldReturnConsoleUrlForOpenShift3ForResource(DataPair dataPair) { + IResource resourceMock = dataPair.getResource(); + String consoleUrl = console.getConsoleUrl(resourceMock); + assertEquals(dataPair.getExpected(), consoleUrl); + } +} diff --git a/src/test/java/com/openshift/internal/restclient/capability/server/OpenShift4ConsoleTest.java b/src/test/java/com/openshift/internal/restclient/capability/server/OpenShift4ConsoleTest.java new file mode 100644 index 00000000..5395aef1 --- /dev/null +++ b/src/test/java/com/openshift/internal/restclient/capability/server/OpenShift4ConsoleTest.java @@ -0,0 +1,178 @@ +/******************************************************************************* + * Copyright (c) 2019 Red Hat, Inc. Distributed under license by Red Hat, Inc. + * All rights reserved. This program is made available under the terms of the + * Eclipse Public License v1.0 which accompanies this distribution, and is + * available at http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: Red Hat, Inc. + ******************************************************************************/ + +package com.openshift.internal.restclient.capability.server; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.doReturn; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +import java.net.MalformedURLException; +import java.net.URL; +import java.util.HashMap; +import java.util.Map; + +import org.jboss.dmr.ModelNode; +import org.junit.Before; +import org.junit.Test; +import org.junit.experimental.theories.DataPoints; +import org.junit.experimental.theories.Theories; +import org.junit.experimental.theories.Theory; +import org.junit.runner.RunWith; + +import com.openshift.internal.restclient.model.ConfigMap; +import com.openshift.restclient.IClient; +import com.openshift.restclient.ResourceKind; +import com.openshift.restclient.capability.server.IConsole; +import com.openshift.restclient.model.IBuild; +import com.openshift.restclient.model.IBuildConfig; +import com.openshift.restclient.model.IConfigMap; +import com.openshift.restclient.model.IDeploymentConfig; +import com.openshift.restclient.model.IEvent; +import com.openshift.restclient.model.IImageStream; +import com.openshift.restclient.model.IPod; +import com.openshift.restclient.model.IProject; +import com.openshift.restclient.model.IReplicationController; +import com.openshift.restclient.model.IResource; +import com.openshift.restclient.model.IService; +import com.openshift.restclient.model.route.IRoute; +import com.openshift.restclient.model.volume.IPersistentVolumeClaim; +import com.openshift.restclient.utils.Samples; + +@RunWith(Theories.class) +public class OpenShift4ConsoleTest { + + private static final String HOST = "http://openshifthost.testing"; + private static final String NAMESPACE = "grumpy"; + private static final String RESOURCE_NAME = "eap-app"; + + @DataPoints + public static DataPair[] dataPoints = new DataPair[] { + new DataPair(mockResource(IBuild.class, ResourceKind.BUILD), + HOST + "/k8s/ns/" + NAMESPACE + "/builds/" + RESOURCE_NAME), + new DataPair(mockResource(IBuildConfig.class, ResourceKind.BUILD_CONFIG), + HOST + "/k8s/ns/" + NAMESPACE + "/buildconfigs/" + RESOURCE_NAME), + new DataPair(mockResource(IDeploymentConfig.class, ResourceKind.DEPLOYMENT_CONFIG), + HOST + "/k8s/ns/" + NAMESPACE + "/deploymentconfigs/" + RESOURCE_NAME), + new DataPair(mockResource(IEvent.class, ResourceKind.EVENT), + HOST + "/k8s/ns/" + NAMESPACE + "/events/"), + new DataPair(mockResource(IImageStream.class, ResourceKind.IMAGE_STREAM), + HOST + "/k8s/ns/" + NAMESPACE + "/imagestreams/" + RESOURCE_NAME), + new DataPair(mockResource(IPod.class, ResourceKind.POD), + HOST + "/k8s/ns/" + NAMESPACE + "/pods/" + RESOURCE_NAME), + new DataPair(mockResource(IProject.class, ResourceKind.PROJECT), + HOST + "/overview/ns/" + NAMESPACE), + new DataPair(mockResource(IPersistentVolumeClaim.class, ResourceKind.PVC), + HOST + "/k8s/ns/" + NAMESPACE + "/persistentvolumeclaims/" + RESOURCE_NAME), + new DataPair(mockResource(IReplicationController.class, ResourceKind.REPLICATION_CONTROLLER), + HOST + "/k8s/ns/" + NAMESPACE + "/replicationcontrollers/" + RESOURCE_NAME), + new DataPair(mockResource(IRoute.class, ResourceKind.ROUTE), + HOST + "/k8s/ns/" + NAMESPACE + "/routes/" + RESOURCE_NAME), + new DataPair(mockResource(IService.class, ResourceKind.SERVICE), + HOST + "/k8s/ns/" + NAMESPACE + "/services/" + RESOURCE_NAME), + new DataPair(null, + HOST), + // inexistant resource -> show project + new DataPair(mockResource(IResource.class, "INEXISTANT_RESOURCE_TYPE"), + HOST + "/overview/ns/" + NAMESPACE) + }; + + private IClient client; + private IConsole console; + + private static R mockResource(Class resourceClass, String kind) { + R resource = mock(resourceClass); + when(resource.getNamespaceName()).thenReturn(NAMESPACE); + when(resource.getName()).thenReturn(RESOURCE_NAME); + doReturn(kind).when(resource).getKind(); + return resource; + } + + @Before + public void setup() throws MalformedURLException { + this.client = mockClient(HOST); + this.console = new Console(client); + } + + private IClient mockClient(String host) throws MalformedURLException { + IClient client = mock(IClient.class); + doReturn(4).when(client).getOpenShiftMajorVersion(); + doReturn(new URL(host)).when(client).getBaseURL(); + + ConfigMap map = mock(ConfigMap.class); + Map data = new HashMap(); + data.put(Console.CONFIGMAP_DATA_CONSOLE_URL, HOST); + doReturn(data).when(map).getData(); + doReturn(map).when(client).get(eq(ResourceKind.CONFIG_MAP), eq(Console.CONFIGMAP_CONSOLE_PUBLIC), eq(Console.NAMESPACE_OPENSHIFT_CONFIG_MANAGED)); + + return client; + } + + @Test + public void shouldBeSupportedForOpenShift4() { + assertTrue("Exp. Console endpoint should be supported for OpenShift 4 server", console.isSupported()); + } + + @Test + public void shouldReturnNullIfOpenShift4HasNoConfigmap() { + // given + doReturn(null).when(client).get(eq(ResourceKind.CONFIG_MAP), eq(Console.CONFIGMAP_CONSOLE_PUBLIC), eq(Console.NAMESPACE_OPENSHIFT_CONFIG_MANAGED)); + // when + String consoleUrl = console.getConsoleUrl(); + assertThat(consoleUrl).isNull(); + } + + @Test + public void shouldReturnNullIfOpenShift4HasNoConfigmapData() { + // given + ConfigMap map = mock(ConfigMap.class); + doReturn(null).when(map).getData(); + doReturn(map).when(client).get(eq(ResourceKind.CONFIG_MAP), eq(Console.CONFIGMAP_CONSOLE_PUBLIC), eq(Console.NAMESPACE_OPENSHIFT_CONFIG_MANAGED)); + // when + String consoleUrl = console.getConsoleUrl(); + // then + assertThat(consoleUrl).isNull(); + } + + @Test + public void shouldReturnNullIfOpenShift4EmptyConfigmapData() { + // given + IConfigMap map = mock(IConfigMap.class); + doReturn(new HashMap<>()).when(map).getData(); + doReturn(map).when(client).get(eq(ResourceKind.CONFIG_MAP), eq(Console.CONFIGMAP_CONSOLE_PUBLIC), eq(Console.NAMESPACE_OPENSHIFT_CONFIG_MANAGED)); + // when + String consoleUrl = console.getConsoleUrl(); + // then + assertThat(consoleUrl).isNull(); + } + + @Test + public void shouldReturnConsoleUrlForForOpenShift4ConfigMap() { + // given + ModelNode node = ModelNode.fromJSONString(Samples.V1_CONFIGMAP_CONSOLE_PUBLIC.getContentAsString()); + ConfigMap map = new ConfigMap(node, client, null); + doReturn(map).when(client).get(eq(ResourceKind.CONFIG_MAP), anyString(), anyString()); + // when + String consoleUrl = console.getConsoleUrl(); + // then + assertThat(consoleUrl).isEqualTo("https://console-openshift-console.apps.crw.codereadyqe.com"); + } + + @Theory + public void shouldReturnConsoleUrlForForOpenShift4ForResource(DataPair dataPair) { + IResource resourceMock = dataPair.getResource(); + String consoleUrl = console.getConsoleUrl(resourceMock); + assertEquals(dataPair.getExpected(), consoleUrl); + } +} diff --git a/src/test/java/com/openshift/internal/restclient/capability/server/ServerTemplateProcessingIntegrationTest.java b/src/test/java/com/openshift/internal/restclient/capability/server/ServerTemplateProcessingIntegrationTest.java index 9f4daabb..9fc4ddcb 100644 --- a/src/test/java/com/openshift/internal/restclient/capability/server/ServerTemplateProcessingIntegrationTest.java +++ b/src/test/java/com/openshift/internal/restclient/capability/server/ServerTemplateProcessingIntegrationTest.java @@ -1,80 +1,106 @@ /******************************************************************************* - * Copyright (c) 2015 Red Hat, Inc. Distributed under license by Red Hat, Inc. + * Copyright (c) 2015-2019 Red Hat, Inc. Distributed under license by Red Hat, Inc. * All rights reserved. This program is made available under the terms of the * Eclipse Public License v1.0 which accompanies this distribution, and is * available at http://www.eclipse.org/legal/epl-v10.html * * Contributors: Red Hat, Inc. ******************************************************************************/ + package com.openshift.internal.restclient.capability.server; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; + import java.net.MalformedURLException; import java.util.ArrayList; import java.util.Collection; +import java.util.stream.Collectors; import org.jboss.dmr.ModelNode; +import org.junit.After; import org.junit.Before; import org.junit.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.openshift.internal.restclient.IntegrationTestHelper; +import com.openshift.internal.restclient.model.KubernetesResource; import com.openshift.internal.restclient.model.template.Template; import com.openshift.restclient.IClient; +import com.openshift.restclient.OpenShiftException; import com.openshift.restclient.capability.CapabilityVisitor; import com.openshift.restclient.capability.server.ITemplateProcessing; +import com.openshift.restclient.model.IProject; import com.openshift.restclient.model.IResource; import com.openshift.restclient.model.template.ITemplate; import com.openshift.restclient.utils.Samples; -/** - * @author Jeff Cantrill - */ public class ServerTemplateProcessingIntegrationTest { - private static final String VERSION = "v1"; - private static final String COMMON = "openshift"; + private static final Logger LOG = LoggerFactory.getLogger(ServerTemplateProcessingIntegrationTest.class); + + private IntegrationTestHelper helper = new IntegrationTestHelper(); + private IClient client; + private IProject project; + private Collection resources = new ArrayList(); + + @Before + public void before() throws MalformedURLException { + this.client = helper.createClientForBasicAuth(); + this.project = helper.getOrCreateIntegrationTestProject(client); + } + + @After + public void after() { + helper.cleanUpResources(client, resources); + } + + @Test + public void testProcessAndApplyTemplate() throws Exception { + ModelNode node = ModelNode.fromJSONString(Samples.V1_TEMPLATE.getContentAsString()); + final Template template = new Template(node, client, null); + node = ModelNode.fromJSONString(Samples.GROUP_TEMPLATE.getContentAsString()); + final Template groupTemplate = new Template(node, client, null); + template.setNamespace(null); + client.accept(new CapabilityVisitor() { + + @Override + public Object visit(ITemplateProcessing capability) { + + try { + return processTemplate(template, capability); + } catch (OpenShiftException e) { + return processTemplate(groupTemplate, capability); + } + } + }, new Object()); + } - private static final Logger LOG = LoggerFactory.getLogger(ServerTemplateProcessingIntegrationTest.class); - - private IClient client; - private IntegrationTestHelper helper = new IntegrationTestHelper(); + private Object processTemplate(final Template template, ITemplateProcessing capability) { + LOG.debug("Processing template: {}", template.toJson()); + assertFalse("Exp. the template to have items for this test be interesting", + template.getObjects().isEmpty()); + final int items = template.getObjects().size(); + ITemplate processedTemplate = capability.process(template, project.getName()); - @Before - public void setup () throws MalformedURLException{ - client = helper.createClient(); - } - - @Test - public void testProcessAndApplyTemplate() throws Exception{ - final Collection results = new ArrayList(); - ModelNode node = ModelNode.fromJSONString(Samples.V1_TEMPLATE.getContentAsString()); - final Template template = new Template(node, client, null); - template.setNamespace(COMMON); - try { - client.accept(new CapabilityVisitor() { - - @Override - public Object visit(ITemplateProcessing capability) { - - LOG.debug("Processing template: " + template.toString()); - ITemplate processedTemplate = capability.process(template, COMMON); - - LOG.debug("Applying template: ", processedTemplate.toString()); - LOG.debug("applied template"); - for (IResource resource : processedTemplate.getItems()) { - LOG.debug("creating: ", resource); - results.add(client.create(resource, COMMON)); - LOG.debug("created: ", resource.toString()); - } - return null; - } - }, new Object()); - } finally { - IntegrationTestHelper.cleanUpResource(client, template); - for (IResource resource : results) { - IntegrationTestHelper.cleanUpResource(client, resource); - } - } - } + LOG.debug("Applying template: {}", processedTemplate.toJson()); + LOG.debug("Applied template"); + assertEquals("Exp. the pre and post item count to be the same", + items, + template.getObjects().size()); + Collection stubs = processedTemplate.getObjects(); + ServerTemplateProcessingIntegrationTest.this.resources = + stubs.stream() + .map(stub -> { + // resources as in template dont have a namespace + ((KubernetesResource) stub).setNamespace(project.getNamespaceName()); + LOG.debug("creating: {}", stub); + IResource resource = client.create(stub); + LOG.debug("created: {}", resource.toJson()); + return resource; + }) + .collect(Collectors.toList()); + return null; + } } diff --git a/src/test/java/com/openshift/internal/restclient/capability/server/ServerTemplateProcessingTest.java b/src/test/java/com/openshift/internal/restclient/capability/server/ServerTemplateProcessingTest.java index b5abfd67..5fcac005 100644 --- a/src/test/java/com/openshift/internal/restclient/capability/server/ServerTemplateProcessingTest.java +++ b/src/test/java/com/openshift/internal/restclient/capability/server/ServerTemplateProcessingTest.java @@ -6,38 +6,57 @@ * * Contributors: Red Hat, Inc. ******************************************************************************/ -package com.openshift.internal.restclient.capability.server; -import static org.junit.Assert.*; -import static org.mockito.Mockito.*; +package com.openshift.internal.restclient.capability.server; -import java.util.ArrayList; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; +import org.junit.Before; import org.junit.Test; -import com.openshift.internal.restclient.capability.server.ServerTemplateProcessing; +import com.openshift.restclient.IApiTypeMapper; +import com.openshift.restclient.IClient; import com.openshift.restclient.ResourceKind; -import com.openshift.restclient.model.IResource; -import com.openshift.restclient.model.template.ITemplate; +import com.openshift.restclient.capability.server.ITemplateProcessing; -/** - * @author Jeff Cantrill - */ public class ServerTemplateProcessingTest { - @Test - public void testTemplateConfigAdapter() { - ITemplate template = mock(ITemplate.class); - when(template.toString()).thenReturn("theToStringValue"); - final ArrayList items = new ArrayList(); - when(template.getItems()).thenReturn(items); - final String namespace = "test"; - ServerTemplateProcessing.TemplateConfigAdapter adapter = new ServerTemplateProcessing.TemplateConfigAdapter (template, namespace); - - assertEquals(namespace, adapter.getNamespace()); - assertEquals(ResourceKind.PROCESSED_TEMPLATES, adapter.getKind()); - assertEquals(template.toString(), adapter.toString()); - assertEquals(items, adapter.getItems()); - } + private IApiTypeMapper mapper; + private IClient client; + private ITemplateProcessing cap; + + @Before + public void setup() { + mapper = mock(IApiTypeMapper.class); + client = mock(IClient.class); + cap = new ServerTemplateProcessing(client); + + } + + @Test + public void testIsSupportedWhenApiEndpointExists() { + when(mapper.isSupported(ResourceKind.PROCESSED_TEMPLATES)).thenReturn(true); + when(client.adapt(IApiTypeMapper.class)).thenReturn(mapper); + + assertTrue("Exp. endpoint to be supported when processedtemplates is supported", cap.isSupported()); + } + + @Test + public void testIsSupportedWhenApiEndpointDoesNotExists() { + when(mapper.isSupported(ResourceKind.PROCESSED_TEMPLATES)).thenReturn(false); + when(client.adapt(IApiTypeMapper.class)).thenReturn(mapper); + + assertFalse("Exp. endpoint to not be supported when processedtemplates does not exist", cap.isSupported()); + } + + @Test + public void testIsNotSupportedWhenNotAdaptableToApiTypeMapper() { + when(client.adapt(IApiTypeMapper.class)).thenReturn(null); + + assertFalse("Exp. endpoint to not be supported when not adaptable", cap.isSupported()); + } } diff --git a/src/test/java/com/openshift/internal/restclient/http/HttpClientTest.java b/src/test/java/com/openshift/internal/restclient/http/HttpClientTest.java deleted file mode 100755 index 540c8506..00000000 --- a/src/test/java/com/openshift/internal/restclient/http/HttpClientTest.java +++ /dev/null @@ -1,516 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2012-2014 Red Hat, Inc. - * Distributed under license by Red Hat, Inc. All rights reserved. - * This program is made available under the terms of the - * Eclipse Public License v1.0 which accompanies this distribution, - * and is available at http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * Red Hat, Inc. - initial API and implementation - ******************************************************************************/ -package com.openshift.internal.restclient.http; - -import static org.fest.assertions.Assertions.assertThat; -import static org.hamcrest.CoreMatchers.instanceOf; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; - -import java.io.IOException; -import java.net.HttpURLConnection; -import java.net.MalformedURLException; -import java.net.SocketTimeoutException; -import java.net.URL; -import java.security.KeyStoreException; -import java.security.cert.X509Certificate; -import java.util.Random; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -import javax.net.ssl.SSLHandshakeException; -import javax.net.ssl.SSLSession; - -import org.junit.After; -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.ExpectedException; - -import com.openshift.internal.restclient.http.UrlConnectionHttpClient; -import com.openshift.internal.restclient.http.UrlConnectionHttpClientBuilder; -import com.openshift.internal.util.TestTimer; -import com.openshift.restclient.ISSLCertificateCallback; -import com.openshift.restclient.http.IHttpClient; -import com.openshift.restclient.http.IHttpConstants; -import com.openshift.restclient.server.HttpServerFake; -import com.openshift.restclient.server.HttpsServerFake; -import com.openshift.restclient.server.WaitingHttpServerFake; -import com.openshift.restclient.utils.Base64Coder; -import com.openshift.restclient.utils.ExceptionCauseMatcher; - -/** - * @author Andre Dietisheim - * @author Nicolas Spano - * @author Corey Daley - * @author Sean Kavanagh - */ -public class HttpClientTest extends TestTimer { - - private static final String ACCEPT_APPLICATION_JSON = "Accept: application/json"; - private static final Pattern AUTHORIZATION_PATTERN = Pattern.compile("Authorization: Basic ([^\n]*)"); - - private HttpServerFake serverFake; - private IHttpClient httpClient; - private HttpsServerFake httpsServerFake; - - @Rule - public ExpectedException expectedException = ExpectedException.none(); - - @Before - public void setUp() throws Exception { - this.serverFake = startHttpServerFake(null); - this.httpsServerFake = startHttpsServerFake(null); - this.httpClient = new UrlConnectionHttpClientBuilder() - .setAcceptMediaType(ACCEPT_APPLICATION_JSON) - .setUserAgent("com.openshift.client.test") - .setConfigTimeout(new Integer("10000")) - .client(); - } - - @After - public void tearDown() { - serverFake.stop(); - httpsServerFake.stop(); - } - - @Test(expected = HttpClientException.class) - public void shouldThrowIfNoAcceptedMediaType() throws SocketTimeoutException, HttpClientException, - MalformedURLException { - IHttpClient client = new UrlConnectionHttpClient( "useragent", null, "42.0"); - client.get(serverFake.getUrl(), IHttpClient.NO_TIMEOUT); - } - - @Test - public void canGet() throws Throwable { - String response = httpClient.get(serverFake.getUrl(), IHttpClient.NO_TIMEOUT); - assertThat(response).startsWith("GET"); - } - - - @Test - public void canHead() throws Throwable { - String response = httpClient.head(serverFake.getUrl(), IHttpClient.NO_TIMEOUT); - assertThat(response).isEqualTo(""); - } - - @Test - public void canDelete() throws Throwable { - String response = httpClient.delete(serverFake.getUrl(), IHttpClient.NO_TIMEOUT); - assertThat(response).startsWith("DELETE"); - } - - /** - * Assumes that the server is sending a certificate that is not known to the - * client. The test does this by having a custom ssl server with a self-signed certificate. - * - * @see HttpsServerFake - */ - @Test - public void shouldFailHttpsSelfsignedCertificateNoCallback() throws Throwable { - // pre-condition - expectedException.expect(new ExceptionCauseMatcher(instanceOf(SSLHandshakeException.class))); - - // operation - httpClient.get(httpsServerFake.getUrl(), IHttpClient.NO_TIMEOUT); - } - - /** - * Assumes that the server is sending a certificate that is not known to the - * client. The test does this by having a custom ssl server with a self-signed certificate. - * - * @see HttpsServerFake - */ - @Test - public void shouldSucceedHttpsSelfsignedCertificate() throws Throwable { - IHttpClient client = new UrlConnectionHttpClientBuilder() - .setAcceptMediaType(ACCEPT_APPLICATION_JSON) - .setUserAgent("com.openshift.client.test") - .setSSLCertificateCallback(new ISSLCertificateCallback() { - - @Override - public boolean allowHostname(String hostname, SSLSession session) { - return true; - } - - @Override - public boolean allowCertificate(X509Certificate[] chain) { - return true; - } - }) - .client(); - client.get(httpsServerFake.getUrl(), IHttpClient.NO_TIMEOUT); - } - - @Test - public void shouldCertificateBeInTrustStore() throws Throwable { - X509Certificate certOne = mock(X509Certificate.class); - when(certOne.getSigAlgName()).thenReturn("sig1"); - UrlConnectionHttpClient client = (UrlConnectionHttpClient) new UrlConnectionHttpClientBuilder() - .setAcceptMediaType(ACCEPT_APPLICATION_JSON) - .setUserAgent("com.openshift.client.test") - .setCertificate(httpsServerFake.getUrl().toString(), certOne) - .setSSLCertificateCallback(new ISSLCertificateCallback() { - - @Override - public boolean allowHostname(String hostname, SSLSession session) { - return true; - } - - @Override - public boolean allowCertificate(X509Certificate[] chain) { - return true; - } - }) - .client(); - X509Certificate[] certs = client.getTrustedCertificates(); - for (X509Certificate cert : certs) { - if (cert.getSigAlgName().equals("sig1")) { - return; - } - } - throw new Throwable("Did not find our certificate."); - } - - /** - * Assumes that the server is sending a certificate that is not known to the - * client. The test does this by having a custom ssl server with a self-signed certificate. - * - * @see HttpsServerFake - */ - @Test - public void shouldFailHttpsSelfsignedCertificate() throws Throwable { - // pre-condition - expectedException.expect(new ExceptionCauseMatcher(instanceOf(SSLHandshakeException.class))); - - IHttpClient client = new UrlConnectionHttpClientBuilder() - .setAcceptMediaType(ACCEPT_APPLICATION_JSON) - .setUserAgent("com.openshift.client.test") - .setSSLCertificateCallback(new ISSLCertificateCallback() { - - @Override - public boolean allowHostname(String hostname, SSLSession session) { - return true; - } - - @Override - public boolean allowCertificate(X509Certificate[] chain) { - return false; - } - }) - .client(); - - // operation - client.get(httpsServerFake.getUrl(), IHttpClient.NO_TIMEOUT); - } - - @Test - public void canAddAuthorization() throws SocketTimeoutException, HttpClientException, MalformedURLException { - String username = "andre.dietisheim@redhat.com"; - String password = "dummyPassword"; - IHttpClient httpClient = new UrlConnectionHttpClientBuilder() - .setAcceptMediaType(ACCEPT_APPLICATION_JSON) - .setUserAgent("com.openshift.client.test") - .setCredentials(username, password, null) - .client(); - - String response = httpClient.get(serverFake.getUrl(), IHttpClient.NO_TIMEOUT); - assertNotNull(response); - Matcher matcher = AUTHORIZATION_PATTERN.matcher(response); - assertTrue(matcher.find()); - assertEquals(1, matcher.groupCount()); - String credentials = matcher.group(1); - String cleartextCredentials = Base64Coder.decode(credentials); - assertThat(credentials) - .describedAs("credentials were not encoded in httpClient").isNotEqualTo(cleartextCredentials); - assertEquals(username + ":" + password, cleartextCredentials); - } - - @Test - public void shouldAcceptJson() throws SocketTimeoutException, HttpClientException, MalformedURLException { - String response = httpClient.get(serverFake.getUrl(), IHttpClient.NO_TIMEOUT); - assertNotNull(response); - assertTrue(response.indexOf(ACCEPT_APPLICATION_JSON) > 0); - } - - @Test - public void shouldAddServiceVersionToAcceptHeader() throws Exception { - // pre-conditions - String version = "42.0"; - AcceptVersionClientFake clientFake = new AcceptVersionClientFake(version); - // operation - HttpURLConnection connection = clientFake.createConnection(); - // verification - assertThat(clientFake.getAcceptHeader(connection)).endsWith("; version=" + version); - } - - @Test(expected = NotFoundException.class) - public void shouldThrowNotFoundException() throws Exception { - HttpServerFake server = null; - try { - // precondition - this.serverFake.stop(); - server = startHttpServerFake("HTTP/1.0 404 Not Found"); - - // operation - httpClient.get(server.getUrl(), IHttpClient.NO_TIMEOUT); - } finally { - server.stop(); - } - } - - /** - * - * RFC 1945 6.1.1 / Reason Phrase is optional - *

- * 'HTTP/1.1 404 ' is equivalent to HTTP/1.1 404 Not Found' - * https://bugzilla.redhat.com/show_bug.cgi?id=913796 - * - * @throws IOException - */ - @Test(expected = NotFoundException.class) - public void shouldReasonPhraseIsOptional() throws Exception { - HttpServerFake server = null; - try { - // precondition - this.serverFake.stop(); - // RFC 1945 6.1.1 / Reason Phrase is optional - server = startHttpServerFake("HTTP/1.0 404 "); - - // operation - httpClient.get(server.getUrl(), IHttpClient.NO_TIMEOUT); - } finally { - server.stop(); - } - } - - @Test - public void shouldHaveURLInExceptionMessage() throws Exception { - HttpServerFake server = null; - try { - // precondition - this.serverFake.stop(); - // RFC 1945 6.1.1 / Reason Phrase is optional - server = startHttpServerFake("HTTP/1.0 404 Not Found"); - - // operation - httpClient.get(server.getUrl(), IHttpClient.NO_TIMEOUT); - fail("Expected NotFoundException not thrown"); - } catch (NotFoundException e) { - assertTrue(e.getMessage().contains(server.getUrl().toString())); - } finally { - server.stop(); - } - } -//TODO delete me? after moving to apache.httpclient -// @Test -// public void shouldRespectGivenTimeoutPOST() throws Throwable { -// // pre-conditions -// final int timeout = 1000; -// final int serverDelay = timeout * 4; -// assertThat(timeout).isLessThan(IHttpConstants.DEFAULT_READ_TIMEOUT); -// WaitingHttpServerFake serverFake = startWaitingHttpServerFake(serverDelay); -// long startTime = System.currentTimeMillis(); -// // operations -// try { -// httpClient.post(serverFake.getUrl(), new FormUrlEncodedMediaType(), timeout); -// fail("Timeout expected."); -// } catch (SocketTimeoutException e) { -// // assert -// assertThat(System.currentTimeMillis() - startTime).isGreaterThan(timeout) -// .isLessThan(serverDelay) -// .isLessThan(IHttpConstants.DEFAULT_READ_TIMEOUT); -// } finally { -// serverFake.stop(); -// } -// } - - @Test - public void shouldRespectGivenTimeoutDELETE() throws Throwable { - // pre-conditions - final int timeout = 1000; - final int serverDelay = timeout * 4; - assertThat(timeout).isLessThan(IHttpClient.DEFAULT_READ_TIMEOUT); - WaitingHttpServerFake serverFake = startWaitingHttpServerFake(serverDelay); - long startTime = System.currentTimeMillis(); - // operations - try { - httpClient.delete(serverFake.getUrl(), timeout); - fail("Timeout expected."); - } catch (SocketTimeoutException e) { - // assert - assertThat(System.currentTimeMillis() - startTime).isGreaterThan(timeout) - .isLessThan(serverDelay) - .isLessThan(IHttpClient.DEFAULT_READ_TIMEOUT); - } finally { - serverFake.stop(); - } - } - -// @Test -// public void shouldRespectGivenTimeoutPUT() throws Throwable { -// // pre-conditions -// final int timeout = 1000; -// final int serverDelay = timeout * 4; -// assertThat(timeout).isLessThan(IHttpConstants.DEFAULT_READ_TIMEOUT); -// WaitingHttpServerFake serverFake = startWaitingHttpServerFake(serverDelay); -// long startTime = System.currentTimeMillis(); -// // operations -// try { -// httpClient.put(serverFake.getUrl(), new FormUrlEncodedMediaType(), timeout); -// fail("Timeout expected."); -// } catch (SocketTimeoutException e) { -// // assert -// assertThat(System.currentTimeMillis() - startTime).isGreaterThan(timeout) -// .isLessThan(serverDelay) -// .isLessThan(IHttpConstants.DEFAULT_READ_TIMEOUT); -// } finally { -// serverFake.stop(); -// } -// } - - @Test - public void shouldRespectGivenTimeoutGET() throws Throwable { - // pre-conditions - final int timeout = 1000; - final int serverDelay = timeout * 4; - assertThat(timeout).isLessThan(IHttpClient.DEFAULT_READ_TIMEOUT); - WaitingHttpServerFake serverFake = this.startWaitingHttpServerFake(serverDelay); - - long startTime = System.currentTimeMillis(); - // operations - try { - httpClient.get(serverFake.getUrl(), timeout); - fail("Timeout expected."); - } catch (SocketTimeoutException e) { - // assert - assertThat(System.currentTimeMillis() - startTime).isGreaterThan(timeout) - .isLessThan(serverDelay) - .isLessThan(IHttpClient.DEFAULT_READ_TIMEOUT); - } finally { - serverFake.stop(); - } - } - - @Test - public void shouldFallbackToOpenShiftTimeout() throws Throwable { - // pre-conditions - final int timeout = 1000; - final int serverDelay = timeout * 15; - assertThat(timeout).isLessThan(IHttpClient.DEFAULT_READ_TIMEOUT); - System.setProperty(IHttpClient.SYSPROP_OPENSHIFT_READ_TIMEOUT, String.valueOf(timeout)); - WaitingHttpServerFake serverFake = startWaitingHttpServerFake(serverDelay); - long startTime = System.currentTimeMillis(); - // operations - try { - httpClient.get(serverFake.getUrl(), IHttpClient.NO_TIMEOUT); - fail("Timeout expected."); - } catch (SocketTimeoutException e) { - // assert - assertThat(System.currentTimeMillis() - startTime).isGreaterThan(timeout) - .isLessThan(serverDelay) - .isLessThan(IHttpClient.DEFAULT_READ_TIMEOUT); - } finally { - serverFake.stop(); - System.clearProperty(IHttpClient.SYSPROP_OPENSHIFT_READ_TIMEOUT); - } - } - -// @Test -// public void shouldRespectDefaultTimeout() throws Throwable { -// // pre-conditions -// final int timeout = 1000; -// final int serverDelay = timeout * 10000; -// IOpenShiftConfiguration configuration = new OpenShiftConfigurationFake(null,null,null,"5000"); -// IHttpClient httpClient = new UrlConnectionHttpClientBuilder() -// .setAcceptMediaType(ACCEPT_APPLICATION_JSON) -// .setUserAgent("com.openshift.client.test") -// .setConfigTimeout(configuration.getTimeout()) -// .client(); -// WaitingHttpServerFake serverFake = startWaitingHttpServerFake(serverDelay); -// long startTime = System.currentTimeMillis(); -// // operations -// try { -// httpClient.get(serverFake.getUrl(), IHttpConstants.NO_TIMEOUT); -// fail("Timeout expected."); -// } catch (SocketTimeoutException e) { -// // assert -// assertThat(System.currentTimeMillis() - startTime) -// .isGreaterThan(configuration.getTimeout() - 20) -// .isLessThan(configuration.getTimeout() + 20); -// } finally { -// serverFake.stop(); -// } -// } - - - private HttpServerFake startHttpServerFake(String statusLine) throws Exception { - int port = new Random().nextInt(9 * 1024) + 1024; - HttpServerFake serverFake = null; - if (statusLine == null) { - serverFake = new HttpServerFake(port); - } else { - serverFake = new HttpServerFake(port, null, statusLine); - } - serverFake.start(); - return serverFake; - } - - private HttpsServerFake startHttpsServerFake(String statusLine) throws Exception { - int port = new Random().nextInt(9 * 1024) + 1024; - HttpsServerFake serverFake = null; - if (statusLine == null) { - serverFake = new HttpsServerFake(port); - } else { - serverFake = new HttpsServerFake(port, null, statusLine); - } - serverFake.start(); - return serverFake; - } - - private WaitingHttpServerFake startWaitingHttpServerFake(int delay) throws Exception { - WaitingHttpServerFake serverFake = new WaitingHttpServerFake(delay); - serverFake.start(); - return serverFake; - } - - private class AcceptVersionClientFake extends UrlConnectionHttpClientFake { - - public AcceptVersionClientFake(String acceptVersion) { - super(null, acceptVersion); - } - - public String getAcceptHeader(HttpURLConnection connection) { - return connection.getRequestProperty(IHttpConstants.PROPERTY_ACCEPT); - } - } - - private abstract class UrlConnectionHttpClientFake extends UrlConnectionHttpClient { - private UrlConnectionHttpClientFake(String userAgent, String acceptVersion) { - super(userAgent, IHttpConstants.MEDIATYPE_APPLICATION_JSON, acceptVersion, - null, IHttpClient.NO_TIMEOUT, null); - } - - private UrlConnectionHttpClientFake(String userAgent, String acceptVersion, ISSLCertificateCallback callback) { - super(userAgent, IHttpConstants.MEDIATYPE_APPLICATION_JSON, acceptVersion, - callback,IHttpClient.NO_TIMEOUT, null); - } - - public HttpURLConnection createConnection() throws IOException, KeyStoreException { - return super.createConnection(new URL("http://localhost"), userAgent, acceptedVersion, acceptedMediaType, sslAuthorizationCallback, NO_TIMEOUT); - } - }; - -} diff --git a/src/test/java/com/openshift/internal/restclient/http/HttpMethodTest.java b/src/test/java/com/openshift/internal/restclient/http/HttpMethodTest.java deleted file mode 100644 index 3a9094e6..00000000 --- a/src/test/java/com/openshift/internal/restclient/http/HttpMethodTest.java +++ /dev/null @@ -1,30 +0,0 @@ - /******************************************************************************* - * Copyright (c) 2015 Red Hat, Inc. Distributed under license by Red Hat, Inc. - * All rights reserved. This program is made available under the terms of the - * Eclipse Public License v1.0 which accompanies this distribution, and is - * available at http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: Red Hat, Inc. - ******************************************************************************/ -package com.openshift.internal.restclient.http; - -import static org.junit.Assert.*; - -import org.junit.Test; - -/** - * @author Andre Dietisheim - */ -public class HttpMethodTest { - - @Test - public void hasValueForKnownValueShouldReturnTrue() { - assertTrue(HttpMethod.hasValue("POST")); - assertTrue(HttpMethod.hasValue("pOst")); - } - @Test - public void hasValueForUnKnownValueShouldReturnFalse() { - assertFalse(HttpMethod.hasValue("afdadsfads")); - } - -} diff --git a/src/test/java/com/openshift/internal/restclient/http/UrlConnectionHttpClientTest.java b/src/test/java/com/openshift/internal/restclient/http/UrlConnectionHttpClientTest.java deleted file mode 100644 index 9c7acf14..00000000 --- a/src/test/java/com/openshift/internal/restclient/http/UrlConnectionHttpClientTest.java +++ /dev/null @@ -1,61 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2015 Red Hat, Inc. Distributed under license by Red Hat, Inc. - * All rights reserved. This program is made available under the terms of the - * Eclipse Public License v1.0 which accompanies this distribution, and is - * available at http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: Red Hat, Inc. - ******************************************************************************/ -package com.openshift.internal.restclient.http; - -import static org.mockito.Matchers.any; -import static org.mockito.Matchers.anyString; -import static org.mockito.Mockito.never; -import static org.mockito.Mockito.verify; - -import java.net.HttpURLConnection; - -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.mockito.Mock; -import org.mockito.runners.MockitoJUnitRunner; - -import com.openshift.internal.restclient.http.UrlConnectionHttpClient; -import com.openshift.restclient.authorization.IAuthorizationStrategy; -import com.openshift.restclient.authorization.IRequest; - -/** - * @author Jeff Cantrill - */ -@RunWith(MockitoJUnitRunner.class) -public class UrlConnectionHttpClientTest { - - @Mock - private IAuthorizationStrategy strategy; - private UrlConnectionHttpClient client; - @Mock - private HttpURLConnection connection; - - @Before - public void setUp(){ - client = new UrlConnectionHttpClient("testagent", "application/json", "1"); - } - - @Test - public void nullAuthStrategyShouldNotThrowNPEWhenSetAuthorization() { - client.setAuthorizationStrategy(null); - client.setAuthorization(connection ); - verify(connection, never()).setRequestProperty(anyString(), anyString()); - } - - @Test - public void setAuthorizationWhenStrategyIsSetShouldUseTheStrategy() { - client.setAuthorizationStrategy(strategy); - - client.setAuthorization(connection); - verify(connection, never()).setRequestProperty(anyString(), anyString()); - verify(strategy).authorize(any(IRequest.class)); - } - -} diff --git a/src/test/java/com/openshift/internal/restclient/model/DeploymentConfigTest.java b/src/test/java/com/openshift/internal/restclient/model/BuildConfigTest.java similarity index 57% rename from src/test/java/com/openshift/internal/restclient/model/DeploymentConfigTest.java rename to src/test/java/com/openshift/internal/restclient/model/BuildConfigTest.java index 8222a3af..acc6fd63 100644 --- a/src/test/java/com/openshift/internal/restclient/model/DeploymentConfigTest.java +++ b/src/test/java/com/openshift/internal/restclient/model/BuildConfigTest.java @@ -8,9 +8,10 @@ * Contributors: * Red Hat, Inc. - initial API and implementation ******************************************************************************/ + package com.openshift.internal.restclient.model; -import static org.junit.Assert.*; +import static org.junit.Assert.assertEquals; import static org.mockito.Mockito.mock; import java.util.HashMap; @@ -20,27 +21,27 @@ import org.junit.Test; import com.openshift.restclient.IClient; -import com.openshift.restclient.capability.resources.IDeployCapability; -import com.openshift.restclient.model.IDeploymentConfig; +import com.openshift.restclient.model.IBuildConfig; /** - * Tests unrelated to the underlying model structure and - * should api version independent - * @author jeff.cantrill + * Tests unrelated to the underlying model structure and should api version + * independent + * + * @author Jeff Maury * */ -public class DeploymentConfigTest { +public class BuildConfigTest { - private IDeploymentConfig config; + private IBuildConfig config; - @Before - public void setUp() throws Exception { - config = new DeploymentConfig(new ModelNode(), mock(IClient.class), new HashMap<>()); - } + @Before + public void setUp() throws Exception { + config = new BuildConfig(new ModelNode(), mock(IClient.class), new HashMap<>()); + } - @Test - public void testIsDeployCapable() { - assertTrue(config.supports(IDeployCapability.class)); - } + @Test + public void testBuildTriggersShouldReturn() { + assertEquals(0, config.getBuildTriggers().size()); + } } diff --git a/src/test/java/com/openshift/internal/restclient/model/KubernetesResourceTest.java b/src/test/java/com/openshift/internal/restclient/model/KubernetesResourceTest.java index 0bf321e8..b163136a 100644 --- a/src/test/java/com/openshift/internal/restclient/model/KubernetesResourceTest.java +++ b/src/test/java/com/openshift/internal/restclient/model/KubernetesResourceTest.java @@ -6,15 +6,16 @@ * * Contributors: Red Hat, Inc. ******************************************************************************/ + package com.openshift.internal.restclient.model; -import static org.fest.assertions.Assertions.assertThat; +import static com.openshift.internal.util.JBossDmrExtentions.getPath; +import static org.assertj.core.api.Assertions.assertThat; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; -import static com.openshift.internal.util.JBossDmrExtentions.*; import java.util.ArrayList; import java.util.List; @@ -31,199 +32,202 @@ import com.openshift.restclient.capability.resources.IDeploymentTraceability; import com.openshift.restclient.capability.resources.ITemplateTraceability; -/** - * @author Jeff Cantrill - */ public class KubernetesResourceTest { - private ModelNode node; - private KubernetesResource resource; - - @Before - public void setup(){ - this.node = createModelNode(); - this.resource = createKubernetesResource(OpenShiftAPIVersion.v1.toString(), node); - } - - private ModelNode createModelNode() { - node = new ModelNode(); - node.get(ResourcePropertyKeys.KIND).set(ResourceKind.LIST.toString()); - - ModelNode annotations = node.get(getPath(KubernetesResource.ANNOTATIONS)); - annotations.get("foo").set("bar"); - annotations.get("template").set("foobar"); - - node.get(KubernetesResource.METADATA_NAME).set("bartender"); - node.get(KubernetesResource.METADATA_NAMESPACE).set("foofighters"); - - return node; - } - - private KubernetesResource createKubernetesResource(String modelVersion, ModelNode node) { - return new KubernetesResource(node, null, - ResourcePropertiesRegistry.getInstance().get(modelVersion, ResourceKind.SERVICE)) {}; - } - - @Test - public void testSetAnnoationWithNullValueShouldReturnGracefully() { - resource.setAnnotation("black",null); - } - - @Test - public void testSetAnnoation() { - resource.setAnnotation("black", "white"); - assertEquals("white",resource.getAnnotation("black")); - } - - @Test - public void testGetAnnotation() { - assertEquals("bar", resource.getAnnotation("foo")); - } - - @Test - public void removeAnnotation() { - resource.removeAnnotation("foo"); - assertNull(resource.getAnnotation("foo")); - } - - @Test - public void isAnnotatedReturnsTrueForKnownAnnotation() { - assertTrue(resource.isAnnotatedWith("foo")); - } - - @Test - public void isAnnotatedReturnsFalseForUnKnownAnnotation() { - assertFalse(resource.isAnnotatedWith("bar")); - } - - @Test - public void supportsIsFalseForUnsupportedCapability() { - assertFalse("Expected to not support capability because IClient is null",resource.supports(IDeploymentTraceability.class)); - } - - @Test - public void getCapabilityReturnsNonNullWhenSupportedCapability() { - assertTrue("Exp. to support capability since resource has template annotation", resource.supports(ITemplateTraceability.class)); - assertNotNull(resource.getCapability(ITemplateTraceability.class)); - } - - @Test - public void testAcceptVisitor(){ - final List visited = new ArrayList(); - resource.accept(new CapabilityVisitor(){ - - @Override - public Object visit(ITemplateTraceability capability) { - visited.add(Boolean.TRUE); - return (Object)null; - } - - }, new Object()); - assertEquals("Exp. the visitor to be visited", 1, visited.size()); - } - - @Test - public void shouldSameHashCodeOnAddedLabels() { - // pre-condition - int hashCodeBeforeChange = resource.hashCode(); - - // operation - resource.set(ResourcePropertyKeys.LABELS, "kungfoo"); - - // verification - int hashCodeAfterChange = resource.hashCode(); - assertEquals(hashCodeBeforeChange, hashCodeAfterChange); - } - - @Test - public void shouldDifferentHashCodeOnDifferentName() { - // pre-condition - int hashCodeBeforeChange = resource.hashCode(); - - // operation - resource.set(KubernetesResource.METADATA_NAME, "brucefoolee"); - - // verification - int hashCodeAfterChange = resource.hashCode(); - assertThat(hashCodeBeforeChange).isNotEqualTo(hashCodeAfterChange); - } - - @Test - public void shouldDifferentHashCodeOnDifferentResourceKind() { - // pre-condition - int hashCodeBeforeChange = resource.hashCode(); - - // operation - node.get(ResourcePropertyKeys.KIND).set(ResourceKind.EVENT.toString()); - - // verification - int hashCodeAfterChange = resource.hashCode(); - assertThat(hashCodeBeforeChange).isNotEqualTo(hashCodeAfterChange); - } - - @Test - public void shouldDifferentHashCodeOnDifferentNamespace() { - // pre-condition - int hashCodeBeforeChange = resource.hashCode(); - - // operation - node.get(new String [] {"metadata", "namespace"}).set("barfoo"); - - // verification - int hashCodeAfterChange = resource.hashCode(); - assertThat(hashCodeBeforeChange).isNotEqualTo(hashCodeAfterChange); - } - - @Test - public void shouldEqualsOnAddedLabels() { - // pre-condition - KubernetesResource otherResource = createKubernetesResource(OpenShiftAPIVersion.v1.toString(), node); - assertEquals(resource, otherResource); - - // operation - otherResource.set(ResourcePropertyKeys.LABELS, "bruceleefoo"); - - // verification - assertEquals(resource, otherResource); - } - - @Test - public void shouldNotEqualsOnDifferentName() { - // pre-condition - KubernetesResource otherResource = createKubernetesResource(OpenShiftAPIVersion.v1.toString(), createModelNode()); - assertEquals(resource, otherResource); - - // operation - otherResource.set(KubernetesResource.METADATA_NAME, "kungfoo"); - - // verification - assertThat(resource).isNotEqualTo(otherResource); - } - - @Test - public void shouldNotEqualsOnDifferentNamespace() { - // pre-condition - KubernetesResource otherResource = createKubernetesResource(OpenShiftAPIVersion.v1.toString(), createModelNode()); - assertEquals(resource, otherResource); - - // operation - otherResource.set(KubernetesResource.METADATA_NAMESPACE, "karate"); - - // verification - assertThat(resource).isNotEqualTo(otherResource); - } - - @Test - public void shouldNotEqualsOnDifferentResourceKind() { - // pre-condition - KubernetesResource otherResource = createKubernetesResource(OpenShiftAPIVersion.v1.toString(), createModelNode()); - assertEquals(resource, otherResource); - - // operation - otherResource.set(ResourcePropertyKeys.KIND, ResourceKind.EVENT.toString()); - - // verification - assertThat(resource).isNotEqualTo(otherResource); - } + private ModelNode node; + private KubernetesResource resource; + + @Before + public void setup() { + this.node = createModelNode(); + this.resource = createKubernetesResource(OpenShiftAPIVersion.v1.toString(), node); + } + + private ModelNode createModelNode() { + node = new ModelNode(); + node.get(ResourcePropertyKeys.KIND).set(ResourceKind.LIST.toString()); + + ModelNode annotations = node.get(getPath(KubernetesResource.ANNOTATIONS)); + annotations.get("foo").set("bar"); + annotations.get("template").set("foobar"); + + node.get(KubernetesResource.METADATA_NAME).set("bartender"); + node.get(KubernetesResource.METADATA_NAMESPACE).set("foofighters"); + + return node; + } + + private KubernetesResource createKubernetesResource(String modelVersion, ModelNode node) { + return new KubernetesResource(node, null, + ResourcePropertiesRegistry.getInstance().get(modelVersion, ResourceKind.SERVICE)) { + }; + } + + @Test + public void testSetAnnoationWithNullValueShouldReturnGracefully() { + resource.setAnnotation("black", null); + } + + @Test + public void testSetAnnoation() { + resource.setAnnotation("black", "white"); + assertEquals("white", resource.getAnnotation("black")); + } + + @Test + public void testGetAnnotation() { + assertEquals("bar", resource.getAnnotation("foo")); + } + + @Test + public void removeAnnotation() { + resource.removeAnnotation("foo"); + assertNull(resource.getAnnotation("foo")); + } + + @Test + public void isAnnotatedReturnsTrueForKnownAnnotation() { + assertTrue(resource.isAnnotatedWith("foo")); + } + + @Test + public void isAnnotatedReturnsFalseForUnKnownAnnotation() { + assertFalse(resource.isAnnotatedWith("bar")); + } + + @Test + public void supportsIsFalseForUnsupportedCapability() { + assertFalse("Expected to not support capability because IClient is null", + resource.supports(IDeploymentTraceability.class)); + } + + @Test + public void getCapabilityReturnsNonNullWhenSupportedCapability() { + assertTrue("Exp. to support capability since resource has template annotation", + resource.supports(ITemplateTraceability.class)); + assertNotNull(resource.getCapability(ITemplateTraceability.class)); + } + + @Test + public void testAcceptVisitor() { + final List visited = new ArrayList(); + resource.accept(new CapabilityVisitor() { + + @Override + public Object visit(ITemplateTraceability capability) { + visited.add(Boolean.TRUE); + return (Object) null; + } + + }, new Object()); + assertEquals("Exp. the visitor to be visited", 1, visited.size()); + } + + @Test + public void shouldSameHashCodeOnAddedLabels() { + // pre-condition + int hashCodeBeforeChange = resource.hashCode(); + + // operation + resource.set(ResourcePropertyKeys.LABELS, "kungfoo"); + + // verification + int hashCodeAfterChange = resource.hashCode(); + assertEquals(hashCodeBeforeChange, hashCodeAfterChange); + } + + @Test + public void shouldDifferentHashCodeOnDifferentName() { + // pre-condition + int hashCodeBeforeChange = resource.hashCode(); + + // operation + resource.set(KubernetesResource.METADATA_NAME, "brucefoolee"); + + // verification + int hashCodeAfterChange = resource.hashCode(); + assertThat(hashCodeBeforeChange).isNotEqualTo(hashCodeAfterChange); + } + + @Test + public void shouldDifferentHashCodeOnDifferentResourceKind() { + // pre-condition + int hashCodeBeforeChange = resource.hashCode(); + + // operation + node.get(ResourcePropertyKeys.KIND).set(ResourceKind.EVENT.toString()); + + // verification + int hashCodeAfterChange = resource.hashCode(); + assertThat(hashCodeBeforeChange).isNotEqualTo(hashCodeAfterChange); + } + + @Test + public void shouldDifferentHashCodeOnDifferentNamespace() { + // pre-condition + int hashCodeBeforeChange = resource.hashCode(); + + // operation + node.get(new String[] { "metadata", "namespace" }).set("barfoo"); + + // verification + int hashCodeAfterChange = resource.hashCode(); + assertThat(hashCodeBeforeChange).isNotEqualTo(hashCodeAfterChange); + } + + @Test + public void shouldEqualsOnAddedLabels() { + // pre-condition + KubernetesResource otherResource = createKubernetesResource(OpenShiftAPIVersion.v1.toString(), node); + assertEquals(resource, otherResource); + + // operation + otherResource.set(ResourcePropertyKeys.LABELS, "bruceleefoo"); + + // verification + assertEquals(resource, otherResource); + } + + @Test + public void shouldNotEqualsOnDifferentName() { + // pre-condition + KubernetesResource otherResource = createKubernetesResource(OpenShiftAPIVersion.v1.toString(), + createModelNode()); + assertEquals(resource, otherResource); + + // operation + otherResource.set(KubernetesResource.METADATA_NAME, "kungfoo"); + + // verification + assertThat(resource).isNotEqualTo(otherResource); + } + + @Test + public void shouldNotEqualsOnDifferentNamespace() { + // pre-condition + KubernetesResource otherResource = createKubernetesResource(OpenShiftAPIVersion.v1.toString(), + createModelNode()); + assertEquals(resource, otherResource); + + // operation + otherResource.set(KubernetesResource.METADATA_NAMESPACE, "karate"); + + // verification + assertThat(resource).isNotEqualTo(otherResource); + } + + @Test + public void shouldNotEqualsOnDifferentResourceKind() { + // pre-condition + KubernetesResource otherResource = createKubernetesResource(OpenShiftAPIVersion.v1.toString(), + createModelNode()); + assertEquals(resource, otherResource); + + // operation + otherResource.set(ResourcePropertyKeys.KIND, ResourceKind.EVENT.toString()); + + // verification + assertThat(resource).isNotEqualTo(otherResource); + } } diff --git a/src/test/java/com/openshift/internal/restclient/model/NamespaceTest.java b/src/test/java/com/openshift/internal/restclient/model/NamespaceTest.java new file mode 100644 index 00000000..4cf9fc1f --- /dev/null +++ b/src/test/java/com/openshift/internal/restclient/model/NamespaceTest.java @@ -0,0 +1,43 @@ +package com.openshift.internal.restclient.model; + +import static org.junit.Assert.assertEquals; +import static org.mockito.Mockito.mock; + +import org.jboss.dmr.ModelNode; +import org.junit.Before; +import org.junit.Test; + +import com.openshift.internal.restclient.model.properties.ResourcePropertiesRegistry; +import com.openshift.restclient.IClient; +import com.openshift.restclient.ResourceKind; +import com.openshift.restclient.model.INamespace; +import com.openshift.restclient.utils.Samples; + +public class NamespaceTest { + + private static final String VERSION = "v1"; + private INamespace namespace; + + @Before + public void setUp(){ + IClient client = mock(IClient.class); + ModelNode node = ModelNode.fromJSONString(Samples.V1_NAMESPACE.getContentAsString()); + namespace = new Namespace(node, client, ResourcePropertiesRegistry.getInstance().get(VERSION, + ResourceKind.NAMESPACE)); + } + + @Test + public void testGetDisplayName() { + assertEquals("OpenShift 3 Sample", namespace.getDisplayName()); + } + + @Test + public void testGetDescription() { + assertEquals("This is an example namespace to demonstrate OpenShift v3", namespace.getDescription()); + } + + @Test + public void testGetRequester() { + assertEquals("admin", namespace.getRequester()); + } +} \ No newline at end of file diff --git a/src/test/java/com/openshift/internal/restclient/model/PortFactory.java b/src/test/java/com/openshift/internal/restclient/model/PortFactory.java index c15b6ded..3004ba64 100644 --- a/src/test/java/com/openshift/internal/restclient/model/PortFactory.java +++ b/src/test/java/com/openshift/internal/restclient/model/PortFactory.java @@ -8,26 +8,24 @@ * Contributors: * Red Hat, Inc. - initial API and implementation ******************************************************************************/ + package com.openshift.internal.restclient.model; import org.jboss.dmr.ModelNode; -/** - * - * @author Jeff Cantrill - * - */ public class PortFactory { - public static ServicePort createServicePort(String name, String proto, int port, int targetPort) { - return createServicePort(name, proto, port, String.valueOf(targetPort)); - } - public static ServicePort createServicePort(String name, String proto, int port, String targetPort) { - ModelNode node = new ModelNode(); - node.get("name").set(name); - node.get("protocol").set(proto); - node.get("port").set(port); - node.get("targetPort").set(targetPort); - return new ServicePort(node); - } + public static ServicePort createServicePort(String name, String proto, int port, int targetPort,int nodePort) { + return createServicePort(name, proto, port, String.valueOf(targetPort),String.valueOf(nodePort)); + } + + public static ServicePort createServicePort(String name, String proto, int port, String targetPort, String nodePort) { + ModelNode node = new ModelNode(); + node.get("name").set(name); + node.get("protocol").set(proto); + node.get("port").set(port); + node.get("targetPort").set(targetPort); + node.get("nodePort").set(nodePort); + return new ServicePort(node); + } } diff --git a/src/test/java/com/openshift/internal/restclient/model/ProjectTest.java b/src/test/java/com/openshift/internal/restclient/model/ProjectTest.java index 68b0fcff..1e2c89e6 100644 --- a/src/test/java/com/openshift/internal/restclient/model/ProjectTest.java +++ b/src/test/java/com/openshift/internal/restclient/model/ProjectTest.java @@ -1,15 +1,20 @@ /******************************************************************************* - * Copyright (c) 2015 Red Hat, Inc. Distributed under license by Red Hat, Inc. + * Copyright (c) 2015-2019 Red Hat, Inc. Distributed under license by Red Hat, Inc. * All rights reserved. This program is made available under the terms of the * Eclipse Public License v1.0 which accompanies this distribution, and is * available at http://www.eclipse.org/legal/epl-v10.html * * Contributors: Red Hat, Inc. ******************************************************************************/ + package com.openshift.internal.restclient.model; -import static org.junit.Assert.*; -import static org.mockito.Mockito.*; +import static org.junit.Assert.assertEquals; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; import java.util.ArrayList; import java.util.List; @@ -18,39 +23,62 @@ import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; -import org.mockito.runners.MockitoJUnitRunner; +import org.mockito.junit.MockitoJUnitRunner; import com.openshift.internal.restclient.OpenShiftAPIVersion; import com.openshift.internal.restclient.ResourceFactory; -import com.openshift.internal.restclient.model.Project; +import com.openshift.restclient.IApiTypeMapper; +import com.openshift.restclient.IApiTypeMapper.IVersionedType; import com.openshift.restclient.IClient; import com.openshift.restclient.ResourceKind; import com.openshift.restclient.model.IService; -/** - * @author Jeff Cantrill - */ @RunWith(MockitoJUnitRunner.class) public class ProjectTest { - @Mock private IClient client; - private Project project; - - @Before - public void setup(){ - project = new ResourceFactory(client){}.create(OpenShiftAPIVersion.v1.toString(), ResourceKind.PROJECT); - project.setName("aprojectname"); - } - - @Test - public void getResourcesShouldUseProjectNameForNamespaceWhenGettingResources() { - ArrayList services = new ArrayList(); - when(client.list(eq(ResourceKind.SERVICE), anyString())).thenReturn(services); - List resources = project.getResources(ResourceKind.SERVICE); - - assertEquals("Exp. a list of services", services, resources); - verify(client).list(eq(ResourceKind.SERVICE), eq(project.getName())); - } - + @Mock + private IClient client; + private Project project; + + @Before + public void setup() { + IApiTypeMapper mapper = mock(IApiTypeMapper.class); + when(client.adapt(IApiTypeMapper.class)).thenReturn(mapper); + when(mapper.getType(anyString(), eq(ResourceKind.PROJECT))).thenReturn(new IVersionedType() { + + @Override + public String getVersion() { + return "v1"; + } + + @Override + public String getPrefix() { + return null; + } + + @Override + public String getKind() { + return ResourceKind.PROJECT; + } + + @Override + public String getApiGroupName() { + return null; + } + }); + project = new ResourceFactory(client) { + }.create(OpenShiftAPIVersion.v1.toString(), ResourceKind.PROJECT); + project.setName("aprojectname"); + } + + @Test + public void getResourcesShouldUseProjectNameForNamespaceWhenGettingResources() { + ArrayList services = new ArrayList(); + when(client.list(eq(ResourceKind.SERVICE), anyString())).thenReturn(services); + List resources = project.getResources(ResourceKind.SERVICE); + + assertEquals("Exp. a list of services", services, resources); + verify(client).list(eq(ResourceKind.SERVICE), eq(project.getName())); + } } diff --git a/src/test/java/com/openshift/internal/restclient/model/RouteTest.java b/src/test/java/com/openshift/internal/restclient/model/RouteTest.java index e68ec452..1ff82372 100644 --- a/src/test/java/com/openshift/internal/restclient/model/RouteTest.java +++ b/src/test/java/com/openshift/internal/restclient/model/RouteTest.java @@ -7,10 +7,14 @@ * * Contributors: * Red Hat, Inc. - initial API and implementation - ******************************************************************************/package com.openshift.internal.restclient.model; + ******************************************************************************/ -import static org.junit.Assert.*; -import static org.mockito.Mockito.*; +package com.openshift.internal.restclient.model; + +import static org.junit.Assert.assertEquals; +import static org.mockito.Mockito.doReturn; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.spy; import org.jboss.dmr.ModelNode; import org.junit.Before; @@ -22,35 +26,44 @@ import com.openshift.restclient.model.route.ITLSConfig; /** - * Test for route functionality that should not depend on the - * underlying api model + * Test for route functionality that should not depend on the underlying api + * model * - * @author Jeff Cantrill * */ public class RouteTest { - - private Route route; - - @Before - public void setUp() throws Exception { - ModelNode root = new ModelNode(); - JBossDmrExtentions.set(root, JBossDmrExtentions.getPath(ResourcePropertyKeys.KIND), ResourceKind.ROUTE); - route = spy(new Route(root, null, null)); - doReturn("www.host.com").when(route).getHost(); - doReturn("/abc").when(route).getPath(); - } - - @Test - public void getURLShouldBeSecureWhenTLSConfigExists() { - doReturn(mock(ITLSConfig.class)).when(route).getTLSConfig(); - assertEquals("https://www.host.com/abc", route.getURL()); - } - - @Test - public void getURLShouldBeInSecureWhenTLSConfigDoesExists() { - doReturn(null).when(route).getTLSConfig(); - assertEquals("http://www.host.com/abc", route.getURL()); - } + + private Route route; + + @Before + public void setUp() throws Exception { + ModelNode root = new ModelNode(); + JBossDmrExtentions.set(root, JBossDmrExtentions.getPath(ResourcePropertyKeys.KIND), ResourceKind.ROUTE); + route = spy(new Route(root, null, null)); + doReturn("www.host.com").when(route).getHost(); + doReturn("/abc").when(route).getPath(); + } + + @Test + public void getURLShouldBeSecureWhenTLSConfigExists() { + doReturn(mock(ITLSConfig.class)).when(route).getTLSConfig(); + assertEquals("https://www.host.com/abc", route.getURL()); + } + + @Test + public void getURLShouldBeInSecureWhenTLSConfigDoesExists() { + doReturn(null).when(route).getTLSConfig(); + assertEquals("http://www.host.com/abc", route.getURL()); + } + + @Test + public void getAndSetInsecureEdgeTerminationPolicy() { + ModelNode modelNode = new ModelNode(); + Route edgeTLSRoute = spy(new Route(modelNode, null, null)); + edgeTLSRoute.createTLSConfig().setTerminationType("edge"); + + edgeTLSRoute.getTLSConfig().setInsecureEdgeTerminationPolicy("Allow"); + assertEquals("Allow", edgeTLSRoute.getTLSConfig().getInsecureEdgeTerminationPolicy()); + } } diff --git a/src/test/java/com/openshift/internal/restclient/model/ServiceTest.java b/src/test/java/com/openshift/internal/restclient/model/ServiceTest.java index ca705c77..01496e5e 100644 --- a/src/test/java/com/openshift/internal/restclient/model/ServiceTest.java +++ b/src/test/java/com/openshift/internal/restclient/model/ServiceTest.java @@ -1,15 +1,22 @@ /******************************************************************************* - * Copyright (c) 2015 Red Hat, Inc. Distributed under license by Red Hat, Inc. + * Copyright (c) 2015-2019 Red Hat, Inc. Distributed under license by Red Hat, Inc. * All rights reserved. This program is made available under the terms of the * Eclipse Public License v1.0 which accompanies this distribution, and is * available at http://www.eclipse.org/legal/epl-v10.html * * Contributors: Red Hat, Inc. ******************************************************************************/ + package com.openshift.internal.restclient.model; -import static org.mockito.Mockito.*; -import static org.junit.Assert.*; +import static org.junit.Assert.assertEquals; +import static org.mockito.ArgumentMatchers.anyMap; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; import java.util.ArrayList; import java.util.List; @@ -20,57 +27,79 @@ import com.openshift.internal.restclient.OpenShiftAPIVersion; import com.openshift.internal.restclient.ResourceFactory; +import com.openshift.restclient.IApiTypeMapper; +import com.openshift.restclient.IApiTypeMapper.IVersionedType; import com.openshift.restclient.IClient; import com.openshift.restclient.IResourceFactory; import com.openshift.restclient.ResourceKind; -import com.openshift.restclient.model.IPod; +import com.openshift.restclient.model.IResource; import com.openshift.restclient.model.IService; import com.openshift.restclient.model.IServicePort; -/** - * @author Jeff Cantrill - */ public class ServiceTest { - private IService service; - private IClient client; + private IService service; + private IClient client; + private IApiTypeMapper mapper; + + @Before + public void setup() { + client = mock(IClient.class); + mapper = mock(IApiTypeMapper.class); + when(client.getOpenShiftAPIVersion()).thenReturn(OpenShiftAPIVersion.v1.name()); + when(client.adapt(IApiTypeMapper.class)).thenReturn(mapper); + when(mapper.getType(anyString(), eq(ResourceKind.SERVICE))).thenReturn(new IVersionedType() { + + @Override + public String getVersion() { + return "v1"; + } + + @Override + public String getPrefix() { + return null; + } + + @Override + public String getKind() { + return ResourceKind.SERVICE; + } + + @Override + public String getApiGroupName() { + return null; + } + }); + IResourceFactory factory = new ResourceFactory(client); + service = factory.stub(ResourceKind.SERVICE, OpenShiftAPIVersion.v1.name()); + } + + @Test + public void testSetPorts() { + ServicePort port = new ServicePort(new ModelNode()); + port.setName("foo"); + port.setTargetPort(12345); + port.setProtocol("tcp"); + List ports = new ArrayList<>(); + ports.add(port); + service.setPorts(ports); + assertEquals(1, service.getPorts().size()); + assertEquals("foo", service.getPorts().get(0).getName()); + } + + @Test + public void testGetPods() { + // setup + when(client.list(anyString(), anyString(), anyMap())).thenReturn(new ArrayList()); + + service.addLabel("bar", "foo"); + service.setSelector("foo", "bar"); + + // exectute + service.getPods(); - @Before - public void setup() { - client = mock(IClient.class); - when(client.getOpenShiftAPIVersion()).thenReturn(OpenShiftAPIVersion.v1.name()); - IResourceFactory factory = new ResourceFactory(client){}; - service = factory.stub(ResourceKind.SERVICE, OpenShiftAPIVersion.v1.name()); - } - - @Test - public void testSetPorts() { - List ports = new ArrayList<>(); - ServicePort port = new ServicePort(new ModelNode()); - port.setName("foo"); - port.setTargetPort(12345); - port.setProtocol("tcp"); - ports.add(port); - service.setPorts(ports); - assertEquals(1,service.getPorts().size()); - assertEquals("foo", service.getPorts().get(0).getName()); - } - - @SuppressWarnings("unchecked") - @Test - public void testGetPods() { - //setup - when(client.list(anyString(), anyString(), anyMap())) - .thenReturn(new ArrayList()); - - service.addLabel("bar","foo"); - service.setSelector("foo", "bar"); - - //exectute - service.getPods(); - - //confirm called with selector and not something else - verify(client, times(1)).list(eq(ResourceKind.POD), anyString(), eq(service.getSelector())); - } + // confirm called with selector and not something else + verify(client, times(1)).list(eq(ResourceKind.POD), anyString(), eq(service.getSelector())); + } } diff --git a/src/test/java/com/openshift/internal/restclient/model/StatusTest.java b/src/test/java/com/openshift/internal/restclient/model/StatusTest.java index c874c66e..91303ff5 100644 --- a/src/test/java/com/openshift/internal/restclient/model/StatusTest.java +++ b/src/test/java/com/openshift/internal/restclient/model/StatusTest.java @@ -6,10 +6,13 @@ * * Contributors: Red Hat, Inc. - initial API and implementation ******************************************************************************/ + package com.openshift.internal.restclient.model; -import static org.junit.Assert.*; -import static org.mockito.Mockito.*; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; +import static org.mockito.Mockito.doReturn; +import static org.mockito.Mockito.spy; import org.jboss.dmr.ModelNode; import org.junit.Before; @@ -21,31 +24,30 @@ /** * Tests that have logic and not specific to a particular api version - * @author Jeff Cantrill * */ public class StatusTest { - private Status status; - - @Before - public void setup() { - ModelNode root = new ModelNode(); - JBossDmrExtentions.set(root, JBossDmrExtentions.getPath(ResourcePropertyKeys.KIND), ResourceKind.STATUS); - status = spy(new Status(root,null,null)); - } - - @Test - public void isFailureShouldReturnTrueWhenFailure() { - doReturn("Failure").when(status).getStatus(); - - assertTrue(status.isFailure()); - } - - @Test - public void isFailureShouldReturnFalseWhenNotFailure() { - doReturn("Other").when(status).getStatus(); - - assertFalse(status.isFailure()); - } + private Status status; + + @Before + public void setup() { + ModelNode root = new ModelNode(); + JBossDmrExtentions.set(root, JBossDmrExtentions.getPath(ResourcePropertyKeys.KIND), ResourceKind.STATUS); + status = spy(new Status(root, null, null)); + } + + @Test + public void isFailureShouldReturnTrueWhenFailure() { + doReturn("Failure").when(status).getStatus(); + + assertTrue(status.isFailure()); + } + + @Test + public void isFailureShouldReturnFalseWhenNotFailure() { + doReturn("Other").when(status).getStatus(); + + assertFalse(status.isFailure()); + } } diff --git a/src/test/java/com/openshift/internal/restclient/model/authorization/RoleBindingTest.java b/src/test/java/com/openshift/internal/restclient/model/authorization/RoleBindingTest.java new file mode 100644 index 00000000..8ae22562 --- /dev/null +++ b/src/test/java/com/openshift/internal/restclient/model/authorization/RoleBindingTest.java @@ -0,0 +1,85 @@ +/******************************************************************************* + * Copyright (c) 2020 Red Hat, Inc. + * Distributed under license by Red Hat, Inc. All rights reserved. + * This program is made available under the terms of the + * Eclipse Public License v2.0 which accompanies this distribution, + * and is available at http://www.eclipse.org/legal/epl-v20.html + * + * Contributors: + * Red Hat, Inc. - initial API and implementation + ******************************************************************************/ + +package com.openshift.internal.restclient.model.authorization; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; + +import java.util.List; + +import org.junit.Test; + +import com.openshift.internal.restclient.TypeMapperFixture; +import com.openshift.restclient.ResourceKind; +import com.openshift.restclient.utils.Samples; + +/** + * @author Red Hat Developers + * + */ +public class RoleBindingTest extends TypeMapperFixture { + + private static final String RBAC_OCP4_GROUP = "{\"kind\":\"APIGroupList\",\"apiVersion\":\"v1\",\"groups\":[{\"name\":\"rbac.authorization.k8s.io\",\"versions\":" + + "[{\"groupVersion\":\"rbac.authorization.k8s.io/v1\",\"version\":\"v1\"},{\"groupVersion\":\"rbac.authorization.k8s.io/v1beta1\",\"version\":\"v1beta1\"}]," + + "\"preferredVersion\":{\"groupVersion\":\"rbac.authorization.k8s.io/v1\",\"version\":\"v1\"}}]}"; + + private static final String RBAC_OCP4_RESOURCE = "{\"kind\":\"APIResourceList\",\"apiVersion\":\"v1\",\"groupVersion\":\"rbac.authorization.k8s.io/v1\",\"resources\"" + + ":[{\"name\":\"clusterrolebindings\",\"singularName\":\"\",\"namespaced\":false,\"kind\":\"ClusterRoleBinding\",\"verbs\":[\"create\",\"delete\"," + + "\"deletecollection\",\"get\",\"list\",\"patch\",\"update\",\"watch\"],\"storageVersionHash\":\"48tpQ8gZHFc=\"},{\"name\":\"clusterroles\",\"singularName\":" + + "\"\",\"namespaced\":false,\"kind\":\"ClusterRole\",\"verbs\":[\"create\",\"delete\",\"deletecollection\",\"get\",\"list\",\"patch\",\"update\",\"watch\"]," + + "\"storageVersionHash\":\"bYE5ZWDrJ44=\"},{\"name\":\"rolebindings\",\"singularName\":\"\",\"namespaced\":true,\"kind\":\"RoleBinding\",\"verbs\":[\"create\"," + + "\"delete\",\"deletecollection\",\"get\",\"list\",\"patch\",\"update\",\"watch\"],\"storageVersionHash\":\"eGsCzGH6b1g=\"},{\"name\":\"roles\",\"singularName\":" + + "\"\",\"namespaced\":true,\"kind\":\"Role\",\"verbs\":[\"create\",\"delete\",\"deletecollection\",\"get\",\"list\",\"patch\",\"update\",\"watch\"]," + + "\"storageVersionHash\":\"7FuwZcIIItM=\"}]}"; + + private static final String RBAC_OCP3_GROUP = "{\"kind\":\"APIGroupList\",\"apiVersion\":\"v1\",\"groups\":[{\"name\":\"authorization.openshift.io\",\"versions\":" + + "[{\"groupVersion\":\"authorization.openshift.io/v1\",\"version\":\"v1\"}],\"preferredVersion\":{\"groupVersion\":\"authorization.openshift.io/v1\"," + + "\"version\":\"v1\"}}]}"; + + private static final String RBAC_OCP3_RESOURCE = "{\"kind\":\"APIResourceList\",\"apiVersion\":\"v1\",\"groupVersion\":\"authorization.openshift.io/v1\",\"resources\":" + + "[{\"name\":\"clusterrolebindings\",\"singularName\":\"\",\"namespaced\":false,\"kind\":\"ClusterRoleBinding\",\"verbs\":[\"create\",\"delete\",\"get\",\"list\"," + + "\"patch\",\"update\"]},{\"name\":\"clusterroles\",\"singularName\":\"\",\"namespaced\":false,\"kind\":\"ClusterRole\",\"verbs\":[\"create\",\"delete\",\"get\"," + + "\"list\",\"patch\",\"update\"]},{\"name\":\"localresourceaccessreviews\",\"singularName\":\"\",\"namespaced\":true,\"kind\":\"LocalResourceAccessReview\"," + + "\"verbs\":[\"create\"]},{\"name\":\"localsubjectaccessreviews\",\"singularName\":\"\",\"namespaced\":true,\"kind\":\"LocalSubjectAccessReview\",\"verbs\":" + + "[\"create\"]},{\"name\":\"resourceaccessreviews\",\"singularName\":\"\",\"namespaced\":false,\"kind\":\"ResourceAccessReview\",\"verbs\":[\"create\"]},{\"name\":" + + "\"rolebindingrestrictions\",\"singularName\":\"\",\"namespaced\":true,\"kind\":\"RoleBindingRestriction\",\"verbs\":[\"create\",\"delete\",\"deletecollection\"," + + "\"get\",\"list\",\"patch\",\"update\",\"watch\"]},{\"name\":\"rolebindings\",\"singularName\":\"\",\"namespaced\":true,\"kind\":\"RoleBinding\",\"verbs\":" + + "[\"create\",\"delete\",\"get\",\"list\",\"patch\",\"update\"]},{\"name\":\"roles\",\"singularName\":\"\",\"namespaced\":true,\"kind\":\"Role\",\"verbs\":" + + "[\"create\",\"delete\",\"get\",\"list\",\"patch\",\"update\"]},{\"name\":\"selfsubjectrulesreviews\",\"singularName\":\"\",\"namespaced\":true,\"kind\":" + + "\"SelfSubjectRulesReview\",\"verbs\":[\"create\"]},{\"name\":\"subjectaccessreviews\",\"singularName\":\"\",\"namespaced\":false,\"kind\":" + + "\"SubjectAccessReview\",\"verbs\":[\"create\"]},{\"name\":\"subjectrulesreviews\",\"singularName\":\"\",\"namespaced\":true,\"kind\":\"SubjectRulesReview\"," + + "\"verbs\":[\"create\"]}]}"; + + @Test + public void checkRoleBindingListOCP4() throws Exception { + getHttpClient().whenRequestTo(base + "/oapi", responseOf("")); + getHttpClient().whenRequestTo(base + "/apis", responseOf(RBAC_OCP4_GROUP)); + getHttpClient().whenRequestTo(base + "/apis/rbac.authorization.k8s.io/v1", responseOf(RBAC_OCP4_RESOURCE)); + getHttpClient().whenRequestTo(base + "/apis/rbac.authorization.k8s.io/v1/namespaces/default/rolebindings", + responseOf(Samples.RBAC_AUTHORIZATION_K8S_IO_ROLEBINDINGS.getContentAsString())); + List roleBindings = getIClient().list(ResourceKind.ROLE_BINDING, "default"); + assertFalse(roleBindings.isEmpty()); + assertEquals(RoleBinding.class, roleBindings.get(0).getClass()); + } + + @Test + public void checkRoleBindingListOCP3() throws Exception { + getHttpClient().whenRequestTo(base + "/oapi", responseOf("")); + getHttpClient().whenRequestTo(base + "/apis", responseOf(RBAC_OCP3_GROUP)); + getHttpClient().whenRequestTo(base + "/apis/authorization.openshift.io/v1", responseOf(RBAC_OCP3_RESOURCE)); + getHttpClient().whenRequestTo(base + "/apis/authorization.openshift.io/v1/namespaces/default/rolebindings", + responseOf(Samples.AUTHORIZATION_OPENSHIFT_IO_ROLEBINDINGS.getContentAsString())); + List roleBindings = getIClient().list(ResourceKind.ROLE_BINDING, "default"); + assertFalse(roleBindings.isEmpty()); + assertEquals(RoleBinding.class, roleBindings.get(0).getClass()); + } +} diff --git a/src/test/java/com/openshift/internal/restclient/model/build/BuildConfigBuilderTest.java b/src/test/java/com/openshift/internal/restclient/model/build/BuildConfigBuilderTest.java index c82ed291..ea5f8a4f 100644 --- a/src/test/java/com/openshift/internal/restclient/model/build/BuildConfigBuilderTest.java +++ b/src/test/java/com/openshift/internal/restclient/model/build/BuildConfigBuilderTest.java @@ -8,10 +8,14 @@ * Contributors: * Red Hat, Inc. - initial API and implementation ******************************************************************************/ + package com.openshift.internal.restclient.model.build; -import static org.junit.Assert.*; -import static org.mockito.Mockito.*; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.when; import java.util.Arrays; import java.util.Collections; @@ -23,7 +27,7 @@ import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; -import org.mockito.runners.MockitoJUnitRunner; +import org.mockito.junit.MockitoJUnitRunner; import com.openshift.internal.restclient.model.BuildConfig; import com.openshift.restclient.IClient; @@ -41,61 +45,53 @@ public class BuildConfigBuilderTest { - @Mock private IClient client; - @Mock private IResourceFactory factory; - private IBuildConfig bc; - private BuildConfig bcImpl; - @Before - public void setUp() throws Exception { - bcImpl = new BuildConfig(new ModelNode(), client, Collections.emptyMap()); - when(client.getResourceFactory()).thenReturn(factory); - when(factory.stub(eq(ResourceKind.BUILD_CONFIG), anyString(), anyString())).thenReturn(bcImpl); - - } + @Mock + private IClient client; + @Mock + private IResourceFactory factory; + private IBuildConfig bc; + private BuildConfig bcImpl; + + @Before + public void setUp() throws Exception { + bcImpl = new BuildConfig(new ModelNode(), client, Collections.emptyMap()); + when(client.getResourceFactory()).thenReturn(factory); + when(factory.stub(eq(ResourceKind.BUILD_CONFIG), anyString(), anyString())).thenReturn(bcImpl); + + } + + @Test + public void testBuild() { + bc = new BuildConfigBuilder(client).named("foo").inNamespace("aNamespace").buildOnConfigChange(true) + .buildOnImageChange(true).buildOnSourceChange(true).fromGitSource() + .fromGitUrl("https://foo/bar/repo.git").usingGitReference("branch").inContextDir("root/directory").end() + .usingSourceStrategy().fromImageStreamTag("builder:latest").inNamespace("other").end() + .toImageStreamTag("foo/target:latest").build(); + + List triggerTypes = Arrays.asList(BuildTriggerType.CONFIG_CHANGE, BuildTriggerType.GENERIC, + BuildTriggerType.GITHUB, BuildTriggerType.IMAGE_CHANGE); + List triggers = bc.getBuildTriggers(); + assertEquals("Exp. all the allowable triggers", triggerTypes.size(), triggers.size()); + triggers.stream() + .forEach(t -> assertTrue(String.format("%s is not in expected types %s", t.getType(), triggerTypes), + triggerTypes.contains(t.getType()))); + triggers.stream().filter( + t -> t.getType().equals(BuildTriggerType.GENERIC) || t.getType().equals(BuildTriggerType.GITHUB)) + .forEach(t -> assertTrue("Exp. the secret to not be blank", + StringUtils.isNotBlank(((IWebhookTrigger) t).getSecret()))); + IGitBuildSource source = bc.getBuildSource(); + assertEquals("https://foo/bar/repo.git", source.getURI()); + assertEquals("branch", source.getRef()); + assertEquals("root/directory", source.getContextDir()); + + ISourceBuildStrategy strategy = bc.getBuildStrategy(); + assertEquals("builder:latest", strategy.getImage().toString()); + assertEquals("other", strategy.getFromNamespace()); - @Test - public void testBuild() { - bc = new BuildConfigBuilder(client) - .named("foo") - .inNamespace("aNamespace") - .buildOnConfigChange(true) - .buildOnImageChange(true) - .buildOnSourceChange(true) - .fromGitSource() - .fromGitUrl("https://foo/bar/repo.git") - .usingGitReference("branch") - .inContextDir("root/directory") - .end() - .usingSourceStrategy() - .fromImageStreamTag("builder:latest") - .inNamespace("other") - .end() - .toImageStreamTag("target:latest") - .build(); - - List triggerTypes = Arrays.asList(BuildTriggerType.CONFIG_CHANGE, - BuildTriggerType.GENERIC, - BuildTriggerType.GITHUB, - BuildTriggerType.IMAGE_CHANGE); - List triggers = bc.getBuildTriggers(); - assertEquals("Exp. all the allowable triggers", triggerTypes.size(), triggers.size()); - triggers.stream() - .forEach(t->assertTrue(String.format("%s is not in expected types %s", t.getType(), triggerTypes), triggerTypes.contains(t.getType()))); - triggers.stream() - .filter(t->t.getType().equals(BuildTriggerType.GENERIC) || t.getType().equals(BuildTriggerType.GITHUB)) - .forEach(t->assertTrue("Exp. the secret to not be blank", StringUtils.isNotBlank(((IWebhookTrigger)t).getSecret()))); - IGitBuildSource source = bc.getBuildSource(); - assertEquals("https://foo/bar/repo.git", source.getURI()); - assertEquals("branch", source.getRef()); - assertEquals("root/directory", source.getContextDir()); - - ISourceBuildStrategy strategy = bc.getBuildStrategy(); - assertEquals("builder:latest", strategy.getImage().toString()); - assertEquals("other", strategy.getFromNamespace()); - - IObjectReference out = bc.getBuildOutputReference(); - assertEquals(ResourceKind.IMAGE_STREAM_TAG, out.getKind()); - assertEquals("target:latest", out.getName()); - } + IObjectReference out = bc.getBuildOutputReference(); + assertEquals(ResourceKind.IMAGE_STREAM_TAG, out.getKind()); + assertEquals("target:latest", out.getName()); + assertEquals("foo", out.getNamespace()); + } } diff --git a/src/test/java/com/openshift/internal/restclient/model/build/BuildConfigTest.java b/src/test/java/com/openshift/internal/restclient/model/build/BuildConfigTest.java index 3c476702..a8023136 100644 --- a/src/test/java/com/openshift/internal/restclient/model/build/BuildConfigTest.java +++ b/src/test/java/com/openshift/internal/restclient/model/build/BuildConfigTest.java @@ -1,15 +1,17 @@ /******************************************************************************* - * Copyright (c) 2015 Red Hat, Inc. Distributed under license by Red Hat, Inc. + * Copyright (c) 2015-2018 Red Hat, Inc. Distributed under license by Red Hat, Inc. * All rights reserved. This program is made available under the terms of the * Eclipse Public License v1.0 which accompanies this distribution, and is * available at http://www.eclipse.org/legal/epl-v10.html * * Contributors: Red Hat, Inc. ******************************************************************************/ + package com.openshift.internal.restclient.model.build; -import static org.junit.Assert.*; -import static com.openshift.internal.util.JBossDmrExtentions.*; +import static com.openshift.internal.util.JBossDmrExtentions.getPath; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; import org.jboss.dmr.ModelNode; import org.junit.Before; @@ -19,58 +21,70 @@ import com.openshift.internal.restclient.model.BuildConfig; import com.openshift.restclient.IClient; import com.openshift.restclient.images.DockerImageURI; +import com.openshift.restclient.model.build.BuildSourceType; import com.openshift.restclient.model.build.BuildStrategyType; +import com.openshift.restclient.model.build.IBinaryBuildSource; +import com.openshift.restclient.model.build.IBuildSource; import com.openshift.restclient.model.build.IBuildStrategy; import com.openshift.restclient.model.build.ICustomBuildStrategy; import com.openshift.restclient.model.build.IDockerBuildStrategy; -/** - * @author Jeff Cantrill - */ public class BuildConfigTest { - @Mock private IClient client; - private BuildConfig config; - private ModelNode node = new ModelNode(); - - @Before - public void setup(){ - config = new BuildConfig(node, client, null); - } - - @Test - public void testGetCustomBuildStrategy(){ - String[] key = new String[]{"spec", "strategy"}; - node.get(key).get("type").set("Custom"); - node.get(key).get("customStrategy").get("exposeDockerSocket").set(true); - node.get(key).get("customStrategy").get("image").set("thebaseImage"); - ModelNode env = new ModelNode(); - env.get("name").set("foo"); - env.get("value").set("bar"); - node.get(key).get("customStrategy").get("env").add(env); - - IBuildStrategy strategy = config.getBuildStrategy(); - assertEquals(BuildStrategyType.CUSTOM, strategy.getType()); - ICustomBuildStrategy custom = (ICustomBuildStrategy) strategy; - assertEquals(new DockerImageURI("thebaseImage"), custom.getImage()); - assertTrue(custom.exposeDockerSocket()); - assertEquals(1, custom.getEnvironmentVariables().size()); - assertTrue("Exp. to find the environment variable", custom.getEnvironmentVariables().containsKey("foo")); - assertEquals("bar", custom.getEnvironmentVariables().get("foo")); - } - - @Test - public void testGetDockerBuildStrategy() { - node.get(getPath(BuildConfig.BUILDCONFIG_TYPE)).set("Docker"); - node.get(getPath(BuildConfig.BUILDCONFIG_DOCKER_CONTEXTDIR)).set("aContextDir"); - node.get(getPath(BuildConfig.BUILDCONFIG_DOCKER_NOCACHE)).set(true); - node.get(getPath(BuildConfig.BUILDCONFIG_DOCKER_BASEIMAGE)).set("thebaseImage"); - - IBuildStrategy strategy = config.getBuildStrategy(); - assertEquals(BuildStrategyType.DOCKER, strategy.getType()); - IDockerBuildStrategy docker = (IDockerBuildStrategy) strategy; - assertEquals("aContextDir", docker.getContextDir()); - assertTrue(docker.isNoCache()); - assertEquals(new DockerImageURI("thebaseImage"), docker.getBaseImage()); - } + @Mock + private IClient client; + private BuildConfig config; + private ModelNode node = new ModelNode(); + + @Before + public void setup() { + config = new BuildConfig(node, client, null); + } + + @Test + public void testGetCustomBuildStrategy() { + String[] key = new String[] { "spec", "strategy" }; + node.get(key).get("type").set("Custom"); + node.get(key).get("customStrategy").get("exposeDockerSocket").set(true); + node.get(key).get("customStrategy").get("image").set("thebaseImage"); + ModelNode env = new ModelNode(); + env.get("name").set("foo"); + env.get("value").set("bar"); + node.get(key).get("customStrategy").get("env").add(env); + + IBuildStrategy strategy = config.getBuildStrategy(); + assertEquals(BuildStrategyType.CUSTOM, strategy.getType()); + ICustomBuildStrategy custom = (ICustomBuildStrategy) strategy; + assertEquals(new DockerImageURI("thebaseImage"), custom.getImage()); + assertTrue(custom.exposeDockerSocket()); + assertEquals(1, custom.getEnvironmentVariables().size()); + assertTrue("Exp. to find the environment variable", custom.getEnvironmentVariables().containsKey("foo")); + assertEquals("bar", custom.getEnvironmentVariables().get("foo")); + } + + @Test + public void testGetDockerBuildStrategy() { + node.get(getPath(BuildConfig.BUILDCONFIG_TYPE)).set("Docker"); + node.get(getPath(BuildConfig.BUILDCONFIG_DOCKER_CONTEXTDIR)).set("aContextDir"); + node.get(getPath(BuildConfig.BUILDCONFIG_DOCKER_NOCACHE)).set(true); + node.get(getPath(BuildConfig.BUILDCONFIG_DOCKER_BASEIMAGE)).set("thebaseImage"); + + IBuildStrategy strategy = config.getBuildStrategy(); + assertEquals(BuildStrategyType.DOCKER, strategy.getType()); + IDockerBuildStrategy docker = (IDockerBuildStrategy) strategy; + assertEquals("aContextDir", docker.getContextDir()); + assertTrue(docker.isNoCache()); + assertEquals(new DockerImageURI("thebaseImage"), docker.getBaseImage()); + } + + @Test + public void testGetBinaryBuildSource() { + node.get(getPath(BuildConfig.BUILDCONFIG_SOURCE_TYPE)).set("Binary"); + node.get(getPath(BuildConfig.BUILDCONFIG_SOURCE_CONTEXTDIR)).set("aContextDir"); + + IBuildSource source = config.getBuildSource(); + assertEquals(BuildSourceType.BINARY, source.getType()); + IBinaryBuildSource binary = (IBinaryBuildSource) source; + assertEquals("aContextDir", binary.getContextDir()); + } } diff --git a/src/test/java/com/openshift/internal/restclient/model/build/BuildRequestTest.java b/src/test/java/com/openshift/internal/restclient/model/build/BuildRequestTest.java new file mode 100644 index 00000000..04e8af47 --- /dev/null +++ b/src/test/java/com/openshift/internal/restclient/model/build/BuildRequestTest.java @@ -0,0 +1,54 @@ +/******************************************************************************* + * Copyright (c) 2015 Red Hat, Inc. Distributed under license by Red Hat, Inc. + * All rights reserved. This program is made available under the terms of the + * Eclipse Public License v1.0 which accompanies this distribution, and is + * available at http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: Red Hat, Inc. + ******************************************************************************/ + +package com.openshift.internal.restclient.model.build; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.fail; + +import org.jboss.dmr.ModelNode; +import org.junit.Before; +import org.junit.Test; +import org.mockito.Mock; + +import com.openshift.restclient.IClient; + +public class BuildRequestTest { + @Mock + private IClient client; + private BuildRequest config; + private ModelNode node = new ModelNode(); + + @Before + public void setup() { + config = new BuildRequest(node, client, null); + } + + @Test + public void testBuildRequestEnvVars() { + + config.setEnvironmentVariable("env1", "value1"); + assertEquals(1, node.get("env").asList().size()); + + config.setEnvironmentVariable("env2", "value2"); + assertEquals(2, node.get("env").asList().size()); + + for (ModelNode mn : node.get("env").asList()) { + if (mn.get("name").asString().equals("env1")) { + assertEquals(mn.get("value").asString(), "value1"); + } else if (mn.get("name").asString().equals("env2")) { + assertEquals(mn.get("value").asString(), "value2"); + } else { + fail("Unexpected environment variable: " + mn.toJSONString(false)); + } + } + + } + +} diff --git a/src/test/java/com/openshift/internal/restclient/model/build/WebhookTriggerTest.java b/src/test/java/com/openshift/internal/restclient/model/build/WebhookTriggerTest.java index d2f201c6..4f59d7c6 100644 --- a/src/test/java/com/openshift/internal/restclient/model/build/WebhookTriggerTest.java +++ b/src/test/java/com/openshift/internal/restclient/model/build/WebhookTriggerTest.java @@ -6,36 +6,36 @@ * * Contributors: Red Hat, Inc. ******************************************************************************/ + package com.openshift.internal.restclient.model.build; -import static org.junit.Assert.*; +import static org.junit.Assert.assertEquals; import org.junit.Before; import org.junit.Test; -import com.openshift.internal.restclient.model.build.WebhookTrigger; import com.openshift.restclient.model.build.BuildTriggerType; import com.openshift.restclient.model.build.IWebhookTrigger; -/** - * @author Jeff Cantrill - */ public class WebhookTriggerTest { - private IWebhookTrigger trigger; - - @Before - public void setup(){ - } - @Test - public void testGetWebhookUrlWhenResourceHasBaseURL() { - trigger = new WebhookTrigger(BuildTriggerType.GENERIC, "seCRet101","https://localhost:8443/oapi/v1/namespaces/test/buildconfigs/foo"); - assertEquals("https://localhost:8443/oapi/v1/namespaces/test/buildconfigs/foo/webhooks/seCRet101/generic", trigger.getWebhookURL()); - } - - @Test - public void testGetWebhookUrlWhenResourceDoesNotHaveBaseURL(){ - trigger = new WebhookTrigger(BuildTriggerType.GENERIC, "seCRet101"," "); - assertEquals("",trigger.getWebhookURL()); - } + private IWebhookTrigger trigger; + + @Before + public void setup() { + } + + @Test + public void testGetWebhookUrlWhenResourceHasBaseURL() { + trigger = new WebhookTrigger(BuildTriggerType.GENERIC, "seCRet101", + "https://localhost:8443/oapi/v1/namespaces/test/buildconfigs/foo"); + assertEquals("https://localhost:8443/oapi/v1/namespaces/test/buildconfigs/foo/webhooks/seCRet101/generic", + trigger.getWebhookURL()); + } + + @Test + public void testGetWebhookUrlWhenResourceDoesNotHaveBaseURL() { + trigger = new WebhookTrigger(BuildTriggerType.GENERIC, "seCRet101", " "); + assertEquals("", trigger.getWebhookURL()); + } } diff --git a/src/test/java/com/openshift/internal/restclient/model/deploy/DeployRequestTest.java b/src/test/java/com/openshift/internal/restclient/model/deploy/DeployRequestTest.java new file mode 100644 index 00000000..08b75df1 --- /dev/null +++ b/src/test/java/com/openshift/internal/restclient/model/deploy/DeployRequestTest.java @@ -0,0 +1,47 @@ +/******************************************************************************* + * Copyright (c) 2015 Red Hat, Inc. Distributed under license by Red Hat, Inc. + * All rights reserved. This program is made available under the terms of the + * Eclipse Public License v1.0 which accompanies this distribution, and is + * available at http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: Red Hat, Inc. + ******************************************************************************/ + +package com.openshift.internal.restclient.model.deploy; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; + +import java.util.HashMap; + +import org.jboss.dmr.ModelNode; +import org.junit.Before; +import org.junit.Test; +import org.mockito.Mock; + +import com.openshift.restclient.IClient; + +public class DeployRequestTest { + @Mock + private IClient client; + private DeploymentRequest config; + private ModelNode node = new ModelNode(); + + @Before + public void setup() { + config = new DeploymentRequest(node, new HashMap()); + } + + @Test + public void testDeploymentRequest() { + + config.setForce(true); + assertTrue("Exp. isForce to be true when set to true", config.isForce()); + config.setLatest(true); + assertEquals("Exp. isLatest to be true when set to true", true, config.isLatest()); + config.setName("foo"); + assertEquals("foo", config.getName()); + + } + +} diff --git a/src/test/java/com/openshift/internal/restclient/model/kubeconfig/KubeClientConfigTest.java b/src/test/java/com/openshift/internal/restclient/model/kubeconfig/KubeClientConfigTest.java index 487d90cc..7b882419 100644 --- a/src/test/java/com/openshift/internal/restclient/model/kubeconfig/KubeClientConfigTest.java +++ b/src/test/java/com/openshift/internal/restclient/model/kubeconfig/KubeClientConfigTest.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2016 Red Hat, Inc. + * Copyright (c) 2016-2019 Red Hat, Inc. * Distributed under license by Red Hat, Inc. All rights reserved. * This program is made available under the terms of the * Eclipse Public License v1.0 which accompanies this distribution, @@ -8,15 +8,18 @@ * Contributors: * Red Hat, Inc. - initial API and implementation ******************************************************************************/ + package com.openshift.internal.restclient.model.kubeconfig; -import static org.junit.Assert.*; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; import java.io.StringReader; import org.junit.Before; import org.junit.Test; +import com.openshift.internal.restclient.IntegrationTestHelper; import com.openshift.restclient.model.kubeclient.ICluster; import com.openshift.restclient.model.kubeclient.IContext; import com.openshift.restclient.model.kubeclient.IKubeClientConfig; @@ -26,38 +29,39 @@ public class KubeClientConfigTest { - private IKubeClientConfig config; - @Before - public void setUp() throws Exception { - - String kubeConfig = Samples.V1_KUBE_CONFIG.getContentAsString(); - StringReader reader = new StringReader(kubeConfig); - - KubeClientConfigSerializer serializer = new KubeClientConfigSerializer(); - config = serializer.loadKubeClientConfig(reader); - } - - @Test - public void testDeserialization() { - assertEquals("default/10-3-9-15:8443/jcantril@redhat.com", config.getCurrentContext()); - - assertEquals(2, config.getClusters().size()); - ICluster cluster = config.getClusters().iterator().next(); - assertEquals("10-3-9-15:8443", cluster.getName()); - assertEquals("https://10.3.9.15:8443", cluster.getServer()); - assertEquals("Exp. cluster skipTLSVerify", true, cluster.isInsecureSkipTLSVerify()); - - assertEquals(4, config.getContexts().size()); - IContext context = config.getContexts().iterator().next(); - assertNotNull(context); - assertEquals("default", context.getNamespace()); - assertEquals("10-3-9-15:8443", context.getCluster()); - assertEquals("jcantril@redhat.com/10-3-9-15:8443", context.getUser()); - - assertEquals("Exp. user count", 2, config.getUsers().size()); - IUser user = config.getUsers().iterator().next(); - assertEquals("admin/localhost:8443", user.getName()); - assertEquals("Q6cbJl4yMwP9o7crPbT5XMx9HSuv9W6jgXXE6omHK0Q", user.getToken()); - } + private IKubeClientConfig config; + + @Before + public void setUp() throws Exception { + + String kubeConfig = Samples.V1_KUBE_CONFIG.getContentAsString(); + StringReader reader = new StringReader(kubeConfig); + + KubeClientConfigSerializer serializer = new KubeClientConfigSerializer(); + config = serializer.loadKubeClientConfig(reader); + } + + @Test + public void testDeserialization() { + assertEquals("default/10-3-9-15:8443/jcantril@redhat.com", config.getCurrentContext()); + + assertEquals(2, config.getClusters().size()); + ICluster cluster = config.getClusters().iterator().next(); + assertEquals("10-3-9-15:8443", cluster.getName()); + assertEquals("https://10.3.9.15:8443", cluster.getServer()); + assertEquals("Exp. cluster skipTLSVerify", true, cluster.isInsecureSkipTLSVerify()); + + assertEquals(4, config.getContexts().size()); + IContext context = config.getContexts().iterator().next(); + assertNotNull(context); + assertEquals(IntegrationTestHelper.getDefaultNamespace(), context.getNamespace()); + assertEquals("10-3-9-15:8443", context.getCluster()); + assertEquals("jcantril@redhat.com/10-3-9-15:8443", context.getUser()); + + assertEquals("Exp. user count", 2, config.getUsers().size()); + IUser user = config.getUsers().iterator().next(); + assertEquals("admin/localhost:8443", user.getName()); + assertEquals("Q6cbJl4yMwP9o7crPbT5XMx9HSuv9W6jgXXE6omHK0Q", user.getToken()); + } } diff --git a/src/test/java/com/openshift/internal/restclient/model/properties/ResourcePropertiesRegistryTest.java b/src/test/java/com/openshift/internal/restclient/model/properties/ResourcePropertiesRegistryTest.java index 83950379..e91efcd1 100644 --- a/src/test/java/com/openshift/internal/restclient/model/properties/ResourcePropertiesRegistryTest.java +++ b/src/test/java/com/openshift/internal/restclient/model/properties/ResourcePropertiesRegistryTest.java @@ -8,10 +8,12 @@ * Contributors: * Red Hat, Inc. - initial API and implementation ******************************************************************************/ + package com.openshift.internal.restclient.model.properties; -import static org.junit.Assert.*; -import static org.mockito.Mockito.*; +import static org.junit.Assert.assertEquals; +import static org.mockito.Mockito.spy; +import static org.mockito.Mockito.when; import java.util.Arrays; import java.util.List; @@ -22,60 +24,67 @@ import com.openshift.internal.restclient.KubernetesAPIVersion; import com.openshift.internal.restclient.OpenShiftAPIVersion; -/** - * @author Jeff Cantrill - */ public class ResourcePropertiesRegistryTest { - - private ResourcePropertiesRegistry registry; - - @Before - public void setUp() throws Exception { - registry = spy(ResourcePropertiesRegistry.getInstance()); - } - - @Test - public void theClientShouldUseTheSameVersionWhenTheyAreTheSame() { - List serverVersions = Arrays.asList(new KubernetesAPIVersion[] {KubernetesAPIVersion.v1, KubernetesAPIVersion.v1beta3}); - assertEquals(KubernetesAPIVersion.v1, registry.getMaxSupportedKubernetesVersion(serverVersions)); - } - - @Test - public void theClientShouldUseTheServerVersionWhenTheServerIsBehindTheClient() { - when(registry.getSupportedKubernetesVersions()).thenReturn(new KubernetesAPIVersion [] {KubernetesAPIVersion.v1, KubernetesAPIVersion.v1beta3}); - List serverVersions = Arrays.asList(new KubernetesAPIVersion[] {KubernetesAPIVersion.v1beta3}); - - assertEquals(KubernetesAPIVersion.v1beta3, registry.getMaxSupportedKubernetesVersion(serverVersions)); - } - - @Test - public void theClientShouldUseTheClientVersionVersionWhenTheClientIsBehindTheServer() { - List serverVersions = Arrays.asList(new KubernetesAPIVersion[] {KubernetesAPIVersion.v1, KubernetesAPIVersion.v1beta3}); - when(registry.getSupportedKubernetesVersions()).thenReturn(new KubernetesAPIVersion [] {KubernetesAPIVersion.v1beta3}); - - assertEquals(KubernetesAPIVersion.v1beta3, registry.getMaxSupportedKubernetesVersion(serverVersions)); - } - - @Test - public void theClientShouldUseTheSameOpenShiftAPIVersionWhenTheyAreTheSame() { - List serverVersions = Arrays.asList(new OpenShiftAPIVersion[] {OpenShiftAPIVersion.v1, OpenShiftAPIVersion.v1beta3}); - assertEquals(OpenShiftAPIVersion.v1, registry.getMaxSupportedOpenShiftVersion(serverVersions)); - } - - @Test - public void theClientShouldUseTheOpenShiftAPIServerVersionWhenTheServerIsBehindTheClient() { - when(registry.getSupportedOpenShiftVersions()).thenReturn(new OpenShiftAPIVersion [] {OpenShiftAPIVersion.v1, OpenShiftAPIVersion.v1beta3}); - List serverVersions = Arrays.asList(new OpenShiftAPIVersion[] {OpenShiftAPIVersion.v1beta3}); - - assertEquals(OpenShiftAPIVersion.v1beta3, registry.getMaxSupportedOpenShiftVersion(serverVersions)); - } - - @Test - public void theClientShouldUseTheOpenShiftAPIClientVersionVersionWhenTheClientIsBehindTheServer() { - List serverVersions = Arrays.asList(new OpenShiftAPIVersion[] {OpenShiftAPIVersion.v1, OpenShiftAPIVersion.v1beta3}); - when(registry.getSupportedOpenShiftVersions()).thenReturn(new OpenShiftAPIVersion [] {OpenShiftAPIVersion.v1beta3}); - - assertEquals(OpenShiftAPIVersion.v1beta3, registry.getMaxSupportedOpenShiftVersion(serverVersions)); - } + + private ResourcePropertiesRegistry registry; + + @Before + public void setUp() throws Exception { + registry = spy(ResourcePropertiesRegistry.getInstance()); + } + + @Test + public void theClientShouldUseTheSameVersionWhenTheyAreTheSame() { + List serverVersions = Arrays + .asList(new KubernetesAPIVersion[] { KubernetesAPIVersion.v1, KubernetesAPIVersion.v1beta3 }); + assertEquals(KubernetesAPIVersion.v1, registry.getMaxSupportedKubernetesVersion(serverVersions)); + } + + @Test + public void theClientShouldUseTheServerVersionWhenTheServerIsBehindTheClient() { + when(registry.getSupportedKubernetesVersions()) + .thenReturn(new KubernetesAPIVersion[] { KubernetesAPIVersion.v1, KubernetesAPIVersion.v1beta3 }); + List serverVersions = Arrays + .asList(new KubernetesAPIVersion[] { KubernetesAPIVersion.v1beta3 }); + + assertEquals(KubernetesAPIVersion.v1beta3, registry.getMaxSupportedKubernetesVersion(serverVersions)); + } + + @Test + public void theClientShouldUseTheClientVersionVersionWhenTheClientIsBehindTheServer() { + List serverVersions = Arrays + .asList(new KubernetesAPIVersion[] { KubernetesAPIVersion.v1, KubernetesAPIVersion.v1beta3 }); + when(registry.getSupportedKubernetesVersions()) + .thenReturn(new KubernetesAPIVersion[] { KubernetesAPIVersion.v1beta3 }); + + assertEquals(KubernetesAPIVersion.v1beta3, registry.getMaxSupportedKubernetesVersion(serverVersions)); + } + + @Test + public void theClientShouldUseTheSameOpenShiftAPIVersionWhenTheyAreTheSame() { + List serverVersions = Arrays + .asList(new OpenShiftAPIVersion[] { OpenShiftAPIVersion.v1, OpenShiftAPIVersion.v1beta3 }); + assertEquals(OpenShiftAPIVersion.v1, registry.getMaxSupportedOpenShiftVersion(serverVersions)); + } + + @Test + public void theClientShouldUseTheOpenShiftAPIServerVersionWhenTheServerIsBehindTheClient() { + when(registry.getSupportedOpenShiftVersions()) + .thenReturn(new OpenShiftAPIVersion[] { OpenShiftAPIVersion.v1, OpenShiftAPIVersion.v1beta3 }); + List serverVersions = Arrays + .asList(new OpenShiftAPIVersion[] { OpenShiftAPIVersion.v1beta3 }); + + assertEquals(OpenShiftAPIVersion.v1beta3, registry.getMaxSupportedOpenShiftVersion(serverVersions)); + } + + @Test + public void theClientShouldUseTheOpenShiftAPIClientVersionVersionWhenTheClientIsBehindTheServer() { + List serverVersions = Arrays + .asList(new OpenShiftAPIVersion[] { OpenShiftAPIVersion.v1, OpenShiftAPIVersion.v1beta3 }); + when(registry.getSupportedOpenShiftVersions()) + .thenReturn(new OpenShiftAPIVersion[] { OpenShiftAPIVersion.v1beta3 }); + + assertEquals(OpenShiftAPIVersion.v1beta3, registry.getMaxSupportedOpenShiftVersion(serverVersions)); + } } diff --git a/src/test/java/com/openshift/internal/restclient/model/template/ParameterTest.java b/src/test/java/com/openshift/internal/restclient/model/template/ParameterTest.java index e86ce0ff..f39f331b 100644 --- a/src/test/java/com/openshift/internal/restclient/model/template/ParameterTest.java +++ b/src/test/java/com/openshift/internal/restclient/model/template/ParameterTest.java @@ -4,7 +4,7 @@ import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; -import org.fest.assertions.Assertions; +import org.assertj.core.api.Assertions; import org.jboss.dmr.ModelNode; import org.junit.Test; @@ -12,131 +12,132 @@ public class ParameterTest { - private Parameter param = new Parameter(new ModelNode()); - - @Test - public void testGetNameWhenUndefined() { - assertEquals("", param.getValue()); - } - - @Test - public void testGetDescriptionWhenUndefined() { - assertEquals("", param.getDescription()); - } - - @Test - public void testGetFromWhenUndefined() { - assertEquals("", param.getFrom()); - } - - @Test - public void testGetGeneratorNameWhenUndefined() { - assertEquals("", param.getGeneratorName()); - } - - @Test - public void testIsRequiredUndefined() { - assertFalse(param.isRequired()); - } - @Test - public void testIsRequiredFalse() { - ModelNode node = new ModelNode(); - node.get("required").set(false); - param = new Parameter(node); - assertFalse(param.isRequired()); - } - - @Test - public void testIsRequired() { - ModelNode node = new ModelNode(); - node.get("required").set(true); - param = new Parameter(node); - assertTrue(param.isRequired()); - } - - @Test - public void shouldNotEqualsIfFromIsDifferent() { - // pre-requisistes - ModelNode node = new ModelNode(); - node.get("from").set("42"); - IParameter parameter = new Parameter(node); - - ModelNode otherNode = new ModelNode(); - otherNode.get("from").set("84"); - IParameter otherParameter = new Parameter(otherNode); - - // operation - // verification - Assertions.assertThat(parameter).isNotEqualTo(otherParameter); - Assertions.assertThat(otherParameter).isNotEqualTo(parameter); - } - - @Test - public void shouldNotEqualsIfGeneratorNameIsDifferent() { - // pre-requisistes - ModelNode node = new ModelNode(); - node.get("generate").set("42"); - IParameter parameter = new Parameter(node); - - ModelNode otherNode = new ModelNode(); - otherNode.get("generate").set("84"); - IParameter otherParameter = new Parameter(otherNode); - - // operation - // verification - Assertions.assertThat(parameter).isNotEqualTo(otherParameter); - Assertions.assertThat(otherParameter).isNotEqualTo(parameter); - } - - @Test - public void shouldNotEqualsIfNameIsDifferent() { - // pre-requisistes - ModelNode node = new ModelNode(); - node.get("name").set("42"); - IParameter parameter = new Parameter(node); - - ModelNode otherNode = new ModelNode(); - otherNode.get("name").set("84"); - IParameter otherParameter = new Parameter(otherNode); - - // operation - // verification - Assertions.assertThat(parameter).isNotEqualTo(otherParameter); - Assertions.assertThat(otherParameter).isNotEqualTo(parameter); - } - - @Test - public void shouldNotEqualsIfValueIsDifferent() { - // pre-requisistes - ModelNode node = new ModelNode(); - node.get("value").set("42"); - IParameter parameter = new Parameter(node); - - ModelNode otherNode = new ModelNode(); - otherNode.get("value").set("84"); - IParameter otherParameter = new Parameter(otherNode); - - // operation - // verification - Assertions.assertThat(parameter).isNotEqualTo(otherParameter); - Assertions.assertThat(otherParameter).isNotEqualTo(parameter); - } - - @Test - public void shouldNotEqualsIfIsRequiredIsDifferent() { - // pre-requisistes - ModelNode node = new ModelNode(); - node.get("required").set(true); - IParameter parameter = new Parameter(node); - - ModelNode otherNode = new ModelNode(); - otherNode.get("required").set(false); - IParameter otherParameter = new Parameter(otherNode); - - // operation - // verification - Assertions.assertThat(parameter).isNotEqualTo(otherParameter); - Assertions.assertThat(otherParameter).isNotEqualTo(parameter); - } + private Parameter param = new Parameter(new ModelNode()); + + @Test + public void testGetNameWhenUndefined() { + assertEquals("", param.getValue()); + } + + @Test + public void testGetDescriptionWhenUndefined() { + assertEquals("", param.getDescription()); + } + + @Test + public void testGetFromWhenUndefined() { + assertEquals("", param.getFrom()); + } + + @Test + public void testGetGeneratorNameWhenUndefined() { + assertEquals("", param.getGeneratorName()); + } + + @Test + public void testIsRequiredUndefined() { + assertFalse(param.isRequired()); + } + + @Test + public void testIsRequiredFalse() { + ModelNode node = new ModelNode(); + node.get("required").set(false); + param = new Parameter(node); + assertFalse(param.isRequired()); + } + + @Test + public void testIsRequired() { + ModelNode node = new ModelNode(); + node.get("required").set(true); + param = new Parameter(node); + assertTrue(param.isRequired()); + } + + @Test + public void shouldNotEqualsIfFromIsDifferent() { + // pre-requisistes + ModelNode node = new ModelNode(); + node.get("from").set("42"); + IParameter parameter = new Parameter(node); + + ModelNode otherNode = new ModelNode(); + otherNode.get("from").set("84"); + IParameter otherParameter = new Parameter(otherNode); + + // operation + // verification + Assertions.assertThat(parameter).isNotEqualTo(otherParameter); + Assertions.assertThat(otherParameter).isNotEqualTo(parameter); + } + + @Test + public void shouldNotEqualsIfGeneratorNameIsDifferent() { + // pre-requisistes + ModelNode node = new ModelNode(); + node.get("generate").set("42"); + IParameter parameter = new Parameter(node); + + ModelNode otherNode = new ModelNode(); + otherNode.get("generate").set("84"); + IParameter otherParameter = new Parameter(otherNode); + + // operation + // verification + Assertions.assertThat(parameter).isNotEqualTo(otherParameter); + Assertions.assertThat(otherParameter).isNotEqualTo(parameter); + } + + @Test + public void shouldNotEqualsIfNameIsDifferent() { + // pre-requisistes + ModelNode node = new ModelNode(); + node.get("name").set("42"); + IParameter parameter = new Parameter(node); + + ModelNode otherNode = new ModelNode(); + otherNode.get("name").set("84"); + IParameter otherParameter = new Parameter(otherNode); + + // operation + // verification + Assertions.assertThat(parameter).isNotEqualTo(otherParameter); + Assertions.assertThat(otherParameter).isNotEqualTo(parameter); + } + + @Test + public void shouldNotEqualsIfValueIsDifferent() { + // pre-requisistes + ModelNode node = new ModelNode(); + node.get("value").set("42"); + IParameter parameter = new Parameter(node); + + ModelNode otherNode = new ModelNode(); + otherNode.get("value").set("84"); + IParameter otherParameter = new Parameter(otherNode); + + // operation + // verification + Assertions.assertThat(parameter).isNotEqualTo(otherParameter); + Assertions.assertThat(otherParameter).isNotEqualTo(parameter); + } + + @Test + public void shouldNotEqualsIfIsRequiredIsDifferent() { + // pre-requisistes + ModelNode node = new ModelNode(); + node.get("required").set(true); + IParameter parameter = new Parameter(node); + + ModelNode otherNode = new ModelNode(); + otherNode.get("required").set(false); + IParameter otherParameter = new Parameter(otherNode); + + // operation + // verification + Assertions.assertThat(parameter).isNotEqualTo(otherParameter); + Assertions.assertThat(otherParameter).isNotEqualTo(parameter); + } } diff --git a/src/test/java/com/openshift/internal/restclient/model/template/TemplateTest.java b/src/test/java/com/openshift/internal/restclient/model/template/TemplateTest.java index 0c3ccbf4..eff074a0 100644 --- a/src/test/java/com/openshift/internal/restclient/model/template/TemplateTest.java +++ b/src/test/java/com/openshift/internal/restclient/model/template/TemplateTest.java @@ -6,9 +6,12 @@ * * Contributors: Red Hat, Inc. - initial API and implementation ******************************************************************************/ + package com.openshift.internal.restclient.model.template; -import static org.junit.Assert.*; +import static org.junit.Assert.assertArrayEquals; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; import java.util.ArrayList; import java.util.Arrays; @@ -26,71 +29,73 @@ import com.openshift.restclient.model.template.ITemplate; public class TemplateTest { - @Mock private IClient client; - private ITemplate template; - private ModelNode node = new ModelNode(); - @Before - public void setUp() throws Exception { - ModelNode params = node.get("parameters"); - params.add(param("foo","bar")); - params.add(param("abc","xyz")); - params.add(param("123","456")); - template = new Template(node, client, null); - } - - @Test - public void testGetParametersWhenNotDefined() { - template = new Template(new ModelNode(), client, null); - assertNotNull(template.getParameters()); - } - - @Test - public void addObjectLabel() { - final String key = "objectLabelKey"; - final String value = "objectLabelValue"; - template.addObjectLabel(key, value); - Map labels = template.getObjectLabels(); - assertEquals(value, labels.get(key)); - } + @Mock + private IClient client; + private ITemplate template; + private ModelNode node = new ModelNode(); + + @Before + public void setUp() throws Exception { + ModelNode params = node.get("parameters"); + params.add(param("foo", "bar")); + params.add(param("abc", "xyz")); + params.add(param("123", "456")); + template = new Template(node, client, null); + } + + @Test + public void testGetParametersWhenNotDefined() { + template = new Template(new ModelNode(), client, null); + assertNotNull(template.getParameters()); + } + + @Test + public void addObjectLabel() { + final String key = "objectLabelKey"; + final String value = "objectLabelValue"; + template.addObjectLabel(key, value); + Map labels = template.getObjectLabels(); + assertEquals(value, labels.get(key)); + } + + @Test + public void updateParameter() { + template.updateParameter("foo", "newbar"); + List updatedParams = new ArrayList(); + for (IParameter param : template.getParameters().values()) { + updatedParams.add(String.format("%s:%s", param.getName(), param.getValue())); + } + + String[] exp = new String[] { "foo:newbar", "abc:xyz", "123:456" }; + String[] act = updatedParams.toArray(new String[] {}); + Arrays.sort(exp); + Arrays.sort(act); + assertArrayEquals(exp, act); + } + + @Test + public void updateParameters() { + Collection parameters = new ArrayList(); + parameters.add(new Parameter(param("foo", "newbar"))); + parameters.add(new Parameter(param("123", "anewvalue"))); - @Test - public void updateParameter() { - template.updateParameter("foo", "newbar"); - List updatedParams = new ArrayList(); - for (IParameter param : template.getParameters().values()) { - updatedParams.add(String.format("%s:%s", param.getName(), param.getValue())); - } + template.updateParameterValues(parameters); - String [] exp = new String [] {"foo:newbar","abc:xyz","123:456"}; - String [] act = updatedParams.toArray(new String [] {}); - Arrays.sort(exp); - Arrays.sort(act); - assertArrayEquals(exp, act); - } + List updatedParams = new ArrayList(); + for (IParameter param : template.getParameters().values()) { + updatedParams.add(String.format("%s:%s", param.getName(), param.getValue())); + } + String[] exp = new String[] { "foo:newbar", "123:anewvalue", "abc:xyz" }; + String[] act = updatedParams.toArray(new String[] {}); + Arrays.sort(exp); + Arrays.sort(act); + assertArrayEquals(exp, act); + } - @Test - public void updateParameters() { - Collection parameters = new ArrayList(); - parameters.add(new Parameter(param("foo", "newbar"))); - parameters.add(new Parameter(param("123", "anewvalue"))); - - template.updateParameterValues(parameters); - - List updatedParams = new ArrayList(); - for (IParameter param : template.getParameters().values()) { - updatedParams.add(String.format("%s:%s", param.getName(), param.getValue())); - } - String [] exp = new String [] {"foo:newbar", "123:anewvalue","abc:xyz"}; - String [] act = updatedParams.toArray(new String [] {}); - Arrays.sort(exp); - Arrays.sort(act); - assertArrayEquals(exp, act); - } - - private ModelNode param(String name, String value) { - ModelNode node = new ModelNode(); - node.get("name").set(name); - node.get("value").set(value); - return node; - } + private ModelNode param(String name, String value) { + ModelNode node = new ModelNode(); + node.get("name").set(name); + node.get("value").set(value); + return node; + } } diff --git a/src/test/java/com/openshift/internal/restclient/model/v1/BuildConfigTest.java b/src/test/java/com/openshift/internal/restclient/model/v1/BuildConfigTest.java index 593d5efa..fbcebc74 100644 --- a/src/test/java/com/openshift/internal/restclient/model/v1/BuildConfigTest.java +++ b/src/test/java/com/openshift/internal/restclient/model/v1/BuildConfigTest.java @@ -1,16 +1,19 @@ /******************************************************************************* - * Copyright (c) 2015 Red Hat, Inc. Distributed under license by Red Hat, Inc. + * Copyright (c) 2015-2019 Red Hat, Inc. Distributed under license by Red Hat, Inc. * All rights reserved. This program is made available under the terms of the * Eclipse Public License v1.0 which accompanies this distribution, and is * available at http://www.eclipse.org/legal/epl-v10.html * * Contributors: Red Hat, Inc. ******************************************************************************/ + package com.openshift.internal.restclient.model.v1; import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; @@ -30,6 +33,8 @@ import com.openshift.internal.restclient.model.build.ImageChangeTrigger; import com.openshift.internal.restclient.model.build.SourceBuildStrategy; import com.openshift.internal.restclient.model.build.WebhookTrigger; +import com.openshift.restclient.IApiTypeMapper; +import com.openshift.restclient.IApiTypeMapper.IVersionedType; import com.openshift.restclient.IClient; import com.openshift.restclient.ResourceKind; import com.openshift.restclient.images.DockerImageURI; @@ -45,142 +50,161 @@ import com.openshift.restclient.model.build.ISourceBuildStrategy; import com.openshift.restclient.utils.Samples; -/** - * @author Jeff Cantrill - */ public class BuildConfigTest { - - private static final String VERSION = "v1"; - private static IBuildConfig config; - private static IClient client; - - @BeforeClass - public static void setup() throws Exception{ - client = mock(IClient.class); - when(client.getBaseURL()).thenReturn(new URL("https://localhost:8443")); - when(client.getOpenShiftAPIVersion()).thenReturn(VERSION); - ModelNode node = ModelNode.fromJSONString(Samples.V1_BUILD_CONFIG.getContentAsString()); - config = new BuildConfig(node, client, null); - } - - @Test - public void getBuildTriggers(){ - assertBuildTriggers(config.getBuildTriggers().toArray(new IBuildTrigger[]{})); - } - - @Test - public void addBuildTriggers() { - BuildConfig writeConfig = new ResourceFactory(client){}.create(VERSION, ResourceKind.BUILD_CONFIG); - - writeConfig.addBuildTrigger(new WebhookTrigger(BuildTriggerType.GITHUB, "secret101", "https://localhost:8443")); - writeConfig.addBuildTrigger(new WebhookTrigger(BuildTriggerType.GENERIC, "secret101", "https://localhost:8443")); - writeConfig.addBuildTrigger(new ImageChangeTrigger("", "", "")); - - assertBuildTriggers(reCreateBuildConfig(writeConfig).getBuildTriggers().toArray(new IBuildTrigger[]{})); - } - - @Test - public void getOutputRespositoryName(){ - assertEquals("origin-ruby-sample:latest", config.getOutputRepositoryName()); - } - - @Test - public void getSourceURI(){ - assertEquals("git://github.com/openshift/ruby-hello-world.git", config.getSourceURI()); - } - - @Test - public void getGitBuildSource(){ - IBuildSource source = config.getBuildSource(); - assertGitBuildSource(source); - } - - @Test - public void setGitBuildSource() { - BuildConfig writeConfig = new ResourceFactory(client){}.create(VERSION, ResourceKind.BUILD_CONFIG); - - Map env = new HashMap(); - env.put("foo", "bar"); - writeConfig.setBuildSource(new GitBuildSource("git://github.com/openshift/ruby-hello-world.git", "", "foobar")); - - assertGitBuildSource(reCreateBuildConfig(writeConfig).getBuildSource()); - } - - @Test - public void getSourceBuildStrategy() { - IBuildStrategy strategy = config.getBuildStrategy(); - assertSourceBuildStrategy(strategy); - } - - @Test - public void setSourceBuildStrategy() { - BuildConfig writeConfig = new ResourceFactory(client){}.create(VERSION, ResourceKind.BUILD_CONFIG); - - ModelNode node = new ModelNodeBuilder() - .set("type", BuildStrategyType.SOURCE) - .set(SourceBuildStrategy.FROM_IMAGE, "ruby-20-centos7:latest") - .set(SourceBuildStrategy.SCRIPTS, "alocation") - .set(SourceBuildStrategy.INCREMENTAL, true) - .add(SourceBuildStrategy.ENV, new ModelNodeBuilder() - .set("name", "foo") - .set("value", "bar")) - .build(); - - writeConfig.setBuildStrategy(new SourceBuildStrategy(node, new HashMap<>())); - - assertSourceBuildStrategy(reCreateBuildConfig(writeConfig).getBuildStrategy()); - } - - private void assertBuildTriggers(IBuildTrigger[] triggers) { - IBuildTrigger [] exp = new IBuildTrigger[]{ - new WebhookTrigger(BuildTriggerType.GITHUB, "secret101","https://localhost:8443"), - new WebhookTrigger(BuildTriggerType.GENERIC, "secret101","https://localhost:8443"), - new ImageChangeTrigger("", "", "") - }; - assertArrayEquals(exp, triggers); - } - - private void assertGitBuildSource(IBuildSource source) { - assertEquals(BuildSourceType.GIT, source.getType()); - assertEquals("git://github.com/openshift/ruby-hello-world.git", source.getURI()); - assertEquals("foobar", source.getContextDir()); - assertTrue(source instanceof IGitBuildSource); - - IGitBuildSource git = (IGitBuildSource)source; - assertEquals("Exp. to get the source ref","", git.getRef()); - } - - private void assertSourceBuildStrategy(IBuildStrategy strategy) { - assertEquals(BuildStrategyType.SOURCE, strategy.getType()); - assertTrue(strategy instanceof ISourceBuildStrategy); - - ISourceBuildStrategy source = (ISourceBuildStrategy)strategy; - assertEquals(new DockerImageURI("ruby-20-centos7:latest"), source.getImage()); - assertEquals("alocation", source.getScriptsLocation()); - assertEquals(true, source.incremental()); - - Map envVars = source.getEnvironmentVariables(); - assertEquals(1, envVars.size()); - assertTrue("Exp. to find the environment variable",envVars.containsKey("foo")); - assertEquals("bar",envVars.get("foo")); - - envVars.put("newKey", "newValue"); - source.setEnvironmentVariables(envVars); - envVars = source.getEnvironmentVariables(); - assertEquals(2, envVars.size()); - assertTrue("Exp. to find the environment variable",envVars.containsKey("newKey")); - assertEquals("newValue",envVars.get("newKey")); - - Collection vars = source.getEnvVars(); - assertTrue(vars.stream().filter(e->"newKey".equals(e.getName())).findFirst().isPresent()); - - vars.remove(vars.toArray()[0]); - source.setEnvVars(vars); - vars = source.getEnvVars(); - assertEquals(1, vars.size()); - } - - private BuildConfig reCreateBuildConfig(BuildConfig config) { - return new BuildConfig(config.getNode(), client, null); - } + + private static final String VERSION = "v1"; + private static IBuildConfig config; + private static IClient client; + + @BeforeClass + public static void setup() throws Exception { + client = mock(IClient.class); + IApiTypeMapper mapper = mock(IApiTypeMapper.class); + when(client.adapt(IApiTypeMapper.class)).thenReturn(mapper); + when(mapper.getType(anyString(), eq(ResourceKind.PVC))).thenReturn(new IVersionedType() { + + @Override + public String getVersion() { + return "v1"; + } + + @Override + public String getPrefix() { + return null; + } + + @Override + public String getKind() { + return ResourceKind.BUILD_CONFIG; + } + + @Override + public String getApiGroupName() { + return null; + } + }); + when(client.getBaseURL()).thenReturn(new URL("https://localhost:8443")); + when(client.getOpenShiftAPIVersion()).thenReturn(VERSION); + ModelNode node = ModelNode.fromJSONString(Samples.V1_BUILD_CONFIG.getContentAsString()); + config = new BuildConfig(node, client, null); + } + + @Test + public void getBuildTriggers() { + assertBuildTriggers(config.getBuildTriggers().toArray(new IBuildTrigger[] {})); + } + + @Test + public void addBuildTriggers() { + BuildConfig writeConfig = new ResourceFactory(client) { + }.create(VERSION, ResourceKind.BUILD_CONFIG); + + writeConfig.addBuildTrigger(new WebhookTrigger(BuildTriggerType.GITHUB, "secret101", "https://localhost:8443")); + writeConfig + .addBuildTrigger(new WebhookTrigger(BuildTriggerType.GENERIC, "secret101", "https://localhost:8443")); + writeConfig.addBuildTrigger(new ImageChangeTrigger("", "", "")); + + assertBuildTriggers(reCreateBuildConfig(writeConfig).getBuildTriggers().toArray(new IBuildTrigger[] {})); + } + + @Test + public void getOutputRespositoryName() { + assertEquals("origin-ruby-sample:latest", config.getOutputRepositoryName()); + } + + @Test + public void getSourceURI() { + assertEquals("git://github.com/openshift/ruby-hello-world.git", config.getSourceURI()); + } + + @Test + public void getGitBuildSource() { + IBuildSource source = config.getBuildSource(); + assertGitBuildSource(source); + } + + @Test + public void setGitBuildSource() { + BuildConfig writeConfig = new ResourceFactory(client) { + }.create(VERSION, ResourceKind.BUILD_CONFIG); + + Map env = new HashMap(); + env.put("foo", "bar"); + writeConfig.setBuildSource(new GitBuildSource("git://github.com/openshift/ruby-hello-world.git", "", "foobar")); + + assertGitBuildSource(reCreateBuildConfig(writeConfig).getBuildSource()); + } + + @Test + public void getSourceBuildStrategy() { + IBuildStrategy strategy = config.getBuildStrategy(); + assertSourceBuildStrategy(strategy); + } + + @Test + public void setSourceBuildStrategy() { + BuildConfig writeConfig = new ResourceFactory(client) { + }.create(VERSION, ResourceKind.BUILD_CONFIG); + + ModelNode node = new ModelNodeBuilder().set("type", BuildStrategyType.SOURCE) + .set(SourceBuildStrategy.FROM_IMAGE, "ruby-20-centos7:latest") + .set(SourceBuildStrategy.SCRIPTS, "alocation").set(SourceBuildStrategy.INCREMENTAL, true) + .add(SourceBuildStrategy.ENV, new ModelNodeBuilder().set("name", "foo").set("value", "bar")).build(); + + writeConfig.setBuildStrategy(new SourceBuildStrategy(node, new HashMap<>())); + + assertSourceBuildStrategy(reCreateBuildConfig(writeConfig).getBuildStrategy()); + } + + private void assertBuildTriggers(IBuildTrigger[] triggers) { + IBuildTrigger[] exp = new IBuildTrigger[] { + new WebhookTrigger(BuildTriggerType.GITHUB, "secret101", "https://localhost:8443"), + new WebhookTrigger(BuildTriggerType.GENERIC, "secret101", "https://localhost:8443"), + new ImageChangeTrigger("", "", "") }; + assertArrayEquals(exp, triggers); + } + + private void assertGitBuildSource(IBuildSource source) { + assertEquals(BuildSourceType.GIT, source.getType()); + assertEquals("foobar", source.getContextDir()); + assertTrue(source instanceof IGitBuildSource); + + IGitBuildSource git = (IGitBuildSource) source; + assertEquals("Exp. to get the source ref", "", git.getRef()); + assertEquals("git://github.com/openshift/ruby-hello-world.git", git.getURI()); + } + + private void assertSourceBuildStrategy(IBuildStrategy strategy) { + assertEquals(BuildStrategyType.SOURCE, strategy.getType()); + assertTrue(strategy instanceof ISourceBuildStrategy); + + ISourceBuildStrategy source = (ISourceBuildStrategy) strategy; + assertEquals(new DockerImageURI("ruby-20-centos7:latest"), source.getImage()); + assertEquals("alocation", source.getScriptsLocation()); + assertEquals(true, source.incremental()); + + Map envVars = source.getEnvironmentVariables(); + assertEquals(1, envVars.size()); + assertTrue("Exp. to find the environment variable", envVars.containsKey("foo")); + assertEquals("bar", envVars.get("foo")); + + envVars.put("newKey", "newValue"); + source.setEnvironmentVariables(envVars); + envVars = source.getEnvironmentVariables(); + assertEquals(2, envVars.size()); + assertTrue("Exp. to find the environment variable", envVars.containsKey("newKey")); + assertEquals("newValue", envVars.get("newKey")); + + Collection vars = source.getEnvVars(); + assertTrue(vars.stream().filter(e -> "newKey".equals(e.getName())).findFirst().isPresent()); + + vars.remove(vars.toArray()[0]); + source.setEnvVars(vars); + vars = source.getEnvVars(); + assertEquals(1, vars.size()); + } + + private BuildConfig reCreateBuildConfig(BuildConfig config) { + return new BuildConfig(config.getNode(), client, null); + } } diff --git a/src/test/java/com/openshift/internal/restclient/model/v1/BuildTest.java b/src/test/java/com/openshift/internal/restclient/model/v1/BuildTest.java index c1f28777..212de5f9 100644 --- a/src/test/java/com/openshift/internal/restclient/model/v1/BuildTest.java +++ b/src/test/java/com/openshift/internal/restclient/model/v1/BuildTest.java @@ -6,9 +6,11 @@ * * Contributors: Red Hat, Inc. ******************************************************************************/ + package com.openshift.internal.restclient.model.v1; -import static org.junit.Assert.*; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; import static org.mockito.Mockito.mock; import org.jboss.dmr.ModelNode; @@ -23,49 +25,46 @@ import com.openshift.restclient.model.build.IBuildStatus; import com.openshift.restclient.utils.Samples; -/** - * @author Jeff Cantrill - */ public class BuildTest { - - private static final String VERSION = "v1"; - private static IBuild build; - - @BeforeClass - public static void setup(){ - IClient client = mock(IClient.class); - ModelNode node = ModelNode.fromJSONString(Samples.V1_BUILD.getContentAsString()); - build = new Build(node, client, ResourcePropertiesRegistry.getInstance().get(VERSION, ResourceKind.BUILD)); - } - - @Test - public void getStatus(){ - assertEquals("Running", build.getStatus()); - } - @Test - public void getMessage(){ - assertEquals("Some status message", build.getMessage()); - } + private static final String VERSION = "v1"; + private static IBuild build; + + @BeforeClass + public static void setup() { + IClient client = mock(IClient.class); + ModelNode node = ModelNode.fromJSONString(Samples.V1_BUILD.getContentAsString()); + build = new Build(node, client, ResourcePropertiesRegistry.getInstance().get(VERSION, ResourceKind.BUILD)); + } + + @Test + public void getStatus() { + assertEquals("Running", build.getStatus()); + } + + @Test + public void getMessage() { + assertEquals("Some status message", build.getMessage()); + } + + @Test + public void getOutputTo() { + assertEquals("origin-ruby-sample:latest", build.getOutputTo().toString()); + } + + @Test + public void getOutputKind() { + assertEquals("ImageStreamTag", build.getOutputKind()); + } - @Test - public void getOutputTo(){ - assertEquals("origin-ruby-sample:latest", build.getOutputTo().toString()); - } + @Test + public void getBuildStatus() { + IBuildStatus status = build.getBuildStatus(); + assertNotNull(status); + assertEquals("Running", status.getPhase()); + assertEquals("172.30.224.48:5000/rails-demo/rails-demo:latest", status.getOutputDockerImage().toString()); + assertEquals("2015-06-10T20:00:51Z", status.getStartTime()); + assertEquals(76895000000000L, status.getDuration()); + } - @Test - public void getOutputKind(){ - assertEquals("ImageStreamTag", build.getOutputKind()); - } - - @Test - public void getBuildStatus() { - IBuildStatus status = build.getBuildStatus(); - assertNotNull(status); - assertEquals("Running", status.getPhase()); - assertEquals("172.30.224.48:5000/rails-demo/rails-demo:latest", status.getOutputDockerImage().toString()); - assertEquals("2015-06-10T20:00:51Z", status.getStartTime()); - assertEquals(76895000000000L, status.getDuration()); - } - } diff --git a/src/test/java/com/openshift/internal/restclient/model/v1/ConfigMapTest.java b/src/test/java/com/openshift/internal/restclient/model/v1/ConfigMapTest.java index 41484320..7df2d7e1 100644 --- a/src/test/java/com/openshift/internal/restclient/model/v1/ConfigMapTest.java +++ b/src/test/java/com/openshift/internal/restclient/model/v1/ConfigMapTest.java @@ -1,45 +1,84 @@ /******************************************************************************* - * Copyright (c) 2015 Red Hat, Inc. Distributed under license by Red Hat, Inc. + * Copyright (c) 2015-2019 Red Hat, Inc. Distributed under license by Red Hat, Inc. * All rights reserved. This program is made available under the terms of the * Eclipse Public License v1.0 which accompanies this distribution, and is * available at http://www.eclipse.org/legal/epl-v10.html * * Contributors: Red Hat, Inc. ******************************************************************************/ + package com.openshift.internal.restclient.model.v1; +import static org.junit.Assert.assertEquals; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +import java.util.Collections; + +import org.jboss.dmr.ModelNode; +import org.junit.Before; +import org.junit.Test; + +import com.openshift.internal.restclient.ResourceFactory; import com.openshift.internal.restclient.model.ConfigMap; import com.openshift.internal.restclient.model.properties.ResourcePropertiesRegistry; +import com.openshift.restclient.IApiTypeMapper; +import com.openshift.restclient.IApiTypeMapper.IVersionedType; import com.openshift.restclient.IClient; import com.openshift.restclient.ResourceKind; import com.openshift.restclient.model.IConfigMap; import com.openshift.restclient.utils.Samples; -import org.jboss.dmr.ModelNode; -import org.junit.Before; -import org.junit.Test; - -import java.util.Collections; - -import static org.junit.Assert.assertEquals; -import static org.mockito.Mockito.mock; /** * @author Ulf Lilleengen */ public class ConfigMapTest { - private static final String VERSION = "v1"; - private IConfigMap configMap; - - @Before - public void setUp(){ - IClient client = mock(IClient.class); - ModelNode node = ModelNode.fromJSONString(Samples.V1_CONFIG_MAP.getContentAsString()); - configMap = new ConfigMap(node, client, ResourcePropertiesRegistry.getInstance().get(VERSION, ResourceKind.CONFIG_MAP)); - } - - @Test - public void testGetData() { - assertEquals(Collections.singletonMap("key1", "config1"), configMap.getData()); - } + private static final String VERSION = "v1"; + private IConfigMap configMap; + private IClient client; + + @Before + public void setUp() { + client = mock(IClient.class); + IApiTypeMapper mapper = mock(IApiTypeMapper.class); + when(client.adapt(IApiTypeMapper.class)).thenReturn(mapper); + when(mapper.getType(anyString(), eq(ResourceKind.CONFIG_MAP))).thenReturn(new IVersionedType() { + + @Override + public String getVersion() { + return "v1"; + } + + @Override + public String getPrefix() { + return null; + } + + @Override + public String getKind() { + return ResourceKind.CONFIG_MAP; + } + + @Override + public String getApiGroupName() { + return null; + } + }); + ModelNode node = ModelNode.fromJSONString(Samples.V1_CONFIG_MAP.getContentAsString()); + configMap = new ConfigMap(node, client, + ResourcePropertiesRegistry.getInstance().get(VERSION, ResourceKind.CONFIG_MAP)); + } + + @Test + public void testIsRegisteredWithFactory() { + configMap = new ResourceFactory(client).create(Samples.V1_CONFIG_MAP.getContentAsString()); + } + + @Test + public void testGetData() { + assertEquals(Collections.singletonMap("key1", "config1"), configMap.getData()); + } } diff --git a/src/test/java/com/openshift/internal/restclient/model/v1/DeploymentConfigTest.java b/src/test/java/com/openshift/internal/restclient/model/v1/DeploymentConfigTest.java index da34bdb5..b8f77e4d 100644 --- a/src/test/java/com/openshift/internal/restclient/model/v1/DeploymentConfigTest.java +++ b/src/test/java/com/openshift/internal/restclient/model/v1/DeploymentConfigTest.java @@ -6,12 +6,16 @@ * * Contributors: Red Hat, Inc. ******************************************************************************/ + package com.openshift.internal.restclient.model.v1; -import static org.junit.Assert.*; +import static com.openshift.internal.util.JBossDmrExtentions.getPath; +import static org.assertj.core.api.Assertions.assertThat; +import static org.junit.Assert.assertArrayEquals; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; -import static com.openshift.internal.util.JBossDmrExtentions.*; import java.util.ArrayList; import java.util.HashMap; @@ -28,123 +32,219 @@ import com.openshift.internal.restclient.model.properties.ResourcePropertiesRegistry; import com.openshift.restclient.IClient; import com.openshift.restclient.ResourceKind; +import com.openshift.restclient.capability.resources.IDeployCapability; import com.openshift.restclient.images.DockerImageURI; +import com.openshift.restclient.model.IContainer; import com.openshift.restclient.model.IPort; import com.openshift.restclient.model.deploy.IDeploymentConfigChangeTrigger; import com.openshift.restclient.model.deploy.IDeploymentImageChangeTrigger; import com.openshift.restclient.model.deploy.IDeploymentTrigger; +import com.openshift.restclient.model.probe.IProbe; import com.openshift.restclient.utils.Samples; -/** - * @author Jeff Cantrill - */ public class DeploymentConfigTest { - - private static final String VERSION = "v1"; - private DeploymentConfig config; - private IClient client; - private ModelNode node; - private Map propertyKeys; - - @Before - public void setup(){ - client = mock(IClient.class); - node = ModelNode.fromJSONString(Samples.V1_DEPLOYMENT_CONIFIG.getContentAsString()); - propertyKeys = ResourcePropertiesRegistry.getInstance().get(VERSION, ResourceKind.DEPLOYMENT_CONFIG); - config = new DeploymentConfig(node, client, propertyKeys); - } - - @Test - public void getLabels() { - assertArrayEquals(new String[] {"template"},config.getLabels().keySet().toArray(new String[] {})); - } - - @Test - public void getConfigChangeTrigger() { - List trigger = new ArrayList<>(config.getTriggers()); - assertEquals("Exp. equal number of triggers",2,trigger.size()); - assertTrue("Expected to find a config change trigger", IDeploymentConfigChangeTrigger.class.isAssignableFrom(trigger.get(0).getClass())); - assertTrue("Expected to find a config change trigger", IDeploymentImageChangeTrigger.class.isAssignableFrom(trigger.get(1).getClass())); - - IDeploymentImageChangeTrigger ict = (IDeploymentImageChangeTrigger) trigger.get(1); - assertEquals("foo", ict.getNamespace()); - } - - @Test - public void getReplicas(){ - assertEquals(1, config.getReplicas()); - } - - @Test - public void setReplicas(){ - config.setReplicas(3); - assertEquals(3, config.getReplicas()); - } - - @Test - public void setLatestVersionNumber(){ - config.setLatestVersionNumber(3); - assertEquals(3, config.getLatestVersionNumber()); - } - - @Test - public void setReplicaSelector() { - Map exp = new HashMap(); - exp.put("foo", "bar"); - node = ModelNode.fromJSONString(Samples.V1_DEPLOYMENT_CONIFIG.getContentAsString()); - DeploymentConfig config = new DeploymentConfig(node, client, ResourcePropertiesRegistry.getInstance().get(VERSION, ResourceKind.DEPLOYMENT_CONFIG)); - config.setReplicaSelector(exp); - assertEquals(exp, config.getReplicaSelector()); - } - - @Test - public void getReplicaSelector() { - Map exp = new HashMap(); - exp.put("name", "database"); - assertEquals(exp, config.getReplicaSelector()); - } - - @Test - public void getTriggerTypes() { - assertArrayEquals(new String[] {"ConfigChange", "ImageChange"}, config.getTriggerTypes().toArray(new String[] {})); - } - - @Test - public void testGetDeploymentStrategyTypes() { - assertEquals("Recreate", config.getDeploymentStrategyType()); - } - - @Test - public void testAddContainer() { - //remove containers hack - String[] path = getPath(DeploymentConfig.DEPLOYMENTCONFIG_CONTAINERS); - node.get(path).clear(); - - //setup - DockerImageURI uri = new DockerImageURI("aproject/an_image_name"); - IPort port = mock(IPort.class); - when(port.getProtocol()).thenReturn("TCP"); - when(port.getContainerPort()).thenReturn(8080); - Set ports = new HashSet<>(); - ports.add(port); - - config.addContainer(uri, ports, new HashMap()); - - List containers = node.get(path).asList(); - assertEquals(1, containers.size()); - - //expectations - ModelNode portNode = new ModelNode(); - portNode.get("protocol").set(port.getProtocol()); - portNode.get("containerPort").set(port.getContainerPort()); - - ModelNode exp = new ModelNode(); - exp.get("name").set(uri.getName()); - exp.get("image").set(uri.getUriWithoutHost()); - exp.get("ports").add(portNode); - - assertEquals(exp.toJSONString(false), containers.get(0).toJSONString(false)); - } - + + private static final String CONTAINER2_NAME = "deployment"; + private static final String CONTAINER1_NAME = "ruby-helloworld-database"; + private static final String VERSION = "v1"; + private DeploymentConfig config; + private IClient client; + private ModelNode node; + private Map propertyKeys; + private IContainer container1; + private IContainer container2; + + @Before + public void setup() { + client = mock(IClient.class); + node = ModelNode.fromJSONString(Samples.V1_DEPLOYMENT_CONIFIG.getContentAsString()); + propertyKeys = ResourcePropertiesRegistry.getInstance().get(VERSION, ResourceKind.DEPLOYMENT_CONFIG); + config = new DeploymentConfig(node, client, propertyKeys); + container1 = config.getContainer(CONTAINER1_NAME); + container2 = config.getContainer(CONTAINER2_NAME); + } + + @Test + public void testIsDeployCapable() { + assertThat(config.supports(IDeployCapability.class)).isTrue(); + } + + @Test + public void getLabels() { + assertArrayEquals(new String[] { "template" }, config.getLabels().keySet().toArray(new String[] {})); + } + + @Test + public void getConfigChangeTrigger() { + List trigger = new ArrayList<>(config.getTriggers()); + assertEquals("Exp. equal number of triggers", 2, trigger.size()); + assertTrue("Expected to find a config change trigger", + IDeploymentConfigChangeTrigger.class.isAssignableFrom(trigger.get(0).getClass())); + assertTrue("Expected to find a config change trigger", + IDeploymentImageChangeTrigger.class.isAssignableFrom(trigger.get(1).getClass())); + + IDeploymentImageChangeTrigger ict = (IDeploymentImageChangeTrigger) trigger.get(1); + assertEquals("foo", ict.getNamespace()); + } + + @Test + public void getReplicas() { + assertEquals(1, config.getReplicas()); + } + + @Test + public void setReplicas() { + config.setReplicas(3); + assertEquals(3, config.getReplicas()); + } + + @Test + public void setLatestVersionNumber() { + config.setLatestVersionNumber(3); + assertEquals(3, config.getLatestVersionNumber()); + } + + @Test + public void setReplicaSelector() { + Map exp = new HashMap(); + exp.put("foo", "bar"); + node = ModelNode.fromJSONString(Samples.V1_DEPLOYMENT_CONIFIG.getContentAsString()); + DeploymentConfig config = new DeploymentConfig(node, client, + ResourcePropertiesRegistry.getInstance().get(VERSION, ResourceKind.DEPLOYMENT_CONFIG)); + config.setReplicaSelector(exp); + assertEquals(exp, config.getReplicaSelector()); + } + + @Test + public void getReplicaSelector() { + Map exp = new HashMap(); + exp.put("name", "database"); + assertEquals(exp, config.getReplicaSelector()); + } + + @Test + public void getTriggerTypes() { + assertArrayEquals(new String[] { "ConfigChange", "ImageChange" }, + config.getTriggerTypes().toArray(new String[] {})); + } + + @Test + public void testGetDeploymentStrategyTypes() { + assertEquals("Recreate", config.getDeploymentStrategyType()); + } + + @Test + public void testAddContainer() { + // remove containers hack + String[] path = getPath(DeploymentConfig.DEPLOYMENTCONFIG_CONTAINERS); + node.get(path).clear(); + + // setup + IPort port = mock(IPort.class); + when(port.getProtocol()).thenReturn("TCP"); + when(port.getContainerPort()).thenReturn(8080); + Set ports = new HashSet<>(); + ports.add(port); + + DockerImageURI uri = new DockerImageURI("aproject/an_image_name"); + config.addContainer(uri, ports, new HashMap()); + + List containers = node.get(path).asList(); + assertEquals(1, containers.size()); + + // expectations + ModelNode portNode = new ModelNode(); + portNode.get("protocol").set(port.getProtocol()); + portNode.get("containerPort").set(port.getContainerPort()); + + ModelNode exp = new ModelNode(); + exp.get("name").set(uri.getName()); + exp.get("image").set(uri.getUriWithoutHost()); + exp.get("ports").add(portNode); + + assertEquals(exp.toJSONString(false), containers.get(0).toJSONString(false)); + } + + @Test + public void shouldNotReturnLivenessProbe() { + IProbe livenessProbe = container1.getLivenessProbe(); + assertThat(livenessProbe).isNull(); + } + + @Test + public void shouldNotReturnReadinessProbe() { + IProbe readinessProbe = container1.getReadinessProbe(); + assertThat(readinessProbe).isNull(); + } + + @Test + public void shouldReturnLivenessProbe() { + // given + // when + IProbe probe = container2.getLivenessProbe(); + + // then + assertThat(probe).isNotNull(); + assertThat(probe.getInitialDelaySeconds()).isEqualTo(11); + assertThat(probe.getTimeoutSeconds()).isEqualTo(12); + assertThat(probe.getPeriodSeconds()).isEqualTo(13); + assertThat(probe.getSuccessThreshold()).isEqualTo(14); + assertThat(probe.getFailureThreshold()).isEqualTo(15); + } + + @Test + public void shouldAlterLivenessProbe() { + // given + // when + IProbe probe = container2.getLivenessProbe(); + probe.setInitialDelaySeconds(100); + probe.setTimeoutSeconds(101); + probe.setPeriodSeconds(102); + probe.setSuccessThreshold(103); + probe.setFailureThreshold(104); + + // then + assertThat(probe).isNotNull(); + assertThat(probe.getInitialDelaySeconds()).isEqualTo(100); + assertThat(probe.getTimeoutSeconds()).isEqualTo(101); + assertThat(probe.getPeriodSeconds()).isEqualTo(102); + assertThat(probe.getSuccessThreshold()).isEqualTo(103); + assertThat(probe.getFailureThreshold()).isEqualTo(104); + } + + @Test + public void shouldReturnReadynessProbe() { + // given + // when + IProbe probe = container2.getReadinessProbe(); + + // then + assertThat(probe).isNotNull(); + assertThat(probe.getInitialDelaySeconds()).isEqualTo(3); + assertThat(probe.getTimeoutSeconds()).isEqualTo(4); + assertThat(probe.getPeriodSeconds()).isEqualTo(5); + assertThat(probe.getSuccessThreshold()).isEqualTo(6); + assertThat(probe.getFailureThreshold()).isEqualTo(7); + } + + @Test + public void shouldAlterReadinessProbe() { + // given + // when + IProbe probe = container2.getReadinessProbe(); + probe.setInitialDelaySeconds(200); + probe.setTimeoutSeconds(201); + probe.setPeriodSeconds(202); + probe.setSuccessThreshold(203); + probe.setFailureThreshold(204); + + // then + assertThat(probe).isNotNull(); + assertThat(probe.getInitialDelaySeconds()).isEqualTo(200); + assertThat(probe.getTimeoutSeconds()).isEqualTo(201); + assertThat(probe.getPeriodSeconds()).isEqualTo(202); + assertThat(probe.getSuccessThreshold()).isEqualTo(203); + assertThat(probe.getFailureThreshold()).isEqualTo(204); + } } diff --git a/src/test/java/com/openshift/internal/restclient/model/v1/EmptyDirVolumeSourceTest.java b/src/test/java/com/openshift/internal/restclient/model/v1/EmptyDirVolumeSourceTest.java index 7e0685a0..2cb993fc 100644 --- a/src/test/java/com/openshift/internal/restclient/model/v1/EmptyDirVolumeSourceTest.java +++ b/src/test/java/com/openshift/internal/restclient/model/v1/EmptyDirVolumeSourceTest.java @@ -8,18 +8,19 @@ * Contributors: * Red Hat, Inc. - initial API and implementation ******************************************************************************/ + package com.openshift.internal.restclient.model.v1; -import com.openshift.internal.restclient.model.volume.EmptyDirVolumeSource; -import com.openshift.internal.restclient.model.volume.PersistentVolumeClaimVolumeSource; -import com.openshift.restclient.model.volume.IEmptyDirVolumeSource; -import com.openshift.restclient.utils.Samples; +import static org.hamcrest.CoreMatchers.is; +import static org.hamcrest.MatcherAssert.assertThat; + import org.jboss.dmr.ModelNode; import org.junit.Before; import org.junit.Test; -import static org.hamcrest.CoreMatchers.is; -import static org.junit.Assert.assertThat; +import com.openshift.internal.restclient.model.volume.EmptyDirVolumeSource; +import com.openshift.restclient.model.volume.IEmptyDirVolumeSource; +import com.openshift.restclient.utils.Samples; /** * @author Ulf Lilleengen diff --git a/src/test/java/com/openshift/internal/restclient/model/v1/EndpointsTest.java b/src/test/java/com/openshift/internal/restclient/model/v1/EndpointsTest.java new file mode 100644 index 00000000..4d2a27b7 --- /dev/null +++ b/src/test/java/com/openshift/internal/restclient/model/v1/EndpointsTest.java @@ -0,0 +1,80 @@ +/******************************************************************************* + * Copyright (c) 2016 Red Hat, Inc. + * Distributed under license by Red Hat, Inc. All rights reserved. + * This program is made available under the terms of the + * Eclipse Public License v1.0 which accompanies this distribution, + * and is available at http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Red Hat, Inc. - initial API and implementation + ******************************************************************************/ + +package com.openshift.internal.restclient.model.v1; + + +import static org.assertj.core.api.Assertions.assertThat; + +import java.util.List; + +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.Mock; +import org.mockito.junit.MockitoJUnitRunner; + +import com.openshift.internal.restclient.TypeMapperFixture; +import com.openshift.restclient.IResourceFactory; +import com.openshift.restclient.api.models.IEndpoints; +import com.openshift.restclient.api.models.IEndpoints.IEndpointAddress; +import com.openshift.restclient.api.models.IEndpoints.IEndpointPort; +import com.openshift.restclient.api.models.IEndpoints.IEndpointSubset; +import com.openshift.restclient.utils.Samples; + +@RunWith(MockitoJUnitRunner.class) +public class EndpointsTest extends TypeMapperFixture { + + private static String JSON = Samples.V1_ENDPOINTS.getContentAsString(); + + @Mock + private IEndpoints endpoint; + + @Before + public void setUp() throws Exception { + super.setUp(); + IResourceFactory factory = getIClient().getResourceFactory(); + endpoint = factory.create(JSON); + } + + @Test + public void testDeserialization() { + List subSets = endpoint.getSubSets(); + assertThat(subSets).isNotEmpty(); + IEndpointSubset subset = subSets.get(0); + + List addresses = subset.getAddresses(); + assertThat(addresses).isNotEmpty(); + IEndpointAddress address = addresses.get(0); + assertThat(address.getName()).isEmpty(); + assertThat(address.getHostName()).isEmpty(); + assertThat(address.getNodeName()).isEmpty(); + assertThat(address.getIP()).isEqualTo("192.168.121.62"); + assertThat(address.getTargetRef()).isNotNull(); + + List notReady = subset.getNotReadyAddresses(); + assertThat(notReady).isNotEmpty(); + address = notReady.get(0); + assertThat(address.getName()).isEqualTo("notready"); + assertThat(address.getHostName()).isEqualTo("foo.bar"); + assertThat(address.getNodeName()).isEqualTo("xyz.abc"); + assertThat(address.getIP()).isEqualTo("192.168.121.68"); + assertThat(address.getTargetRef()).isNull(); + + List ports = subset.getPorts(); + assertThat(ports).isNotEmpty(); + IEndpointPort port = ports.get(0); + assertThat(port.getName()).isEqualTo("443-tcp"); + assertThat(port.getPort()).isEqualTo(443); + assertThat(port.getProtocol()).isEqualTo("TCP"); + } + +} diff --git a/src/test/java/com/openshift/internal/restclient/model/v1/EnvironmentVariableTest.java b/src/test/java/com/openshift/internal/restclient/model/v1/EnvironmentVariableTest.java new file mode 100644 index 00000000..89e6b088 --- /dev/null +++ b/src/test/java/com/openshift/internal/restclient/model/v1/EnvironmentVariableTest.java @@ -0,0 +1,96 @@ +/******************************************************************************* + * Copyright (c) 2017 Red Hat, Inc. Distributed under license by Red Hat, Inc. + * All rights reserved. This program is made available under the terms of the + * Eclipse Public License v1.0 which accompanies this distribution, and is + * available at http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: Red Hat, Inc. + ******************************************************************************/ + +package com.openshift.internal.restclient.model.v1; + +import static org.assertj.core.api.Assertions.assertThat; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.Collections; +import java.util.HashMap; +import java.util.Map; + +import org.junit.Test; + +import com.openshift.internal.restclient.model.EnvironmentVariable; +import com.openshift.internal.restclient.model.ModelNodeBuilder; +import com.openshift.restclient.model.IEnvironmentVariable; +import com.openshift.restclient.utils.EnvironmentVariableUtils; + +/** + * @author Andre Dietisheim + */ +public class EnvironmentVariableTest { + + @Test + public void shouldBeEqualGivenEqualNameAndValue() { + // given + IEnvironmentVariable var1 = createEnvironmentVariable("foo", "bar"); + IEnvironmentVariable var2 = createEnvironmentVariable("foo", "bar"); + // when + // then + assertThat(var1).isEqualTo(var2); + } + + @Test + public void shouldBeNonEqualGivenNonEqualNameAndValue() { + // given + IEnvironmentVariable var1 = createEnvironmentVariable("foo", "bar"); + IEnvironmentVariable var2 = createEnvironmentVariable("kung", "foo"); + // when + // then + assertThat(var1).isNotEqualTo(var2); + } + + @Test + public void shouldReturnEmptyMapGivenEmptyEnvVars() { + // given + Collection envVars = Collections.emptyList(); + // when + Map envVarsMap = EnvironmentVariableUtils.toMapOfStrings(envVars); + // then + assertThat(envVarsMap).isEmpty(); + } + + @SuppressWarnings("serial") + @Test + public void shouldReturnMapOfStringsForEnvVariables() { + // given + Collection envVars = createEnvironmentVariables("foo", "bar", "kung", "foo", "smurfHater", + "gargamel"); + // when + Map envVarsMap = EnvironmentVariableUtils.toMapOfStrings(envVars); + // then + assertThat(envVarsMap).isEqualTo(new HashMap() { + { + put("foo", "bar"); + put("kung", "foo"); + put("smurfHater", "gargamel"); + } + }); + } + + private Collection createEnvironmentVariables(String... touples) { + assertThat(touples).isNotNull(); + assertThat(touples.length % 2).isEqualTo(0); + + ArrayList envVars = new ArrayList(); + for (int i = 0; i < touples.length;) { + envVars.add(createEnvironmentVariable(touples[i++], touples[i++])); + } + return envVars; + } + + private IEnvironmentVariable createEnvironmentVariable(String name, String value) { + ModelNodeBuilder builder = new ModelNodeBuilder(); + builder.set(EnvironmentVariable.NAME, name).set(EnvironmentVariable.VALUE, value); + return new EnvironmentVariable(builder.build(), null); + } +} diff --git a/src/test/java/com/openshift/internal/restclient/model/v1/EventTest.java b/src/test/java/com/openshift/internal/restclient/model/v1/EventTest.java new file mode 100644 index 00000000..0a47937e --- /dev/null +++ b/src/test/java/com/openshift/internal/restclient/model/v1/EventTest.java @@ -0,0 +1,92 @@ +/******************************************************************************* + * Copyright (c) 2016 Red Hat, Inc. + * Distributed under license by Red Hat, Inc. All rights reserved. + * This program is made available under the terms of the + * Eclipse Public License v1.0 which accompanies this distribution, + * and is available at http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Red Hat, Inc. - initial API and implementation + ******************************************************************************/ + +package com.openshift.internal.restclient.model.v1; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; + +import java.util.HashMap; + +import org.jboss.dmr.ModelNode; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.Mock; +import org.mockito.junit.MockitoJUnitRunner; + +import com.openshift.internal.restclient.model.KubernetesEvent; +import com.openshift.restclient.IClient; +import com.openshift.restclient.model.IEvent; +import com.openshift.restclient.model.IEvent.IEventSource; +import com.openshift.restclient.model.IObjectReference; +import com.openshift.restclient.utils.Samples; + +@RunWith(MockitoJUnitRunner.class) +public class EventTest { + + private static String JSON = Samples.V1_EVENT.getContentAsString(); + + @Mock + private IClient client; + private IEvent event; + + @Before + public void setUp() throws Exception { + ModelNode node = ModelNode.fromJSONString(JSON); + event = new KubernetesEvent(node, client, new HashMap<>()); + } + + @Test + public void testGetEventSource() { + IEventSource source = event.getEventSource(); + assertNotNull(source); + assertEquals("deploymentconfig-controller", source.getComponent()); + assertEquals("", source.getHost()); + } + + @Test + public void testGetType() { + assertEquals("Normal", event.getType()); + } + + @Test + public void testGetCount() { + assertEquals(1, event.getCount()); + } + + @Test + public void testGetFirstSeen() { + assertEquals("2016-08-08T01:49:26Z", event.getFirstSeenTimestamp()); + } + + @Test + public void testGetLastSeen() { + assertEquals("2016-08-08T01:49:26Z", event.getLastSeenTimestamp()); + } + + @Test + public void testGetReason() { + assertEquals("DeploymentCreated", event.getReason()); + } + + @Test + public void testGetInvolvedObject() { + IObjectReference ref = event.getInvolvedObject(); + assertNotNull(ref); + } + + @Test + public void testGetMessage() { + assertEquals("Created new deployment \"nodejs-1\" for version 1", event.getMessage()); + } + +} diff --git a/src/test/java/com/openshift/internal/restclient/model/v1/GroupTest.java b/src/test/java/com/openshift/internal/restclient/model/v1/GroupTest.java new file mode 100644 index 00000000..ee57ad18 --- /dev/null +++ b/src/test/java/com/openshift/internal/restclient/model/v1/GroupTest.java @@ -0,0 +1,66 @@ +/******************************************************************************* + * Copyright (c) 2018 Red Hat, Inc. + * + * Distributed under license by Red Hat, Inc. All rights reserved. + * This program is made available under the terms of the + * Eclipse Public License v1.0 which accompanies this distribution, + * and is available at http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Red Hat, Inc. - initial API and implementation + * Roland T. Lichti - implementation of user.openshift.io/v1/groups + ******************************************************************************/ + +package com.openshift.internal.restclient.model.v1; + +import static org.junit.Assert.assertEquals; +import static org.mockito.Mockito.mock; + +import java.util.HashSet; +import java.util.Set; + +import org.jboss.dmr.ModelNode; +import org.junit.Before; +import org.junit.Test; + +import com.openshift.internal.restclient.model.properties.ResourcePropertiesRegistry; +import com.openshift.internal.restclient.model.user.OpenShiftGroup; +import com.openshift.restclient.IClient; +import com.openshift.restclient.ResourceKind; +import com.openshift.restclient.model.user.IGroup; +import com.openshift.restclient.utils.Samples; + +/** + * Test to validate the lookup paths are correct for the version + */ +public class GroupTest { + + private static final String VERSION = "v1"; + private IGroup group; + + @Before + public void setUp() { + IClient client = mock(IClient.class); + ModelNode node = ModelNode.fromJSONString(Samples.V1_GROUP.getContentAsString()); + group = new OpenShiftGroup(node, client, + ResourcePropertiesRegistry.getInstance().get(VERSION, ResourceKind.GROUP)); + } + + @Test + public void testGroupName() { + assertEquals("test-group", group.getName()); + } + + @Test + public void testUid() { + assertEquals("5374bc7a-c985-11e8-8799-525400d45cd2", group.getUID()); + } + + @Test + public void testUsers() { + Set userlist = new HashSet<>(1); + userlist.add("test-admin"); + + assertEquals(group.getUsers(), userlist); + } +} diff --git a/src/test/java/com/openshift/internal/restclient/model/v1/HostPathVolumeSourceTest.java b/src/test/java/com/openshift/internal/restclient/model/v1/HostPathVolumeSourceTest.java new file mode 100644 index 00000000..3da01e7f --- /dev/null +++ b/src/test/java/com/openshift/internal/restclient/model/v1/HostPathVolumeSourceTest.java @@ -0,0 +1,50 @@ +/******************************************************************************* + * Copyright (c) 2016 Red Hat, Inc. + * Distributed under license by Red Hat, Inc. All rights reserved. + * This program is made available under the terms of the + * Eclipse Public License v1.0 which accompanies this distribution, + * and is available at http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Red Hat, Inc. - initial API and implementation + ******************************************************************************/ + +package com.openshift.internal.restclient.model.v1; + +import static org.hamcrest.CoreMatchers.is; +import static org.hamcrest.MatcherAssert.assertThat; + +import org.jboss.dmr.ModelNode; +import org.junit.Before; +import org.junit.Test; + +import com.openshift.internal.restclient.model.ModelNodeBuilder; +import com.openshift.internal.restclient.model.volume.VolumeSource; +import com.openshift.restclient.model.volume.IHostPathVolumeSource; + +public class HostPathVolumeSourceTest { + + private IHostPathVolumeSource source; + + @Before + public void setUp() throws Exception { + ModelNode node = new ModelNodeBuilder().set("name", "somevolumesourcename") + .set("hostPath", new ModelNodeBuilder().set("path", "/foo").build()).build(); + source = (IHostPathVolumeSource) VolumeSource.create(node); + } + + @Test + public void testName() { + assertThat(source.getName(), is("somevolumesourcename")); + source.setName("thenewname"); + assertThat(source.getName(), is("thenewname")); + } + + @Test + public void testPath() { + assertThat(source.getPath(), is("/foo")); + source.setPath("thenewpath"); + assertThat(source.getPath(), is("thenewpath")); + } + +} diff --git a/src/test/java/com/openshift/internal/restclient/model/v1/IdentityTest.java b/src/test/java/com/openshift/internal/restclient/model/v1/IdentityTest.java new file mode 100644 index 00000000..67d5f881 --- /dev/null +++ b/src/test/java/com/openshift/internal/restclient/model/v1/IdentityTest.java @@ -0,0 +1,70 @@ +/******************************************************************************* + * Copyright (c) 2018 Red Hat, Inc. + * + * Distributed under license by Red Hat, Inc. All rights reserved. + * This program is made available under the terms of the + * Eclipse Public License v1.0 which accompanies this distribution, + * and is available at http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Red Hat, Inc. - initial API and implementation + * Roland T. Lichti - implementation of user.openshift.io/v1/identities + ******************************************************************************/ + +package com.openshift.internal.restclient.model.v1; + +import static org.junit.Assert.assertEquals; +import static org.mockito.Mockito.mock; + +import org.jboss.dmr.ModelNode; +import org.junit.Before; +import org.junit.Test; + +import com.openshift.internal.restclient.model.properties.ResourcePropertiesRegistry; +import com.openshift.internal.restclient.model.user.OpenShiftIdentity; +import com.openshift.restclient.IClient; +import com.openshift.restclient.ResourceKind; +import com.openshift.restclient.model.user.IIdentity; +import com.openshift.restclient.utils.Samples; + +/** + * Test to validate the lookup paths are correct for the version + */ +public class IdentityTest { + + private static final String VERSION = "v1"; + private IIdentity identity; + + @Before + public void setUp() { + IClient client = mock(IClient.class); + ModelNode node = ModelNode.fromJSONString(Samples.V1_IDENTITY.getContentAsString()); + identity = new OpenShiftIdentity(node, client, + ResourcePropertiesRegistry.getInstance().get(VERSION, ResourceKind.IDENTITY)); + } + + @Test + public void testUserName() { + assertEquals("test-admin", identity.getUserName()); + } + + @Test + public void testUid() { + assertEquals("94b42e96-0faa-11e5-9467-080027893417", identity.getUID()); + } + + @Test + public void testProviderName() { + assertEquals("anypassword", identity.getProviderName()); + } + + @Test + public void testUserReferenceName() { + assertEquals("test-admin", identity.getUser().getName()); + } + + @Test + public void testUserReferenceUid() { + assertEquals("94b42e96-0faa-11e5-9467-080027893417", identity.getUser().getUID()); + } +} diff --git a/src/test/java/com/openshift/internal/restclient/model/v1/ImageStreamImportTest.java b/src/test/java/com/openshift/internal/restclient/model/v1/ImageStreamImportTest.java index 71b91323..7c70eb51 100644 --- a/src/test/java/com/openshift/internal/restclient/model/v1/ImageStreamImportTest.java +++ b/src/test/java/com/openshift/internal/restclient/model/v1/ImageStreamImportTest.java @@ -6,9 +6,13 @@ * * Contributors: Red Hat, Inc. ******************************************************************************/ + package com.openshift.internal.restclient.model.v1; -import static org.junit.Assert.*; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertTrue; import static org.mockito.Mockito.mock; import java.util.Collection; @@ -26,40 +30,39 @@ import com.openshift.restclient.model.image.IImageStreamImport; import com.openshift.restclient.utils.Samples; -/** - * @author Jeff Cantrill - */ public class ImageStreamImportTest { - private static final String VERSION = "v1"; - private static IClient client; - private IImageStreamImport stream; + private static final String VERSION = "v1"; + private static IClient client; + private IImageStreamImport stream; + + @Before + public void setup() { + client = mock(IClient.class); + ModelNode node = ModelNode.fromJSONString(Samples.V1_IMAGE_STREAM_IMPORT.getContentAsString()); + stream = new ImageStreamImport(node, client, + ResourcePropertiesRegistry.getInstance().get(VERSION, ResourceKind.IMAGE_STREAM_IMPORT)); + } + + @Test + public void testImport() { + assertFalse(stream.isImport()); + + stream.setImport(true); + assertTrue(stream.isImport()); + } + + @Test + public void testGetImageStatus() { + Collection status = stream.getImageStatus(); + assertEquals(1, status.size()); + assertEquals("Success", status.iterator().next().getStatus()); + } - @Before - public void setup(){ - client = mock(IClient.class); - ModelNode node = ModelNode.fromJSONString(Samples.V1_IMAGE_STREAM_IMPORT.getContentAsString()); - stream = new ImageStreamImport(node, client, ResourcePropertiesRegistry.getInstance().get(VERSION, ResourceKind.IMAGE_STREAM_IMPORT)); - } - - @Test - public void testImport() { - assertFalse(stream.isImport()); - - stream.setImport(true); - assertTrue(stream.isImport()); - } - - @Test - public void testGetImageStatus() { - Collection status = stream.getImageStatus(); - assertEquals(1, status.size()); - assertEquals("Success", status.iterator().next().getStatus()); - } - - @Test - public void testGetImageJsonFor() { - assertTrue("Exp. to find the json blob for the given image", StringUtils.isNotBlank(stream.getImageJsonFor("latest"))); + @Test + public void testGetImageJsonFor() { + assertTrue("Exp. to find the json blob for the given image", + StringUtils.isNotBlank(stream.getImageJsonFor("latest"))); - assertNull("Exp. to not find the json blob", stream.getImageJsonFor("bar")); - } + assertNull("Exp. to not find the json blob", stream.getImageJsonFor("bar")); + } } diff --git a/src/test/java/com/openshift/internal/restclient/model/v1/ImageStreamTest.java b/src/test/java/com/openshift/internal/restclient/model/v1/ImageStreamTest.java index a397df59..2f0d5abd 100644 --- a/src/test/java/com/openshift/internal/restclient/model/v1/ImageStreamTest.java +++ b/src/test/java/com/openshift/internal/restclient/model/v1/ImageStreamTest.java @@ -6,13 +6,15 @@ * * Contributors: Red Hat, Inc. ******************************************************************************/ + package com.openshift.internal.restclient.model.v1; -import static org.junit.Assert.*; +import static org.junit.Assert.assertArrayEquals; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; import static org.mockito.Mockito.mock; import java.util.Collection; -import java.util.HashMap; import java.util.Optional; import java.util.stream.Collectors; @@ -22,7 +24,6 @@ import com.openshift.internal.restclient.model.ImageStream; import com.openshift.internal.restclient.model.properties.ResourcePropertiesRegistry; -import com.openshift.internal.util.JBossDmrExtentions; import com.openshift.restclient.IClient; import com.openshift.restclient.ResourceKind; import com.openshift.restclient.images.DockerImageURI; @@ -30,57 +31,55 @@ import com.openshift.restclient.model.image.ITagReference; import com.openshift.restclient.utils.Samples; -/** - * @author Jeff Cantrill - */ public class ImageStreamTest { - private static final String VERSION = "v1"; - private static IClient client; - private IImageStream stream; - private ModelNode node; + private static final String VERSION = "v1"; + private static IClient client; + private IImageStream stream; + private ModelNode node; + + @Before + public void setup() { + client = mock(IClient.class); + node = ModelNode.fromJSONString(Samples.V1_IMAGE_STREAM.getContentAsString()); + stream = new ImageStream(node, client, + ResourcePropertiesRegistry.getInstance().get(VERSION, ResourceKind.IMAGE_STREAM)); + } + + @Test + public void testGetTags() { + Collection tags = stream.getTags().stream().map(tr -> tr.getName()).collect(Collectors.toList()); + assertArrayEquals(new Object[] { "8.1", "latest" }, tags.toArray()); + } + + @Test + public void testAddTag() { + ITagReference tag = stream.addTag("1234", ResourceKind.IMAGE_STREAM_TAG, "foo/bar"); + Optional actTag = stream.getTags().stream().filter(t -> "1234".equals(t.getName())).findFirst(); + assertTrue("Exp. the tag to have been added", actTag.isPresent()); + assertEquals(tag.toJson(), actTag.get().toJson()); + } + + @Test + public void testAddTagWithNamespace() { + ITagReference tag = stream.addTag("1234", ResourceKind.IMAGE_STREAM_TAG, "foo/bar", "fromNmspc"); + Optional actTag = stream.getTags().stream().filter(t -> "1234".equals(t.getName())).findFirst(); + assertTrue("Exp. the tag to have been added", actTag.isPresent()); + assertEquals(tag.toJson(), actTag.get().toJson()); + } - @Before - public void setup(){ - client = mock(IClient.class); - node = ModelNode.fromJSONString(Samples.V1_IMAGE_STREAM.getContentAsString()); - stream = new ImageStream(node, client, ResourcePropertiesRegistry.getInstance().get(VERSION, ResourceKind.IMAGE_STREAM)); - } - - @Test - public void testGetTags() { - Collection tags = stream.getTags().stream().map(tr->tr.getName()).collect(Collectors.toList()); - assertArrayEquals(new Object [] {"8.1", "latest"}, tags.toArray()); - } - - @Test - public void testAddTag() { - ITagReference tag = stream.addTag("1234", ResourceKind.IMAGE_STREAM_TAG, "foo/bar"); - Optional actTag = stream.getTags().stream().filter(t->"1234".equals(t.getName())).findFirst(); - assertTrue("Exp. the tag to have been added",actTag.isPresent()); - assertEquals(tag.toJson(), actTag.get().toJson()); - } - - @Test - public void testAddTagWithNamespace() { - ITagReference tag = stream.addTag("1234", ResourceKind.IMAGE_STREAM_TAG, "foo/bar", "fromNmspc"); - Optional actTag = stream.getTags().stream().filter(t->"1234".equals(t.getName())).findFirst(); - assertTrue("Exp. the tag to have been added",actTag.isPresent()); - assertEquals(tag.toJson(), actTag.get().toJson()); - } - - @Test - public void getDockerImageRepository() { - DockerImageURI uri = new DockerImageURI("172.30.224.48:5000/openshift/wildfly:latest"); - assertEquals(uri, stream.getDockerImageRepository()); - node.get("spec").clear(); - assertEquals(uri, stream.getDockerImageRepository()); - } + @Test + public void getDockerImageRepository() { + DockerImageURI uri = new DockerImageURI("172.30.224.48:5000/openshift/wildfly:latest"); + assertEquals(uri, stream.getDockerImageRepository()); + node.get("spec").clear(); + assertEquals(uri, stream.getDockerImageRepository()); + } - @Test - public void setDockerImageRepository() { - DockerImageURI newUri = new DockerImageURI("172.30.244.213:5000/tests/origin-ruby-sample"); - stream.setDockerImageRepository(newUri); - assertEquals(newUri, stream.getDockerImageRepository()); - } + @Test + public void setDockerImageRepository() { + DockerImageURI newUri = new DockerImageURI("172.30.244.213:5000/tests/origin-ruby-sample"); + stream.setDockerImageRepository(newUri); + assertEquals(newUri, stream.getDockerImageRepository()); + } } diff --git a/src/test/java/com/openshift/internal/restclient/model/v1/LifecycleTest.java b/src/test/java/com/openshift/internal/restclient/model/v1/LifecycleTest.java new file mode 100644 index 00000000..6b8eca82 --- /dev/null +++ b/src/test/java/com/openshift/internal/restclient/model/v1/LifecycleTest.java @@ -0,0 +1,82 @@ +/******************************************************************************* + * Copyright (c) 2016 Red Hat, Inc. + * Distributed under license by Red Hat, Inc. All rights reserved. + * This program is made available under the terms of the + * Eclipse Public License v1.0 which accompanies this distribution, + * and is available at http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Red Hat, Inc. - initial API and implementation + ******************************************************************************/ + +package com.openshift.internal.restclient.model.v1; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; + +import org.jboss.dmr.ModelNode; +import org.junit.Before; +import org.junit.Test; + +import com.openshift.internal.restclient.model.ExecAction; +import com.openshift.internal.restclient.model.Lifecycle; +import com.openshift.restclient.model.IExecAction; +import com.openshift.restclient.model.IHandler; +import com.openshift.restclient.model.ILifecycle; +import com.openshift.restclient.utils.Samples; + +/** + * @author Ulf Lilleengen + */ +public class LifecycleTest { + private ILifecycle lifecycle; + + @Before + public void setup() { + ModelNode node = ModelNode.fromJSONString(Samples.V1_LIFECYCLE.getContentAsString()); + lifecycle = Lifecycle.fromJson(node); + } + + @Test + public void testPostStart() { + assertTrue(lifecycle.getPostStart().isPresent()); + assertEquals(IHandler.EXEC, lifecycle.getPostStart().get().getType()); + IExecAction exec = (IExecAction)lifecycle.getPostStart().get(); + assertEquals(1, exec.getCommand().size()); + assertEquals("postcmd1", exec.getCommand().get(0)); + } + + @Test + public void testPreStop() { + assertTrue(lifecycle.getPreStop().isPresent()); + assertEquals(IHandler.EXEC, lifecycle.getPreStop().get().getType()); + IExecAction exec = (IExecAction)lifecycle.getPreStop().get(); + assertEquals(2, exec.getCommand().size()); + assertEquals("precmd1", exec.getCommand().get(0)); + assertEquals("precmd2", exec.getCommand().get(1)); + } + + @Test + public void testBuilder() { + lifecycle = new Lifecycle.Builder() + .preStop(new ExecAction.Builder() + .command("cmd1") + .build()) + .postStart(new ExecAction.Builder() + .command("cmd2") + .build()) + .build(); + + assertTrue(lifecycle.getPreStop().isPresent()); + assertTrue(lifecycle.getPostStart().isPresent()); + + assertEqualJson("{\"preStop\":{\"exec\":{\"command\":[\"cmd1\"]}},\"postStart\":{\"exec\":{\"command\":[\"cmd2\"]}}}", lifecycle.toJson()); + } + + private static void assertEqualJson(String expected, String actual) { + ModelNode expectedNode = ModelNode.fromJSONString(expected); + ModelNode actualNode = ModelNode.fromJSONString(actual); + assertEquals(expectedNode.toJSONString(true), actualNode.toJSONString(true)); + } +} + diff --git a/src/test/java/com/openshift/internal/restclient/model/v1/ListTest.java b/src/test/java/com/openshift/internal/restclient/model/v1/ListTest.java index b20f296e..88446d11 100644 --- a/src/test/java/com/openshift/internal/restclient/model/v1/ListTest.java +++ b/src/test/java/com/openshift/internal/restclient/model/v1/ListTest.java @@ -6,6 +6,7 @@ * * Contributors: Red Hat, Inc. ******************************************************************************/ + package com.openshift.internal.restclient.model.v1; import static org.junit.Assert.assertEquals; @@ -28,40 +29,39 @@ import com.openshift.restclient.model.IResource; import com.openshift.restclient.utils.Samples; -/** - * @author Jeff Cantrill - */ public class ListTest { - - private static final String VERSION = "v1"; - private static IClient client; - - @BeforeClass - public static void setup() throws Exception{ - client = mock(IClient.class); - when(client.getBaseURL()).thenReturn(new URL("https://localhost:8443")); - when(client.getOpenShiftAPIVersion()).thenReturn(VERSION); - when(client.getResourceFactory()).thenReturn(new ResourceFactory(client)); - } - private IList createList(Samples sample) { - ModelNode node = ModelNode.fromJSONString(sample.getContentAsString()); - return new List(node, client, null); - } - - @Test - public void testItemKindsAreDefined() { - IList resource = createList(Samples.V1_BUILD_CONFIG_LIST); - Collection items = resource.getItems(); - assertTrue("Expected to be entries in the list",items.size() >0 ); - assertEquals(ResourceKind.BUILD_CONFIG, items.iterator().next().getKind()); - } + private static final String VERSION = "v1"; + private static IClient client; + + @BeforeClass + public static void setup() throws Exception { + client = mock(IClient.class); + when(client.getBaseURL()).thenReturn(new URL("https://localhost:8443")); + when(client.getOpenShiftAPIVersion()).thenReturn(VERSION); + when(client.getResourceFactory()).thenReturn(new ResourceFactory(client)); + } + + private IList createList(Samples sample) { + ModelNode node = ModelNode.fromJSONString(sample.getContentAsString()); + return new List(node, client, null); + } + + @Test + public void testItemKindAndApiVersionAreDefined() { + IList resource = createList(Samples.V1_BUILD_CONFIG_LIST); + Collection items = resource.getItems(); + assertTrue("Expected to be entries in the list", items.size() > 0); + IResource bc = items.iterator().next(); + assertEquals(ResourceKind.BUILD_CONFIG, bc.getKind()); + assertEquals("v1", bc.getApiVersion()); + } - @Test - public void testEmptyList() { - IList resource = createList(Samples.V1_CONFIG_MAP_LIST_EMPTY); - Collection items = resource.getItems(); - assertEquals(0, items.size()); - } + @Test + public void testEmptyList() { + IList resource = createList(Samples.V1_CONFIG_MAP_LIST_EMPTY); + Collection items = resource.getItems(); + assertEquals(0, items.size()); + } } diff --git a/src/test/java/com/openshift/internal/restclient/model/v1/ObjectRefTest.java b/src/test/java/com/openshift/internal/restclient/model/v1/ObjectRefTest.java index 9df96343..77bf21ec 100644 --- a/src/test/java/com/openshift/internal/restclient/model/v1/ObjectRefTest.java +++ b/src/test/java/com/openshift/internal/restclient/model/v1/ObjectRefTest.java @@ -6,54 +6,78 @@ * * Contributors: Red Hat, Inc. ******************************************************************************/ + package com.openshift.internal.restclient.model.v1; -import static org.junit.Assert.*; +import static org.junit.Assert.assertEquals; import org.jboss.dmr.ModelNode; -import org.junit.BeforeClass; +import org.junit.Before; import org.junit.Test; import com.openshift.internal.restclient.model.ObjectReference; +import com.openshift.restclient.ResourceKind; import com.openshift.restclient.model.IObjectReference; import com.openshift.restclient.utils.Samples; -/** - * @author Jeff Cantrill - */ public class ObjectRefTest { - private static IObjectReference objRef; - - @BeforeClass - public static void setup(){ - ModelNode node = ModelNode.fromJSONString(Samples.V1_OBJECT_REF.getContentAsString()); - objRef = new ObjectReference(node); - } - - @Test - public void testGetKind(){ - assertEquals("ServiceAccount", objRef.getKind()); - } - @Test - public void testGetNamespace(){ - assertEquals("test", objRef.getNamespace()); - } - @Test - public void testGetName(){ - assertEquals("builder", objRef.getName()); - } - @Test - public void testGetUID(){ - assertEquals("ce20b132-7986-11e5-b1e5-080027bdffff", objRef.getUID()); - } - @Test - public void getResourceVersion(){ - assertEquals("33366", objRef.getResourceVersion()); - } - @Test - public void getApiVersion(){ - assertEquals("v1", objRef.getApiVersion()); - } + private static final String CONTENT = Samples.V1_OBJECT_REF.getContentAsString(); + private IObjectReference objRef; + private ModelNode node; + + @Before + public void setup() { + node = ModelNode.fromJSONString(CONTENT); + objRef = new ObjectReference(node); + } + + @Test + public void testGetKind() { + assertEquals("ServiceAccount", objRef.getKind()); + } + + @Test + public void testSetKind() { + objRef.setKind(ResourceKind.BUILD); + assertEquals(ResourceKind.BUILD, new ObjectReference(node.clone()).getKind()); + } + + @Test + public void testGetNamespace() { + assertEquals("test", objRef.getNamespace()); + } + + @Test + public void testSetNamespace() { + objRef.setNamespace("newnamespace"); + assertEquals("newnamespace", new ObjectReference(node.clone()).getNamespace()); + } + + @Test + public void testGetName() { + assertEquals("builder", objRef.getName()); + } + + @Test + public void testSetName() { + objRef.setName("newname"); + assertEquals("newname", new ObjectReference(node.clone()).getName()); + } + + @Test + public void testGetUID() { + assertEquals("ce20b132-7986-11e5-b1e5-080027bdffff", objRef.getUID()); + } + + @Test + public void getResourceVersion() { + assertEquals("33366", objRef.getResourceVersion()); + } + + @Test + public void getApiVersion() { + assertEquals("v1", objRef.getApiVersion()); + } } diff --git a/src/test/java/com/openshift/internal/restclient/model/v1/PVCTest.java b/src/test/java/com/openshift/internal/restclient/model/v1/PVCTest.java index 0dd3f774..3551ba85 100644 --- a/src/test/java/com/openshift/internal/restclient/model/v1/PVCTest.java +++ b/src/test/java/com/openshift/internal/restclient/model/v1/PVCTest.java @@ -1,68 +1,101 @@ /******************************************************************************* - * Copyright (c) 2015 Red Hat, Inc. Distributed under license by Red Hat, Inc. + * Copyright (c) 2015-2019 Red Hat, Inc. Distributed under license by Red Hat, Inc. * All rights reserved. This program is made available under the terms of the * Eclipse Public License v1.0 which accompanies this distribution, and is * available at http://www.eclipse.org/legal/epl-v10.html * * Contributors: Red Hat, Inc. ******************************************************************************/ + package com.openshift.internal.restclient.model.v1; -import static org.junit.Assert.*; +import static org.junit.Assert.assertArrayEquals; +import static org.junit.Assert.assertEquals; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +import java.util.Collections; import org.junit.Before; import org.junit.Test; import com.openshift.internal.restclient.ResourceFactory; +import com.openshift.restclient.IApiTypeMapper; +import com.openshift.restclient.IApiTypeMapper.IVersionedType; import com.openshift.restclient.IClient; +import com.openshift.restclient.ResourceKind; import com.openshift.restclient.model.volume.IPersistentVolumeClaim; import com.openshift.restclient.model.volume.PVCAccessModes; import com.openshift.restclient.utils.Samples; -import java.util.Collections; - -/** - * @author Jeff Cantrill - */ public class PVCTest { - private static final String V1 = "v1"; - private IPersistentVolumeClaim claim; - - @Before - public void setup(){ - IClient client = mock(IClient.class); - claim = new ResourceFactory(client).create(Samples.V1_PVC.getContentAsString()); - assertEquals(V1, claim.getApiVersion()); - } - - @Test - public void testGetAccessModes(){ - assertArrayEquals(new String[] {PVCAccessModes.READ_WRITE_ONCE}, claim.getAccessModes().toArray()); - } + private static final String V1 = "v1"; + private IPersistentVolumeClaim claim; + + @Before + public void setup() { + IClient client = mock(IClient.class); + IApiTypeMapper mapper = mock(IApiTypeMapper.class); + when(client.adapt(IApiTypeMapper.class)).thenReturn(mapper); + when(mapper.getType(anyString(), eq(ResourceKind.PVC))).thenReturn(new IVersionedType() { + + @Override + public String getVersion() { + return "v1"; + } + + @Override + public String getPrefix() { + return null; + } + + @Override + public String getKind() { + return ResourceKind.PVC; + } + + @Override + public String getApiGroupName() { + return null; + } + }); + claim = new ResourceFactory(client).create(Samples.V1_PVC.getContentAsString()); + assertEquals(V1, claim.getApiVersion()); + } + + @Test + public void testGetAccessModes() { + assertArrayEquals(new String[] { PVCAccessModes.READ_WRITE_ONCE }, claim.getAccessModes().toArray()); + } + + @Test + public void testSetAccessModes() { + claim.setAccessModes(Collections.singleton(PVCAccessModes.READ_WRITE_MANY)); + assertArrayEquals(new String[] { PVCAccessModes.READ_WRITE_MANY }, claim.getAccessModes().toArray()); + } + + @Test + public void testGetStatus() { + assertEquals("Pending", claim.getStatus()); + } - @Test - public void testSetAccessModes() { - claim.setAccessModes(Collections.singleton(PVCAccessModes.READ_WRITE_MANY)); - assertArrayEquals(new String[] {PVCAccessModes.READ_WRITE_MANY}, claim.getAccessModes().toArray()); - } + @Test + public void testGetRequestedStorage() { + assertEquals("15m", claim.getRequestedStorage()); + } - - @Test - public void testGetStatus(){ - assertEquals("Pending", claim.getStatus()); - } - - @Test - public void testGetRequestedStorage(){ - assertEquals("15m", claim.getRequestedStorage()); - } + @Test + public void testSetRequestedStorage() { + claim.setRequestedStorage("1Gi"); + assertEquals("1Gi", claim.getRequestedStorage()); + } - @Test - public void testSetRequestedStorage() { - claim.setRequestedStorage("1Gi"); - assertEquals("1Gi", claim.getRequestedStorage()); - } + @Test + public void testGetVolumeName() { + assertEquals("pv02", claim.getVolumeName()); + } } diff --git a/src/test/java/com/openshift/internal/restclient/model/v1/PVCVolumeSourceTest.java b/src/test/java/com/openshift/internal/restclient/model/v1/PVCVolumeSourceTest.java index f6118923..52f76773 100644 --- a/src/test/java/com/openshift/internal/restclient/model/v1/PVCVolumeSourceTest.java +++ b/src/test/java/com/openshift/internal/restclient/model/v1/PVCVolumeSourceTest.java @@ -8,18 +8,20 @@ * Contributors: * Red Hat, Inc. - initial API and implementation ******************************************************************************/ + package com.openshift.internal.restclient.model.v1; -import com.openshift.internal.restclient.model.volume.PersistentVolumeClaimVolumeSource; -import com.openshift.internal.restclient.model.volume.VolumeSource; -import com.openshift.restclient.model.volume.IPersistentVolumeClaimVolumeSource; -import com.openshift.restclient.utils.Samples; +import static org.hamcrest.CoreMatchers.is; +import static org.hamcrest.MatcherAssert.assertThat; + import org.jboss.dmr.ModelNode; import org.junit.Before; import org.junit.Test; -import static org.hamcrest.CoreMatchers.is; -import static org.junit.Assert.assertThat; +import com.openshift.internal.restclient.model.volume.PersistentVolumeClaimVolumeSource; +import com.openshift.internal.restclient.model.volume.VolumeSource; +import com.openshift.restclient.model.volume.IPersistentVolumeClaimVolumeSource; +import com.openshift.restclient.utils.Samples; /** * @author Ulf Lilleengen diff --git a/src/test/java/com/openshift/internal/restclient/model/v1/PersistentVolumeTest.java b/src/test/java/com/openshift/internal/restclient/model/v1/PersistentVolumeTest.java index 5510d341..eb6d5491 100644 --- a/src/test/java/com/openshift/internal/restclient/model/v1/PersistentVolumeTest.java +++ b/src/test/java/com/openshift/internal/restclient/model/v1/PersistentVolumeTest.java @@ -8,8 +8,13 @@ * Contributors: * Red Hat, Inc. - initial API and implementation ******************************************************************************/ + package com.openshift.internal.restclient.model.v1; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; +import static org.mockito.Mockito.mock; + import java.util.Arrays; import java.util.HashSet; import java.util.Set; @@ -30,117 +35,113 @@ import com.openshift.restclient.utils.MemoryUnit; import com.openshift.restclient.utils.Samples; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; -import static org.mockito.Mockito.mock; - - public class PersistentVolumeTest { - private static final String VERSION = "v1"; - private static final Samples sample = Samples.V1_PERSISTENT_VOLUME; - private IPersistentVolume pv; - private IClient client; - - @Before - public void setUp() { - client = mock(IClient.class); - ModelNode node = ModelNode.fromJSONString(sample.getContentAsString()); - pv = new PersistentVolume(node, client, ResourcePropertiesRegistry.getInstance().get(VERSION, ResourceKind.PERSISTENT_VOLUME)); - } - - @Test - public void testGetCapacityString() { - pv.setCapacity(13L, MemoryUnit.Pi); - long capacity = pv.getCapacity("Ki"); - assertEquals(14293651161088L, capacity); - - capacity = pv.getCapacity("Ti"); - assertEquals(13312L, capacity); - - capacity = pv.getCapacity("Pi"); - assertEquals(13L, capacity); - } - - @Test - public void testGetCapacity() { - pv.setCapacity(13L, MemoryUnit.Pi); - long capacity = pv.getCapacity(); - assertEquals(14636698788954112L, capacity); - } - - @Test - public void testSetCapacity() { - pv.setCapacity(1L, MemoryUnit.Ki); - long capacity = pv.getCapacity(); - assertEquals(1024L, capacity); - - pv.setCapacity(31L, MemoryUnit.Ti); - capacity = pv.getCapacity(MemoryUnit.Ti); - assertEquals(31L, capacity); - } - - @Test(expected = ArithmeticException.class) - public void testSetCapacityOverflow() { - /* - * 2^4 * 2 ^60 = 2^64, LONG_MAX is only 2^64-1 - */ - pv.setCapacity(16L, MemoryUnit.Ei); - pv.getCapacity(); - } - - @Test - public void testGetCapacityUnit() { - pv.setCapacity(1L, MemoryUnit.Ki); - MemoryUnit unit = pv.getCapacityUnit(); - assertEquals(MemoryUnit.Ki, unit); - - pv.setCapacity(1L, MemoryUnit.Pi); - unit = pv.getCapacityUnit(); - assertEquals(MemoryUnit.Pi, unit); - } - - @Test - public void testAccessModes() { - pv.setAccessModes("ReadWriteOnce"); - Set modes = pv.getAccessModes(); - assertTrue(modes.contains("ReadWriteOnce")); - - pv.setAccessModes("ReadWriteOnce", "ReadOnlyMany", "ReadWriteMany"); - modes = pv.getAccessModes(); - Set expected = new HashSet<>(); - expected.addAll(Arrays.asList("ReadWriteOnce", "ReadOnlyMany", "ReadWriteMany")); - assertTrue(modes.containsAll(expected)); - } - - @Test - public void testReclaimPolicy() { - pv.setReclaimPolicy("Recycle"); - String policy = pv.getReclaimPolicy(); - assertEquals(policy, "Recycle"); - } - - @Test - public void testGetPersistentVolumeProperties() { - pv.getPersistentVolumeProperties(); - - } - - @Test - public void testNFSVolume() { - INfsVolumeProperties volume = new NfsVolumeProperties("10.10.10.10", "/tmp/dir", true); - pv.setPersistentVolumeProperties(volume); - volume = (INfsVolumeProperties) pv.getPersistentVolumeProperties(); - assertEquals("/tmp/dir", volume.getPath()); - assertEquals("10.10.10.10", volume.getServer()); - assertEquals(true, volume.isReadOnly()); - } - - @Test - public void testHostPathVolume() { - IHostPathVolumeProperties volume = new HostPathVolumeProperties("/tmp/dir"); - pv.setPersistentVolumeProperties(volume); - volume = (IHostPathVolumeProperties) pv.getPersistentVolumeProperties(); - assertEquals("/tmp/dir", volume.getPath()); - } + private static final String VERSION = "v1"; + private static final Samples sample = Samples.V1_PERSISTENT_VOLUME; + private IPersistentVolume pv; + private IClient client; + + @Before + public void setUp() { + client = mock(IClient.class); + ModelNode node = ModelNode.fromJSONString(sample.getContentAsString()); + pv = new PersistentVolume(node, client, + ResourcePropertiesRegistry.getInstance().get(VERSION, ResourceKind.PERSISTENT_VOLUME)); + } + + @Test + public void testGetCapacityString() { + pv.setCapacity(13L, MemoryUnit.Pi); + long capacity = pv.getCapacity("Ki"); + assertEquals(14293651161088L, capacity); + + capacity = pv.getCapacity("Ti"); + assertEquals(13312L, capacity); + + capacity = pv.getCapacity("Pi"); + assertEquals(13L, capacity); + } + + @Test + public void testGetCapacity() { + pv.setCapacity(13L, MemoryUnit.Pi); + long capacity = pv.getCapacity(); + assertEquals(14636698788954112L, capacity); + } + + @Test + public void testSetCapacity() { + pv.setCapacity(1L, MemoryUnit.Ki); + long capacity = pv.getCapacity(); + assertEquals(1024L, capacity); + + pv.setCapacity(31L, MemoryUnit.Ti); + capacity = pv.getCapacity(MemoryUnit.Ti); + assertEquals(31L, capacity); + } + + @Test(expected = ArithmeticException.class) + public void testSetCapacityOverflow() { + /* + * 2^4 * 2 ^60 = 2^64, LONG_MAX is only 2^64-1 + */ + pv.setCapacity(16L, MemoryUnit.Ei); + pv.getCapacity(); + } + + @Test + public void testGetCapacityUnit() { + pv.setCapacity(1L, MemoryUnit.Ki); + MemoryUnit unit = pv.getCapacityUnit(); + assertEquals(MemoryUnit.Ki, unit); + + pv.setCapacity(1L, MemoryUnit.Pi); + unit = pv.getCapacityUnit(); + assertEquals(MemoryUnit.Pi, unit); + } + + @Test + public void testAccessModes() { + pv.setAccessModes("ReadWriteOnce"); + Set modes = pv.getAccessModes(); + assertTrue(modes.contains("ReadWriteOnce")); + + pv.setAccessModes("ReadWriteOnce", "ReadOnlyMany", "ReadWriteMany"); + modes = pv.getAccessModes(); + Set expected = new HashSet<>(); + expected.addAll(Arrays.asList("ReadWriteOnce", "ReadOnlyMany", "ReadWriteMany")); + assertTrue(modes.containsAll(expected)); + } + + @Test + public void testReclaimPolicy() { + pv.setReclaimPolicy("Recycle"); + String policy = pv.getReclaimPolicy(); + assertEquals(policy, "Recycle"); + } + + @Test + public void testGetPersistentVolumeProperties() { + pv.getPersistentVolumeProperties(); + + } + + @Test + public void testNFSVolume() { + INfsVolumeProperties volume = new NfsVolumeProperties("10.10.10.10", "/tmp/dir", true); + pv.setPersistentVolumeProperties(volume); + volume = (INfsVolumeProperties) pv.getPersistentVolumeProperties(); + assertEquals("/tmp/dir", volume.getPath()); + assertEquals("10.10.10.10", volume.getServer()); + assertEquals(true, volume.isReadOnly()); + } + + @Test + public void testHostPathVolume() { + IHostPathVolumeProperties volume = new HostPathVolumeProperties("/tmp/dir"); + pv.setPersistentVolumeProperties(volume); + volume = (IHostPathVolumeProperties) pv.getPersistentVolumeProperties(); + assertEquals("/tmp/dir", volume.getPath()); + } } diff --git a/src/test/java/com/openshift/internal/restclient/model/v1/PipelineBuildConfigTest.java b/src/test/java/com/openshift/internal/restclient/model/v1/PipelineBuildConfigTest.java new file mode 100644 index 00000000..b973213d --- /dev/null +++ b/src/test/java/com/openshift/internal/restclient/model/v1/PipelineBuildConfigTest.java @@ -0,0 +1,182 @@ +/******************************************************************************* + * Copyright (c) 2017 Red Hat, Inc. Distributed under license by Red Hat, Inc. + * All rights reserved. This program is made available under the terms of the + * Eclipse Public License v1.0 which accompanies this distribution, and is + * available at http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: Red Hat, Inc. + ******************************************************************************/ + +package com.openshift.internal.restclient.model.v1; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.doReturn; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +import java.net.MalformedURLException; +import java.net.URL; +import java.util.Arrays; +import java.util.List; + +import org.jboss.dmr.ModelNode; +import org.junit.Before; +import org.junit.Test; + +import com.openshift.internal.restclient.model.BuildConfig; +import com.openshift.internal.restclient.model.EnvironmentVariable; +import com.openshift.internal.restclient.model.ModelNodeBuilder; +import com.openshift.internal.restclient.model.build.BuildConfigBuilder; +import com.openshift.restclient.IClient; +import com.openshift.restclient.IResourceFactory; +import com.openshift.restclient.ResourceKind; +import com.openshift.restclient.model.IBuildConfig; +import com.openshift.restclient.model.IEnvironmentVariable; +import com.openshift.restclient.model.build.BuildStrategyType; +import com.openshift.restclient.model.build.IBuildConfigBuilder; +import com.openshift.restclient.model.build.IBuildStrategy; +import com.openshift.restclient.model.build.IJenkinsPipelineStrategy; +import com.openshift.restclient.utils.Samples; + +/** + * @author Andre Dietisheim + */ +public class PipelineBuildConfigTest { + + private static final String VERSION = "v1"; + + private IBuildConfig pipelineBc; + private IBuildConfigBuilder builder; + + @Before + public void setup() throws Exception { + this.pipelineBc = createBuildConfig(Samples.V1_BUILDCONFIG_PIPELINE.getContentAsString()); + this.builder = createBuilder(); + } + + private IBuildConfig createBuildConfig(String content) throws MalformedURLException { + IClient client = createClient(); + BuildConfig bc = new BuildConfig(ModelNode.fromJSONString(content), client, null); + IResourceFactory factory = createResourceFactoryFor(bc); + when(client.getResourceFactory()).thenReturn(factory); + return bc; + } + + private IBuildConfigBuilder createBuilder() throws MalformedURLException { + IClient client = createClient(); + IBuildConfig bc = new BuildConfig(new ModelNode(), client, null); + IResourceFactory factory = createResourceFactoryFor(bc); + when(client.getResourceFactory()).thenReturn(factory); + + return new BuildConfigBuilder(client).named("foor").inNamespace("bar"); + } + + private IClient createClient() throws MalformedURLException { + IClient client = mock(IClient.class); + doReturn(new URL("https://localhost:8443")).when(client).getBaseURL(); + doReturn(VERSION).when(client).getOpenShiftAPIVersion(); + return client; + } + + private IResourceFactory createResourceFactoryFor(IBuildConfig bc) { + IResourceFactory factory = mock(IResourceFactory.class); + when(factory.stub(eq(ResourceKind.BUILD_CONFIG), anyString(), anyString())).thenReturn(bc); + return factory; + } + + @Test + public void shouldHaveJenkinsPipelineBuildStrategy() { + // given + // when + IBuildStrategy strategy = pipelineBc.getBuildStrategy(); + // then + assertThat(strategy).isNotNull(); + assertThat(strategy.getType()).isEqualTo(BuildStrategyType.JENKINS_PIPELINE); + } + + @Test + public void shouldHaveJenkinsfile() { + // given + // when + IJenkinsPipelineStrategy strategy = pipelineBc.getBuildStrategy(); + // then + assertThat(strategy.getJenkinsfile()).isNotEmpty(); + } + + @Test + public void shouldHaveJenkinsfileGivenItWasSet() { + // given + IJenkinsPipelineStrategy strategy = pipelineBc.getBuildStrategy(); + // when + strategy.setJenkinsfile("fooBar"); + // then + assertThat(strategy.getJenkinsfile()).isEqualTo("fooBar"); + } + + @Test + public void shouldHaveJenkinsfilePath() { + // given + // when + IJenkinsPipelineStrategy strategy = pipelineBc.getBuildStrategy(); + // then + assertThat(strategy.getJenkinsfilePath()).isNotEmpty(); + } + + @Test + public void shouldHaveJenkinsfilePathGivenItWasSet() { + // given + IJenkinsPipelineStrategy strategy = pipelineBc.getBuildStrategy(); + // when + strategy.setJenkinsfilePath("/foo/bar"); + // then + assertThat(strategy.getJenkinsfilePath()).isEqualTo("/foo/bar"); + } + + @Test + public void shouldHaveEnvVars() { + // given + // when + IJenkinsPipelineStrategy strategy = pipelineBc.getBuildStrategy(); + // then + assertThat(strategy.getEnvVars()).containsOnly( + new EnvironmentVariable(new ModelNodeBuilder().set("name", "foo").set("value", "bar").build(), null), + new EnvironmentVariable(new ModelNodeBuilder().set("name", "kung").set("value", "foo").build(), null)); + } + + @Test + public void shouldHaveEnvVarsThatWereSet() { + // given + IJenkinsPipelineStrategy strategy = pipelineBc.getBuildStrategy(); + IEnvironmentVariable envVar = new EnvironmentVariable( + new ModelNodeBuilder().set("name", "gargamel").set("value", "crazyLad").build(), null); + List envVars = Arrays.asList(envVar); + // when + strategy.setEnvVars(envVars); + // then + assertThat(strategy.getEnvVars()).containsOnly(envVar); + } + + @Test + public void shouldBuildJenkinsPipelineStrategyBuildConfig() { + // given + // when + IBuildConfig bc = builder.usingJenkinsPipelineStrategy().end().build(); + // then + IBuildStrategy strategy = bc.getBuildStrategy(); + assertThat(strategy).isInstanceOf(IJenkinsPipelineStrategy.class); + } + + @Test + public void shouldBuildJenkinsPipelineStrategyWithJenkinsfileAndPath() { + // given + // when + IBuildConfig bc = builder.usingJenkinsPipelineStrategy().usingFile("node('aNode') {}") + .usingFilePath("some/path/to/some/location").end().build(); + // then + IJenkinsPipelineStrategy strategy = bc.getBuildStrategy(); + assertThat(strategy.getJenkinsfile()).isEqualTo("node('aNode') {}"); + assertThat(strategy.getJenkinsfilePath()).isEqualTo("some/path/to/some/location"); + } +} diff --git a/src/test/java/com/openshift/internal/restclient/model/v1/PodTest.java b/src/test/java/com/openshift/internal/restclient/model/v1/PodTest.java index a9256122..f0e85cc7 100644 --- a/src/test/java/com/openshift/internal/restclient/model/v1/PodTest.java +++ b/src/test/java/com/openshift/internal/restclient/model/v1/PodTest.java @@ -6,13 +6,18 @@ * * Contributors: Red Hat, Inc. ******************************************************************************/ + package com.openshift.internal.restclient.model.v1; -import static org.junit.Assert.*; +import static org.assertj.core.api.Assertions.assertThat; +import static org.junit.Assert.assertArrayEquals; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; import static org.mockito.Mockito.mock; import java.util.Collection; import java.util.HashSet; +import java.util.List; import java.util.Optional; import java.util.Set; @@ -20,72 +25,202 @@ import org.junit.Before; import org.junit.Test; +import com.openshift.internal.restclient.model.ExecAction; +import com.openshift.internal.restclient.model.Lifecycle; import com.openshift.internal.restclient.model.Pod; import com.openshift.internal.restclient.model.Port; import com.openshift.internal.restclient.model.properties.ResourcePropertiesRegistry; import com.openshift.restclient.IClient; import com.openshift.restclient.ResourceKind; import com.openshift.restclient.model.IContainer; +import com.openshift.restclient.model.IExecAction; import com.openshift.restclient.model.IPod; import com.openshift.restclient.model.IPort; import com.openshift.restclient.utils.Samples; -/** - * @author Jeff Cantrill - */ public class PodTest { - private static final String VERSION = "v1"; - private IPod pod; - - @Before - public void setup(){ - IClient client = mock(IClient.class); - ModelNode node = ModelNode.fromJSONString(Samples.V1_POD.getContentAsString()); - pod = new Pod(node, client, ResourcePropertiesRegistry.getInstance().get(VERSION, ResourceKind.POD)); - } - - @Test - public void testGetHost(){ - assertEquals("127.0.0.1", pod.getHost()); - } - - @Test - public void testGetStatus(){ - assertEquals("Running", pod.getStatus()); - } - - @Test - public void testGetImages(){ - String [] exp = new String []{"openshift/origin-deployer:v0.6"}; - assertArrayEquals(exp, pod.getImages().toArray()); - } - - @Test - public void getIP() { - assertEquals("1.2.3.4", pod.getIP()); - } - - @Test - public void getContainerPorts() { - Set ports = new HashSet(); - Port port = new Port(new ModelNode()); - port.setName("http"); - port.setProtocol("TCP"); - port.setContainerPort(8080); - ports.add(port); - assertEquals(ports, pod.getContainerPorts()); - } - - @Test - public void testAddContainer() { - Collection initial = pod.getContainers(); - IContainer foo = pod.addContainer("foo"); - foo.setLifecycle("bar"); - Collection containers = pod.getContainers(); - assertEquals(initial.size() + 1, containers.size()); - - Optional container = containers.stream().filter(c->"foo".equals(c.getName()) && "bar".equals(c.getLifecycle())).findFirst(); - assertTrue("Exp. the container to be added", container.isPresent()); - } + private static final String VERSION = "v1"; + + private IClient client; + private IPod pod1; + private IContainer pod1container1; + + private IPod pod2; + + @Before + public void setup() { + this.client = mock(IClient.class); + ModelNode node = ModelNode.fromJSONString(Samples.V1_POD.getContentAsString()); + this.pod1 = createPod(node); + this.pod1container1 = pod1.getContainers().stream().findFirst().orElse(null); + + node = ModelNode.fromJSONString(Samples.V1_POD_MULTICONTAINER_READY.getContentAsString()); + this.pod2 = createPod(node); + } + + @Test + public void testGetHost() { + assertEquals("127.0.0.1", pod1.getHost()); + } + + @Test + public void testGetStatusPhase() { + assertEquals("Running", pod1.getStatus()); + } + + @Test + public void testGetStatusDeletion() { + ((Pod) pod1).getNode().get("metadata", "deletionTimestamp").set("2016-11-02T16:31:55Z"); + assertEquals("Terminating", pod1.getStatus()); + } + + @Test + public void testGetStatusWaitingReason() { + ((Pod) pod1).getNode().get("status", "containerStatuses").asList().get(0).get("state").set("waiting", + new ModelNode().set("reason", "ReasonNotToWork")); + assertEquals("ReasonNotToWork", pod1.getStatus()); + } + + @Test + public void testGetStatusTerminateReason() { + ((Pod) pod1).getNode().get("status", "containerStatuses").asList().get(0).get("state").set("terminated", + new ModelNode().set("reason", "ReasonToTerminate")); + assertEquals("ReasonToTerminate", pod1.getStatus()); + } + + /** + * Check that if both reason and exit code are set, status returns the reason. + */ + @Test + public void testGetStatusTerminateReasonAndExit() { + ModelNode node = new ModelNode(); + node.get("reason").set("ReasonToTerminate"); + node.get("exitCode").set("Let's go! Time to exit!"); + ((Pod) pod1).getNode().get("status", "containerStatuses").asList().get(0).get("state").set("terminated", node); + assertEquals("ReasonToTerminate", pod1.getStatus()); + } + + @Test + public void testGetStatusTerminatedSignal() { + ((Pod) pod1).getNode().get("status", "containerStatuses").asList().get(0).get("state").set("terminated", + new ModelNode().set("signal", "Alarm! Terminate!")); + assertEquals("Signal: Alarm! Terminate!", pod1.getStatus()); + } + + /** + * Check that if both signal and exit code are set, status returns the signal. + */ + @Test + public void testGetStatusTerminatedSignalAndExit() { + ModelNode node = new ModelNode(); + node.get("signal").set("Alarm! Terminate!"); + node.get("exitCode").set("Let's go! Time to exit!"); + ((Pod) pod1).getNode().get("status", "containerStatuses").asList().get(0).get("state").set("terminated", node); + assertEquals("Signal: Alarm! Terminate!", pod1.getStatus()); + } + + @Test + public void testGetStatusTerminatedExit() { + ((Pod) pod1).getNode().get("status", "containerStatuses").asList().get(0).get("state").set("terminated", + new ModelNode().set("exitCode", "Let's go! Time to exit!")); + assertEquals("Exit Code: Let's go! Time to exit!", pod1.getStatus()); + } + + @Test + public void testGetImages() { + String[] exp = new String[] { "openshift/origin-deployer:v0.6" }; + assertArrayEquals(exp, pod1.getImages().toArray()); + } + + @Test + public void getIP() { + assertEquals("1.2.3.4", pod1.getIP()); + } + + @Test + public void getContainerPorts() { + Port port = new Port(new ModelNode()); + port.setName("http"); + port.setProtocol("TCP"); + port.setContainerPort(8080); + Set ports = new HashSet<>(); + ports.add(port); + assertEquals(ports, pod1.getContainerPorts()); + } + + @Test + public void testAddContainer() { + Collection initial = pod1.getContainers(); + IContainer foo = pod1.addContainer("foo"); + + foo.setLifecycle(new Lifecycle.Builder() + .preStop(new ExecAction.Builder().command("cmd1").command("cmd2").build()).build()); + + Collection containers = pod1.getContainers(); + assertEquals(initial.size() + 1, containers.size()); + + Optional container = containers.stream() + .filter(c -> "foo".equals(c.getName()) + && "cmd1".equals(((IExecAction) c.getLifecycle().getPreStop().get()).getCommand().get(0))) + .findFirst(); + assertTrue("Exp. the container to be added", container.isPresent()); + } + + @Test + public void getContainerCommands() { + List cmd = pod1container1.getCommand(); + List cmdArgs = pod1container1.getCommandArgs(); + assertEquals("/bin/sh", cmd.get(0)); + assertEquals("-c", cmdArgs.get(0)); + assertEquals("echo 'hello'", cmdArgs.get(1)); + } + + @Test + public void getContainerResourceRequirements() { + assertEquals("1", pod1container1.getRequestsCPU()); + assertEquals("128Mi", pod1container1.getRequestsMemory()); + assertEquals("4", pod1container1.getLimitsCPU()); + assertEquals("1Gi", pod1container1.getLimitsMemory()); + } + + @Test + public void resetContainerResourceRequirements() { + pod1container1.setRequestsMemory(null); + pod1container1.setRequestsCPU(null); + pod1container1.setLimitsMemory(null); + pod1container1.setLimitsCPU(null); + assertEquals("", pod1container1.getRequestsCPU()); + assertEquals("", pod1container1.getRequestsMemory()); + assertEquals("", pod1container1.getLimitsCPU()); + assertEquals("", pod1container1.getLimitsMemory()); + } + + @Test + public void shouldBeReadyIfAllContainersAreReady() { + assertThat(pod2.isReady()).isTrue(); + } + + @Test + public void shouldNotBeReadyIfAtLeast1ContainerIsNotReady() { + IPod nonReadyPod = setContainerReady(1, false, pod2, client); + + assertThat(nonReadyPod.isReady()).isFalse(); + } + + private IPod setContainerReady(int index, boolean ready, IPod pod, IClient client) { + ModelNode node = ModelNode.fromJSONString(pod.toJson()); + ModelNode podStatusNode = node.get("status"); + ModelNode allContainerStatusNode = podStatusNode.get("containerStatuses"); + assertThat(allContainerStatusNode.isDefined()).isTrue(); + assertThat(allContainerStatusNode.get(index).isDefined()).isTrue();; + ModelNode statusNode = allContainerStatusNode.get(index); + ModelNode readyNode = statusNode.get("ready"); + readyNode.set(ready); + return createPod(node); + } + + private Pod createPod(ModelNode node) { + return new Pod(node, client, ResourcePropertiesRegistry.getInstance().get(VERSION, ResourceKind.POD)); + } } diff --git a/src/test/java/com/openshift/internal/restclient/model/v1/ProjectRequestTest.java b/src/test/java/com/openshift/internal/restclient/model/v1/ProjectRequestTest.java index a7b0ef22..14e1b7a2 100644 --- a/src/test/java/com/openshift/internal/restclient/model/v1/ProjectRequestTest.java +++ b/src/test/java/com/openshift/internal/restclient/model/v1/ProjectRequestTest.java @@ -6,12 +6,12 @@ * * Contributors: Red Hat, Inc. ******************************************************************************/ + package com.openshift.internal.restclient.model.v1; import static org.junit.Assert.assertEquals; import static org.mockito.Mockito.mock; - import org.jboss.dmr.ModelNode; import org.junit.Before; import org.junit.Test; @@ -25,39 +25,39 @@ /** * Test to validate the lookup paths are correct for the version - * @author Jeff Cantrill */ -public class ProjectRequestTest{ - - private static final String VERSION = "v1"; - private IProjectRequest request; - - @Before - public void setUp(){ - IClient client = mock(IClient.class); - ModelNode node = ModelNode.fromJSONString(Samples.V1_PROJECT_REQUEST.getContentAsString()); - request = new OpenshiftProjectRequest(node, client, ResourcePropertiesRegistry.getInstance().get(VERSION, ResourceKind.PROJECT_REQUEST)); - } - - @Test - public void setDisplayName() { - request.setDisplayName("the other display name"); - assertEquals("the other display name", request.getDisplayName()); - } - - @Test - public void testGetDisplayName() { - assertEquals("the display name", request.getDisplayName()); - } - - @Test - public void testGetDescription() { - assertEquals("The project description", request.getDescription()); - } - - @Test - public void testSetDescription() { - request.setDescription("The other project description"); - assertEquals("The other project description", request.getDescription()); - } +public class ProjectRequestTest { + + private static final String VERSION = "v1"; + private IProjectRequest request; + + @Before + public void setUp() { + IClient client = mock(IClient.class); + ModelNode node = ModelNode.fromJSONString(Samples.V1_PROJECT_REQUEST.getContentAsString()); + request = new OpenshiftProjectRequest(node, client, + ResourcePropertiesRegistry.getInstance().get(VERSION, ResourceKind.PROJECT_REQUEST)); + } + + @Test + public void setDisplayName() { + request.setDisplayName("the other display name"); + assertEquals("the other display name", request.getDisplayName()); + } + + @Test + public void testGetDisplayName() { + assertEquals("the display name", request.getDisplayName()); + } + + @Test + public void testGetDescription() { + assertEquals("The project description", request.getDescription()); + } + + @Test + public void testSetDescription() { + request.setDescription("The other project description"); + assertEquals("The other project description", request.getDescription()); + } } \ No newline at end of file diff --git a/src/test/java/com/openshift/internal/restclient/model/v1/ProjectTest.java b/src/test/java/com/openshift/internal/restclient/model/v1/ProjectTest.java index 6e8ef73d..12051100 100644 --- a/src/test/java/com/openshift/internal/restclient/model/v1/ProjectTest.java +++ b/src/test/java/com/openshift/internal/restclient/model/v1/ProjectTest.java @@ -6,12 +6,12 @@ * * Contributors: Red Hat, Inc. ******************************************************************************/ + package com.openshift.internal.restclient.model.v1; import static org.junit.Assert.assertEquals; import static org.mockito.Mockito.mock; - import org.jboss.dmr.ModelNode; import org.junit.Before; import org.junit.Test; @@ -25,27 +25,32 @@ /** * Test to validate the lookup paths are correct for the version - * @author Jeff Cantrill */ -public class ProjectTest{ - - private static final String VERSION = "v1"; - private IProject project; - - @Before - public void setUp(){ - IClient client = mock(IClient.class); - ModelNode node = ModelNode.fromJSONString(Samples.V1_PROJECT.getContentAsString()); - project = new Project(node, client, ResourcePropertiesRegistry.getInstance().get(VERSION, ResourceKind.PROJECT)); - } - - @Test - public void testGetDisplayName() { - assertEquals("OpenShift 3 Sample", project.getDisplayName()); - } - - @Test - public void testGetDescription() { - assertEquals("This is an example project to demonstrate OpenShift v3", project.getDescription()); - } +public class ProjectTest { + + private static final String VERSION = "v1"; + private IProject project; + + @Before + public void setUp() { + IClient client = mock(IClient.class); + ModelNode node = ModelNode.fromJSONString(Samples.V1_PROJECT.getContentAsString()); + project = new Project(node, client, + ResourcePropertiesRegistry.getInstance().get(VERSION, ResourceKind.PROJECT)); + } + + @Test + public void testGetDisplayName() { + assertEquals("OpenShift 3 Sample", project.getDisplayName()); + } + + @Test + public void testGetDescription() { + assertEquals("This is an example project to demonstrate OpenShift v3", project.getDescription()); + } + + @Test + public void testGetStatus() { + assertEquals("Active", project.getStatus()); + } } \ No newline at end of file diff --git a/src/test/java/com/openshift/internal/restclient/model/v1/ReplicationControllerTest.java b/src/test/java/com/openshift/internal/restclient/model/v1/ReplicationControllerTest.java index 7fc0695d..7a6a3563 100644 --- a/src/test/java/com/openshift/internal/restclient/model/v1/ReplicationControllerTest.java +++ b/src/test/java/com/openshift/internal/restclient/model/v1/ReplicationControllerTest.java @@ -6,9 +6,12 @@ * * Contributors: Red Hat, Inc. ******************************************************************************/ + package com.openshift.internal.restclient.model.v1; import static com.openshift.internal.util.JBossDmrExtentions.getPath; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.entry; import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; @@ -17,11 +20,16 @@ import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; -import java.util.*; +import java.util.Arrays; +import java.util.Collection; +import java.util.Collections; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.Set; -import com.openshift.internal.restclient.model.volume.EmptyDirVolumeSource; -import com.openshift.internal.restclient.model.volume.SecretVolumeSource; -import com.openshift.restclient.model.volume.ISecretVolumeSource; import org.jboss.dmr.ModelNode; import org.json.JSONException; import org.junit.Before; @@ -31,6 +39,8 @@ import com.openshift.internal.restclient.model.ModelNodeBuilder; import com.openshift.internal.restclient.model.ReplicationController; import com.openshift.internal.restclient.model.properties.ResourcePropertiesRegistry; +import com.openshift.internal.restclient.model.volume.EmptyDirVolumeSource; +import com.openshift.internal.restclient.model.volume.SecretVolumeSource; import com.openshift.restclient.IClient; import com.openshift.restclient.ResourceKind; import com.openshift.restclient.images.DockerImageURI; @@ -47,276 +57,307 @@ import com.openshift.restclient.model.volume.IVolumeSource; import com.openshift.restclient.utils.Samples; -/** - * @author Jeff Cantrill - */ public class ReplicationControllerTest { - private static final String VERSION = "v1"; - private static IReplicationController rc; - private static ModelNode node; - private static IClient client; - - @Before - public void setup(){ - client = mock(IClient.class); - node = ModelNode.fromJSONString(Samples.V1_REPLICATION_CONTROLLER.getContentAsString()); - rc = new ReplicationController(node, client, ResourcePropertiesRegistry.getInstance().get(VERSION, ResourceKind.REPLICATION_CONTROLLER)); - } - - public void testGetEnvironmentVariablesWithValueFrom() { - - Collection envVars = rc.getEnvironmentVariables(); - - //fieldref - Optional envVar = envVars.stream().filter(e->"OPENSHIFT_KUBE_PING_NAMESPACE".equals(e.getName())).findFirst(); - assertTrue("Exp. to find env var", envVar.isPresent()); - IEnvVarSource from = envVar.get().getValueFrom(); - assertTrue(from instanceof IObjectFieldSelector); - IObjectFieldSelector selector = (IObjectFieldSelector)from; - assertEquals("v1",selector.getApiVersion()); - assertEquals("metadata.namespace",selector.getFieldPath()); - - //configmapkeyref - envVar = envVars.stream().filter(e->"OPENSHIFT_CONFIGMAP_KEY_REF".equals(e.getName())).findFirst(); - assertTrue("Exp. to find env var", envVar.isPresent()); - from = envVar.get().getValueFrom(); - assertTrue(from instanceof IConfigMapKeySelector); - IConfigMapKeySelector configSelector = (IConfigMapKeySelector) from; - assertEquals("xyz",configSelector.getName()); - assertEquals("abc123",configSelector.getKey()); - - //secretkeyref - envVar = envVars.stream().filter(e->"OPENSHIFT_SECRET_KEY_REF".equals(e.getName())).findFirst(); - assertTrue("Exp. to find env var", envVar.isPresent()); - from = envVar.get().getValueFrom(); - assertTrue(from instanceof ISecretKeySelector); - ISecretKeySelector secretKeySelector = (ISecretKeySelector) from; - assertEquals("bar",secretKeySelector.getName()); - assertEquals("foo",secretKeySelector.getKey()); - } - - @Test - public void testEnvironmentVariable() { - //add - rc.setEnvironmentVariable("foo", "bar"); - Collection envVars = rc.getEnvironmentVariables(); - Optional envVar = envVars.stream().filter(e->"foo".equals(e.getName())).findFirst(); - assertTrue("Exp. to find env var", envVar.isPresent()); - assertEquals("bar", envVar.get().getValue()); - - //update - int size = rc.getEnvironmentVariables().size(); - rc.setEnvironmentVariable("foo", "baz"); - assertEquals(size, rc.getEnvironmentVariables().size()); - envVars = rc.getEnvironmentVariables(); - envVar = envVars.stream().filter(e->"foo".equals(e.getName())).findFirst(); - assertEquals("baz", envVar.get().getValue()); - - rc.removeEnvironmentVariable("foo"); - assertEquals(size - 1, rc.getEnvironmentVariables().size()); - } - - @Test - public void testEnvironmentVariableFromMissingEnv() { - String[] path = getPath(ReplicationController.SPEC_TEMPLATE_CONTAINERS); - ModelNode containers = node.get(path); - containers.get(0).remove("env"); - testEnvironmentVariable(); - } - - @Test - public void testEnvironmentVariableForANamedContainer() { - rc.setEnvironmentVariable("ruby-helloworld-database", "fooz", "balls"); - Collection envVars = rc.getEnvironmentVariables("ruby-helloworld-database"); - Optional envVar = envVars.stream().filter(e->"fooz".equals(e.getName())).findFirst(); - assertTrue("Exp. to find env var", envVar.isPresent()); - assertEquals("balls", envVar.get().getValue()); - } - - @Test - public void setReplicaSelector() { - Map exp = new HashMap<>(); - exp.put("foo", "bar"); - rc.setReplicaSelector(exp); - assertEquals(exp, rc.getReplicaSelector()); - } - - @Test - public void setReplicaSelectorFromMissingSelector() { - String[] path = new String[]{"status"}; - node.get(path).clear(); - setReplicaSelector(); - } - - - @Test - public void setReplicaSelectorWithKeyValue() { - Map exp = new HashMap<>(); - exp.put("foo", "bar"); - rc.setReplicaSelector("foo","bar"); - assertEquals(exp, rc.getReplicaSelector()); - } - - @Test - public void getReplicaSelector() { - Map labels = new HashMap<>(); - labels.put("name", "database"); - labels.put("deployment", "database-1"); - labels.put("deploymentconfig", "database"); - assertEquals(labels, rc.getReplicaSelector()); - } - - @Test - public void getDesiredReplicaCount(){ - assertEquals(1, rc.getDesiredReplicaCount()); - } - - @Test - public void setDesiredReplicaCount(){ - rc.setDesiredReplicaCount(9); - assertEquals(9, rc.getDesiredReplicaCount()); - - rc.setReplicas(6); - assertEquals(6, rc.getDesiredReplicaCount()); - } - - @Test - public void getCurrentReplicaCount(){ - assertEquals(2, rc.getCurrentReplicaCount()); - } - - @Test - public void testGetImages(){ - String [] exp = new String []{"openshift/mysql-55-centos7:latest"}; - assertArrayEquals(exp , rc.getImages().toArray()); - } - - @Test - public void testGetContainer() { - assertNull(rc.getContainer(" ")); - assertNotNull(rc.getContainer("ruby-helloworld-database")); - } - @Test - public void testGetContainers() { - Collection containers = rc.getContainers(); - assertNotNull(containers); - assertEquals(1, containers.size()); - - String[] path = getPath(ReplicationController.SPEC_TEMPLATE_CONTAINERS); - node.get(path).clear(); - assertNotNull(rc.getContainers()); - } - - @Test - public void testAddContainer() throws JSONException { - //remove containers hack - String[] path = getPath(ReplicationController.SPEC_TEMPLATE_CONTAINERS); - node.get(path).clear(); - //setup - DockerImageURI uri = new DockerImageURI("aproject/an_image_name"); - IPort port = mock(IPort.class); - when(port.getProtocol()).thenReturn("TCP"); - when(port.getContainerPort()).thenReturn(8080); - Set ports = new HashSet<>(); - ports.add(port); - - IContainer container = rc.addContainer(uri.getName(), uri, ports, new HashMap(), Arrays.asList("/tmp")); - - List containers = node.get(path).asList(); - assertEquals(1, containers.size()); - - ModelNode exp = new ModelNodeBuilder() - .set("name", uri.getName()) - .set("image",uri.toString()) - .add("ports", new ModelNodeBuilder() - .set("containerPort", port.getContainerPort()) - .set("protocol", port.getProtocol()) - ) - .add("volumeMounts", new ModelNodeBuilder() - .set("name", uri.getName() +"-"+1) - .set("mountPath", "/tmp") - .set("readOnly", false) - ) - .build(); - - JSONAssert.assertEquals(exp.toJSONString(false), container.toJSONString(), true); - - Object [] sourceNames = rc.getVolumes().stream().map(IVolumeSource::getName).toArray(); - - Object [] contVolNames = container.getVolumes().stream().map(IVolume::getName).toArray(); - assertArrayEquals(sourceNames,contVolNames); - } - - @Test - public void testAddContainerAllowsContainerToBeFurtherManipulated() throws JSONException{ - //remove containers hack - String[] path = getPath(ReplicationController.SPEC_TEMPLATE_CONTAINERS); - node.get(path).clear(); - - //setup - DockerImageURI uri = new DockerImageURI("arepo/aproject/an_image_name"); - IPort port = mock(IPort.class); - when(port.getProtocol()).thenReturn("TCP"); - when(port.getContainerPort()).thenReturn(8080); - Set ports = new HashSet<>(); - ports.add(port); - - IVolumeMount mount = mock(IVolumeMount.class); - when(mount.getName()).thenReturn(uri.getName() +"-"+1); - when(mount.getMountPath()).thenReturn("/tmp"); - when(mount.isReadOnly()).thenReturn(Boolean.FALSE); - Set mounts = new HashSet<>(); - mounts.add(mount); - - IContainer container = rc.addContainer(uri.getName()); - container.setImage(uri); - container.setPorts(ports); - container.setVolumeMounts(mounts); - - ModelNode exp = new ModelNodeBuilder() - .set("name", uri.getName()) - .set("image",uri.toString()) - .add("ports", new ModelNodeBuilder() - .set("containerPort", port.getContainerPort()) - .set("protocol", port.getProtocol()) - ) - .add("volumeMounts", new ModelNodeBuilder() - .set("name", uri.getName() +"-"+1) - .set("mountPath", "/tmp") - .set("readOnly", false) - ) - .build(); - - JSONAssert.assertEquals(exp.toJSONString(false), container.toJSONString(), true); - } - - @Test - public void testSetVolumes() { - IVolumeSource source = new EmptyDirVolumeSource("myvolume"); - rc.setVolumes(Collections.singleton(source)); - Set volumes = rc.getVolumes(); - assertEquals(1, volumes.size()); - assertEquals("myvolume", volumes.iterator().next().getName()); - } - - @Test - public void testAddSecretVolumeToPodSpec() throws JSONException { - IVolumeMount volumeMount = new IVolumeMount() { - public String getName() { return "my-secret"; } - public String getMountPath() { return "/path/to/my/secret/"; } - public boolean isReadOnly() { return true; } - public void setName(String name) {} - public void setMountPath(String path) {} - public void setReadOnly(boolean readonly) {} - }; - SecretVolumeSource source = new SecretVolumeSource(volumeMount.getName()); - source.setSecretName("the-secret"); - rc.addVolume(source); - Set podSpecVolumes = rc.getVolumes(); - Optional vol = podSpecVolumes.stream() - .filter(v->v.getName().equals(volumeMount.getName())) + private static final String VERSION = "v1"; + private static IReplicationController rc; + private static ModelNode node; + private static IClient client; + + @Before + public void setup() { + client = mock(IClient.class); + node = ModelNode.fromJSONString(Samples.V1_REPLICATION_CONTROLLER.getContentAsString()); + rc = new ReplicationController(node, client, + ResourcePropertiesRegistry.getInstance().get(VERSION, ResourceKind.REPLICATION_CONTROLLER)); + } + + @Test + public void shouldReturnValueFrom_FieldRef() { + Collection envVars = rc.getEnvironmentVariables(); + Optional envVar = envVars.stream() + .filter(e -> "ENV_FIELD_REF".equals(e.getName())) .findFirst(); - assertTrue("Expected to find secret volume in pod spec", vol.isPresent()); - } + assertThat(envVar.isPresent()).isTrue(); + IEnvVarSource from = envVar.get().getValueFrom(); + assertThat(from).isInstanceOf(IObjectFieldSelector.class); + IObjectFieldSelector selector = (IObjectFieldSelector) from; + assertThat(selector.getFieldPath()).isEqualTo("metadata.namespace"); + } + + @Test + public void shouldReturnValueFrom_ConfigMapKeyRef() { + Collection envVars = rc.getEnvironmentVariables(); + Optional envVar = envVars.stream() + .filter(e -> "ENV_CONFIGMAPKEY_REF".equals(e.getName())) + .findFirst(); + assertThat(envVar.isPresent()).isTrue(); + IEnvVarSource from = envVar.get().getValueFrom(); + assertThat(from).isInstanceOf(IConfigMapKeySelector.class); + IConfigMapKeySelector configSelector = (IConfigMapKeySelector) from; + assertThat(configSelector.getName()).isEqualTo("env-config", configSelector.getName()); + assertThat(configSelector.getKey()).isEqualTo("log_level"); + } + + @Test + public void shouldReturnValueFrom_SecretKeyRef() { + Collection envVars = rc.getEnvironmentVariables(); + + Optional envVar = envVars.stream().filter(e -> "ENV_SECRETKEY_REF".equals(e.getName())).findFirst(); + assertThat(envVar.isPresent()).isTrue(); + IEnvVarSource from = envVar.get().getValueFrom(); + assertThat(from).isInstanceOf(ISecretKeySelector.class); + ISecretKeySelector secretKeySelector = (ISecretKeySelector) from; + assertThat(secretKeySelector.getName()).isEqualTo("nodejs-mongo-persistent"); + assertThat(secretKeySelector.getKey()).isEqualTo("database-user"); + } + + @Test + public void testEnvironmentVariable() { + // add + rc.setEnvironmentVariable("foo", "bar"); + Collection envVars = rc.getEnvironmentVariables(); + Optional envVar = envVars.stream().filter(e -> "foo".equals(e.getName())).findFirst(); + assertTrue("Exp. to find env var", envVar.isPresent()); + assertEquals("bar", envVar.get().getValue()); + + // update + int size = rc.getEnvironmentVariables().size(); + rc.setEnvironmentVariable("foo", "baz"); + assertEquals(size, rc.getEnvironmentVariables().size()); + envVars = rc.getEnvironmentVariables(); + envVar = envVars.stream().filter(e -> "foo".equals(e.getName())).findFirst(); + assertEquals("baz", envVar.get().getValue()); + + rc.removeEnvironmentVariable("foo"); + assertEquals(size - 1, rc.getEnvironmentVariables().size()); + } + + @Test + public void testEnvironmentVariableFromMissingEnv() { + String[] path = getPath(ReplicationController.SPEC_TEMPLATE_CONTAINERS); + ModelNode containers = node.get(path); + containers.get(0).remove("env"); + testEnvironmentVariable(); + } + + @Test + public void testEnvironmentVariableForANamedContainer() { + rc.setEnvironmentVariable("ruby-helloworld-database", "fooz", "balls"); + Collection envVars = rc.getEnvironmentVariables("ruby-helloworld-database"); + Optional envVar = envVars.stream().filter(e -> "fooz".equals(e.getName())).findFirst(); + assertTrue("Exp. to find env var", envVar.isPresent()); + assertEquals("balls", envVar.get().getValue()); + } + + @Test + public void setReplicaSelector() { + Map exp = new HashMap<>(); + exp.put("foo", "bar"); + rc.setReplicaSelector(exp); + assertEquals(exp, rc.getReplicaSelector()); + } + + @Test + public void setReplicaSelectorFromMissingSelector() { + String[] path = new String[] { "status" }; + node.get(path).clear(); + setReplicaSelector(); + } + + @Test + public void setReplicaSelectorWithKeyValue() { + Map exp = new HashMap<>(); + exp.put("foo", "bar"); + rc.setReplicaSelector("foo", "bar"); + assertEquals(exp, rc.getReplicaSelector()); + } + + @Test + public void getReplicaSelector() { + Map labels = new HashMap<>(); + labels.put("name", "database"); + labels.put("deployment", "database-1"); + labels.put("deploymentconfig", "database"); + assertEquals(labels, rc.getReplicaSelector()); + } + + @Test + public void getServiceAccountName() { + assertEquals("dbServiceAccountName", rc.getServiceAccountName()); + } + + @Test + public void setServiceAccountName() { + rc.setServiceAccountName("newDBServiceAccountName"); + assertEquals("newDBServiceAccountName", rc.getServiceAccountName()); + } + + @Test + public void getDesiredReplicaCount() { + assertEquals(1, rc.getDesiredReplicaCount()); + } + + @Test + public void setDesiredReplicaCount() { + rc.setDesiredReplicaCount(9); + assertEquals(9, rc.getDesiredReplicaCount()); + + rc.setReplicas(6); + assertEquals(6, rc.getDesiredReplicaCount()); + } + + @Test + public void getCurrentReplicaCount() { + assertEquals(2, rc.getCurrentReplicaCount()); + } + + @Test + public void testGetImages() { + String[] exp = new String[] { "openshift/mysql-55-centos7:latest" }; + assertArrayEquals(exp, rc.getImages().toArray()); + } + + @Test + public void testGetContainer() { + assertNull(rc.getContainer(" ")); + assertNotNull(rc.getContainer("ruby-helloworld-database")); + } + + @Test + public void testGetContainers() { + Collection containers = rc.getContainers(); + assertNotNull(containers); + assertEquals(1, containers.size()); + + String[] path = getPath(ReplicationController.SPEC_TEMPLATE_CONTAINERS); + node.get(path).clear(); + assertNotNull(rc.getContainers()); + } + + @Test + public void testAddContainer() throws JSONException { + // remove containers hack + String[] path = getPath(ReplicationController.SPEC_TEMPLATE_CONTAINERS); + node.get(path).clear(); + // setup + IPort port = mock(IPort.class); + when(port.getProtocol()).thenReturn("TCP"); + when(port.getContainerPort()).thenReturn(8080); + Set ports = new HashSet<>(); + ports.add(port); + DockerImageURI uri = new DockerImageURI("aproject/an_image_name"); + + IContainer container = rc.addContainer(uri.getName(), uri, ports, new HashMap(), + Arrays.asList("/tmp")); + + List containers = node.get(path).asList(); + assertEquals(1, containers.size()); + + ModelNode exp = new ModelNodeBuilder().set("name", uri.getName()).set("image", uri.toString()) + .add("ports", + new ModelNodeBuilder().set("containerPort", port.getContainerPort()).set("protocol", + port.getProtocol())) + .add("volumeMounts", new ModelNodeBuilder().set("name", uri.getName() + "-" + 1) + .set("mountPath", "/tmp").set("readOnly", false)) + .build(); + + JSONAssert.assertEquals(exp.toJSONString(false), container.toJson(), true); + + Object[] sourceNames = rc.getVolumes().stream().map(IVolumeSource::getName).toArray(); + + Object[] contVolNames = container.getVolumes().stream().map(IVolume::getName).toArray(); + assertArrayEquals(sourceNames, contVolNames); + } + + @Test + public void testAddContainerAllowsContainerToBeFurtherManipulated() throws JSONException { + // remove containers hack + String[] path = getPath(ReplicationController.SPEC_TEMPLATE_CONTAINERS); + node.get(path).clear(); + + // setup + IPort port = mock(IPort.class); + when(port.getProtocol()).thenReturn("TCP"); + when(port.getContainerPort()).thenReturn(8080); + Set ports = new HashSet<>(); + ports.add(port); + DockerImageURI uri = new DockerImageURI("arepo/aproject/an_image_name"); + + IVolumeMount mount = mock(IVolumeMount.class); + when(mount.getName()).thenReturn(uri.getName() + "-" + 1); + when(mount.getMountPath()).thenReturn("/tmp"); + when(mount.isReadOnly()).thenReturn(Boolean.FALSE); + Set mounts = new HashSet<>(); + mounts.add(mount); + + IContainer container = rc.addContainer(uri.getName()); + container.setImage(uri); + container.setPorts(ports); + container.setVolumeMounts(mounts); + + IVolumeMount fooVolumeMount = container.addVolumeMount("foobar"); + fooVolumeMount.setMountPath("/tmp2"); + + ModelNode exp = new ModelNodeBuilder().set("name", uri.getName()).set("image", uri.toString()) + .add("ports", + new ModelNodeBuilder().set("containerPort", port.getContainerPort()).set("protocol", + port.getProtocol())) + .add("volumeMounts", + new ModelNodeBuilder().set("name", uri.getName() + "-" + 1).set("mountPath", "/tmp") + .set("readOnly", false)) + .add("volumeMounts", new ModelNodeBuilder().set("name", "foobar").set("mountPath", "/tmp2")).build(); + + JSONAssert.assertEquals(exp.toJSONString(false), container.toJson(), true); + } + + @Test + public void shouldReturnTemplateLabels() { + Map labels = rc.getTemplateLabels(); + assertThat(labels).hasSize(3) + .contains(entry("deployment", "database-1")) + .contains(entry("deploymentconfig", "database")) + .contains(entry("name", "database")); + } + + @Test + public void testSetVolumes() { + IVolumeSource source = new EmptyDirVolumeSource("myvolume"); + rc.setVolumes(Collections.singleton(source)); + Set volumes = rc.getVolumes(); + assertEquals(1, volumes.size()); + assertEquals("myvolume", volumes.iterator().next().getName()); + } + + @Test + public void testAddSecretVolumeToPodSpec() throws JSONException { + IVolumeMount volumeMount = new IVolumeMount() { + public String getName() { + return "my-secret"; + } + + public String getMountPath() { + return "/path/to/my/secret/"; + } + + public boolean isReadOnly() { + return true; + } + + public void setName(String name) { + } + + public void setMountPath(String path) { + } + + public void setReadOnly(boolean readonly) { + } + }; + SecretVolumeSource source = new SecretVolumeSource(volumeMount.getName()); + source.setSecretName("the-secret"); + rc.addVolume(source); + Set podSpecVolumes = rc.getVolumes(); + Optional vol = podSpecVolumes.stream().filter(v -> v.getName().equals(volumeMount.getName())).findFirst(); + assertTrue("Expected to find secret volume in pod spec", vol.isPresent()); + } } diff --git a/src/test/java/com/openshift/internal/restclient/model/v1/ResourceTest.java b/src/test/java/com/openshift/internal/restclient/model/v1/ResourceTest.java index 6a5f3a28..8f606538 100644 --- a/src/test/java/com/openshift/internal/restclient/model/v1/ResourceTest.java +++ b/src/test/java/com/openshift/internal/restclient/model/v1/ResourceTest.java @@ -6,6 +6,7 @@ * * Contributors: Red Hat, Inc. ******************************************************************************/ + package com.openshift.internal.restclient.model.v1; import static org.junit.Assert.assertEquals; @@ -23,34 +24,32 @@ import com.openshift.restclient.model.IResource; import com.openshift.restclient.utils.Samples; -/** - * @author Jeff Cantrill - */ public class ResourceTest { - - private static final String VERSION = "v1"; - private static IResource resource; - - @Before - public void setup(){ - IClient client = mock(IClient.class); - ModelNode node = ModelNode.fromJSONString(Samples.V1_SERVICE.getContentAsString()); - resource = new KubernetesResource(node, client, ResourcePropertiesRegistry.getInstance().get(VERSION, ResourceKind.SERVICE)) {}; - } - - @Test - public void getNamespace(){ - assertEquals("test", resource.getNamespace()); - } - - @Test - public void getNamespaceWhenUndefinedShouldReturnEmptyString(){ - IClient client = mock(IClient.class); - ModelNode node = ModelNode.fromJSONString(Samples.V1_SERVICE.getContentAsString()); - node.get("metadata").remove("namespace"); - resource = new Build(node, client, ResourcePropertiesRegistry.getInstance().get(VERSION, ResourceKind.PROJECT)); - assertEquals("", resource.getNamespace()); - } - - + + private static final String VERSION = "v1"; + private static IResource resource; + + @Before + public void setup() { + IClient client = mock(IClient.class); + ModelNode node = ModelNode.fromJSONString(Samples.V1_SERVICE.getContentAsString()); + resource = new KubernetesResource(node, client, + ResourcePropertiesRegistry.getInstance().get(VERSION, ResourceKind.SERVICE)) { + }; + } + + @Test + public void getNamespace() { + assertEquals("test", resource.getNamespaceName()); + } + + @Test + public void getNamespaceWhenUndefinedShouldReturnEmptyString() { + IClient client = mock(IClient.class); + ModelNode node = ModelNode.fromJSONString(Samples.V1_SERVICE.getContentAsString()); + node.get("metadata").remove("namespace"); + resource = new Build(node, client, ResourcePropertiesRegistry.getInstance().get(VERSION, ResourceKind.PROJECT)); + assertEquals("", resource.getNamespaceName()); + } + } diff --git a/src/test/java/com/openshift/internal/restclient/model/v1/RoleBindingTest.java b/src/test/java/com/openshift/internal/restclient/model/v1/RoleBindingTest.java index 7d5e19b2..6dacbc20 100644 --- a/src/test/java/com/openshift/internal/restclient/model/v1/RoleBindingTest.java +++ b/src/test/java/com/openshift/internal/restclient/model/v1/RoleBindingTest.java @@ -6,9 +6,11 @@ * * Contributors: Red Hat, Inc. ******************************************************************************/ + package com.openshift.internal.restclient.model.v1; -import static org.junit.Assert.*; +import static org.junit.Assert.assertArrayEquals; +import static org.junit.Assert.assertEquals; import static org.mockito.Mockito.mock; import java.util.Arrays; @@ -28,61 +30,59 @@ import com.openshift.restclient.model.authorization.IRoleBinding; import com.openshift.restclient.utils.Samples; -/** - * @author Jeff Cantrill - */ public class RoleBindingTest { - private static final String VERSION = "v1"; - private static IRoleBinding binding; - - @BeforeClass - public static void setup(){ - IClient client = mock(IClient.class); - ModelNode node = ModelNode.fromJSONString(Samples.V1_ROLE_BINDING.getContentAsString()); - binding = new RoleBinding(node, client, ResourcePropertiesRegistry.getInstance().get(VERSION, ResourceKind.ROLE_BINDING)); - } - - @Test - public void testUserNames(){ - Set users = new HashSet<>(Arrays.asList("alpha","beta")); - binding.setUserNames(users); - binding.addUserName("omega"); - - users.add("omega"); - assertArrayEquals(users.toArray(), binding.getUserNames().toArray()); - } - - @Test - public void testGroupNames(){ - Set groups = new HashSet<>(Arrays.asList("phi","zeta")); - binding.setGroupNames(groups); - binding.addGroupName("pi"); - - groups.add("pi"); - assertArrayEquals(groups.toArray(), binding.getGroupNames().toArray()); - } - - @Test - public void testSubjects(){ - ModelNode node = new ModelNode(); - node.get("name").set("bar"); - IObjectReference ref = new ObjectReference(node); - Set subjects = new HashSet<>(); - subjects.add(ref); - - binding.setSubjects(subjects); - - assertArrayEquals(subjects.toArray(), binding.getSubjects().toArray()); - } - - @Test - public void testRoleRefs() { - ModelNode node = new ModelNode(); - node.get("name").set("bar"); - IObjectReference ref = new ObjectReference(node); - binding.setRoleRef(ref); - assertEquals("bar", binding.getRoleRef().getName()); - } - + private static final String VERSION = "v1"; + private static IRoleBinding binding; + + @BeforeClass + public static void setup() { + IClient client = mock(IClient.class); + ModelNode node = ModelNode.fromJSONString(Samples.V1_ROLE_BINDING.getContentAsString()); + binding = new RoleBinding(node, client, + ResourcePropertiesRegistry.getInstance().get(VERSION, ResourceKind.ROLE_BINDING)); + } + + @Test + public void testUserNames() { + Set users = new HashSet<>(Arrays.asList("alpha", "beta")); + binding.setUserNames(users); + binding.addUserName("omega"); + + users.add("omega"); + assertArrayEquals(users.toArray(), binding.getUserNames().toArray()); + } + + @Test + public void testGroupNames() { + Set groups = new HashSet<>(Arrays.asList("phi", "zeta")); + binding.setGroupNames(groups); + binding.addGroupName("pi"); + + groups.add("pi"); + assertArrayEquals(groups.toArray(), binding.getGroupNames().toArray()); + } + + @Test + public void testSubjects() { + ModelNode node = new ModelNode(); + node.get("name").set("bar"); + IObjectReference ref = new ObjectReference(node); + Set subjects = new HashSet<>(); + subjects.add(ref); + + binding.setSubjects(subjects); + + assertArrayEquals(subjects.toArray(), binding.getSubjects().toArray()); + } + + @Test + public void testRoleRefs() { + ModelNode node = new ModelNode(); + node.get("name").set("bar"); + IObjectReference ref = new ObjectReference(node); + binding.setRoleRef(ref); + assertEquals("bar", binding.getRoleRef().getName()); + } + } diff --git a/src/test/java/com/openshift/internal/restclient/model/v1/RouteTest.java b/src/test/java/com/openshift/internal/restclient/model/v1/RouteTest.java index 810f0d2f..a130c662 100644 --- a/src/test/java/com/openshift/internal/restclient/model/v1/RouteTest.java +++ b/src/test/java/com/openshift/internal/restclient/model/v1/RouteTest.java @@ -6,11 +6,13 @@ * * Contributors: Red Hat, Inc. ******************************************************************************/ -package com.openshift.internal.restclient.model.v1; -import static org.junit.Assert.*; -import static org.mockito.Mockito.*; +package com.openshift.internal.restclient.model.v1; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNull; +import static org.mockito.Mockito.mock; import org.jboss.dmr.ModelNode; import org.junit.Before; @@ -22,91 +24,126 @@ import com.openshift.restclient.ResourceKind; import com.openshift.restclient.model.route.IRoute; import com.openshift.restclient.model.route.ITLSConfig; +import com.openshift.restclient.model.route.ITargetPort; import com.openshift.restclient.model.route.TLSTerminationType; import com.openshift.restclient.utils.Samples; /** * Test to validate the lookup paths are correct for the version - * @author Jeff Cantrill */ -public class RouteTest{ - - private static final String VERSION = "v1"; - private static final Samples sample = Samples.V1_ROUTE; - private IRoute route; - private IClient client; - - @Before - public void setUp(){ - client = mock(IClient.class); - ModelNode node = ModelNode.fromJSONString(sample.getContentAsString()); - route = new Route(node, client, ResourcePropertiesRegistry.getInstance().get(VERSION, ResourceKind.ROUTE)); - } - - @Test - public void getTLSConfigWhenUndefined() { - ModelNode node = ModelNode.fromJSONString(Samples.V1_ROUTE_WO_TLS.getContentAsString()); - route = new Route(node, client, ResourcePropertiesRegistry.getInstance().get(VERSION, ResourceKind.ROUTE)); - ITLSConfig tlsConfig = route.getTLSConfig(); - assertNull(tlsConfig); - } - - @Test - public void createTLSConfigWhenUndefined() { - ModelNode node = ModelNode.fromJSONString(Samples.V1_ROUTE_WO_TLS.getContentAsString()); - route = new Route(node, client, ResourcePropertiesRegistry.getInstance().get(VERSION, ResourceKind.ROUTE)); - ITLSConfig tls = route.createTLSConfig(); - assertNotNull(tls); - assertEquals("", tls.getTerminationType()); - assertEquals("", tls.getCertificate()); - assertEquals("", tls.getCACertificate()); - assertEquals("", tls.getKey()); - } - - @Test - public void testGetHost() { - assertEquals("www.example.com", route.getHost()); - } - - @Test - public void testGetPath() { - assertEquals("/abc", route.getPath()); - } - - @Test - public void testGetAndSetPath() { - route.setPath("/def"); - assertEquals("/def", route.getPath()); - } - - @Test - public void getServiceName() throws Exception { - assertEquals("frontend", route.getServiceName()); - } - - @Test - public void setServiceName() throws Exception { - route.setServiceName("frontend-alt"); - assertEquals("frontend-alt", route.getServiceName()); - } - - @Test - public void getTLSConfig() throws Exception { - ITLSConfig tls = route.getTLSConfig(); - assertEquals(TLSTerminationType.EDGE, tls.getTerminationType()); - assertEquals("theCert", tls.getCertificate()); - assertEquals("theCACert", tls.getCACertificate()); - assertEquals("theKey", tls.getKey()); - } - - @Test - public void createTLSConfigWhenAlreadyDefined() throws Exception { - ITLSConfig tls = route.createTLSConfig(); - assertEquals(TLSTerminationType.EDGE, tls.getTerminationType()); - assertEquals("theCert", tls.getCertificate()); - assertEquals("theCACert", tls.getCACertificate()); - assertEquals("theKey", tls.getKey()); - } +public class RouteTest { + + private static final String VERSION = "v1"; + private static final Samples sample = Samples.V1_ROUTE; + private IRoute route; + private IClient client; + + @Before + public void setUp() { + client = mock(IClient.class); + ModelNode node = ModelNode.fromJSONString(sample.getContentAsString()); + route = new Route(node, client, ResourcePropertiesRegistry.getInstance().get(VERSION, ResourceKind.ROUTE)); + } + + @Test + public void getTLSConfigWhenUndefined() { + ModelNode node = ModelNode.fromJSONString(Samples.V1_ROUTE_WO_TLS.getContentAsString()); + route = new Route(node, client, ResourcePropertiesRegistry.getInstance().get(VERSION, ResourceKind.ROUTE)); + ITLSConfig tlsConfig = route.getTLSConfig(); + assertNull(tlsConfig); + } + + @Test + public void createTLSConfigWhenUndefined() { + ModelNode node = ModelNode.fromJSONString(Samples.V1_ROUTE_WO_TLS.getContentAsString()); + route = new Route(node, client, ResourcePropertiesRegistry.getInstance().get(VERSION, ResourceKind.ROUTE)); + ITLSConfig tls = route.createTLSConfig(); + assertNotNull(tls); + assertEquals("", tls.getTerminationType()); + assertEquals("", tls.getCertificate()); + assertEquals("", tls.getCACertificate()); + assertEquals("", tls.getKey()); + } + + @Test + public void getPortWhenUndefined() { + ModelNode node = ModelNode.fromJSONString(Samples.V1_ROUTE_WO_TLS.getContentAsString()); + route = new Route(node, client, ResourcePropertiesRegistry.getInstance().get(VERSION, ResourceKind.ROUTE)); + ITargetPort port = route.getPort(); + assertNull(port); + } + + @Test + public void createPortWhenUndefined() { + ModelNode node = ModelNode.fromJSONString(Samples.V1_ROUTE_WO_TLS.getContentAsString()); + route = new Route(node, client, ResourcePropertiesRegistry.getInstance().get(VERSION, ResourceKind.ROUTE)); + ITargetPort port = route.createPort(); + assertNotNull(port); + assertEquals("", port.getTargetPortName()); + assertEquals(-1, port.getTargetPort().intValue()); + } + + @Test + public void getNumericPortWhenDefined() { + ModelNode node = ModelNode.fromJSONString(Samples.V1_ROUTE_PORT_NUMERIC.getContentAsString()); + route = new Route(node, client, ResourcePropertiesRegistry.getInstance().get(VERSION, ResourceKind.ROUTE)); + ITargetPort port = route.getPort(); + assertNotNull(port); + assertEquals(8080, port.getTargetPort().intValue()); + } + + @Test + public void getNamePortWhenDefined() { + ModelNode node = ModelNode.fromJSONString(Samples.V1_ROUTE_PORT_NAME.getContentAsString()); + route = new Route(node, client, ResourcePropertiesRegistry.getInstance().get(VERSION, ResourceKind.ROUTE)); + ITargetPort port = route.getPort(); + assertNotNull(port); + assertEquals("http-8080", port.getTargetPortName()); + } + + @Test + public void testGetHost() { + assertEquals("www.example.com", route.getHost()); + } + + @Test + public void testGetPath() { + assertEquals("/abc", route.getPath()); + } + + @Test + public void testGetAndSetPath() { + route.setPath("/def"); + assertEquals("/def", route.getPath()); + } + + @Test + public void getServiceName() throws Exception { + assertEquals("frontend", route.getServiceName()); + } + + @Test + public void setServiceName() throws Exception { + route.setServiceName("frontend-alt"); + assertEquals("frontend-alt", route.getServiceName()); + } + + @Test + public void getTLSConfig() throws Exception { + ITLSConfig tls = route.getTLSConfig(); + assertEquals(TLSTerminationType.EDGE, tls.getTerminationType()); + assertEquals("theCert", tls.getCertificate()); + assertEquals("theCACert", tls.getCACertificate()); + assertEquals("theKey", tls.getKey()); + } + @Test + public void createTLSConfigWhenAlreadyDefined() throws Exception { + ITLSConfig tls = route.createTLSConfig(); + assertEquals(TLSTerminationType.EDGE, tls.getTerminationType()); + assertEquals("theCert", tls.getCertificate()); + assertEquals("theCACert", tls.getCACertificate()); + assertEquals("theKey", tls.getKey()); + } } diff --git a/src/test/java/com/openshift/internal/restclient/model/v1/SecretTest.java b/src/test/java/com/openshift/internal/restclient/model/v1/SecretTest.java index bf6d3be1..26191fce 100644 --- a/src/test/java/com/openshift/internal/restclient/model/v1/SecretTest.java +++ b/src/test/java/com/openshift/internal/restclient/model/v1/SecretTest.java @@ -6,15 +6,14 @@ * * Contributors: Red Hat, Inc. ******************************************************************************/ + package com.openshift.internal.restclient.model.v1; import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; import static org.mockito.Mockito.mock; import java.io.ByteArrayInputStream; -import org.apache.commons.lang.StringUtils; import org.jboss.dmr.ModelNode; import org.junit.Before; import org.junit.Test; @@ -28,38 +27,38 @@ /** * Test to validate that Secret object works as expected + * * @author Jiri Pechanec */ -public class SecretTest{ +public class SecretTest { + + private static final String VERSION = "v1"; + private static final Samples sample = Samples.V1_SECRET; + private ISecret secret; - private static final String VERSION = "v1"; - private static final Samples sample = Samples.V1_SECRET; - private ISecret secret; - - @Before - public void setUp() { - IClient client = mock(IClient.class); - ModelNode node = ModelNode.fromJSONString(sample.getContentAsString()); - secret = new Secret(node, client, ResourcePropertiesRegistry.getInstance().get(VERSION, ResourceKind.SECRET)); - } - - @Test - public void testSecretType() { - assertEquals("kubernetes.io/dockercfg", secret.getType()); - } + @Before + public void setUp() { + IClient client = mock(IClient.class); + ModelNode node = ModelNode.fromJSONString(sample.getContentAsString()); + secret = new Secret(node, client, ResourcePropertiesRegistry.getInstance().get(VERSION, ResourceKind.SECRET)); + } - @Test - public void testGetData() { - assertTrue(StringUtils.isNotBlank(new String(secret.getData(".dockercfg")))); - } + @Test + public void testSecretType() { + assertEquals("kubernetes.io/dockercfg", secret.getType()); + } - @Test - public void testAddAndGetData() { - secret.addData("my-key1", "secret word".getBytes()); - secret.addData("my-key2", new ByteArrayInputStream("blah blah".getBytes())); - assertEquals("secret word", new String(secret.getData("my-key1"))); - assertEquals("blah blah", new String(secret.getData("my-key2"))); - } + @Test + public void testGetData() { + assertEquals("value-1", new String(secret.getData(".dockercfg"))); + } + @Test + public void testAddAndGetData() { + secret.addData("my-key1", "secret word".getBytes()); + secret.addData("my-key2", new ByteArrayInputStream("blah blah".getBytes())); + assertEquals("secret word", new String(secret.getData("my-key1"))); + assertEquals("blah blah", new String(secret.getData("my-key2"))); + } } diff --git a/src/test/java/com/openshift/internal/restclient/model/v1/SecretVolumeSourceTest.java b/src/test/java/com/openshift/internal/restclient/model/v1/SecretVolumeSourceTest.java index 11f7d824..a4a07dd0 100644 --- a/src/test/java/com/openshift/internal/restclient/model/v1/SecretVolumeSourceTest.java +++ b/src/test/java/com/openshift/internal/restclient/model/v1/SecretVolumeSourceTest.java @@ -8,17 +8,19 @@ * Contributors: * Red Hat, Inc. - initial API and implementation ******************************************************************************/ + package com.openshift.internal.restclient.model.v1; -import com.openshift.internal.restclient.model.volume.SecretVolumeSource; -import com.openshift.restclient.model.volume.ISecretVolumeSource; -import com.openshift.restclient.utils.Samples; +import static org.hamcrest.CoreMatchers.is; +import static org.hamcrest.MatcherAssert.assertThat; + import org.jboss.dmr.ModelNode; import org.junit.Before; import org.junit.Test; -import static org.hamcrest.CoreMatchers.is; -import static org.junit.Assert.assertThat; +import com.openshift.internal.restclient.model.volume.SecretVolumeSource; +import com.openshift.restclient.model.volume.ISecretVolumeSource; +import com.openshift.restclient.utils.Samples; /** * @author Ulf Lilleengen diff --git a/src/test/java/com/openshift/internal/restclient/model/v1/ServiceAccountTest.java b/src/test/java/com/openshift/internal/restclient/model/v1/ServiceAccountTest.java index 9ad7efe0..5299328e 100644 --- a/src/test/java/com/openshift/internal/restclient/model/v1/ServiceAccountTest.java +++ b/src/test/java/com/openshift/internal/restclient/model/v1/ServiceAccountTest.java @@ -6,78 +6,80 @@ * * Contributors: Red Hat, Inc. ******************************************************************************/ + package com.openshift.internal.restclient.model.v1; +import static org.junit.Assert.assertArrayEquals; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; +import static org.mockito.Mockito.mock; + +import org.jboss.dmr.ModelNode; +import org.junit.Before; +import org.junit.Test; + import com.openshift.internal.restclient.model.ServiceAccount; import com.openshift.internal.restclient.model.properties.ResourcePropertiesRegistry; import com.openshift.restclient.IClient; import com.openshift.restclient.ResourceKind; import com.openshift.restclient.model.serviceaccount.IServiceAccount; import com.openshift.restclient.utils.Samples; -import org.jboss.dmr.ModelNode; -import org.junit.Before; -import org.junit.Test; - -import static org.junit.Assert.assertArrayEquals; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; -import static org.mockito.Mockito.mock; /** * @author David Simansky | dsimansk@redhat.com */ public class ServiceAccountTest { - private static final String VERSION = "v1"; - private static final Samples sample = Samples.V1_SERVICE_ACCOUNT; - private IServiceAccount serviceAccount; - - @Before - public void setUp() { - IClient client = mock(IClient.class); - ModelNode node = ModelNode.fromJSONString(sample.getContentAsString()); - serviceAccount = new ServiceAccount(node, client, ResourcePropertiesRegistry.getInstance().get(VERSION, - ResourceKind.SERVICE_ACCOUNT)); - } - - @Test - public void testGetSecrets() { - String[] expSecrets = new String []{"deployer-token-luifi", "deployer-dockercfg-jq62e"}; - assertArrayEquals(expSecrets, serviceAccount.getSecrets().toArray()); - } + private static final String VERSION = "v1"; + private static final Samples sample = Samples.V1_SERVICE_ACCOUNT; + private IServiceAccount serviceAccount; + + @Before + public void setUp() { + IClient client = mock(IClient.class); + ModelNode node = ModelNode.fromJSONString(sample.getContentAsString()); + serviceAccount = new ServiceAccount(node, client, + ResourcePropertiesRegistry.getInstance().get(VERSION, ResourceKind.SERVICE_ACCOUNT)); + } + + @Test + public void testGetSecrets() { + String[] expSecrets = new String[] { "deployer-token-luifi", "deployer-dockercfg-jq62e" }; + assertArrayEquals(expSecrets, serviceAccount.getSecrets().toArray()); + } - @Test - public void testGetImagePullSecrets() { - String[] expSecrets = new String []{"deployer-dockercfg-jq62e"}; - assertArrayEquals(expSecrets, serviceAccount.getImagePullSecrets().toArray()); - } + @Test + public void testGetImagePullSecrets() { + String[] expSecrets = new String[] { "deployer-dockercfg-jq62e" }; + assertArrayEquals(expSecrets, serviceAccount.getImagePullSecrets().toArray()); + } - @Test - public void testAddSecret() { - serviceAccount.addSecret("my-test-secret"); - assertEquals(3, serviceAccount.getSecrets().size()); - assertTrue(serviceAccount.getSecrets().contains("my-test-secret")); - } + @Test + public void testAddSecret() { + serviceAccount.addSecret("my-test-secret"); + assertEquals(3, serviceAccount.getSecrets().size()); + assertTrue(serviceAccount.getSecrets().contains("my-test-secret")); + } - @Test - public void testAddNullSecret() { - serviceAccount.addSecret(null); - assertEquals(3, serviceAccount.getSecrets().size()); - assertTrue(serviceAccount.getSecrets().contains("")); - } + @Test + public void testAddNullSecret() { + serviceAccount.addSecret(null); + assertEquals(3, serviceAccount.getSecrets().size()); + assertTrue(serviceAccount.getSecrets().contains("")); + } - @Test - public void testAddImagePullSecret() { - serviceAccount.addImagePullSecret("my-test-secret"); - assertEquals(2, serviceAccount.getImagePullSecrets().size()); - assertTrue(serviceAccount.getImagePullSecrets().contains("my-test-secret")); - } + @Test + public void testAddImagePullSecret() { + serviceAccount.addImagePullSecret("my-test-secret"); + assertEquals(2, serviceAccount.getImagePullSecrets().size()); + assertTrue(serviceAccount.getImagePullSecrets().contains("my-test-secret")); + } - @Test - public void testAddNullImagePullSecret() { - serviceAccount.addImagePullSecret(null); - assertEquals(2, serviceAccount.getImagePullSecrets().size()); - assertTrue(serviceAccount.getImagePullSecrets().contains("")); - } + @Test + public void testAddNullImagePullSecret() { + serviceAccount.addImagePullSecret(null); + assertEquals(2, serviceAccount.getImagePullSecrets().size()); + assertTrue(serviceAccount.getImagePullSecrets().contains("")); + } } diff --git a/src/test/java/com/openshift/internal/restclient/model/v1/ServiceTest.java b/src/test/java/com/openshift/internal/restclient/model/v1/ServiceTest.java index 70fd55fe..fec2e086 100644 --- a/src/test/java/com/openshift/internal/restclient/model/v1/ServiceTest.java +++ b/src/test/java/com/openshift/internal/restclient/model/v1/ServiceTest.java @@ -6,6 +6,7 @@ * * Contributors: Red Hat, Inc. ******************************************************************************/ + package com.openshift.internal.restclient.model.v1; import static org.junit.Assert.assertEquals; @@ -30,102 +31,121 @@ /** * Test to validate the lookup paths are correct for the version - * @author Jeff Cantrill */ -public class ServiceTest{ - - private static final String VERSION = "v1"; - private IService service; - - @Before - public void setUp(){ - IClient client = mock(IClient.class); - ModelNode node = ModelNode.fromJSONString(Samples.V1_SERVICE.getContentAsString()); - service = new Service(node, client, ResourcePropertiesRegistry.getInstance().get(VERSION, ResourceKind.SERVICE)); - } - - @Test - public void testGetPortalIP() { - assertEquals("172.30.57.114", service.getPortalIP()); - } - - @Test - public void testGetTargetPort() { - assertEquals("3306", service.getTargetPort()); - } - - @Test - public void testSetTargetPort() { - service.setTargetPort(5030); - assertEquals("5030", service.getTargetPort()); - } - - @Test - public void testGetPort() { - assertEquals(5434, service.getPort()); - } - - @Test - public void testSetPort() { - service.setPort(5055); - assertEquals(5055, service.getPort()); - } - - @Test - public void testGetSelector() { - Map selector = new HashMap(); - selector.put("name", "database"); - assertEquals(selector, service.getSelector()); - } - - @Test - public void testSetSelectorSimple() { - Map selector = new HashMap(); - selector.put("name", "myselector"); - service.setSelector("name","myselector"); - assertEquals(selector, service.getSelector()); - } - - @Test - public void testGetName() { - assertEquals("database", service.getName()); - } - - @Test - public void testSetName() { - ((Service) service).setName("hello-openshift"); - assertEquals("hello-openshift", service.getName()); - } - - @Test - public void testGetNamespace() { - assertEquals("test", service.getNamespace()); - } - - @Test - public void testSetNamespace() { - // pre-condition - // operation - ((Service) service).setNamespace("foo"); - // verification - assertEquals("foo", service.getNamespace()); - } - - @Test - public void testGetPorts() { - IServicePort [] ports = service.getPorts().toArray(new IServicePort[] {}); - assertEquals(2, ports.length); - assertEquals(PortFactory.createServicePort("db", "TCP", 5434, 3306), ports[0]); - assertEquals(PortFactory.createServicePort("other", "TCP", 9999, 8888), ports[1]); - } - - @Test - public void testSetPorts() { - IServicePort port = PortFactory.createServicePort("newport", "TCP", 4444, 5555); - service.setPorts(Arrays.asList(port)); - IServicePort [] ports = service.getPorts().toArray(new IServicePort[] {}); - assertEquals(1, service.getPorts().size()); - assertEquals(port, ports[0]); - } - +public class ServiceTest { + + private static final String VERSION = "v1"; + private IService service; + + @Before + public void setUp() { + IClient client = mock(IClient.class); + ModelNode node = ModelNode.fromJSONString(Samples.V1_SERVICE.getContentAsString()); + service = new Service(node, client, + ResourcePropertiesRegistry.getInstance().get(VERSION, ResourceKind.SERVICE)); + } + + @Test + public void testGetPortalIP() { + assertEquals("172.30.57.114", service.getPortalIP()); + } + + @Test + public void testGetClusterIP() { + assertEquals("172.30.57.114", service.getClusterIP()); + } + + @Test + public void testGetTargetPort() { + assertEquals("3306", service.getTargetPort()); + } + + @Test + public void testSetTargetPort() { + service.setTargetPort(5030); + assertEquals("5030", service.getTargetPort()); + } + + @Test + public void testGetPort() { + assertEquals(5434, service.getPort()); + } + + @Test + public void testSetPort() { + service.setPort(5055); + assertEquals(5055, service.getPort()); + } + + @Test + public void testGetSelector() { + Map selector = new HashMap(); + selector.put("name", "database"); + assertEquals(selector, service.getSelector()); + } + + @Test + public void testSetSelectorSimple() { + Map selector = new HashMap(); + selector.put("name", "myselector"); + service.setSelector("name", "myselector"); + assertEquals(selector, service.getSelector()); + } + + @Test + public void testGetName() { + assertEquals("database", service.getName()); + } + + @Test + public void testSetName() { + ((Service) service).setName("hello-openshift"); + assertEquals("hello-openshift", service.getName()); + } + + @Test + public void testGetNamespace() { + assertEquals("test", service.getNamespaceName()); + } + + @Test + public void testSetNamespace() { + // pre-condition + // operation + ((Service) service).setNamespace("foo"); + // verification + assertEquals("foo", service.getNamespaceName()); + } + + @Test + public void testGetPorts() { + IServicePort[] ports = service.getPorts().toArray(new IServicePort[] {}); + assertEquals(2, ports.length); + assertEquals(PortFactory.createServicePort("db", "TCP", 5434, 3306,45678), ports[0]); + assertEquals(PortFactory.createServicePort("other", "TCP", 9999, 8888,56789), ports[1]); + } + + @Test + public void testSetPorts() { + IServicePort port = PortFactory.createServicePort("newport", "TCP", 4444, 5555,6666); + service.setPorts(Arrays.asList(port)); + IServicePort[] ports = service.getPorts().toArray(new IServicePort[] {}); + assertEquals(1, service.getPorts().size()); + assertEquals(port, ports[0]); + } + + @Test + public void testAddPorts() { + IServicePort port = service.addPort(8299, 9299, "testport"); + service.setPorts(Arrays.asList(port)); + IServicePort[] ports = service.getPorts().toArray(new IServicePort[] {}); + assertEquals(1, service.getPorts().size()); + assertEquals(port, ports[0]); + } + + @Test + public void testSetType() { + service.setType("NodePort"); + assertEquals("NodePort", service.getType()); + } } diff --git a/src/test/java/com/openshift/internal/restclient/model/v1/StatusTest.java b/src/test/java/com/openshift/internal/restclient/model/v1/StatusTest.java index 22b705ae..f4c36a12 100644 --- a/src/test/java/com/openshift/internal/restclient/model/v1/StatusTest.java +++ b/src/test/java/com/openshift/internal/restclient/model/v1/StatusTest.java @@ -6,10 +6,11 @@ * * Contributors: Red Hat, Inc. ******************************************************************************/ + package com.openshift.internal.restclient.model.v1; -import static org.junit.Assert.*; -import static org.mockito.Mockito.*; +import static org.junit.Assert.assertEquals; +import static org.mockito.Mockito.mock; import org.jboss.dmr.ModelNode; import org.junit.BeforeClass; @@ -24,32 +25,31 @@ /** * Test to validate the lookup paths are correct for the version - * @author Jeff Cantrill */ -public class StatusTest{ - - private static final String VERSION = "v1"; - private static IStatus status; - - @BeforeClass - public static void setUp(){ - IClient client = mock(IClient.class); - ModelNode node = ModelNode.fromJSONString(Samples.V1_Status.getContentAsString()); - status = new Status(node, client, ResourcePropertiesRegistry.getInstance().get(VERSION, ResourceKind.STATUS)); - } - - @Test - public void testGetMessage() { - assertEquals("Unable to determine kind and namespace from url, /osapi/users", status.getMessage()); - } - - @Test - public void testGetCode() { - assertEquals(403, status.getCode()); - } - - @Test - public void testGetStatus() { - assertEquals("Failure", status.getStatus()); - } +public class StatusTest { + + private static final String VERSION = "v1"; + private static IStatus status; + + @BeforeClass + public static void setUp() { + IClient client = mock(IClient.class); + ModelNode node = ModelNode.fromJSONString(Samples.V1_Status.getContentAsString()); + status = new Status(node, client, ResourcePropertiesRegistry.getInstance().get(VERSION, ResourceKind.STATUS)); + } + + @Test + public void testGetMessage() { + assertEquals("Unable to determine kind and namespace from url, /osapi/users", status.getMessage()); + } + + @Test + public void testGetCode() { + assertEquals(403, status.getCode()); + } + + @Test + public void testGetStatus() { + assertEquals("Failure", status.getStatus()); + } } diff --git a/src/test/java/com/openshift/internal/restclient/model/v1/TemplateTest.java b/src/test/java/com/openshift/internal/restclient/model/v1/TemplateTest.java index 6e9581cc..8e8dd5cb 100644 --- a/src/test/java/com/openshift/internal/restclient/model/v1/TemplateTest.java +++ b/src/test/java/com/openshift/internal/restclient/model/v1/TemplateTest.java @@ -6,10 +6,14 @@ * * Contributors: Red Hat, Inc. ******************************************************************************/ + package com.openshift.internal.restclient.model.v1; -import static org.junit.Assert.*; -import static org.mockito.Mockito.*; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; import java.util.Map; @@ -27,53 +31,54 @@ /** * Test to validate the lookup paths are correct for the version * - * @author Jeff Cantrill */ -public class TemplateTest{ +public class TemplateTest { + + private static final String VERSION = "v1"; + private ITemplate template; + + @Before + public void setUp() { + IClient client = mock(IClient.class); + when(client.getResourceFactory()).thenReturn(new ResourceFactory(client) { + }); + ModelNode node = ModelNode.fromJSONString(Samples.V1_TEMPLATE.getContentAsString()); + template = new Template(node, client, null); + } + + @Test + public void testGetApiVersion() { + assertEquals(VERSION, template.getApiVersion()); + } - private static final String VERSION = "v1"; - private ITemplate template; - - @Before - public void setUp(){ - IClient client = mock(IClient.class); - when(client.getResourceFactory()).thenReturn(new ResourceFactory(client){}); - ModelNode node = ModelNode.fromJSONString(Samples.V1_TEMPLATE.getContentAsString()); - template = new Template(node, client, null); - } - @Test - public void testGetApiVersion() { - assertEquals(VERSION, template.getApiVersion()); - } + @Test + public void testGetItems() { + assertEquals("Exp. the number of items to be more than zero", 8, template.getObjects().size()); + } - @Test - public void testGetItems() { - assertEquals("Exp. the number of items to be more than zero", 8, template.getItems().size()); - } + @Test + public void testGetParameters() { + Map parameters = template.getParameters(); + assertEquals("Exp. the number of items to be more than zero", 5, parameters.size()); + IParameter param = parameters.get("MYSQL_PASSWORD"); + assertNotNull(param); + assertEquals("", param.getValue()); + assertEquals("[a-zA-Z0-9]{8}", param.getFrom()); + assertEquals("expression", param.getGeneratorName()); + assertEquals("database password", param.getDescription()); + assertTrue("required", param.isRequired()); + } - @Test - public void testGetParameters() { - Map parameters = template.getParameters(); - assertEquals("Exp. the number of items to be more than zero",5, parameters.size()); - IParameter param = parameters.get("MYSQL_PASSWORD"); - assertNotNull(param); - assertEquals("",param.getValue()); - assertEquals("[a-zA-Z0-9]{8}",param.getFrom()); - assertEquals("expression",param.getGeneratorName()); - assertEquals("database password",param.getDescription()); - assertTrue("required", param.isRequired()); - } - - @Test - public void testGetLabels() { - assertEquals("Exp. to retrieve the labels",2, template.getLabels().size()); - assertEquals("bar", template.getLabels().get("foo")); - } + @Test + public void testGetLabels() { + assertEquals("Exp. to retrieve the labels", 2, template.getLabels().size()); + assertEquals("bar", template.getLabels().get("foo")); + } - @Test - public void testGetObjectLabels() { - assertEquals("Exp. to retrieve the object labels",1, template.getObjectLabels().size()); - assertEquals("application-template-stibuild", template.getObjectLabels().get("template")); - } + @Test + public void testGetObjectLabels() { + assertEquals("Exp. to retrieve the object labels", 1, template.getObjectLabels().size()); + assertEquals("application-template-stibuild", template.getObjectLabels().get("template")); + } } diff --git a/src/test/java/com/openshift/internal/restclient/model/v1/UnrecognizedResourceTest.java b/src/test/java/com/openshift/internal/restclient/model/v1/UnrecognizedResourceTest.java index 8202cbec..80367700 100644 --- a/src/test/java/com/openshift/internal/restclient/model/v1/UnrecognizedResourceTest.java +++ b/src/test/java/com/openshift/internal/restclient/model/v1/UnrecognizedResourceTest.java @@ -6,6 +6,7 @@ * * Contributors: Red Hat, Inc. ******************************************************************************/ + package com.openshift.internal.restclient.model.v1; import static org.junit.Assert.assertEquals; @@ -21,31 +22,30 @@ /** * Test to validate the lookup paths are correct for the version - * @author Jeff Cantrill */ -public class UnrecognizedResourceTest{ - - private IResource service; - - @Before - public void setUp(){ - IClient client = mock(IClient.class); - service = new ResourceFactory(client).create(Samples.V1_UNRECOGNIZED.getContentAsString(), false); - } - - @Test - public void testGetName() { - assertEquals("database", service.getName()); - } - - @Test - public void testGetNamespace() { - assertEquals("test", service.getNamespace()); - } - - @Test - public void testGetKind() { - assertEquals("IMadeThisOneUp", service.getKind()); - } +public class UnrecognizedResourceTest { + + private IResource service; + + @Before + public void setUp() { + IClient client = mock(IClient.class); + service = new ResourceFactory(client).create(Samples.V1_UNRECOGNIZED.getContentAsString()); + } + + @Test + public void testGetName() { + assertEquals("database", service.getName()); + } + + @Test + public void testGetNamespace() { + assertEquals("test", service.getNamespaceName()); + } + + @Test + public void testGetKind() { + assertEquals("IMadeThisOneUp", service.getKind()); + } } diff --git a/src/test/java/com/openshift/internal/restclient/model/v1/UserTest.java b/src/test/java/com/openshift/internal/restclient/model/v1/UserTest.java index b52ed6d2..15fb0ce0 100644 --- a/src/test/java/com/openshift/internal/restclient/model/v1/UserTest.java +++ b/src/test/java/com/openshift/internal/restclient/model/v1/UserTest.java @@ -6,10 +6,13 @@ * * Contributors: Red Hat, Inc. ******************************************************************************/ + package com.openshift.internal.restclient.model.v1; -import static org.junit.Assert.*; -import static org.mockito.Mockito.*; +import static org.junit.Assert.assertEquals; +import static org.mockito.Mockito.mock; + +import java.util.HashSet; import org.jboss.dmr.ModelNode; import org.junit.Before; @@ -24,22 +27,43 @@ /** * Test to validate the lookup paths are correct for the version - * @author Jeff Cantrill */ -public class UserTest{ - - private static final String VERSION = "v1"; - private IUser resource; - - @Before - public void setUp(){ - IClient client = mock(IClient.class); - ModelNode node = ModelNode.fromJSONString(Samples.V1_USER.getContentAsString()); - resource = new OpenShiftUser(node, client, ResourcePropertiesRegistry.getInstance().get(VERSION, ResourceKind.USER)); - } - - @Test - public void testFullName() { - assertEquals("Foo Master", resource.getFullName()); - } +public class UserTest { + + private static final String VERSION = "v1"; + private IUser user; + + @Before + public void setUp() { + IClient client = mock(IClient.class); + ModelNode node = ModelNode.fromJSONString(Samples.V1_USER.getContentAsString()); + user = new OpenShiftUser(node, client, + ResourcePropertiesRegistry.getInstance().get(VERSION, ResourceKind.USER)); + } + + @Test + public void testFullName() { + assertEquals("Foo Master", user.getFullName()); + } + + @Test + public void testUid() { + assertEquals("94b42e96-0faa-11e5-9467-080027893417", user.getUID()); + } + + @Test + public void testIdentities() { + HashSet identities = new HashSet<>(1); + identities.add("anypassword:test-admin"); + + assertEquals(identities, user.getIdentities()); + } + + @Test + public void testGroups() { + HashSet groups = new HashSet<>(1); + groups.add("test-group"); + + assertEquals(groups, user.getGroups()); + } } diff --git a/src/test/java/com/openshift/internal/restclient/okhttp/BasicChallangeHandlerTest.java b/src/test/java/com/openshift/internal/restclient/okhttp/BasicChallangeHandlerTest.java new file mode 100644 index 00000000..d7f2aeee --- /dev/null +++ b/src/test/java/com/openshift/internal/restclient/okhttp/BasicChallangeHandlerTest.java @@ -0,0 +1,79 @@ +/******************************************************************************* + * Copyright (c) 2016 Red Hat, Inc. + * Distributed under license by Red Hat, Inc. All rights reserved. + * This program is made available under the terms of the + * Eclipse Public License v1.0 which accompanies this distribution, + * and is available at http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Red Hat, Inc. - initial API and implementation + ******************************************************************************/ + +package com.openshift.internal.restclient.okhttp; + +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; +import static org.mockito.Mockito.when; + +import org.apache.commons.lang.StringUtils; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.Mock; +import org.mockito.junit.MockitoJUnitRunner; + +import com.openshift.restclient.authorization.IAuthorizationContext; +import com.openshift.restclient.http.IHttpConstants; + +import okhttp3.Headers; +import okhttp3.Request; +import okhttp3.Request.Builder; + +@RunWith(MockitoJUnitRunner.class) +public class BasicChallangeHandlerTest { + + @Mock + private IAuthorizationContext context; + private BasicChallengeHandler handler; + + @Before + public void setUp() throws Exception { + this.handler = new BasicChallengeHandler(context); + + when(context.getUserName()).thenReturn("username"); + when(context.getPassword()).thenReturn("password"); + } + + @Test + public void testCanHandle() { + assertTrue(handler.canHandle(givenHeader(IHttpConstants.PROPERTY_WWW_AUTHENTICATE, "basic"))); + assertTrue(handler.canHandle(givenHeader(IHttpConstants.PROPERTY_WWW_AUTHENTICATE, "bAsIC"))); + assertTrue(handler.canHandle(givenHeader(IHttpConstants.PROPERTY_WWW_AUTHENTICATE, "Basic realm=\"WallyWorld\""))); + assertFalse(handler.canHandle(givenHeader(IHttpConstants.PROPERTY_WWW_AUTHENTICATE, "foobar"))); + assertFalse(handler.canHandle(givenHeader(IHttpConstants.PROPERTY_WWW_AUTHENTICATE, ""))); + assertFalse(handler.canHandle(givenHeader("key", "value"))); + } + + @Test + public void testHandleChallange() { + Builder builder = new Request.Builder().url("http://foo"); + Request request = handler.handleChallenge(builder).build(); + String authorization = request.header(IHttpConstants.PROPERTY_AUTHORIZATION); + assertTrue("Exp. auth to not be blank", StringUtils.isNotBlank(authorization)); + assertTrue("Exp. auth to be basic", authorization.startsWith(IHttpConstants.AUTHORIZATION_BASIC)); + } + + @Test + public void testHandleChallangeWhenUsernameIsNull() { + when(context.getUserName()).thenReturn(null); + Builder builder = new Request.Builder().url("http://foo"); + Request request = handler.handleChallenge(builder).build(); + String authorization = request.header(IHttpConstants.PROPERTY_AUTHORIZATION); + assertTrue("Exp. auth to not be blank", StringUtils.isNotBlank(authorization)); + assertTrue("Exp. auth to be basic", authorization.startsWith(IHttpConstants.AUTHORIZATION_BASIC)); + } + + private Headers givenHeader(String name, String value) { + return new Headers.Builder().add(name, value).build(); + } +} diff --git a/src/test/java/com/openshift/internal/restclient/okhttp/ClientProxyConnectionTest.java b/src/test/java/com/openshift/internal/restclient/okhttp/ClientProxyConnectionTest.java new file mode 100644 index 00000000..f4171895 --- /dev/null +++ b/src/test/java/com/openshift/internal/restclient/okhttp/ClientProxyConnectionTest.java @@ -0,0 +1,127 @@ +/******************************************************************************* + * Copyright (c) 2015 Red Hat, Inc. + * Distributed under license by Red Hat, Inc. All rights reserved. + * This program is made available under the terms of the + * Eclipse Public License v1.0 which accompanies this distribution, + * and is available at http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Red Hat, Inc. - initial API and implementation + ******************************************************************************/ + +package com.openshift.internal.restclient.okhttp; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotSame; +import static org.junit.Assert.assertNull; + +import java.io.IOException; +import java.lang.reflect.Field; +import java.net.InetSocketAddress; +import java.net.Proxy; +import java.net.ProxySelector; +import java.net.SocketAddress; +import java.net.URI; +import java.util.ArrayList; +import java.util.List; + +import org.junit.Test; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.openshift.internal.restclient.DefaultClient; +import com.openshift.restclient.ClientBuilder; + +import okhttp3.OkHttpClient; + +/** + * @author Vlad Slepukhin + */ +public class ClientProxyConnectionTest { + + private static final Logger LOG = LoggerFactory.getLogger(ClientProxyConnectionTest.class); + + + private static final String OPENSHIFT_URL = "https://openshift.test.com"; + private static final String PROXY_HOST = "127.0.0.1"; + private static final int PROXY_PORT = 8080; + + private class TestProxySelector extends ProxySelector { + + @Override + public List select(URI uri) { + List result = new ArrayList<>(); + result.add(new Proxy(Proxy.Type.HTTP, new InetSocketAddress(PROXY_HOST, PROXY_PORT))); + return result; + } + + @Override + public void connectFailed(URI uri, SocketAddress sa, IOException ioe) { + } + } + + @Test + public void testProxySetInOkHttp() throws NoSuchFieldException, IllegalAccessException { + Proxy expectedProxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(PROXY_HOST, PROXY_PORT)); + DefaultClient client = (DefaultClient) new ClientBuilder(OPENSHIFT_URL) + .proxy(expectedProxy) + .build(); + + OkHttpClient okClient = getOkHttpClient(client); + Proxy proxyInOkClient = okClient.proxy(); + + LOG.info(proxyInOkClient.toString()); + + assertEquals(expectedProxy.type(), proxyInOkClient.type()); + assertEquals(expectedProxy.address(), proxyInOkClient.address()); + } + + @Test + public void testProxyNotSetInOkHttp() throws NoSuchFieldException, IllegalAccessException { + DefaultClient client = (DefaultClient) new ClientBuilder(OPENSHIFT_URL) + .build(); + + OkHttpClient okClient = getOkHttpClient(client); + Proxy proxyInOkClient = okClient.proxy(); + + assertNull(proxyInOkClient); + } + + @Test + public void testProxySelectorSetInOkHttp() throws NoSuchFieldException, IllegalAccessException { + ProxySelector expectedSelector = new TestProxySelector(); + DefaultClient client = (DefaultClient) new ClientBuilder(OPENSHIFT_URL) + .proxySelector(expectedSelector) + .build(); + + + OkHttpClient okClient = getOkHttpClient(client); + ProxySelector proxySelector = okClient.proxySelector(); + + assertNotSame(proxySelector, ProxySelector.getDefault()); + assertEquals(expectedSelector, proxySelector); + + Proxy expectedProxyFromList = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(PROXY_HOST, PROXY_PORT)); + Proxy actualProxyFromList = proxySelector.select(null).get(0); + assertEquals(expectedProxyFromList.type(), actualProxyFromList.type()); + assertEquals(expectedProxyFromList.address(), actualProxyFromList.address()); + } + + @Test + public void testProxySelectorNotSetInOkHttp() throws NoSuchFieldException, IllegalAccessException { + DefaultClient client = (DefaultClient) new ClientBuilder(OPENSHIFT_URL) + .build(); + + OkHttpClient okClient = getOkHttpClient(client); + ProxySelector proxySelector = okClient.proxySelector(); + + assertEquals(proxySelector, ProxySelector.getDefault()); + } + + + private OkHttpClient getOkHttpClient(DefaultClient client) throws NoSuchFieldException, IllegalAccessException { + Field clientField = client.getClass().getDeclaredField("client"); + clientField.setAccessible(true); + return (OkHttpClient) clientField.get(client); + } +} diff --git a/src/test/java/com/openshift/internal/restclient/okhttp/WatchClientTest.java b/src/test/java/com/openshift/internal/restclient/okhttp/WatchClientTest.java new file mode 100644 index 00000000..0fafc145 --- /dev/null +++ b/src/test/java/com/openshift/internal/restclient/okhttp/WatchClientTest.java @@ -0,0 +1,81 @@ +/******************************************************************************* + * Copyright (c) 2015-2018 Red Hat, Inc. + * Distributed under license by Red Hat, Inc. All rights reserved. + * This program is made available under the terms of the + * Eclipse Public License v1.0 which accompanies this distribution, + * and is available at http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Red Hat, Inc. - initial API and implementation + ******************************************************************************/ + +package com.openshift.internal.restclient.okhttp; + +import static org.hamcrest.CoreMatchers.equalTo; +import static org.hamcrest.CoreMatchers.not; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; + +import java.io.IOException; +import java.net.ProtocolException; + +import org.junit.Test; + +import com.openshift.internal.restclient.DefaultClient; +import com.openshift.internal.restclient.okhttp.WatchClient.WatchEndpoint; +import com.openshift.restclient.IOpenShiftWatchListener; +import com.openshift.restclient.IOpenShiftWatchListener.ChangeType; +import com.openshift.restclient.ResourceKind; +import com.openshift.restclient.http.IHttpConstants; + +import okhttp3.Protocol; +import okhttp3.Request; +import okhttp3.Response; + +/** + * @author Andre Dietisheim + */ +public class WatchClientTest { + + @Test + public void testOnFailureCallBackNotifiesListener() { + DefaultClient client = null; + + IOpenShiftWatchListener listener = mock(IOpenShiftWatchListener.class); + + WatchEndpoint endpoint = new WatchEndpoint(client, listener, ResourceKind.BUILD); + endpoint.onFailure(null, new IOException(), null); + verify(listener).error(any(Throwable.class)); + } + + @Test + public void shouldIgnoreUnsupportedFeatureResponseOnFailure() { + DefaultClient client = mock(DefaultClient.class); + IOpenShiftWatchListener listener = mock(IOpenShiftWatchListener.class); + + WatchEndpoint endpoint = new WatchEndpoint(client, listener, ResourceKind.BUILD); + Response.Builder responseBuilder = new Response.Builder(); + responseBuilder.code(IHttpConstants.STATUS_OK).message("").protocol(Protocol.HTTP_2) + .request(new Request.Builder().url("http://localhost").build()); + endpoint.onFailure(null, new ProtocolException(), responseBuilder.build()); + verify(listener, never()).error(any()); + } + + @Test + public void changeTypeShouldEqualSameChangeType() { + assertThat(ChangeType.ADDED, equalTo(ChangeType.ADDED)); + } + + @Test + public void changeTypeShouldNotEqualDifferentChangeType() { + assertThat(ChangeType.ADDED, not(equalTo(ChangeType.DELETED))); + } + + @Test + public void changeTypeShouldEqualSameChangeTypeInLowercase() { + assertThat(ChangeType.ADDED, equalTo(new ChangeType(ChangeType.ADDED.getValue().toLowerCase()))); + } +} diff --git a/src/test/java/com/openshift/internal/util/JBossDmrExtentionsTest.java b/src/test/java/com/openshift/internal/util/JBossDmrExtentionsTest.java index 88e5cdda..477f9c71 100644 --- a/src/test/java/com/openshift/internal/util/JBossDmrExtentionsTest.java +++ b/src/test/java/com/openshift/internal/util/JBossDmrExtentionsTest.java @@ -6,12 +6,23 @@ * * Contributors: Red Hat, Inc. ******************************************************************************/ + package com.openshift.internal.util; -import static org.junit.Assert.*; -import static com.openshift.internal.util.JBossDmrExtentions.*; +import static com.openshift.internal.util.JBossDmrExtentions.asBoolean; +import static com.openshift.internal.util.JBossDmrExtentions.asInt; +import static com.openshift.internal.util.JBossDmrExtentions.asList; +import static com.openshift.internal.util.JBossDmrExtentions.asMap; +import static com.openshift.internal.util.JBossDmrExtentions.asSet; +import static com.openshift.internal.util.JBossDmrExtentions.asString; +import static com.openshift.internal.util.JBossDmrExtentions.toJsonString; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; import java.util.HashMap; +import java.util.List; import java.util.Map; import org.jboss.dmr.ModelNode; @@ -19,92 +30,105 @@ import org.junit.Before; import org.junit.Test; -/** - * @author Jeff Cantrill - */ public class JBossDmrExtentionsTest { - private ModelNode node = ModelNode.fromJSONString("{\"foo\":\"bar\", \"int\":\"3\", \"bool\":\"true\"}"); - private Map paths = new HashMap(); - private static final String KEY_FOO = "foo"; - private static final String KEY_XYZ = "xyz"; - private static final String KEY_BOOL = "bool"; - private static final String KEY_INT = "int"; - - @Before - public void setup() { - paths.put(KEY_FOO, new String[] {"foo"}); - paths.put(KEY_XYZ, new String[] {"xyz"}); - paths.put(KEY_BOOL, new String[] {"bool"}); - paths.put(KEY_INT, new String[] {"int"}); - } - - @Test - public void testToJson() { - ModelNode complex = new ModelNode(); - complex.get("sub1", "sub2"); - complex.get("sub1a").set("avalue"); - - ModelNode node = new ModelNode(); - node.get("foo","bar"); - node.get("xyz").add(1).add(2).add(3); - node.get("xyz").get(1).clear(); - node.get("xyz").add(complex); - node.get("def").add(new ModelNode()); - node.get("abc").set("xyx"); - assertEquals("{\"foo\" : {}, \"xyz\" : [1,3,{\"sub1\" : {}, \"sub1a\" : \"avalue\"}], \"abc\" : \"xyx\"}", toJsonString(node, true)); - } - - @Test - public void testGettersDoNotAddNodeToJsonTree() { - asMap(node, paths, "openshift.map"); - assertFalse(node.has("openshift","map")); - - asSet(node, paths, "openshift.set", ModelType.STRING); - assertFalse(node.has("openshift","set")); - - asInt(node, paths, "openshift.int"); - assertFalse(node.has("openshift","int")); - - asString(node, paths, "openshift.string"); - assertFalse(node.has("openshift","string")); - - asBoolean(node, paths, "openshift.bool"); - assertFalse(node.has("openshift","bool")); - } - - @Test - public void testAsMapWhenPropertyKeysAreNull() { - assertNotNull(asMap(new ModelNode(), null, null)); - } - - @Test - public void asIntForUndefinedShouldReturnZero() { - assertEquals(0, asInt(node, paths, KEY_XYZ)); - } - - @Test - public void asIntForAValueShouldReturnValue() { - assertEquals(3,asInt(node, paths, KEY_INT)); - } - @Test - public void asBooleanForUndefinedShouldReturnFalse() { - assertFalse(asBoolean(node, paths, KEY_XYZ)); - } - - @Test - public void asBooleanForAValueShouldReturnValue() { - assertTrue(asBoolean(node, paths, KEY_BOOL)); - } - - @Test - public void asStringForUndefinedShouldReturnEmptySpace() { - assertEquals("", asString(node, paths, KEY_XYZ)); - } - - @Test - public void asStringForAValueShouldReturnTheValue() { - assertEquals("bar", asString(node, paths, KEY_FOO)); - } + private ModelNode node = ModelNode + .fromJSONString("{\"foo\":\"bar\", \"int\":\"3\", \"bool\":\"true\", \"list\": [\"1\", \"2\", \"3\"]}"); + private Map paths = new HashMap(); + private static final String KEY_FOO = "foo"; + private static final String KEY_XYZ = "xyz"; + private static final String KEY_BOOL = "bool"; + private static final String KEY_INT = "int"; + private static final String KEY_LIST = "list"; + + @Before + public void setup() { + paths.put(KEY_FOO, new String[] { "foo" }); + paths.put(KEY_XYZ, new String[] { "xyz" }); + paths.put(KEY_BOOL, new String[] { "bool" }); + paths.put(KEY_INT, new String[] { "int" }); + paths.put(KEY_LIST, new String[] { "list" }); + } + + @Test + public void testToJson() { + ModelNode complex = new ModelNode(); + complex.get("sub1", "sub2"); + complex.get("sub1a").set("avalue"); + + ModelNode node = new ModelNode(); + node.get("foo", "bar"); + node.get("xyz").add(1).add(2).add(3); + node.get("xyz").get(1).clear(); + node.get("xyz").add(complex); + node.get("def").add(new ModelNode()); + node.get("abc").set("xyx"); + assertEquals("{\"foo\":{},\"xyz\":[1,3,{\"sub1\":{},\"sub1a\":\"avalue\"}],\"abc\":\"xyx\"}", + toJsonString(node, true)); + } + + @Test + public void testGettersDoNotAddNodeToJsonTree() { + asMap(node, paths, "openshift.map"); + assertFalse(node.has("openshift", "map")); + + asSet(node, paths, "openshift.set", ModelType.STRING); + assertFalse(node.has("openshift", "set")); + + asInt(node, paths, "openshift.int"); + assertFalse(node.has("openshift", "int")); + + asString(node, paths, "openshift.string"); + assertFalse(node.has("openshift", "string")); + + asBoolean(node, paths, "openshift.bool"); + assertFalse(node.has("openshift", "bool")); + + asList(node, paths, "openshift.list", ModelType.STRING); + assertFalse(node.has("openshift", "set")); + } + + @Test + public void testAsMapWhenPropertyKeysAreNull() { + assertNotNull(asMap(new ModelNode(), null, null)); + } + + @Test + public void asIntForUndefinedShouldReturnZero() { + assertEquals(0, asInt(node, paths, KEY_XYZ)); + } + + @Test + public void asIntForAValueShouldReturnValue() { + assertEquals(3, asInt(node, paths, KEY_INT)); + } + + @Test + public void asBooleanForUndefinedShouldReturnFalse() { + assertFalse(asBoolean(node, paths, KEY_XYZ)); + } + + @Test + public void asBooleanForAValueShouldReturnValue() { + assertTrue(asBoolean(node, paths, KEY_BOOL)); + } + + @Test + public void asStringForUndefinedShouldReturnEmptySpace() { + assertEquals("", asString(node, paths, KEY_XYZ)); + } + + @Test + public void asStringForAValueShouldReturnTheValue() { + assertEquals("bar", asString(node, paths, KEY_FOO)); + } + + @Test + public void asListForStringReturnsOrderedValues() { + List l = asList(node, paths, KEY_LIST, ModelType.STRING); + assertEquals("1", l.get(0)); + assertEquals("2", l.get(1)); + assertEquals("3", l.get(2)); + } } diff --git a/src/test/java/com/openshift/internal/util/StringSplitterTest.java b/src/test/java/com/openshift/internal/util/StringSplitterTest.java new file mode 100644 index 00000000..5fd9e7b6 --- /dev/null +++ b/src/test/java/com/openshift/internal/util/StringSplitterTest.java @@ -0,0 +1,76 @@ +/******************************************************************************* + * Copyright (c) 2018 Red Hat, Inc. Distributed under license by Red Hat, Inc. + * All rights reserved. This program is made available under the terms of the + * Eclipse Public License v1.0 which accompanies this distribution, and is + * available at http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: Red Hat, Inc. + ******************************************************************************/ + +package com.openshift.internal.util; + +import static org.hamcrest.CoreMatchers.is; +import static org.hamcrest.MatcherAssert.assertThat; + +import java.util.Arrays; +import java.util.List; + +import org.junit.Test; + +public class StringSplitterTest { + @Test + public void testSimpleUniqueParameter() { + List result = StringSplitter.split("parm1"); + List expected = Arrays.asList("parm1"); + assertThat(result, is(expected)); + } + + @Test + public void testSimpleManyParameters() { + List result = StringSplitter.split("parm1 parm2 parm3"); + List expected = Arrays.asList("parm1", "parm2", "parm3"); + assertThat(result, is(expected)); + } + + @Test + public void testQuotedUniqueParameter() { + List result = StringSplitter.split("\"parm1\""); + List expected = Arrays.asList("parm1"); + assertThat(result, is(expected)); + } + + @Test + public void testQuotedManyParameters() { + List result = StringSplitter.split("\"parm1\" \"parm2\" \"parm3\""); + List expected = Arrays.asList("parm1", "parm2", "parm3"); + assertThat(result, is(expected)); + } + + @Test + public void testQuotedManyParametersWithAdjacentValue() { + List result = StringSplitter.split("\"parm1\" \"parm2\"a \"parm3\""); + List expected = Arrays.asList("parm1", "parm2a", "parm3"); + assertThat(result, is(expected)); + } + + @Test + public void testQuotedManyParametersUnfinished() { + List result = StringSplitter.split("\"parm1\" \"parm2\" \"parm3"); + List expected = Arrays.asList("parm1", "parm2", "parm3"); + assertThat(result, is(expected)); + } + + @Test + public void testSimpleDoubleSpaceManyParameters() { + List result = StringSplitter.split("parm1 parm2 parm3"); + List expected = Arrays.asList("parm1", "parm2", "parm3"); + assertThat(result, is(expected)); + } + + @Test + public void testSimpleEndSpaceManyParameters() { + List result = StringSplitter.split("parm1 parm2 parm3 "); + List expected = Arrays.asList("parm1", "parm2", "parm3"); + assertThat(result, is(expected)); + } +} diff --git a/src/test/java/com/openshift/internal/util/TestTimer.java b/src/test/java/com/openshift/internal/util/TestTimer.java index adc97511..beb78df1 100644 --- a/src/test/java/com/openshift/internal/util/TestTimer.java +++ b/src/test/java/com/openshift/internal/util/TestTimer.java @@ -6,44 +6,45 @@ * * Contributors: Red Hat, Inc. ******************************************************************************/ + package com.openshift.internal.util; -import com.openshift.restclient.OpenShiftException; +import java.io.IOException; + import org.junit.After; import org.junit.Before; import org.junit.Rule; import org.junit.rules.TestName; -import java.io.IOException; +import com.openshift.restclient.OpenShiftException; /** * @author Corey Daley */ public class TestTimer { - protected long startTime; - protected long endTime; - - @Rule - public TestName name = new TestName(); - - @Before - public void startTimer() throws OpenShiftException, IOException { - this.startTime = 0; - this.startTime = System.currentTimeMillis(); - } - - @After - public void endTimer() { - this.endTime = 0; - this.endTime = System.currentTimeMillis(); - calcExecTime(); - - - } - - public void calcExecTime() { - if (System.getProperty("showTestTimes") != null) { - System.out.println(this.getClass() +"#"+name.getMethodName() + " : " + (this.endTime - this.startTime)); - } - } + protected long startTime; + protected long endTime; + + @Rule + public TestName name = new TestName(); + + @Before + public void startTimer() throws OpenShiftException, IOException { + this.startTime = 0; + this.startTime = System.currentTimeMillis(); + } + + @After + public void endTimer() { + this.endTime = 0; + this.endTime = System.currentTimeMillis(); + calcExecTime(); + + } + + public void calcExecTime() { + if (System.getProperty("showTestTimes") != null) { + System.out.println(this.getClass() + "#" + name.getMethodName() + " : " + (this.endTime - this.startTime)); + } + } } diff --git a/src/test/java/com/openshift/internal/util/URIUtilsTest.java b/src/test/java/com/openshift/internal/util/URIUtilsTest.java index 53cb7ae7..c97d89de 100644 --- a/src/test/java/com/openshift/internal/util/URIUtilsTest.java +++ b/src/test/java/com/openshift/internal/util/URIUtilsTest.java @@ -6,9 +6,10 @@ * * Contributors: Red Hat, Inc. ******************************************************************************/ + package com.openshift.internal.util; -import static org.junit.Assert.*; +import static org.junit.Assert.assertArrayEquals; import java.net.URI; import java.net.URISyntaxException; @@ -18,44 +19,39 @@ import org.junit.Before; import org.junit.Test; -import com.openshift.internal.util.URIUtils; - -/** - * @author Jeff Cantrill - */ public class URIUtilsTest { - - private String location = "https://10.0.2.15:8443/oauth/token/display#access_token=MmJiMTQzMGMtZjA0Mi00ODJmLTkzMDUtYzEyMTE5ODU1OGJh&expires_in=3600&token_type=bearer"; - private Map exp = new HashMap(); - - @Before - public void setup(){ - exp.put("access_token", "MmJiMTQzMGMtZjA0Mi00ODJmLTkzMDUtYzEyMTE5ODU1OGJh"); - exp.put("expires_in", "3600"); - exp.put("token_type", "bearer"); - } - - @Test - public void testSplitFragmentFromURIString(){ - assertMaps(exp, URIUtils.splitFragment(location)); - } - - @Test - public void testSplitFragmentFromURIWithNoFragment() throws Exception{ - URI uri = new URI("http://localhost"); - Map pairs = URIUtils.splitFragment(uri); - assertMaps(new HashMap(), pairs); - } - - @Test - public void testSplitFragmentFromURI() throws URISyntaxException { - URI uri = new URI(location); - - Map pairs = URIUtils.splitFragment(uri); - assertMaps(exp, pairs); - } - - private void assertMaps(Map exp, Map act){ - assertArrayEquals(exp.entrySet().toArray(), act.entrySet().toArray()); - } + + private String location = "https://10.0.2.15:8443/oauth/token/display#access_token=MmJiMTQzMGMtZjA0Mi00ODJmLTkzMDUtYzEyMTE5ODU1OGJh&expires_in=3600&token_type=bearer"; + private Map exp = new HashMap(); + + @Before + public void setup() { + exp.put("access_token", "MmJiMTQzMGMtZjA0Mi00ODJmLTkzMDUtYzEyMTE5ODU1OGJh"); + exp.put("expires_in", "3600"); + exp.put("token_type", "bearer"); + } + + @Test + public void testSplitFragmentFromURIString() { + assertMaps(exp, URIUtils.splitFragment(location)); + } + + @Test + public void testSplitFragmentFromURIWithNoFragment() throws Exception { + URI uri = new URI("http://localhost"); + Map pairs = URIUtils.splitFragment(uri); + assertMaps(new HashMap(), pairs); + } + + @Test + public void testSplitFragmentFromURI() throws URISyntaxException { + URI uri = new URI(location); + + Map pairs = URIUtils.splitFragment(uri); + assertMaps(exp, pairs); + } + + private void assertMaps(Map exp, Map act) { + assertArrayEquals(exp.entrySet().toArray(), act.entrySet().toArray()); + } } diff --git a/src/test/java/com/openshift/restclient/OpenShiftContextTest.java b/src/test/java/com/openshift/restclient/OpenShiftContextTest.java index 9c05b69f..db1ab8fa 100644 --- a/src/test/java/com/openshift/restclient/OpenShiftContextTest.java +++ b/src/test/java/com/openshift/restclient/OpenShiftContextTest.java @@ -6,11 +6,12 @@ * * Contributors: Red Hat, Inc. ******************************************************************************/ + package com.openshift.restclient; -import static junit.framework.Assert.assertEquals; -import static junit.framework.Assert.assertNotSame; -import static junit.framework.Assert.assertNull; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotSame; +import static org.junit.Assert.assertNull; import org.junit.After; import org.junit.Test; @@ -22,63 +23,63 @@ */ public class OpenShiftContextTest { - @After - public void tearDown() { - OpenShiftContext.get().clear(); - } - - @Test - public void testGetValue() { - String value = "bar"; - OpenShiftContext.get().put("foo", value); - assertEquals(value, OpenShiftContext.get().get("foo")); - } - - @Test - public void testRemove() { - OpenShiftContext.get().put("foo", "bar"); - OpenShiftContext.get().remove("foo"); - assertNull(OpenShiftContext.get().get("foo")); - } - - @Test - public void testClear() { - OpenShiftContext.get().put("foo", "bar"); - OpenShiftContext.get().clear(); - assertNull(OpenShiftContext.get().get("foo")); - } - - @Test - public void testConcurrency() throws Exception { - OpenShiftContext[] contexts = new OpenShiftContext[2]; - Thread t0 = new SomeThread(0, contexts); - Thread t1 = new SomeThread(1, contexts); - - t0.start(); - t1.start(); - t0.join(); - t1.join(); - - assertNotSame(contexts[0], contexts[1]); - assertEquals(t0.getName(), contexts[0].get("foo")); - assertEquals(t1.getName(), contexts[1].get("foo")); - } - - static class SomeThread extends Thread { - - private int index; - private OpenShiftContext[] contexts; + @After + public void tearDown() { + OpenShiftContext.get().clear(); + } + + @Test + public void testGetValue() { + String value = "bar"; + OpenShiftContext.get().put("foo", value); + assertEquals(value, OpenShiftContext.get().get("foo")); + } + + @Test + public void testRemove() { + OpenShiftContext.get().put("foo", "bar"); + OpenShiftContext.get().remove("foo"); + assertNull(OpenShiftContext.get().get("foo")); + } + + @Test + public void testClear() { + OpenShiftContext.get().put("foo", "bar"); + OpenShiftContext.get().clear(); + assertNull(OpenShiftContext.get().get("foo")); + } + + @Test + public void testConcurrency() throws Exception { + OpenShiftContext[] contexts = new OpenShiftContext[2]; + Thread t0 = new SomeThread(0, contexts); + Thread t1 = new SomeThread(1, contexts); + + t0.start(); + t1.start(); + t0.join(); + t1.join(); + + assertNotSame(contexts[0], contexts[1]); + assertEquals(t0.getName(), contexts[0].get("foo")); + assertEquals(t1.getName(), contexts[1].get("foo")); + } + + static class SomeThread extends Thread { + + private int index; + private OpenShiftContext[] contexts; + + SomeThread(int index, OpenShiftContext[] contexts) { + super("Thread-" + index); + this.index = index; + this.contexts = contexts; + } - SomeThread(int index, OpenShiftContext[] contexts) { - super("Thread-"+index); - this.index = index; - this.contexts = contexts; - } - - public void run() { - assertNull(OpenShiftContext.get().get("foo")); - OpenShiftContext.get().put("foo", getName()); - contexts[index] = OpenShiftContext.get(); - }; - } + public void run() { + assertNull(OpenShiftContext.get().get("foo")); + OpenShiftContext.get().put("foo", getName()); + contexts[index] = OpenShiftContext.get(); + } + } } diff --git a/src/test/java/com/openshift/restclient/ResourceKindTest.java b/src/test/java/com/openshift/restclient/ResourceKindTest.java index 3eac5044..3fc79228 100644 --- a/src/test/java/com/openshift/restclient/ResourceKindTest.java +++ b/src/test/java/com/openshift/restclient/ResourceKindTest.java @@ -8,54 +8,54 @@ * Contributors: * Red Hat, Inc. - initial API and implementation ******************************************************************************/ + package com.openshift.restclient; -import static org.junit.Assert.*; +import static org.junit.Assert.assertEquals; import org.junit.Test; -/** - * - * @author jeff.cantrill - * - */ public class ResourceKindTest { - @Test - public void testPluralizeWhenNull() { - assertEquals("",ResourceKind.pluralize(null)); - } - - @Test - public void testPluralizeWhenEmpty() { - assertEquals("",ResourceKind.pluralize(" ")); - } - - @Test - public void testPluralizeWhenEndsWithAnS() { - assertEquals("Status",ResourceKind.pluralize(ResourceKind.STATUS)); - } - - @Test - public void testPluralizeWhenEndsWithY() { - assertEquals("Families",ResourceKind.pluralize("Family")); - } - - @Test - public void testPluralizeWhenEndsWithAnythingElse() { - assertEquals("Services",ResourceKind.pluralize(ResourceKind.SERVICE)); - } - @Test - public void testPluralizeCamelCaseKind() { - assertEquals("ReplicationControllers",ResourceKind.pluralize(ResourceKind.REPLICATION_CONTROLLER)); - } - @Test - public void testPluralizeCamelCaseKindForceLower() { - assertEquals("replicationcontrollers",ResourceKind.pluralize(ResourceKind.REPLICATION_CONTROLLER, true, true)); - } - @Test - public void testPluralizeCamelCaseKindUncapitalize() { - assertEquals("replicationControllers",ResourceKind.pluralize(ResourceKind.REPLICATION_CONTROLLER, false, true)); - } + @Test + public void testPluralizeWhenNull() { + assertEquals("", ResourceKind.pluralize(null)); + } + + @Test + public void testPluralizeWhenEmpty() { + assertEquals("", ResourceKind.pluralize(" ")); + } + + @Test + public void testPluralizeWhenEndsWithAnS() { + assertEquals("Status", ResourceKind.pluralize(ResourceKind.STATUS)); + } + + @Test + public void testPluralizeWhenEndsWithY() { + assertEquals("Families", ResourceKind.pluralize("Family")); + } + + @Test + public void testPluralizeWhenEndsWithAnythingElse() { + assertEquals("Services", ResourceKind.pluralize(ResourceKind.SERVICE)); + } + + @Test + public void testPluralizeCamelCaseKind() { + assertEquals("ReplicationControllers", ResourceKind.pluralize(ResourceKind.REPLICATION_CONTROLLER)); + } + + @Test + public void testPluralizeCamelCaseKindForceLower() { + assertEquals("replicationcontrollers", ResourceKind.pluralize(ResourceKind.REPLICATION_CONTROLLER, true, true)); + } + + @Test + public void testPluralizeCamelCaseKindUncapitalize() { + assertEquals("replicationControllers", + ResourceKind.pluralize(ResourceKind.REPLICATION_CONTROLLER, false, true)); + } } diff --git a/src/test/java/com/openshift/restclient/WatchClientIntegrationTest.java b/src/test/java/com/openshift/restclient/WatchClientIntegrationTest.java index 468f3990..9b84b482 100644 --- a/src/test/java/com/openshift/restclient/WatchClientIntegrationTest.java +++ b/src/test/java/com/openshift/restclient/WatchClientIntegrationTest.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2015 Red Hat, Inc. + * Copyright (c) 2015-2019 Red Hat, Inc. * Distributed under license by Red Hat, Inc. All rights reserved. * This program is made available under the terms of the * Eclipse Public License v1.0 which accompanies this distribution, @@ -8,10 +8,10 @@ * Contributors: * Red Hat, Inc. - initial API and implementation ******************************************************************************/ + package com.openshift.restclient; -import static com.openshift.internal.restclient.IntegrationTestHelper.cleanUpResource; -import static org.junit.Assert.assertArrayEquals; +import static org.assertj.core.api.Assertions.assertThat; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; @@ -34,78 +34,91 @@ public class WatchClientIntegrationTest { - private static final Logger LOG = LoggerFactory.getLogger(WatchClientIntegrationTest.class); - - private IntegrationTestHelper helper = new IntegrationTestHelper(); - private IClient client; - private IResource project; - - private ExecutorService service; - private boolean isError; - - @Before - public void setup() { - service = Executors.newSingleThreadScheduledExecutor(); - client = helper.createClientForBasicAuth(); - IResource projRequest = client.getResourceFactory().stub(ResourceKind.PROJECT_REQUEST, helper.generateNamespace()); - project = client.create(projRequest); - } - - @After - public void teardown() { - cleanUpResource(client, project); - service.shutdownNow(); - } - - @SuppressWarnings("rawtypes") - @Test(timeout=30000) - public void test() throws Exception{ - List results = new ArrayList(); - CountDownLatch latch = new CountDownLatch(2); - IOpenShiftWatchListener listener = new IOpenShiftWatchListener() { - - @SuppressWarnings("unchecked") - @Override - public void received(IResource resource, ChangeType change) { - results.add(change); - } - - @Override - public void connected(List resources) { - latch.countDown(); - } - - @Override - public void disconnected() { - latch.countDown(); - } - - @Override - public void error(Throwable err) { - latch.countDown(); - isError = true; - LOG.error("",err); - } - }; - - IWatcher watcher = null; - try { - watcher = client.watch(project.getName(), listener, ResourceKind.SERVICE, ResourceKind.POD); - latch.await(); - assertFalse("Expected connection without error",isError); - IService service = client.getResourceFactory().stub(ResourceKind.SERVICE,"hello-world", project.getName()); - service.addPort(8080,8080); - service = client.create(service); - service.addLabel("foo", "bar"); - service = client.update(service); - client.delete(service); - assertArrayEquals(new ChangeType[] {ChangeType.ADDED, ChangeType.MODIFIED, ChangeType.DELETED}, results.toArray()); - assertEquals(0, latch.getCount()); - }finally { - if(watcher != null) { - watcher.stop(); - } - } - } + private static final Logger LOG = LoggerFactory.getLogger(WatchClientIntegrationTest.class); + + private IntegrationTestHelper helper = new IntegrationTestHelper(); + private IClient client; + private IResource project; + public static final String[] KINDS = new String[] { + ResourceKind.BUILD_CONFIG, + ResourceKind.DEPLOYMENT_CONFIG, + ResourceKind.SERVICE, + ResourceKind.POD, + ResourceKind.REPLICATION_CONTROLLER, + ResourceKind.BUILD, + ResourceKind.IMAGE_STREAM, + ResourceKind.ROUTE + }; + + private ExecutorService executor; + private boolean isError; + + private IService service; + + @Before + public void setup() { + this.executor = Executors.newSingleThreadScheduledExecutor(); + this.client = helper.createClientForBasicAuth(); + this.project = helper.getOrCreateIntegrationTestProject(client); + // kill existing service to avoid name clash + } + + @After + public void teardown() { + executor.shutdownNow(); + } + + @Test(timeout = IntegrationTestHelper.TEST_LONG_TIMEOUT) + public void test() throws Exception { + List results = new ArrayList<>(); + CountDownLatch latch = new CountDownLatch(KINDS.length); + IOpenShiftWatchListener listener = new IOpenShiftWatchListener() { + + @Override + public void received(IResource resource, ChangeType change) { + results.add(change); + } + + @Override + public void connected(List resources) { + latch.countDown(); + } + + @Override + public void disconnected() { + latch.countDown(); + } + + @Override + public void error(Throwable err) { + latch.countDown(); + isError = true; + LOG.error("", err); + } + }; + IWatcher watcher = null; + try { + watcher = client.watch(project.getName(), listener, KINDS); + latch.await(); + assertFalse("Expected connection without error", isError); + IService stub = helper.stubService(client, + project.getNamespaceName(), + IntegrationTestHelper.appendRandom("hello-openshift"), + 8787, 8787, + ""); + this.service = client.create(stub); + this.service.addLabel("foo", "bar"); + this.service = client.update(service); + client.delete(stub); + this.service = null; + assertThat(results).containsExactly( + ChangeType.ADDED, + ChangeType.MODIFIED, + ChangeType.DELETED); + assertEquals(0, latch.getCount()); + } finally { + helper.stopWatcher(watcher); + } + } } diff --git a/src/test/java/com/openshift/restclient/authorization/BasicAuthorizationStrategyTest.java b/src/test/java/com/openshift/restclient/authorization/BasicAuthorizationStrategyTest.java deleted file mode 100644 index 40ea1e54..00000000 --- a/src/test/java/com/openshift/restclient/authorization/BasicAuthorizationStrategyTest.java +++ /dev/null @@ -1,88 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2015 Red Hat, Inc. Distributed under license by Red Hat, Inc. - * All rights reserved. This program is made available under the terms of the - * Eclipse Public License v1.0 which accompanies this distribution, and is - * available at http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: Red Hat, Inc. - ******************************************************************************/ -package com.openshift.restclient.authorization; - -import static org.fest.assertions.Assertions.assertThat; -import static org.mockito.Matchers.eq; -import static org.mockito.Mockito.verify; - -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.mockito.Mock; -import org.mockito.runners.MockitoJUnitRunner; - -import com.openshift.restclient.utils.Base64Coder; - -/** - * @author Jeff Cantrill - */ -@RunWith(MockitoJUnitRunner.class) -public class BasicAuthorizationStrategyTest { - - @Mock - private IRequest request; - private BasicAuthorizationStrategy strategy; - - @Before - public void setup(){ - strategy= new BasicAuthorizationStrategy("aUserName", "aPassword",null); - } - - @Test - public void testAuthorize() { - String usernamePassword = String.format("Basic %s", Base64Coder.encode("aUserName:aPassword")); - strategy.authorize(request); - verify(request).setProperty(eq("Authorization"), eq(usernamePassword)); - } - - @Test - public void BasicStrategyShouldEqualBasicStrategyWithDifferentUsername() { - assertThat(new BasicAuthorizationStrategy("aUsername", "aPassword", null)) - .isNotEqualTo(new BasicAuthorizationStrategy("differentUsername", "aPassword", null)); - } - - @Test - public void BasicStrategyShouldEqualBasicStrategyWithDifferentToken() { - assertThat(new BasicAuthorizationStrategy("aUsername", "aPassword", "123")) - .isEqualTo(new BasicAuthorizationStrategy("aUsername", "aPassword", "234")); - } - - @Test - public void BasicStrategyShouldEqualBasicStrategyWithDifferentPassword() { - assertThat(new BasicAuthorizationStrategy("aUsername", "aPassword", null)) - .isEqualTo(new BasicAuthorizationStrategy("aUsername", "differentPassword", null)); - } - - @Test - public void BasicStrategyShouldNotEqualNonBasicStrategy() { - assertThat(new BasicAuthorizationStrategy("aUsername", "aPassword", null)) - .isNotEqualTo(new IAuthorizationStrategy() { - - - @Override - public String getUsername() { - return null; - } - - @Override - public String getToken() { - return null; - } - - @Override - public void authorize(IRequest request) { - } - - @Override - public void accept(IAuthorizationStrategyVisitor visitor) { - } - }); - } -} diff --git a/src/test/java/com/openshift/restclient/authorization/TokenAuthorizationStrategyTest.java b/src/test/java/com/openshift/restclient/authorization/TokenAuthorizationStrategyTest.java deleted file mode 100644 index a7a424cb..00000000 --- a/src/test/java/com/openshift/restclient/authorization/TokenAuthorizationStrategyTest.java +++ /dev/null @@ -1,93 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2015 Red Hat, Inc. Distributed under license by Red Hat, Inc. - * All rights reserved. This program is made available under the terms of the - * Eclipse Public License v1.0 which accompanies this distribution, and is - * available at http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: Red Hat, Inc. - ******************************************************************************/ -package com.openshift.restclient.authorization; - -import static org.fest.assertions.Assertions.assertThat; -import static org.mockito.Matchers.eq; -import static org.mockito.Mockito.verify; - -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.mockito.Mock; -import org.mockito.runners.MockitoJUnitRunner; - -/** - * @author Jeff Cantrill - */ -@RunWith(MockitoJUnitRunner.class) -public class TokenAuthorizationStrategyTest { - - @Mock - private IRequest request; - private TokenAuthorizationStrategy strategy; - - @Before - public void setup(){ - strategy = new TokenAuthorizationStrategy("123"); - } - - @Test - public void testAuthorize() { - strategy.authorize(request); - - verify(request).setProperty(eq("Authorization"), eq("Bearer 123")); - } - - @Test - public void TokenStrategiesShoulEqualTokenStrategyWithDifferentToken() { - assertThat(new TokenAuthorizationStrategy("123")).isEqualTo(new TokenAuthorizationStrategy("42")); - } - - @Test - public void TokenStrategiesWithSameTokensShouldEqual() { - assertThat(new TokenAuthorizationStrategy("123")).isEqualTo(new TokenAuthorizationStrategy("123")); - } - - @Test - public void TokenStrategiesShoulNotEqualTokenStrategyWithDifferentUsername() { - TokenAuthorizationStrategy tokenStrategy1 = new TokenAuthorizationStrategy("123", "aUsername"); - TokenAuthorizationStrategy tokenStrategy2 = new TokenAuthorizationStrategy("123", "differentUser"); - assertThat(tokenStrategy1).isNotEqualTo(tokenStrategy2); - } - - @Test - public void TokenStrategiesShoulEqualTokenStrategyWithSameUsernameAndSameToken() { - TokenAuthorizationStrategy tokenStrategy1 = new TokenAuthorizationStrategy("123", "aUser"); - TokenAuthorizationStrategy tokenStrategy2 = new TokenAuthorizationStrategy("123", "aUser"); - assertThat(tokenStrategy1).isEqualTo(tokenStrategy2); - } - - @Test - public void TokenStrategyShouldNotEqualNonTokenStrategy() { - assertThat(new TokenAuthorizationStrategy("123")) - .isNotEqualTo(new IAuthorizationStrategy() { - - @Override - public String getToken() { - return null; - } - - - @Override - public String getUsername() { - return null; - } - - @Override - public void authorize(IRequest request) { - } - - @Override - public void accept(IAuthorizationStrategyVisitor visitor) { - } - }); - } - -} diff --git a/src/test/java/com/openshift/restclient/authorization/URLConnectionAuthorizationRequestTest.java b/src/test/java/com/openshift/restclient/authorization/URLConnectionAuthorizationRequestTest.java deleted file mode 100644 index 44996d9f..00000000 --- a/src/test/java/com/openshift/restclient/authorization/URLConnectionAuthorizationRequestTest.java +++ /dev/null @@ -1,34 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2015 Red Hat, Inc. Distributed under license by Red Hat, Inc. - * All rights reserved. This program is made available under the terms of the - * Eclipse Public License v1.0 which accompanies this distribution, and is - * available at http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: Red Hat, Inc. - ******************************************************************************/ -package com.openshift.restclient.authorization; - -import static org.mockito.Mockito.*; - -import java.net.URLConnection; - -import org.junit.Test; - -import com.openshift.restclient.authorization.URLConnectionRequest; - -/** - * @author Jeff Cantrill - */ -public class URLConnectionAuthorizationRequestTest { - - @Test - public void testSetProperty() { - URLConnection conn = mock(URLConnection.class); - - URLConnectionRequest request = new URLConnectionRequest(conn); - request.setProperty("foo", "bar"); - - verify(conn).setRequestProperty(eq("foo"), eq("bar")); - } - -} diff --git a/src/test/java/com/openshift/restclient/images/DockerImageURITest.java b/src/test/java/com/openshift/restclient/images/DockerImageURITest.java index cc6b3e4b..4dad6b30 100644 --- a/src/test/java/com/openshift/restclient/images/DockerImageURITest.java +++ b/src/test/java/com/openshift/restclient/images/DockerImageURITest.java @@ -6,101 +6,108 @@ * * Contributors: Red Hat, Inc. ******************************************************************************/ + package com.openshift.restclient.images; -import static org.junit.Assert.*; +import static org.junit.Assert.assertEquals; import org.junit.Test; -import com.openshift.restclient.images.DockerImageURI; - -/** - * @author Jeff Cantrill - */ public class DockerImageURITest { - - private static final String NAME = "foo"; - private static final String TAG = "bar"; - private static final String USERNAME = "openshift"; - private static final String REPO_HOST = "127.0.0.1"; - - private static final String NAME_TAG = String.format("%s:%s", NAME, TAG); - private static final String USER_NAME_TAG = String.format("%s/%s:%s", USERNAME, NAME, TAG); - private static final String REPO_USER_NAME_TAG = String.format("%s/%s/%s:%s", REPO_HOST, USERNAME, NAME, TAG);;; - - @Test - public void testGetUriWithoutHost(){ - assertEquals("Exp. to get the uri without tag", String.format("%s/%s:%s", USERNAME, NAME, TAG), new DockerImageURI(REPO_USER_NAME_TAG).getUriWithoutHost()); - } - @Test - public void testGetUriWithoutTag(){ - assertEquals("Exp. to get the uri without tag", String.format("%s/%s/%s", REPO_HOST, USERNAME, NAME), new DockerImageURI(REPO_USER_NAME_TAG).getUriWithoutTag()); - } - @Test - public void testGetBaseUri(){ - assertEquals("Exp. to get the uri without repo", USER_NAME_TAG, new DockerImageURI(REPO_USER_NAME_TAG).getBaseUri()); - } - @Test - public void testGetAbsoluteUri() { - assertEquals("Exp. to get the full uri", REPO_USER_NAME_TAG, new DockerImageURI(REPO_USER_NAME_TAG).getAbsoluteUri()); - } - - @Test - public void testGetAbsoluteUriWithoutRepo() { - assertEquals("Exp. to get the full uri without rep", USER_NAME_TAG, new DockerImageURI(USER_NAME_TAG).getAbsoluteUri()); - } - - @Test - public void testGetAbsoluteUriWithoutUserName() { - assertEquals("Exp. to get the full uri without user name", NAME_TAG, new DockerImageURI(NAME_TAG).getAbsoluteUri()); - } - - @Test - public void testGetAbsoluteUriWithoutTag() { - assertEquals("Exp. to get the full uri without user name", String.format("%s:%s", NAME, "latest"), new DockerImageURI(NAME).getAbsoluteUri()); - } - - @Test - public void testName() { - DockerImageURI tag = new DockerImageURI(NAME); - assertEquals(NAME, tag.getName()); - assertEquals("Expected to toString to return the correct uri", String.format("%s:%s", NAME, "latest"), tag.toString()); - } - - @Test - public void testNameWithTag() { - DockerImageURI tag = new DockerImageURI(NAME_TAG); - assertNameAndTag(tag); - assertEquals("Expected to toString to return the correct uri", NAME_TAG, tag.toString()); - } - - @Test - public void testUserWithNameAndTag() { - DockerImageURI tag = new DockerImageURI(USER_NAME_TAG); - assertNameAndTag(tag); - assertUserName(tag); - assertEquals("Expected to toString to return the correct uri", USER_NAME_TAG, tag.toString()); - } - - @Test - public void testRepoWithUserWithNameAndTag() { - DockerImageURI tag = new DockerImageURI(REPO_USER_NAME_TAG); - assertNameAndTag(tag); - assertUserName(tag); - assertRepoHost(tag); - assertEquals("Expected to toString to return the correct uri", REPO_USER_NAME_TAG, tag.toString()); - } - - private void assertRepoHost(DockerImageURI tag) { - assertEquals("Expected to parse our the repo host", REPO_HOST, tag.getRepositoryHost()); - } - - private void assertUserName(DockerImageURI tag) { - assertEquals("Expected to parse our the username", USERNAME, tag.getUserName()); - } - - private void assertNameAndTag(DockerImageURI tag){ - assertEquals("Expected to parse out the name", NAME, tag.getName()); - assertEquals("Expected to parse out the tage", TAG, tag.getTag()); - } + + private static final String NAME = "foo"; + private static final String TAG = "bar"; + private static final String USERNAME = "openshift"; + private static final String REPO_HOST = "127.0.0.1"; + + private static final String NAME_TAG = String.format("%s:%s", NAME, TAG); + private static final String USER_NAME_TAG = String.format("%s/%s:%s", USERNAME, NAME, TAG); + private static final String REPO_USER_NAME_TAG = String.format("%s/%s/%s:%s", REPO_HOST, USERNAME, NAME, TAG); + + @Test + public void testGetUriWithoutHost() { + assertEquals("Exp. to get the uri without tag", String.format("%s/%s:%s", USERNAME, NAME, TAG), + new DockerImageURI(REPO_USER_NAME_TAG).getUriWithoutHost()); + } + + @Test + public void testGetUriWithoutTag() { + assertEquals("Exp. to get the uri without tag", String.format("%s/%s/%s", REPO_HOST, USERNAME, NAME), + new DockerImageURI(REPO_USER_NAME_TAG).getUriWithoutTag()); + } + + @Test + public void testGetBaseUri() { + assertEquals("Exp. to get the uri without repo", USER_NAME_TAG, + new DockerImageURI(REPO_USER_NAME_TAG).getBaseUri()); + } + + @Test + public void testGetAbsoluteUri() { + assertEquals("Exp. to get the full uri", REPO_USER_NAME_TAG, + new DockerImageURI(REPO_USER_NAME_TAG).getAbsoluteUri()); + } + + @Test + public void testGetAbsoluteUriWithoutRepo() { + assertEquals("Exp. to get the full uri without rep", USER_NAME_TAG, + new DockerImageURI(USER_NAME_TAG).getAbsoluteUri()); + } + + @Test + public void testGetAbsoluteUriWithoutUserName() { + assertEquals("Exp. to get the full uri without user name", NAME_TAG, + new DockerImageURI(NAME_TAG).getAbsoluteUri()); + } + + @Test + public void testGetAbsoluteUriWithoutTag() { + assertEquals("Exp. to get the full uri without user name", String.format("%s:%s", NAME, "latest"), + new DockerImageURI(NAME).getAbsoluteUri()); + } + + @Test + public void testName() { + DockerImageURI tag = new DockerImageURI(NAME); + assertEquals(NAME, tag.getName()); + assertEquals("Expected to toString to return the correct uri", String.format("%s:%s", NAME, "latest"), + tag.toString()); + } + + @Test + public void testNameWithTag() { + DockerImageURI tag = new DockerImageURI(NAME_TAG); + assertNameAndTag(tag); + assertEquals("Expected to toString to return the correct uri", NAME_TAG, tag.toString()); + } + + @Test + public void testUserWithNameAndTag() { + DockerImageURI tag = new DockerImageURI(USER_NAME_TAG); + assertNameAndTag(tag); + assertUserName(tag); + assertEquals("Expected to toString to return the correct uri", USER_NAME_TAG, tag.toString()); + } + + @Test + public void testRepoWithUserWithNameAndTag() { + DockerImageURI tag = new DockerImageURI(REPO_USER_NAME_TAG); + assertNameAndTag(tag); + assertUserName(tag); + assertRepoHost(tag); + assertEquals("Expected to toString to return the correct uri", REPO_USER_NAME_TAG, tag.toString()); + } + + private void assertRepoHost(DockerImageURI tag) { + assertEquals("Expected to parse our the repo host", REPO_HOST, tag.getRepositoryHost()); + } + + private void assertUserName(DockerImageURI tag) { + assertEquals("Expected to parse our the username", USERNAME, tag.getUserName()); + } + + private void assertNameAndTag(DockerImageURI tag) { + assertEquals("Expected to parse out the name", NAME, tag.getName()); + assertEquals("Expected to parse out the tage", TAG, tag.getTag()); + } } diff --git a/src/test/java/com/openshift/restclient/model/MocksFactory.java b/src/test/java/com/openshift/restclient/model/MocksFactory.java index 2285c29f..aefadafc 100644 --- a/src/test/java/com/openshift/restclient/model/MocksFactory.java +++ b/src/test/java/com/openshift/restclient/model/MocksFactory.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2016 Red Hat, Inc. + * Copyright (c) 2016-2019 Red Hat, Inc. * Distributed under license by Red Hat, Inc. All rights reserved. * This program is made available under the terms of the * Eclipse Public License v1.0 which accompanies this distribution, @@ -8,9 +8,12 @@ * Contributors: * Red Hat, Inc. - initial API and implementation ******************************************************************************/ + package com.openshift.restclient.model; -import static org.mockito.Mockito.when; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.lenient; import java.lang.reflect.Field; @@ -18,100 +21,117 @@ import com.openshift.internal.restclient.OpenShiftAPIVersion; import com.openshift.internal.restclient.ResourceFactory; +import com.openshift.restclient.IApiTypeMapper; +import com.openshift.restclient.IApiTypeMapper.IVersionedType; import com.openshift.restclient.IClient; import com.openshift.restclient.IResourceFactory; +import com.openshift.restclient.ResourceKind; import com.openshift.restclient.utils.Samples; -/** - * A mock factory to return fixtures of api models. - * - * @author jeff.cantrill - * - */ public class MocksFactory { - - private IClient client; - private IResourceFactory factory; - public MocksFactory() { - this(Mockito.mock(IClient.class)); - } - - public MocksFactory(IClient client) { - this.client = client; - this.factory = new ResourceFactory(client); - } - - public IClient getClient() { - return client; - } - - public T mock(Class klass, String namespace, String name) { - T mock = mock(klass); - when(mock.getNamespace()).thenReturn(namespace); - when(mock.getName()).thenReturn(name); - return mock; - } - - /** - * Mock the given kind based on the class - * @param klass - * @return a mocked instance with mocked name, version, and namespace - */ - public T mock(Class klass) { - final String version = OpenShiftAPIVersion.v1.toString(); - T mock = Mockito.mock(klass); - when(mock.getName()).thenReturn("a" + klass.getSimpleName()); - when(mock.getApiVersion()).thenReturn(version); - when(mock.getNamespace()).thenReturn("aNamespace"); - when(mock.getKind()).thenReturn(klass.getSimpleName().substring(1)); - return mock; - } - - /** - * Stub a given kind based on the JSON files defined in {@link Samples} - * @param kind - * @return a stubbed resource - */ - public T stub(Class kind) { - String name = kind.getSimpleName(); - if(name.startsWith("I")) { - name = name.substring(1); - } - return stub(name); - } - - /** - * Stub a given kind based on the JSON files defined in {@link Samples} - * @param kind - * @return a stubbed resource - */ - public T stub(String kind) { - final String version = OpenShiftAPIVersion.v1.toString(); - String stub = String.format("%s_%s", version, splitCamelCase(kind, "_")).toUpperCase(); - try { - Field field = Samples.class.getField(stub); - Samples sample = (Samples) field.get(null); - return factory.create(sample.getContentAsString()); - } catch (NoSuchFieldException | SecurityException | IllegalArgumentException | IllegalAccessException e) { - throw new RuntimeException(String.format("Sample not found for kind %s"), e); - } - } - - /** - * Split the camelcase string and delimit with the given delimiter - * @param value the camelcase string - * @param delimiter the delimiter for the resulting string - * @return - */ - private String splitCamelCase(String value, String delimiter) { - return value.replaceAll( - String.format("%s|%s|%s", - "(?<=[A-Z])(?=[A-Z][a-z])", - "(?<=[^A-Z])(?=[A-Z])", - "(?<=[A-Za-z])(?=[^A-Za-z])" - ), - delimiter - ); - } + private IClient client; + private IResourceFactory factory; + + public MocksFactory() { + this(Mockito.mock(IClient.class)); + } + + public MocksFactory(IClient client) { + this.client = client; + this.factory = new ResourceFactory(client); + IApiTypeMapper mapper = Mockito.mock(IApiTypeMapper.class); + lenient().when(client.adapt(IApiTypeMapper.class)).thenReturn(mapper); + lenient().when(mapper.getType(anyString(), eq(ResourceKind.BUILD_CONFIG))).thenReturn(new IVersionedType() { + + @Override + public String getVersion() { + return "v1"; + } + + @Override + public String getPrefix() { + return null; + } + + @Override + public String getKind() { + return ResourceKind.BUILD_CONFIG; + } + + @Override + public String getApiGroupName() { + return null; + } + }); + } + + public IClient getClient() { + return client; + } + + public T mock(Class klass, String namespace, String name) { + T mock = mock(klass); + lenient().when(mock.getNamespaceName()).thenReturn(namespace); + lenient().when(mock.getName()).thenReturn(name); + return mock; + } + + /** + * Mock the given kind based on the class + * + * @return a mocked instance with mocked name, version, and namespace + */ + public T mock(Class klass) { + final String version = OpenShiftAPIVersion.v1.toString(); + T mock = Mockito.mock(klass); + lenient().when(mock.getName()).thenReturn("a" + klass.getSimpleName()); + lenient().when(mock.getApiVersion()).thenReturn(version); + lenient().when(mock.getNamespaceName()).thenReturn("aNamespace"); + lenient().when(mock.getKind()).thenReturn(klass.getSimpleName().substring(1)); + return mock; + } + + /** + * Stub a given kind based on the JSON files defined in {@link Samples} + * + * @return a stubbed resource + */ + public T stub(Class kind) { + String name = kind.getSimpleName(); + if (name.startsWith("I")) { + name = name.substring(1); + } + return stub(name); + } + + /** + * Stub a given kind based on the JSON files defined in {@link Samples} + * + * @return a stubbed resource + */ + public T stub(String kind) { + final String version = OpenShiftAPIVersion.v1.toString(); + String stub = String.format("%s_%s", version, splitCamelCase(kind, "_")).toUpperCase(); + try { + Field field = Samples.class.getField(stub); + Samples sample = (Samples) field.get(null); + return factory.create(sample.getContentAsString()); + } catch (NoSuchFieldException | SecurityException | IllegalArgumentException | IllegalAccessException e) { + throw new RuntimeException(String.format("Sample not found for kind %s"), e); + } + } + + /** + * Split the camelcase string and delimit with the given delimiter + * + * @param value + * the camelcase string + * @param delimiter + * the delimiter for the resulting string + */ + private String splitCamelCase(String value, String delimiter) { + return value.replaceAll(String.format("%s|%s|%s", "(?<=[A-Z])(?=[A-Z][a-z])", "(?<=[^A-Z])(?=[A-Z])", + "(?<=[A-Za-z])(?=[^A-Za-z])"), delimiter); + } } diff --git a/src/test/java/com/openshift/restclient/server/HttpServerFake.java b/src/test/java/com/openshift/restclient/server/HttpServerFake.java index 4ecbdcc8..02cbaddd 100644 --- a/src/test/java/com/openshift/restclient/server/HttpServerFake.java +++ b/src/test/java/com/openshift/restclient/server/HttpServerFake.java @@ -16,6 +16,7 @@ * under the License. * *************************************************************************/ + package com.openshift.restclient.server; import java.io.BufferedReader; @@ -31,174 +32,173 @@ import java.text.MessageFormat; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; + import org.apache.commons.io.IOUtils; + /** * @author André Dietisheim * @author Nicolas Spano */ public class HttpServerFake { - public static final int DEFAULT_PORT = 1234; - private static final String DEFAULT_STATUSLINE = "HTTP/1.1 200 OK\n"; - - private ExecutorService executor; - private int port; - private String response; - private String statusLine; - private ServerFakeSocket serverFakeSocket; - - public HttpServerFake(int port) { - this(port, null, DEFAULT_STATUSLINE); - } - - public HttpServerFake() { - this(null); - } - - public HttpServerFake(String response) { - this(DEFAULT_PORT, response, DEFAULT_STATUSLINE); - } - - public HttpServerFake(String response, String statusLine) { - this(DEFAULT_PORT, response, statusLine); - } - - /** - * - * @param port - * the port to listen to (address is always localhost) - * @param response - * the reponse to return to the requesting socket. If - * null the request string is returned. - * @param statusLine the status line that shall be returned - * - * @see ServerFakeSocket#getResponse(Socket) - */ - public HttpServerFake(int port, String response, String statusLine) { - this.port = port; - this.response = response; - if (statusLine != null) { - this.statusLine = statusLine; - } else { - this.statusLine = DEFAULT_STATUSLINE; - } - } - - public void start() throws Exception { - executor = Executors.newFixedThreadPool(1); - this.serverFakeSocket = createServerFakeSocket(statusLine, response, port); - executor.submit(serverFakeSocket); - } - - protected ServerFakeSocket createServerFakeSocket(String statusLine, String response, int port) throws Exception { - return new ServerFakeSocket(statusLine, response, port); - } - - public URL getUrl() throws MalformedURLException { - return new URL(MessageFormat.format("http://localhost:{0}/", String.valueOf(port))); - } - - public URL getHttpsUrl() throws MalformedURLException { - return new URL(MessageFormat.format("https://localhost:{0}/", String.valueOf(port))); - } - - public void stop() { - serverFakeSocket.close(); - executor.shutdownNow(); - } - - - protected void write(byte[] bytes, OutputStream outputStream) throws IOException{ + public static final int DEFAULT_PORT = 1234; + private static final String DEFAULT_STATUSLINE = "HTTP/1.1 200 OK\n"; + + private ExecutorService executor; + private int port; + private String response; + private String statusLine; + private ServerFakeSocket serverFakeSocket; + + public HttpServerFake(int port) { + this(port, null, DEFAULT_STATUSLINE); + } + + public HttpServerFake() { + this(null); + } + + public HttpServerFake(String response) { + this(DEFAULT_PORT, response, DEFAULT_STATUSLINE); + } + + public HttpServerFake(String response, String statusLine) { + this(DEFAULT_PORT, response, statusLine); + } + + /** + * + * @param port + * the port to listen to (address is always localhost) + * @param response + * the reponse to return to the requesting socket. If + * null the request string is returned. + * @param statusLine + * the status line that shall be returned + * + * @see ServerFakeSocket#getResponse(Socket) + */ + public HttpServerFake(int port, String response, String statusLine) { + this.port = port; + this.response = response; + if (statusLine != null) { + this.statusLine = statusLine; + } else { + this.statusLine = DEFAULT_STATUSLINE; + } + } + + public void start() throws Exception { + executor = Executors.newFixedThreadPool(1); + this.serverFakeSocket = createServerFakeSocket(statusLine, response, port); + executor.submit(serverFakeSocket); + } + + protected ServerFakeSocket createServerFakeSocket(String statusLine, String response, int port) throws Exception { + return new ServerFakeSocket(statusLine, response, port); + } + + public URL getUrl() throws MalformedURLException { + return new URL(MessageFormat.format("http://localhost:{0}/", String.valueOf(port))); + } + + public URL getHttpsUrl() throws MalformedURLException { + return new URL(MessageFormat.format("https://localhost:{0}/", String.valueOf(port))); + } + + public void stop() { + serverFakeSocket.close(); + executor.shutdownNow(); + } + + protected void write(byte[] bytes, OutputStream outputStream) throws IOException { outputStream.write(bytes); } - protected int getPort() { - return port; - } - - protected class ServerFakeSocket implements Runnable { - - private String statusLine; - private String response; - private ServerSocket serverSocket; - - public ServerFakeSocket(String statusLine, String response, int port) throws Exception { - this.statusLine = statusLine; - this.response = response; - this.serverSocket = createServerSocket(port); - } - - protected ServerSocket createServerSocket(int port) throws Exception { - return new ServerSocket(port); - } - - public void run() { - Socket socket = null; - OutputStream outputStream = null; - try { - socket = serverSocket.accept(); - String response = getResponse(socket); - outputStream = socket.getOutputStream(); - writeResponseHeader(outputStream); - write(response.getBytes(), outputStream); - outputStream.flush(); - } catch (IOException e) { - // e.printStackTrace(); - } finally { - // we should not close the connection, let the client close the - // connection - IOUtils.closeQuietly(outputStream); - } - } - - protected void writeResponseHeader(OutputStream outputStream) throws IOException { - outputStream.write(statusLine.getBytes()); - outputStream.write("\n".getBytes()); - } - - /** - * Returns the response given to this server at creation time or the - * content that may be read from the socket is returned. - * - * @param inputStream - * @return - * @throws IOException - */ - private String getResponse(Socket socket) throws IOException { - if (response != null) { - return response; - } - return readRequestToString(socket.getInputStream()); - } - - private String readRequestToString(InputStream inputStream) throws IOException { - BufferedReader bufferedReader = null; - bufferedReader = new BufferedReader(new InputStreamReader(inputStream)); - StringWriter writer = new StringWriter(); - String line = null; - while ((line = bufferedReader.readLine()) != null) { - if (line.isEmpty()) { - break; - } - writer.write(line); - writer.write('\n'); - } - return writer.toString(); - } - - public void close() { - silentlyClose(serverSocket); - } - - private void silentlyClose(ServerSocket serverSocket) { - if (serverSocket != null) { - try { - serverSocket.close(); - } catch (IOException e) { - //e.printStackTrace(); - } - } - } - - } + protected int getPort() { + return port; + } + + protected class ServerFakeSocket implements Runnable { + + private String statusLine; + private String response; + private ServerSocket serverSocket; + + public ServerFakeSocket(String statusLine, String response, int port) throws Exception { + this.statusLine = statusLine; + this.response = response; + this.serverSocket = createServerSocket(port); + } + + protected ServerSocket createServerSocket(int port) throws Exception { + return new ServerSocket(port); + } + + public void run() { + Socket socket = null; + OutputStream outputStream = null; + try { + socket = serverSocket.accept(); + String response = getResponse(socket); + outputStream = socket.getOutputStream(); + writeResponseHeader(outputStream); + write(response.getBytes(), outputStream); + outputStream.flush(); + } catch (IOException e) { + // e.printStackTrace(); + } finally { + // we should not close the connection, let the client close the + // connection + IOUtils.closeQuietly(outputStream); + } + } + + protected void writeResponseHeader(OutputStream outputStream) throws IOException { + outputStream.write(statusLine.getBytes()); + outputStream.write("\n".getBytes()); + } + + /** + * Returns the response given to this server at creation time or the content + * that may be read from the socket is returned. + * + */ + private String getResponse(Socket socket) throws IOException { + if (response != null) { + return response; + } + return readRequestToString(socket.getInputStream()); + } + + private String readRequestToString(InputStream inputStream) throws IOException { + BufferedReader bufferedReader = null; + bufferedReader = new BufferedReader(new InputStreamReader(inputStream)); + StringWriter writer = new StringWriter(); + String line = null; + while ((line = bufferedReader.readLine()) != null) { + if (line.isEmpty()) { + break; + } + writer.write(line); + writer.write('\n'); + } + return writer.toString(); + } + + public void close() { + silentlyClose(serverSocket); + } + + private void silentlyClose(ServerSocket serverSocket) { + if (serverSocket != null) { + try { + serverSocket.close(); + } catch (IOException e) { + // e.printStackTrace(); + } + } + } + + } } diff --git a/src/test/java/com/openshift/restclient/server/HttpsServerFake.java b/src/test/java/com/openshift/restclient/server/HttpsServerFake.java index 00260530..c665b9f5 100644 --- a/src/test/java/com/openshift/restclient/server/HttpsServerFake.java +++ b/src/test/java/com/openshift/restclient/server/HttpsServerFake.java @@ -8,6 +8,7 @@ * Contributors: * Red Hat, Inc. - initial API and implementation ******************************************************************************/ + package com.openshift.restclient.server; import java.net.MalformedURLException; @@ -16,7 +17,6 @@ import java.net.URL; import java.security.KeyStore; import java.text.MessageFormat; - import javax.net.ssl.KeyManager; import javax.net.ssl.KeyManagerFactory; import javax.net.ssl.SSLContext; @@ -25,71 +25,75 @@ /** * A Https server fake that holds a single self-signed certificate in its * keystore. The certificate is in src/test/resources/server-keystore.jks and - * hold a single self-signed certificate that was created in the following way (password: 123456): - *


+ * hold a single self-signed certificate that was created in the following way
+ * (password: 123456):
+ * 
+ * 
+ * 
  * keytool -genkey -keystore server-keystore.jks -alias localhost -dname "CN=localhost,OU=JBoss Tools" -keyalg "RSA" -sigalg "SHA1withRSA" -keysize 2048 -validity 3650
- * 
+ *
+ *
* * @author André Dietisheim */ public class HttpsServerFake extends HttpServerFake { - private static final String KEYSTORE_PASSWORD = "123456"; - private static final String KEYSTORE_TYPE = "JKS"; - private static final String KEYSTORE_FILE = "/server-keystore.jks"; - - public HttpsServerFake(int port) { - super(port); - } + private static final String KEYSTORE_PASSWORD = "123456"; + private static final String KEYSTORE_TYPE = "JKS"; + private static final String KEYSTORE_FILE = "/server-keystore.jks"; - /** - * - * @param port - * the port to listen to (address is always localhost) - * @param response - * the reponse to return to the requesting socket. If - * null the request string is returned. - * @param statusLine - * the status line that shall be returned - * - * @see ServerFakeSocket#getResponse(Socket) - */ - public HttpsServerFake(int port, String response, String statusLine) { - super(port, response, statusLine); - } + public HttpsServerFake(int port) { + super(port); + } - @Override - public URL getUrl() throws MalformedURLException { - return new URL(MessageFormat.format("https://localhost:{0}/", String.valueOf(getPort()))); - } + /** + * + * @param port + * the port to listen to (address is always localhost) + * @param response + * the reponse to return to the requesting socket. If + * null the request string is returned. + * @param statusLine + * the status line that shall be returned + * + * @see ServerFakeSocket#getResponse(Socket) + */ + public HttpsServerFake(int port, String response, String statusLine) { + super(port, response, statusLine); + } - @Override - protected ServerFakeSocket createServerFakeSocket(String statusLine, String response, int port) throws Exception { - return new HttpsServerFakeSocket(statusLine, response, port); - } + @Override + public URL getUrl() throws MalformedURLException { + return new URL(MessageFormat.format("https://localhost:{0}/", String.valueOf(getPort()))); + } + @Override + protected ServerFakeSocket createServerFakeSocket(String statusLine, String response, int port) throws Exception { + return new HttpsServerFakeSocket(statusLine, response, port); + } - protected class HttpsServerFakeSocket extends ServerFakeSocket { + protected class HttpsServerFakeSocket extends ServerFakeSocket { - public HttpsServerFakeSocket(String statusLine, String response, int port) throws Exception { - super(statusLine, response, port); - } + public HttpsServerFakeSocket(String statusLine, String response, int port) throws Exception { + super(statusLine, response, port); + } - @Override - protected ServerSocket createServerSocket(int port) throws Exception { - KeyStore keyStore = KeyStore.getInstance(KEYSTORE_TYPE); - keyStore.load(getClass().getResourceAsStream(KEYSTORE_FILE), KEYSTORE_PASSWORD.toCharArray()); + @Override + protected ServerSocket createServerSocket(int port) throws Exception { + KeyStore keyStore = KeyStore.getInstance(KEYSTORE_TYPE); + keyStore.load(getClass().getResourceAsStream(KEYSTORE_FILE), KEYSTORE_PASSWORD.toCharArray()); - KeyManagerFactory keyManagerFactory = - KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm()); - keyManagerFactory.init(keyStore, KEYSTORE_PASSWORD.toCharArray()); - KeyManager keyManagers[] = keyManagerFactory.getKeyManagers(); + KeyManagerFactory keyManagerFactory = KeyManagerFactory + .getInstance(KeyManagerFactory.getDefaultAlgorithm()); + keyManagerFactory.init(keyStore, KEYSTORE_PASSWORD.toCharArray()); + KeyManager [] keyManagers = keyManagerFactory.getKeyManagers(); - SSLContext sslContext = SSLContext.getInstance("TLS"); - sslContext.init(keyManagers, null, null); - SSLServerSocket sslServerSocket = (SSLServerSocket) sslContext.getServerSocketFactory().createServerSocket(port); - sslServerSocket.setEnabledCipherSuites(sslContext.getServerSocketFactory().getSupportedCipherSuites()); - return sslServerSocket; - } - } + SSLContext sslContext = SSLContext.getInstance("TLS"); + sslContext.init(keyManagers, null, null); + SSLServerSocket sslServerSocket = (SSLServerSocket) sslContext.getServerSocketFactory() + .createServerSocket(port); + sslServerSocket.setEnabledCipherSuites(sslContext.getServerSocketFactory().getSupportedCipherSuites()); + return sslServerSocket; + } + } } diff --git a/src/test/java/com/openshift/restclient/server/WaitingHttpServerFake.java b/src/test/java/com/openshift/restclient/server/WaitingHttpServerFake.java index 6b417801..33ffd6d1 100644 --- a/src/test/java/com/openshift/restclient/server/WaitingHttpServerFake.java +++ b/src/test/java/com/openshift/restclient/server/WaitingHttpServerFake.java @@ -8,6 +8,7 @@ * Contributors: * Red Hat, Inc. - initial API and implementation ******************************************************************************/ + package com.openshift.restclient.server; import java.io.IOException; diff --git a/src/test/java/com/openshift/restclient/utils/ExceptionCauseMatcher.java b/src/test/java/com/openshift/restclient/utils/ExceptionCauseMatcher.java index 54738825..38eb77c3 100644 --- a/src/test/java/com/openshift/restclient/utils/ExceptionCauseMatcher.java +++ b/src/test/java/com/openshift/restclient/utils/ExceptionCauseMatcher.java @@ -8,6 +8,7 @@ * Contributors: * Red Hat, Inc. - initial API and implementation ******************************************************************************/ + package com.openshift.restclient.utils; import org.hamcrest.Description; @@ -19,19 +20,18 @@ */ public class ExceptionCauseMatcher extends TypeSafeMatcher { - private Matcher causeMatcher; + private Matcher causeMatcher; - public ExceptionCauseMatcher(Matcher matcher) { - this.causeMatcher = matcher; - } + public ExceptionCauseMatcher(Matcher matcher) { + this.causeMatcher = matcher; + } - public void describeTo(Description description) { - description.appendText("exception with cause "); - } - - @Override - public boolean matchesSafely(Throwable throwable) { - return causeMatcher.matches(throwable.getCause()); - } -} + public void describeTo(Description description) { + description.appendText("exception with cause "); + } + @Override + public boolean matchesSafely(Throwable throwable) { + return causeMatcher.matches(throwable.getCause()); + } +} diff --git a/src/test/java/com/openshift/restclient/utils/ResourceTestHelper.java b/src/test/java/com/openshift/restclient/utils/ResourceTestHelper.java index cbe229fd..99248d2d 100644 --- a/src/test/java/com/openshift/restclient/utils/ResourceTestHelper.java +++ b/src/test/java/com/openshift/restclient/utils/ResourceTestHelper.java @@ -8,9 +8,12 @@ * Contributors: * Red Hat, Inc. - initial API and implementation ******************************************************************************/ + package com.openshift.restclient.utils; -import static org.mockito.Mockito.*; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; import com.openshift.restclient.IClient; import com.openshift.restclient.model.IDeploymentConfig; @@ -18,29 +21,28 @@ /** * Helper for BDD driven unit tests - * @author jeff.cantrill * */ public class ResourceTestHelper { - public static void givenResourceIsAnnotatedWith(IResource resource, String annotation, String value) { - when(resource.isAnnotatedWith(annotation)).thenReturn(true); - when(resource.getAnnotation(annotation)).thenReturn(value); - } - - public static void givenDeployConfigIsVersion(IDeploymentConfig config, int version) { - when(config.getLatestVersionNumber()).thenReturn(version); - } - - public static void thenResourceShouldBeUpdated(IClient client, IResource config) { - verify(client, times(1)).update(config); - } - - public static void thenResourceShouldNotBeUpdated(IClient client, IResource config) { - verify(client, times(0)).update(config); - } - - public static void thenResourceShouldBeRetrieved(IClient client, String namespace, String kind, String name) { - verify(client, times(1)).get(kind, name, namespace); - } + public static void givenResourceIsAnnotatedWith(IResource resource, String annotation, String value) { + when(resource.isAnnotatedWith(annotation)).thenReturn(true); + when(resource.getAnnotation(annotation)).thenReturn(value); + } + + public static void givenDeployConfigIsVersion(IDeploymentConfig config, int version) { + when(config.getLatestVersionNumber()).thenReturn(version); + } + + public static void thenResourceShouldBeUpdated(IClient client, IResource config) { + verify(client, times(1)).update(config); + } + + public static void thenResourceShouldNotBeUpdated(IClient client, IResource config) { + verify(client, times(0)).update(config); + } + + public static void thenResourceShouldBeRetrieved(IClient client, String namespace, String kind, String name) { + verify(client, times(1)).get(kind, name, namespace); + } } diff --git a/src/test/java/com/openshift/restclient/utils/Samples.java b/src/test/java/com/openshift/restclient/utils/Samples.java index 90fe625a..43cc669a 100644 --- a/src/test/java/com/openshift/restclient/utils/Samples.java +++ b/src/test/java/com/openshift/restclient/utils/Samples.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2014-2015 Red Hat, Inc. + * Copyright (c) 2014-2019 Red Hat, Inc. * Distributed under license by Red Hat, Inc. All rights reserved. * This program is made available under the terms of the * Eclipse Public License v1.0 which accompanies this distribution, @@ -8,6 +8,7 @@ * Contributors: * Red Hat, Inc. - initial API and implementation ******************************************************************************/ + package com.openshift.restclient.utils; import java.io.InputStream; @@ -19,65 +20,88 @@ * @author Jeff Cantrill */ public enum Samples { + OPENSHIFT_VERSION("openshift3/api_openshift_version.json"), + KUBERNETES_VERSION("openshift3/api_kubernetes_version.json"), + WELL_KNOW_OAUTH_AUTHORIZATION_SERVER("openshift3/api_well_known_oauth_authorization_server.json"), + + GROUP_ENDPONT_API_V1("openshift3/api_v1_endpoint.json"), + GROUP_ENDPONT_OAPI_V1("openshift3/oapi_v1_endpoint.json"), + GROUP_ENDPONT_APIS("openshift3/apis_endpoint.json"), + GROUP_ENDPONT_APIS_EXTENSIONS("openshift3/apis_endpoint_extensions.json"), + + // api/extensions + V1BETA1_API_EXT_SCALE("openshift3/api/extensions/v1beta1_scale.json"), + + //v1 + V1_KUBE_CONFIG("openshift3/v1_kubeconfig.yaml"), - GROUP_ENDPONT_API_V1("openshift3/api_v1_endpoint.json"), - GROUP_ENDPONT_OAPI_V1("openshift3/oapi_v1_endpoint.json"), - GROUP_ENDPONT_APIS("openshift3/apis_endpoint.json"), - GROUP_ENDPONT_APIS_EXTENSIONS("openshift3/apis_endpoint_extensions.json"), - - //v1 - V1_KUBE_CONFIG("openshift3/v1_kubeconfig.yaml"), + V1_BUILD_CONFIG("openshift3/v1_build_config.json"), + V1_BUILD_CONFIG_LIST("openshift3/v1_build_config_list.json"), + V1_DEPLOYMENT_CONIFIG("openshift3/v1_deployment_config.json"), + V1_ENDPOINTS("openshift3/api/v1_endpoints.json"), + V1_EVENT("openshift3/v1_event.json"), + V1_IMAGE_STREAM("openshift3/v1_image_stream.json"), + V1_IMAGE_STREAM_IMPORT("openshift3/v1_image_stream_import.json"), + V1_BUILD("openshift3/v1_build.json"), + V1_OBJECT_REF("openshift3/v1_objectref.json"), + V1_NAMESPACE("openshift3/v1_namespace.json"), + V1_POD("openshift3/v1_pod.json"), + V1_POD_MULTICONTAINER_READY("openshift3/v1_pod_multiContainer_ready.json"), + V1_PROJECT("openshift3/v1_project.json"), + V1_PROJECT_REQUEST("openshift3/v1_project_request.json"), + V1_PVC("openshift3/v1_pvc.json"), + V1_PERSISTENT_VOLUME("openshift3/v1_persistent_volume.json"), + V1_REPLICATION_CONTROLLER("openshift3/v1_replication_controller.json"), + V1_ROLE_BINDING("openshift3/v1_role_binding.json"), + V1_ROUTE("openshift3/v1_route.json"), + V1_ROUTE_WO_TLS("openshift3/v1_route_wo_tls.json"), + V1_ROUTE_PORT_NUMERIC("openshift3/v1_route_port_numeric.json"), + V1_ROUTE_PORT_NAME("openshift3/v1_route_port_name.json"), + V1_SERVICE("openshift3/v1_service.json"), + V1_SERVICE_ACCOUNT("openshift3/v1_service_account.json"), + V1_Status("openshift3/v1_status.json"), + V1_TEMPLATE("openshift3/v1_template.json"), + GROUP_TEMPLATE("openshift3/group_template.json"), + V1_USER("openshift3/v1_user.json"), + V1_IDENTITY("openshift3/v1_identity.json"), + V1_GROUP("openshift3/v1_group.json"), + V1_SECRET("openshift3/v1_secret.json"), + V1_UNRECOGNIZED("openshift3/v1_unrecognized.json"), + V1_CONFIG_MAP("openshift3/v1_config_map.json"), + V1_CONFIG_MAP_LIST_EMPTY("openshift3/v1_config_map_list_empty.json"), + V1_EMPTYDIR_VOLUME_SOURCE("openshift3/v1_empty_dir_volume_source.json"), + V1_SECRET_VOLUME_SOURCE("openshift3/v1_secret_volume_source.json"), + V1_PVC_VOLUME_SOURCE("openshift3/v1_pvc_volume_source.json"), + V1_LIFECYCLE("openshift3/v1_lifecycle.json"), + V1_DOCKER_IMAGE_MANIFEST("dockerregistry/v1_image_manifest.json"), + V1_BUILDCONFIG_PIPELINE("openshift3/v1_buildconfig_pipeline.json"), + V1_CONFIGMAP_CONSOLE_PUBLIC("openshift3/v1_config_map_console_public.json"), + + RBAC_AUTHORIZATION_K8S_IO_ROLEBINDINGS("k8s/rbac.authorization.k8s.io/v1/rolebindings.json"), + AUTHORIZATION_OPENSHIFT_IO_ROLEBINDINGS("openshift3/authorization.openshift.io/v1/rolebindings.json"); + + private static final String SAMPLES_FOLDER = "/samples/"; - V1_BUILD_CONFIG("openshift3/v1_build_config.json"), - V1_BUILD_CONFIG_LIST("openshift3/v1_build_config_list.json"), - V1_DEPLOYMENT_CONIFIG("openshift3/v1_deployment_config.json"), - V1_IMAGE_STREAM("openshift3/v1_image_stream.json"), - V1_IMAGE_STREAM_IMPORT("openshift3/v1_image_stream_import.json"), - V1_BUILD("openshift3/v1_build.json"), - V1_OBJECT_REF("openshift3/v1_objectref.json"), - V1_POD("openshift3/v1_pod.json"), - V1_PROJECT("openshift3/v1_project.json"), - V1_PROJECT_REQUEST("openshift3/v1_project_request.json"), - V1_PVC("openshift3/v1_pvc.json"), - V1_PERSISTENT_VOLUME("openshift3/v1_persistent_volume.json"), - V1_REPLICATION_CONTROLLER("openshift3/v1_replication_controller.json"), - V1_ROLE_BINDING("openshift3/v1_role_binding.json"), - V1_ROUTE("openshift3/v1_route.json"), - V1_ROUTE_WO_TLS("openshift3/v1_route_wo_tls.json"), - V1_SERVICE("openshift3/v1_service.json"), - V1_SERVICE_ACCOUNT("openshift3/v1_service_account.json"), - V1_Status("openshift3/v1_status.json"), - V1_TEMPLATE("openshift3/v1_template.json"), - V1_USER("openshift3/v1_user.json"), - V1_SECRET("openshift3/v1_secret.json"), - V1_UNRECOGNIZED("openshift3/v1_unrecognized.json"), - V1_CONFIG_MAP("openshift3/v1_config_map.json"), - V1_CONFIG_MAP_LIST_EMPTY("openshift3/v1_config_map_list_empty.json"), - V1_EMPTYDIR_VOLUME_SOURCE("openshift3/v1_empty_dir_volume_source.json"), - V1_SECRET_VOLUME_SOURCE("openshift3/v1_secret_volume_source.json"), - V1_PVC_VOLUME_SOURCE("openshift3/v1_pvc_volume_source.json"); + private String filePath; - private static final String SAMPLES_FOLDER = "/samples/"; + Samples(String fileName) { + this.filePath = SAMPLES_FOLDER + fileName; + } - private String filePath; + Samples(String root, String filename) { + this.filePath = root + filename; + } - Samples(String fileName) { - this.filePath = SAMPLES_FOLDER + fileName; - } - - Samples(String root, String filename){ - this.filePath = root + filename; - } + public String getContentAsString() { + String content = null; + try { + final InputStream contentStream = Samples.class.getResourceAsStream(filePath); + content = IOUtils.toString(contentStream, "UTF-8"); + } catch (Throwable e) { + e.printStackTrace(); + throw new RuntimeException("Could not read file " + filePath + ": " + e.getMessage()); + } + return content; + } - public String getContentAsString() { - String content = null; - try { - final InputStream contentStream = Samples.class.getResourceAsStream(filePath); - content = IOUtils.toString(contentStream, "UTF-8"); - } catch (Throwable e) { - e.printStackTrace(); - throw new RuntimeException("Could not read file " + filePath + ": " + e.getMessage()); - } - return content; - } } diff --git a/src/test/resources/log4j.xml b/src/test/resources/log4j.xml deleted file mode 100644 index dde9ab0a..00000000 --- a/src/test/resources/log4j.xml +++ /dev/null @@ -1,20 +0,0 @@ - - - - - - - - - - - - - - - - - - - - diff --git a/src/test/resources/log4j2.xml b/src/test/resources/log4j2.xml new file mode 100644 index 00000000..27b353e2 --- /dev/null +++ b/src/test/resources/log4j2.xml @@ -0,0 +1,18 @@ + +> + + + + + + + + + + + \ No newline at end of file diff --git a/src/test/resources/openshiftv3IntegrationTest.properties b/src/test/resources/openshiftv3IntegrationTest.properties index 272d35c4..b7cef753 100644 --- a/src/test/resources/openshiftv3IntegrationTest.properties +++ b/src/test/resources/openshiftv3IntegrationTest.properties @@ -1,9 +1,24 @@ -#serverURL=https://127.0.0.1:8443 -serverURL=https://10.1.2.2:8443 - -#osadm policy add-cluster-role-to-user cluster-admin $ADMIN_USER --config=openshift.local.config/master/admin.kubeconfig -default.clusteradmin.user=admin -default.clusteradmin.password=admin -default.project=int-test -default.openshift.location=/home/jeff.cantrill/scripts/oc +# cdk +serverURL=https://192.168.64.91:8443 +default.clusteradmin.user=developer +default.clusteradmin.password=developer +# OS 4.1 +serverURL=https://api.crw.codereadyqe.com:6443 +default.clusteradmin.user=andre +default.clusteradmin.password=andre +# OS 3.11 +#serverURL=https://console.rh-us-east-1.openshift.com +#default.clusteradmin.user= +#default.clusteradmin.password= +# OS 4.2 +#serverURL= +#default.clusteradmin.user= +#default.clusteradmin.password= + +integrationtest.project=int-test +ocbinary.location=/usr/local/bin/oc + +# to allow policy and roles integration tests to pass, in cdk enable admin-user.addon or execute +#oc adm policy add-cluster-role-to-user cluster-admin admin + diff --git a/src/test/resources/rest-spring-boot.zip b/src/test/resources/rest-spring-boot.zip new file mode 100644 index 00000000..3831fe12 Binary files /dev/null and b/src/test/resources/rest-spring-boot.zip differ diff --git a/src/test/resources/samples/dockerregistry/v1_image_manifest.json b/src/test/resources/samples/dockerregistry/v1_image_manifest.json new file mode 100644 index 00000000..7265208d --- /dev/null +++ b/src/test/resources/samples/dockerregistry/v1_image_manifest.json @@ -0,0 +1,38 @@ +{ + "schemaVersion": 1, + "name": "openshift/hello-openshift", + "tag": "latest", + "architecture": "amd64", + "fsLayers": [ + { + "blobSum": "sha256:3617f1cc9f1a693e5bd904855aa07d448aa2b1600fa773396ec7042b456adb71" + }, + { + "blobSum": "sha256:a3ed95caeb02ffe68cdd9fd84406680ae93d633cb16422d00e8a7c22955b46d4" + } + ], + "history": [ + { + "v1Compatibility": "{\"architecture\":\"amd64\",\"author\":\"Jessica Forrester \\u003cjforrest@redhat.com\\u003e\",\"config\":{\"Hostname\":\"\",\"Domainname\":\"\",\"User\":\"\",\"AttachStdin\":false,\"AttachStdout\":false,\"AttachStderr\":false,\"ExposedPorts\":{\"8080/tcp\":{},\"8888/tcp\":{}},\"Tty\":false,\"OpenStdin\":false,\"StdinOnce\":false,\"Env\":[\"PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin\"],\"Cmd\":null,\"Image\":\"\",\"Volumes\":null,\"WorkingDir\":\"\",\"Entrypoint\":[\"/hello-openshift\"],\"OnBuild\":null,\"Labels\":{}},\"container\":\"3b9f6b446705b66fd50dee69a24bd956e18798ce259f527917fe336302654d76\",\"container_config\":{\"Hostname\":\"3b9f6b446705\",\"Domainname\":\"\",\"User\":\"\",\"AttachStdin\":false,\"AttachStdout\":false,\"AttachStderr\":false,\"Tty\":false,\"OpenStdin\":false,\"StdinOnce\":false,\"Env\":null,\"Cmd\":null,\"Image\":\"scratch-o9u3gdotxmoitn1v9pcyz7qn\",\"Volumes\":null,\"WorkingDir\":\"\",\"Entrypoint\":[\"/bin/sh\",\"-c\",\"# NOP\"],\"OnBuild\":null,\"Labels\":{}},\"created\":\"2016-06-22T20:14:52.468448916Z\",\"docker_version\":\"1.10.3\",\"id\":\"5f162644b2633962f753b9a09c7783d342c8aaebccaf6270fde68404d2af7a8c\",\"os\":\"linux\",\"parent\":\"3690474eb5b4b26fdfbd89c6e159e8cc376ca76ef48032a30fa6aafd56337880\"}" + }, + { + "v1Compatibility": "{\"id\":\"3690474eb5b4b26fdfbd89c6e159e8cc376ca76ef48032a30fa6aafd56337880\",\"comment\":\"Imported from -\",\"created\":\"2016-06-22T20:14:51.59971969Z\",\"container_config\":{\"Cmd\":[\"\"]}}" + } + ], + "signatures": [ + { + "header": { + "jwk": { + "crv": "P-256", + "kid": "CH7Z:EUDI:ZK45:Z644:ZVCW:AXKU:TNHT:G23N:QUDL:PXLW:4RSV:QTF4", + "kty": "EC", + "x": "ldmqX-aMDXSs3_zCy8co89v6v5CJh9nAskmLW7a4vIw", + "y": "OD9FZrrTo5nBzndcvpwlqrzzoZ4PI4BbYcdvfAvHdbA" + }, + "alg": "ES256" + }, + "signature": "l2qVDJfKpBRtD5Lcuj9RJ8wI2SwfjO6jVnd8q9_zN-dz4EJkF-5Aww7_0gdAz7tV-AmuG9_HIL8fdcDtof-Txg", + "protected": "eyJmb3JtYXRMZW5ndGgiOjE5NDEsImZvcm1hdFRhaWwiOiJDbjAiLCJ0aW1lIjoiMjAxNi0wNi0yM1QxNjowNTowNloifQ" + } + ] +} \ No newline at end of file diff --git a/src/test/resources/samples/k8s/rbac.authorization.k8s.io/v1/rolebindings.json b/src/test/resources/samples/k8s/rbac.authorization.k8s.io/v1/rolebindings.json new file mode 100644 index 00000000..0f54f9a0 --- /dev/null +++ b/src/test/resources/samples/k8s/rbac.authorization.k8s.io/v1/rolebindings.json @@ -0,0 +1,139 @@ +{ + "apiVersion": "v1", + "items": [ + { + "apiVersion": "rbac.authorization.k8s.io/v1", + "kind": "RoleBinding", + "metadata": { + "creationTimestamp": "2020-04-16T14:37:03Z", + "name": "machine-config-daemon-events", + "namespace": "default", + "resourceVersion": "2388", + "selfLink": "/apis/rbac.authorization.k8s.io/v1/namespaces/default/rolebindings/machine-config-daemon-events", + "uid": "ffc653d7-9cb1-4af9-89d4-1aa95512b1fd" + }, + "roleRef": { + "apiGroup": "rbac.authorization.k8s.io", + "kind": "ClusterRole", + "name": "machine-config-daemon-events" + }, + "subjects": [ + { + "kind": "ServiceAccount", + "name": "machine-config-daemon", + "namespace": "openshift-machine-config-operator" + } + ] + }, + { + "apiVersion": "rbac.authorization.k8s.io/v1", + "kind": "RoleBinding", + "metadata": { + "creationTimestamp": "2020-04-16T15:05:23Z", + "name": "prometheus-k8s", + "namespace": "default", + "resourceVersion": "15971", + "selfLink": "/apis/rbac.authorization.k8s.io/v1/namespaces/default/rolebindings/prometheus-k8s", + "uid": "016e7037-7081-45ef-bf3c-3f75773b0ef9" + }, + "roleRef": { + "apiGroup": "rbac.authorization.k8s.io", + "kind": "Role", + "name": "prometheus-k8s" + }, + "subjects": [ + { + "kind": "ServiceAccount", + "name": "prometheus-k8s", + "namespace": "openshift-monitoring" + } + ] + }, + { + "apiVersion": "rbac.authorization.k8s.io/v1", + "kind": "RoleBinding", + "metadata": { + "annotations": { + "openshift.io/description": "Allows deploymentconfigs in this namespace to rollout pods in this namespace. It is auto-managed by a controller; remove subjects to disable." + }, + "creationTimestamp": "2020-04-16T14:42:27Z", + "name": "system:deployers", + "namespace": "default", + "resourceVersion": "6343", + "selfLink": "/apis/rbac.authorization.k8s.io/v1/namespaces/default/rolebindings/system:deployers", + "uid": "686aef1c-9b44-4b14-b618-7b795dce8afb" + }, + "roleRef": { + "apiGroup": "rbac.authorization.k8s.io", + "kind": "ClusterRole", + "name": "system:deployer" + }, + "subjects": [ + { + "kind": "ServiceAccount", + "name": "deployer", + "namespace": "default" + } + ] + }, + { + "apiVersion": "rbac.authorization.k8s.io/v1", + "kind": "RoleBinding", + "metadata": { + "annotations": { + "openshift.io/description": "Allows builds in this namespace to push images to this namespace. It is auto-managed by a controller; remove subjects to disable." + }, + "creationTimestamp": "2020-04-16T14:42:27Z", + "name": "system:image-builders", + "namespace": "default", + "resourceVersion": "6309", + "selfLink": "/apis/rbac.authorization.k8s.io/v1/namespaces/default/rolebindings/system:image-builders", + "uid": "168be431-6fb1-4ff2-b31d-69f25425da20" + }, + "roleRef": { + "apiGroup": "rbac.authorization.k8s.io", + "kind": "ClusterRole", + "name": "system:image-builder" + }, + "subjects": [ + { + "kind": "ServiceAccount", + "name": "builder", + "namespace": "default" + } + ] + }, + { + "apiVersion": "rbac.authorization.k8s.io/v1", + "kind": "RoleBinding", + "metadata": { + "annotations": { + "openshift.io/description": "Allows all pods in this namespace to pull images from this namespace. It is auto-managed by a controller; remove subjects to disable." + }, + "creationTimestamp": "2020-04-16T14:42:26Z", + "name": "system:image-pullers", + "namespace": "default", + "resourceVersion": "6276", + "selfLink": "/apis/rbac.authorization.k8s.io/v1/namespaces/default/rolebindings/system:image-pullers", + "uid": "0ce48cfa-80c0-4ec0-a6ba-e7f10aa8ed9c" + }, + "roleRef": { + "apiGroup": "rbac.authorization.k8s.io", + "kind": "ClusterRole", + "name": "system:image-puller" + }, + "subjects": [ + { + "apiGroup": "rbac.authorization.k8s.io", + "kind": "Group", + "name": "system:serviceaccounts:default" + } + ] + } + ], + "kind": "List", + "metadata": { + "resourceVersion": "", + "selfLink": "" + } +} diff --git a/src/test/resources/samples/openshift3/api/extensions/v1beta1_scale.json b/src/test/resources/samples/openshift3/api/extensions/v1beta1_scale.json new file mode 100644 index 00000000..b3a8eee2 --- /dev/null +++ b/src/test/resources/samples/openshift3/api/extensions/v1beta1_scale.json @@ -0,0 +1,15 @@ +{ + "kind": "Scale", + "apiVersion": "extensions/v1beta1", + "metadata": { + "name": "logging-kibana", + "namespace": "logging", + "creationTimestamp": "2016-08-22T20:09:51Z" + }, + "spec": { + "replicas": 2 + }, + "status": { + "replicas": 0 + } +} \ No newline at end of file diff --git a/src/test/resources/samples/openshift3/api/v1_endpoints.json b/src/test/resources/samples/openshift3/api/v1_endpoints.json new file mode 100644 index 00000000..06600028 --- /dev/null +++ b/src/test/resources/samples/openshift3/api/v1_endpoints.json @@ -0,0 +1,56 @@ +{ + "kind": "Endpoints", + "apiVersion": "v1", + "metadata": { + "name": "router", + "namespace": "default", + "selfLink": "/api/v1/namespaces/default/endpoints/router", + "uid": "0cfabcdf-c16b-11e6-80f6-525400320112", + "resourceVersion": "603", + "creationTimestamp": "2016-12-13T19:33:40Z", + "labels": { + "router": "router" + } + }, + "subsets": [ + { + "addresses": [ + { + "ip": "192.168.121.62", + "targetRef": { + "kind": "Pod", + "namespace": "default", + "name": "router-1-sk2p5", + "uid": "1a1f7dad-c16b-11e6-80f6-525400320112", + "resourceVersion": "601" + } + } + ], + "notreadyaddresses": [ + { + "name": "notready", + "ip": "192.168.121.68", + "hostname": "foo.bar", + "nodeName": "xyz.abc" + } + ], + "ports": [ + { + "name": "443-tcp", + "port": 443, + "protocol": "TCP" + }, + { + "name": "1936-tcp", + "port": 1936, + "protocol": "TCP" + }, + { + "name": "80-tcp", + "port": 80, + "protocol": "TCP" + } + ] + } + ] +} diff --git a/src/test/resources/samples/openshift3/api_kubernetes_version.json b/src/test/resources/samples/openshift3/api_kubernetes_version.json new file mode 100644 index 00000000..dc24fde9 --- /dev/null +++ b/src/test/resources/samples/openshift3/api_kubernetes_version.json @@ -0,0 +1,11 @@ +{ + "major": "1", + "minor": "6", + "gitVersion": "v1.6.1+5115d708d7", + "gitCommit": "010d313", + "gitTreeState": "clean", + "buildDate": "2017-06-07T23:14:34Z", + "goVersion": "go1.7.5", + "compiler": "gc", + "platform": "linux/amd64" +} diff --git a/src/test/resources/samples/openshift3/api_openshift_version.json b/src/test/resources/samples/openshift3/api_openshift_version.json new file mode 100644 index 00000000..70ba3dfa --- /dev/null +++ b/src/test/resources/samples/openshift3/api_openshift_version.json @@ -0,0 +1,7 @@ +{ + "major": "3", + "minor": "6+", + "gitCommit": "3c221d5", + "gitVersion": "v3.6.0-alpha.2+3c221d5", + "buildDate": "2017-06-07T23:14:34Z" +} diff --git a/src/test/resources/samples/openshift3/api_v1_endpoint.json b/src/test/resources/samples/openshift3/api_v1_endpoint.json index 416b8031..ca080238 100644 --- a/src/test/resources/samples/openshift3/api_v1_endpoint.json +++ b/src/test/resources/samples/openshift3/api_v1_endpoint.json @@ -4,183 +4,492 @@ "resources": [ { "name": "bindings", + "singularName": "", "namespaced": true, - "kind": "Binding" + "kind": "Binding", + "verbs": [ + "create" + ] }, { "name": "componentstatuses", + "singularName": "", "namespaced": false, - "kind": "ComponentStatus" + "kind": "ComponentStatus", + "verbs": [ + "get", + "list" + ], + "shortNames": [ + "cs" + ] }, { "name": "configmaps", + "singularName": "", "namespaced": true, - "kind": "ConfigMap" + "kind": "ConfigMap", + "verbs": [ + "create", + "delete", + "deletecollection", + "get", + "list", + "patch", + "update", + "watch" + ], + "shortNames": [ + "cm" + ] }, { "name": "endpoints", + "singularName": "", "namespaced": true, - "kind": "Endpoints" + "kind": "Endpoints", + "verbs": [ + "create", + "delete", + "deletecollection", + "get", + "list", + "patch", + "update", + "watch" + ], + "shortNames": [ + "ep" + ] }, { "name": "events", + "singularName": "", "namespaced": true, - "kind": "Event" + "kind": "Event", + "verbs": [ + "create", + "delete", + "deletecollection", + "get", + "list", + "patch", + "update", + "watch" + ], + "shortNames": [ + "ev" + ] }, { "name": "limitranges", + "singularName": "", "namespaced": true, - "kind": "LimitRange" + "kind": "LimitRange", + "verbs": [ + "create", + "delete", + "deletecollection", + "get", + "list", + "patch", + "update", + "watch" + ], + "shortNames": [ + "limits" + ] }, { "name": "namespaces", + "singularName": "", "namespaced": false, - "kind": "Namespace" + "kind": "Namespace", + "verbs": [ + "create", + "delete", + "get", + "list", + "patch", + "update", + "watch" + ], + "shortNames": [ + "ns" + ] }, { "name": "namespaces/finalize", + "singularName": "", "namespaced": false, - "kind": "Namespace" + "kind": "Namespace", + "verbs": [ + "update" + ] }, { "name": "namespaces/status", + "singularName": "", "namespaced": false, - "kind": "Namespace" + "kind": "Namespace", + "verbs": [ + "get", + "patch", + "update" + ] }, { "name": "nodes", + "singularName": "", "namespaced": false, - "kind": "Node" + "kind": "Node", + "verbs": [ + "create", + "delete", + "deletecollection", + "get", + "list", + "patch", + "update", + "watch" + ], + "shortNames": [ + "no" + ] }, { "name": "nodes/proxy", + "singularName": "", "namespaced": false, - "kind": "Node" + "kind": "Node", + "verbs": [] }, { "name": "nodes/status", + "singularName": "", "namespaced": false, - "kind": "Node" + "kind": "Node", + "verbs": [ + "get", + "patch", + "update" + ] }, { "name": "persistentvolumeclaims", + "singularName": "", "namespaced": true, - "kind": "PersistentVolumeClaim" + "kind": "PersistentVolumeClaim", + "verbs": [ + "create", + "delete", + "deletecollection", + "get", + "list", + "patch", + "update", + "watch" + ], + "shortNames": [ + "pvc" + ] }, { "name": "persistentvolumeclaims/status", + "singularName": "", "namespaced": true, - "kind": "PersistentVolumeClaim" + "kind": "PersistentVolumeClaim", + "verbs": [ + "get", + "patch", + "update" + ] }, { "name": "persistentvolumes", + "singularName": "", "namespaced": false, - "kind": "PersistentVolume" + "kind": "PersistentVolume", + "verbs": [ + "create", + "delete", + "deletecollection", + "get", + "list", + "patch", + "update", + "watch" + ], + "shortNames": [ + "pv" + ] }, { "name": "persistentvolumes/status", + "singularName": "", "namespaced": false, - "kind": "PersistentVolume" + "kind": "PersistentVolume", + "verbs": [ + "get", + "patch", + "update" + ] }, { "name": "pods", + "singularName": "", "namespaced": true, - "kind": "Pod" + "kind": "Pod", + "verbs": [ + "create", + "delete", + "deletecollection", + "get", + "list", + "patch", + "update", + "watch" + ], + "shortNames": [ + "po" + ], + "categories": [ + "all" + ] }, { "name": "pods/attach", + "singularName": "", "namespaced": true, - "kind": "Pod" + "kind": "Pod", + "verbs": [] }, { "name": "pods/binding", + "singularName": "", "namespaced": true, - "kind": "Binding" + "kind": "Binding", + "verbs": [ + "create" + ] + }, + { + "name": "pods/eviction", + "singularName": "", + "namespaced": true, + "group": "policy", + "version": "v1beta1", + "kind": "Eviction", + "verbs": [ + "create" + ] }, { "name": "pods/exec", + "singularName": "", "namespaced": true, - "kind": "Pod" + "kind": "Pod", + "verbs": [] }, { "name": "pods/log", + "singularName": "", "namespaced": true, - "kind": "Pod" + "kind": "Pod", + "verbs": [ + "get" + ] }, { "name": "pods/portforward", + "singularName": "", "namespaced": true, - "kind": "Pod" + "kind": "Pod", + "verbs": [] }, { "name": "pods/proxy", + "singularName": "", "namespaced": true, - "kind": "Pod" + "kind": "Pod", + "verbs": [] }, { "name": "pods/status", + "singularName": "", "namespaced": true, - "kind": "Pod" + "kind": "Pod", + "verbs": [ + "get", + "patch", + "update" + ] }, { "name": "podtemplates", + "singularName": "", "namespaced": true, - "kind": "PodTemplate" + "kind": "PodTemplate", + "verbs": [ + "create", + "delete", + "deletecollection", + "get", + "list", + "patch", + "update", + "watch" + ] }, { "name": "replicationcontrollers", + "singularName": "", "namespaced": true, - "kind": "ReplicationController" + "kind": "ReplicationController", + "verbs": [ + "create", + "delete", + "deletecollection", + "get", + "list", + "patch", + "update", + "watch" + ], + "shortNames": [ + "rc" + ], + "categories": [ + "all" + ] }, { "name": "replicationcontrollers/scale", + "singularName": "", "namespaced": true, - "kind": "Scale" + "group": "autoscaling", + "version": "v1", + "kind": "Scale", + "verbs": [ + "get", + "patch", + "update" + ] }, { "name": "replicationcontrollers/status", + "singularName": "", "namespaced": true, - "kind": "ReplicationController" + "kind": "ReplicationController", + "verbs": [ + "get", + "patch", + "update" + ] }, { "name": "resourcequotas", + "singularName": "", "namespaced": true, - "kind": "ResourceQuota" + "kind": "ResourceQuota", + "verbs": [ + "create", + "delete", + "deletecollection", + "get", + "list", + "patch", + "update", + "watch" + ], + "shortNames": [ + "quota" + ] }, { "name": "resourcequotas/status", + "singularName": "", "namespaced": true, - "kind": "ResourceQuota" + "kind": "ResourceQuota", + "verbs": [ + "get", + "patch", + "update" + ] }, { "name": "secrets", + "singularName": "", "namespaced": true, - "kind": "Secret" - }, - { - "name": "securitycontextconstraints", - "namespaced": false, - "kind": "SecurityContextConstraints" + "kind": "Secret", + "verbs": [ + "create", + "delete", + "deletecollection", + "get", + "list", + "patch", + "update", + "watch" + ] }, { "name": "serviceaccounts", + "singularName": "", "namespaced": true, - "kind": "ServiceAccount" + "kind": "ServiceAccount", + "verbs": [ + "create", + "delete", + "deletecollection", + "get", + "list", + "patch", + "update", + "watch" + ], + "shortNames": [ + "sa" + ] }, { "name": "services", + "singularName": "", "namespaced": true, - "kind": "Service" + "kind": "Service", + "verbs": [ + "create", + "delete", + "get", + "list", + "patch", + "update", + "watch" + ], + "shortNames": [ + "svc" + ], + "categories": [ + "all" + ] }, { "name": "services/proxy", + "singularName": "", "namespaced": true, - "kind": "Service" + "kind": "Service", + "verbs": [] }, { "name": "services/status", + "singularName": "", "namespaced": true, - "kind": "Service" + "kind": "Service", + "verbs": [ + "get", + "patch", + "update" + ] } ] } \ No newline at end of file diff --git a/src/test/resources/samples/openshift3/api_well_known_oauth_authorization_server.json b/src/test/resources/samples/openshift3/api_well_known_oauth_authorization_server.json new file mode 100644 index 00000000..dbe01bab --- /dev/null +++ b/src/test/resources/samples/openshift3/api_well_known_oauth_authorization_server.json @@ -0,0 +1,24 @@ +{ + "issuer": "https://api.rh-us-east-1.openshift.com", + "authorization_endpoint": "https://api.rh-us-east-1.openshift.com/oauth/authorize", + "token_endpoint": "https://api.rh-us-east-1.openshift.com/oauth/token", + "scopes_supported": [ + "user:check-access", + "user:full", + "user:info", + "user:list-projects", + "user:list-scoped-projects" + ], + "response_types_supported": [ + "code", + "token" + ], + "grant_types_supported": [ + "authorization_code", + "implicit" + ], + "code_challenge_methods_supported": [ + "plain", + "S256" + ] +} \ No newline at end of file diff --git a/src/test/resources/samples/openshift3/apis_endpoint_extensions.json b/src/test/resources/samples/openshift3/apis_endpoint_extensions.json index b4c64c5c..16fc80cf 100644 --- a/src/test/resources/samples/openshift3/apis_endpoint_extensions.json +++ b/src/test/resources/samples/openshift3/apis_endpoint_extensions.json @@ -4,88 +4,214 @@ "resources": [ { "name": "daemonsets", - "namespaced": true, - "kind": "DaemonSet" + "singularName": "", + "namespaced": true, + "kind": "DaemonSet", + "verbs": [ + "create", + "delete", + "deletecollection", + "get", + "list", + "patch", + "update", + "watch" + ], + "shortNames": [ + "ds" + ] }, { "name": "daemonsets/status", + "singularName": "", "namespaced": true, - "kind": "DaemonSet" + "kind": "DaemonSet", + "verbs": [ + "get", + "patch", + "update" + ] }, { "name": "deployments", - "namespaced": true, - "kind": "Deployment" + "singularName": "", + "namespaced": true, + "kind": "Deployment", + "verbs": [ + "create", + "delete", + "deletecollection", + "get", + "list", + "patch", + "update", + "watch" + ], + "shortNames": [ + "deploy" + ] }, { "name": "deployments/rollback", + "singularName": "", "namespaced": true, - "kind": "DeploymentRollback" + "kind": "DeploymentRollback", + "verbs": [ + "create" + ] }, { "name": "deployments/scale", + "singularName": "", "namespaced": true, - "kind": "Scale" + "group": "extensions", + "version": "v1beta1", + "kind": "Scale", + "verbs": [ + "get", + "patch", + "update" + ] }, { "name": "deployments/status", + "singularName": "", "namespaced": true, - "kind": "Deployment" - }, - { - "name": "horizontalpodautoscalers", - "namespaced": true, - "kind": "HorizontalPodAutoscaler" - }, - { - "name": "horizontalpodautoscalers/status", - "namespaced": true, - "kind": "HorizontalPodAutoscaler" + "kind": "Deployment", + "verbs": [ + "get", + "patch", + "update" + ] }, { "name": "ingresses", - "namespaced": true, - "kind": "Ingress" + "singularName": "", + "namespaced": true, + "kind": "Ingress", + "verbs": [ + "create", + "delete", + "deletecollection", + "get", + "list", + "patch", + "update", + "watch" + ], + "shortNames": [ + "ing" + ] }, { "name": "ingresses/status", - "namespaced": true, - "kind": "Ingress" - }, - { - "name": "jobs", - "namespaced": true, - "kind": "Job" - }, - { - "name": "jobs/status", - "namespaced": true, - "kind": "Job" + "singularName": "", + "namespaced": true, + "kind": "Ingress", + "verbs": [ + "get", + "patch", + "update" + ] + }, + { + "name": "networkpolicies", + "singularName": "", + "namespaced": true, + "kind": "NetworkPolicy", + "verbs": [ + "create", + "delete", + "deletecollection", + "get", + "list", + "patch", + "update", + "watch" + ], + "shortNames": [ + "netpol" + ] + }, + { + "name": "podsecuritypolicies", + "singularName": "", + "namespaced": false, + "kind": "PodSecurityPolicy", + "verbs": [ + "create", + "delete", + "deletecollection", + "get", + "list", + "patch", + "update", + "watch" + ], + "shortNames": [ + "psp" + ] }, { "name": "replicasets", - "namespaced": true, - "kind": "ReplicaSet" + "singularName": "", + "namespaced": true, + "kind": "ReplicaSet", + "verbs": [ + "create", + "delete", + "deletecollection", + "get", + "list", + "patch", + "update", + "watch" + ], + "shortNames": [ + "rs" + ] }, { "name": "replicasets/scale", + "singularName": "", "namespaced": true, - "kind": "Scale" + "group": "extensions", + "version": "v1beta1", + "kind": "Scale", + "verbs": [ + "get", + "patch", + "update" + ] }, { "name": "replicasets/status", + "singularName": "", "namespaced": true, - "kind": "ReplicaSet" + "kind": "ReplicaSet", + "verbs": [ + "get", + "patch", + "update" + ] }, { "name": "replicationcontrollers", + "singularName": "", "namespaced": true, - "kind": "ReplicationControllerDummy" + "kind": "ReplicationControllerDummy", + "verbs": [] }, { "name": "replicationcontrollers/scale", - "namespaced": true, - "kind": "Scale" + "singularName": "", + "namespaced": true, + "kind": "Scale", + "verbs": [ + "get", + "patch", + "update" + ] } ] } \ No newline at end of file diff --git a/src/test/resources/samples/openshift3/authorization.openshift.io/v1/rolebindings.json b/src/test/resources/samples/openshift3/authorization.openshift.io/v1/rolebindings.json new file mode 100644 index 00000000..2d1a29c6 --- /dev/null +++ b/src/test/resources/samples/openshift3/authorization.openshift.io/v1/rolebindings.json @@ -0,0 +1,140 @@ +{ + "apiVersion": "v1", + "items": [ + { + "apiVersion": "authorization.openshift.io/v1", + "groupNames": null, + "kind": "RoleBinding", + "metadata": { + "creationTimestamp": "2019-03-06T15:28:13Z", + "name": "admin", + "namespace": "jbosstools", + "resourceVersion": "231467480", + "selfLink": "/apis/authorization.openshift.io/v1/namespaces/jbosstools/rolebindings/admin", + "uid": "74f6f212-4024-11e9-98a4-02e0bae989b4" + }, + "roleRef": { + "name": "admin" + }, + "subjects": [ + { + "kind": "User", + "name": "105985317302514941658" + } + ], + "userNames": [ + "105985317302514941658" + ] + }, + { + "apiVersion": "authorization.openshift.io/v1", + "groupNames": null, + "kind": "RoleBinding", + "metadata": { + "creationTimestamp": "2019-03-06T15:28:13Z", + "name": "project-owner", + "namespace": "jbosstools", + "resourceVersion": "231467483", + "selfLink": "/apis/authorization.openshift.io/v1/namespaces/jbosstools/rolebindings/project-owner", + "uid": "74f7fe60-4024-11e9-98a4-02e0bae989b4" + }, + "roleRef": { + "name": "project-owner" + }, + "subjects": [ + { + "kind": "User", + "name": "105985317302514941658" + } + ], + "userNames": [ + "105985317302514941658" + ] + }, + { + "apiVersion": "authorization.openshift.io/v1", + "groupNames": null, + "kind": "RoleBinding", + "metadata": { + "creationTimestamp": "2019-03-06T15:28:13Z", + "name": "system:deployers", + "namespace": "jbosstools", + "resourceVersion": "231467487", + "selfLink": "/apis/authorization.openshift.io/v1/namespaces/jbosstools/rolebindings/system%3Adeployers", + "uid": "74fb1262-4024-11e9-98a4-02e0bae989b4" + }, + "roleRef": { + "name": "system:deployer" + }, + "subjects": [ + { + "kind": "ServiceAccount", + "name": "deployer", + "namespace": "jbosstools" + } + ], + "userNames": [ + "system:serviceaccount:jbosstools:deployer" + ] + }, + { + "apiVersion": "authorization.openshift.io/v1", + "groupNames": null, + "kind": "RoleBinding", + "metadata": { + "creationTimestamp": "2019-03-06T15:28:13Z", + "name": "system:image-builders", + "namespace": "jbosstools", + "resourceVersion": "231467485", + "selfLink": "/apis/authorization.openshift.io/v1/namespaces/jbosstools/rolebindings/system%3Aimage-builders", + "uid": "74fa4045-4024-11e9-98a4-02e0bae989b4" + }, + "roleRef": { + "name": "system:image-builder" + }, + "subjects": [ + { + "kind": "ServiceAccount", + "name": "builder", + "namespace": "jbosstools" + } + ], + "userNames": [ + "system:serviceaccount:jbosstools:builder" + ] + }, + { + "apiVersion": "authorization.openshift.io/v1", + "groupNames": [ + "system:serviceaccounts:jbosstools" + ], + "kind": "RoleBinding", + "metadata": { + "annotations": { + "openshift.io/description": "Allows all pods in this namespace to pull images from this namespace. It is auto-managed by a controller; remove subjects to disable." + }, + "creationTimestamp": "2019-03-06T15:28:13Z", + "name": "system:image-pullers", + "namespace": "jbosstools", + "resourceVersion": "231467475", + "selfLink": "/apis/authorization.openshift.io/v1/namespaces/jbosstools/rolebindings/system%3Aimage-pullers", + "uid": "74f0bf3f-4024-11e9-8234-02fe3a6cfaba" + }, + "roleRef": { + "name": "system:image-puller" + }, + "subjects": [ + { + "kind": "SystemGroup", + "name": "system:serviceaccounts:jbosstools" + } + ], + "userNames": null + } + ], + "kind": "List", + "metadata": { + "resourceVersion": "", + "selfLink": "" + } +} diff --git a/src/test/resources/samples/openshift3/group_template.json b/src/test/resources/samples/openshift3/group_template.json new file mode 100644 index 00000000..306845e5 --- /dev/null +++ b/src/test/resources/samples/openshift3/group_template.json @@ -0,0 +1,450 @@ +{ + "kind": "Template", + "apiVersion": "template.openshift.io/v1", + "metadata": { + "name": "ruby-helloworld-sample", + "namespace": "myproject", + "selfLink": "/oapi/v1/namespaces/myproject/templates/ruby-helloworld-sample", + "uid": "870dab76-38c7-11e6-8e5e-3c970e32f15a", + "resourceVersion": "86618", + "creationTimestamp": "2016-06-22T22:20:29Z", + "labels": { + "abc": "xyz", + "foo": "bar" + }, + "annotations": { + "description": "This example shows how to create a simple ruby application in openshift origin v3", + "iconClass": "icon-ruby", + "tags": "instant-app,ruby,mysql" + } + }, + "objects": [ + { + "kind": "Service", + "apiVersion": "v1", + "metadata": { + "name": "frontend", + "creationTimestamp": null + }, + "spec": { + "ports": [ + { + "name": "web", + "protocol": "TCP", + "port": 5432, + "targetPort": 8080, + "nodePort": 0 + } + ], + "selector": { + "name": "frontend" + }, + "portalIP": "", + "type": "ClusterIP", + "sessionAffinity": "None" + }, + "status": { + "loadBalancer": {} + } + }, + { + "kind": "Route", + "apiVersion": "v1", + "metadata": { + "name": "route-edge", + "creationTimestamp": null + }, + "spec": { + "host": "www.example.com", + "to": { + "kind": "Service", + "name": "frontend" + }, + "tls": { + "termination": "edge", + "certificate": "-----BEGIN CERTIFICATE-----\nMIIDIjCCAgqgAwIBAgIBATANBgkqhkiG9w0BAQUFADCBoTELMAkGA1UEBhMCVVMx\nCzAJBgNVBAgMAlNDMRUwEwYDVQQHDAxEZWZhdWx0IENpdHkxHDAaBgNVBAoME0Rl\nZmF1bHQgQ29tcGFueSBMdGQxEDAOBgNVBAsMB1Rlc3QgQ0ExGjAYBgNVBAMMEXd3\ndy5leGFtcGxlY2EuY29tMSIwIAYJKoZIhvcNAQkBFhNleGFtcGxlQGV4YW1wbGUu\nY29tMB4XDTE1MDExMjE0MTk0MVoXDTE2MDExMjE0MTk0MVowfDEYMBYGA1UEAwwP\nd3d3LmV4YW1wbGUuY29tMQswCQYDVQQIDAJTQzELMAkGA1UEBhMCVVMxIjAgBgkq\nhkiG9w0BCQEWE2V4YW1wbGVAZXhhbXBsZS5jb20xEDAOBgNVBAoMB0V4YW1wbGUx\nEDAOBgNVBAsMB0V4YW1wbGUwgZ8wDQYJKoZIhvcNAQEBBQADgY0AMIGJAoGBAMrv\ngu6ZTTefNN7jjiZbS/xvQjyXjYMN7oVXv76jbX8gjMOmg9m0xoVZZFAE4XyQDuCm\n47VRx5Qrf/YLXmB2VtCFvB0AhXr5zSeWzPwaAPrjA4ebG+LUo24ziS8KqNxrFs1M\nmNrQUgZyQC6XIe1JHXc9t+JlL5UZyZQC1IfaJulDAgMBAAGjDTALMAkGA1UdEwQC\nMAAwDQYJKoZIhvcNAQEFBQADggEBAFCi7ZlkMnESvzlZCvv82Pq6S46AAOTPXdFd\nTMvrh12E1sdVALF1P1oYFJzG1EiZ5ezOx88fEDTW+Lxb9anw5/KJzwtWcfsupf1m\nV7J0D3qKzw5C1wjzYHh9/Pz7B1D0KthQRATQCfNf8s6bbFLaw/dmiIUhHLtIH5Qc\nyfrejTZbOSP77z8NOWir+BWWgIDDB2//3AkDIQvT20vmkZRhkqSdT7et4NmXOX/j\njhPti4b2Fie0LeuvgaOdKjCpQQNrYthZHXeVlOLRhMTSk3qUczenkKTOhvP7IS9q\n+Dzv5hqgSfvMG392KWh5f8xXfJNs4W5KLbZyl901MeReiLrPH3w=\n-----END CERTIFICATE-----", + "key": "-----BEGIN PRIVATE KEY-----\nMIICeAIBADANBgkqhkiG9w0BAQEFAASCAmIwggJeAgEAAoGBAMrvgu6ZTTefNN7j\njiZbS/xvQjyXjYMN7oVXv76jbX8gjMOmg9m0xoVZZFAE4XyQDuCm47VRx5Qrf/YL\nXmB2VtCFvB0AhXr5zSeWzPwaAPrjA4ebG+LUo24ziS8KqNxrFs1MmNrQUgZyQC6X\nIe1JHXc9t+JlL5UZyZQC1IfaJulDAgMBAAECgYEAnxOjEj/vrLNLMZE1Q9H7PZVF\nWdP/JQVNvQ7tCpZ3ZdjxHwkvf//aQnuxS5yX2Rnf37BS/TZu+TIkK4373CfHomSx\nUTAn2FsLmOJljupgGcoeLx5K5nu7B7rY5L1NHvdpxZ4YjeISrRtEPvRakllENU5y\ngJE8c2eQOx08ZSRE4TkCQQD7dws2/FldqwdjJucYijsJVuUdoTqxP8gWL6bB251q\nelP2/a6W2elqOcWId28560jG9ZS3cuKvnmu/4LG88vZFAkEAzphrH3673oTsHN+d\nuBd5uyrlnGjWjuiMKv2TPITZcWBjB8nJDSvLneHF59MYwejNNEof2tRjgFSdImFH\nmi995wJBAMtPjW6wiqRz0i41VuT9ZgwACJBzOdvzQJfHgSD9qgFb1CU/J/hpSRIM\nkYvrXK9MbvQFvG6x4VuyT1W8mpe1LK0CQAo8VPpffhFdRpF7psXLK/XQ/0VLkG3O\nKburipLyBg/u9ZkaL0Ley5zL5dFBjTV2Qkx367Ic2b0u9AYTCcgi2DsCQQD3zZ7B\nv7BOm7MkylKokY2MduFFXU0Bxg6pfZ7q3rvg8gqhUFbaMStPRYg6myiDiW/JfLhF\nTcFT4touIo7oriFJ\n-----END PRIVATE KEY-----", + "caCertificate": "-----BEGIN CERTIFICATE-----\nMIIEFzCCAv+gAwIBAgIJALK1iUpF2VQLMA0GCSqGSIb3DQEBBQUAMIGhMQswCQYD\nVQQGEwJVUzELMAkGA1UECAwCU0MxFTATBgNVBAcMDERlZmF1bHQgQ2l0eTEcMBoG\nA1UECgwTRGVmYXVsdCBDb21wYW55IEx0ZDEQMA4GA1UECwwHVGVzdCBDQTEaMBgG\nA1UEAwwRd3d3LmV4YW1wbGVjYS5jb20xIjAgBgkqhkiG9w0BCQEWE2V4YW1wbGVA\nZXhhbXBsZS5jb20wHhcNMTUwMTEyMTQxNTAxWhcNMjUwMTA5MTQxNTAxWjCBoTEL\nMAkGA1UEBhMCVVMxCzAJBgNVBAgMAlNDMRUwEwYDVQQHDAxEZWZhdWx0IENpdHkx\nHDAaBgNVBAoME0RlZmF1bHQgQ29tcGFueSBMdGQxEDAOBgNVBAsMB1Rlc3QgQ0Ex\nGjAYBgNVBAMMEXd3dy5leGFtcGxlY2EuY29tMSIwIAYJKoZIhvcNAQkBFhNleGFt\ncGxlQGV4YW1wbGUuY29tMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA\nw2rK1J2NMtQj0KDug7g7HRKl5jbf0QMkMKyTU1fBtZ0cCzvsF4CqV11LK4BSVWaK\nrzkaXe99IVJnH8KdOlDl5Dh/+cJ3xdkClSyeUT4zgb6CCBqg78ePp+nN11JKuJlV\nIG1qdJpB1J5O/kCLsGcTf7RS74MtqMFo96446Zvt7YaBhWPz6gDaO/TUzfrNcGLA\nEfHVXkvVWqb3gqXUztZyVex/gtP9FXQ7gxTvJml7UkmT0VAFjtZnCqmFxpLZFZ15\n+qP9O7Q2MpsGUO/4vDAuYrKBeg1ZdPSi8gwqUP2qWsGd9MIWRv3thI2903BczDc7\nr8WaIbm37vYZAS9G56E4+wIDAQABo1AwTjAdBgNVHQ4EFgQUugLrSJshOBk5TSsU\nANs4+SmJUGwwHwYDVR0jBBgwFoAUugLrSJshOBk5TSsUANs4+SmJUGwwDAYDVR0T\nBAUwAwEB/zANBgkqhkiG9w0BAQUFAAOCAQEAaMJ33zAMV4korHo5aPfayV3uHoYZ\n1ChzP3eSsF+FjoscpoNSKs91ZXZF6LquzoNezbfiihK4PYqgwVD2+O0/Ty7UjN4S\nqzFKVR4OS/6lCJ8YncxoFpTntbvjgojf1DEataKFUN196PAANc3yz8cWHF4uvjPv\nWkgFqbIjb+7D1YgglNyovXkRDlRZl0LD1OQ0ZWhd4Ge1qx8mmmanoBeYZ9+DgpFC\nj9tQAbS867yeOryNe7sEOIpXAAqK/DTu0hB6+ySsDfMo4piXCc2aA/eI2DCuw08e\nw17Dz9WnupZjVdwTKzDhFgJZMLDqn37HQnT6EemLFqbcR0VPEnfyhDtZIQ==\n-----END CERTIFICATE-----" + } + }, + "status": {} + }, + { + "kind": "ImageStream", + "apiVersion": "v1", + "metadata": { + "name": "origin-ruby-sample", + "creationTimestamp": null + }, + "spec": {}, + "status": { + "dockerImageRepository": "" + } + }, + { + "kind": "ImageStream", + "apiVersion": "v1", + "metadata": { + "name": "ruby-20-centos7", + "creationTimestamp": null + }, + "spec": { + "dockerImageRepository": "openshift/ruby-20-centos7" + }, + "status": { + "dockerImageRepository": "" + } + }, + { + "kind": "BuildConfig", + "apiVersion": "v1", + "metadata": { + "name": "ruby-sample-build", + "creationTimestamp": null, + "labels": { + "name": "ruby-sample-build" + } + }, + "spec": { + "triggers": [ + { + "type": "github", + "github": { + "secret": "secret101" + } + }, + { + "type": "generic", + "generic": { + "secret": "secret101" + } + }, + { + "type": "imageChange", + "imageChange": {} + } + ], + "source": { + "type": "Git", + "git": { + "uri": "git://github.com/openshift/ruby-hello-world.git" + } + }, + "strategy": { + "type": "Source", + "sourceStrategy": { + "from": { + "kind": "ImageStreamTag", + "name": "ruby-20-centos7:latest" + }, + "incremental": true + } + }, + "output": { + "to": { + "kind": "ImageStreamTag", + "name": "origin-ruby-sample:latest" + } + }, + "resources": {} + }, + "status": { + "lastVersion": 0 + } + }, + { + "kind": "DeploymentConfig", + "apiVersion": "v1", + "metadata": { + "name": "frontend", + "creationTimestamp": null + }, + "spec": { + "strategy": { + "type": "Rolling", + "rollingParams": { + "updatePeriodSeconds": 1, + "intervalSeconds": 1, + "timeoutSeconds": 120, + "pre": { + "failurePolicy": "Abort", + "execNewPod": { + "command": [ + "/bin/true" + ], + "env": [ + { + "name": "CUSTOM_VAR1", + "value": "custom_value1" + } + ], + "containerName": "ruby-helloworld" + } + }, + "post": { + "failurePolicy": "Ignore", + "execNewPod": { + "command": [ + "/bin/false" + ], + "env": [ + { + "name": "CUSTOM_VAR2", + "value": "custom_value2" + } + ], + "containerName": "ruby-helloworld" + } + } + }, + "resources": {} + }, + "triggers": [ + { + "type": "ImageChange", + "imageChangeParams": { + "automatic": true, + "containerNames": [ + "ruby-helloworld" + ], + "from": { + "kind": "ImageStreamTag", + "name": "origin-ruby-sample:latest" + }, + "lastTriggeredImage": "" + } + }, + { + "type": "ConfigChange" + } + ], + "replicas": 2, + "selector": { + "name": "frontend" + }, + "template": { + "metadata": { + "creationTimestamp": null, + "labels": { + "name": "frontend" + } + }, + "spec": { + "containers": [ + { + "name": "ruby-helloworld", + "image": "origin-ruby-sample", + "ports": [ + { + "containerPort": 8080, + "protocol": "TCP" + } + ], + "env": [ + { + "name": "ADMIN_USERNAME", + "value": "${ADMIN_USERNAME}" + }, + { + "name": "ADMIN_PASSWORD", + "value": "${ADMIN_PASSWORD}" + }, + { + "name": "MYSQL_USER", + "value": "${MYSQL_USER}" + }, + { + "name": "MYSQL_PASSWORD", + "value": "${MYSQL_PASSWORD}" + }, + { + "name": "MYSQL_DATABASE", + "value": "${MYSQL_DATABASE}" + } + ], + "resources": {}, + "terminationMessagePath": "/dev/termination-log", + "imagePullPolicy": "IfNotPresent", + "capabilities": {}, + "securityContext": { + "capabilities": {}, + "privileged": false + } + } + ], + "restartPolicy": "Always", + "dnsPolicy": "ClusterFirst", + "serviceAccount": "" + } + } + }, + "status": {} + }, + { + "kind": "Service", + "apiVersion": "v1", + "metadata": { + "name": "database", + "creationTimestamp": null + }, + "spec": { + "ports": [ + { + "name": "db", + "protocol": "TCP", + "port": 5434, + "targetPort": 3306, + "nodePort": 0 + } + ], + "selector": { + "name": "database" + }, + "portalIP": "", + "type": "ClusterIP", + "sessionAffinity": "None" + }, + "status": { + "loadBalancer": {} + } + }, + { + "kind": "DeploymentConfig", + "apiVersion": "v1", + "metadata": { + "name": "database", + "creationTimestamp": null + }, + "spec": { + "strategy": { + "type": "Recreate", + "recreateParams": { + "pre": { + "failurePolicy": "Abort", + "execNewPod": { + "command": [ + "/bin/true" + ], + "env": [ + { + "name": "CUSTOM_VAR1", + "value": "custom_value1" + } + ], + "containerName": "ruby-helloworld-database" + } + }, + "post": { + "failurePolicy": "Ignore", + "execNewPod": { + "command": [ + "/bin/false" + ], + "env": [ + { + "name": "CUSTOM_VAR2", + "value": "custom_value2" + } + ], + "containerName": "ruby-helloworld-database" + } + } + }, + "resources": {} + }, + "triggers": [ + { + "type": "ConfigChange" + } + ], + "replicas": 1, + "selector": { + "name": "database" + }, + "template": { + "metadata": { + "creationTimestamp": null, + "labels": { + "name": "database" + } + }, + "spec": { + "containers": [ + { + "name": "ruby-helloworld-database", + "image": "openshift/mysql-55-centos7:latest", + "ports": [ + { + "containerPort": 3306, + "protocol": "TCP" + } + ], + "env": [ + { + "name": "MYSQL_USER", + "value": "${MYSQL_USER}" + }, + { + "name": "MYSQL_PASSWORD", + "value": "${MYSQL_PASSWORD}" + }, + { + "name": "MYSQL_DATABASE", + "value": "${MYSQL_DATABASE}" + } + ], + "resources": {}, + "terminationMessagePath": "/dev/termination-log", + "imagePullPolicy": "Always", + "capabilities": {}, + "securityContext": { + "capabilities": {}, + "privileged": false + } + } + ], + "restartPolicy": "Always", + "dnsPolicy": "ClusterFirst", + "serviceAccount": "" + } + } + }, + "status": {} + } + ], + "parameters": [ + { + "name": "ADMIN_USERNAME", + "description": "administrator username", + "generate": "expression", + "from": "admin[A-Z0-9]{3}" + }, + { + "name": "ADMIN_PASSWORD", + "description": "administrator password", + "generate": "expression", + "from": "[a-zA-Z0-9]{8}" + }, + { + "name": "MYSQL_USER", + "description": "database username", + "generate": "expression", + "from": "user[A-Z0-9]{3}" + }, + { + "name": "MYSQL_PASSWORD", + "description": "database password", + "generate": "expression", + "from": "[a-zA-Z0-9]{8}", + "required": true + }, + { + "name": "MYSQL_DATABASE", + "description": "database name", + "value": "root" + } + ], + "labels": { + "template": "application-template-stibuild" + } +} diff --git a/src/test/resources/samples/openshift3/oapi_v1_endpoint.json b/src/test/resources/samples/openshift3/oapi_v1_endpoint.json index 02826428..6f5e16a6 100644 --- a/src/test/resources/samples/openshift3/oapi_v1_endpoint.json +++ b/src/test/resources/samples/openshift3/oapi_v1_endpoint.json @@ -3,254 +3,730 @@ "groupVersion": "v1", "resources": [ { - "name": "buildconfigs", + "name": "appliedclusterresourcequotas", + "singularName": "", "namespaced": true, - "kind": "BuildConfig" + "kind": "AppliedClusterResourceQuota", + "verbs": [ + "get", + "list" + ] + }, + { + "name": "buildconfigs", + "singularName": "", + "namespaced": true, + "kind": "BuildConfig", + "verbs": [ + "create", + "delete", + "deletecollection", + "get", + "list", + "patch", + "update", + "watch" + ], + "shortNames": [ + "bc" + ] }, { "name": "buildconfigs/instantiate", + "singularName": "", "namespaced": true, - "kind": "BuildRequest" + "kind": "BuildRequest", + "verbs": [ + "create" + ] }, { "name": "buildconfigs/instantiatebinary", + "singularName": "", "namespaced": true, - "kind": "BinaryBuildRequestOptions" + "kind": "BinaryBuildRequestOptions", + "verbs": [] }, { "name": "buildconfigs/webhooks", + "singularName": "", "namespaced": true, - "kind": "Status" + "kind": "Build", + "verbs": [] }, { "name": "builds", + "singularName": "", "namespaced": true, - "kind": "Build" + "kind": "Build", + "verbs": [ + "create", + "delete", + "deletecollection", + "get", + "list", + "patch", + "update", + "watch" + ] }, { "name": "builds/clone", + "singularName": "", "namespaced": true, - "kind": "BuildRequest" + "kind": "BuildRequest", + "verbs": [ + "create" + ] }, { "name": "builds/details", + "singularName": "", "namespaced": true, - "kind": "Build" + "kind": "Build", + "verbs": [ + "update" + ] }, { "name": "builds/log", + "singularName": "", "namespaced": true, - "kind": "BuildLog" + "kind": "BuildLog", + "verbs": [ + "get" + ] }, { "name": "clusternetworks", + "singularName": "", "namespaced": false, - "kind": "ClusterNetwork" - }, - { - "name": "clusterpolicies", + "kind": "ClusterNetwork", + "verbs": [ + "create", + "delete", + "deletecollection", + "get", + "list", + "patch", + "update", + "watch" + ] + }, + { + "name": "clusterresourcequotas", + "singularName": "", "namespaced": false, - "kind": "ClusterPolicy" - }, - { - "name": "clusterpolicybindings", + "kind": "ClusterResourceQuota", + "verbs": [ + "create", + "delete", + "deletecollection", + "get", + "list", + "patch", + "update", + "watch" + ], + "shortNames": [ + "clusterquota" + ] + }, + { + "name": "clusterresourcequotas/status", + "singularName": "", "namespaced": false, - "kind": "ClusterPolicyBinding" + "kind": "ClusterResourceQuota", + "verbs": [ + "get", + "patch", + "update" + ] }, { "name": "clusterrolebindings", + "singularName": "", "namespaced": false, - "kind": "ClusterRoleBinding" + "kind": "ClusterRoleBinding", + "verbs": [ + "create", + "delete", + "get", + "list", + "patch", + "update" + ] }, { "name": "clusterroles", + "singularName": "", "namespaced": false, - "kind": "ClusterRole" + "kind": "ClusterRole", + "verbs": [ + "create", + "delete", + "get", + "list", + "patch", + "update" + ] }, { - "name": "deploymentconfigrollbacks", + "name": "deploymentconfigs", + "singularName": "", "namespaced": true, - "kind": "DeploymentConfigRollback" + "kind": "DeploymentConfig", + "verbs": [ + "create", + "delete", + "deletecollection", + "get", + "list", + "patch", + "update", + "watch" + ], + "shortNames": [ + "dc" + ] }, { - "name": "deploymentconfigs", + "name": "deploymentconfigs/instantiate", + "singularName": "", "namespaced": true, - "kind": "DeploymentConfig" + "kind": "DeploymentRequest", + "verbs": [ + "create" + ] }, { "name": "deploymentconfigs/log", + "singularName": "", + "namespaced": true, + "kind": "DeploymentLog", + "verbs": [ + "get" + ] + }, + { + "name": "deploymentconfigs/rollback", + "singularName": "", "namespaced": true, - "kind": "DeploymentLog" + "kind": "DeploymentConfigRollback", + "verbs": [ + "create" + ] }, { "name": "deploymentconfigs/scale", + "singularName": "", + "namespaced": true, + "group": "extensions", + "version": "v1beta1", + "kind": "Scale", + "verbs": [ + "get", + "patch", + "update" + ] + }, + { + "name": "deploymentconfigs/status", + "singularName": "", "namespaced": true, - "kind": "Scale" + "kind": "DeploymentConfig", + "verbs": [ + "get", + "patch", + "update" + ] }, { - "name": "generatedeploymentconfigs", + "name": "egressnetworkpolicies", + "singularName": "", "namespaced": true, - "kind": "DeploymentConfig" + "kind": "EgressNetworkPolicy", + "verbs": [ + "create", + "delete", + "deletecollection", + "get", + "list", + "patch", + "update", + "watch" + ] }, { "name": "groups", + "singularName": "", "namespaced": false, - "kind": "Group" + "kind": "Group", + "verbs": [ + "create", + "delete", + "deletecollection", + "get", + "list", + "patch", + "update", + "watch" + ] }, { "name": "hostsubnets", + "singularName": "", "namespaced": false, - "kind": "HostSubnet" + "kind": "HostSubnet", + "verbs": [ + "create", + "delete", + "deletecollection", + "get", + "list", + "patch", + "update", + "watch" + ] }, { "name": "identities", + "singularName": "", "namespaced": false, - "kind": "Identity" + "kind": "Identity", + "verbs": [ + "create", + "delete", + "deletecollection", + "get", + "list", + "patch", + "update", + "watch" + ] }, { "name": "images", + "singularName": "", "namespaced": false, - "kind": "Image" + "kind": "Image", + "verbs": [ + "create", + "delete", + "deletecollection", + "get", + "list", + "patch", + "update", + "watch" + ] + }, + { + "name": "imagesignatures", + "singularName": "", + "namespaced": false, + "kind": "ImageSignature", + "verbs": [ + "create", + "delete" + ] }, { "name": "imagestreamimages", + "singularName": "", "namespaced": true, - "kind": "ImageStreamImage" + "kind": "ImageStreamImage", + "verbs": [ + "get" + ], + "shortNames": [ + "isimage" + ] }, { "name": "imagestreamimports", + "singularName": "", "namespaced": true, - "kind": "ImageStreamImport" + "kind": "ImageStreamImport", + "verbs": [ + "create" + ] }, { "name": "imagestreammappings", + "singularName": "", "namespaced": true, - "kind": "ImageStreamMapping" + "kind": "ImageStreamMapping", + "verbs": [ + "create" + ] }, { "name": "imagestreams", - "namespaced": true, - "kind": "ImageStream" + "singularName": "", + "namespaced": true, + "kind": "ImageStream", + "verbs": [ + "create", + "delete", + "deletecollection", + "get", + "list", + "patch", + "update", + "watch" + ], + "shortNames": [ + "is" + ] }, { "name": "imagestreams/secrets", + "singularName": "", "namespaced": true, - "kind": "SecretList" + "kind": "SecretList", + "verbs": [ + "get" + ] }, { "name": "imagestreams/status", + "singularName": "", "namespaced": true, - "kind": "ImageStream" + "kind": "ImageStream", + "verbs": [ + "get", + "patch", + "update" + ] }, { "name": "imagestreamtags", - "namespaced": true, - "kind": "ImageStreamTag" + "singularName": "", + "namespaced": true, + "kind": "ImageStreamTag", + "verbs": [ + "create", + "delete", + "get", + "list", + "patch", + "update" + ], + "shortNames": [ + "istag" + ] }, { "name": "localresourceaccessreviews", + "singularName": "", "namespaced": true, - "kind": "LocalResourceAccessReview" + "kind": "LocalResourceAccessReview", + "verbs": [ + "create" + ] }, { "name": "localsubjectaccessreviews", + "singularName": "", "namespaced": true, - "kind": "LocalSubjectAccessReview" + "kind": "LocalSubjectAccessReview", + "verbs": [ + "create" + ] }, { "name": "netnamespaces", + "singularName": "", "namespaced": false, - "kind": "NetNamespace" + "kind": "NetNamespace", + "verbs": [ + "create", + "delete", + "deletecollection", + "get", + "list", + "patch", + "update", + "watch" + ] }, { "name": "oauthaccesstokens", + "singularName": "", "namespaced": false, - "kind": "OAuthAccessToken" + "kind": "OAuthAccessToken", + "verbs": [ + "create", + "delete", + "deletecollection", + "get", + "list", + "patch", + "update", + "watch" + ] }, { "name": "oauthauthorizetokens", + "singularName": "", "namespaced": false, - "kind": "OAuthAuthorizeToken" + "kind": "OAuthAuthorizeToken", + "verbs": [ + "create", + "delete", + "deletecollection", + "get", + "list", + "patch", + "update", + "watch" + ] }, { "name": "oauthclientauthorizations", + "singularName": "", "namespaced": false, - "kind": "OAuthClientAuthorization" + "kind": "OAuthClientAuthorization", + "verbs": [ + "create", + "delete", + "deletecollection", + "get", + "list", + "patch", + "update", + "watch" + ] }, { "name": "oauthclients", + "singularName": "", "namespaced": false, - "kind": "OAuthClient" + "kind": "OAuthClient", + "verbs": [ + "create", + "delete", + "deletecollection", + "get", + "list", + "patch", + "update", + "watch" + ] + }, + { + "name": "podsecuritypolicyreviews", + "singularName": "", + "namespaced": true, + "kind": "PodSecurityPolicyReview", + "verbs": [ + "create" + ] }, { - "name": "policies", + "name": "podsecuritypolicyselfsubjectreviews", + "singularName": "", "namespaced": true, - "kind": "Policy" + "kind": "PodSecurityPolicySelfSubjectReview", + "verbs": [ + "create" + ] }, { - "name": "policybindings", + "name": "podsecuritypolicysubjectreviews", + "singularName": "", "namespaced": true, - "kind": "PolicyBinding" + "kind": "PodSecurityPolicySubjectReview", + "verbs": [ + "create" + ] }, { "name": "processedtemplates", + "singularName": "", "namespaced": true, - "kind": "Template" + "kind": "Template", + "verbs": [ + "create" + ] }, { "name": "projectrequests", + "singularName": "", "namespaced": false, - "kind": "ProjectRequest" + "kind": "ProjectRequest", + "verbs": [ + "create", + "list" + ] }, { "name": "projects", + "singularName": "", "namespaced": false, - "kind": "Project" + "kind": "Project", + "verbs": [ + "create", + "delete", + "get", + "list", + "patch", + "update", + "watch" + ] }, { "name": "resourceaccessreviews", + "singularName": "", "namespaced": true, - "kind": "ResourceAccessReview" + "kind": "ResourceAccessReview", + "verbs": [ + "create" + ] + }, + { + "name": "rolebindingrestrictions", + "singularName": "", + "namespaced": true, + "kind": "RoleBindingRestriction", + "verbs": [ + "create", + "delete", + "deletecollection", + "get", + "list", + "patch", + "update", + "watch" + ] }, { "name": "rolebindings", + "singularName": "", "namespaced": true, - "kind": "RoleBinding" + "kind": "RoleBinding", + "verbs": [ + "create", + "delete", + "get", + "list", + "patch", + "update" + ] }, { "name": "roles", + "singularName": "", "namespaced": true, - "kind": "Role" + "kind": "Role", + "verbs": [ + "create", + "delete", + "get", + "list", + "patch", + "update" + ] }, { "name": "routes", + "singularName": "", "namespaced": true, - "kind": "Route" + "kind": "Route", + "verbs": [ + "create", + "delete", + "deletecollection", + "get", + "list", + "patch", + "update", + "watch" + ] }, { "name": "routes/status", + "singularName": "", + "namespaced": true, + "kind": "Route", + "verbs": [ + "get", + "patch", + "update" + ] + }, + { + "name": "selfsubjectrulesreviews", + "singularName": "", "namespaced": true, - "kind": "Route" + "kind": "SelfSubjectRulesReview", + "verbs": [ + "create" + ] }, { "name": "subjectaccessreviews", + "singularName": "", + "namespaced": true, + "kind": "SubjectAccessReview", + "verbs": [ + "create" + ] + }, + { + "name": "subjectrulesreviews", + "singularName": "", "namespaced": true, - "kind": "SubjectAccessReview" + "kind": "SubjectRulesReview", + "verbs": [ + "create" + ] }, { "name": "templates", + "singularName": "", "namespaced": true, - "kind": "Template" + "kind": "Template", + "verbs": [ + "create", + "delete", + "deletecollection", + "get", + "list", + "patch", + "update", + "watch" + ] }, { "name": "useridentitymappings", + "singularName": "", "namespaced": false, - "kind": "UserIdentityMapping" + "kind": "UserIdentityMapping", + "verbs": [ + "create", + "delete", + "get", + "patch", + "update" + ] }, { "name": "users", + "singularName": "", "namespaced": false, - "kind": "User" + "kind": "User", + "verbs": [ + "create", + "delete", + "deletecollection", + "get", + "list", + "patch", + "update", + "watch" + ] } ] } \ No newline at end of file diff --git a/src/test/resources/samples/openshift3/v1_build_config.json b/src/test/resources/samples/openshift3/v1_build_config.json index 6780d6ba..438dd6c3 100644 --- a/src/test/resources/samples/openshift3/v1_build_config.json +++ b/src/test/resources/samples/openshift3/v1_build_config.json @@ -55,7 +55,7 @@ "name" : "foo", "value" : "bar" }] - }, + } }, "output": { "to": { diff --git a/src/test/resources/samples/openshift3/v1_buildconfig_pipeline.json b/src/test/resources/samples/openshift3/v1_buildconfig_pipeline.json new file mode 100644 index 00000000..bc20b5e4 --- /dev/null +++ b/src/test/resources/samples/openshift3/v1_buildconfig_pipeline.json @@ -0,0 +1,44 @@ +{ + "apiVersion": "v1", + "kind": "BuildConfig", + "metadata": { + "labels": { + "build": "mapsapp-pipeline" + }, + "name": "mapsapp-pipeline" + }, + "spec": { + "runPolicy": "Serial", + "source": { + }, + "strategy": { + "type": "JenkinsPipeline", + "jenkinsPipelineStrategy": { + "jenkinsfile": "def project = \"\"\nnode {\n project = \"${env.PROJECT_NAME}\"\n\n stage('Create NationalParks back-end') {\n def nationalParksURL = \"${NATIONALPARKS_GIT_URI}\"\n def nationalParksBranch = \"${NATIONALPARKS_GIT_REF}\"\n checkout([$class: \"GitSCM\", branches: [[name: \"*/${nationalParksBranch}\"]], doGenerateSubmoduleConfigurations: false, extensions: [[$class: \"RelativeTargetDirectory\", relativeTargetDir: \"nationalparks\"]], submoduleCfg: [], userRemoteConfigs: [[url: \"${nationalParksURL}\"]]])\n sh \"oc new-app -f nationalparks/ose3/pipeline-buildconfig-template.json -p GIT_URI=${nationalParksURL} -p GIT_REF=${nationalParksBranch} -n ${project} --dry-run -o yaml | oc apply -f - -n ${project}\"\n }\n\n stage('Create MLBParks back-end') {\n def mlbParksURL = \"${MLBPARKS_GIT_URI}\"\n def mlbParksBranch = \"${MLBPARKS_GIT_REF}\"\n checkout([$class: \"GitSCM\", branches: [[name: \"*/${mlbParksBranch}\"]], doGenerateSubmoduleConfigurations: false, extensions: [[$class: \"RelativeTargetDirectory\", relativeTargetDir: \"mlbparks\"]], submoduleCfg: [], userRemoteConfigs: [[url: \"${mlbParksURL}\"]]])\n sh \"oc new-app -f mlbparks/ose3/pipeline-buildconfig-template.json -p GIT_URI=${mlbParksURL} -p GIT_REF=${mlbParksBranch} -n ${project} --dry-run -o yaml | oc apply -f - -n ${project}\"\n }\n\n stage('Create ParksMap front-end') {\n def parksMapURL = \"${PARKSMAP_GIT_URI}\"\n def parksMapBranch = \"${PARKSMAP_GIT_REF}\"\n checkout([$class: \"GitSCM\", branches: [[name: \"*/${parksMapBranch}\"]], doGenerateSubmoduleConfigurations: false, extensions: [[$class: \"RelativeTargetDirectory\", relativeTargetDir: \"parksmap\"]], submoduleCfg: [], userRemoteConfigs: [[url: \"${parksMapURL}\"]]])\n sh \"oc new-app -f parksmap/ose3/pipeline-buildconfig-template.json -p GIT_URI=${parksMapURL} -p GIT_REF=${parksMapBranch} -n ${project} --dry-run -o yaml | oc apply -f - -n ${project}\"\n }\n}\n\nstage('Build Back-ends') {\n parallel (\n \"nationalparks\": {\n node {\n openshiftBuild buildConfig: \"nationalparks-pipeline\", namespace: project\n }\n },\n \"mlbparks\": {\n node {\n openshiftBuild buildConfig: \"mlbparks-pipeline\", namespace: project\n }\n }\n )\n}\n\nnode {\n stage('Build Front-end') {\n openshiftBuild buildConfig: \"parksmap-pipeline\", namespace: project\n }\n}", + "jenkinsfilePath": "some/repo/dir/filename", + "env": [{ + "name" : "foo", + "value" : "bar" + }, + { + "name" : "kung", + "value" : "foo" + }] + } + }, + "triggers": [ + { + "github": { + "secret": "${GITHUB_TRIGGER_SECRET}" + }, + "type": "GitHub" + }, + { + "generic": { + "secret": "${GENERIC_TRIGGER_SECRET}" + }, + "type": "Generic" + } + ] + } +} diff --git a/src/test/resources/samples/openshift3/v1_config_map_console_public.json b/src/test/resources/samples/openshift3/v1_config_map_console_public.json new file mode 100644 index 00000000..7511b64e --- /dev/null +++ b/src/test/resources/samples/openshift3/v1_config_map_console_public.json @@ -0,0 +1,18 @@ +{ + "apiVersion": "v1", + "data": { + "consoleURL": "https://console-openshift-console.apps.crw.codereadyqe.com" + }, + "kind": "ConfigMap", + "metadata": { + "annotations": { + "release.openshift.io/create-only": "true" + }, + "creationTimestamp": "2019-09-24T11:13:17Z", + "name": "console-public", + "namespace": "openshift-config-managed", + "resourceVersion": "13313", + "selfLink": "/api/v1/namespaces/openshift-config-managed/configmaps/console-public", + "uid": "4f16131e-debc-11e9-a5c3-02ae3992b00c" + } +} \ No newline at end of file diff --git a/src/test/resources/samples/openshift3/v1_config_map_list_empty.json b/src/test/resources/samples/openshift3/v1_config_map_list_empty.json index a804f099..9dd98e80 100644 --- a/src/test/resources/samples/openshift3/v1_config_map_list_empty.json +++ b/src/test/resources/samples/openshift3/v1_config_map_list_empty.json @@ -3,6 +3,6 @@ "apiVersion": "v1", "metadata": { "selfLink": "/api/v1/namespaces/fooproj/configmaps", - "resourceVersion": "1418", + "resourceVersion": "1418" } } diff --git a/src/test/resources/samples/openshift3/v1_deployment_config.json b/src/test/resources/samples/openshift3/v1_deployment_config.json index 2f962862..ad360c61 100644 --- a/src/test/resources/samples/openshift3/v1_deployment_config.json +++ b/src/test/resources/samples/openshift3/v1_deployment_config.json @@ -113,10 +113,49 @@ "capabilities": {}, "privileged": false } - } - ], - "restartPolicy": "Always", - "dnsPolicy": "ClusterFirst" + }, + { + "name": "deployment", + "image": "openshift/origin-deployer:v0.6", + "ports": [ + { + "name" : "http", + "containerPort": 8080, + "protocol": "TCP" + } + ], + "env": [ + { + "name": "OPENSHIFT_DEPLOYMENT_NAME", + "value": "database-1" + } + ], + "livenessProbe" : { + "httpGet" : { + "path" : "/pagecount", + "port" : 8080, + "scheme" : "HTTP" + }, + "initialDelaySeconds" : 11, + "timeoutSeconds" : 12, + "periodSeconds" : 13, + "successThreshold" : 14, + "failureThreshold" : 15 + }, + "readinessProbe" : { + "httpGet" : { + "path" : "/pagecount", + "port" : 8080, + "scheme" : "HTTP" + }, + "initialDelaySeconds" : 3, + "timeoutSeconds" : 4, + "periodSeconds" : 5, + "successThreshold" : 6, + "failureThreshold" : 7 + } + } + ] } } }, diff --git a/src/test/resources/samples/openshift3/v1_event.json b/src/test/resources/samples/openshift3/v1_event.json new file mode 100644 index 00000000..0bc9edb5 --- /dev/null +++ b/src/test/resources/samples/openshift3/v1_event.json @@ -0,0 +1,29 @@ +{ + "kind": "Event", + "apiVersion": "v1", + "metadata": { + "name": "nodejs.1468b1fa2928e73e", + "namespace": "myproject", + "selfLink": "/api/v1/namespaces/myproject/events/nodejs.1468b1fa2928e73e", + "uid": "567a41b5-5d0a-11e6-9808-507b9dfa4ab3", + "resourceVersion": "450", + "creationTimestamp": "2016-08-08T01:49:26Z" + }, + "involvedObject": { + "kind": "DeploymentConfig", + "namespace": "myproject", + "name": "nodejs", + "uid": "234e71be-5d0a-11e6-9808-507b9dfa4ab3", + "apiVersion": "v1", + "resourceVersion": "445" + }, + "reason": "DeploymentCreated", + "message": "Created new deployment \"nodejs-1\" for version 1", + "source": { + "component": "deploymentconfig-controller" + }, + "firstTimestamp": "2016-08-08T01:49:26Z", + "lastTimestamp": "2016-08-08T01:49:26Z", + "count": 1, + "type": "Normal" +} \ No newline at end of file diff --git a/src/test/resources/samples/openshift3/v1_group.json b/src/test/resources/samples/openshift3/v1_group.json new file mode 100644 index 00000000..d7eda2e3 --- /dev/null +++ b/src/test/resources/samples/openshift3/v1_group.json @@ -0,0 +1,14 @@ +{ + "apiVersion": "user.openshift.io/v1", + "kind": "Group", + "metadata": { + "creationTimestamp": "2018-10-06T16:31:50Z", + "name": "test-group", + "resourceVersion": "33097", + "selfLink": "/apis/user.openshift.io/v1/groups/clusteradmins", + "uid": "5374bc7a-c985-11e8-8799-525400d45cd2" + }, + "users": [ + "test-admin" + ] +} \ No newline at end of file diff --git a/src/test/resources/samples/openshift3/v1_identity.json b/src/test/resources/samples/openshift3/v1_identity.json new file mode 100644 index 00000000..3aca2678 --- /dev/null +++ b/src/test/resources/samples/openshift3/v1_identity.json @@ -0,0 +1,17 @@ +{ + "kind": "Identity", + "apiVersion": "user.openshift.io/v1", + "metadata": { + "creationTimestamp": "2018-10-06T13:13:14Z", + "name": "anypassword:test-admin", + "resourceVersion": "13524", + "selfLink": "/apis/user.openshift.io/v1/identities/anypassword%3Atest-admin", + "uid": "94b42e96-0faa-11e5-9467-080027893417" + }, + "providerName": "anypassword", + "providerUserName": "test-admin", + "user": { + "name": "test-admin", + "uid": "94b42e96-0faa-11e5-9467-080027893417" + } +} diff --git a/src/test/resources/samples/openshift3/v1_lifecycle.json b/src/test/resources/samples/openshift3/v1_lifecycle.json new file mode 100644 index 00000000..2d156c94 --- /dev/null +++ b/src/test/resources/samples/openshift3/v1_lifecycle.json @@ -0,0 +1,17 @@ +{ + "preStop": { + "exec":{ + "command": [ + "precmd1", + "precmd2" + ] + } + }, + "postStart": { + "exec": { + "command": [ + "postcmd1" + ] + } + } +} diff --git a/src/test/resources/samples/openshift3/v1_namespace.json b/src/test/resources/samples/openshift3/v1_namespace.json new file mode 100644 index 00000000..ced5a5d0 --- /dev/null +++ b/src/test/resources/samples/openshift3/v1_namespace.json @@ -0,0 +1,28 @@ +{ + "kind": "Namespace", + "apiVersion": "v1", + "metadata": { + "annotations": { + "openshift.io/description": "This is an example namespace to demonstrate OpenShift v3", + "openshift.io/display-name": "OpenShift 3 Sample", + "openshift.io/requester": "admin", + "openshift.io/sa.scc.mcs": "s0:c8,c2", + "openshift.io/sa.scc.supplemental-groups": "1000060000/10000", + "openshift.io/sa.scc.uid-range": "1000060000/10000" + }, + "creationTimestamp": "2018-03-09T21:19:53Z", + "name": "test", + "resourceVersion": "292005", + "selfLink": "/osapi/v1beta3/namespaces/test", + "uid": "9bf521ab-23df-11e8-ba22-e2a386cca5ea" + }, + "spec": { + "finalizers": [ + "openshift.io/origin", + "kubernetes" + ] + }, + "status": { + "phase": "Active" + } +} \ No newline at end of file diff --git a/src/test/resources/samples/openshift3/v1_objectref.json b/src/test/resources/samples/openshift3/v1_objectref.json index 607423a5..3bf9b168 100644 --- a/src/test/resources/samples/openshift3/v1_objectref.json +++ b/src/test/resources/samples/openshift3/v1_objectref.json @@ -4,5 +4,5 @@ "name": "builder", "uid": "ce20b132-7986-11e5-b1e5-080027bdffff", "resourceVersion": "33366", - "apiVersion": "v1", + "apiVersion": "v1" } \ No newline at end of file diff --git a/src/test/resources/samples/openshift3/v1_pod.json b/src/test/resources/samples/openshift3/v1_pod.json index f17e2e93..f1e9f32e 100644 --- a/src/test/resources/samples/openshift3/v1_pod.json +++ b/src/test/resources/samples/openshift3/v1_pod.json @@ -62,7 +62,16 @@ "value": "test" } ], - "resources": {}, + "resources": { + "requests": { + "cpu": "1", + "memory": "128Mi" + }, + "limits": { + "cpu": "4", + "memory": "1Gi" + } + }, "volumeMounts": [ { "name": "deployer-token-22jov", @@ -71,7 +80,15 @@ } ], "terminationMessagePath": "/dev/termination-log", - "imagePullPolicy": "IfNotPresent" + "imagePullPolicy": "IfNotPresent", + "command" : [ + "/bin/sh" + ], + "args" : [ + "-c", + "echo 'hello'" + ] + } ], "restartPolicy": "Never", diff --git a/src/test/resources/samples/openshift3/v1_pod_multiContainer_ready.json b/src/test/resources/samples/openshift3/v1_pod_multiContainer_ready.json new file mode 100644 index 00000000..b4b60c5d --- /dev/null +++ b/src/test/resources/samples/openshift3/v1_pod_multiContainer_ready.json @@ -0,0 +1,392 @@ +{ + "kind" : "Pod", + "apiVersion" : "v1", + "metadata" : { + "name" : "nodejs-mongo-persistent-1-g4vbs", + "generateName" : "nodejs-mongo-persistent-1-", + "namespace" : "jbide25000-2", + "selfLink" : "/api/v1/namespaces/jbide25000-2/pods/nodejs-mongo-persistent-1-g4vbs", + "uid" : "5a44638d-2b8b-11e9-9384-06d3e3320f22", + "resourceVersion" : "442694201", + "creationTimestamp" : "2019-02-08T10:21:52Z", + "deletionTimestamp" : "2019-02-08T10:23:52Z", + "deletionGracePeriodSeconds" : 0, + "labels" : { + "deployment" : "nodejs-mongo-persistent-1", + "deploymentconfig" : "nodejs-mongo-persistent", + "name" : "nodejs-mongo-persistent" + }, + "annotations" : { + "kubernetes.io/limit-ranger" : "LimitRanger plugin set: cpu request for container nodejs-mongo-persistent; cpu limit for container nodejs-mongo-persistent", + "openshift.io/deployment-config.latest-version" : "1", + "openshift.io/deployment-config.name" : "nodejs-mongo-persistent", + "openshift.io/deployment.name" : "nodejs-mongo-persistent-1", + "openshift.io/scc" : "restricted" + }, + "ownerReferences" : [{ + "apiVersion" : "v1", + "kind" : "ReplicationController", + "name" : "nodejs-mongo-persistent-1", + "uid" : "5641d4f6-2b8b-11e9-a209-02dd5d026c14", + "controller" : true, + "blockOwnerDeletion" : true + }] + }, + "spec" : { + "volumes" : [{ + "name" : "default-token-xv9r6", + "secret" : { + "secretName" : "default-token-xv9r6", + "defaultMode" : 420 + } + }], + "containers" : [{ + "name" : "nodejs-mongo-persistent", + "image" : "docker-registry.default.svc:5000/jbide25000-2/nodejs-mongo-persistent@sha256:4f2b1c1b85a61918ace38a90cd7e31f833891fb81cb84c104fbe43d5e1091103", + "ports" : [{ + "containerPort" : 8080, + "protocol" : "TCP" + }], + "env" : [ + { + "name" : "DATABASE_SERVICE_NAME", + "value" : "mongodb" + }, + { + "name" : "MONGODB_USER", + "valueFrom" : {"secretKeyRef" : { + "name" : "nodejs-mongo-persistent", + "key" : "database-user" + }} + }, + { + "name" : "MONGODB_PASSWORD", + "valueFrom" : {"secretKeyRef" : { + "name" : "nodejs-mongo-persistent", + "key" : "database-password" + }} + }, + { + "name" : "MONGODB_DATABASE", + "value" : "sampledb" + }, + { + "name" : "MONGODB_ADMIN_PASSWORD", + "valueFrom" : {"secretKeyRef" : { + "name" : "nodejs-mongo-persistent", + "key" : "database-admin-password" + }} + } + ], + "resources" : { + "limits" : { + "cpu" : "300m", + "memory" : "512Mi" + }, + "requests" : { + "cpu" : "75m", + "memory" : "512Mi" + } + }, + "volumeMounts" : [{ + "name" : "default-token-xv9r6", + "readOnly" : true, + "mountPath" : "/var/run/secrets/kubernetes.io/serviceaccount" + }], + "livenessProbe" : { + "httpGet" : { + "path" : "/pagecount", + "port" : 8080, + "scheme" : "HTTP" + }, + "initialDelaySeconds" : 30, + "timeoutSeconds" : 3, + "periodSeconds" : 10, + "successThreshold" : 1, + "failureThreshold" : 3 + }, + "readinessProbe" : { + "httpGet" : { + "path" : "/pagecount", + "port" : 8080, + "scheme" : "HTTP" + }, + "initialDelaySeconds" : 3, + "timeoutSeconds" : 3, + "periodSeconds" : 10, + "successThreshold" : 1, + "failureThreshold" : 3 + }, + "terminationMessagePath" : "/dev/termination-log", + "terminationMessagePolicy" : "File", + "imagePullPolicy" : "IfNotPresent", + "securityContext" : { + "capabilities" : {"drop" : [ + "KILL", + "MKNOD", + "SETGID", + "SETUID" + ]}, + "runAsUser" : 1003800000 + } + }, + { + "name" : "nodejs-mongo-persistent-2", + "image" : "docker-registry.default.svc:5000/jbide25000-2/nodejs-mongo-persistent@sha256:4f2b1c1b85a61918ace38a90cd7e31f833891fb81cb84c104fbe43d5e1091103", + "ports" : [{ + "containerPort" : 8080, + "protocol" : "TCP" + }], + "env" : [ + { + "name" : "DATABASE_SERVICE_NAME", + "value" : "mongodb" + }, + { + "name" : "MONGODB_USER", + "valueFrom" : {"secretKeyRef" : { + "name" : "nodejs-mongo-persistent", + "key" : "database-user" + }} + }, + { + "name" : "MONGODB_PASSWORD", + "valueFrom" : {"secretKeyRef" : { + "name" : "nodejs-mongo-persistent", + "key" : "database-password" + }} + }, + { + "name" : "MONGODB_DATABASE", + "value" : "sampledb" + }, + { + "name" : "MONGODB_ADMIN_PASSWORD", + "valueFrom" : {"secretKeyRef" : { + "name" : "nodejs-mongo-persistent", + "key" : "database-admin-password" + }} + } + ], + "resources" : { + "limits" : { + "cpu" : "300m", + "memory" : "512Mi" + }, + "requests" : { + "cpu" : "75m", + "memory" : "512Mi" + } + }, + "volumeMounts" : [{ + "name" : "default-token-xv9r6", + "readOnly" : true, + "mountPath" : "/var/run/secrets/kubernetes.io/serviceaccount" + }], + "livenessProbe" : { + "httpGet" : { + "path" : "/pagecount", + "port" : 8080, + "scheme" : "HTTP" + }, + "initialDelaySeconds" : 30, + "timeoutSeconds" : 3, + "periodSeconds" : 10, + "successThreshold" : 1, + "failureThreshold" : 3 + }, + "readinessProbe" : { + "httpGet" : { + "path" : "/pagecount", + "port" : 8080, + "scheme" : "HTTP" + }, + "initialDelaySeconds" : 3, + "timeoutSeconds" : 3, + "periodSeconds" : 10, + "successThreshold" : 1, + "failureThreshold" : 3 + }, + "terminationMessagePath" : "/dev/termination-log", + "terminationMessagePolicy" : "File", + "imagePullPolicy" : "IfNotPresent", + "securityContext" : { + "capabilities" : {"drop" : [ + "KILL", + "MKNOD", + "SETGID", + "SETUID" + ]}, + "runAsUser" : 1003800000 + } + }, + { + "name" : "nodejs-mongo-persistent-3", + "image" : "docker-registry.default.svc:5000/jbide25000-2/nodejs-mongo-persistent@sha256:4f2b1c1b85a61918ace38a90cd7e31f833891fb81cb84c104fbe43d5e1091103", + "ports" : [{ + "containerPort" : 8080, + "protocol" : "TCP" + }], + "env" : [ + { + "name" : "DATABASE_SERVICE_NAME", + "value" : "mongodb" + }, + { + "name" : "MONGODB_USER", + "valueFrom" : {"secretKeyRef" : { + "name" : "nodejs-mongo-persistent", + "key" : "database-user" + }} + }, + { + "name" : "MONGODB_PASSWORD", + "valueFrom" : {"secretKeyRef" : { + "name" : "nodejs-mongo-persistent", + "key" : "database-password" + }} + }, + { + "name" : "MONGODB_DATABASE", + "value" : "sampledb" + }, + { + "name" : "MONGODB_ADMIN_PASSWORD", + "valueFrom" : {"secretKeyRef" : { + "name" : "nodejs-mongo-persistent", + "key" : "database-admin-password" + }} + } + ], + "resources" : { + "limits" : { + "cpu" : "300m", + "memory" : "512Mi" + }, + "requests" : { + "cpu" : "75m", + "memory" : "512Mi" + } + }, + "volumeMounts" : [{ + "name" : "default-token-xv9r6", + "readOnly" : true, + "mountPath" : "/var/run/secrets/kubernetes.io/serviceaccount" + }], + "livenessProbe" : { + "httpGet" : { + "path" : "/pagecount", + "port" : 8080, + "scheme" : "HTTP" + }, + "initialDelaySeconds" : 30, + "timeoutSeconds" : 3, + "periodSeconds" : 10, + "successThreshold" : 1, + "failureThreshold" : 3 + }, + "readinessProbe" : { + "httpGet" : { + "path" : "/pagecount", + "port" : 8080, + "scheme" : "HTTP" + }, + "initialDelaySeconds" : 3, + "timeoutSeconds" : 3, + "periodSeconds" : 10, + "successThreshold" : 1, + "failureThreshold" : 3 + }, + "terminationMessagePath" : "/dev/termination-log", + "terminationMessagePolicy" : "File", + "imagePullPolicy" : "IfNotPresent", + "securityContext" : { + "capabilities" : {"drop" : [ + "KILL", + "MKNOD", + "SETGID", + "SETUID" + ]}, + "runAsUser" : 1003800000 + } + }], + "restartPolicy" : "Always", + "terminationGracePeriodSeconds" : 30, + "dnsPolicy" : "ClusterFirst", + "nodeSelector" : { + "servicecomponent" : "nodeint", + "servicephase" : "hostedprod", + "vpc" : "vpc-8055ade5" + }, + "serviceAccountName" : "default", + "serviceAccount" : "default", + "nodeName" : "opennode-66-103.hosted.a3.vary.redhat.com", + "securityContext" : { + "seLinuxOptions" : {"level" : "s0:c62,c9"}, + "fsGroup" : 1003800000 + }, + "imagePullSecrets" : [{"name" : "default-dockercfg-jtlcb"}], + "schedulerName" : "default-scheduler", + "tolerations" : [{ + "key" : "node.kubernetes.io/memory-pressure", + "operator" : "Exists", + "effect" : "NoSchedule" + }] + }, + "status" : { + "phase" : "Running", + "conditions" : [ + { + "type" : "Initialized", + "status" : "True", + "lastTransitionTime" : "2019-02-08T10:21:52Z" + }, + { + "type" : "Ready", + "status" : "False", + "lastTransitionTime" : "2019-02-08T10:23:53Z", + "reason" : "ContainersNotReady", + "message" : "containers with unready status: [nodejs-mongo-persistent]" + }, + { + "type" : "PodScheduled", + "status" : "True", + "lastTransitionTime" : "2019-02-08T10:21:52Z" + } + ], + "hostIP" : "10.29.66.103", + "podIP" : "172.20.68.204", + "startTime" : "2019-02-08T10:21:52Z", + "containerStatuses" : [{ + "name" : "nodejs-mongo-persistent", + "state" : {"running" : {"startedAt" : "2019-02-08T10:23:59Z"}}, + "lastState" : {}, + "ready" : true, + "restartCount" : 0, + "image" : "docker-registry.default.svc:5000/jbide25000-2/nodejs-mongo-persistent@sha256:4f2b1c1b85a61918ace38a90cd7e31f833891fb81cb84c104fbe43d5e1091103", + "imageID" : "docker-pullable://docker-registry.default.svc:5000/jbide25000-2/nodejs-mongo-persistent@sha256:4f2b1c1b85a61918ace38a90cd7e31f833891fb81cb84c104fbe43d5e1091103", + "containerID" : "docker://dd892f0393cca8702553a2d4152fb848c98602687b1d9f21663b97ae800efb6a" + }, + { + "name" : "nodejs-mongo-persistent-2", + "state" : {"running" : {"startedAt" : "2019-02-08T10:24:59Z"}}, + "lastState" : {}, + "ready" : true, + "restartCount" : 0, + "image" : "docker-registry.default.svc:5000/jbide25000-2/nodejs-mongo-persistent@sha256:4f2b1c1b85a61918ace38a90cd7e31f833891fb81cb84c104fbe43d5e1091103", + "imageID" : "docker-pullable://docker-registry.default.svc:5000/jbide25000-2/nodejs-mongo-persistent@sha256:4f2b1c1b85a61918ace38a90cd7e31f833891fb81cb84c104fbe43d5e1091103", + "containerID" : "docker://dd892f0393cca8702553a2d4152fb848c98602687b1d9f21663b97ae800efb6a" + }, + { + "name" : "nodejs-mongo-persistent-3", + "state" : {"running" : {"startedAt" : "2019-02-08T10:25:59Z"}}, + "lastState" : {}, + "ready" : true, + "restartCount" : 0, + "image" : "docker-registry.default.svc:5000/jbide25000-2/nodejs-mongo-persistent@sha256:4f2b1c1b85a61918ace38a90cd7e31f833891fb81cb84c104fbe43d5e1091103", + "imageID" : "docker-pullable://docker-registry.default.svc:5000/jbide25000-2/nodejs-mongo-persistent@sha256:4f2b1c1b85a61918ace38a90cd7e31f833891fb81cb84c104fbe43d5e1091103", + "containerID" : "docker://fd892f0393cca8702553a2d4152fb848c98602687b1d9f21663b97ae800efb6a" + }], + "qosClass" : "Burstable" + } +} diff --git a/src/test/resources/samples/openshift3/v1_project_request.json b/src/test/resources/samples/openshift3/v1_project_request.json index a4fcb72f..998f7939 100644 --- a/src/test/resources/samples/openshift3/v1_project_request.json +++ b/src/test/resources/samples/openshift3/v1_project_request.json @@ -2,7 +2,7 @@ "kind": "ProjectRequest", "apiVersion": "v1", "metadata": { - "name": "test", + "name": "test" }, "displayName": "the display name", "description": "The project description" diff --git a/src/test/resources/samples/openshift3/v1_pvc.json b/src/test/resources/samples/openshift3/v1_pvc.json index 1a64954f..91a4a896 100644 --- a/src/test/resources/samples/openshift3/v1_pvc.json +++ b/src/test/resources/samples/openshift3/v1_pvc.json @@ -20,7 +20,8 @@ "requests": { "storage": "15m" } - } + }, + "volumeName": "pv02" }, "status": { "phase": "Pending" diff --git a/src/test/resources/samples/openshift3/v1_replication_controller.json b/src/test/resources/samples/openshift3/v1_replication_controller.json index 7a717b17..81358cc0 100644 --- a/src/test/resources/samples/openshift3/v1_replication_controller.json +++ b/src/test/resources/samples/openshift3/v1_replication_controller.json @@ -65,8 +65,28 @@ { "name": "MYSQL_DATABASE", "value": "root" - } - ], + }, + { + "name": "ENV_FIELD_REF", + "valueFrom": { "fieldRef": { + "fieldPath": "metadata.namespace" + }} + }, + { + "name": "ENV_CONFIGMAPKEY_REF", + "valueFrom": { "configMapKeyRef": { + "name": "env-config", + "key": "log_level" + }} + }, + { + "name" : "ENV_SECRETKEY_REF", + "valueFrom" : { "secretKeyRef" : { + "name" : "nodejs-mongo-persistent", + "key" : "database-user" + }} + } + ], "resources": {}, "terminationMessagePath": "/dev/termination-log", "imagePullPolicy": "Always", @@ -77,7 +97,8 @@ } ], "restartPolicy": "Always", - "dnsPolicy": "ClusterFirst" + "dnsPolicy": "ClusterFirst", + "serviceAccountName": "dbServiceAccountName" } } }, diff --git a/src/test/resources/samples/openshift3/v1_route_port_name.json b/src/test/resources/samples/openshift3/v1_route_port_name.json new file mode 100644 index 00000000..14f8ed35 --- /dev/null +++ b/src/test/resources/samples/openshift3/v1_route_port_name.json @@ -0,0 +1,31 @@ +{ + "kind": "Route", + "apiVersion": "v1", + "metadata": { + "name": "route-edge", + "namespace": "test", + "selfLink": "/osapi/v1beta3/namespaces/test/routes/route-edge", + "uid": "5dfdb081-0fab-11e5-9467-080027893417", + "resourceVersion": "383", + "creationTimestamp": "2015-06-10T20:00:39Z", + "labels": { + "foo": "bar", + "template": "application-template-stibuild" + }, + "annotations": { + "openshift.io/host.generated": "false" + } + }, + "spec": { + "host": "www.example.com", + "path" : "/abc", + "to": { + "kind": "Service", + "name": "frontend" + }, + "port": { + "targetPort": "http-8080" + } + }, + "status": {} +} diff --git a/src/test/resources/samples/openshift3/v1_route_port_numeric.json b/src/test/resources/samples/openshift3/v1_route_port_numeric.json new file mode 100644 index 00000000..36db0db6 --- /dev/null +++ b/src/test/resources/samples/openshift3/v1_route_port_numeric.json @@ -0,0 +1,31 @@ +{ + "kind": "Route", + "apiVersion": "v1", + "metadata": { + "name": "route-edge", + "namespace": "test", + "selfLink": "/osapi/v1beta3/namespaces/test/routes/route-edge", + "uid": "5dfdb081-0fab-11e5-9467-080027893417", + "resourceVersion": "383", + "creationTimestamp": "2015-06-10T20:00:39Z", + "labels": { + "foo": "bar", + "template": "application-template-stibuild" + }, + "annotations": { + "openshift.io/host.generated": "false" + } + }, + "spec": { + "host": "www.example.com", + "path" : "/abc", + "to": { + "kind": "Service", + "name": "frontend" + }, + "port": { + "targetPort": 8080 + } + }, + "status": {} +} diff --git a/src/test/resources/samples/openshift3/v1_route_wo_tls.json b/src/test/resources/samples/openshift3/v1_route_wo_tls.json index e67f5d4a..2efacfa9 100644 --- a/src/test/resources/samples/openshift3/v1_route_wo_tls.json +++ b/src/test/resources/samples/openshift3/v1_route_wo_tls.json @@ -22,7 +22,7 @@ "to": { "kind": "Service", "name": "frontend" - }, + } }, "status": {} } \ No newline at end of file diff --git a/src/test/resources/samples/openshift3/v1_secret.json b/src/test/resources/samples/openshift3/v1_secret.json index 19330d2d..19a73f7d 100644 --- a/src/test/resources/samples/openshift3/v1_secret.json +++ b/src/test/resources/samples/openshift3/v1_secret.json @@ -15,7 +15,7 @@ } }, "data": { - ".dockercfg": "value-1" + ".dockercfg": "dmFsdWUtMQ==" }, "type": "kubernetes.io/dockercfg" } \ No newline at end of file diff --git a/src/test/resources/samples/openshift3/v1_service.json b/src/test/resources/samples/openshift3/v1_service.json index 1fcee341..57454ad4 100644 --- a/src/test/resources/samples/openshift3/v1_service.json +++ b/src/test/resources/samples/openshift3/v1_service.json @@ -20,20 +20,20 @@ "protocol": "TCP", "port": 5434, "targetPort": 3306, - "nodePort": 0 + "nodePort": 45678 }, { - "name": "other", - "protocol": "TCP", - "port": 9999, - "targetPort": 8888, - "nodePort": 0 + "name": "other", + "protocol": "TCP", + "port": 9999, + "targetPort": 8888, + "nodePort": 56789 } ], "selector": { "name": "database" }, - "portalIP": "172.30.57.114", + "clusterIP": "172.30.57.114", "type": "ClusterIP", "sessionAffinity": "None" }, diff --git a/src/test/resources/samples/openshift3/v1_template.json b/src/test/resources/samples/openshift3/v1_template.json index 09fdf1e3..487fc2ab 100644 --- a/src/test/resources/samples/openshift3/v1_template.json +++ b/src/test/resources/samples/openshift3/v1_template.json @@ -3,25 +3,25 @@ "apiVersion": "v1", "metadata": { "name": "ruby-helloworld-sample", - "namespace": "test", - "selfLink": "/osapi/v1beta3/namespaces/test/templates/ruby-helloworld-sample", - "uid": "1affe776-0fab-11e5-9467-080027893417", - "resourceVersion": "366", - "creationTimestamp": "2015-06-10T19:58:47Z", + "namespace": "myproject", + "selfLink": "/oapi/v1/namespaces/myproject/templates/ruby-helloworld-sample", + "uid": "870dab76-38c7-11e6-8e5e-3c970e32f15a", + "resourceVersion": "86618", + "creationTimestamp": "2016-06-22T22:20:29Z", + "labels": { + "abc": "xyz", + "foo": "bar" + }, "annotations": { "description": "This example shows how to create a simple ruby application in openshift origin v3", "iconClass": "icon-ruby", "tags": "instant-app,ruby,mysql" - }, - "labels" : { - "foo" : "bar", - "abc" : "xyz" } }, "objects": [ { "kind": "Service", - "apiVersion": "v1beta3", + "apiVersion": "v1", "metadata": { "name": "frontend", "creationTimestamp": null @@ -49,7 +49,7 @@ }, { "kind": "Route", - "apiVersion": "v1beta3", + "apiVersion": "v1", "metadata": { "name": "route-edge", "creationTimestamp": null @@ -71,7 +71,7 @@ }, { "kind": "ImageStream", - "apiVersion": "v1beta3", + "apiVersion": "v1", "metadata": { "name": "origin-ruby-sample", "creationTimestamp": null @@ -83,7 +83,7 @@ }, { "kind": "ImageStream", - "apiVersion": "v1beta3", + "apiVersion": "v1", "metadata": { "name": "ruby-20-centos7", "creationTimestamp": null @@ -97,7 +97,7 @@ }, { "kind": "BuildConfig", - "apiVersion": "v1beta3", + "apiVersion": "v1", "metadata": { "name": "ruby-sample-build", "creationTimestamp": null, @@ -154,7 +154,7 @@ }, { "kind": "DeploymentConfig", - "apiVersion": "v1beta3", + "apiVersion": "v1", "metadata": { "name": "frontend", "creationTimestamp": null @@ -282,7 +282,7 @@ }, { "kind": "Service", - "apiVersion": "v1beta3", + "apiVersion": "v1", "metadata": { "name": "database", "creationTimestamp": null @@ -310,7 +310,7 @@ }, { "kind": "DeploymentConfig", - "apiVersion": "v1beta3", + "apiVersion": "v1", "metadata": { "name": "database", "creationTimestamp": null @@ -436,7 +436,7 @@ "description": "database password", "generate": "expression", "from": "[a-zA-Z0-9]{8}", - "required" : true + "required": true }, { "name": "MYSQL_DATABASE", @@ -447,4 +447,4 @@ "labels": { "template": "application-template-stibuild" } -} \ No newline at end of file +} diff --git a/src/test/resources/samples/openshift3/v1_user.json b/src/test/resources/samples/openshift3/v1_user.json index 182deeb3..87034680 100644 --- a/src/test/resources/samples/openshift3/v1_user.json +++ b/src/test/resources/samples/openshift3/v1_user.json @@ -12,5 +12,7 @@ "identities": [ "anypassword:test-admin" ], - "groups": null + "groups": [ + "test-group" + ] } diff --git a/startOCP.sh b/startOCP.sh new file mode 100755 index 00000000..972c6b47 --- /dev/null +++ b/startOCP.sh @@ -0,0 +1,11 @@ +if [ "$1" = "v3.9.0" ] +then curl https://github.com/openshift/origin/releases/download/v3.9.0/openshift-origin-client-tools-v3.9.0-191fece-linux-64bit.tar.gz --location --output oc-client.tgz +elif [ "$1" = "v3.10.0" ] +then curl https://github.com/openshift/origin/releases/download/v3.10.0/openshift-origin-client-tools-v3.10.0-dd10d17-linux-64bit.tar.gz --location --output oc-client.tgz +elif [ "$1" = "v3.11.0" ] +then curl https://github.com/openshift/origin/releases/download/v3.11.0/openshift-origin-client-tools-v3.11.0-0cbc58b-linux-64bit.tar.gz --location --output oc-client.tgz +fi +tar -xzvf oc-client.tgz +mv openshift-origin-client*/oc . +rm -rf openshift-origin-client* +./oc cluster up