Java Code Examples for io.fabric8.kubernetes.client.utils.Utils#isNullOrEmpty()

The following examples show how to use io.fabric8.kubernetes.client.utils.Utils#isNullOrEmpty() . 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: KubernetesDiscoveryClient.java    From spring-cloud-kubernetes with Apache License 2.0 6 votes vote down vote up
@Override
public ServiceInstance getLocalServiceInstance() {
    String serviceName = properties.getServiceName();
    String podName = System.getenv(HOSTNAME);
    ServiceInstance defaultInstance = new DefaultServiceInstance(serviceName, "localhost", 8080, false);

    Endpoints endpoints = client.endpoints().withName(serviceName).get();
    if (Utils.isNullOrEmpty(podName) || endpoints == null) {
        return defaultInstance;
    }
    try {
        return endpoints.getSubsets()
                .stream()
                .filter(s -> s.getAddresses().get(0).getTargetRef().getName().equals(podName))
                .map(s -> (ServiceInstance) new KubernetesServiceInstance(serviceName,
                        s.getAddresses().stream().findFirst().orElseThrow(IllegalStateException::new),
                        s.getPorts().stream().findFirst().orElseThrow(IllegalStateException::new),
                        false))
                .findFirst().orElse(defaultInstance);
    } catch (Throwable t) {
        return defaultInstance;
    }
}
 
Example 2
Source File: KubernetesAttributesExtractor.java    From kubernetes-client with Apache License 2.0 6 votes vote down vote up
protected AttributeSet extractMetadataAttributes(HasMetadata hasMetadata) {
    AttributeSet metadataAttributes = new AttributeSet();
    if (!Utils.isNullOrEmpty(hasMetadata.getMetadata().getName())) {
      metadataAttributes = metadataAttributes.add(new Attribute(NAME, hasMetadata.getMetadata().getName()));
    }

    if (!Utils.isNullOrEmpty(hasMetadata.getMetadata().getNamespace())) {
        metadataAttributes = metadataAttributes.add(new Attribute(NAMESPACE, hasMetadata.getMetadata().getNamespace()));
    }

  if (hasMetadata.getMetadata().getLabels() != null) {
    for (Map.Entry<String, String> label : hasMetadata.getMetadata().getLabels().entrySet()) {
      metadataAttributes = metadataAttributes.add(new Attribute(LABEL_KEY_PREFIX + label.getKey(), label.getValue()));
    }
  }
  return metadataAttributes;
}
 
Example 3
Source File: BaseOperation.java    From kubernetes-client with Apache License 2.0 6 votes vote down vote up
@Override
public T createOrReplace(T... items) {
  T item = getItem();
  if (items.length > 1) {
    throw new IllegalArgumentException("Too many items to create.");
  } else if (items.length == 1) {
    item = items[0];
  }

  if (item == null) {
    throw new IllegalArgumentException("Nothing to create.");
  }

  if (Utils.isNullOrEmpty(name) && item instanceof HasMetadata) {
    return withName(((HasMetadata)item).getMetadata().getName()).createOrReplace(item);
  }
  if (fromServer().get() == null) {
    return create(item);
  } else {
    return replace(item);
  }
}
 
Example 4
Source File: SubjectAccessReviewOperationImpl.java    From kubernetes-client with Apache License 2.0 5 votes vote down vote up
@Override
public URL getRootUrl() {
  // This is an OpenShift resource. If no API Group Name is specified, use /oapi endpoint
  if (Utils.isNullOrEmpty(context.getApiGroupName())) {
    try {
      return new URL(OpenShiftConfig.wrap(getConfig()).getOpenShiftUrl());
    } catch (MalformedURLException e) {
      throw KubernetesClientException.launderThrowable(e);
    }
  } else {
    return super.getRootUrl();
  }
}
 
Example 5
Source File: AbstractSessionManagerStepExecution.java    From kubernetes-pipeline-plugin with Apache License 2.0 5 votes vote down vote up
protected URL toURL(String url) {
    if (Utils.isNullOrEmpty(url)) {
        return null;
    }
    try {
        return new URL(url);
    } catch (MalformedURLException e) {
        throw new IllegalArgumentException("Specified url:["+url+"] is malformed");
    }
}
 
