Java Code Examples for io.fabric8.kubernetes.client.utils.URLUtils#join()

The following examples show how to use io.fabric8.kubernetes.client.utils.URLUtils#join() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: OpenShiftConfig.java    From kubernetes-client with Apache License 2.0 6 votes vote down vote up
@Buildable(builderPackage = "io.fabric8.kubernetes.api.builder", editableEnabled = false, refs = {@BuildableReference(Config.class)})
public OpenShiftConfig(String openShiftUrl, String oapiVersion, String masterUrl, String apiVersion, String namespace, Boolean trustCerts, Boolean disableHostnameVerification, String caCertFile, String caCertData, String clientCertFile, String clientCertData, String clientKeyFile, String clientKeyData, String clientKeyAlgo, String clientKeyPassphrase, String username, String password, String oauthToken, int watchReconnectInterval, int watchReconnectLimit, int connectionTimeout, int requestTimeout, long rollingTimeout, long scaleTimeout, int loggingInterval, Integer maxConcurrentRequestsPerHost, String httpProxy, String httpsProxy, String[] noProxy, Map<Integer, String> errorMessages, String userAgent, TlsVersion[] tlsVersions, long buildTimeout, long websocketTimeout, long websocketPingInterval, String proxyUsername, String proxyPassword, String trustStoreFile, String trustStorePassphrase, String keyStoreFile, String keyStorePassphrase, String impersonateUsername, String[] impersonateGroups, Map<String, List<String>> impersonateExtras, boolean openshiftApiGroupsEnabled, boolean disableApiGroupCheck) {
  super(masterUrl, apiVersion, namespace, trustCerts, disableHostnameVerification, caCertFile, caCertData, clientCertFile, clientCertData, clientKeyFile, clientKeyData, clientKeyAlgo, clientKeyPassphrase, username, password, oauthToken, watchReconnectInterval, watchReconnectLimit, connectionTimeout, requestTimeout, rollingTimeout, scaleTimeout, loggingInterval, maxConcurrentRequestsPerHost, httpProxy, httpsProxy, noProxy, errorMessages, userAgent, tlsVersions, websocketTimeout, websocketPingInterval, proxyUsername, proxyPassword, trustStoreFile, trustStorePassphrase, keyStoreFile, keyStorePassphrase, impersonateUsername, impersonateGroups, impersonateExtras);
  this.oapiVersion = oapiVersion;
  this.openShiftUrl = openShiftUrl;
  this.buildTimeout = buildTimeout;
  this.openshiftApiGroupsEnabled = openshiftApiGroupsEnabled;
  this.disableApiGroupCheck = openshiftApiGroupsEnabled ? false : disableApiGroupCheck;

  if (this.openShiftUrl == null || this.openShiftUrl.isEmpty()) {
    this.openShiftUrl = URLUtils.join(getMasterUrl(), "oapi", this.oapiVersion);
  }
  if (!this.openShiftUrl.endsWith("/")) {
    this.openShiftUrl = this.openShiftUrl + "/";
  }
}
 
Example 2
Source File: PodUpload.java    From kubernetes-client with Apache License 2.0 6 votes vote down vote up
private static URL buildCommandUrl(String command, PodOperationContext context, OperationSupport operationSupport)
  throws UnsupportedEncodingException, MalformedURLException {

  final StringBuilder commandBuilder = new StringBuilder();
  commandBuilder.append("exec?");
  commandBuilder.append("command=sh&command=-c");
  commandBuilder.append("&command=");
  commandBuilder.append(URLUtils.encodeToUTF(command));
  if (context.getContainerId() != null && !context.getContainerId().isEmpty()) {
    commandBuilder.append("&container=").append(context.getContainerId());
  }
  commandBuilder.append("&stdin=true");
  commandBuilder.append("&stderr=true");
  return new URL(
    URLUtils.join(operationSupport.getResourceUrl().toString(), commandBuilder.toString()));
}
 
Example 3
Source File: PodOperationsImpl.java    From kubernetes-client with Apache License 2.0 5 votes vote down vote up
@Override
public LogWatch watchLog(OutputStream out) {
  try {
    URL url = new URL(URLUtils.join(getResourceUrl().toString(), getLogParameters() + "&follow=true"));
    Request request = new Request.Builder().url(url).get().build();
    final LogWatchCallback callback = new LogWatchCallback(out);
    OkHttpClient clone = client.newBuilder().readTimeout(0, TimeUnit.MILLISECONDS).build();
    clone.newCall(request).enqueue(callback);
    callback.waitUntilReady();
    return callback;
  } catch (Throwable t) {
    throw KubernetesClientException.launderThrowable(forOperationType("watchLog"), t);
  }
}
 
