Example usage for java.lang String join

List of usage examples for java.lang String join

Introduction

In this page you can find the example usage for java.lang String join.

Prototype

public static String join(CharSequence delimiter, Iterable<? extends CharSequence> elements) 

Source Link

Document

Returns a new String composed of copies of the CharSequence elements joined together with a copy of the specified delimiter .

Usage

From source file:com.github.lukaszbudnik.dqueue.QueueClientImpl.java

@Override
public Future<UUID> publish(Item item) {
    if (item.getStartTime() == null || item.getStartTime().version() != 1) {
        throw new IllegalArgumentException("Start time must be a valid UUID version 1 identifier");
    }// w w  w .  j  a v  a  2  s.c o  m
    if (item.getContents() == null) {
        throw new IllegalArgumentException("Contents must not be null");
    }
    if (item.getFilters() == null) {
        throw new IllegalArgumentException(
                "Filters cannot be null, if no filters are to be used pass an empty map");
    }

    Future<UUID> publishResult = executorService.submit(() -> {
        String filterNames;
        if (item.getFilters().isEmpty()) {
            filterNames = NO_FILTERS;
        } else {
            filterNames = String.join("_", item.getFilters().keySet());
        }
        String wholeOperationMetricName = "dqueue.publish." + filterNames + ".whole.timer";
        Optional<Timer.Context> publishTimer = Optional.ofNullable(metricRegistry)
                .map(m -> m.timer(wholeOperationMetricName).time());

        try {
            String tableName = createTableIfNotExists("publish", filterNames, item.getFilters());

            QueryBuilder queryBuilder = new QueryBuilder(cluster);
            DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
            String primaryKey = df.format(new Date(UUIDs.unixTimestamp(item.getStartTime())));
            final Insert insert = queryBuilder.insertInto(cassandraKeyspace, tableName).value("key", primaryKey)
                    .value("start_time", item.getStartTime()).value("contents", item.getContents());

            if (item.getFilters() != null && !item.getFilters().isEmpty()) {
                for (String key : item.getFilters().keySet()) {
                    insert.value(key, item.getFilters().get(key));
                }
            }

            String cassandraInsertMetricName = "dqueue.publish." + filterNames + ".cassandraInsert.timer";
            executeAndMeasureTime(() -> session.executeAsync(insert).getUninterruptibly(),
                    cassandraInsertMetricName);

            return item.getStartTime();
        } finally {
            publishTimer.ifPresent(Timer.Context::stop);
        }
    });

    return publishResult;
}

From source file:edu.umd.umiacs.clip.tools.classifier.LibSVMUtils.java

public static List<String> applyScalingModel(Map<Integer, Pair<Float, Float>> model, List<String> examples) {
    return examples.stream().map(LibSVMUtils::split)
            .map(triple -> triple.getLeft() + String.join(" ",
                    triple.getMiddle().stream()
                            .map(pair -> Pair.of(pair.getLeft(),
                                    !model.containsKey(pair.getLeft()) ? 1f
                                            : ((pair.getRight() - model.get(pair.getLeft()).getLeft())
                                                    / model.get(pair.getLeft()).getRight())))
                            .//  w  ww. j ava2 s  .com
                            //map(pair -> Pair.of(pair.getKey(), 2 * pair.getRight() - 1)).
                            filter(pair -> pair.getValue() != 0f)
                            .map(pair -> pair.getLeft() + ":" + pair.getRight()).collect(toList()))
                    + triple.getRight())
            .collect(toList());
}

From source file:MSUmpire.Utility.ExportTable.java

