Example usage for org.apache.commons.lang3 StringUtils join

List of usage examples for org.apache.commons.lang3 StringUtils join

Introduction

In this page you can find the example usage for org.apache.commons.lang3 StringUtils join.

Prototype

public static String join(final Iterable<?> iterable, final String separator) 

Source Link

Document

Joins the elements of the provided Iterable into a single String containing the provided elements.

No delimiter is added before or after the list.

Usage

From source file:com.ctrip.infosec.rule.executor.WhiteListRulesExecutorService.java

/**
 * /*from  w w w.j  a va2s .  co m*/
 */
void execute(RiskFact fact) {

    // matchRules      
    List<WhitelistRule> matchedRules = Configs.matchWhitelistRules(fact);
    List<String> scriptRulePackageNames = Collections3.extractToList(matchedRules, "ruleNo");
    logger.debug(Contexts.getLogPrefix() + "matched whitelist rules: "
            + StringUtils.join(scriptRulePackageNames, ", "));
    TraceLogger.traceLog("? " + matchedRules.size() + " ???? ...");

    StatelessWhitelistRuleEngine statelessWhitelistRuleEngine = SpringContextHolder
            .getBean(StatelessWhitelistRuleEngine.class);
    for (WhitelistRule rule : matchedRules) {
        RuleMonitorHelper.newTrans(fact, RuleMonitorType.WB_RULE, rule.getRuleNo());
        TraceLogger.beginNestedTrans(fact.eventId);
        TraceLogger.setNestedLogPrefix("[" + rule.getRuleNo() + "]");
        Contexts.setPolicyOrRuleNo(rule.getRuleNo());
        try {
            long start = System.currentTimeMillis();

            // add current execute ruleNo and logPrefix before execution
            fact.ext.put(Constants.key_ruleNo, rule.getRuleNo());
            fact.ext.put(Constants.key_isAsync, false);

            statelessWhitelistRuleEngine.execute(rule.getRuleNo(), fact);

            // remove current execute ruleNo when finished execution.
            fact.ext.remove(Constants.key_ruleNo);
            fact.ext.remove(Constants.key_isAsync);

            long handlingTime = System.currentTimeMillis() - start;
            if (handlingTime > 100) {
                logger.info(Contexts.getLogPrefix() + "whitelistRule: " + rule.getRuleNo() + ", usage: "
                        + handlingTime + "ms");
            }

            if (fact.finalWhitelistResult.isEmpty()) {
                TraceLogger.traceLog(
                        ">>>> [" + rule.getRuleNo() + "] ???. usage: " + handlingTime + "ms");
            } else {
                TraceLogger.traceLog(">>>> [" + rule.getRuleNo() + "] ???: riskLevel = "
                        + fact.finalWhitelistResult.get(Constants.riskLevel) + ", riskMessage = "
                        + fact.finalWhitelistResult.get(Constants.riskMessage) + ", usage = "
                        + fact.finalWhitelistResult.get(Constants.timeUsage) + "ms");
            }

        } catch (Throwable ex) {
            logger.warn(Contexts.getLogPrefix() + "???. whitelistRule: "
                    + rule.getRuleNo(), ex);
            TraceLogger.traceLog("[" + rule.getRuleNo() + "] EXCEPTION: " + ex.toString());
        } finally {
            TraceLogger.commitNestedTrans();
            RuleMonitorHelper.commitTrans(fact);
            Contexts.clearLogPrefix();
        }
    }

}

From source file:converter.TagsConverter.java

@Override
public String getAsString(FacesContext context, UIComponent component, Object value) {
    List<String> topicSelected = (List<String>) value;
    return StringUtils.join(topicSelected, ",");
}

From source file:annis.sqlgen.annopool.ApMatrixSqlGenerator.java

