Java Code Examples for io.fabric8.utils.Strings#isNullOrBlank()

The following examples show how to use io.fabric8.utils.Strings#isNullOrBlank() . 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: CreateEventStepExecution.java    From kubernetes-pipeline-plugin with Apache License 2.0 6 votes vote down vote up
@Override
public String run() throws Exception {

    String json = step.getJson();
    String index = step.getIndex();

    if (Strings.isNullOrBlank(json)) {
        throw new AbortException("No JSON payload found");
    }
    // validate JSON structure
    ObjectMapper objectMapper = new ObjectMapper();
    objectMapper.readTree(json);

    String id = ElasticsearchClient.createEvent(json, index, listener);
    if (Strings.isNullOrBlank(id)){
        throw new AbortException("Error creating event in elasticsearch");
    }

    return id;

}
 
Example 2
Source File: ApproveRequestedEventStepExecution.java    From kubernetes-pipeline-plugin with Apache License 2.0 6 votes vote down vote up
@Override
public String run() throws Exception {

    if (Strings.isNullOrBlank(step.getApp())) {
        throw new AbortException("No App name provided");
    }

    if (Strings.isNullOrBlank(step.getEnvironment())) {
        throw new AbortException("No environment name provided");
    }
    ApprovalEventDTO approval = new ApprovalEventDTO();
    approval.setApp(step.getApp());
    approval.setEnvironment(step.getEnvironment());
    approval.setRequestedTime(new Date());

    String json = mapper.writeValueAsString(approval);

    return ElasticsearchClient.createEvent(json, ElasticsearchClient.APPROVE, listener);

}
 
Example 3
Source File: CamelXmlHelper.java    From fabric8-forge with Apache License 2.0 6 votes vote down vote up
private static String getIdOrIndex(Node node, Map<String, Integer> nodeCounts) {
    String answer = null;
    if (node instanceof Element) {
        Element element = (Element) node;
        String elementName = element.getTagName();
        if ("routes".equals(elementName)) {
            elementName = "camelContext";
        }
        Integer countObject = nodeCounts.get(elementName);
        int count = countObject != null ? countObject.intValue() : 0;
        nodeCounts.put(elementName, ++count);
        answer = element.getAttribute("id");
        if (Strings.isNullOrBlank(answer)) {
            answer = "_" + elementName + count;
        }
    }
    return answer;
}
 
Example 4
Source File: ApproveReceivedEventStepExecution.java    From kubernetes-pipeline-plugin with Apache License 2.0 6 votes vote down vote up
@Override
public String run() throws Exception {

    if (step.getApproved() == null) {
        throw new AbortException("No Approved boolean set");
    }

    if (Strings.isNullOrBlank(step.getId())) {
        // if we dont have an id to update ignore the request as it's likely elasticsearch isn't running
        listener.getLogger().println("No approve event id found.  Skipping approval event update request");
        return OK;
    }
    ApprovalEventDTO approval = new ApprovalEventDTO();
    approval.setApproved(step.getApproved());
    approval.setReceivedTime(new Date());

    String json = mapper.writeValueAsString(approval);

    Boolean success = ElasticsearchClient.updateEvent(step.getId(), json, ElasticsearchClient.APPROVE, listener);
    if (!success){
        throw new AbortException("Error updating Approve event id ["+step.getId()+"]");
    }

    return OK;

}
 
Example 5
Source File: NodeDtoSupport.java    From fabric8-forge with Apache License 2.0 6 votes vote down vote up
public void defaultKey(NodeDto owner, Map<String, Integer> nodeCounts) {
    String elementName = getPattern();
    Integer countObject = nodeCounts.get(elementName);
    int count = countObject != null ? countObject : 0;
    nodeCounts.put(elementName, ++count);
    if (Strings.isNullOrBlank(key)) {
        key = owner.getKey();
        if (Strings.isNullOrBlank(key)) {
            key = "";
        } else {
            key += "/";
        }
        if (Strings.isNotBlank(id)) {
            key += id;
        } else {
            key += "_" + elementName + count;
        }
    }
}
 
Example 6
Source File: SubscribeRequest.java    From funktion-connectors with Apache License 2.0 6 votes vote down vote up
/**
 * Returns the connector name either from an explicit parameter or by taking the first trigger
 */
public String findConnectorName() {
    String answer = getConnectorName();
    if (Strings.isNullOrBlank(answer)) {
        if (funktion != null) {
            List<Flow> flows = notNullList(funktion.getFlows());
            for (Flow flow : flows) {
                List<Step> steps = notNullList(flow.getSteps());
                for (Step step : steps) {
                    if (step instanceof Endpoint) {
                        Endpoint endpoint = (Endpoint) step;
                        String uri = endpoint.getUri();
                        if (Strings.isNotBlank(uri)) {
                            try {
                                return getURIScheme(uri);
                            } catch (URISyntaxException e) {
                                LOG.info("Ignoring parse issue with Endpoint URI: " + uri + ". " + e, e);
                            }
                        }
                    }
                }
            }
        }
    }
    return answer;
}
 
