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);
}
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);
};
}
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;
}
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);
}
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);
}
Aggregations