Example usage for com.google.common.base Splitter split

List of usage examples for com.google.common.base Splitter split

Introduction

In this page you can find the example usage for com.google.common.base Splitter split.

Prototype

@CheckReturnValue
public Iterable<String> split(final CharSequence sequence) 

Source Link

Document

Splits sequence into string components and makes them available through an Iterator , which may be lazily evaluated.

Usage

From source file:com.appdynamics.extensions.redis.RedisMonitorTask.java

private RedisMetrics parseInfoString(String info) {
    RedisMetrics metricsForAServer = new RedisMetrics();
    Map<String, String> metrics = Maps.newHashMap();
    String categoryName = "";
    Set<String> excludePatterns = server.getExcludePatterns();
    Splitter lineSplitter = Splitter.on(System.getProperty("line.separator")).trimResults().omitEmptyStrings();
    for (String currentLine : lineSplitter.split(info)) {
        if (currentLine.startsWith("#")) { // Every Category of metrics
            // starts with # like #Memory
            categoryName = currentLine.substring(1).trim();
            continue; // No need to go through if the line starts with a #
        }/*from  w ww .  j  a  va  2s  .c o m*/
        String[] kv = currentLine.split(COLON_SEPARATOR);
        if (kv.length == 2) {
            String key = kv[0].trim();
            String metricPath = getMetricPath(categoryName, key);
            if (!isKeyExcluded(metricPath, excludePatterns)) { //
                String value = kv[1].trim();
                if (NumberUtils.isNumber(value)) {
                    metrics.put(metricPath, MetricUtils.toWholeNumberString(Double.parseDouble(value)));
                    continue; // No need to procees further if the value is
                              // a Number
                }
                setRole(metrics, key, metricPath, value);
                setMasterLinkStatus(metrics, key, metricPath, value);
                setKeySpaceMetrics(metrics, key, metricPath, value);
            }
        }
    }
    metricsForAServer.setMetrics(metrics);
    return metricsForAServer;
}

From source file:com.b2international.snowowl.datastore.BranchPath.java

@Override
public String lastSegment() {
    if (BranchPathUtils.isMain(this)) {
        return IBranchPath.MAIN_BRANCH;
    }/*from   w  w w .j a  va2 s.c  om*/

    if (StringUtils.isEmpty(path)) {
        return IBranchPath.EMPTY_PATH;
    }

    final Splitter splitter = Splitter.on(IBranchPath.SEPARATOR_CHAR).omitEmptyStrings().trimResults();
    final Iterable<String> segments = splitter.split(path);

    return Iterables.getLast(segments, IBranchPath.EMPTY_PATH);
}

From source file:com.mapr.synth.samplers.StringSampler.java

protected void readDistribution(String resourceName) {
    try {/*from www.  j  a va 2  s.c o m*/
        if (distribution.compareAndSet(null, new Multinomial<String>())) {
            Splitter onTab = Splitter.on("\t").trimResults();
            for (String line : Resources.readLines(Resources.getResource(resourceName), Charsets.UTF_8)) {
                if (!line.startsWith("#")) {
                    Iterator<String> parts = onTab.split(line).iterator();
                    String name = translate(parts.next());
                    double weight = Double.parseDouble(parts.next());
                    distribution.get().add(name, weight);
                }
            }
        }

    } catch (IOException e) {
        throw new RuntimeException("Couldn't read built-in resource file", e);
    }
}

From source file:org.lilyproject.tools.import_.cli.JsonImportTool.java