Example 7
Source File: RepositoryResource.java    From fabric8-forge with Apache License 2.0 6 votes vote down vote up
protected void configureBranch(Git git, String branch) {
    // lets update the merge config
    if (Strings.isNotBlank(branch)) {
        StoredConfig config = git.getRepository().getConfig();
        if (Strings.isNullOrBlank(config.getString("branch", branch, "remote")) || Strings.isNullOrBlank(config.getString("branch", branch, "merge"))) {
            config.setString("branch", branch, "remote", getRemote());
            config.setString("branch", branch, "merge", "refs/heads/" + branch);
            try {
                config.save();
            } catch (IOException e) {
                LOG.error("Failed to save the git configuration to " + basedir
                        + " with branch " + branch + " on remote repo: " + remoteRepository + " due: " + e.getMessage() + ". This exception is ignored.", e);
            }
        }
    }
}
 
Example 8
Source File: ProjectFileSystem.java    From fabric8-forge with Apache License 2.0 5 votes vote down vote up
public File getNamespaceProjectFolder(String namespace, String projectId, String secretNamespace, String secretName) {
    if (Strings.isNullOrBlank(secretNamespace)) {
        secretNamespace = namespace;
    }
    if (Strings.isNullOrBlank(secretName)) {
        secretName = "_null";
    }
    File projectFolder = new File(new File(rootProjectFolder), "namespace/" + secretNamespace + "/" + secretName + "/" + namespace + "/" + projectId);
    projectFolder.mkdirs();
    return projectFolder;
}
 
Example 9
Source File: ProjectFileSystem.java    From fabric8-forge with Apache License 2.0 5 votes vote down vote up
public String getCloneUrl(String user, String repositoryName, UserDetails userDetails) {
    GitRepoClient repoClient = userDetails.createRepoClient();
    RepositoryDTO dto = repositoryCache.getOrFindUserRepository(user, repositoryName, repoClient);
    if (dto == null) {
        throw new NotFoundException("No repository defined for user: " + user + " and name: " + repositoryName);
    }
    String cloneUrl = dto.getCloneUrl();
    if (Strings.isNullOrBlank(cloneUrl)) {
        throw new NotFoundException("No cloneUrl defined for user repository: " + user + "/" + repositoryName);
    }
    return cloneUrl;
}
 
Example 10
Source File: ApplyStepExecution.java    From kubernetes-pipeline-plugin with Apache License 2.0 5 votes vote down vote up
private String getRegistry() {
    if (Strings.isNullOrBlank(step.getRegistry())) {
        // lets try and find an external docker registry in the users home namespace pipeline config
        KubernetesClient client = getKubernetes();
        ConfigMap cm = client.configMaps().inNamespace(this.buildConfigNamespace).withName(Constants.USERS_PIPELINE_CONFIGMAP_NAME).get();
        if (cm != null){
            Map<String, String> data = cm.getData();
            if (data != null){
                String rs = data.get(Constants.EXTERNAL_DOCKER_REGISTRY_URL);
                if (Strings.isNotBlank(rs)){
                    return rs;
                }
            }
        }

        // fall back to namespace env vars to support old fabric8 version
        if (isOpenShift() && openShiftClient().supportsOpenShiftAPIGroup(OpenShiftAPIGroups.IMAGE)) {
            if (Strings.isNotBlank(env.get(Constants.OPENSHIFT_DOCKER_REGISTRY_SERVICE_HOST))){
                return env.get(Constants.OPENSHIFT_DOCKER_REGISTRY_SERVICE_HOST) + ":" + env.get(Constants.OPENSHIFT_DOCKER_REGISTRY_SERVICE_PORT);
            }
        } else if (Strings.isNotBlank(env.get(Constants.FABRIC8_DOCKER_REGISTRY_SERVICE_HOST))) {
            return env.get(Constants.FABRIC8_DOCKER_REGISTRY_SERVICE_HOST) + ":" + env.get(Constants.FABRIC8_DOCKER_REGISTRY_SERVICE_PORT);
        }
        return null;
    } else {
        return step.getRegistry();
    }
}
 
Example 11
Source File: CommandsResource.java    From fabric8-forge with Apache License 2.0 5 votes vote down vote up
/**
 * Returns true if the name is valid. Lets filter out commands which are not suitable to run inside fabric8-forge
 */
