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:beans.WidgetServerImpl.java

@PostConstruct
public void init() {
    Utils.addAllTrimmed(filterOutputLines, StringUtils.split(conf.cloudify.removeOutputLines, "|"));
    Utils.addAllTrimmed(filterOutputStrings, StringUtils.split(conf.cloudify.removeOutputString, "|"));
}

From source file:com.threewks.thundr.view.negotiating.strategy.AcceptsHeaderNegotiationStrategy.java

private List<AcceptsComponent> cleanAndOrderAcceptHeader(String acceptsHeader) {
    List<AcceptsComponent> components = new ArrayList<AcceptsComponent>();
    for (String component : StringUtils.split(acceptsHeader, ",")) {
        components.add(new AcceptsComponent(ViewNegotiatorRegistryImpl.normaliseContentType(component)));
    }//from   w  w w.  j av a 2  s  .  c  o  m
    Collections.sort(components, AcceptsComponent.Comparator);
    return components;
}

From source file:com.ethlo.geodata.util.ResourceUtil.java

private Resource openConnection(String urlStr) throws IOException {
    final String[] urlParts = StringUtils.split(urlStr, "|");

    if (urlStr.startsWith("file:")) {
        String path = urlParts[0].substring(7);
        if (path.startsWith("~" + File.separator)) {
            path = System.getProperty("user.home") + path.substring(1);
        }//from w ww  .  ja  va 2s.c o  m
        final File file = new File(path);
        if (!file.exists()) {
            throw new FileNotFoundException(file.getAbsolutePath());
        }
        return new FileSystemResource(file);
    } else if (urlStr.startsWith("classpath:")) {
        return new ClassPathResource(urlParts[0].substring(10));
    }

    return new UrlResource(urlParts[0]);
}

From source file:com.netflix.hystrix.contrib.javanica.cache.HystrixCacheKeyGenerator.java

public HystrixGeneratedCacheKey generateCacheKey(
        CacheInvocationContext<? extends Annotation> cacheInvocationContext)
        throws HystrixCacheKeyGenerationException {
    MethodExecutionAction cacheKeyMethod = cacheInvocationContext.getCacheKeyMethod();
    if (cacheKeyMethod != null) {
        try {//from   w  w  w  . java  2  s  .co  m
            return new DefaultHystrixGeneratedCacheKey(
                    (String) cacheKeyMethod.execute(cacheInvocationContext.getExecutionType()));
        } catch (Throwable throwable) {
            throw new HystrixCacheKeyGenerationException(throwable);
        }
    } else {
        if (cacheInvocationContext.hasKeyParameters()) {
            StringBuilder cacheKeyBuilder = new StringBuilder();
            for (CacheInvocationParameter parameter : cacheInvocationContext.getKeyParameters()) {
                CacheKey cacheKey = parameter.getCacheKeyAnnotation();
                if (cacheKey != null && StringUtils.isNotBlank(cacheKey.value())) {
                    appendPropertyValue(cacheKeyBuilder,
                            Arrays.asList(StringUtils.split(cacheKey.value(), ".")), parameter.getValue());
                } else {
                    cacheKeyBuilder.append(parameter.getValue());
                }
            }
            return new DefaultHystrixGeneratedCacheKey(cacheKeyBuilder.toString());
        } else {
            return DefaultHystrixGeneratedCacheKey.EMPTY;
        }
    }
}

From source file:ca.simplegames.micro.extensions.i18n.I18NExtension.java

