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

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

Introduction

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

Prototype

public static String[] split(final String str, final String separatorChars) 

Source Link

Document

Splits the provided text into an array, separators specified.

Usage

From source file:edu.gmu.csd.processor.DataProcessor.java

public static WinningResult calculateMeanStandardDeviation(String raffle) {
    String[] dataFieldsArr = null;
    if (StringUtils.isNotEmpty(raffle)) {
        dataFieldsArr = StringUtils.split(raffle, ",");
    }/*from  www  .j a va2s.  co  m*/
    WinningResult winningResult = null;

    if (null != dataFieldsArr) {
        double mean;
        double sum = 0;
        double squareSum = 0;
        double stndrdDeviation;

        // First for loop to calculate the mean.
        for (String meanData : dataFieldsArr) {
            sum = sum + Integer.parseInt(meanData);
        }

        mean = sum / dataFieldsArr.length;

        // Second for loop to calculate the standard deviation.
        for (String sdData : dataFieldsArr) {
            double square = Math.pow((Integer.parseInt(sdData) - mean), 2);

            squareSum = squareSum + square;
        }

        stndrdDeviation = Math.sqrt(squareSum / (dataFieldsArr.length - 1));

        winningResult = new WinningResult();
        winningResult.setMean(mean);
        winningResult.setStandardDeviation(stndrdDeviation);
    }

    return winningResult;
}

From source file:SampleLang.java

/**
 * Check if the key is valid//from   w ww. ja v  a  2s .  com
 * @param key license key value
 * @return true if key is valid, false otherwise.
 */
public static boolean checkLicenseKey(String key) {
    //checks if empty or null
    if (StringUtils.isBlank(key)) {
        return false;
    }
    //delete all white space
    key = StringUtils.deleteWhitespace(key);
    //Split String using the - separator
    String[] keySplit = StringUtils.split(key, "-");
    //check lengths of whole and parts
    if (keySplit.length != 2 || keySplit[0].length() != 4 || keySplit[1].length() != 4) {
        return false;
    }
    //Check if first part is numeric
    if (!StringUtils.isNumeric(keySplit[0])) {
        return false;
    }
    //Check if second part contains only
    //the four characters 'J', 'A', 'V' and 'A'
    if (!StringUtils.containsOnly(keySplit[1], new char[] { 'J', 'A', 'V', 'A' })) {
        return false;
    }
    //Check if the fourth character
    //in the first part is a '0'
    if (StringUtils.indexOf(keySplit[0], '0') != 3) {
        return false;
    }
    //If all conditions are fulfilled, key is valid.
    return true;
}

From source file:com.sixwonders.courtkiosk.CitationAdapter.java

public static ArrayList<Citation> adaptCitationData(ArrayList<JSONObject> jsonObjects) {
    ArrayList<Citation> citations = new ArrayList<Citation>();
    try {/*w  w w  . j av a 2s .  com*/
        for (JSONObject jsonObject : jsonObjects) {
            Citation citation = new Citation();
            //id,,,,,date_of_birth,defendant_address,defendant_city,defendant_state,drivers_license_number,court_date,court_location,court_address
            if (jsonObject.getInt("citation_number") != 0) {
                citation.setCitation_number(jsonObject.getInt("citation_number"));
            }
            if (!StringUtils.isEmpty(jsonObject.get("citation_date").toString())) {
                citation.setCitation_date(StringUtils.split(jsonObject.getString("citation_date"), ' ')[0]);
            }
            if (!StringUtils.isEmpty(jsonObject.get("first_name").toString())) {
                citation.setFirst_name(jsonObject.getString("first_name"));
            }
            if (!StringUtils.isEmpty(jsonObject.get("last_name").toString())) {
                citation.setFirst_name(jsonObject.getString("last_name"));
            }
            if (!StringUtils.isEmpty(jsonObject.get("court_location").toString())) {
                citation.setCourt_location(jsonObject.getString("court_location"));
            }
            citations.add(citation);
        }
    } catch (JSONException e) {
        e.printStackTrace();
    }

    return citations;
}

From source file:com.google.mr4c.util.PathUtils.java