protected boolean isValidCommandName(String name) {
    if (Strings.isNullOrBlank(name) || ignoreCommands.contains(name)) {
        return false;
    }
    for (String prefix : ignoreCommandPrefixes) {
        if (name.startsWith(prefix)) {
            return false;
        }
    }
    return true;
}
 
Example 12
Source File: AbstractDevOpsCommand.java    From fabric8-forge with Apache License 2.0 5 votes vote down vote up
protected String getOrFindGitUrl(UIExecutionContext context, String gitUrlText) {
    if (Strings.isNullOrBlank(gitUrlText)) {
        final Project project = getSelectedProject(context);
        if (project != null) {
            Resource<?> root = project.getRoot();
            if (root != null) {
                try {
                    Resource<?> gitFolder = root.getChild(".git");
                    if (gitFolder != null) {
                        Resource<?> config = gitFolder.getChild("config");
                        if (config != null) {
                            String configText = config.getContents();
                            gitUrlText = GitHelpers.extractGitUrl(configText);
                        }
                    }
                } catch (Exception e) {
                    log.debug("Ignoring missing git folders: " + e, e);
                }
            }
        }
    }
    if (Strings.isNullOrBlank(gitUrlText)) {
        Model mavenModel = getMavenModel(context);
        if (mavenModel != null) {
            Scm scm = mavenModel.getScm();
            if (scm != null) {
                String connection = scm.getConnection();
                if (Strings.isNotBlank(connection)) {
                    gitUrlText = connection;
                }
            }
        }
    }
    if (Strings.isNullOrBlank(gitUrlText)) {
        throw new IllegalArgumentException("Could not find git URL");
    }
    return gitUrlText;
}
 
Example 13
Source File: RepositoriesResource.java    From fabric8-forge with Apache License 2.0 5 votes vote down vote up
protected void enrichRepository(RepositoryDTO repositoryDTO) {
    String repoName = repositoryDTO.getName();
    if (Strings.isNullOrBlank(repoName)) {
        String fullName = repositoryDTO.getFullName();
        if (Strings.isNotBlank(fullName)) {
            String[] split = fullName.split("/", 2);
            if (split != null && split.length > 1) {
                String user = split[0];
                String name = split[1];
                //repositoryDTO.setUser(user);
                repositoryDTO.setName(name);
            }
        }
    }
}
 
Example 14
Source File: MavenHelpers.java    From fabric8-forge with Apache License 2.0 5 votes vote down vote up
/**
 * Returns the maven plugin for the given artifact id or returns null if it cannot be found
 */
public static Plugin findPlugin(List<Plugin> plugins, String artifactId) {
    if (plugins != null) {
        for (Plugin plugin : plugins) {
            String groupId = plugin.getGroupId();
            if (Strings.isNullOrBlank(groupId) || Objects.equal(groupId, mavenPluginsGroupId)) {
                if (Objects.equal(artifactId, plugin.getArtifactId())) {
                    return plugin;
                }
            }
        }
    }
    return null;
}
 
Example 15
Source File: EditFromOrToEndpointXmlStep.java    From fabric8-forge with Apache License 2.0 5 votes vote down vote up
@Override
protected Result addOrEditEndpointXml(FileResource file, String uri, String endpointUrl, String endpointInstanceName, String xml, String lineNumber, String lineNumberEnd) throws Exception {
    String key = parentNode.getKey();
    if (Strings.isNullOrBlank(key)) {
        return Results.fail("Parent node has no key! " + parentNode + " in file " + file.getName());
    }

    Document root = XmlLineNumberParser.parseXml(file.getResourceInputStream());
    if (root != null) {
        Node selectedNode = CamelXmlHelper.findCamelNodeInDocument(root, key);
        if (selectedNode != null) {

            // we need to add after the parent node, so use line number information from the parent
            lineNumber = (String) selectedNode.getUserData(XmlLineNumberParser.LINE_NUMBER);
            lineNumberEnd = (String) selectedNode.getUserData(XmlLineNumberParser.LINE_NUMBER_END);

            if (lineNumber != null && lineNumberEnd != null) {

                // read all the lines
                List<String> lines = LineNumberHelper.readLines(file.getResourceInputStream());

                // the list is 0-based, and line number is 1-based
                int idx = Integer.valueOf(lineNumber) - 1;
                String line = lines.get(idx);

                // replace uri with new value
                line = StringHelper.replaceAll(line, endpointUrl, uri);
                lines.set(idx, line);

                // and save the file back
                String content = LineNumberHelper.linesToString(lines);
                file.setContents(content);
                return Results.success("Updated: " + line.trim());
            }
        }
        return Results.fail("Cannot find Camel node in XML file: " + key);
    } else {
        return Results.fail("Cannot load Camel XML file: " + file.getName());
    }
}
 
