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

The following examples show how to use io.fabric8.utils.Strings#isNotBlank() . 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: 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 2
Source File: CommandHelpers.java    From fabric8-forge with Apache License 2.0 6 votes vote down vote up
public static String getResultMessage(Result result) {
    if (result instanceof CompositeResult) {
        CompositeResult compositeResult = (CompositeResult) result;
        List<Result> results = compositeResult.getResults();
        StringBuilder buffer = new StringBuilder();
        for (Result childResult : results) {
            String childResultMessage = getResultMessage(childResult);
            if (Strings.isNotBlank(childResultMessage)) {
                if (buffer.length() > 0) {
                    buffer.append("\n");
                }
                buffer.append(childResultMessage);
            }
        }
        return buffer.toString();
    } else if (result != null) {
        return result.getMessage();
    } else {
        return null;
    }
}
 
Example 3
Source File: BuildConfigs.java    From fabric8-forge with Apache License 2.0 6 votes vote down vote up
public static BuildConfig createBuildConfig(String buildConfigName, Map<String, String> labels, String gitUrlText, String outputImageStreamName, String imageText, String webhookSecret) {
    BuildConfigBuilder buildConfigBuilder = buildConfigBuilder(buildConfigName, labels);
    BuildConfigSpecBuilder specBuilder = new BuildConfigSpecBuilder();

    addBuildParameterGitSource(specBuilder, gitUrlText);
    if (Strings.isNotBlank(outputImageStreamName)) {
        addBuildParameterOutput(specBuilder, outputImageStreamName);
    }
    if (Strings.isNotBlank(imageText)) {
        addBuildConfigSpectiStrategy(specBuilder, imageText);
    }
    if (Strings.isNotBlank(webhookSecret)) {
        addWebHookTriggers(specBuilder, webhookSecret);
    }
    return buildConfigBuilder.withSpec(specBuilder.build()).build();
}
 
Example 4
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 5
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 6
Source File: RepositoryResource.java    From fabric8-forge with Apache License 2.0 6 votes vote down vote up
public CommitInfo createCommitInfo(RevCommit entry) {
    final Date date = GitUtils.getCommitDate(entry);
    PersonIdent authorIdent = entry.getAuthorIdent();
    String author = null;
    String name = null;
    String email = null;
    String avatarUrl = null;
    if (authorIdent != null) {
        author = authorIdent.getName();
        name = authorIdent.getName();
        email = authorIdent.getEmailAddress();

        // lets try default the avatar
        if (Strings.isNotBlank(email)) {
            avatarUrl = getAvatarUrl(email);
        }
    }
    boolean merge = entry.getParentCount() > 1;
    String shortMessage = entry.getShortMessage();
    String sha = entry.getName();
    return new CommitInfo(sha, author, name, email, avatarUrl, date, merge, shortMessage);
}
 
Example 7
Source File: CamelXmlHelper.java    From fabric8-forge with Apache License 2.0 5 votes vote down vote up
public static Node findCamelNodeInDocument(Document root, String key) {
    Node selectedNode = null;
    if (root != null && Strings.isNotBlank(key)) {
        String[] paths = key.split("/");
        NodeList camels = getCamelContextElements(root);
        if (camels != null) {
            Map<String, Integer> rootNodeCounts = new HashMap<>();
            for (int i = 0, size = camels.getLength(); i < size; i++) {
                Node node = camels.item(i);
                boolean first = true;
                for (String path : paths) {
                    if (first) {
                        first = false;
                        String actual = getIdOrIndex(node, rootNodeCounts);
                        if (!Objects.equal(actual, path)) {
                            node = null;
                        }
                    } else {
                        node = findCamelNodeForPath(node, path);
                    }
                    if (node == null) {
                        break;
                    }
                }
                if (node != null) {
                    return node;
                }
            }
        }
    }
    return selectedNode;
}
 
Example 8
Source File: MavenHelpers.java    From fabric8-forge with Apache License 2.0 5 votes vote down vote up
/**
 * Returns true if the dependency was added or false if its already there
 */
public static boolean ensureMavenDependencyAdded(Project project, DependencyInstaller dependencyInstaller, String groupId, String artifactId, String scope) {
    List<Dependency> dependencies = project.getFacet(DependencyFacet.class).getEffectiveDependencies();
    for (Dependency d : dependencies) {
        if (groupId.equals(d.getCoordinate().getGroupId()) && artifactId.equals(d.getCoordinate().getArtifactId())) {
            getLOG().debug("Project already includes:  " + groupId + ":" + artifactId + " for version: " + d.getCoordinate().getVersion());
            return false;
        }
    }

    DependencyBuilder component = DependencyBuilder.create().
            setGroupId(groupId).
            setArtifactId(artifactId);

    if (scope != null) {
        component.setScopeType(scope);
    }

    String version = MavenHelpers.getVersion(groupId, artifactId);
    if (Strings.isNotBlank(version)) {
        component = component.setVersion(version);
        getLOG().debug("Adding pom.xml dependency:  " + groupId + ":" + artifactId + " version: " + version + " scope: " + scope);
    } else {
        getLOG().debug("No version could be found for:  " + groupId + ":" + artifactId);
    }
    dependencyInstaller.install(project, component);
    return true;
}
 