Example 6
Source File: ProjectRequestsOperationImpl.java    From kubernetes-client with Apache License 2.0 5 votes vote down vote up
@Override
public URL getRootUrl() {
  // This is an OpenShift resource. If no API Group Name is specified, use /oapi endpoint
  if (Utils.isNullOrEmpty(context.getApiGroupName())) {
    try {
      return new URL(OpenShiftConfig.wrap(getConfig()).getOpenShiftUrl());
    } catch (MalformedURLException e) {
      throw KubernetesClientException.launderThrowable(e);
    }
  } else {
    return super.getRootUrl();
  }
}
 
Example 7
Source File: OpenShiftOperation.java    From kubernetes-client with Apache License 2.0 5 votes vote down vote up
@Override
public URL getRootUrl() {
  // This is an OpenShift resource. If no API Group Name is specified, use /oapi endpoint
  if (Utils.isNullOrEmpty(context.getApiGroupName())) {
    try {
      return new URL(OpenShiftConfig.wrap(getConfig()).getOpenShiftUrl());
    } catch (MalformedURLException e) {
      throw KubernetesClientException.launderThrowable(e);
    }
  } else {
    return super.getRootUrl();
  }
}
 
Example 8
Source File: BuildConfigOperationsImpl.java    From kubernetes-client with Apache License 2.0 5 votes vote down vote up
private String getQueryParameters() throws MalformedURLException {
  StringBuilder sb = new StringBuilder();
  sb.append(URLUtils.join(getResourceUrl().toString(), "instantiatebinary"));
  if (Utils.isNullOrEmpty(message)) {
    sb.append("?commit=");
  } else {
    sb.append("?commit=").append(message);
  }

  if (!Utils.isNullOrEmpty(authorName)) {
    sb.append("&revision.authorName=").append(authorName);
  }

  if (!Utils.isNullOrEmpty(authorEmail)) {
    sb.append("&revision.authorEmail=").append(authorEmail);
  }

  if (!Utils.isNullOrEmpty(committerName)) {
    sb.append("&revision.committerName=").append(committerName);
  }

  if (!Utils.isNullOrEmpty(committerEmail)) {
    sb.append("&revision.committerEmail=").append(committerEmail);
  }

  if (!Utils.isNullOrEmpty(commit)) {
    sb.append("&revision.commit=").append(commit);
  }

  if (!Utils.isNullOrEmpty(asFile)) {
    sb.append("&asFile=").append(asFile);
  }
  return sb.toString();
}
 
Example 9
Source File: PodOperationsImpl.java    From kubernetes-client with Apache License 2.0 5 votes vote down vote up
private void evictThis() {
  try {
    if (Utils.isNullOrEmpty(getNamespace())) {
      throw new KubernetesClientException("Namespace not specified, but operation requires it.");
    }
    if (Utils.isNullOrEmpty(getName())) {
      throw new KubernetesClientException("Name not specified, but operation requires it.");
    }
    handleEvict(getResourceUrl(), getNamespace(), getName());
  } catch (Exception e) {
    throw KubernetesClientException.launderThrowable(forOperationType("evict"), e);
  }
}
 
Example 10
Source File: SubjectAccessReviewOperationImpl.java    From kubernetes-client with Apache License 2.0 5 votes vote down vote up
@Override
protected <T> String checkNamespace(T item) {
  String operationNs = getNamespace();
  String itemNs = (item instanceof HasMetadata && ((HasMetadata)item).getMetadata() != null) ? ((HasMetadata) item).getMetadata().getNamespace() : null;
  if (Utils.isNullOrEmpty(operationNs) && Utils.isNullOrEmpty(itemNs)) {
    return null;
  } else if (Utils.isNullOrEmpty(itemNs)) {
    return operationNs;
  } else if (Utils.isNullOrEmpty(operationNs)) {
    return itemNs;
  } else if (itemNs.equals(operationNs)) {
    return itemNs;
  }
  throw new KubernetesClientException("Namespace mismatch. Item namespace:" + itemNs + ". Operation namespace:" + operationNs + ".");
}
 