@Override
protected void addFromOuterJoins(StringBuilder sb, QueryData queryData, TableAccessStrategy tas,
        String indent) {/*from w ww. java 2s.  co m*/
    // get all the original outer joins
    super.addFromOuterJoins(sb, queryData, tas, indent);

    List<Long> corpusList = queryData.getCorpusList();

    // add join to annotation pool  tables

    // node annopool
    sb.append(indent).append(TABSTOP);
    sb.append("LEFT OUTER JOIN annotation_pool AS node_anno ON  (")
            .append(tas.aliasedColumn(NODE_TABLE, "node_anno_ref")).append(" = node_anno.id AND ")
            .append(tas.aliasedColumn(NODE_TABLE, "toplevel_corpus"))
            .append(" = node_anno.toplevel_corpus AND node_anno.toplevel_corpus IN (")
            .append(StringUtils.join(corpusList, ", ")).append("))");

    sb.append("\n");

    // edge annopool
    //    sb.append(indent).append(TABSTOP);
    //    sb.append(
    //      "LEFT OUTER JOIN annotation_pool AS edge_anno ON (").append(tas.
    //      aliasedColumn(RANK_TABLE, "edge_anno_ref")).append(" = edge_anno.id AND ").
    //      append(tas.aliasedColumn(RANK_TABLE, "toplevel_corpus")).append(" = edge_anno.toplevel_corpus AND "
    //      + "edge_anno.toplevel_corpus IN (").append(StringUtils.join(corpusList,
    //      ", ")).append("))");

}

From source file:cc.sion.core.utils.Collections3.java

/**
 * ????(Getter), ??./*from  www  .ja  v a  2s . com*/
 *
 * @param collection ???.
 * @param propertyName ??????.
 * @param separator .
 */
public static String extractToString(final Collection collection, final String propertyName,
        final String separator) {
    List list = extractToList(collection, propertyName);
    return StringUtils.join(list, separator);
}

From source file:annis.sqlgen.ListExampleQueriesHelper.java

public String createSQLQuery(List<Long> corpusIDs) {
    if (corpusIDs == null || corpusIDs.isEmpty()) {
        return "SELECT example_query, example_queries.\"type\", used_ops, "
                + "description, c.name as corpus_name " + "\nFROM example_queries, corpus c"
                + "\nWHERE corpus_ref = c.id";
    } else {/*  w  w w. j  a v  a 2  s  .  com*/
        String sql = "SELECT example_query, example_queries.\"type\", used_ops, "
                + "description, c.name as corpus_name  " + "\nFROM example_queries, ("
                + "\nSELECT * FROM corpus " + "\nWHERE corpus.id in (" + StringUtils.join(corpusIDs, ",")
                + ")) as c" + "\nWHERE   corpus_ref = c.id" + "\nORDER BY (nodes, used_ops)";

        return sql;
    }
}

From source file:com.jrzmq.core.email.SimpleMailService.java

/**
 * ??/*from ww  w.jav  a2  s  .c o  m*/
 * @param emailTo 
 * @param project 
 * @param ???
 * @param map     ?
 */
public void sendMail(String emailTo, String subject, String templateName, Map<String, Object> map) {
    SimpleMailMessage msg = new SimpleMailMessage();
    msg.setSentDate(new Date());
    msg.setTo(emailTo);
    msg.setSubject(subject);

    try {
        msg.setText(generateContent(templateName, map));
        mailSender.send(msg);
        if (logger.isInfoEnabled()) {
            logger.info("??{}", StringUtils.join(msg.getTo(), ","));
        }
    } catch (Exception e) {
        logger.error("??{},:{},", new Object[] { emailTo, subject }, e);
    }
}

From source file:hydrograph.engine.cascading.scheme.hive.parquet.HiveParquetSchemeHelper.java

public static String getParquetSchemeMessage(Fields sinkFields, String[] columnTypes) {
    List<String> columnName = new ArrayList<String>();
    for (int i = 0; i < sinkFields.size(); i++) {
        columnName.add(sinkFields.get(i).toString());
    }//from  w w w.j a  v  a2 s. co m
    String dataTypes = StringUtils.join(columnTypes, ":");
    return HiveSchemaConverter.convert(columnName, TypeInfoUtils.getTypeInfosFromTypeString(dataTypes))
            .toString();
}

From source file:com.act.lcms.db.analysis.PathwayProductAnalysis.java

