io.fabric8.openshift.api.model.Parameter Java Examples

The following examples show how to use io.fabric8.openshift.api.model.Parameter. 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: OpenshiftHelper.java    From jkube with Eclipse Public License 2.0 6 votes vote down vote up
private static void combineParameters(List<Parameter> parameters, List<Parameter> otherParameters) {
    if (otherParameters != null && otherParameters.size() > 0) {
        Map<String, Parameter> map = new HashMap<>();
        for (Parameter parameter : parameters) {
            map.put(parameter.getName(), parameter);
        }
        for (Parameter otherParameter : otherParameters) {
            String name = otherParameter.getName();
            Parameter original = map.get(name);
            if (original == null) {
                parameters.add(otherParameter);
            } else {
                if (StringUtils.isNotBlank(original.getValue())) {
                    original.setValue(otherParameter.getValue());
                }
            }
        }
    }
}
 
Example #2
Source File: Fabric8OpenShiftServiceImpl.java    From launchpad-missioncontrol with Apache License 2.0 6 votes vote down vote up
@Override
public void configureProject(final OpenShiftProject project,
                             final URI sourceRepositoryUri,
                             final String gitRef,
                             final URI pipelineTemplateUri) {
    final InputStream pipelineTemplateStream;
    try {
        pipelineTemplateStream = pipelineTemplateUri.toURL().openStream();
    } catch (IOException e) {
        throw new RuntimeException("Could not create OpenShift pipeline", e);
    }
    List<Parameter> parameters = Arrays.asList(
            createParameter("GIT_URL", sourceRepositoryUri.toString()),
            createParameter("GIT_REF", gitRef));
    configureProject(project, pipelineTemplateStream, parameters);
    fixJenkinsServiceAccount(project);
}
 
Example #3
Source File: TemplateOperationsImpl.java    From kubernetes-client with Apache License 2.0 6 votes vote down vote up
@Override
public KubernetesList process(Map<String, String> valuesMap) {
  Template t = get();
  try {
    List<Parameter> parameters = t.getParameters();
    if (parameters != null) {
      for (Parameter p : parameters) {
        String v = valuesMap.get(p.getName());
        if (v != null) {
          p.setGenerate(null);
          p.setValue(v);
        }
      }
    }

    RequestBody body = RequestBody.create(JSON, JSON_MAPPER.writeValueAsString(t));
    Request.Builder requestBuilder = new Request.Builder().post(body).url(getProcessUrl());
    t = handleResponse(requestBuilder);
    KubernetesList l = new KubernetesList();
    l.setItems(t.getObjects());
    return l;
  } catch (Exception e) {
    throw KubernetesClientException.launderThrowable(forOperationType("process"), e);
  }
}
 
Example #4
Source File: OpenshiftHelper.java    From jkube with Eclipse Public License 2.0 5 votes vote down vote up
public static KubernetesList processTemplatesLocally(Template entity, boolean failOnMissingParameterValue) throws IOException {
    List<HasMetadata> objects = null;
    if (entity != null) {
        objects = entity.getObjects();
        if (objects == null || objects.isEmpty()) {
            return null;
        }
    }
    List<Parameter> parameters = entity != null ? entity.getParameters() : null;
    if (parameters != null && !parameters.isEmpty()) {
        String json = "{\"kind\": \"List\", \"apiVersion\": \"" + DEFAULT_API_VERSION + "\",\n" +
                "  \"items\": " + ResourceUtil.toJson(objects) + " }";

        // lets make a few passes in case there's expressions in values
        for (int i = 0; i < 5; i++) {
            for (Parameter parameter : parameters) {
                String name = parameter.getName();
                String from = "${" + name + "}";
                String value = parameter.getValue();

                // TODO generate random strings for passwords etc!
                if (StringUtils.isBlank(value)) {
                    if (failOnMissingParameterValue) {
                        throw new IllegalArgumentException("No value available for parameter name: " + name);
                    } else {
                        value = "";
                    }
                }
                json = json.replace(from, value);
            }
        }
        return  OBJECT_MAPPER.readerFor(KubernetesList.class).readValue(json);
    } else {
        KubernetesList answer = new KubernetesList();
        answer.setItems(objects);
        return answer;
    }
}
 
