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

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

Introduction

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

Prototype

public static String substringBefore(final String str, final String separator) 

Source Link

Document

Gets the substring before the first occurrence of a separator.

Usage

From source file:io.gromit.geolite2.geonames.CountryFinder.java

/**
 * Read countries.//from  w w  w  . ja  v  a 2 s . c  om
 *
 * @param countriesLocationUrl the countries location url
 * @return the country finder
 */
private CountryFinder readCountries(String countriesLocationUrl) {
    ZipInputStream zipis = null;
    try {
        zipis = new ZipInputStream(new URL(countriesLocationUrl).openStream(), Charset.forName("UTF-8"));
        ZipEntry zipEntry = zipis.getNextEntry();
        logger.info("reading " + zipEntry.getName());
        if (crc == zipEntry.getCrc()) {
            logger.info("skipp, same CRC");
            return this;
        }

        CsvParserSettings settings = new CsvParserSettings();
        settings.setSkipEmptyLines(true);
        settings.trimValues(true);
        CsvFormat format = new CsvFormat();
        format.setDelimiter('\t');
        format.setLineSeparator("\n");
        format.setCharToEscapeQuoteEscaping('\0');
        format.setQuote('\0');
        settings.setFormat(format);
        CsvParser parser = new CsvParser(settings);

        List<String[]> lines = parser.parseAll(new InputStreamReader(zipis, "UTF-8"));

        for (String[] entry : lines) {
            Country country = new Country();
            country.setIso(entry[0]);
            country.setIso3(entry[1]);
            country.setName(entry[2]);
            country.setCapital(entry[3]);
            country.setContinent(entry[4]);
            country.setCurrencyCode(entry[5]);
            country.setCurrencyName(entry[6]);
            country.setPhone(entry[7]);
            country.setLanguage(StringUtils.substringBefore(entry[8], ","));
            country.setGeonameId(NumberUtils.toInt(entry[9]));
            geonameMap.put(country.getGeonameId(), country);
            isoMap.put(country.getIso(), country);
        }
    } catch (Exception e) {
        throw new RuntimeException(e);
    } finally {
        try {
            zipis.close();
        } catch (Exception e) {
        }
        ;
    }
    logger.info("loaded " + geonameMap.size() + " countries");
    return this;
}

From source file:com.netflix.spinnaker.halyard.deploy.spinnaker.v1.profile.DeckProfile.java