public static void main(String[] args) throws Exception {
    Options opts = new Options();
    for (Option.Builder b : OPTION_BUILDERS) {
        opts.addOption(b.build());/*from w  w  w.  j  a  va  2 s  .  c om*/
    }

    CommandLine cl = null;
    try {
        CommandLineParser parser = new DefaultParser();
        cl = parser.parse(opts, args);
    } catch (ParseException e) {
        System.err.format("Argument parsing failed: %s\n", e.getMessage());
        HELP_FORMATTER.printHelp(LoadPlateCompositionIntoDB.class.getCanonicalName(), HELP_MESSAGE, opts, null,
                true);
        System.exit(1);
    }

    if (cl.hasOption("help")) {
        HELP_FORMATTER.printHelp(LoadPlateCompositionIntoDB.class.getCanonicalName(), HELP_MESSAGE, opts, null,
                true);
        return;
    }

    File lcmsDir = new File(cl.getOptionValue(OPTION_DIRECTORY));
    if (!lcmsDir.isDirectory()) {
        System.err.format("File at %s is not a directory\n", lcmsDir.getAbsolutePath());
        HELP_FORMATTER.printHelp(LoadPlateCompositionIntoDB.class.getCanonicalName(), HELP_MESSAGE, opts, null,
                true);
        System.exit(1);
    }

    Double fontScale = null;
    if (cl.hasOption("font-scale")) {
        try {
            fontScale = Double.parseDouble(cl.getOptionValue("font-scale"));
        } catch (IllegalArgumentException e) {
            System.err.format("Argument for font-scale must be a floating point number.\n");
            System.exit(1);
        }
    }

    try (DB db = DB.openDBFromCLI(cl)) {
        Set<Integer> takeSamplesFromPlateIds = null;
        if (cl.hasOption(OPTION_FILTER_BY_PLATE_BARCODE)) {
            String[] plateBarcodes = cl.getOptionValues(OPTION_FILTER_BY_PLATE_BARCODE);
            System.out.format("Considering only sample wells in plates: %s\n",
                    StringUtils.join(plateBarcodes, ", "));
            takeSamplesFromPlateIds = new HashSet<>(plateBarcodes.length);
            for (String plateBarcode : plateBarcodes) {
                Plate p = Plate.getPlateByBarcode(db, plateBarcode);
                if (p == null) {
                    System.err.format("WARNING: unable to find plate in DB with barcode %s\n", plateBarcode);
                } else {
                    takeSamplesFromPlateIds.add(p.getId());
                }
            }
            // Allow filtering on barcode even if we couldn't find any in the DB.
        }

        System.out.format("Loading/updating LCMS scan files into DB\n");
        ScanFile.insertOrUpdateScanFilesInDirectory(db, lcmsDir);

        System.out.format("Processing LCMS scans\n");
        Pair<List<LCMSWell>, Set<Integer>> positiveWellsAndPlateIds = Utils.extractWellsAndPlateIds(db,
                cl.getOptionValues(OPTION_STRAINS), cl.getOptionValues(OPTION_CONSTRUCT),
                takeSamplesFromPlateIds, false);
        List<LCMSWell> positiveWells = positiveWellsAndPlateIds.getLeft();
        if (positiveWells.size() == 0) {
            throw new RuntimeException("Found no LCMS wells for specified strains/constructs");
        }
        // Only take negative samples from the plates where we found the positive samples.
        Pair<List<LCMSWell>, Set<Integer>> negativeWellsAndPlateIds = Utils.extractWellsAndPlateIds(db,
                cl.getOptionValues(OPTION_NEGATIVE_STRAINS), cl.getOptionValues(OPTION_NEGATIVE_CONSTRUCTS),
                positiveWellsAndPlateIds.getRight(), true);
        List<LCMSWell> negativeWells = negativeWellsAndPlateIds.getLeft();
        if (negativeWells == null || negativeWells.size() == 0) {
            System.err.format("WARNING: no valid negative samples found in same plates as positive samples\n");
        }

        // Extract the chemicals in the pathway and their product masses, then look up info on those chemicals
        List<Pair<ChemicalAssociatedWithPathway, Double>> productMasses = Utils
                .extractMassesForChemicalsAssociatedWithConstruct(db, cl.getOptionValue(OPTION_CONSTRUCT));
        List<Pair<String, Double>> searchMZs = new ArrayList<>(productMasses.size());
        List<ChemicalAssociatedWithPathway> pathwayChems = new ArrayList<>(productMasses.size());
        for (Pair<ChemicalAssociatedWithPathway, Double> productMass : productMasses) {
            String chemName = productMass.getLeft().getChemical();
            searchMZs.add(Pair.of(chemName, productMass.getRight()));
            pathwayChems.add(productMass.getLeft());
        }
        System.out.format("Searching for intermediate/side-reaction products:\n");
        for (Pair<String, Double> searchMZ : searchMZs) {
            System.out.format("  %s: %.3f\n", searchMZ.getLeft(), searchMZ.getRight());
        }

        // Look up the standard by name.
        List<StandardWell> standardWells = new ArrayList<>();
        if (cl.hasOption(OPTION_STANDARD_WELLS)) {
            Plate standardPlate = Plate.getPlateByBarcode(db, cl.getOptionValue(OPTION_STANDARD_PLATE_BARCODE));
            Map<Integer, StandardWell> pathwayIdToStandardWell = extractStandardWellsFromOptionsList(db,
                    pathwayChems, cl.getOptionValues(OPTION_STANDARD_WELLS), standardPlate);
            for (ChemicalAssociatedWithPathway c : pathwayChems) { // TODO: we can avoid this loop.
                StandardWell well = pathwayIdToStandardWell.get(c.getId());
                if (well != null) {
                    standardWells.add(well);
                }
            }
        } else {
            for (ChemicalAssociatedWithPathway c : pathwayChems) {
                String standardName = c.getChemical();
                System.out.format("Searching for well containing standard %s\n", standardName);
                List<StandardWell> wells = StandardIonAnalysis.getStandardWellsForChemical(db, c.getChemical());
                if (wells != null) {
                    standardWells.addAll(wells);
                }
            }
        }

        boolean useFineGrainedMZ = cl.hasOption("fine-grained-mz");
        boolean useSNR = cl.hasOption(OPTION_USE_SNR);

        /* Process the standard, positive, and negative wells, producing ScanData containers that will allow them to be
         * iterated over for graph writing. We do not need to specify granular includeIons and excludeIons since
         * this would not take advantage of our caching strategy which uses a list of metlin ions as an index. */
        HashMap<Integer, Plate> plateCache = new HashMap<>();
        Pair<List<ScanData<StandardWell>>, Double> allStandardScans = AnalysisHelper.processScans(db, lcmsDir,
                searchMZs, ScanData.KIND.STANDARD, plateCache, standardWells, useFineGrainedMZ, EMPTY_SET,
                EMPTY_SET, useSNR);
        Pair<List<ScanData<LCMSWell>>, Double> allPositiveScans = AnalysisHelper.processScans(db, lcmsDir,
                searchMZs, ScanData.KIND.POS_SAMPLE, plateCache, positiveWells, useFineGrainedMZ, EMPTY_SET,
                EMPTY_SET, useSNR);
        Pair<List<ScanData<LCMSWell>>, Double> allNegativeScans = AnalysisHelper.processScans(db, lcmsDir,
                searchMZs, ScanData.KIND.NEG_CONTROL, plateCache, negativeWells, useFineGrainedMZ, EMPTY_SET,
                EMPTY_SET, useSNR);

        String fmt = "pdf";
        String outImg = cl.getOptionValue(OPTION_OUTPUT_PREFIX) + "." + fmt;
        String outData = cl.getOptionValue(OPTION_OUTPUT_PREFIX) + ".data";
        String outAnalysis = cl.getOptionValue(OPTION_OUTPUT_PREFIX) + ".tsv";

        System.err.format("Writing combined scan data to %s and graphs to %s\n", outData, outImg);
        String plottingDirectory = cl.getOptionValue(OPTION_PLOTTING_DIR);

        List<ScanData<LCMSWell>> posNegWells = new ArrayList<>();
        posNegWells.addAll(allPositiveScans.getLeft());
        posNegWells.addAll(allNegativeScans.getLeft());

        Map<Integer, String> searchIons;
        if (cl.hasOption(OPTION_PATHWAY_SEARCH_IONS)) {
            searchIons = extractPathwayStepIons(pathwayChems, cl.getOptionValues(OPTION_PATHWAY_SEARCH_IONS),
                    cl.getOptionValue(OPTION_SEARCH_ION, "M+H"));
            /* This is pretty lazy, but works with the existing API.  Extract all selected ions for all search masses when
             * performing the scan, then filter down to the desired ions for the plot at the end.
             * TODO: specify the masses and scans per sample rather than batching everything together.  It might be slower,
             * but it'll be clearer to read. */
        } else {
            // We need to make sure that the standard metlin ion we choose is consistent with the ion modes of
            // the given positive, negative and standard scan files. For example, we should not pick a negative
            // metlin ion if all our available positive control scan files are in the positive ion mode.
            Map<Integer, Pair<Boolean, Boolean>> ionModes = new HashMap<>();
            for (ChemicalAssociatedWithPathway chemical : pathwayChems) {
                boolean isPositiveScanPresent = false;
                boolean isNegativeScanPresent = false;

                for (ScanData<StandardWell> scan : allStandardScans.getLeft()) {
                    if (chemical.getChemical().equals(scan.getWell().getChemical())
                            && chemical.getChemical().equals(scan.getTargetChemicalName())) {
                        if (MS1.IonMode.valueOf(
                                scan.getScanFile().getMode().toString().toUpperCase()) == MS1.IonMode.POS) {
                            isPositiveScanPresent = true;
                        }

                        if (MS1.IonMode.valueOf(
                                scan.getScanFile().getMode().toString().toUpperCase()) == MS1.IonMode.NEG) {
                            isNegativeScanPresent = true;
                        }
                    }
                }

                for (ScanData<LCMSWell> scan : posNegWells) {
                    if (chemical.getChemical().equals(scan.getWell().getChemical())
                            && chemical.getChemical().equals(scan.getTargetChemicalName())) {
                        if (MS1.IonMode.valueOf(
                                scan.getScanFile().getMode().toString().toUpperCase()) == MS1.IonMode.POS) {
                            isPositiveScanPresent = true;
                        }

                        if (MS1.IonMode.valueOf(
                                scan.getScanFile().getMode().toString().toUpperCase()) == MS1.IonMode.NEG) {
                            isNegativeScanPresent = true;
                        }
                    }
                }

                ionModes.put(chemical.getId(), Pair.of(isPositiveScanPresent, isNegativeScanPresent));
            }

            // Sort in descending order of media where MeOH and Water related media are promoted to the top and
            // anything derived from yeast media are demoted. We do this because we want to first process the water
            // and meoh media before processing the yeast media since the yeast media depends on the analysis of the former.
            Collections.sort(standardWells, new Comparator<StandardWell>() {
                @Override
                public int compare(StandardWell o1, StandardWell o2) {
                    if (StandardWell.doesMediaContainYeastExtract(o1.getMedia())
                            && !StandardWell.doesMediaContainYeastExtract(o2.getMedia())) {
                        return 1;
                    } else {
                        return 0;
                    }
                }
            });

            searchIons = extractPathwayStepIonsFromStandardIonAnalysis(pathwayChems, lcmsDir, db, standardWells,
                    plottingDirectory, ionModes);
        }

        produceLCMSPathwayHeatmaps(lcmsDir, outData, outImg, outAnalysis, pathwayChems, allStandardScans,
                allPositiveScans, allNegativeScans, fontScale, cl.hasOption(OPTION_USE_HEATMAP), searchIons);
    }
}