public Extension register(String name, SiteContext site, Map<String, Object> locales) throws Exception {
    Assert.notNull(name, "The name of the extension must not be null!");
    this.name = StringUtils.defaultIfBlank(name, "i18N");

    if (locales != null) {
        Map interceptConfig = (Map<String, Object>) locales.get("intercept");

        if (interceptConfig != null) {
            intercept = StringUtils.defaultString((String) interceptConfig.get("parameter_name"), "lang");
            scopesSrc = StringUtils.defaultString((String) interceptConfig.get("scope"), "context");
            scopes = StringUtils.split(scopesSrc, ",");
        }/*from w  w w  .j  a v  a  2s . c  o m*/

        defaultEncoding = StringUtils.defaultString((String) locales.get("default_encoding"), Globals.UTF8);
        fallbackToSystemLocale = locales.get("fallback_to_system_locale") != null
                ? (Boolean) locales.get("fallback_to_system_locale")
                : true;

        resourceCacheRefreshInterval = Integer
                .parseInt(StringUtils.defaultString((locales.get("resource_cache")).toString(), "10"));

        List<String> paths = (List<String>) locales.get("base_names");
        if (paths != null && !paths.isEmpty()) {
            List<String> absPaths = new ArrayList<String>();

            for (String path : paths) {
                File realPath = new File(path);
                if (!realPath.exists()) {
                    realPath = new File(site.getWebInfPath().getAbsolutePath(), path);
                }

                try {
                    absPaths.add(realPath.toURI().toURL().toString());
                    //absPaths.add(pathConfig.getValue());
                } catch (MalformedURLException e) {
                    e.printStackTrace();
                }
            }
            resourceBasePaths = absPaths.toArray(new String[absPaths.size()]);
        } else {
            resourceBasePaths = new String[] { "config/locales/messages" };
        }

        //Configure the i18n
        messageSource = new ReloadableResourceBundleMessageSource();
        messageSource.setDefaultEncoding(defaultEncoding);
        messageSource.setFallbackToSystemLocale(fallbackToSystemLocale);
        messageSource.setCacheSeconds(resourceCacheRefreshInterval);
        messageSource.setBasenames(resourceBasePaths);

        Filter i18N = new I18NFilter(this);
        final FilterManager filterManager = site.getFilterManager();

        filterManager.addFilter(i18N);
        // now make sure the i18N filter is always first (if present)
        Collections.swap(filterManager.getBeforeFilters(), 0, filterManager.getBeforeFilters().size() - 1);

        infoDetails.add(String.format("  default encoding ........: %s", defaultEncoding));
        infoDetails.add(String.format("  fallback to system locale: %s", fallbackToSystemLocale));
        infoDetails.add(String.format("  cache refresh ...........: %s", resourceCacheRefreshInterval));
        infoDetails.add(String.format("  resource bundle .........: %s", Arrays.toString(resourceBasePaths)));
        infoDetails.add(String.format("  Listening for ...........: '%s'", intercept));
        infoDetails.add(String.format("       in scope(s) ........: %s", scopesSrc));
    }

    return this;
}

From source file:com.qcadoo.mes.basic.shift.WorkingHours.java

private Set<TimeRange> parseIntervals(final String hoursRanges) {
    if (StringUtils.isBlank(hoursRanges)) {
        return Collections.emptySet();
    }//from w w w.  j av  a  2 s .c om
    String trimmedHoursRanges = StringUtils.remove(hoursRanges, ' ');
    if (!WORKING_HOURS_PATTERN.matcher(trimmedHoursRanges).matches()) {
        throw new IllegalArgumentException(
                String.format("Invalid shift's work time definition format: %s", hoursRanges));
    }
    final Set<TimeRange> intervals = Sets.newHashSet();
    for (String hoursRange : StringUtils.split(trimmedHoursRanges, ',')) {
        TimeRange interval = stringToInterval(hoursRange);
        if (interval != null) {
            intervals.add(interval);
        }
    }
    return intervals;
}

From source file:com.whatlookingfor.modules.sys.utils.DictUtils.java

/**
 * ??type?value???/*from w  w w . j a  va  2s  .  c  o m*/
 * @param values
 * @param type
 * @param defaultValue
 * @return
 */
public static String getDictLabels(String values, String type, String defaultValue) {
    if (StringUtils.isNotBlank(type) && StringUtils.isNotBlank(values)) {
        List<String> valueList = Lists.newArrayList();
        for (String value : StringUtils.split(values, ",")) {
            valueList.add(getDictLabel(value, type, defaultValue));
        }
        return StringUtils.join(valueList, ",");
    }
    return defaultValue;
}

From source file:com.mirth.connect.plugins.datatypes.hl7v2.HL7v2ResponseValidator.java