private void ProteinLevelExport(int TopNPep, int TopNFrag, float Freq) throws IOException {
    FileWriter proWriter = new FileWriter(WorkFolder + "ProtSummary_" + DateTimeTag.GetTag() + ".xls");
    FileWriter pepWriter = new FileWriter(WorkFolder + "PeptideSummary_" + DateTimeTag.GetTag() + ".xls");
    FileWriter NOWriter = new FileWriter(WorkFolder + "IDNoSummary_" + DateTimeTag.GetTag() + ".xls");
    FileWriter fragWriter = new FileWriter(WorkFolder + "FragSummary_" + DateTimeTag.GetTag() + ".xls");
    //Fragment Summary//////////////////////////////////////////
    for (LCMSID IDsummary : FileList) {
        HashMap<String, FragmentPeak> FragMap = IDSummaryFragments
                .get(FilenameUtils.getBaseName(IDsummary.mzXMLFileName));
        if (FragMap == null) {
            Logger.getRootLogger().error(
                    "Cannot find fragment map for " + FilenameUtils.getBaseName(IDsummary.mzXMLFileName));
            Logger.getRootLogger().debug("Printing all fragment maps");
            for (String key : FragMap.keySet()) {
                Logger.getRootLogger().debug(key);
            }// www  .  j  a va  2  s  .  c o  m
        }
        for (String key : CombineProtID.ProteinList.keySet()) {
            if (IDsummary.ProteinList.containsKey(key)) {
                ProtID protein = IDsummary.ProteinList.get(key);
                for (PepIonID pep : protein.PeptideID.values()) {
                    for (FragmentPeak frag : pep.FragmentPeaks) {
                        final String mapkey =
                                // key + ";" + pep.GetKey() + ";" + frag.IonType;
                                key + ";" + pep.GetKey() + ";" + frag.IonType + ";+" + frag.Charge;
                        //                            ProteinFragMap.putIfAbsent(mapkey, frag.FragMZ);// needs Java 8
                        if (!ProteinFragMap.containsKey(mapkey))
                            ProteinFragMap.put(mapkey, frag.FragMZ);
                        frag.Prob1 = pep.MaxProbability;
                        frag.Prob2 = pep.TargetedProbability();
                        frag.RT = pep.PeakRT;
                        FragMap.put(mapkey, frag);
                    }
                }
            }
        }
    }

    NOWriter.write(
            "File\tNo. Proteins\tNo. peptide ions (Spec-centric)\tNo. peptide ions (Pep-centric)\tNo. proein assoc. ions\n");

    //ProteinSummary/////////////
    proWriter.write("Protein Key\t");
    proWriter.write("Selected_peptides\t");
    for (LCMSID IDSummary : FileList) {
        NOWriter.write(FilenameUtils.getBaseName(IDSummary.mzXMLFileName) + "\t" + IDSummary.ProteinList.size()
                + "\t" + IDSummary.GetPepIonList().size() + "\t" + IDSummary.GetMappedPepIonList().size() + "\t"
                + IDSummary.AssignedPepIonList.size() + "\n");
        String file = FilenameUtils.getBaseName(IDSummary.mzXMLFileName);
        proWriter.write(file + "_Prob\t" + file + "_Peptides\t" + file + "_PSMs\t" + file + "_MS1_iBAQ\t" + file
                + "_Top" + TopNPep + "pep/Top" + TopNFrag + "fra ,Freq>" + Freq + "\t");
    }
    proWriter.write("\n");

    NOWriter.close();
    if (CombineProtID != null) {
        for (String key : CombineProtID.ProteinList.keySet()) {
            proWriter.write(key + "\t");
            for (final LCMSID IDsummary : FileList) {
                if (IDsummary.ProteinList.containsKey(key)) {
                    final ProtID protein = IDsummary.ProteinList.get(key);
                    proWriter.write(String.join("|", fragselection.TopPeps.get(protein.getAccNo())));
                    break;
                }
            }
            proWriter.write("\t");
            for (LCMSID IDsummary : FileList) {
                if (IDsummary.ProteinList.containsKey(key)) {
                    ProtID protein = IDsummary.ProteinList.get(key);
                    proWriter.write(protein.Probability + "\t" + protein.PeptideID.size() + "\t"
                            + protein.GetSpectralCount() + "\t" + protein.GetAbundanceByMS1_IBAQ() + "\t"
                            + protein.GetAbundanceByTopCorrFragAcrossSample(
                                    fragselection.TopPeps.get(protein.getAccNo()), fragselection.TopFrags)
                            + "\t");
                } else {
                    proWriter.write("\t\t\t\t\t");
                }
            }
            proWriter.write("\n");
        }
        proWriter.close();
    }

    fragWriter.write("Fragment Key\tProtein\tPeptide\tFragment\tFragMz\t");
    for (LCMSID IDSummary : FileList) {
        String file = FilenameUtils.getBaseName(IDSummary.mzXMLFileName);
        fragWriter.write(file + "_RT\t" + file + "_Spec_Centric_Prob\t" + file + "_Pep_Centric_Prob\t" + file
                + "_Intensity\t" + file + "_Corr\t" + file + "_PPM\t");
    }
    fragWriter.write("\n");
    for (final Map.Entry<String, Float> ent : new java.util.TreeMap<>(ProteinFragMap).entrySet()) {
        final String key = ent.getKey();
        fragWriter.write(key + "\t" + key.split(";")[0] + "\t" + key.split(";")[1] + "\t" + key.split(";")[2]
                + key.split(";")[3] + "\t" + ent.getValue() + "\t");
        for (LCMSID IDSummary : FileList) {
            if (IDSummaryFragments.get(FilenameUtils.getBaseName(IDSummary.mzXMLFileName)).containsKey(key)) {
                FragmentPeak fragmentPeak = IDSummaryFragments
                        .get(FilenameUtils.getBaseName(IDSummary.mzXMLFileName)).get(key);
                fragWriter.write(fragmentPeak.RT + "\t" + fragmentPeak.Prob1 + "\t" + fragmentPeak.Prob2 + "\t"
                        + fragmentPeak.intensity + "\t" + fragmentPeak.corr + "\t" + fragmentPeak.ppm + "\t");
            } else {
                fragWriter.write("\t\t\t\t\t\t");
            }
        }
        fragWriter.write("\n");
    }
    fragWriter.close();

    ////PepSummary///////////////////////////////////
    for (LCMSID IDsummary : FileList) {
        HashMap<String, FragmentPeak> FragMap = new HashMap<>();
        IDSummaryFragments.put(FilenameUtils.getBaseName(IDsummary.mzXMLFileName), FragMap);

        for (String key : IDsummary.GetPepIonList().keySet()) {
            if (!IdentifiedPepMap.contains(key)) {
                IdentifiedPepMap.add(key);
            }
        }
        for (String key : IDsummary.GetMappedPepIonList().keySet()) {
            if (!IdentifiedPepMap.contains(key)) {
                IdentifiedPepMap.add(key);
            }
        }
    }

    pepWriter.write("Peptide Key\tSequence\tModSeq\tProteins\tmz\tCharge\tMaxProb\t");
    pepWriter.write("Selected_fragments\t");
    for (LCMSID IDSummary : FileList) {
        String file = FilenameUtils.getBaseName(IDSummary.mzXMLFileName);
        pepWriter.write(file + "_Spec_Centric_Prob\t" + file + "_Pep_Centric_Prob\t" + file + "_PSMs\t" + file
                + "_RT\t" + file + "_MS1\t" + file + "_Top" + TopNFrag + "fra\t");
    }
    pepWriter.write("\n");

    for (String key : IdentifiedPepMap) {
        pepWriter.write(key + "\t");
        float maxprob = 0f;
        boolean output = false;
        for (LCMSID IDSummary : FileList) {
            if (IDSummary.GetPepIonList().containsKey(key)) {
                PepIonID peptide = IDSummary.GetPepIonList().get(key);
                if (!output) {
                    pepWriter.write(
                            peptide.Sequence + "\t" + peptide.ModSequence + "\t" + peptide.ParentProteins()
                                    + "\t" + peptide.ObservedMz + "\t" + peptide.Charge + "\t");
                    output = true;
                }
                if (peptide.MaxProbability > maxprob) {
                    maxprob = peptide.MaxProbability;
                }
            }
            if (IDSummary.GetMappedPepIonList().containsKey(key)) {
                PepIonID peptide = IDSummary.GetMappedPepIonList().get(key);
                if (!output) {
                    pepWriter.write(
                            peptide.Sequence + "\t" + peptide.ModSequence + "\t" + peptide.ParentProteins()
                                    + "\t" + peptide.ObservedMz + "\t" + peptide.Charge + "\t");
                    output = true;
                }
                if (peptide.TargetedProbability() > maxprob) {
                    maxprob = peptide.TargetedProbability();
                }
            }
        }
        pepWriter.write(maxprob + "\t");

        for (final LCMSID IDSummary : FileList) {
            if (IDSummary.GetPepIonList().containsKey(key)) {
                final PepIonID peptide = IDSummary.GetPepIonList().get(key);
                pepWriter.write(String.join("|", fragselection.TopFrags.get(peptide.GetKey())));
                break;
            } else if (IDSummary.GetMappedPepIonList().containsKey(key)) {
                final PepIonID peptide = IDSummary.GetMappedPepIonList().get(key);
                pepWriter.write(String.join("|", fragselection.TopFrags.get(peptide.GetKey())));
                break;
            } else {
            }
        }
        pepWriter.write("\t");

        for (LCMSID IDSummary : FileList) {
            if (IDSummary.GetPepIonList().containsKey(key)) {
                PepIonID peptide = IDSummary.GetPepIonList().get(key);
                pepWriter.write(peptide.MaxProbability + "\t-1\t" + peptide.GetSpectralCount() + "\t"
                        + peptide.PeakRT + "\t" + peptide.PeakHeight[0] + "\t"
                        + peptide.GetPepAbundanceByTopCorrFragAcrossSample(
                                fragselection.TopFrags.get(peptide.GetKey()))
                        + "\t");
            } else if (IDSummary.GetMappedPepIonList().containsKey(key)) {
                PepIonID peptide = IDSummary.GetMappedPepIonList().get(key);
                pepWriter.write("-1\t" + peptide.TargetedProbability() + "\t" + peptide.GetSpectralCount()
                        + "\t" + peptide.PeakRT + "\t" + peptide.PeakHeight[0] + "\t"
                        + peptide.GetPepAbundanceByTopCorrFragAcrossSample(
                                fragselection.TopFrags.get(peptide.GetKey()))
                        + "\t");
            } else {
                pepWriter.write("\t\t\t\t\t\t");
            }
        }
        pepWriter.write("\n");
    }
    pepWriter.close();
}

