Java Code Examples for io.fabric8.kubernetes.client.utils.Serialization#unmarshal()

The following examples show how to use io.fabric8.kubernetes.client.utils.Serialization#unmarshal() . 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: NamespaceVisitFromServerGetWatchDeleteRecreateWaitApplicableListImpl.java    From kubernetes-client with Apache License 2.0 6 votes vote down vote up
public NamespaceVisitFromServerGetWatchDeleteRecreateWaitApplicableListImpl(OkHttpClient client, Config config, String namespace, String explicitNamespace, Boolean fromServer, Boolean deletingExisting, List<Visitor> visitors, Object item, InputStream inputStream, Map<String, String> parameters, long gracePeriodSeconds, DeletionPropagation propagationPolicy, Boolean cascading, long watchRetryInitialBackoffMillis, double watchRetryBackoffMultiplier) {
    super(client, config);
    this.fallbackNamespace = namespace;
    this.explicitNamespace = explicitNamespace;
    this.fromServer = fromServer;
    this.deletingExisting = deletingExisting;
    this.visitors = visitors != null ? new ArrayList<>(visitors) : new ArrayList<>();
    this.watchRetryInitialBackoffMillis = watchRetryInitialBackoffMillis;
    this.watchRetryBackoffMultiplier = watchRetryBackoffMultiplier;

  if (item != null) {
      this.item = item;
    } else if (inputStream != null) {
      this.item = Serialization.unmarshal(inputStream, parameters);
    } else {
      throw new IllegalArgumentException("Need to either specify an Object or an InputStream.");
    }

    this.inputStream = inputStream;
    this.cascading = cascading;
    this.gracePeriodSeconds = gracePeriodSeconds;
    this.propagationPolicy = propagationPolicy;
    this.visitors.add(new ChangeNamespace(explicitNamespace, fallbackNamespace));
}
 
Example 2
Source File: OpenshiftAdapterSupport.java    From kubernetes-client with Apache License 2.0 6 votes vote down vote up
/**
 * Check if OpenShift API Groups are available
 * @param httpClient   The httpClient.
 * @param masterUrl    The master url.
 * @return             True if the new <code>/apis/*.openshift.io/</code> APIs are found in the root paths.
 */
static boolean isOpenShiftAPIGroups(OkHttpClient httpClient, String masterUrl) {
  try {
    Request.Builder requestBuilder = new Request.Builder()
      .get()
      .url(URLUtils.join(masterUrl, APIS));
    Response response = httpClient.newCall(requestBuilder.build()).execute();
    APIGroupList apiGroupList = Serialization.unmarshal(response.body().string(), APIGroupList.class);

    for (APIGroup apiGroup : apiGroupList.getGroups()) {
      if (apiGroup.getName().endsWith("openshift.io")) {
        return true;
      }
    }
  } catch(Exception e) {
    KubernetesClientException.launderThrowable(e);
  }
  return false;
}
 
Example 3
Source File: OperationSupport.java    From kubernetes-client with Apache License 2.0 6 votes vote down vote up
/**
 * Send an http request and handle the response, optionally performing placeholder substitution to the response.
 *
 * @param client               OkHttp client provided
 * @param requestBuilder       Request builder
 * @param type                 Type of object provided
 * @param parameters           A hashmap containing parameters
 * @param <T>                  Template argument provided
 *
 * @return                      Returns a de-serialized object as api server response of provided type.
 * @throws ExecutionException   Execution Exception
 * @throws InterruptedException Interrupted Exception
 * @throws KubernetesClientException KubernetesClientException
 * @throws IOException IOException
 */
protected <T> T handleResponse(OkHttpClient client, Request.Builder requestBuilder, Class<T> type, Map<String, String> parameters) throws ExecutionException, InterruptedException, KubernetesClientException, IOException {
  VersionUsageUtils.log(this.resourceT, this.apiGroupVersion);
  Request request = requestBuilder.build();
  Response response = client.newCall(request).execute();
  try (ResponseBody body = response.body()) {
    assertResponseCode(request, response);
    if (type != null) {
      try (InputStream bodyInputStream = body.byteStream()) {
        return Serialization.unmarshal(bodyInputStream, type, parameters);
      }
    } else {
      return null;
    }
  } catch (Exception e) {
    if (e instanceof KubernetesClientException) {
      throw e;
    }
    throw requestException(request, e);
  } finally {
    if(response != null && response.body() != null) {
      response.body().close();
    }
  }
}
 
