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

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

Introduction

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

Prototype

public static boolean startsWith(final CharSequence str, final CharSequence prefix) 

Source Link

Document

Check if a CharSequence starts with a specified prefix.

null s are handled without exceptions.

Usage

From source file:annis.test.CsvResultSetProvider.java

public Object[] getArrayValue(int column, int sqlType) {
    String str = getStringValue(column);
    if (StringUtils.startsWith(str, "{") && StringUtils.endsWith(str, "}")) {
        String stripped = str.substring(1, str.length() - 1);
        String[] split = stripped.split(",");

        if (sqlType == Types.BIGINT) {
            Long[] result = new Long[split.length];
            for (int i = 0; i < result.length; i++) {
                try {
                    result[i] = Long.parseLong(split[i]);
                } catch (NumberFormatException ex) {
                    log.error(null, ex);
                }//  w w  w  .j ava 2 s  . c  o  m
            }
            return result;
        } else {
            // just return the string if requested so
            return split;
        }
    }

    return null;
}

From source file:gobblin.util.ConfigUtils.java

/**
 * Convert all the keys that start with a <code>prefix</code> in {@link Properties} to a
 * {@link Config} instance. The method also tries to guess the types of properties.
 *
 * <p>//ww w . ja  v  a2  s.  co m
 *   This method will throw an exception if (1) the {@link Object#toString()} method of any two keys in the
 *   {@link Properties} objects returns the same {@link String}, or (2) if any two keys are prefixes of one another,
 *   see the Java Docs of {@link ConfigFactory#parseMap(Map)} for more details.
 * </p>
 *
 * @param properties the given {@link Properties} instance
 * @param prefix of keys to be converted
 * @return a {@link Config} instance
 */
public static Config propertiesToTypedConfig(Properties properties, Optional<String> prefix) {
    Map<String, Object> typedProps = guessPropertiesTypes(properties);
    ImmutableMap.Builder<String, Object> immutableMapBuilder = ImmutableMap.builder();
    for (Map.Entry<String, Object> entry : typedProps.entrySet()) {
        if (StringUtils.startsWith(entry.getKey(), prefix.or(StringUtils.EMPTY))) {
            immutableMapBuilder.put(entry.getKey(), entry.getValue());
        }
    }
    return ConfigFactory.parseMap(immutableMapBuilder.build());
}

From source file:com.adguard.commons.web.UrlUtils.java

/**
 * Extracts domain name from the url. Also crops www.
 *
 * @param url url//w w  w. ja  v a2 s.c  om
 * @return domain name
 */
public static String getDomainName(String url) {
    if (StringUtils.isEmpty(url)) {
        return null;
    }

    try {
        if (!StringUtils.startsWith(url, "http://") && !StringUtils.startsWith(url, "https://")) {
            url = "http://" + url;
        }
        return getDomainName(new URL(url));
    } catch (MalformedURLException ex) {
        return null;
    }
}

From source file:io.treefarm.plugins.haxe.components.OpenFLCompiler.java

private List<String> getStandardArgumentsList(String nmml, String targetString, String buildDir, String appMain,
        String appFile, List<String> additionalArguments) {
    List<String> list = new ArrayList<String>();
    list.add(nmml);//from  w  ww  . j  a  v a2s .  c o m
    list.add(targetString);
    list.add("--app-path=" + buildDir);
    if (appMain != null) {
        list.add("--app-main=" + appMain);
    }
    if (appFile != null) {
        list.add("--app-file=" + appFile);
    }
    if (debug) {
        list.add("-debug");
        list.add("--haxeflag='-D log'");
    }
    if (verbose) {
        list.add("-verbose");
    }

    if (additionalArguments != null) {
        List<String> compilerArgs = new ArrayList<String>();
        for (String arg : additionalArguments) {
            if (StringUtils.startsWith(arg, "--macro ")) {
                compilerArgs.add(StringUtils.replace(arg, "--macro ", "--macro="));
            } else {
                String haxeFlag = "--haxeflag='" + arg + "'";
                compilerArgs.add(haxeFlag);
            }
        }
        list.addAll(compilerArgs);
    }
    return list;
}

From source file:eionet.webq.web.controller.WebQProxyDelegation.java

/**
 * This method delegates multipart POST request to remote host using authorisation stored in UserFile.
 *
 * @param uri     the actual uri to make the request
 * @param body    body request body to forward to remote host
 * @param fileId  user session file id/*from  w  w  w  .java 2 s.c o  m*/
 * @param request standard HttpServletRequest
 * @return result request results received from uri
 * @throws URISyntaxException        wrong uri of remote file
 * @throws FileNotAvailableException the remote file is not available
 */