From source file:com.rabidgremlin.legalbeagle.report.TsvReportWriter.java

public void generateReport(String output, Report report) throws Exception {
    log.info("Writing report to {}...", output);

    PrintWriter out = new PrintWriter(new File(output));

    out.println("File\tStatus\tDescription\tLicense(s)\tError");

    for (ReportItem reportItem : report.getReportItems()) {
        out.print(reportItem.getFile().getAbsolutePath());
        out.print("\t");
        out.print(reportItem.getReportItemStatus());
        out.print("\t");

        if (reportItem.getDescription() != null) {
            out.print(reportItem.getDescription());
        }/*w w  w .j  a v  a2s .  co  m*/
        out.print("\t");

        out.print(StringUtils.join(reportItem.getLicenses(), "; "));
        out.print("\t");

        if (reportItem.getError() != null) {
            out.print(reportItem.getError());
        }

        out.println();

    }

    out.flush();
    out.close();
}

From source file:com.cnksi.core.tools.utils.Collections3.java

/**
 * ????(Getter), ??./*from  w ww.  j  av  a2s  .com*/
 * 
 * @param collection ???.
 * @param propertyName ??????.
 * @param separator .
 */
public static String extractToString(final Collection collection, final String propertyName,
        final String separator) {

    List list = extractToList(collection, propertyName);
    return StringUtils.join(list, separator);
}