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

The following examples show how to use io.fabric8.kubernetes.client.utils.Utils#isNotNullOrEmpty() . 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: GetNamespaceStepExecution.java    From kubernetes-pipeline-plugin with Apache License 2.0 6 votes vote down vote up
@Override
protected String run() throws Exception {
    String namespace = null;
    try {
        FilePath workspace = getContext().get(FilePath.class);
        namespace = workspace.child(Config.KUBERNETES_NAMESPACE_PATH).readToString();
        if (Utils.isNotNullOrEmpty(namespace)) {
            return namespace;
        }
    } catch (Throwable t) {
        //it might be executed outside of a `node` block in which case, we want to ignore.
    }

    NamespaceAction namespaceAction = new NamespaceAction(getContext().get(Run.class));
    namespace = namespaceAction.getNamespace();

    if (Utils.isNotNullOrEmpty(namespace)) {
        return namespace;
    }
    return step.getFallbackNamespace();
}
 
Example 2
Source File: CertUtils.java    From kubernetes-client with Apache License 2.0 6 votes vote down vote up
private static File getDefaultTrustStoreFile() {
  String securityDirectory =
    System.getProperty("java.home") + File.separator + "lib" + File.separator + "security" + File.separator;

  String trustStorePath = System.getProperty(TRUST_STORE_SYSTEM_PROPERTY);
  if (Utils.isNotNullOrEmpty(trustStorePath)) {
    return new File(trustStorePath);
  }

  File jssecacertsFile = new File(securityDirectory + "jssecacerts");
  if (jssecacertsFile.exists() && jssecacertsFile.isFile()) {
    return jssecacertsFile;
  }

  return new File(securityDirectory + "cacerts");
}
 
Example 3
Source File: CertUtils.java    From kubernetes-client with Apache License 2.0 6 votes vote down vote up
public static KeyStore createKeyStore(InputStream certInputStream, InputStream keyInputStream, String clientKeyAlgo, char[] clientKeyPassphrase, String keyStoreFile, char[] keyStorePassphrase) throws IOException, CertificateException, NoSuchAlgorithmException, InvalidKeySpecException, KeyStoreException {
    CertificateFactory certFactory = CertificateFactory.getInstance("X509");
    Collection<? extends Certificate> certificates = certFactory.generateCertificates(certInputStream);
    PrivateKey privateKey = loadKey(keyInputStream, clientKeyAlgo);

    KeyStore keyStore = KeyStore.getInstance("JKS");
    if (Utils.isNotNullOrEmpty(keyStoreFile)){
      keyStore.load(new FileInputStream(keyStoreFile), keyStorePassphrase);
    } else {
      loadDefaultKeyStoreFile(keyStore, keyStorePassphrase);
    }

    String alias = certificates.stream().map(cert->((X509Certificate)cert).getIssuerX500Principal().getName()).collect(Collectors.joining("_"));
    keyStore.setKeyEntry(alias, privateKey, clientKeyPassphrase, certificates.toArray(new Certificate[0]));

    return keyStore;
}
 
Example 4
Source File: LoadMultipleDocumentsFromFileExample.java    From kubernetes-client with Apache License 2.0 6 votes vote down vote up
private static String display(HasMetadata item) {
  StringBuilder sb = new StringBuilder();
  sb.append("[ ");
  if (Utils.isNotNullOrEmpty(item.getKind())) {
    sb.append(" Kind:").append(item.getKind());
  }
  if (Utils.isNotNullOrEmpty(item.getMetadata().getName())) {
    sb.append(" Name:").append(item.getMetadata().getName());
  }

  if (item.getMetadata().getLabels() != null && !item.getMetadata().getLabels().isEmpty()) {
    sb.append(" Lables: [ ");
    for (Map.Entry<String, String> entry : item.getMetadata().getLabels().entrySet()) {
      sb.append(entry.getKey()).append(":").append(entry.getValue()).append(" ");
    }
    sb.append("]");
  }
  sb.append(" ]");
  return sb.toString();
}
 
