Search in sources :

Example 1 with Utils.isNotNullOrEmpty

use of io.fabric8.kubernetes.client.utils.Utils.isNotNullOrEmpty in project spring-cloud-kubernetes by spring-cloud.

the class Fabric8ServiceInstanceMapper method map.

@Override
public KubernetesServiceInstance map(Service service) {
    final ObjectMeta meta = service.getMetadata();
    final List<ServicePort> ports = service.getSpec().getPorts();
    ServicePort port = null;
    if (ports.size() == 1) {
        port = ports.get(0);
    } else if (ports.size() > 1 && Utils.isNotNullOrEmpty(this.properties.getPortName())) {
        Optional<ServicePort> optPort = ports.stream().filter(it -> properties.getPortName().endsWith(it.getName())).findAny();
        if (optPort.isPresent()) {
            port = optPort.get();
        }
    }
    if (port == null) {
        return null;
    }
    final String host = KubernetesServiceInstanceMapper.createHost(service.getMetadata().getName(), service.getMetadata().getNamespace(), properties.getClusterDomain());
    final boolean secure = KubernetesServiceInstanceMapper.isSecure(service.getMetadata().getLabels(), service.getMetadata().getAnnotations(), port.getName(), port.getPort());
    return new KubernetesServiceInstance(meta.getUid(), meta.getName(), host, port.getPort(), getServiceMetadata(service), secure);
}
Also used : ObjectMeta(io.fabric8.kubernetes.api.model.ObjectMeta) ServicePort(io.fabric8.kubernetes.api.model.ServicePort) KubernetesServiceInstance(org.springframework.cloud.kubernetes.commons.discovery.KubernetesServiceInstance) Optional(java.util.Optional)

Example 2 with Utils.isNotNullOrEmpty

use of io.fabric8.kubernetes.client.utils.Utils.isNotNullOrEmpty in project che-server by eclipse-che.

the class OpenShiftClientFactory method buildKubernetesInterceptor.

@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);
    };
}
Also used : Response(okhttp3.Response) KubernetesClientFactory(org.eclipse.che.workspace.infrastructure.kubernetes.KubernetesClientFactory) Authenticator(okhttp3.Authenticator) URL(java.net.URL) Strings.isNullOrEmpty(com.google.common.base.Strings.isNullOrEmpty) DefaultOpenShiftClient(io.fabric8.openshift.client.DefaultOpenShiftClient) Singleton(javax.inject.Singleton) Inject(javax.inject.Inject) Utils(io.fabric8.kubernetes.client.utils.Utils) EventListener(okhttp3.EventListener) Response(okhttp3.Response) Named(javax.inject.Named) KubernetesClientConfigFactory(org.eclipse.che.workspace.infrastructure.kubernetes.KubernetesClientConfigFactory) KubernetesClientException(io.fabric8.kubernetes.client.KubernetesClientException) Interceptor(okhttp3.Interceptor) OpenShiftOAuthInterceptor(io.fabric8.openshift.client.internal.OpenShiftOAuthInterceptor) Request(okhttp3.Request) URLUtils(io.fabric8.kubernetes.client.utils.URLUtils) OpenShiftConfigBuilder(io.fabric8.openshift.client.OpenShiftConfigBuilder) OpenShiftClient(io.fabric8.openshift.client.OpenShiftClient) Credentials(okhttp3.Credentials) Nullable(org.eclipse.che.commons.annotation.Nullable) Consumer(java.util.function.Consumer) Config(io.fabric8.kubernetes.client.Config) InfrastructureException(org.eclipse.che.api.workspace.server.spi.InfrastructureException) OpenShiftConfig(io.fabric8.openshift.client.OpenShiftConfig) OkHttpClient(okhttp3.OkHttpClient) KubernetesClient(io.fabric8.kubernetes.client.KubernetesClient) ImpersonatorInterceptor(io.fabric8.kubernetes.client.utils.ImpersonatorInterceptor) Utils.isNotNullOrEmpty(io.fabric8.kubernetes.client.utils.Utils.isNotNullOrEmpty) OkHttpClient(okhttp3.OkHttpClient) OpenShiftConfigBuilder(io.fabric8.openshift.client.OpenShiftConfigBuilder) Request(okhttp3.Request) URL(java.net.URL) KubernetesClientException(io.fabric8.kubernetes.client.KubernetesClientException) InfrastructureException(org.eclipse.che.api.workspace.server.spi.InfrastructureException) KubernetesClientException(io.fabric8.kubernetes.client.KubernetesClientException)

Example 3 with Utils.isNotNullOrEmpty

use of io.fabric8.kubernetes.client.utils.Utils.isNotNullOrEmpty in project kubernetes-client by fabric8io.

the class HttpClientUtils method createApplicableInterceptors.