@Override
public Response validate(Response response, ConnectorMessage connectorMessage) {
    HL7v2ResponseValidationProperties responseValidationProperties = getReplacedResponseValidationProperties(
            connectorMessage);//from  ww  w . j  ava  2s  .c  om
    String[] successfulACKCodes = StringUtils.split(responseValidationProperties.getSuccessfulACKCode(), ',');
    String[] errorACKCodes = StringUtils.split(responseValidationProperties.getErrorACKCode(), ',');
    String[] rejectedACKCodes = StringUtils.split(responseValidationProperties.getRejectedACKCode(), ',');
    boolean validateMessageControlId = responseValidationProperties.isValidateMessageControlId();

    String responseData = response.getMessage();

    if (StringUtils.isNotBlank(responseData)) {
        try {
            if (responseData.trim().startsWith("<")) {
                // XML response received
                Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder()
                        .parse(new InputSource(new CharArrayReader(responseData.toCharArray())));
                String ackCode = XPathFactory.newInstance().newXPath().compile("//MSA.1/text()").evaluate(doc)
                        .trim();

                boolean rejected = Arrays.asList(rejectedACKCodes).contains(ackCode);
                boolean error = rejected || Arrays.asList(errorACKCodes).contains(ackCode);

                if (error || rejected) {
                    String msa3 = StringUtils.trim(
                            XPathFactory.newInstance().newXPath().compile("//MSA.3/text()").evaluate(doc));
                    String err1 = StringUtils.trim(
                            XPathFactory.newInstance().newXPath().compile("//ERR.1/text()").evaluate(doc));
                    handleNACK(response, rejected, msa3, err1);
                } else if (Arrays.asList(successfulACKCodes).contains(ackCode)) {
                    if (validateMessageControlId) {
                        String msa2 = StringUtils.trim(
                                XPathFactory.newInstance().newXPath().compile("//MSA.2/text()").evaluate(doc));
                        String originalControlID = getOriginalControlId(connectorMessage);

                        if (!StringUtils.equals(msa2, originalControlID)) {
                            handleInvalidControlId(response, originalControlID, msa2);
                        } else {
                            response.setStatus(Status.SENT);
                        }
                    } else {
                        response.setStatus(Status.SENT);
                    }
                }
            } else {
                // ER7 response received
                if (serializationProperties.isConvertLineBreaks()) {
                    responseData = StringUtil.convertLineBreaks(responseData, serializationSegmentDelimiter);
                }

                int index = -1;
                boolean valid = true;

                // Attempt to find the MSA segment using the segment delimiters in the serialization properties
                if ((index = responseData.indexOf(serializationSegmentDelimiter + "MSA")) >= 0) {
                    // MSA found; add the length of the segment delimiter, MSA, and field separator to get to the index of MSA.1
                    index += serializationSegmentDelimiter.length() + 4;

                    if (index < responseData.length()) {
                        boolean rejected = startsWithAny(responseData, rejectedACKCodes, index);
                        boolean error = rejected || startsWithAny(responseData, errorACKCodes, index);

                        char fieldSeparator = responseData.charAt(index - 1);
                        if (error || rejected) {
                            String msa3 = null;
                            String err1 = null;

                            // Index of MSA.2
                            index = responseData.indexOf(fieldSeparator, index);
                            if (index >= 0) {
                                // Index of MSA.3
                                index = responseData.indexOf(fieldSeparator, index + 1);
                                if (index >= 0) {
                                    // Find the next index of either the field separator or segment delimiter, and then the resulting substring
                                    String tempSegment = StringUtils.substring(responseData, index + 1);
                                    index = StringUtils.indexOfAny(tempSegment,
                                            fieldSeparator + serializationSegmentDelimiter);

                                    if (index >= 0) {
                                        msa3 = StringUtils.substring(tempSegment, 0, index);
                                    } else {
                                        msa3 = StringUtils.substring(tempSegment, 0);
                                    }
                                }
                            }

                            if ((index = responseData.indexOf(serializationSegmentDelimiter + "ERR")) >= 0) {
                                // ERR found; add the length of the segment delimiter, ERR, and field separator to get to the index of ERR.1
                                index += serializationSegmentDelimiter.length() + 4;
                                // Find the next index of either the field separator or segment delimiter, and then the resulting substring
                                String tempSegment = StringUtils.substring(responseData, index);
                                index = StringUtils.indexOfAny(tempSegment,
                                        fieldSeparator + serializationSegmentDelimiter);

                                if (index >= 0) {
                                    err1 = StringUtils.substring(tempSegment, 0, index);
                                } else {
                                    err1 = StringUtils.substring(tempSegment, 0);
                                }
                            }

                            handleNACK(response, rejected, msa3, err1);
                        } else if (startsWithAny(responseData, successfulACKCodes, index)) {
                            if (validateMessageControlId) {
                                String msa2 = "";
                                index = responseData.indexOf(fieldSeparator, index);

                                if (index >= 0) {
                                    String tempSegment = StringUtils.substring(responseData, index + 1);
                                    index = StringUtils.indexOfAny(tempSegment,
                                            fieldSeparator + serializationSegmentDelimiter);

                                    if (index >= 0) {
                                        msa2 = StringUtils.substring(tempSegment, 0, index);
                                    } else {
                                        msa2 = StringUtils.substring(tempSegment, 0);
                                    }
                                }
                                String originalControlID = getOriginalControlId(connectorMessage);

                                if (!StringUtils.equals(msa2, originalControlID)) {
                                    handleInvalidControlId(response, originalControlID, msa2);
                                } else {
                                    response.setStatus(Status.SENT);
                                }
                            } else {
                                response.setStatus(Status.SENT);
                            }
                        } else {
                            valid = false;
                        }
                    } else {
                        valid = false;
                    }
                } else {
                    valid = false;
                }

                if (!valid) {
                    response.setStatus(Status.QUEUED);
                    response.setStatusMessage("Invalid HL7 v2.x acknowledgement received.");
                    response.setError(response.getStatusMessage());
                }
            }
        } catch (Exception e) {
            response.setStatus(Status.QUEUED);
            response.setStatusMessage("Error validating response: " + e.getMessage());
            response.setError(ErrorMessageBuilder.buildErrorMessage(this.getClass().getSimpleName(),
                    response.getStatusMessage(), e));
        }
    } else {
        response.setStatus(Status.QUEUED);
        response.setStatusMessage("Empty or blank response received.");
        response.setError(response.getStatusMessage());
    }

    return response;
}