Example 5
Source File: OperationContext.java    From kubernetes-client with Apache License 2.0 6 votes vote down vote up
public OperationContext(OkHttpClient client, Config config, String plural, String namespace, String name, String apiGroupName, String apiGroupVersion, boolean cascading, Object item, Map<String, String> labels, Map<String, String[]> labelsNot, Map<String, String[]> labelsIn, Map<String, String[]> labelsNotIn, Map<String, String> fields, Map<String, String[]> fieldsNot, String resourceVersion, boolean reloadingFromServer, long gracePeriodSeconds, DeletionPropagation propagationPolicy, long watchRetryInitialBackoffMillis, double watchRetryBackoffMultiplier) {
  this.client = client;
  this.config = config;
  this.plural = plural;
  this.namespace = Utils.isNotNullOrEmpty(namespace) ? namespace : (config != null ? config.getNamespace() : null);
  this.name = name;
  this.cascading = cascading;
  this.labels = labels != null ? labels : new HashMap<>();
  this.labelsNot = labelsNot != null ? labelsNot : new HashMap<>();
  this.labelsIn = labelsIn != null ? labelsIn : new HashMap<>();
  this.labelsNotIn = labelsNotIn != null ? labelsNotIn : new HashMap<>();
  this.fields = fields != null ? fields : new HashMap<>();
  this.fieldsNot = fieldsNot != null ? fieldsNot : new HashMap<>();
  this.resourceVersion = resourceVersion;
  this.reloadingFromServer = reloadingFromServer;
  this.gracePeriodSeconds = gracePeriodSeconds;
  this.propagationPolicy = propagationPolicy;
  this.watchRetryInitialBackoffMillis = watchRetryInitialBackoffMillis;
  this.watchRetryBackoffMultiplier = watchRetryBackoffMultiplier;
  this.item = item;
  this.apiGroupName =  ApiVersionUtil.apiGroup(item, apiGroupName);
  this.apiGroupVersion = ApiVersionUtil.apiVersion(item, apiGroupVersion);
}
 
Example 6
Source File: PodUpload.java    From kubernetes-client with Apache License 2.0 5 votes vote down vote up
public static boolean upload(OkHttpClient client, PodOperationContext context,
  OperationSupport operationSupport, Path pathToUpload)
  throws IOException, InterruptedException {

  if (Utils.isNotNullOrEmpty(context.getFile()) && pathToUpload.toFile().isFile()) {
    return uploadFile(client, context, operationSupport, pathToUpload);
  } else if (Utils.isNotNullOrEmpty(context.getDir()) && pathToUpload.toFile().isDirectory()) {
    return uploadDirectory(client, context, operationSupport, pathToUpload);
  }
  throw new IllegalArgumentException("Provided arguments are not valid (file, directory, path)");
}
 
Example 7
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 8
Source File: ZipkinKubernetesAutoConfiguration.java    From spring-cloud-kubernetes with Apache License 2.0 5 votes vote down vote up
@Bean
public ZipkinSpanReporter reporter(KubernetesClient client, KubernetesZipkinDiscoveryProperties discoveryProperties, SpanMetricReporter spanMetricReporter, ZipkinProperties zipkin) {
    String serviceName = discoveryProperties.getServiceName();
    String serviceNamespace = Utils.isNotNullOrEmpty(discoveryProperties.getServiceNamespace()) ? discoveryProperties.getServiceNamespace() : client.getNamespace();

    List<ServiceInstance> services = getInstances(client, serviceName, serviceNamespace);
    String serviceUrl = services.stream()
            .findFirst()
            .map(s -> s.getUri().toString())
            .orElse(null);

    return serviceUrl == null || serviceUrl.isEmpty()
            ? new NullZipkinSpanReporter()
            : new HttpZipkinSpanReporter(serviceUrl, zipkin.getFlushInterval(), zipkin.getCompression().isEnabled(), spanMetricReporter);
}
 