Example 11
Source File: NamespaceVisitFromServerGetWatchDeleteRecreateWaitApplicableListImpl.java    From kubernetes-client with Apache License 2.0 5 votes vote down vote up
@Override
public void visit(ObjectMetaBuilder builder) {
    if (Utils.isNotNullOrEmpty(explicitNamespace)) {
        builder.withNamespace(explicitNamespace);
    } else if (Utils.isNullOrEmpty(builder.getNamespace())) {
        builder.withNamespace(fallbackNamespace);
    }
}
 
Example 12
Source File: NamespaceVisitFromServerGetWatchDeleteRecreateWaitApplicableImpl.java    From kubernetes-client with Apache License 2.0 5 votes vote down vote up
@Override
public void visit(ObjectMetaBuilder builder) {
  if (Utils.isNotNullOrEmpty(explicitNamespace)) {
    builder.withNamespace(explicitNamespace);
  } else if (Utils.isNullOrEmpty(builder.getNamespace())) {
    builder.withNamespace(fallbackNamespace);
  }
}
 
Example 13
Source File: OperationSupport.java    From kubernetes-client with Apache License 2.0 5 votes vote down vote up
protected <T> String checkName(T item) {
  String operationName = getName();
  String itemName = item instanceof HasMetadata ? ((HasMetadata) item).getMetadata().getName() : null;
  if (Utils.isNullOrEmpty(operationName) && Utils.isNullOrEmpty(itemName)) {
    return null;
  } else if (Utils.isNullOrEmpty(itemName)) {
    return operationName;
  } else if (Utils.isNullOrEmpty(operationName)) {
    return itemName;
  } else if (itemName.equals(operationName)) {
    return itemName;
  }
  throw new KubernetesClientException("Name mismatch. Item name:" + itemName + ". Operation name:" + operationName + ".");
}
 
Example 14
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 15
Source File: KubernetesAttributesExtractor.java    From kubernetes-client with Apache License 2.0 5 votes vote down vote up
@Override
public AttributeSet extract(HasMetadata o) {
  AttributeSet attributes = extractMetadataAttributes(o);
  if (!Utils.isNullOrEmpty(o.getKind())) {
      attributes = attributes.add(new Attribute(KIND, o.getKind().toLowerCase(Locale.ROOT)));
  }
  return attributes;
}
 