Example #5
Source File: OpenshiftHelper.java    From jkube with Eclipse Public License 2.0 5 votes vote down vote up
public static Template combineTemplates(Template firstTemplate, Template template) {
    List<HasMetadata> objects = template.getObjects();
    if (objects != null) {
        for (HasMetadata object : objects) {
            addTemplateObject(firstTemplate, object);
        }
    }
    List<Parameter> parameters = firstTemplate.getParameters();
    if (parameters == null) {
        parameters = new ArrayList<>();
        firstTemplate.setParameters(parameters);
    }
    combineParameters(parameters, template.getParameters());
    String name = KubernetesHelper.getName(template);
    if (StringUtils.isNotBlank(name)) {
        // lets merge all the jkube annotations using the template id qualifier as a postfix
        Map<String, String> annotations = KubernetesHelper.getOrCreateAnnotations(firstTemplate);
        Map<String, String> otherAnnotations = KubernetesHelper.getOrCreateAnnotations(template);
        Set<Map.Entry<String, String>> entries = otherAnnotations.entrySet();
        for (Map.Entry<String, String> entry : entries) {
            String key = entry.getKey();
            String value = entry.getValue();
            if (!annotations.containsKey(key)) {
                annotations.put(key, value);
            }
        }
    }
    return firstTemplate;
}
 
Example #6
Source File: Fabric8OpenShiftServiceImpl.java    From launchpad-missioncontrol with Apache License 2.0 5 votes vote down vote up
@Override
public void configureProject(final OpenShiftProject project, final URI sourceRepositoryUri) {
    final InputStream pipelineTemplateStream = getClass().getResourceAsStream("/pipeline-template.yml");
    List<Parameter> parameters = Arrays.asList(
            createParameter("SOURCE_REPOSITORY_URL", sourceRepositoryUri.toString()),
            createParameter("PROJECT", project.getName()),
            createParameter("OPENSHIFT_CONSOLE_URL", this.getConsoleUrl().toString()),
            createParameter("GITHUB_WEBHOOK_SECRET", Long.toString(System.currentTimeMillis())));
    configureProject(project, pipelineTemplateStream, parameters);
    fixJenkinsServiceAccount(project);
}
 
Example #7
Source File: Fabric8OpenShiftServiceImpl.java    From launchpad-missioncontrol with Apache License 2.0 5 votes vote down vote up
@Override
public void configureProject(final OpenShiftProject project, InputStream templateStream, final URI sourceRepositoryUri, final String sourceRepositoryContextDir) {
    List<Parameter> parameters = Arrays.asList(
            createParameter("SOURCE_REPOSITORY_URL", sourceRepositoryUri.toString()),
            createParameter("SOURCE_REPOSITORY_DIR", sourceRepositoryContextDir),
            createParameter("PROJECT", project.getName()),
            createParameter("OPENSHIFT_CONSOLE_URL", this.getConsoleUrl().toString()),
            createParameter("GITHUB_WEBHOOK_SECRET", Long.toString(System.currentTimeMillis())));
    configureProject(project, templateStream, parameters);
}
 
Example #8
Source File: Fabric8OpenShiftServiceImpl.java    From launchpad-missioncontrol with Apache License 2.0 5 votes vote down vote up
private void applyParameterValueProperties(final OpenShiftProject project, final Template template) {
    RouteList routes = null;
    for (Parameter parameter : template.getParameters()) {
        // Find any parameters with special "fabric8-value" properties
        if (parameter.getAdditionalProperties().containsKey("fabric8-value")
                && parameter.getValue() == null) {
            String value = parameter.getAdditionalProperties().get("fabric8-value").toString();
            Matcher m = PARAM_VAR_PATTERN.matcher(value);
            StringBuffer newval = new StringBuffer();
            while (m.find()) {
                String type = m.group(1);
                String routeName = m.group(2);
                String propertyPath = m.group(3);
                String propertyValue = "";
                // We only support "route/XXX[.spec.host]" for now,
                // but we're prepared for future expansion
                if ("route".equals(type) && ".spec.host".equals(propertyPath)) {
                    // Try to find a Route with that name and use its host name
                    if (routes == null) {
                        routes = client.routes().inNamespace(project.getName()).list();
                    }
                    propertyValue = routes.getItems().stream()
                        .filter(r -> routeName.equals(r.getMetadata().getName()))
                        .map(r -> r.getSpec().getHost())
                        .filter(Objects::nonNull)
                        .findAny()
                        .orElse(propertyValue);
                }
                m.appendReplacement(newval, Matcher.quoteReplacement(propertyValue));
            }
            m.appendTail(newval);
            parameter.setValue(newval.toString());
        }
    }
}
 
Example #9
Source File: NamespaceVisitFromServerGetWatchDeleteRecreateWaitApplicableListImpl.java    From kubernetes-client with Apache License 2.0 5 votes vote down vote up
private static List<HasMetadata> processTemplate(Template template, Boolean failOnMissing)  {
  List<Parameter> parameters = template != null ? template.getParameters() : null;
  KubernetesList list = new KubernetesListBuilder()
    .withItems(template.getObjects())
    .build();

  try {
    String json = OBJECT_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 name = parameter.getName();
          String regex = "${" + name + "}";
          String value;
          if (Utils.isNotNullOrEmpty(parameter.getValue())) {
            value = parameter.getValue();
          } else if (EXPRESSION.equals(parameter.getGenerate())) {
            Generex generex = new Generex(parameter.getFrom());
            value = generex.random();
          } else if (failOnMissing) {
            throw new IllegalArgumentException("No value available for parameter name: " + name);
          } else {
            value = "";
          }
          json = json.replace(regex, value);
        }
      }
    }

    list = OBJECT_MAPPER.readValue(json, KubernetesList.class);
  } catch (IOException e) {
    throw KubernetesClientException.launderThrowable(e);
  }
  return list.getItems();
}
 