Example 9
Source File: CamelCatalogHelper.java    From fabric8-forge with Apache License 2.0 5 votes vote down vote up
public static DataFormatDto createDataFormatDto(CamelCatalog camelCatalog, String name) {
    // use the camel catalog
    String json = camelCatalog.dataFormatJSonSchema(name);
    if (json == null) {
        return null;
    }

    DataFormatDto dto = new DataFormatDto();
    List<Map<String, String>> data = JSonSchemaHelper.parseJsonSchema("dataformat", json, false);
    for (Map<String, String> row : data) {
        if (row.get("name") != null) {
            dto.setName(row.get("name"));
        } else if (row.get("modelName") != null) {
            dto.setModelName(row.get("modelName"));
        } else if (row.get("title") != null) {
            dto.setTitle(row.get("title"));
        } else if (row.get("description") != null) {
            dto.setDescription(row.get("description"));
        } else if (row.get("label") != null) {
            String labelText = row.get("label");
            if (Strings.isNotBlank(labelText)) {
                dto.setTags(labelText.split(","));
            }
        } else if (row.get("javaType") != null) {
            dto.setJavaType(row.get("javaType"));
        } else if (row.get("modelJavaType") != null) {
            dto.setModelJavaType(row.get("modelJavaType"));
        } else if (row.get("groupId") != null) {
            dto.setGroupId(row.get("groupId"));
        } else if (row.get("artifactId") != null) {
            dto.setArtifactId(row.get("artifactId"));
        } else if (row.get("version") != null) {
            dto.setVersion(row.get("version"));
        }
    }
    return dto;
}
 
Example 10
Source File: PopulateMavenRepositoryTest.java    From fabric8-forge with Apache License 2.0 5 votes vote down vote up
protected void createProjects(Furnace furnace) throws Exception {
    File projectsOutputFolder = new File(baseDir, "target/createdProjects");
    Files.recursiveDelete(projectsOutputFolder);

    ProjectGenerator generator = new ProjectGenerator(furnace, projectsOutputFolder, localMavenRepo);
    File archetypeJar = generator.getArtifactJar("io.fabric8.archetypes", "archetypes-catalog", ProjectGenerator.FABRIC8_ARCHETYPE_VERSION);

    List<String> archetypes = getArchetypesFromJar(archetypeJar);
    assertThat(archetypes).describedAs("Archetypes to create").isNotEmpty();

    String testArchetype = System.getProperty(TEST_ARCHETYPE_SYSTEM_PROPERTY, "");
    if (Strings.isNotBlank(testArchetype)) {
        LOG.info("Due to system property: '" + TEST_ARCHETYPE_SYSTEM_PROPERTY + "' we will just run the test on archetype: " + testArchetype);
        generator.createProjectFromArchetype(testArchetype);
    } else {
        for (String archetype : archetypes) {
            // TODO fix failing archetypes...
            if (!archetype.startsWith("jboss-fuse-") && !archetype.startsWith("swarm")) {
                generator.createProjectFromArchetype(archetype);
            }
        }
    }

    removeSnapshotFabric8Artifacts();


    List<File> failedFolders = generator.getFailedFolders();
    if (failedFolders.size() > 0) {
        LOG.error("Failed to build all the projects!!!");
        for (File failedFolder : failedFolders) {
            LOG.error("Failed to build project: " + failedFolder.getName());
        }
    }
}
 
Example 11
Source File: ApplyStepExecution.java    From kubernetes-pipeline-plugin with Apache License 2.0 5 votes vote down vote up
private void addDeploymentVersion(Map<String, String> deploymentVersions, HasMetadata resource) {
    String name = KubernetesHelper.getName(resource);
    String version = KubernetesHelper.getLabels(resource).get("version");
    // TODO if there is no version label could we find it from somewhere else?
    if (Strings.isNotBlank(version)) {
        deploymentVersions.put(name, version);
    } else {
        listener.getLogger().println("No version label for  " + KubernetesHelper.getKind(resource) + " "
                + KubernetesHelper.getName(resource) + " in namespace "
                + KubernetesHelper.getNamespace(resource));
    }
}
 