Example 16
Source File: Config.java    From kubernetes-client with Apache License 2.0 4 votes vote down vote up
private static boolean loadFromKubeconfig(Config config, String context, String kubeconfigContents, String kubeconfigPath) {
  try {
    io.fabric8.kubernetes.api.model.Config kubeConfig = KubeConfigUtils.parseConfigFromString(kubeconfigContents);
    config.setContexts(kubeConfig.getContexts());
    Context currentContext = setCurrentContext(context, config, kubeConfig);
    Cluster currentCluster = KubeConfigUtils.getCluster(kubeConfig, currentContext);
    if (currentContext != null) {
        config.setNamespace(currentContext.getNamespace());
    }
    if (currentCluster != null) {
      config.setMasterUrl(currentCluster.getServer());
      config.setTrustCerts(currentCluster.getInsecureSkipTlsVerify() != null && currentCluster.getInsecureSkipTlsVerify());
      config.setDisableHostnameVerification(currentCluster.getInsecureSkipTlsVerify() != null && currentCluster.getInsecureSkipTlsVerify());
      config.setCaCertData(currentCluster.getCertificateAuthorityData());
      AuthInfo currentAuthInfo = KubeConfigUtils.getUserAuthInfo(kubeConfig, currentContext);
      if (currentAuthInfo != null) {
        // rewrite tls asset paths if needed
        String caCertFile = currentCluster.getCertificateAuthority();
        String clientCertFile = currentAuthInfo.getClientCertificate();
        String clientKeyFile = currentAuthInfo.getClientKey();
        if (kubeconfigPath != null && !kubeconfigPath.isEmpty()) {
          caCertFile = absolutify(new File(kubeconfigPath), currentCluster.getCertificateAuthority());
          clientCertFile = absolutify(new File(kubeconfigPath), currentAuthInfo.getClientCertificate());
          clientKeyFile = absolutify(new File(kubeconfigPath), currentAuthInfo.getClientKey());
        }
        config.setCaCertFile(caCertFile);
        config.setClientCertFile(clientCertFile);
        config.setClientCertData(currentAuthInfo.getClientCertificateData());
        config.setClientKeyFile(clientKeyFile);
        config.setClientKeyData(currentAuthInfo.getClientKeyData());
        config.setOauthToken(currentAuthInfo.getToken());
        config.setUsername(currentAuthInfo.getUsername());
        config.setPassword(currentAuthInfo.getPassword());

        if (Utils.isNullOrEmpty(config.getOauthToken()) && currentAuthInfo.getAuthProvider() != null) {
          if (currentAuthInfo.getAuthProvider().getConfig() != null) {
            if (!Utils.isNullOrEmpty(currentAuthInfo.getAuthProvider().getConfig().get(ACCESS_TOKEN))) {
              // GKE token
              config.setOauthToken(currentAuthInfo.getAuthProvider().getConfig().get(ACCESS_TOKEN));
            } else if (!Utils.isNullOrEmpty(currentAuthInfo.getAuthProvider().getConfig().get(ID_TOKEN))) {
              // OpenID Connect token
              config.setOauthToken(currentAuthInfo.getAuthProvider().getConfig().get(ID_TOKEN));
            }
          }
        } else if (config.getOauthTokenProvider() == null) {  // https://kubernetes.io/docs/reference/access-authn-authz/authentication/#client-go-credential-plugins
          ExecConfig exec = currentAuthInfo.getExec();
          if (exec != null) {
            String apiVersion = exec.getApiVersion();
            if ("client.authentication.k8s.io/v1alpha1".equals(apiVersion) || "client.authentication.k8s.io/v1beta1".equals(apiVersion)) {
              List<String> argv = new ArrayList<String>();
              String command = exec.getCommand();
              if (command.contains("/") && !command.startsWith("/") && kubeconfigPath != null && !kubeconfigPath.isEmpty()) {
                // Appears to be a relative path; normalize. Spec is vague about how to detect this situation.
                command = Paths.get(kubeconfigPath).resolveSibling(command).normalize().toString();
              }
              argv.add(command);
              List<String> args = exec.getArgs();
              if (args != null) {
                argv.addAll(args);
              }
              ProcessBuilder pb = new ProcessBuilder(argv);
              List<ExecEnvVar> env = exec.getEnv();
              if (env != null) {
                Map<String, String> environment = pb.environment();
                env.forEach(var -> environment.put(var.getName(), var.getValue()));
              }
              // TODO check behavior of tty & stdin
              Process p = pb.start();
              if (p.waitFor() != 0) {
                LOGGER.warn(IOHelpers.readFully(p.getErrorStream()));
              }
              ExecCredential ec = Serialization.unmarshal(p.getInputStream(), ExecCredential.class);
              if (!apiVersion.equals(ec.apiVersion)) {
                LOGGER.warn("Wrong apiVersion {} vs. {}", ec.apiVersion, apiVersion);
              }
              if (ec.status != null && ec.status.token != null) {
                config.setOauthToken(ec.status.token);
              } else {
                LOGGER.warn("No token returned");
              }
            } else { // TODO v1beta1?
              LOGGER.warn("Unsupported apiVersion: {}", apiVersion);
            }
          }
        }

        config.getErrorMessages().put(401, "Unauthorized! Token may have expired! Please log-in again.");
        config.getErrorMessages().put(403, "Forbidden! User " + (currentContext != null? currentContext.getUser() : "") + " doesn't have permission.");
      }
      return true;
    }
  } catch (Exception e) {
    LOGGER.error("Failed to parse the kubeconfig.", e);
  }

  return false;
}
 
Example 17
Source File: CertUtils.java    From kubernetes-client with Apache License 2.0 4 votes vote down vote up
private static char[] getTrustStorePassphrase(String trustStorePassphrase) {
  if (Utils.isNullOrEmpty(trustStorePassphrase)) {
    return System.getProperty(TRUST_STORE_PASSWORD_SYSTEM_PROPERTY, "changeit").toCharArray();
  }
  return trustStorePassphrase.toCharArray();
}
 