Example 4
Source File: OpenShiftConfig.java    From kubernetes-client with Apache License 2.0 5 votes vote down vote up
private static String getDefaultOpenShiftUrl(Config config) {
  String openshiftUrl = Utils.getSystemPropertyOrEnvVar(OPENSHIFT_URL_SYSTEM_PROPERTY);
  if (openshiftUrl != null) {
    // The OPENSHIFT_URL environment variable may be set to the root url (i.e. without the '/oapi/version' path) in some configurations
    if (isRootURL(openshiftUrl)) {
      openshiftUrl = URLUtils.join(openshiftUrl, "oapi", getDefaultOapiVersion(config));
    }
    return openshiftUrl;
  } else {
    return URLUtils.join(config.getMasterUrl(), "oapi", getDefaultOapiVersion(config));
  }
}
 
Example 5
Source File: BuildOperationsImpl.java    From kubernetes-client with Apache License 2.0 5 votes vote down vote up
@Override
public LogWatch watchLog(OutputStream out) {
  try {
    URL url = new URL(URLUtils.join(getResourceUrl().toString(), getLogParameters() + "&follow=true"));
    Request request = new Request.Builder().url(url).get().build();
    final LogWatchCallback callback = new LogWatchCallback(out);
    OkHttpClient clone = client.newBuilder().readTimeout(0, TimeUnit.MILLISECONDS).build();
    clone.newCall(request).enqueue(callback);
    callback.waitUntilReady();
    return callback;
  } catch (Throwable t) {
    throw KubernetesClientException.launderThrowable(forOperationType("watchLog"), t);
  }
}
 
Example 6
Source File: BuildOperationsImpl.java    From kubernetes-client with Apache License 2.0 5 votes vote down vote up
protected ResponseBody doGetLog(){
  try {
    URL url = new URL(URLUtils.join(getResourceUrl().toString(), getLogParameters()));
    Request.Builder requestBuilder = new Request.Builder().get().url(url);
    Request request = requestBuilder.build();
    Response response = client.newCall(request).execute();
    ResponseBody body = response.body();
    assertResponseCode(request, response);
    return body;
  } catch (Throwable t) {
    throw KubernetesClientException.launderThrowable(forOperationType("doGetLog"), t);
  }
}
 
Example 7
Source File: BuildConfigOperationsImpl.java    From kubernetes-client with Apache License 2.0 5 votes vote down vote up
@Override
public Build instantiate(BuildRequest request) {
  try {
    updateApiVersion(request);
    URL instantiationUrl = new URL(URLUtils.join(getResourceUrl().toString(), "instantiate"));
    RequestBody requestBody = RequestBody.create(JSON, BaseOperation.JSON_MAPPER.writer().writeValueAsString(request));
    Request.Builder requestBuilder = new Request.Builder().post(requestBody).url(instantiationUrl);
    return handleResponse(requestBuilder, Build.class);
  } catch (Exception e) {
    throw KubernetesClientException.launderThrowable(e);
  }
}
 
Example 8
Source File: PodMetricOperationsImpl.java    From kubernetes-client with Apache License 2.0 5 votes vote down vote up
public PodMetricsList metrics(String namespace) {
  try {
    String resourceUrl = URLUtils.join(config.getMasterUrl(), METRIC_ENDPOINT_URL,
      "namespaces", namespace, "pods");
    return handleMetric(resourceUrl, PodMetricsList.class);
  } catch(Exception e) {
    throw KubernetesClientException.launderThrowable(e);
  }
}
 
Example 9
Source File: PodMetricOperationsImpl.java    From kubernetes-client with Apache License 2.0 5 votes vote down vote up
public PodMetricsList metrics() {
  try {
    String resourceUrl = URLUtils.join(config.getMasterUrl(), METRIC_ENDPOINT_URL, "pods");
    return handleMetric(resourceUrl, PodMetricsList.class);
  } catch(Exception e) {
    throw KubernetesClientException.launderThrowable(e);
  }
}
 
Example 10
Source File: PodMetricOperationsImpl.java    From kubernetes-client with Apache License 2.0 5 votes vote down vote up
public PodMetrics metrics(String namespace, String podName) {
  try {
    Utils.checkNotNull(namespace, "Namespace not provided");
    Utils.checkNotNull(podName, "Name not provided");

    String resourceUrl = URLUtils.join(config.getMasterUrl(), METRIC_ENDPOINT_URL,
      "namespaces", namespace, "pods", podName);
    return handleMetric(resourceUrl, PodMetrics.class);
  } catch(Exception e) {
    throw KubernetesClientException.launderThrowable(e);
  }
}
 