@Override
public ProfileConfig generateFullConfig(ProfileConfig config, DeploymentConfiguration deploymentConfiguration,
        SpinnakerEndpoints endpoints) {/*www  . ja  va  2s .  c o  m*/
    StringResource configTemplate = new StringResource(config.getPrimaryConfigContents());

    // Configure apache2
    JarResource spinnakerConfTemplate = new JarResource("/apache2/spinnaker.conf");
    JarResource portsConfTemplate = new JarResource("/apache2/ports.conf");
    Map<String, String> bindings = new HashMap<>();
    bindings.put("deck-host", endpoints.getServices().getDeck().getHost());
    bindings.put("deck-port", endpoints.getServices().getDeck().getPort() + "");

    config.extendConfig("apache2/spinnaker.conf", spinnakerConfTemplate.setBindings(bindings).toString());
    config.extendConfig("apache2/ports.conf", portsConfTemplate.setBindings(bindings).toString());

    Features features = deploymentConfiguration.getFeatures();

    bindings = new HashMap<>();
    // Configure global settings
    bindings.put("gate.baseUrl", endpoints.getServices().getGate().getPublicEndpoint());
    bindings.put("timezone", deploymentConfiguration.getTimezone());

    // Configure feature-flags
    bindings.put("features.auth", Boolean.toString(features.isAuth(deploymentConfiguration)));
    bindings.put("features.chaos", Boolean.toString(features.isChaos()));
    bindings.put("features.fiat", Boolean.toString(features.isFiat()));
    bindings.put("features.jobs", Boolean.toString(features.isJobs()));

    // Configure Kubernetes
    KubernetesProvider kubernetesProvider = deploymentConfiguration.getProviders().getKubernetes();
    bindings.put("kubernetes.default.account", kubernetesProvider.getPrimaryAccount());
    bindings.put("kubernetes.default.namespace", "default");
    bindings.put("kubernetes.default.proxy", "localhost:8001");

    // Configure GCE
    GoogleProvider googleProvider = deploymentConfiguration.getProviders().getGoogle();
    bindings.put("google.default.account", googleProvider.getPrimaryAccount());
    bindings.put("google.default.region", "us-central1");
    bindings.put("google.default.zone", "us-central1-f");

    // Configure Appengine
    AppengineProvider appengineProvider = deploymentConfiguration.getProviders().getAppengine();
    bindings.put("appengine.default.account", appengineProvider.getPrimaryAccount());
    bindings.put("appengine.enabled", Boolean.toString(appengineProvider.getPrimaryAccount() != null));

    // Configure Openstack
    OpenstackProvider openstackProvider = deploymentConfiguration.getProviders().getOpenstack();
    bindings.put("openstack.default.account", openstackProvider.getPrimaryAccount());
    if (openstackProvider.getPrimaryAccount() != null) {
        OpenstackAccount openstackAccount = (OpenstackAccount) accountService.getProviderAccount(
                deploymentConfiguration.getName(), "openstack", openstackProvider.getPrimaryAccount());
        //Regions in openstack are a comma separated list. Use the first as primary.
        String firstRegion = StringUtils.substringBefore(openstackAccount.getRegions(), ",");
        bindings.put("openstack.default.region", firstRegion);
    }

    config.setConfig(config.getPrimaryConfigFile(), configTemplate.setBindings(bindings).toString());
    return config;
}

From source file:io.wcm.tooling.commons.contentpackagebuilder.ContentPackage.java

/**
 * Adds a binary file with explicit mime type.
 * @param path Full content path and file name of file
 * @param inputStream Input stream with binary data
 * @param contentType Mime type, optionally with ";charset=XYZ" extension
 * @throws IOException//  w w  w.j  av  a2  s .c o m
 */
public void addFile(String path, InputStream inputStream, String contentType) throws IOException {
    String fullPath = buildJcrPathForZip(path);
    writeBinaryFile(fullPath, inputStream);

    if (StringUtils.isNotEmpty(contentType)) {
        String mimeType = StringUtils.substringBefore(contentType, CONTENT_TYPE_CHARSET_EXTENSION);
        String encoding = StringUtils.substringAfter(contentType, CONTENT_TYPE_CHARSET_EXTENSION);

        String fullPathMetadata = fullPath + ".dir/.content.xml";
        Document doc = xmlContentBuilder.buildNtFile(mimeType, encoding);
        writeXmlDocument(fullPathMetadata, doc);
    }
}

From source file:com.norconex.commons.lang.url.QueryString.java

/**
 * Apply this url QueryString on the given URL. If a query string already
 * exists, it is replaced by this one./*from  w ww. ja v  a  2  s .c om*/
 * @param url the URL to apply this query string.
 * @return url with query string added
 */
public String applyOnURL(String url) {
    if (StringUtils.isBlank(url)) {
        return url;
    }
    return StringUtils.substringBefore(url, "?") + toString();
}

From source file:com.thruzero.common.core.utils.ExceptionUtilsExt.java

public static String findMethodAtClassFromTrace(final Class<?> clazz) {
    String result = findTraceAt(clazz);
    result = StringUtils.substringBefore(result, "(");
    return StringUtils.substringAfterLast(result, ".");
}

From source file:com.eryansky.common.web.struts2.utils.Struts2Utils.java

/**
 * ?contentTypeheaders./*from w  w w.  ja v  a2s.c o m*/
 */