Example 9
Source File: UtilsTest.java    From kubernetes-client with Apache License 2.0 5 votes vote down vote up
@Test
@DisplayName("isNotNullOrEmpty, some null values, should return true")
void isNotNullOrEmptySomeAreNullTest() {
  // Given
  String[] testSample = new String[] {"notNullObj", null, null};

  // When
  final boolean result = Utils.isNotNullOrEmpty(testSample);

  // Then
  assertTrue(result);
}
 
Example 10
Source File: PodOperationsImpl.java    From kubernetes-client with Apache License 2.0 5 votes vote down vote up
@Override
public InputStream read() {
  try {
    if (Utils.isNotNullOrEmpty(getContext().getFile())) {
      return readFile(getContext().getFile());
    } else if (Utils.isNotNullOrEmpty(getContext().getDir())) {
      return readTar(getContext().getDir());
    }
    throw new IllegalStateException("No file or dir has been specified");
  } catch (Exception e) {
    throw KubernetesClientException.launderThrowable(e);
  }
}
 
Example 11
Source File: KubernetesClientException.java    From kubernetes-client with Apache License 2.0 5 votes vote down vote up
public static RuntimeException launderThrowable(OperationInfo spec, Status status, Throwable cause) {
  StringBuilder sb = new StringBuilder();
  sb.append(describeOperation(spec)+ " failed.");
  if (status != null && Utils.isNotNullOrEmpty(status.getMessage())) {
    sb.append("Reason: ").append(status.getMessage());
  }
  return launderThrowable(sb.toString(), cause);
}
 
Example 12
Source File: KubernetesClientException.java    From kubernetes-client with Apache License 2.0 5 votes vote down vote up
private static final String describeOperation(OperationInfo operation) {
  StringBuilder sb = new StringBuilder();
  sb.append("Operation");
  if (Utils.isNotNullOrEmpty(operation.getOperationType())) {
    sb.append(": [").append(operation.getOperationType() + "]");
  }
  sb.append(" ");
  sb.append(" for kind: [").append(operation.getKind()).append("] ");
  sb.append(" with name: [").append(operation.getName()).append("] ");
  sb.append(" in namespace: [").append(operation.getNamespace()).append("] ");
  return sb.toString();
}
 
Example 13
Source File: AbstractStepExecution.java    From kubernetes-pipeline-plugin with Apache License 2.0 5 votes vote down vote up
/**
 * Generates a namespace id/name if one has not been explicitly specified.
 * If no name or prefix is specified, it will try to determine a namespace based on the enclosing elements.
 * Finally it will fallback to generating one using the default prefix.
 *
 * @param name          A fixed namespace name.
 * @param prefix        The prefix to use.
 * @param sessionId     The id of the session.
 * @return              The name if not null or empty, else prefix-sessionId.
 */
protected String generateNamespaceId(String name, String prefix, String sessionId) {
    if (Utils.isNotNullOrEmpty(name)) {
        return name;
    } else if (Utils.isNotNullOrEmpty(prefix)) {
        return String.format(NAME_FORMAT, prefix, sessionId);
    }

    NamespaceAction namespaceAction = getNamespaceAction();
    if (namespaceAction != null && Utils.isNotNullOrEmpty(namespaceAction.getNamespace())) {
        return namespaceAction.getNamespace();
    }

    return String.format(NAME_FORMAT, DEFAULT_PREFIX, sessionId);
}
 
Example 14
Source File: AbstractSessionManagerStepExecution.java    From kubernetes-pipeline-plugin with Apache License 2.0 5 votes vote down vote up
protected boolean isNamespaceProvided() {
    if (Utils.isNotNullOrEmpty(getStep().getName())) {
        return true;
    }

    NamespaceAction namespaceAction = getNamespaceAction();
    if (namespaceAction != null && Utils.isNotNullOrEmpty(namespaceAction.getNamespace())) {
        return true;
    }
    return false;
}
 