@RequestMapping(value = "/restProxyWithAuth", method = RequestMethod.POST, produces = "text/html;charset=utf-8")
@ResponseBody
public String restProxyPostWithAuth(@RequestParam("uri") String uri, @RequestBody String body,
        @RequestParam int fileId, HttpServletRequest request)
        throws URISyntaxException, FileNotAvailableException {

    UserFile file = userFileHelper.getUserFile(fileId, request);

    if (file != null
            && ProxyDelegationHelper.isCompanyIdParameterValidForBdrEnvelope(uri, file.getEnvelope())) {
        if (StringUtils.startsWith(uri, file.getEnvelope())) {
            return envelopeService.submitRequest(file, uri, body);
        } else if (file.isAuthorized()) {
            // check if we have known host in db
            KnownHost knownHost = knownHostsService.getKnownHost(uri);
            if (knownHost != null) {
                if (knownHost.getAuthenticationMethod() == KnownHostAuthenticationMethod.REQUEST_PARAMETER) {
                    // add ticket parameter to request URI if needed
                    LOGGER.info("Add ticket parameter from known hosts to URL: " + uri);
                    uri += (uri.contains("?")) ? "&" : "?";
                    uri += knownHost.getKey() + "=" + knownHost.getTicket();
                } else if (knownHost.getAuthenticationMethod() == KnownHostAuthenticationMethod.BASIC) {
                    // Add basic authorisation if needed
                    HttpHeaders authorization = getHttpHeaderWithBasicAuthentication(knownHost);
                    LOGGER.info("Add basic auth from known hosts to URL: " + uri);
                    HttpEntity<String> httpEntity = new HttpEntity<String>(body, authorization);
                    return new RestTemplate().postForObject(new URI(uri), httpEntity, String.class);
                }
            }
        }
    }
    LOGGER.info("/restProxy [POST] uri=" + uri);
    return restTemplate.postForObject(new URI(uri), body, String.class);
}

From source file:com.bellman.bible.service.device.speak.TextToSpeechController.java

@Override
public void onUtteranceCompleted(String utteranceId) {
    Log.d(TAG, "onUtteranceCompleted:" + utteranceId);
    // pause/rew/ff can sometimes allow old messages to complete so need to prevent move to next sentence if completed utterance is out of date
    if ((!isPaused && isSpeaking) && StringUtils.startsWith(utteranceId, UTTERANCE_PREFIX)) {
        long utteranceNo = Long.valueOf(StringUtils.removeStart(utteranceId, UTTERANCE_PREFIX));
        if (utteranceNo == uniqueUtteranceNo - 1) {
            mSpeakTextProvider.finishedUtterance(utteranceId);

            // estimate cps
            mSpeakTiming.finished(utteranceId);

            // ask TTs to say the text
            if (mSpeakTextProvider.isMoreTextToSpeak()) {
                speakNextChunk();// w ww. jav  a 2  s  . co  m
            } else {
                Log.d(TAG, "Shutting down TTS");
                shutdown();
            }
        }
    }
}

From source file:com.github.ferstl.depgraph.AbstractGraphMojo.java

private StyleResource getCustomStyleResource() throws MojoFailureException {
    StyleResource customStyleResource;/*from  ww  w.  j av  a2  s  .c  o  m*/
    if (StringUtils.startsWith(this.customStyleConfiguration, "classpath:")) {
        String resourceName = StringUtils.substring(this.customStyleConfiguration, 10,
                this.customStyleConfiguration.length());
        customStyleResource = new ClasspathStyleResource(resourceName, getClass().getClassLoader());
    } else {
        customStyleResource = new FileSystemStyleResource(Paths.get(this.customStyleConfiguration));
    }

    if (!customStyleResource.exists()) {
        throw new MojoFailureException(
                "Custom configuration '" + this.customStyleConfiguration + "' does not exist.");
    }

    return customStyleResource;
}

From source file:com.sonicle.webtop.core.app.servlet.ResourceRequest.java