private static HttpServletResponse initResponseHeader(final String contentType, final String... headers) {
    //?headers?
    String encoding = DEFAULT_ENCODING;
    boolean noCache = DEFAULT_NOCACHE;
    for (String header : headers) {
        String headerName = StringUtils.substringBefore(header, ":");
        String headerValue = StringUtils.substringAfter(header, ":");

        if (StringUtils.equalsIgnoreCase(headerName, HEADER_ENCODING)) {
            encoding = headerValue;
        } else if (StringUtils.equalsIgnoreCase(headerName, HEADER_NOCACHE)) {
            noCache = Boolean.parseBoolean(headerValue);
        } else {
            throw new IllegalArgumentException(headerName + "??header");
        }
    }

    HttpServletResponse response = ServletActionContext.getResponse();

    //headers?
    String fullContentType = contentType + ";charset=" + encoding;
    response.setContentType(fullContentType);
    if (noCache) {
        ServletUtils.setDisableCacheHeader(response);
    }

    return response;
}

From source file:com.mgmtp.jfunk.data.generator.data.GeneratorDataSource.java

/**
 * {@inheritDoc}/*from  w  w w . j  av a2  s .  c o  m*/
 * 
 * @return Always returns {@code true} for known data set keys, because new data is generated
 *         upon request.
 */
@Override
public boolean hasMoreData(final String dataSetKey) {
    if (dataSetKeys.isEmpty()) {
        // Fill set of known data set keys
        for (String constraintId : getGenerator().getConstraintIds()) {
            if (constraintId != null && constraintId.endsWith(".all")) {
                String key = StringUtils.substringBefore(constraintId, "." + GeneratorConstants.ALL_CONSTRAINT);
                dataSetKeys.add(key);
            }
        }
    }
    return dataSetKeys.contains(dataSetKey);
}

From source file:org.openscore.lang.compiler.modeller.TransformersHandler.java

private String keyToTransform(Transformer transformer) {
    String key;/*  ww  w .  java 2s .c  o m*/
    if (transformer.keyToTransform() != null) {
        key = transformer.keyToTransform();
    } else {
        String simpleClassName = transformer.getClass().getSimpleName();
        key = StringUtils.substringBefore(simpleClassName, Transformer.class.getSimpleName());
    }
    return key.toLowerCase();
}

From source file:eu.openanalytics.rsb.data.FileResultStore.java

private File getResultFile(final String applicationName, final String userName, final UUID jobId) {
    final String jobIdAsString = jobId.toString();
    final File[] resultFiles = getResultsDirectory(applicationName, userName).listFiles(new FilenameFilter() {
        public boolean accept(final File dir, final String name) {
            return jobIdAsString.equals(StringUtils.substringBefore(name, "."));
        }//  ww  w  . jav a 2s  . c om
    });

    if ((resultFiles == null) || (resultFiles.length == 0)) {
        return null;
    }

    if (resultFiles.length > 1) {
        throw new IllegalStateException("Found " + resultFiles.length + " results for job Id: " + jobId);
    }

    return resultFiles[0];
}

From source file:com.founder.fix.fixflow.explorer.util.ResultUtils.java

/**
 * ?contentTypeheaders./* w  ww .j av a2 s  . c o m*/
 */
private HttpServletResponse initResponseHeader(final String contentType, final String... headers) {
    // ?headers?
    String encoding = DEFAULT_ENCODING;
    boolean noCache = DEFAULT_NOCACHE;
    for (String header : headers) {
        String headerName = StringUtils.substringBefore(header, ":");
        String headerValue = StringUtils.substringAfter(header, ":");

        if (StringUtils.equalsIgnoreCase(headerName, HEADER_ENCODING)) {
            encoding = headerValue;
        } else if (StringUtils.equalsIgnoreCase(headerName, HEADER_NOCACHE)) {
            noCache = Boolean.parseBoolean(headerValue);
        } else {
            throw new IllegalArgumentException(headerName + "??header");
        }
    }

    // headers?
    String fullContentType = contentType + ";charset=" + encoding;
    response.setContentType(fullContentType);
    if (noCache) {
        setDisableCacheHeader(response);
    }

    return response;
}