Example 4
Source File: CustomTemplatePodTemplateProvider.java    From teamcity-kubernetes-plugin with Apache License 2.0 6 votes vote down vote up
@Used("tests")
/* package local for tests */ Pod getPodTemplateInternal(@NotNull final CloudInstanceUserData cloudInstanceUserData,
                                  @NotNull final String imageId,
                                  @NotNull final String namespace,
                                  final String instanceName,
                                  String spec) {
    spec = spec.replaceAll("%instance\\.id%", instanceName);

    if (StringUtil.isEmpty(spec)) {
        throw new KubeCloudException("Custom pod template spec is not specified for image " + imageId);
    }

    final PodTemplateSpec podTemplateSpec = Serialization.unmarshal(
      new ByteArrayInputStream(spec.getBytes()),
      PodTemplateSpec.class
    );

    return patchedPodTemplateSpec(podTemplateSpec,
                                  instanceName,
                                  namespace,
                                  myServerSettings.getServerUUID(),
                                  imageId,
                                  cloudInstanceUserData);
}
 
Example 5
Source File: CustomTemplatePodTemplateProvider.java    From teamcity-kubernetes-plugin with Apache License 2.0 6 votes vote down vote up
@Nullable
@Override
public PersistentVolumeClaim getPVC(@NotNull final String instanceName,
                                    @NotNull final KubeCloudImage kubeCloudImage) {
    String pvcTemplate = kubeCloudImage.getPVCTemplate();
    if (StringUtil.isEmpty(pvcTemplate)){
        return null;
    }
    pvcTemplate = pvcTemplate.replaceAll("%instance\\.id%", instanceName);
    final PersistentVolumeClaim pvc = Serialization.unmarshal(
      new ByteArrayInputStream(pvcTemplate.getBytes()),
      PersistentVolumeClaim.class
    );

    return pvc;
}
 
Example 6
Source File: OpenshiftAdapterSupport.java    From kubernetes-client with Apache License 2.0 6 votes vote down vote up
/**
 * Check if OpenShift API Groups are available
 * @param client   The client.
 * @return         True if the new <code>/apis/*.openshift.io/</code> APIs are found in the root paths.
 */
static boolean isOpenShiftAPIGroups(Client client) {
  URL masterUrl = client.getMasterUrl();

  OkHttpClient httpClient = ((BaseClient)client).getHttpClient();
  try {
    Request.Builder requestBuilder = new Request.Builder()
      .get()
      .url(URLUtils.join(masterUrl.toString(), APIS));
    Response response = httpClient.newCall(requestBuilder.build()).execute();
    APIGroupList apiGroupList = Serialization.unmarshal(response.body().string(), APIGroupList.class);

    for (APIGroup apiGroup : apiGroupList.getGroups()) {
      if (apiGroup.getName().endsWith("openshift.io")) {
        return true;
      }
    }
  } catch(Exception e) {
    KubernetesClientException.launderThrowable(e);
  }
  return false;
}
 
Example 7
Source File: WebServerController.java    From java-operator-sdk with Apache License 2.0 5 votes vote down vote up
private <T> T loadYaml(Class<T> clazz, String yaml) {
    try (InputStream is = getClass().getResourceAsStream(yaml)) {
        return Serialization.unmarshal(is, clazz);
    } catch (IOException ex) {
        throw new IllegalStateException("Cannot find yaml on classpath: " + yaml);
    }
}
 
Example 8
Source File: AdmissionReviewTest.java    From kubernetes-client with Apache License 2.0 5 votes vote down vote up
@Test
@DisplayName("Should be able to deserialize from AdmissionRequest option set to PatchOption")
public void testJacksonParsingWithPathOptions() throws IOException {
  InputStream jsonStream = getClass().getResourceAsStream("/admissionreview-withpatchoptions.json");
  AdmissionReview admissionReview = Serialization.unmarshal(jsonStream, AdmissionReview.class);
  assertEquals("PATCH", admissionReview.getRequest().getOperation());
  assertRequest(admissionReview);
}
 