From source file:com.vmware.admiral.compute.container.ShellContainerExecutorService.java

public static String[] buildComplexCommand(String... commands) {
    String[] commandString = new String[3];
    commandString[0] = "sh";
    commandString[1] = "-c";
    commandString[2] = String.join(" && ", commands);

    return commandString;
}

From source file:org.kitodo.sruimport.SRUImport.java

private String createSearchFieldString(LinkedHashMap<String, String> searchFields)
        throws UnsupportedEncodingException {
    List<String> searchOperands = searchFields.entrySet().stream()
            .map(entry -> entry.getKey() + equalsOperand + entry.getValue()).collect(Collectors.toList());
    return URLEncoder.encode(String.join(" AND ", searchOperands), StandardCharsets.UTF_8.displayName());
}

From source file:com.netflix.spinnaker.clouddriver.kubernetes.v2.op.manifest.KubernetesDeployManifestOperation.java

@Override
public OperationResult operate(List _unused) {
    getTask().updateStatus(OP_NAME, "Beginning deployment of manifest...");

    List<KubernetesManifest> inputManifests = description.getManifests();
    List<KubernetesManifest> deployManifests = new ArrayList<>();
    if (inputManifests == null || inputManifests.isEmpty()) {
        log.warn("Relying on deprecated single manifest input: " + description.getManifest());
        inputManifests = Collections.singletonList(description.getManifest());
    }/* w ww. j  a v  a2 s  .c  o m*/

    inputManifests = inputManifests.stream().filter(Objects::nonNull).collect(Collectors.toList());

    List<Artifact> requiredArtifacts = description.getRequiredArtifacts();
    if (requiredArtifacts == null) {
        requiredArtifacts = new ArrayList<>();
    }

    List<Artifact> optionalArtifacts = description.getOptionalArtifacts();
    if (optionalArtifacts == null) {
        optionalArtifacts = new ArrayList<>();
    }

    List<Artifact> artifacts = new ArrayList<>();
    artifacts.addAll(requiredArtifacts);
    artifacts.addAll(optionalArtifacts);

    Set<Artifact> boundArtifacts = new HashSet<>();

    for (KubernetesManifest manifest : inputManifests) {
        if (StringUtils.isEmpty(manifest.getNamespace()) && manifest.getKind().isNamespaced()) {
            manifest.setNamespace(credentials.getDefaultNamespace());
        }

        KubernetesResourceProperties properties = findResourceProperties(manifest);
        if (properties == null) {
            throw new IllegalArgumentException("Unsupported Kubernetes object kind '"
                    + manifest.getKind().toString() + "', unable to continue.");
        }
        KubernetesHandler deployer = properties.getHandler();
        if (deployer == null) {
            throw new IllegalArgumentException("No deployer available for Kubernetes object kind '"
                    + manifest.getKind().toString() + "', unable to continue.");
        }

        getTask().updateStatus(OP_NAME,
                "Swapping out artifacts in " + manifest.getFullResourceName() + " from context...");
        ReplaceResult replaceResult = deployer.replaceArtifacts(manifest, artifacts);
        deployManifests.add(replaceResult.getManifest());
        boundArtifacts.addAll(replaceResult.getBoundArtifacts());
    }

    Set<Artifact> unboundArtifacts = new HashSet<>(requiredArtifacts);
    unboundArtifacts.removeAll(boundArtifacts);

    getTask().updateStatus(OP_NAME, "Checking if all requested artifacts were bound...");
    if (!unboundArtifacts.isEmpty()) {
        throw new IllegalArgumentException("The following artifacts could not be bound: '" + unboundArtifacts
                + "' . Failing the stage as this is likely a configuration error.");
    }

    getTask().updateStatus(OP_NAME, "Sorting manifests by priority...");
    deployManifests.sort(Comparator.comparingInt(m -> findResourceProperties(m).getHandler().deployPriority()));
    getTask().updateStatus(OP_NAME, "Deploy order is: " + String.join(", ", deployManifests.stream()
            .map(KubernetesManifest::getFullResourceName).collect(Collectors.toList())));

    OperationResult result = new OperationResult();
    for (KubernetesManifest manifest : deployManifests) {
        KubernetesResourceProperties properties = findResourceProperties(manifest);
        boolean versioned = description.getVersioned() == null ? properties.isVersioned()
                : description.getVersioned();
        KubernetesArtifactConverter converter = versioned ? properties.getVersionedConverter()
                : properties.getUnversionedConverter();
        KubernetesHandler deployer = properties.getHandler();

        Moniker moniker = description.getMoniker();
        Artifact artifact = converter.toArtifact(provider, manifest);

        getTask().updateStatus(OP_NAME, "Annotating manifest " + manifest.getFullResourceName()
                + " with artifact, relationships & moniker...");
        KubernetesManifestAnnotater.annotateManifest(manifest, artifact);

        namer.applyMoniker(manifest, moniker);
        manifest.setName(converter.getDeployedName(artifact));

        getTask().updateStatus(OP_NAME,
                "Swapping out artifacts in " + manifest.getFullResourceName() + " from other deployments...");
        ReplaceResult replaceResult = deployer.replaceArtifacts(manifest,
                new ArrayList<>(result.getCreatedArtifacts()));
        boundArtifacts.addAll(replaceResult.getBoundArtifacts());
        manifest = replaceResult.getManifest();

        getTask().updateStatus(OP_NAME,
                "Submitting manifest " + manifest.getFullResourceName() + " to kubernetes master...");
        result.merge(deployer.deploy(credentials, manifest));

        result.getCreatedArtifacts().add(artifact);
    }

    result.getBoundArtifacts().addAll(boundArtifacts);
    result.removeSensitiveKeys(registry, accountName);
    return result;
}