From source file:com.ebuddy.cassandra.test.AbstractCassandraThriftSystemTest.java

@BeforeMethod(alwaysRun = true)
public void setUp() throws Exception {
    // default to using cassandra on localhost, but can be overridden with a system property
    String cassandraHosts = System.getProperty(CASSANDRA_HOSTS_SYSTEM_PROPERTY, EMBEDDED_CASSANDRA_HOST);
    String[] hosts = StringUtils.split(cassandraHosts, ",");
    numHosts = hosts.length;/*from  w  w  w. j  a v a  2 s .co m*/

    if (EMBEDDED_CASSANDRA_HOST.equals(cassandraHosts)) {
        EmbeddedCassandraServerHelper.startEmbeddedCassandra();
    }

    // default cluster name can also be overridden with a system property
    String clusterName = System.getProperty(CLUSTER_NAME_PROPERTY, TEST_CLUSTER);

    hostConfigurator = new CassandraHostConfigurator(cassandraHosts);
    cluster = HFactory.getOrCreateCluster(clusterName, hostConfigurator);
    keyspace = HFactory.createKeyspace(TEST_KEYSPACE, cluster);

    dropAndCreateSchema();
    sleepAfterSchemaChangeIfNecessary();
}

From source file:io.wcm.devops.conga.plugins.sling.fileheader.OsgiConfigFileHeader.java

@Override
public FileHeaderContext extract(FileContext file) {
    try {/*from w  ww.ja va  2 s  .  c  o  m*/
        String content = FileUtils.readFileToString(file.getFile(), file.getCharset());
        String[] contentLines = StringUtils.split(content, "\n");
        if (contentLines.length > 0 && StringUtils.startsWith(contentLines[0], getCommentLinePrefix())) {
            String fullComment = StringUtils
                    .trim(StringUtils.substringAfter(contentLines[0], getCommentBlockStart()));
            List<String> lines = ImmutableList.of(fullComment);
            return new FileHeaderContext().commentLines(lines);
        }
    } catch (IOException ex) {
        throw new GeneratorException("Unable parse add file header from " + file.getCanonicalPath(), ex);
    }
    return null;
}