@Override
public int run(CommandLine cmd) throws Exception {
    int result = super.run(cmd);
    if (result != 0) {
        return result;
    }/*w w  w. j a  v a 2s.c  o  m*/

    int workers = OptionUtil.getIntOption(cmd, workersOption, 1);

    String tableName = OptionUtil.getStringOption(cmd, tableOption, Table.RECORD.name);
    String repositoryName = OptionUtil.getStringOption(cmd, repositoryOption,
            RepoAndTableUtil.DEFAULT_REPOSITORY);
    ImportFileFormat fileFormat = OptionUtil.getEnum(cmd, fileFormatOption, ImportFileFormat.JSON,
            ImportFileFormat.class);

    if (cmd.getArgList().size() < 1) {
        System.out.println("No import file specified!");
        return 1;
    }

    boolean schemaOnly = cmd.hasOption(schemaOnlyOption.getOpt());
    boolean ignoreEmptyFields = cmd.hasOption(ignoreEmptyFieldsOption.getLongOpt());
    boolean ignoreAndDeleteEmptyFields = cmd.hasOption(ignoreAndDeleteEmptyFieldsOption.getLongOpt());
    long maxErrors = OptionUtil.getLongOption(cmd, maxErrorsOption, 1L);

    if (cmd.hasOption(rolesOption.getLongOpt())) {
        Set<String> roles = new HashSet<String>();
        Splitter splitter = Splitter.on(",").trimResults().omitEmptyStrings();
        for (String role : splitter.split(cmd.getOptionValue(rolesOption.getLongOpt()))) {
            roles.add(role);
        }
        AuthorizationContextHolder
                .setCurrentContext(new AuthorizationContext("lily-import", repositoryName, roles));
    }

    lilyClient = new LilyClient(zkConnectionString, zkSessionTimeout);

    for (String arg : (List<String>) cmd.getArgList()) {
        System.out.println("----------------------------------------------------------------------");
        System.out.println("Importing " + arg + " to " + tableName + " table of repository " + repositoryName);
        InputStream is = new FileInputStream(arg);
        try {
            LRepository repository = lilyClient.getRepository(repositoryName);
            LTable table = repository.getTable(tableName);
            ImportListener importListener;
            if (cmd.hasOption(quietOption.getOpt())) {
                importListener = new DefaultImportListener(System.out, EntityType.RECORD);
            } else {
                importListener = new DefaultImportListener();
            }

            JsonImport.ImportSettings settings = new JsonImport.ImportSettings();
            settings.importListener = importListener;
            settings.threadCount = workers;
            settings.maximumRecordErrors = maxErrors;
            if (ignoreAndDeleteEmptyFields) {
                settings.recordReader = IgnoreAndDeleteEmptyFieldsRecordReader.INSTANCE;
            } else if (ignoreEmptyFields) {
                settings.recordReader = IgnoreEmptyFieldsRecordReader.INSTANCE;
            } else {
                settings.recordReader = RecordReader.INSTANCE;
            }

            switch (fileFormat) {
            case JSON:
                if (schemaOnly) {
                    JsonImport.loadSchema(repository, is, settings);
                } else {
                    JsonImport.load(table, repository, is, settings);
                }
                break;
            case JSON_LINES:
                JsonImport.loadJsonLines(table, repository, is, settings);
                break;
            default:
                throw new RuntimeException("Unexpected import file format: " + fileFormat);
            }
        } finally {
            Closer.close(is);
        }
    }

    System.out.println("Import done");

    return 0;
}

From source file:net.exclaimindustries.paste.braket.client.ui.CreateTournamentDialog.java

@UiHandler("saveButton")
void saveMe(ClickEvent event) {

    try {/*from   w  w w  .  j a v a  2  s.  co m*/
        saveButton.setEnabled(false);

        final Tournament tournament = new Tournament();
        // Easy stuff first
        tournament.setName(name.getText());
        tournament.setUpsetValue(Double.valueOf(upset.getText()));
        tournament.setBuyInValue(Double.valueOf(buyIn.getText()));

        // Parse the game mask
        String gmString = gameMask.getText();
        BigInteger gm = BigInteger.ZERO;
        for (int i = gmString.length() - 1; i >= 0; --i) {
            if (gmString.charAt(i) == '1') {
                gm = gm.setBit(i);
            }
        }
        tournament.setGameMask(gm);

        // Parse the payouts
        Splitter splitter = Splitter.on(',').trimResults().omitEmptyStrings();
        Iterable<String> poSplit = splitter.split(payOut.getText());

        LinkedList<Double> po = new LinkedList<Double>();
        for (String poValue : poSplit) {
            if (poValue.toLowerCase().equals("null")) {
                po.add(null);
            } else {
                po.add(Double.valueOf(poValue));
            }
        }
        tournament.setPayOutValues(po);

        // Parse the round values
        Iterable<String> rvSplit = splitter.split(roundValues.getText());

        LinkedList<Double> rv = new LinkedList<Double>();
        for (String rvValue : rvSplit) {
            rv.add(Double.valueOf(rvValue));
        }
        tournament.setRoundValues(rv);

        tournament.setStartTime(dateBox.getValue());

        // BraketEntryPoint.tournaService.storeTournament(tournament,
        // new AsyncCallback<Long>() {
        //
        // @Override
        // public void onFailure(Throwable caught) {
        // BraketEntryPoint.displayException(caught);
        // }
        //
        // @Override
        // public void onSuccess(Long result) {
        //
        // BraketEntryPoint
        // .displayToast("Tournament successfully created.");
        //
        // hide();
        // resetValues();
        // }
        //
        // });
    } catch (Throwable caught) {
        // BraketEntryPoint.displayException(caught);
    }
}