From source file:net.maritimecloud.identityregistry.keycloak.spi.eventprovider.McEventListenerProvider.java

public void onEvent(Event event) {
    // We only worry about IDENTITY_PROVIDER_LOGIN events.
    if (event.getType() != EventType.LOGIN && event.getType() != EventType.IDENTITY_PROVIDER_LOGIN) {
        return;//from  w w w. j  a v  a2  s  .c o  m
    }
    StringBuilder sb = new StringBuilder();

    sb.append("type=");
    sb.append(event.getType());
    sb.append(", realmId=");
    sb.append(event.getRealmId());
    sb.append(", clientId=");
    sb.append(event.getClientId());
    sb.append(", userId=");
    sb.append(event.getUserId());
    sb.append(", ipAddress=");
    sb.append(event.getIpAddress());

    if (event.getError() != null) {
        sb.append(", error=");
        sb.append(event.getError());
    }
    String identityProvider = null;
    if (event.getDetails() != null) {
        for (Map.Entry<String, String> e : event.getDetails().entrySet()) {
            if ("identity_provider".equals(e.getKey())) {
                identityProvider = e.getValue();
            }
            sb.append(", ");
            sb.append(e.getKey());
            if (e.getValue() == null || e.getValue().indexOf(' ') == -1) {
                sb.append("=");
                sb.append(e.getValue());
            } else {
                sb.append("='");
                sb.append(e.getValue());
                sb.append("'");
            }
        }
    }
    log.info("event info: " + sb.toString());

    // Only users coming from an identity provider is sync'ed.
    if (identityProvider == null) {
        log.info("no identity provider found for this user, so sync skipped!");
        return;
    }

    // we skip certain identity providers
    if (Arrays.binarySearch(idpNotToSync, identityProvider) < 0) {
        log.info("this identity provider is setup not to be sync'ed, so sync skipped!");
        return;
    }

    if (event.getRealmId() != null && event.getUserId() != null) {
        RealmModel realm = session.realms().getRealm(event.getRealmId());
        UserModel user = session.users().getUserById(event.getUserId(), realm);
        User mcUser = new User();
        mcUser.setEmail(user.getEmail());
        mcUser.setFirstName(user.getFirstName());
        mcUser.setLastName(user.getLastName());
        String orgShortName = null;
        if (event.getType() == EventType.IDENTITY_PROVIDER_LOGIN) {
            // The username should be in the form "<org-shortname>.<user-unique-org-id>"
            String[] splitName = user.getUsername().split(".", 1);
            if (splitName.length == 2) {
                orgShortName = splitName[0].toUpperCase();
                mcUser.setUserOrgId(splitName[1]);
            } else {
                return;
            }
        } else {
            // TODO: This is for testing only!! Remove again!! 
            List<String> orgList = user.getAttributes().get("org");
            if (orgList != null && orgList.size() > 0) {
                orgShortName = orgList.get(0);
            }
            mcUser.setUserOrgId(user.getUsername());
        }
        if (orgShortName == null || orgShortName.isEmpty()) {
            log.warn("No org shortname found, skipping user sync");
            return;
        }
        List<String> permissionsList = user.getAttributes().get("permissions");
        if (permissionsList != null && permissionsList.size() > 0) {
            mcUser.setPermissions(String.join(", ", permissionsList));
        }

        List<String> mrnList = user.getAttributes().get("mrn");
        if (mrnList != null && mrnList.size() > 0) {
            mcUser.setMrn(String.join(", ", mrnList));
        }

        if (user != null && user.getAttributes() != null) {
            for (Map.Entry<String, List<String>> e : user.getAttributes().entrySet()) {
                log.info("user attr: " + e.getKey() + ", value: " + String.join(", ", e.getValue()));
            }
        }
        sendUserUpdate(mcUser, orgShortName);
    }
}