Example 11
Source File: PodOperationsImpl.java    From kubernetes-client with Apache License 2.0 5 votes vote down vote up
private void handleEvict(URL podUrl, String namespace, String name) throws ExecutionException, InterruptedException, IOException {
  Eviction eviction = new EvictionBuilder()
    .withNewMetadata()
    .withName(name)
    .withNamespace(namespace)
    .endMetadata()
    .withDeleteOptions(new DeleteOptions())
    .build();

  RequestBody requestBody = RequestBody.create(JSON, JSON_MAPPER.writeValueAsString(eviction));

  URL requestUrl = new URL(URLUtils.join(podUrl.toString(), "eviction"));
  Request.Builder requestBuilder = new Request.Builder().post(requestBody).url(requestUrl);
  handleResponse(requestBuilder, null, Collections.<String, String>emptyMap());
}
 
Example 12
Source File: PodOperationsImpl.java    From kubernetes-client with Apache License 2.0 5 votes vote down vote up
protected ResponseBody doGetLog(){
  try {
    URL url = new URL(URLUtils.join(getResourceUrl().toString(), getLogParameters()));
    Request.Builder requestBuilder = new Request.Builder().get().url(url);
    Request request = requestBuilder.build();
    Response response = client.newCall(request).execute();
    ResponseBody body = response.body();
    assertResponseCode(request, response);
    return body;
  } catch (Throwable t) {
    throw KubernetesClientException.launderThrowable(forOperationType("doGetLog"), t);
  }
}
 
Example 13
Source File: NodeMetricOperationsImpl.java    From kubernetes-client with Apache License 2.0 5 votes vote down vote up
public NodeMetrics metrics(String nodeName) {
	try {
		String resourceUrl = URLUtils.join(config.getMasterUrl(), METRIC_ENDPOINT_URL, nodeName);
		return handleMetric(resourceUrl, NodeMetrics.class);
	} catch(Exception e) {
		throw KubernetesClientException.launderThrowable(e);
	}
}
 
Example 14
Source File: NodeMetricOperationsImpl.java    From kubernetes-client with Apache License 2.0 5 votes vote down vote up
public NodeMetricsList metrics() {
	try {
		String resourceUrl = URLUtils.join(config.getMasterUrl(), METRIC_ENDPOINT_URL);
		return handleMetric(resourceUrl, NodeMetricsList.class);
	} catch(Exception e) {
		throw KubernetesClientException.launderThrowable(e);
	}
}
 
Example 15
Source File: OperationSupport.java    From kubernetes-client with Apache License 2.0 5 votes vote down vote up
public URL getRootUrl() {
  try {
    if (!Utils.isNullOrEmpty(apiGroupName)) {
      return new URL(URLUtils.join(config.getMasterUrl().toString(), "apis", apiGroupName, apiGroupVersion));
    }
    return new URL(URLUtils.join(config.getMasterUrl().toString(), "api", apiGroupVersion));
  } catch (MalformedURLException e) {
    throw KubernetesClientException.launderThrowable(e);
  }
}
 
Example 16
Source File: ZipkinMinimalKubernetesTest.java    From kubernetes-zipkin with Apache License 2.0 5 votes vote down vote up
@Test
@RunAsClient
public void testConnectionToZipkinQuery() throws Exception {
    String url = URLUtils.join(KubernetesHelper.getServiceURL(service), "/api/v1/services");
    OkHttpClient httpClient = new OkHttpClient();
    try {
        Request request = new Request.Builder().get().url(url).build();
        Response response = httpClient.newCall(request).execute();
        Assert.assertNotNull(response);
        Assert.assertEquals(200, response.code());
    } finally {
        close(httpClient);
    }
}
 