Example 15
Source File: CertUtils.java    From kubernetes-client with Apache License 2.0 5 votes vote down vote up
private static void loadDefaultKeyStoreFile(KeyStore keyStore, char[] keyStorePassphrase)
  throws CertificateException, NoSuchAlgorithmException, IOException {

  String keyStorePath = System.getProperty(KEY_STORE_SYSTEM_PROPERTY);
  if (Utils.isNotNullOrEmpty(keyStorePath)) {
    File keyStoreFile = new File(keyStorePath);
    if (loadDefaultStoreFile(keyStore, keyStoreFile, keyStorePassphrase)) {
      return;
    }
  }

  keyStore.load(null);
}
 
Example 16
Source File: UtilsTest.java    From kubernetes-client with Apache License 2.0 5 votes vote down vote up
@Test
@DisplayName("isNotNullOrEmpty, null, should return false")
void isNotNullOrEmpty() {
  // When
  final boolean result1 = Utils.isNotNullOrEmpty((Map)null);
  final boolean result2 = Utils.isNotNullOrEmpty((String)null);
  final boolean result3 = Utils.isNotNullOrEmpty("");

  // Then
  assertFalse(result1);
  assertFalse(result2);
  assertFalse(result3);
}
 
Example 17
Source File: BaseOperation.java    From kubernetes-client with Apache License 2.0 4 votes vote down vote up
private void addQueryStringParam(HttpUrl.Builder requestUrlBuilder, String name, String value) {
  if(Utils.isNotNullOrEmpty(value)) {
    requestUrlBuilder.addQueryParameter(name, value);
  }
}
 
Example 18
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);
  };
}
 
Example 19
Source File: TemplateOperationsImpl.java    From kubernetes-client with Apache License 2.0 4 votes vote down vote up
public KubernetesList processLocally(Map<String, String> valuesMap)  {
  String namespace = getItem() != null ? getItem().getMetadata().getNamespace() : getNamespace();
  if (namespace == null) {
    namespace = getConfig().getNamespace();
  }

  String name = getItem() != null ? getItem().getMetadata().getName() : getName();

  Template t = withParameters(valuesMap)
    .inNamespace(namespace)
    .withName(name)
    .get();

  List<Parameter> parameters = t != null ? t.getParameters() : null;
  KubernetesList list = new KubernetesListBuilder()
    .withItems(t != null && t.getObjects() != null ? t.getObjects() : Collections.<HasMetadata>emptyList())
    .build();

  try {
    String json = JSON_MAPPER.writeValueAsString(list);
    if (parameters != null && !parameters.isEmpty()) {
      // lets make a few passes in case there's expressions in values
      for (int i = 0; i < 5; i++) {
        for (Parameter parameter : parameters) {
          String parameterName = parameter.getName();
          String parameterValue;
          if (valuesMap.containsKey(parameterName)) {
            parameterValue = valuesMap.get(parameterName);
          } else if (Utils.isNotNullOrEmpty(parameter.getValue())) {
            parameterValue = parameter.getValue();
          } else if (EXPRESSION.equals(parameter.getGenerate())) {
            Generex generex = new Generex(parameter.getFrom());
            parameterValue = generex.random();
          } else if (parameter.getRequired() == null || !parameter.getRequired()) {
            parameterValue = "";
          } else {
            throw new IllegalArgumentException("No value available for parameter name: " + parameterName);
          }
          if (parameterValue == null) {
            logger.debug("Parameter {} has a null value", parameterName);
            parameterValue = "";
          }
          json = Utils.interpolateString(json, Collections.singletonMap(parameterName, parameterValue));
        }
      }
    }

    list = JSON_MAPPER.readValue(json, KubernetesList.class);
  } catch (IOException e) {
    throw KubernetesClientException.launderThrowable(e);
  }
  return list;
}
 
Example 20
Source File: CertUtilsTest.java    From kubernetes-client with Apache License 2.0 4 votes vote down vote up
private void storeSystemProperty(String systemProperty) {
  String value = System.getProperty(systemProperty);
  if (Utils.isNotNullOrEmpty(value)) {
    systemProperties.put(systemProperty, value);
  }
}