/**
  * Takes the elements of one path and prepends any elements that are missing in another path
*//*from   w  w w  . jav  a 2s.c  om*/
public static String prependMissingPathElements(String path, String otherPath, String separator) {

    List<String> pathElements = Arrays.asList(StringUtils.split(path, separator));
    List<String> otherElements = Arrays.asList(StringUtils.split(otherPath, separator));
    List<String> toAdd = new ArrayList<String>();
    for (String element : otherElements) {
        if (!pathElements.contains(element)) {
            toAdd.add(element);
        }
    }
    List<String> newElements = new ArrayList<String>();
    newElements.addAll(toAdd);
    newElements.addAll(pathElements);
    return StringUtils.join(newElements, separator);
}

From source file:info.mikaelsvensson.devtools.common.PathUtils.java

public static String getRelativePath(File source, File target) {
    source = source.isDirectory() ? source : source.getParentFile();

    String sourceFixed = fixPath(source);
    String targetFixed = fixPath(target);

    String[] sourceParts = StringUtils.split(sourceFixed, SEP);
    String[] targetParts = StringUtils.split(targetFixed, SEP);
    int sharedParts = 0;
    for (int i = 0; i < sourceParts.length; i++) {
        String sourcePart = sourceParts[i];
        if (targetParts.length == i) {
            break;
        }/*from   w ww . ja  v a 2 s.c o  m*/
        String targetPart = targetParts[i];
        if (sourcePart.equals(targetPart)) {
            sharedParts = i;
        }
    }

    String toSharedRoot = StringUtils.repeat(".." + SEP, sourceParts.length - sharedParts - 1);
    String fromSharedRoot = StringUtils.join(targetParts, SEP, sharedParts + 1, targetParts.length);
    if (StringUtils.isEmpty(toSharedRoot) && StringUtils.isEmpty(fromSharedRoot)) {
        return "." + SEP;
    } else {
        return toSharedRoot + fromSharedRoot;
    }

}

From source file:com.mb.framework.util.StringUtil.java

/**
 * This method is used for splitting string by separator
 * @param str//from  w  ww . j  av  a  2s.  co m
 * @param separator
 * @return
 */
public static String[] split(String str, String separator) {
    return StringUtils.split(str, separator);
}

From source file:eqtlmappingpipeline.util.ModuleEqtWestraReplication.java

/**
 * @param args the command line arguments
 *//*from   w  w w. j  a v  a2 s.  c  o m*/