Example 17
Source File: CustomResourceCondition.java    From dekorate with Apache License 2.0 4 votes vote down vote up
@Override
public ConditionEvaluationResult evaluateExecutionCondition(ExtensionContext context) {
 Optional<OnCustomResourcePresentCondition> annotation = context.getElement().map(e -> e.getAnnotation(OnCustomResourcePresentCondition.class));
 if (!annotation.isPresent()) {
  return ConditionEvaluationResult.enabled("Condition not found!");
 }
 OnCustomResourcePresentCondition condition = annotation.get();
  try {
    String apiVersion = condition.apiVersion();
    String kind = condition.kind();
    String plural = Strings.isNotNullOrEmpty(condition.plural()) ? condition.plural() : Pluralize.FUNCTION.apply(kind).toLowerCase();
    String name = condition.name();
    String namespace = condition.namespace();

    KubernetesClient client = getKubernetesClient(context);
    Config config = client.getConfiguration();
    OkHttpClient http = client.adapt(OkHttpClient.class);

    List<String> parts = new ArrayList<>();
    parts.add(config.getMasterUrl());
    parts.add("apis");
    parts.add(apiVersion);

    if (Strings.isNotNullOrEmpty(namespace)) {
      parts.add("namespaces");
      parts.add(namespace);
    }

    parts.add(plural);
    if (Strings.isNotNullOrEmpty(name)) {
      parts.add(name);
    }
    parts.add(plural);
    String requestUrl = URLUtils.join(parts.stream().toArray(s->new String[s]));
    Request request = new Request.Builder().get().url(requestUrl).build();
    Response response = http.newCall(request).execute();

    if (!response.isSuccessful()) {
      return ConditionEvaluationResult.disabled("Could not lookup custom resource.");
    }


    //TODO: Add support for cases where name() is empty. In this case the result will be a list.
    //We need to check if empty.
    return ConditionEvaluationResult.enabled("Found resource with apiVersion:" + apiVersion + " kind:" + kind + " namespace: " + (Strings.isNullOrEmpty(namespace) ? "any" : namespace) + " name: " + (Strings.isNullOrEmpty(name) ? "any" : name));

  } catch (Throwable t) {
    return ConditionEvaluationResult.disabled("Could not lookup for service.");
  }
}
 
Example 18
Source File: OperationSupport.java    From kubernetes-client with Apache License 2.0 4 votes vote down vote up
public URL getResourceUrl() throws MalformedURLException {
  if (name == null) {
    return getNamespacedUrl();
  }
  return new URL(URLUtils.join(getNamespacedUrl().toString(), name));
}
 
Example 19
Source File: OperationSupport.java    From kubernetes-client with Apache License 2.0 4 votes vote down vote up
public URL getResourceUrl(String namespace, String name) throws MalformedURLException {
  if (name == null) {
    return getNamespacedUrl(namespace);
  }
  return new URL(URLUtils.join(getNamespacedUrl(namespace).toString(), name));
}
 
Example 20
Source File: OpenShiftClientFactory.java    From che with Eclipse Public License 2.0 4 votes vote down vote up
@Override
protected Interceptor buildKubernetesInterceptor(Config config) {
  final String oauthToken;
  if (Utils.isNotNullOrEmpty(config.getUsername())
      && Utils.isNotNullOrEmpty(config.getPassword())) {
    synchronized (getHttpClient()) {
      try {
        OkHttpClient.Builder builder = getHttpClient().newBuilder();
        builder.interceptors().clear();
        OkHttpClient clone = builder.build();

        String credential = Credentials.basic(config.getUsername(), config.getPassword());
        URL url = new URL(URLUtils.join(config.getMasterUrl(), AUTHORIZE_PATH));
        Response response =
            clone
                .newCall(
                    new Request.Builder()
                        .get()
                        .url(url)
                        .header(AUTHORIZATION, credential)
                        .build())
                .execute();

        // False positive warn: according to javadocs response.body() returns non-null value
        // if called after Call.execute()
        response.body().close();
        response = response.priorResponse() != null ? response.priorResponse() : response;
        response = response.networkResponse() != null ? response.networkResponse() : response;
        String token = response.header(LOCATION);
        if (token == null || token.isEmpty()) {
          throw new KubernetesClientException(
              "Unexpected response ("
                  + response.code()
                  + " "
                  + response.message()
                  + "), to the authorization request. Missing header:["
                  + LOCATION
                  + "]!");
        }
        token = token.substring(token.indexOf(BEFORE_TOKEN) + BEFORE_TOKEN.length());
        token = token.substring(0, token.indexOf(AFTER_TOKEN));
        oauthToken = token;
      } catch (Exception e) {
        throw KubernetesClientException.launderThrowable(e);
      }
    }
  } else if (Utils.isNotNullOrEmpty(config.getOauthToken())) {
    oauthToken = config.getOauthToken();
  } else {
    oauthToken = null;
  }

  return chain -> {
    Request request = chain.request();
    if (isNotNullOrEmpty(oauthToken)) {
      Request authReq =
          chain.request().newBuilder().addHeader("Authorization", "Bearer " + oauthToken).build();
      return chain.proceed(authReq);
    }
    return chain.proceed(request);
  };
}