From source file:com.oneops.boo.BooConfigInterpolator.java

private String file(String path, boolean keepNewlines, int numWhitespaceToBePrepend) {
    if (path.startsWith("~")) {
        path = path.replace("~", HOME);
    } else if (path.startsWith("@")) {
        path = path.substring(1);//from  ww  w.  ja v a2  s  .  co m
    } else if (path.startsWith("./")) {
        path = path.replace("./", String.format("%s%s", WORK, File.separator));
    }
    try {
        final String contents = keepNewlines ? readFileToString(new File(path))
                : FileUtils.readFileToString(new File(path), StandardCharsets.UTF_8);
        if (numWhitespaceToBePrepend > 0) {
            final String lines[] = contents.split("\\r?\\n");
            final StringBuilder sb = new StringBuilder();
            final String whitespaces = String.join("", Collections.nCopies(numWhitespaceToBePrepend, " "));
            boolean isFirstLineVisited = false;
            for (String line : lines) {
                if (isFirstLineVisited) {
                    sb.append(whitespaces).append(line).append('\n');
                } else {
                    sb.append(line).append('\n');
                    isFirstLineVisited = true;
                }
            }
            return sb.toString();
        } else {
            return contents;
        }

    } catch (IOException e) {
        // Content that might be required for the compute to function may be ommitted so just fail
        // fast. If it's an ssh public key that is meant to be injected and it doesn't work it will result
        // in a compute you can't log in to.
        throw new RuntimeException(String.format("%s cannot be found or cannot be read.", path));
    }
}