Example 12
Source File: FileDTO.java    From fabric8-forge with Apache License 2.0 5 votes vote down vote up
protected static String joinPaths(String parentPath, String name) {
    String path = name;
    if (Strings.isNotBlank(parentPath)) {
        String separator = path.endsWith("/") || name.startsWith("/") ? "" : "/";
        path = parentPath + separator + name;
    }
    return path;
}
 
Example 13
Source File: ApplyStepExecution.java    From kubernetes-pipeline-plugin with Apache License 2.0 5 votes vote down vote up
/**
 * Appends a CLI argument if the value is not null or empty
 */
private void appendCliArgument(StringBuilder builder, String arg, Object value) {
    if (value != null) {
        String text = value.toString();
        if (Strings.isNotBlank(text)) {
            builder.append(" ");
            builder.append(arg);
            builder.append(" ");
            builder.append(text);
        }
    }
}
 
Example 14
Source File: CamelCatalogHelper.java    From fabric8-forge with Apache License 2.0 5 votes vote down vote up
public static ComponentDto createComponentDto(CamelCatalog camelCatalog, String scheme) {
    // use the camel catalog
    String json = camelCatalog.componentJSonSchema(scheme);
    if (json == null) {
        return null;
    }

    ComponentDto dto = new ComponentDto();
    List<Map<String, String>> data = JSonSchemaHelper.parseJsonSchema("component", json, false);
    for (Map<String, String> row : data) {
        if (row.get("scheme") != null) {
            dto.setScheme(row.get("scheme"));
        } else if (row.get("syntax") != null) {
            dto.setSyntax(row.get("syntax"));
        } else if (row.get("title") != null) {
            dto.setTitle(row.get("title"));
        } else if (row.get("description") != null) {
            dto.setDescription(row.get("description"));
        } else if (row.get("label") != null) {
            String labelText = row.get("label");
            if (Strings.isNotBlank(labelText)) {
                dto.setTags(labelText.split(","));
            }
        } else if (row.get("consumerOnly") != null) {
            dto.setConsumerOnly("true".equals(row.get("consumerOnly")));
        } else if (row.get("producerOnly") != null) {
            dto.setProducerOnly("true".equals(row.get("producerOnly")));
        } else if (row.get("javaType") != null) {
            dto.setJavaType(row.get("javaType"));
        } else if (row.get("groupId") != null) {
            dto.setGroupId(row.get("groupId"));
        } else if (row.get("artifactId") != null) {
            dto.setArtifactId(row.get("artifactId"));
        } else if (row.get("version") != null) {
            dto.setVersion(row.get("version"));
        }
    }
    return dto;
}
 
Example 15
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 16
Source File: OutputFormatHelper.java    From fabric8-forge with Apache License 2.0 5 votes vote down vote up
public static void addTableTextOutput(StringBuilder buffer, String title, TablePrinter table) {
    if (Strings.isNotBlank(title)) {
        buffer.append(title);
        buffer.append(":\n\n");
    }
    buffer.append(table.asText());
    buffer.append("\n");
}
 
Example 17
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 18
Source File: CamelCatalogHelper.java    From fabric8-forge with Apache License 2.0 4 votes vote down vote up
public static LanguageDto createLanguageDto(CamelCatalog camelCatalog, String name) {
    // use the camel catalog

    // TODO: 2.17.3/2.18 method is bean language
    if ("method".equals(name)) {
        name = "bean";
    }

    String json = camelCatalog.languageJSonSchema(name);
    if (json == null) {
        return null;
    }

    LanguageDto dto = new LanguageDto();
    List<Map<String, String>> data = JSonSchemaHelper.parseJsonSchema("language", json, false);
    for (Map<String, String> row : data) {
        if (row.get("name") != null) {
            dto.setName(row.get("name"));
        } else if (row.get("modelName") != null) {
            dto.setModelName(row.get("modelName"));
        } else if (row.get("title") != null) {
            dto.setTitle(row.get("title"));
        } else if (row.get("description") != null) {
            dto.setDescription(row.get("description"));
        } else if (row.get("label") != null) {
            String labelText = row.get("label");
            if (Strings.isNotBlank(labelText)) {
                dto.setTags(labelText.split(","));
            }
        } else if (row.get("javaType") != null) {
            dto.setJavaType(row.get("javaType"));
        } else if (row.get("modelJavaType") != null) {
            dto.setModelJavaType(row.get("modelJavaType"));
        } else if (row.get("groupId") != null) {
            dto.setGroupId(row.get("groupId"));
        } else if (row.get("artifactId") != null) {
            dto.setArtifactId(row.get("artifactId"));
        } else if (row.get("version") != null) {
            dto.setVersion(row.get("version"));
        }
    }
    return dto;
}
 