Example 9
Source File: AdmissionReviewTest.java    From kubernetes-client with Apache License 2.0 5 votes vote down vote up
@Test
@DisplayName("Should be able to deserialize from AdmissionRequest option set to CreateOption")
public void testJacksonParsingWithCreateOptions() throws IOException {
  InputStream jsonStream = getClass().getResourceAsStream("/admissionreview.json");
  AdmissionReview admissionReview = Serialization.unmarshal(jsonStream, AdmissionReview.class);
  assertEquals("CREATE", admissionReview.getRequest().getOperation());
  assertRequest(admissionReview);
}
 
Example 10
Source File: IntegrationTestSupport.java    From java-operator-sdk with Apache License 2.0 5 votes vote down vote up
private <T> T loadYaml(Class<T> clazz, String yaml) {
    try (InputStream is = getClass().getResourceAsStream(yaml)) {
        return Serialization.unmarshal(is, clazz);
    } catch (IOException ex) {
        throw new IllegalStateException("Cannot find yaml on classpath: " + yaml);
    }
}
 
Example 11
Source File: DefaultOpenShiftClient.java    From kubernetes-client with Apache License 2.0 4 votes vote down vote up
public static DefaultOpenShiftClient fromConfig(InputStream is) {
  return new DefaultOpenShiftClient(Serialization.unmarshal(is, OpenShiftConfig.class));
}
 
Example 12
Source File: OperationSupport.java    From kubernetes-client with Apache License 2.0 4 votes vote down vote up
protected static <T> T unmarshal(InputStream is, final Class<T> type) throws KubernetesClientException {
  return Serialization.unmarshal(is, type);
}
 
Example 13
Source File: OperationSupport.java    From kubernetes-client with Apache License 2.0 4 votes vote down vote up
protected static <T> T unmarshal(InputStream is, TypeReference<T> type) throws KubernetesClientException {
 return Serialization.unmarshal(is, type);
}
 
Example 14
Source File: DefaultOpenShiftClient.java    From kubernetes-client with Apache License 2.0 4 votes vote down vote up
public static DefaultOpenShiftClient fromConfig(String config) {
  return new DefaultOpenShiftClient(Serialization.unmarshal(config, OpenShiftConfig.class));
}
 
Example 15
Source File: DefaultKubernetesClient.java    From kubernetes-client with Apache License 2.0 4 votes vote down vote up
public static DefaultKubernetesClient fromConfig(String config) {
  return new DefaultKubernetesClient(Serialization.unmarshal(config, Config.class));
}
 
Example 16
Source File: DefaultKubernetesClient.java    From kubernetes-client with Apache License 2.0 4 votes vote down vote up
public static DefaultKubernetesClient fromConfig(InputStream is) {
  return new DefaultKubernetesClient(Serialization.unmarshal(is, Config.class));
}
 
Example 17
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 18
Source File: KnativeTestUtils.java    From module-ballerina-kubernetes with Apache License 2.0 2 votes vote down vote up
/**
 * Load YAML files to kubernetes resource(s).
 *
 * @param file The path of the file.
 * @param <T>  The type reference of the artifact.
 * @return The refered type.
 * @throws IOException When yaml file could not be loaded.
 */
public static <T> T loadYaml(File file) throws IOException {
    FileInputStream fileInputStream = FileUtils.openInputStream(file);
    return Serialization.unmarshal(fileInputStream, Collections.emptyMap());
}
 
Example 19
Source File: KubernetesTestUtils.java    From module-ballerina-kubernetes with Apache License 2.0 2 votes vote down vote up
/**
 * Load YAML files to kubernetes resource(s).
 *
 * @param file The path of the file.
 * @param <T>  The type reference of the artifact.
 * @return The refered type.
 * @throws IOException When yaml file could not be loaded.
 */
public static <T> T loadYaml(File file) throws IOException {
    FileInputStream fileInputStream = FileUtils.openInputStream(file);
    return Serialization.unmarshal(fileInputStream, Collections.emptyMap());
}
 
Example 20
Source File: Utils.java    From module-ballerina-kubernetes with Apache License 2.0 2 votes vote down vote up
/**
 * Load YAML files to kubernetes resource(s).
 *
 * @param file The path of the file.
 * @param <T>  The type reference of the artifact.
 * @return The refered type.
 * @throws IOException When yaml file could not be loaded.
 */
public static <T> T loadYaml(File file) throws IOException {
    FileInputStream fileInputStream = FileUtils.openInputStream(file);
    return Serialization.unmarshal(fileInputStream, Collections.emptyMap());
}