public static Map<String, io.fabric8.kubernetes.client.http.Interceptor> createApplicableInterceptors(Config config, HttpClient.Factory factory) {
    Map<String, io.fabric8.kubernetes.client.http.Interceptor> interceptors = new LinkedHashMap<>();
    // Header Interceptor
    interceptors.put(HEADER_INTERCEPTOR, new Interceptor() {

        @Override
        public void before(BasicBuilder builder, HttpHeaders headers) {
            if (Utils.isNotNullOrEmpty(config.getUsername()) && Utils.isNotNullOrEmpty(config.getPassword())) {
                builder.header("Authorization", basicCredentials(config.getUsername(), config.getPassword()));
            } else if (Utils.isNotNullOrEmpty(config.getOauthToken())) {
                builder.header("Authorization", "Bearer " + config.getOauthToken());
            }
            if (config.getCustomHeaders() != null && !config.getCustomHeaders().isEmpty()) {
                for (Map.Entry<String, String> entry : config.getCustomHeaders().entrySet()) {
                    builder.header(entry.getKey(), entry.getValue());
                }
            }
            if (config.getUserAgent() != null && !config.getUserAgent().isEmpty()) {
                builder.setHeader("User-Agent", config.getUserAgent());
            }
        }
    });
    // Impersonator Interceptor
    interceptors.put(ImpersonatorInterceptor.NAME, new ImpersonatorInterceptor(config));
    // Token Refresh Interceptor
    interceptors.put(TokenRefreshInterceptor.NAME, new TokenRefreshInterceptor(config, factory));
    // Backwards Compatibility Interceptor
    String shouldDisableBackwardsCompatibilityInterceptor = Utils.getSystemPropertyOrEnvVar(KUBERNETES_BACKWARDS_COMPATIBILITY_INTERCEPTOR_DISABLE, "false");
    if (!Boolean.parseBoolean(shouldDisableBackwardsCompatibilityInterceptor)) {
        interceptors.put(BackwardsCompatibilityInterceptor.NAME, new BackwardsCompatibilityInterceptor());
    }
    return interceptors;
}
Also used : HttpHeaders(io.fabric8.kubernetes.client.http.HttpHeaders) LinkedHashMap(java.util.LinkedHashMap) BasicBuilder(io.fabric8.kubernetes.client.http.BasicBuilder) Interceptor(io.fabric8.kubernetes.client.http.Interceptor)

Example 4 with Utils.isNotNullOrEmpty

use of io.fabric8.kubernetes.client.utils.Utils.isNotNullOrEmpty in project kubernetes-client by fabric8io.

the class JObject method generateJava.

@Override
public GeneratorResult generateJava() {
    CompilationUnit cu = new CompilationUnit();
    if (!this.pkg.isEmpty()) {
        cu.setPackageDeclaration(this.pkg);
    }
    ClassOrInterfaceDeclaration clz = cu.addClass(this.className);
    clz.addAnnotation(new SingleMemberAnnotationExpr(new Name("com.fasterxml.jackson.annotation.JsonInclude"), new NameExpr("com.fasterxml.jackson.annotation.JsonInclude.Include.NON_NULL")));
    clz.addAnnotation(new SingleMemberAnnotationExpr(new Name("com.fasterxml.jackson.annotation.JsonPropertyOrder"), new NameExpr(getSortedFieldsAsParam(this.fields.keySet()))));
    clz.addAnnotation(new SingleMemberAnnotationExpr(new Name("com.fasterxml.jackson.databind.annotation.JsonDeserialize"), new NameExpr("using = com.fasterxml.jackson.databind.JsonDeserializer.None.class")));
    if (config.isObjectExtraAnnotations()) {
        addExtraAnnotations(clz);
    }
    clz.addImplementedType("io.fabric8.kubernetes.api.model.KubernetesResource");
    List<GeneratorResult.ClassResult> buffer = new ArrayList<>(this.fields.size() + 1);
    List<String> sortedKeys = this.fields.keySet().stream().sorted().collect(Collectors.toList());
    for (String k : sortedKeys) {
        AbstractJSONSchema2Pojo prop = this.fields.get(k);
        boolean isRequired = this.required.contains(k);
        GeneratorResult gr = prop.generateJava();
        // For now the inner types are only for enums
        if (!gr.getInnerClasses().isEmpty()) {
            for (GeneratorResult.ClassResult enumCR : gr.getInnerClasses()) {
                Optional<EnumDeclaration> ed = enumCR.getCompilationUnit().getEnumByName(enumCR.getName());
                if (ed.isPresent()) {
                    clz.addMember(ed.get());
                }
            }
        }
        buffer.addAll(gr.getTopLevelClasses());
        String originalFieldName = k;
        String fieldName = AbstractJSONSchema2Pojo.sanitizeString(k);
        String fieldType = prop.getType();
        try {
            FieldDeclaration objField = clz.addField(fieldType, fieldName, Modifier.Keyword.PRIVATE);
            objField.addAnnotation(new SingleMemberAnnotationExpr(new Name("com.fasterxml.jackson.annotation.JsonProperty"), new StringLiteralExpr(originalFieldName)));
            if (isRequired) {
                objField.addAnnotation("javax.validation.constraints.NotNull");
            }
            objField.createGetter();
            objField.createSetter();
            if (Utils.isNotNullOrEmpty(prop.getDescription())) {
                objField.setJavadocComment(prop.getDescription());
                objField.addAnnotation(new SingleMemberAnnotationExpr(new Name("com.fasterxml.jackson.annotation.JsonPropertyDescription"), new StringLiteralExpr(prop.getDescription().replace("\"", "\\\""))));
            }
        } catch (Exception cause) {
            throw new JavaGeneratorException("Error generating field " + fieldName + " with type " + prop.getType(), cause);
        }
    }
    if (this.preserveUnknownFields || config.isAlwaysPreserveUnknownFields()) {
        ClassOrInterfaceType mapType = new ClassOrInterfaceType().setName(Keywords.JAVA_UTIL_MAP).setTypeArguments(new ClassOrInterfaceType().setName("String"), new ClassOrInterfaceType().setName("Object"));
        FieldDeclaration objField = clz.addField(mapType, Keywords.ADDITIONAL_PROPERTIES, Modifier.Keyword.PRIVATE);
        objField.setVariables(new NodeList<>(new VariableDeclarator().setName(Keywords.ADDITIONAL_PROPERTIES).setType(mapType).setInitializer("new java.util.HashMap<>()")));
        objField.addAnnotation("com.fasterxml.jackson.annotation.JsonIgnore");
        objField.createGetter().addAnnotation("com.fasterxml.jackson.annotation.JsonAnyGetter");
        objField.createSetter().addAnnotation("com.fasterxml.jackson.annotation.JsonAnySetter");
    }
    buffer.add(new GeneratorResult.ClassResult(this.className, cu));
    return new GeneratorResult(buffer);
}
Also used : CompilationUnit(com.github.javaparser.ast.CompilationUnit) ClassOrInterfaceDeclaration(com.github.javaparser.ast.body.ClassOrInterfaceDeclaration) ClassOrInterfaceType(com.github.javaparser.ast.type.ClassOrInterfaceType) FieldDeclaration(com.github.javaparser.ast.body.FieldDeclaration) JavaGeneratorException(io.fabric8.java.generator.exceptions.JavaGeneratorException) EnumDeclaration(com.github.javaparser.ast.body.EnumDeclaration) VariableDeclarator(com.github.javaparser.ast.body.VariableDeclarator) JavaGeneratorException(io.fabric8.java.generator.exceptions.JavaGeneratorException)