public static void main(String[] args) throws IOException, LdCalculatorException {

    System.out.println(HEADER);
    System.out.println();
    System.out.flush(); //flush to make sure header is before errors
    try {
        Thread.sleep(25); //Allows flush to complete
    } catch (InterruptedException ex) {
    }

    CommandLineParser parser = new PosixParser();
    final CommandLine commandLine;
    try {
        commandLine = parser.parse(OPTIONS, args, true);
    } catch (ParseException ex) {
        System.err.println("Invalid command line arguments: " + ex.getMessage());
        System.err.println();
        new HelpFormatter().printHelp(" ", OPTIONS);
        System.exit(1);
        return;
    }

    final String[] genotypesBasePaths = commandLine.getOptionValues("g");
    final RandomAccessGenotypeDataReaderFormats genotypeDataType;
    final String replicationQtlFilePath = commandLine.getOptionValue("e");
    final String interactionQtlFilePath = commandLine.getOptionValue("i");
    final String outputFilePath = commandLine.getOptionValue("o");
    final double ldCutoff = Double.parseDouble(commandLine.getOptionValue("ld"));
    final int window = Integer.parseInt(commandLine.getOptionValue("w"));

    System.out.println("Genotype: " + Arrays.toString(genotypesBasePaths));
    System.out.println("Interaction file: " + interactionQtlFilePath);
    System.out.println("Replication file: " + replicationQtlFilePath);
    System.out.println("Output: " + outputFilePath);
    System.out.println("LD: " + ldCutoff);
    System.out.println("Window: " + window);

    try {
        if (commandLine.hasOption("G")) {
            genotypeDataType = RandomAccessGenotypeDataReaderFormats
                    .valueOf(commandLine.getOptionValue("G").toUpperCase());
        } else {
            if (genotypesBasePaths[0].endsWith(".vcf")) {
                System.err.println(
                        "Only vcf.gz is supported. Please see manual on how to do create a vcf.gz file.");
                System.exit(1);
                return;
            }
            try {
                genotypeDataType = RandomAccessGenotypeDataReaderFormats
                        .matchFormatToPath(genotypesBasePaths[0]);
            } catch (GenotypeDataException e) {
                System.err
                        .println("Unable to determine input 1 type based on specified path. Please specify -G");
                System.exit(1);
                return;
            }
        }
    } catch (IllegalArgumentException e) {
        System.err.println("Error parsing --genotypesFormat \"" + commandLine.getOptionValue("G")
                + "\" is not a valid input data format");
        System.exit(1);
        return;
    }

    final RandomAccessGenotypeData genotypeData;

    try {
        genotypeData = genotypeDataType.createFilteredGenotypeData(genotypesBasePaths, 100, null, null, null,
                0.8);
    } catch (TabixFileNotFoundException e) {
        LOGGER.fatal("Tabix file not found for input data at: " + e.getPath() + "\n"
                + "Please see README on how to create a tabix file");
        System.exit(1);
        return;
    } catch (IOException e) {
        LOGGER.fatal("Error reading input data: " + e.getMessage(), e);
        System.exit(1);
        return;
    } catch (IncompatibleMultiPartGenotypeDataException e) {
        LOGGER.fatal("Error combining the impute genotype data files: " + e.getMessage(), e);
        System.exit(1);
        return;
    } catch (GenotypeDataException e) {
        LOGGER.fatal("Error reading input data: " + e.getMessage(), e);
        System.exit(1);
        return;
    }

    ChrPosTreeMap<ArrayList<ReplicationQtl>> replicationQtls = new ChrPosTreeMap<>();

    CSVReader replicationQtlReader = new CSVReader(new FileReader(replicationQtlFilePath), '\t');
    String[] replicationHeader = replicationQtlReader.readNext();
    String[] replicationLine;
    while ((replicationLine = replicationQtlReader.readNext()) != null) {

        try {

            GeneticVariant variant = genotypeData.getSnpVariantByPos(replicationLine[REPLICATION_SNP_CHR_COL],
                    Integer.parseInt(replicationLine[REPLICATION_SNP_POS_COL]));
            if (variant == null) {
                continue;
            }

            Alleles variantAlleles = variant.getVariantAlleles();
            String[] replicationAllelesString = StringUtils.split(replicationLine[REPLICATION_ALLELES_COL],
                    '/');

            Alleles replicationAlleles = Alleles.createBasedOnString(replicationAllelesString[0],
                    replicationAllelesString[1]);
            Allele assessedAlleleReplication = Allele.create(replicationLine[REPLICATION_ALLELE_ASSESSED_COL]);

            boolean isAmbigous = replicationAlleles.isAtOrGcSnp();

            if (!variantAlleles.equals(replicationAlleles)) {
                if (variantAlleles.equals(replicationAlleles.getComplement())) {
                    assessedAlleleReplication = assessedAlleleReplication.getComplement();
                } else {
                    continue;
                }
            }

            ReplicationQtl replicationQtl = new ReplicationQtl(replicationLine[REPLICATION_SNP_CHR_COL],
                    Integer.parseInt(replicationLine[REPLICATION_SNP_POS_COL]),
                    replicationLine[REPLICATION_GENE_COL],
                    Double.parseDouble(replicationLine[REPLICATION_BETA_COL]),
                    assessedAlleleReplication.getAlleleAsString(), replicationLine, isAmbigous);
            ArrayList<ReplicationQtl> posReplicationQtls = replicationQtls.get(replicationQtl.getChr(),
                    replicationQtl.getPos());
            if (posReplicationQtls == null) {
                posReplicationQtls = new ArrayList<>();
                replicationQtls.put(replicationQtl.getChr(), replicationQtl.getPos(), posReplicationQtls);
            }
            posReplicationQtls.add(replicationQtl);

        } catch (Exception e) {
            System.out.println(Arrays.toString(replicationLine));
            throw e;
        }
    }

    int interactionSnpNotInGenotypeData = 0;
    int noReplicationQtlsInWindow = 0;
    int noReplicationQtlsInLd = 0;
    int multipleReplicationQtlsInLd = 0;
    int replicationTopSnpNotInGenotypeData = 0;

    final CSVWriter outputWriter = new CSVWriter(new FileWriter(new File(outputFilePath)), '\t', '\0');
    final String[] outputLine = new String[15 + EXTRA_COL_FROM_REPLICATION.length];
    int c = 0;
    outputLine[c++] = "Chr";
    outputLine[c++] = "Pos";
    outputLine[c++] = "SNP";
    outputLine[c++] = "Gene";
    outputLine[c++] = "Module";
    outputLine[c++] = "DiscoveryZ";
    outputLine[c++] = "ReplicationZ";
    outputLine[c++] = "DiscoveryZCorrected";
    outputLine[c++] = "ReplicationZCorrected";
    outputLine[c++] = "DiscoveryAlleleAssessed";
    outputLine[c++] = "ReplicationAlleleAssessed";
    outputLine[c++] = "bestLd";
    outputLine[c++] = "bestLd_dist";
    outputLine[c++] = "nextLd";
    outputLine[c++] = "replicationAmbigous";
    for (int i = 0; i < EXTRA_COL_FROM_REPLICATION.length; ++i) {
        outputLine[c++] = replicationHeader[EXTRA_COL_FROM_REPLICATION[i]];
    }
    outputWriter.writeNext(outputLine);

    HashSet<String> notFound = new HashSet<>();

    CSVReader interactionQtlReader = new CSVReader(new FileReader(interactionQtlFilePath), '\t');
    interactionQtlReader.readNext();//skip header
    String[] interactionQtlLine;
    while ((interactionQtlLine = interactionQtlReader.readNext()) != null) {

        String snp = interactionQtlLine[1];
        String chr = interactionQtlLine[2];
        int pos = Integer.parseInt(interactionQtlLine[3]);
        String gene = interactionQtlLine[4];
        String alleleAssessed = interactionQtlLine[9];
        String module = interactionQtlLine[12];
        double discoveryZ = Double.parseDouble(interactionQtlLine[10]);

        GeneticVariant interactionQtlVariant = genotypeData.getSnpVariantByPos(chr, pos);

        if (interactionQtlVariant == null) {
            System.err.println("Interaction QTL SNP not found in genotype data: " + chr + ":" + pos);
            ++interactionSnpNotInGenotypeData;
            continue;
        }

        ReplicationQtl bestMatch = null;
        double bestMatchR2 = Double.NaN;
        Ld bestMatchLd = null;
        double nextBestR2 = Double.NaN;

        ArrayList<ReplicationQtl> sameSnpQtls = replicationQtls.get(chr, pos);

        if (sameSnpQtls != null) {
            for (ReplicationQtl sameSnpQtl : sameSnpQtls) {
                if (sameSnpQtl.getGene().equals(gene)) {
                    bestMatch = sameSnpQtl;
                    bestMatchR2 = 1;
                }
            }
        }

        NavigableMap<Integer, ArrayList<ReplicationQtl>> potentionalReplicationQtls = replicationQtls
                .getChrRange(chr, pos - window, true, pos + window, true);

        for (ArrayList<ReplicationQtl> potentialReplicationQtls : potentionalReplicationQtls.values()) {

            for (ReplicationQtl potentialReplicationQtl : potentialReplicationQtls) {

                if (!potentialReplicationQtl.getGene().equals(gene)) {
                    continue;
                }

                GeneticVariant potentialReplicationQtlVariant = genotypeData
                        .getSnpVariantByPos(potentialReplicationQtl.getChr(), potentialReplicationQtl.getPos());

                if (potentialReplicationQtlVariant == null) {
                    notFound.add(potentialReplicationQtl.getChr() + ":" + potentialReplicationQtl.getPos());
                    ++replicationTopSnpNotInGenotypeData;
                    continue;
                }

                Ld ld = interactionQtlVariant.calculateLd(potentialReplicationQtlVariant);
                double r2 = ld.getR2();

                if (r2 > 1) {
                    r2 = 1;
                }

                if (bestMatch == null) {
                    bestMatch = potentialReplicationQtl;
                    bestMatchR2 = r2;
                    bestMatchLd = ld;
                } else if (r2 > bestMatchR2) {
                    bestMatch = potentialReplicationQtl;
                    nextBestR2 = bestMatchR2;
                    bestMatchR2 = r2;
                    bestMatchLd = ld;
                }

            }
        }

        double replicationZ = Double.NaN;
        double replicationZCorrected = Double.NaN;
        double discoveryZCorrected = Double.NaN;

        String replicationAlleleAssessed = null;

        if (bestMatch != null) {
            replicationZ = bestMatch.getBeta();
            replicationAlleleAssessed = bestMatch.getAssessedAllele();

            if (pos != bestMatch.getPos()) {

                String commonHap = null;
                double commonHapFreq = -1;
                for (Map.Entry<String, Double> hapFreq : bestMatchLd.getHaplotypesFreq().entrySet()) {

                    double f = hapFreq.getValue();

                    if (f > commonHapFreq) {
                        commonHapFreq = f;
                        commonHap = hapFreq.getKey();
                    }

                }

                String[] commonHapAlleles = StringUtils.split(commonHap, '/');

                discoveryZCorrected = commonHapAlleles[0].equals(alleleAssessed) ? discoveryZ : discoveryZ * -1;
                replicationZCorrected = commonHapAlleles[1].equals(replicationAlleleAssessed) ? replicationZ
                        : replicationZ * -1;

            } else {

                discoveryZCorrected = discoveryZ;
                replicationZCorrected = alleleAssessed.equals(replicationAlleleAssessed) ? replicationZ
                        : replicationZ * -1;
                //replicationZCorrected = alleleAssessed.equals(replicationAlleleAssessed) || alleleAssessed.equals(String.valueOf(Utils.getComplementNucleotide(replicationAlleleAssessed.charAt(0)))) ? replicationZ : replicationZ * -1;

            }

        }

        c = 0;
        outputLine[c++] = chr;
        outputLine[c++] = String.valueOf(pos);
        outputLine[c++] = snp;
        outputLine[c++] = gene;
        outputLine[c++] = module;
        outputLine[c++] = String.valueOf(discoveryZ);
        outputLine[c++] = bestMatch == null ? "NA" : String.valueOf(replicationZ);
        outputLine[c++] = bestMatch == null ? "NA" : String.valueOf(discoveryZCorrected);
        outputLine[c++] = bestMatch == null ? "NA" : String.valueOf(replicationZCorrected);
        outputLine[c++] = alleleAssessed;
        outputLine[c++] = bestMatch == null ? "NA" : String.valueOf(bestMatch.getAssessedAllele());
        outputLine[c++] = String.valueOf(bestMatchR2);
        outputLine[c++] = bestMatch == null ? "NA" : String.valueOf(Math.abs(pos - bestMatch.getPos()));
        outputLine[c++] = String.valueOf(nextBestR2);
        outputLine[c++] = bestMatch == null ? "NA" : String.valueOf(bestMatch.isIsAmbigous());

        if (bestMatch == null) {
            for (int i = 0; i < EXTRA_COL_FROM_REPLICATION.length; ++i) {
                outputLine[c++] = "NA";
            }
        } else {
            for (int i = 0; i < EXTRA_COL_FROM_REPLICATION.length; ++i) {
                outputLine[c++] = bestMatch.getLine()[EXTRA_COL_FROM_REPLICATION[i]];
            }
        }

        outputWriter.writeNext(outputLine);

    }

    outputWriter.close();

    for (String e : notFound) {
        System.err.println("Not found: " + e);
    }

    System.out.println("interactionSnpNotInGenotypeData: " + interactionSnpNotInGenotypeData);
    System.out.println("noReplicationQtlsInWindow: " + noReplicationQtlsInWindow);
    System.out.println("noReplicationQtlsInLd: " + noReplicationQtlsInLd);
    System.out.println("multipleReplicationQtlsInLd: " + multipleReplicationQtlsInLd);
    System.out.println("replicationTopSnpNotInGenotypeData: " + replicationTopSnpNotInGenotypeData);

}

From source file:com.deploymentio.cfnstacker.template.VelocityUtil.java

public static String joinLinesWithSingleQuote(String content) {
    String[] lines = StringUtils.split(content, "\r\n");
    for (int i = 0; i < lines.length; i++) {
        lines[i] = "'" + lines[i].replace("\\\"", "\\\\\"") + "\\n'";
    }/*from www. j a  v  a2  s .c o m*/
    return StringUtils.join(lines, " +\n");
}

From source file:com.jdom.util.collections.CollectionsUtil.java

public static Set<String> asSetFromLine(String line, char separator) {
    List<String> list = (StringUtils.isEmpty(line)) ? Collections.<String>emptyList()
            : Arrays.asList(StringUtils.split(line, separator));
    return new HashSet<String>(list);
}

From source file:com.opensearchserver.extractor.ResourceLink.java

public static String join(String... path) {
    String join = StringUtils.join(path, '/');
    path = StringUtils.split(join, '/');
    return StringUtils.join(path, '/');
}