Example 18
Source File: CertUtils.java    From kubernetes-client with Apache License 2.0 4 votes vote down vote up
private static char[] getKeyStorePassphrase(String keyStorePassphrase) {
  if (Utils.isNullOrEmpty(keyStorePassphrase)) {
    return System.getProperty(KEY_STORE_PASSWORD_SYSTEM_PROPERTY, "changeit").toCharArray();
  }
  return keyStorePassphrase.toCharArray();
}
 
Example 19
Source File: OpenShiftOAuthInterceptor.java    From kubernetes-client with Apache License 2.0 4 votes vote down vote up
@Override
public Response intercept(Chain chain) throws IOException {
  Request request = chain.request();

  //Build new request
  Request.Builder builder = request.newBuilder();

  String token = oauthToken.get();
  // avoid overwriting basic auth token with stale bearer token
  if (Utils.isNotNullOrEmpty(token) && Utils.isNullOrEmpty(request.header(AUTHORIZATION))) {
    setAuthHeader(builder, token);
  }

  request = builder.build();
  Response response = chain.proceed(request);

  //If response is Forbidden or Unauthorized, try to obtain a token via authorize() or via config.
  if (response.code() != 401 && response.code() != 403) {
    return response;
  } else if (Utils.isNotNullOrEmpty(config.getUsername()) && Utils.isNotNullOrEmpty(config.getPassword())) {
    synchronized (client) {
      // current token (if exists) is borked, don't resend
      oauthToken.set(null);
      token = authorize();
      if (token != null) {
        oauthToken.set(token);
      }
    }
  } else if (Utils.isNotNullOrEmpty(config.getOauthToken())) {
    token = config.getOauthToken();
    oauthToken.set(token);
  }


  //If token was obtained, then retry request using the obtained token.
  if (Utils.isNotNullOrEmpty(token)) {
    // Close the previous response to prevent leaked connections.
    response.body().close();

    setAuthHeader(builder, token);
    request = builder.build();
    return chain.proceed(request); //repeat request with new token
  } else {
    return response;
  }
}
 
Example 20
Source File: KubernetesAttributesExtractor.java    From kubernetes-client with Apache License 2.0 4 votes vote down vote up
private static AttributeSet extract(Matcher m) {
  AttributeSet attributes = new AttributeSet();
  if (m.matches()) {
    String kind = m.group(KIND);
    if (!Utils.isNullOrEmpty(kind)) {

      //Poor mans to singular.
      //Special Case for PodSecurityPolicies and NetworkPolicies because
      //we need to return PodSecurityPolicy and NetworkPolicy respectively
      //because it is returning PodSecurityPolicie and NetworkPolicie now
      //Right now not adding generalised case of "ies" because it may break other resource not sure

      if (kind.endsWith("ses")) {
        kind = kind.substring(0, kind.length() - 2);
      }
      else if (kind.equalsIgnoreCase("PodSecurityPolicies") ||
        kind.equalsIgnoreCase("NetworkPolicies")){
        kind = kind.substring(0,kind.length() - 3) + "y";
      }
      else if (kind.equalsIgnoreCase("securityContextConstraints") ||
        kind.equalsIgnoreCase("endpoints")){
        // do nothing
        // because its a case which is ending with s but its name is
        // like that, it is not plural
      }
      else if (kind.endsWith("s")) {
        kind = kind.substring(0, kind.length() - 1);
      }
      attributes = attributes.add(new Attribute(KIND, kind));
    }

    String namespace = m.group(NAMESPACE);
    if (!Utils.isNullOrEmpty(namespace)) {
      attributes = attributes.add(new Attribute(NAMESPACE, namespace));
    }

    try {
      String name = m.group(NAME);
      if (!Utils.isNullOrEmpty(name)) {
        attributes = attributes.add(new Attribute(NAME, name));
      }
    } catch (IllegalArgumentException e) {
      //group is missing, which is perfectly valid for create, update etc requests.
    }
  }
  return attributes;
}