From source file:com.searchcode.app.service.CodeMatcher.java

/**
 * If changing anything in here be wary of performance issues as it is the slowest method by a long shot.
 * Be especially careful of branch prediction issues which is why this method has been re-written several times
 * just to avoid those issues even though the result was a LONGER method
 * TODO wring more performance out of this method where possible
 *//*  w w  w  . j  a va2s  .c o  m*/
public List<CodeMatchResult> findMatchingLines(List<String> code, List<String> matchTerms,
        boolean highlightLine) {
    List<CodeMatchResult> resultLines = new LinkedList<>();

    int codesize = code.size();
    int searchThrough = codesize > this.MAXLINEDEPTH ? this.MAXLINEDEPTH : codesize;
    int matching = 0;

    // Go through each line finding matching lines
    for (int i = 0; i < searchThrough; i++) {
        String matchRes = code.get(i).toLowerCase().replaceAll("\\s+", " ");
        matching = 0;

        for (String matchTerm : matchTerms) {
            if (matchRes.contains(matchTerm.replace("*", ""))) {
                matching++;
            }
        }

        if (matching != 0) {
            resultLines.add(new CodeMatchResult(code.get(i), true, false, matching, i));
        }
    }

    // Get the adjacent lines
    List<CodeMatchResult> adajacentLines = new LinkedList<>();
    for (CodeMatchResult cmr : resultLines) {
        int linenumber = cmr.getLineNumber();
        int previouslinenumber = linenumber - 1;
        int nextlinenumber = linenumber + 1;

        if (previouslinenumber >= 0 && !this.resultExists(resultLines, previouslinenumber)) {
            adajacentLines.add(
                    new CodeMatchResult(code.get(previouslinenumber), false, false, 0, previouslinenumber));
        }

        if (nextlinenumber < codesize && !this.resultExists(resultLines, nextlinenumber)) {
            adajacentLines.add(new CodeMatchResult(code.get(nextlinenumber), false, false, 0, nextlinenumber));
        }
    }

    resultLines.addAll(adajacentLines);

    // If not matching we probably matched on the filename or past 10000
    if (resultLines.size() == 0) {
        searchThrough = codesize > MATCHLINES ? MATCHLINES : codesize;

        for (int i = 0; i < searchThrough; i++) {
            resultLines.add(new CodeMatchResult(code.get(i), false, false, 0, i));
        }
    }

    // Highlight the lines if required but always escape everything
    if (highlightLine) {
        for (CodeMatchResult cmr : resultLines) {
            if (cmr.isMatching()) {
                String line = Values.EMPTYSTRING;
                try {
                    line = this.highlightLine(cmr.getLine(), matchTerms);
                } catch (StringIndexOutOfBoundsException ex) {
                    Singleton.getLogger().severe("Unable to highlightLine " + cmr.getLine() + " using terms "
                            + String.join(",", matchTerms) + " " + ex.toString());
                }
                cmr.setLine(line);
            } else {
                cmr.setLine(StringEscapeUtils.escapeHtml4(cmr.getLine()));
            }
        }
    } else {
        for (CodeMatchResult cmr : resultLines) {
            cmr.setLine(StringEscapeUtils.escapeHtml4(cmr.getLine()));
        }
    }

    return resultLines;
}

From source file:de.austinpadernale.holidays.Holiday.java

private String createName() {
    List<String> n = new ArrayList<>();
    n.add(String.format("Holiday-Type(%s)", holidayType));
    if (day != null) {
        n.add(String.format("Day(%s)", day));
    }//from   ww w .j av  a2s. co m
    if (month != null) {
        n.add(String.format("Month(%s)", month));
    }
    if (offset != null) {
        n.add(String.format("Offset(%s)", offset));
    }
    if (week != null) {
        n.add(String.format("Week(%s)", week));
    }
    return String.join("-", n);
}