Example 16
Source File: ExecutionResult.java    From fabric8-forge with Apache License 2.0 5 votes vote down vote up
public void appendOut(String text) {
    if (Strings.isNullOrBlank(this.output)) {
        this.output = text;
    } else {
        this.output += "\n" + text;
    }
}
 
Example 17
Source File: EnvironmentVariables.java    From fabric8-forge with Apache License 2.0 5 votes vote down vote up
public static String getEnvironmentValue(String envVarName, String defaultValue) {
    String answer = System.getenv(envVarName);
    if (Strings.isNullOrBlank(answer)) {
        answer = defaultValue;
    }
    LOG.info("Using $" + envVarName + " value " + answer);
    return answer;
}
 
Example 18
Source File: ApplyStepExecution.java    From kubernetes-pipeline-plugin with Apache License 2.0 5 votes vote down vote up
protected void addEnvironmentAnnotations(HasMetadata resource) throws AbortException {
    Map<String, String> mapEnvVarToAnnotation = new HashMap<>();
    String resourceName = "environmentAnnotations.properties";
    URL url = getClass().getResource(resourceName);
    if (url == null) {
        throw new AbortException("Cannot find resource `" + resourceName + "` on the classpath!");
    }
    addPropertiesFileToMap(url, mapEnvVarToAnnotation);
    //TODO add this in and support for non java projects
    //addPropertiesFileToMap(this.environmentVariableToAnnotationsFile, mapEnvVarToAnnotation);
    addPropertiesFileToMap(new File("./src/main/fabric8/environmentToAnnotations.properties"), mapEnvVarToAnnotation);
    Map<String, String> annotations = KubernetesHelper.getOrCreateAnnotations(resource);
    Set<Map.Entry<String, String>> entries = mapEnvVarToAnnotation.entrySet();
    for (Map.Entry<String, String> entry : entries) {
        String envVar = entry.getKey();
        String annotation = entry.getValue();
        if (Strings.isNotBlank(envVar) && Strings.isNotBlank(annotation)) {
            String value = Systems.getEnvVarOrSystemProperty(envVar);
            if (Strings.isNullOrBlank(value)) {
                value = tryDefaultAnnotationEnvVar(envVar);
            }
            if (Strings.isNotBlank(value)) {
                String oldValue = annotations.get(annotation);
                if (Strings.isNotBlank(oldValue)) {
                    listener.getLogger().println("Not adding annotation `" + annotation + "` to " + KubernetesHelper.getKind(resource) + " " + KubernetesHelper.getName(resource) + " with value `" + value + "` as there is already an annotation value of `" + oldValue + "`");
                } else {
                    annotations.put(annotation, value);
                }
            }
        }
    }
}
 
Example 19
Source File: DevOpsSave.java    From fabric8-forge with Apache License 2.0 4 votes vote down vote up
private static String getStringAttribute(Map<Object, Object> attributeMap, String name, String defaultValue) {
    String answer = getStringAttribute(attributeMap, name);
    return Strings.isNullOrBlank(answer) ? defaultValue : answer;
}
 
Example 20
Source File: PomValidator.java    From ipaas-quickstarts with Apache License 2.0 4 votes vote down vote up
private void validateVersion(String kind, Element element, Element propertyElement) {
    Element version = DomHelper.firstChild(element, "version");
    if (version != null) {
        String textContent = version.getTextContent();
        if (textContent != null) {
            textContent = textContent.trim();
            if (Strings.isNotBlank(textContent)) {
                String groupId = textContent(DomHelper.firstChild(element, "groupId"));
                String artifactId = textContent(DomHelper.firstChild(element, "artifactId"));

                String coords = groupId + ":" + artifactId;
                if (Strings.isNullOrBlank(groupId)) {
                    coords = artifactId;
                }

                if (!textContent.startsWith("${") || !textContent.endsWith("}")) {
                    warn("" + kind + " " + coords + " does not use a maven property for version; has value: " + textContent);
                } else {
                    String propertyName = textContent.substring(2, textContent.length() - 1);
                    String propertyValue = "????";
                    boolean unknownValue = true;
                    if (propertyElement != null) {
                        Element property = DomHelper.firstChild(propertyElement, propertyName);
                        if (property != null) {
                            propertyValue = property.getTextContent();
                            if (Strings.isNotBlank(propertyValue)) {
                                unknownValue = false;
                            }
                        }
                    }
                    if (!mavenDependenciesProperties.containsKey(propertyName)) {
                        if (!addMavenDependency.containsKey(propertyName) || !unknownValue) {
                            addMavenDependency.put(propertyName, propertyValue);
                        }
                    }
                }
            }
        }
    }

}