From source file:com.appdynamics.extensions.redis.RedisMonitorTask.java

private void setKeySpaceMetrics(Map<String, String> metrics, String key, String metricPath, String value) {
    for (String keyspace : server.getKeyspaces()) {
        if (keyspace.equals(key)) {
            logger.debug("gathering stats for keyspace " + keyspace);
            Splitter metricsSplitter = Splitter.on(COMMA_SEPARATOR).trimResults();
            String keySpaceMetricPath = metricPath + METRIC_SEPARATOR;
            for (String metric : metricsSplitter.split(value)) {
                String[] keyValue = metric.split(EQUALS_SEPARATOR);
                metrics.put(keySpaceMetricPath + keyValue[0].trim(), keyValue[1].trim());
            }/*from   ww w. j  a  v  a  2s.com*/
        }
    }
}

From source file:com.lithium.flow.config.AbstractConfig.java

@Override
@Nonnull//from  ww w  .  j  a va 2  s  . c om
public final List<String> getList(@Nonnull String key, @Nonnull List<String> def, @Nonnull Splitter splitter) {
    checkNotNull(key);
    checkNotNull(def);
    checkNotNull(splitter);

    if (containsKey(key)) {
        Iterable<String> split = splitter.split(getString(key));
        return Lists.newArrayList(split).stream().filter(item -> item.length() > 0).collect(toList());
    } else {
        return Lists.newArrayList(def);
    }
}

From source file:com.eucalyptus.util.WildcardNameMatcher.java

private Pattern buildPattern(final String patternList) {
    if (!patternList.trim().isEmpty()) {
        final Splitter splitter = Splitter.on(CharMatcher.WHITESPACE.or(CharMatcher.anyOf(",;|"))).trimResults()
                .omitEmptyStrings();/* ww w.  j a v a 2 s  .  com*/
        final StringBuilder builder = new StringBuilder();
        builder.append("(");
        for (final String nameWithWildcards : splitter.split(patternList)) {
            builder.append(toPattern(nameWithWildcards));
            builder.append('|');
        }
        builder.append(PATTERN_DEFAULT);
        builder.append(")");
        return Pattern.compile(builder.toString());

    }
    return PATTERN_DEFAULT_COMPILED;
}

From source file:com.eucalyptus.context.ContextWireTapMessageSelector.java

private Pattern buildPattern(final String patternSource) {
    if (!patternSource.trim().isEmpty()) {
        final Splitter splitter = Splitter.on(CharMatcher.WHITESPACE.or(CharMatcher.anyOf(",;|"))).trimResults()
                .omitEmptyStrings();/*from   w w  w  . jav  a  2 s.c om*/
        final StringBuilder builder = new StringBuilder();
        builder.append("(");
        for (final String nameWithWildcards : splitter.split(patternSource)) {
            builder.append(toPattern(nameWithWildcards));
            builder.append('|');
        }
        builder.append(PATTERN_DEFAULT);
        builder.append(")");
        return Pattern.compile(builder.toString());

    }
    return PATTERN_DEFAULT_COMPILED;
}

From source file:com.google.publicalerts.cap.validator.PshbServlet.java

private void sendMail(String toAddress, String topic, String msg, Set<CapProfile> profiles,
        ValidationResult result) {/* w  w  w .ja  va2 s . c o  m*/
    Properties props = new Properties();
    Session session = Session.getDefaultInstance(props, null);
    MimeMessage message = new MimeMessage(session);
    try {
        message.setFrom(new InternetAddress("admin@cap-validator.appspotmail.com", "CAP Validator"));
        Splitter splitter = Splitter.on(",").trimResults().omitEmptyStrings();
        for (String address : splitter.split(toAddress)) {
            message.addRecipient(Message.RecipientType.TO, new InternetAddress(address));
        }
        message.setSubject("CAP Validator: Invalid CAP alerts from " + topic);
        message.setText(msg, "UTF-8", "html");
        log.info("about to send email to: " + toAddress);
        mailSender.sendMail(message);
    } catch (MessagingException e) {
        String err = "Could not send mail to: " + toAddress + " Message:" + e.getMessage();
        log.log(Level.SEVERE, err, e);
    } catch (UnsupportedEncodingException e) {
        String err = "Could not send mail to: " + toAddress + " Message:" + e.getMessage();
        log.log(Level.SEVERE, err, e);
    }
}