Example 19
Source File: ArchetypeTest.java    From ipaas-quickstarts with Apache License 2.0 4 votes vote down vote up
@AfterClass
public static void afterAll() throws Exception {
    if (failed) {
        return;
    }
    // now let invoke the projects
    final int[] resultPointer = new int[1];
    List<String> failedProjects = new ArrayList<>();
    List<String> successfulProjects = new ArrayList<>();

    for (final String outDir : outDirs) {
        // thread locals are evil (I'm talking to you - org.codehaus.plexus.DefaultPlexusContainer#lookupRealm!)
        Thread t = new Thread(new Runnable() {
            @Override
            public void run() {
                LOG.info("Invoking projects in " + outDir);
                System.setProperty("maven.multiModuleProjectDirectory", "$M2_HOME");
                // Dmaven.multiModuleProjectDirectory
                String[] args = {"-U", "clean", "package"};
                boolean useArq = Objects.equals(arqTesting, "true");
                if (useArq) {
                    args = new String[]{"clean", "install", "-U"};
                    String fabric8Mode = System.getProperty("fabric8.mode", "");
                    if (Strings.isNotBlank(fabric8Mode) && KubernetesHelper.isOpenShift(new DefaultKubernetesClient())) {
                        // lets add a workaround for a lack of discovery OOTB with fabric8-maven-plugin
                        args = new String[]{"clean", "install", "-U", "-Dfabric8.mode=" + fabric8Mode};
                    }
                }
                File logFile = new File(new File(outDir), "output.log");
                logFile.delete();
                resultPointer[0] = invokeMaven(args, outDir, logFile);
                LOG.info("result: " + resultPointer[0]);

                if (useArq && resultPointer[0] == 0) {
                    args = new String[]{"failsafe:integration-test", "failsafe:verify"};
                    LOG.info("Now trying to run the integration tests via: mvn " + Strings.join(" ", args));
                    resultPointer[0] = invokeMaven(args, outDir, logFile);
                    LOG.info("result: " + resultPointer[0]);
                }
            }
        });
        t.start();
        t.join();
        String projectName = new File(outDir).getName();
        if (resultPointer[0] != 0) {
            failedProjects.add(projectName);
            LOG.error("Failed project: " + projectName);
        } else {
            successfulProjects.add(projectName);
            LOG.info("Successful project: " + projectName);
        }
    }

    for (String successful : successfulProjects) {
        LOG.info("Successful project: " + successful);
    }
    for (String failedProject : failedProjects) {
        LOG.error("Failed project: " + failedProject);
    }
    assertThat(failedProjects).describedAs("Projects failed: " + failedProjects).isEmpty();
}
 
Example 20
Source File: XmlRouteParser.java    From fabric8-forge with Apache License 2.0 4 votes vote down vote up
public static void parseXmlRouteEndpoints(InputStream xml, String baseDir, String fullyQualifiedFileName,
                                          List<CamelEndpointDetails> endpoints) throws Exception {

    // find all the endpoints (currently only <endpoint> and within <route>)
    // try parse it as dom
    Document dom = null;
    try {
        dom = XmlLineNumberParser.parseXml(xml);
    } catch (Exception e) {
        // ignore as the xml file may not be valid at this point
    }
    if (dom != null) {
        List<Node> nodes = CamelXmlHelper.findAllEndpoints(dom);
        for (Node node : nodes) {
            String uri = getSafeAttribute(node, "uri");
            if (uri != null) {
                // trim and remove whitespace noise
                uri = trimEndpointUri(uri);
            }
            if (Strings.isNotBlank(uri)) {
                String id = getSafeAttribute(node, "id");
                String lineNumber = (String) node.getUserData(XmlLineNumberParser.LINE_NUMBER);
                String lineNumberEnd = (String) node.getUserData(XmlLineNumberParser.LINE_NUMBER_END);

                // we only want the relative dir name from the resource directory, eg META-INF/spring/foo.xml
                String fileName = fullyQualifiedFileName;
                if (fileName.startsWith(baseDir)) {
                    fileName = fileName.substring(baseDir.length() + 1);
                }

                boolean consumerOnly = false;
                boolean producerOnly = false;
                String nodeName = node.getNodeName();
                if ("from".equals(nodeName) || "pollEnrich".equals(nodeName)) {
                    consumerOnly = true;
                } else if ("to".equals(nodeName) || "enrich".equals(nodeName) || "wireTap".equals(nodeName)) {
                    producerOnly = true;
                }

                CamelEndpointDetails detail = new CamelEndpointDetails();
                detail.setFileName(fileName);
                detail.setLineNumber(lineNumber);
                detail.setLineNumberEnd(lineNumberEnd);
                detail.setEndpointInstance(id);
                detail.setEndpointUri(uri);
                detail.setEndpointComponentName(endpointComponentName(uri));
                detail.setConsumerOnly(consumerOnly);
                detail.setProducerOnly(producerOnly);
                endpoints.add(detail);
            }
        }
    }
}