Example #10
Source File: HelmParameter.java    From jkube with Eclipse Public License 2.0 4 votes vote down vote up
public HelmParameter(Parameter parameter) {
  this.parameter = parameter;
}
 
Example #11
Source File: HelmParameter.java    From jkube with Eclipse Public License 2.0 4 votes vote down vote up
public Parameter getParameter() {
  return parameter;
}
 
Example #12
Source File: Fabric8OpenShiftServiceImpl.java    From launchpad-missioncontrol with Apache License 2.0 4 votes vote down vote up
private Parameter createParameter(final String name, final String value) {
    Parameter parameter = new Parameter();
    parameter.setName(name);
    parameter.setValue(value);
    return parameter;
}
 
Example #13
Source File: TemplateExample.java    From kubernetes-client with Apache License 2.0 4 votes vote down vote up
public static void main(String[] args) {
  try (OpenShiftClient client = new DefaultOpenShiftClient()) {
    try {
      logger.info("Creating temporary namespace '{}' for example", NAMESPACE);
      client.namespaces().createNew().withNewMetadata().withName(NAMESPACE).endMetadata().done();

      final Template loadedTemplate = client.templates()
        .load(TemplateExample.class.getResourceAsStream(TEST_TEMPLATE_RESOURCE)).get();
      for (Parameter p : loadedTemplate.getParameters()) {
        final String required = Boolean.TRUE.equals(p.getRequired()) ? "*" : "";
        logger.info("Loaded parameter from template: {}{} - '{}' ({})",
          p.getName(), required, p.getValue(), p.getGenerate());
      }

      final Template serverUploadedTemplate = client.templates()
        .inNamespace(NAMESPACE)
        .load(TemplateExample.class.getResourceAsStream(TEST_TEMPLATE_RESOURCE))
        .create();
      logger.info("Template {} successfully created on server", serverUploadedTemplate.getMetadata().getName());
      final Template serverDownloadedTemplate = client.templates().inNamespace(NAMESPACE).withName(DEFAULT_NAME_OF_TEMPLATE).get();
      logger.info("Template {} successfully downloaded from server", serverDownloadedTemplate.getMetadata().getName());

      final KubernetesList processedTemplateWithDefaultParameters = client.templates()
        .inNamespace(NAMESPACE).withName(DEFAULT_NAME_OF_TEMPLATE).process();
      logger.info("Template {} successfully processed to list with {} items, and requiredBoolean = {}",
        processedTemplateWithDefaultParameters.getItems().get(0).getMetadata().getLabels().get("template"),
        processedTemplateWithDefaultParameters.getItems().size(),
        processedTemplateWithDefaultParameters.getItems().get(0).getMetadata().getLabels().get("requiredBoolean"));

      final KubernetesList processedTemplateWithCustomParameters = client.templates()
        .inNamespace(NAMESPACE).withName(DEFAULT_NAME_OF_TEMPLATE).process(Collections.singletonMap("REQUIRED_BOOLEAN", "true"));
      logger.info("Template {} successfully processed to list with {} items, and requiredBoolean = {}",
        processedTemplateWithCustomParameters.getItems().get(0).getMetadata().getLabels().get("template"),
        processedTemplateWithCustomParameters.getItems().size(),
        processedTemplateWithCustomParameters.getItems().get(0).getMetadata().getLabels().get("requiredBoolean"));

      KubernetesList l = client.lists().load(TemplateExample.class.getResourceAsStream("/test-list.yml")).get();
      logger.info("{}", l.getItems().size());

      final boolean templateDeleted = client.templates().inNamespace(NAMESPACE).withName(DEFAULT_NAME_OF_TEMPLATE).delete();
      logger.info("Template {} was {}deleted", DEFAULT_NAME_OF_TEMPLATE, templateDeleted ? "" : "**NOT** ");
      client.lists().inNamespace(NAMESPACE).load(TemplateExample.class.getResourceAsStream("/test-list.yml")).create();
    } finally {
      // And finally clean up the namespace
      client.namespaces().withName(NAMESPACE).delete();
      logger.info("Deleted namespace {}", NAMESPACE);
    }
  }
}
 
Example #14
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;
}