Example 5 with Utils.isNotNullOrEmpty

use of io.fabric8.kubernetes.client.utils.Utils.isNotNullOrEmpty in project kubernetes-client by fabric8io.

the class OperationSupport method createStatus.

public static Status createStatus(HttpResponse<?> response) {
    String statusMessage = "";
    int statusCode = response != null ? response.code() : 0;
    if (response == null) {
        statusMessage = "No response";
    } else {
        try {
            String bodyString = response.bodyString();
            if (Utils.isNotNullOrEmpty(bodyString)) {
                Status status = JSON_MAPPER.readValue(bodyString, Status.class);
                if (status.getCode() == null) {
                    status = new StatusBuilder(status).withCode(statusCode).build();
                }
                return status;
            }
        } catch (IOException e) {
        // ignored
        }
        if (response.message() != null) {
            statusMessage = response.message();
        }
    }
    return createStatus(statusCode, statusMessage);
}
Also used : Status(io.fabric8.kubernetes.api.model.Status) StatusBuilder(io.fabric8.kubernetes.api.model.StatusBuilder) IOException(java.io.IOException)

Aggregations

KubernetesClientException (io.fabric8.kubernetes.client.KubernetesClientException)5 IOException (java.io.IOException)5 KubernetesListBuilder (io.fabric8.kubernetes.api.model.KubernetesListBuilder)3 Status (io.fabric8.kubernetes.api.model.Status)3 Utils (io.fabric8.kubernetes.client.utils.Utils)3 OpenShiftConfig (io.fabric8.openshift.client.OpenShiftConfig)3 OpenShiftConfigBuilder (io.fabric8.openshift.client.OpenShiftConfigBuilder)3 KeyStore (java.security.KeyStore)3 Strings.isNullOrEmpty (com.google.common.base.Strings.isNullOrEmpty)2 Generex (com.mifmif.common.regex.Generex)2 ConfigMap (io.fabric8.kubernetes.api.model.ConfigMap)2 KubernetesList (io.fabric8.kubernetes.api.model.KubernetesList)2 StatusBuilder (io.fabric8.kubernetes.api.model.StatusBuilder)2 Config (io.fabric8.kubernetes.client.Config)2 KubernetesClient (io.fabric8.kubernetes.client.KubernetesClient)2 CertUtils.createKeyStore (io.fabric8.kubernetes.client.internal.CertUtils.createKeyStore)2 ImpersonatorInterceptor (io.fabric8.kubernetes.client.utils.ImpersonatorInterceptor)2 URLUtils (io.fabric8.kubernetes.client.utils.URLUtils)2 Utils.isNotNullOrEmpty (io.fabric8.kubernetes.client.utils.Utils.isNotNullOrEmpty)2 Parameter (io.fabric8.openshift.api.model.Parameter)2