protected LookupResult lookupNoCache(HttpServletRequest req, String reqPath) {
    String subject = null, subjectPath = null, jsPath = null, path = null, targetPath = null;
    boolean isVirtualUrl = false, jsPathFound = false;
    URL targetUrl = null;/*w w  w . ja  va 2 s.  c  o  m*/

    try {
        WebTopApp wta = WebTopApp.get(req);

        // Builds a convenient URL for the servlet relative URL
        try {
            //String reqPath = req.getPathInfo();
            //logger.trace("Requested path [{}]", reqPath);

            Matcher matcher = PATTERN_VIRTUAL_URL.matcher(reqPath);
            if (matcher.matches()) {
                // Matches URLs like: /{service.id}/{service.version}/{remaining.url.part}
                // Eg. /com.sonicle.webtop.core/5.1.1/laf/default/service.css
                //   {service.id} -> com.sonicle.webtop.core
                //   {service.version} -> 5.1.1
                //   {remaining.url.part} -> laf/default/service.css
                isVirtualUrl = true;
                subject = matcher.group(1);
                path = matcher.group(3);

                if (!wta.getServiceManager().hasService(subject)) {
                    return new Error(HttpServletResponse.SC_BAD_REQUEST, "Bad Request");
                }
                targetUrl = new URL("http://fake/client/" + subject + "/" + path);

            } else {
                isVirtualUrl = false;
                String[] urlParts = splitPath(reqPath);
                subject = urlParts[0];
                jsPath = wta.getServiceManager().getServiceJsPath(subject);
                jsPathFound = (jsPath != null);
                subjectPath = (jsPathFound) ? jsPath : urlParts[0];
                path = urlParts[1];

                targetUrl = new URL("http://fake/" + subjectPath + "/" + path);
            }
            targetPath = targetUrl.getPath();

            //logger.trace("Translated path [{}]", translPath);
            if (isForbidden(targetPath))
                return new Error(HttpServletResponse.SC_FORBIDDEN, "Forbidden");

        } catch (MalformedURLException ex1) {
            return new Error(HttpServletResponse.SC_BAD_REQUEST, "Bad Request");
        }

        if (!isVirtualUrl && path.startsWith("images")) {
            // Addresses domain public images
            // URLs like "/{domainPublicName}/images/{relativePathToFile}"
            // Eg.   "/1bbc048f/images/login.png"
            //      "/1bbc048f/images/sub/login.png"
            WebTopManager wtMgr = wta.getWebTopManager();

            String domainId = wtMgr.publicNameToDomainId(subject);
            if (StringUtils.isBlank(domainId)) {
                // We must support old-style URL using {domainInternetName}
                // instead of {domainPublicName}
                // Eg.   "/sonicle.com/images/login.png"
                domainId = wtMgr.internetNameToDomain(subject);
            }
            if (StringUtils.isBlank(domainId)) {
                return new Error(HttpServletResponse.SC_BAD_REQUEST, "Bad Request");
            }

            return lookupDomainImage(req, targetUrl, domainId);

        } else if (isVirtualUrl && subject.equals(CoreManifest.ID)
                && path.equals("resources/images/login.png")) {
            // Addresses login image
            // URLs like "/{serviceId}/{serviceVersion}/resources/images/login.png"
            // Eg.   "/com.sonicle.webtop.core/5.0.0/images/login.png"
            return lookupLoginImage(req, targetUrl);

        } else if (isVirtualUrl && subject.equals(CoreManifest.ID) && path.equals("resources/license.html")) {
            // Addresses licence page
            // URLs like "/{serviceId}/{serviceVersion}/resources/license.html"
            return lookupLicense(req, targetUrl);

        } else if (!isVirtualUrl && path.startsWith("whatsnew/")) {
            return lookupWhatsnew(req, targetUrl, path, subject);
        } else {
            if (StringUtils.endsWith(targetPath, ".js")) {
                String sessionId = ServletHelper.getSessionID(req);
                if (StringUtils.startsWith(path, "resources/vendor")
                        || StringUtils.startsWith(path, "resources/libs")) {
                    // If targets lib folder, simply return requested file without handling debug versions
                    return lookupJs(req, targetUrl, false);

                } else if (StringUtils.startsWith(path, "boot/")) {
                    return lookupJs(req, targetUrl, isJsDebug());

                } else if (StringUtils.startsWith(FilenameUtils.getBaseName(path), "Locale")) {
                    return lookupLocaleJs(req, targetUrl, subject);

                } else {
                    return lookupJs(req, targetUrl, isJsDebug());
                }

            } else if (StringUtils.startsWith(path, "laf")) {
                return lookupLAF(req, targetUrl, path, subject, subjectPath);

            } else {
                return lookupDefault(req, isVirtualUrl ? ClientCaching.YES : ClientCaching.AUTO, targetUrl);
            }
        }

    } catch (ServletException ex) {
        return new Error(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, ex.getMessage());
    }
}

From source file:io.wcm.handler.url.impl.UrlHandlerImpl.java

String setFragment(String url, String fragment) {
    if (StringUtils.isEmpty(url)) {
        return url;
    }/* w  w w . j  a v a 2  s.c  o m*/

    // strip off anchor if already present
    StringBuilder urlBuilder;
    int index = url.indexOf('#');
    if (index >= 0) {
        urlBuilder = new StringBuilder(url.substring(0, index));
    } else {
        urlBuilder = new StringBuilder(url);
    }

    // prepend "#" for anchor if not present
    if (StringUtils.isNotBlank(fragment)) {
        if (!StringUtils.startsWith(fragment, "#")) {
            urlBuilder.append('#');
        }
        urlBuilder.append(fragment);
    }

    return urlBuilder.toString();
}

From source file:com.nike.cerberus.operation.core.EnableConfigReplicationOperation.java

private void touchCurrentFiles() {
    final String bucketName = environmentMetadata.getBucketName();
    final ObjectListing objectListing = s3Client.listObjects(bucketName);

    logger.info("Touching config files that already exist so they are replicated.");
    objectListing.getObjectSummaries().forEach(os -> {
        if (!StringUtils.startsWith(os.getKey(), "consul")) {
            logger.debug("Touching {}.", os.getKey());
            final S3Object object = s3Client.getObject(bucketName, os.getKey());
            s3Client.putObject(bucketName, object.getKey(), object.getObjectContent(),
                    object.getObjectMetadata());
        }//from w w  w . ja va2  s  .c o  m
    });
}