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

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

Introduction

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

Prototype

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

Source Link

Document

Gets the substring after the first occurrence of a separator.

Usage

From source file:com.netflix.spinnaker.clouddriver.ecs.services.EcsCloudMetricService.java

private void deregisterScalableTargets(Set<String> resources, String account, String region) {
    NetflixAmazonCredentials credentials = (NetflixAmazonCredentials) accountCredentialsProvider
            .getCredentials(account);//  w w  w  .  j  a  v a2  s  .  c  o m
    AWSApplicationAutoScaling autoScaling = amazonClientProvider.getAmazonApplicationAutoScaling(credentials,
            region, false);

    Map<String, Set<String>> resourceMap = new HashMap<>();
    for (String resource : resources) {
        String namespace = StringUtils.substringBefore(resource, "/");
        String service = StringUtils.substringAfter(resource, "/");
        if (resourceMap.containsKey(namespace)) {
            resourceMap.get(namespace).add(service);
        } else {
            Set<String> serviceSet = new HashSet<>();
            serviceSet.add(service);
            resourceMap.put(namespace, serviceSet);
        }
    }

    Set<DeregisterScalableTargetRequest> deregisterRequests = new HashSet<>();
    for (String namespace : resourceMap.keySet()) {
        String nextToken = null;
        do {
            DescribeScalableTargetsRequest request = new DescribeScalableTargetsRequest()
                    .withServiceNamespace(namespace).withResourceIds(resourceMap.get(namespace));

            if (nextToken != null) {
                request.setNextToken(nextToken);
            }

            DescribeScalableTargetsResult result = autoScaling.describeScalableTargets(request);

            deregisterRequests.addAll(result.getScalableTargets().stream()
                    .map(scalableTarget -> new DeregisterScalableTargetRequest()
                            .withResourceId(scalableTarget.getResourceId())
                            .withScalableDimension(scalableTarget.getScalableDimension())
                            .withServiceNamespace(scalableTarget.getServiceNamespace()))
                    .collect(Collectors.toSet()));

            nextToken = result.getNextToken();
        } while (nextToken != null && nextToken.length() != 0);
    }

    for (DeregisterScalableTargetRequest request : deregisterRequests) {
        autoScaling.deregisterScalableTarget(request);
    }
}

From source file:com.norconex.collector.http.url.impl.DefaultURLExtractor.java

private String extractURL(final UrlParts urlParts, final String rawURL) {
    if (rawURL == null) {
        return null;
    }// www.  jav  a  2s .  c  om
    String url = rawURL;
    if (url.startsWith("//")) {
        // this is URL relative to protocol
        url = urlParts.protocol + StringUtils.substringAfter(url, "//");
    } else if (url.startsWith("/")) {
        // this is a URL relative to domain name
        url = urlParts.absoluteBase + url;
    } else if (url.startsWith("?") || url.startsWith("#")) {
        // this is a relative url and should have the full page base
        url = urlParts.documentBase + url;
    } else if (!url.contains("://")) {
        if (urlParts.relativeBase.endsWith("/")) {
            // This is a URL relative to the last URL segment
            url = urlParts.relativeBase + url;
        } else {
            url = urlParts.relativeBase + "/" + url;
        }
    }
    //TODO have configurable whether to strip anchors.
    url = StringUtils.substringBefore(url, "#");
    return url;
}

From source file:io.wcm.maven.plugins.contentpackage.DownloadMojo.java

/**
 * Download content package from CRX instance
 *//*from ww w.  j a v  a  2s . c  om*/
private File downloadFile(File file, String ouputFilePath) throws MojoExecutionException {
    try (CloseableHttpClient httpClient = getHttpClient()) {
        getLog().info("Download " + file.getName() + " from " + getCrxPackageManagerUrl());

        // 1st: try upload to get path of package - or otherwise make sure package def exists (no install!)
        HttpPost post = new HttpPost(getCrxPackageManagerUrl() + "/.json?cmd=upload");
        MultipartEntityBuilder entity = MultipartEntityBuilder.create().addBinaryBody("package", file)
                .addTextBody("force", "true");
        post.setEntity(entity.build());
        JSONObject jsonResponse = executePackageManagerMethodJson(httpClient, post);
        boolean success = jsonResponse.optBoolean("success", false);
        String msg = jsonResponse.optString("msg", null);
        String path = jsonResponse.optString("path", null);

        // package already exists - get path from error message and continue
        if (!success && StringUtils.startsWith(msg, CRX_PACKAGE_EXISTS_ERROR_MESSAGE_PREFIX)
                && StringUtils.isEmpty(path)) {
            path = StringUtils.substringAfter(msg, CRX_PACKAGE_EXISTS_ERROR_MESSAGE_PREFIX);
            success = true;
        }
        if (!success) {
            throw new MojoExecutionException("Package path detection failed: " + msg);
        }

        getLog().info("Package path is: " + path + " - now rebuilding package...");

        // 2nd: build package
        HttpPost buildMethod = new HttpPost(getCrxPackageManagerUrl() + "/console.html" + path + "?cmd=build");
        executePackageManagerMethodHtml(httpClient, buildMethod, 0);

        // 3rd: download package
        String crxUrl = StringUtils.removeEnd(getCrxPackageManagerUrl(), "/crx/packmgr/service");
        HttpGet downloadMethod = new HttpGet(crxUrl + path);

        // execute download
        CloseableHttpResponse response = httpClient.execute(downloadMethod);
        try {
            if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {

                // get response stream
                InputStream responseStream = response.getEntity().getContent();

                // delete existing file
                File outputFileObject = new File(ouputFilePath);
                if (outputFileObject.exists()) {
                    outputFileObject.delete();
                }

                // write response file
                FileOutputStream fos = new FileOutputStream(outputFileObject);
                IOUtil.copy(responseStream, fos);
                fos.flush();
                responseStream.close();
                fos.close();

                getLog().info("Package downloaded to " + outputFileObject.getAbsolutePath());

                return outputFileObject;
            } else {
                throw new MojoExecutionException(
                        "Package download failed:\n" + EntityUtils.toString(response.getEntity()));
            }
        } finally {
            if (response != null) {
                EntityUtils.consumeQuietly(response.getEntity());
                try {
                    response.close();
                } catch (IOException ex) {
                    // ignore
                }
            }
        }
    } catch (FileNotFoundException ex) {
        throw new MojoExecutionException("File not found: " + file.getAbsolutePath(), ex);
    } catch (IOException ex) {
        throw new MojoExecutionException("Download operation failed.", ex);
    }
}

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/*from  w  ww  .j  av a  2s  . 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.wso2.code.quality.matrices.Reviewer.java

/**
 * reads the search API output and save the pull request number with the repo name in a map
 *
 * @param rootJsonObject JSONObject received from github search API
 *///from w  w w . j a va 2  s  .  co  m
public void savePrNumberAndRepoName(JSONObject rootJsonObject) {
    JSONArray itemsJsonArray = (JSONArray) rootJsonObject.get(GITHUB_REVIEW_API_ITEMS_KEY);

    Pmt.arrayToStream(itemsJsonArray).map(JSONObject.class::cast)
            .filter(o -> o.get(GITHUB_REVIEW_API_STATE_KEY).equals(GITHUB_REVIEW_API_CLOSED_STATE_KEY))
            .forEach(prJsonObject -> {
                String repositoryUrl = (String) prJsonObject.get(GITHUB_REVIEW_API_REPOSITORY_URL_KEY);
                String repositoryLocation = StringUtils.substringAfter(repositoryUrl,
                        "https://api.github.com/repos/");
                if (repositoryLocation.contains("wso2/")) {
                    // to filter out only the repositories belongs to wso2
                    int pullRequetNumber = (int) prJsonObject.get(GITHUB_REVIEW_API_NUMBER_KEY);
                    mapContainingPRNoAgainstRepoName.putIfAbsent(repositoryLocation, new HashSet<Integer>()); // put the repo name key only if it does not exists in the map
                    mapContainingPRNoAgainstRepoName.get(repositoryLocation).add(pullRequetNumber); // since SET is there we do not need to check for availability of the key in the map
                }
            });
}

From source file:com.tyro.oss.pact.spring4.pact.provider.PactTestBase.java

protected MockHttpServletRequestBuilder createRequestBuilderWithMethodAndUri(Pact.InteractionRequest request)
        throws Exception {
    String uri = request.getUri().contains(getServletContextPathWithoutTrailingSlash())
            ? StringUtils.substringAfter(request.getUri(), getServletContextPathWithoutTrailingSlash())
            : request.getUri();//w  ww.jav  a  2s . c o  m
    uri = UriUtils.decode(uri, "UTF-8");

    switch (request.getMethod()) {
    case GET:
        return get(uri);
    case POST:
        return post(uri);
    case PUT:
        return put(uri);
    case DELETE:
        return delete(uri);
    default:
        throw new RuntimeException("Unsupported method " + request.getMethod());
    }
}

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

/**
 * ?contentTypeheaders./*from www  .  ja  v a2s  .  co 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:de.jfachwert.net.Telefonnummer.java

/**
 * Liefert die Nummer der Ortsvermittlungsstelle, d.h. die Telefonnummer
 * ohne Vorwahl und Laenderkennzahl.//  ww  w .j a  va  2  s  .c o  m
 *
 * @return z.B. "32168"
 */
public Telefonnummer getRufnummer() {
    String inlandsnummer = RegExUtils.replaceAll(this.getInlandsnummer().toString(), "[ /]+", " ");
    return new Telefonnummer(StringUtils.substringAfter(inlandsnummer, " ").replaceAll(" ", ""));
}

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

/**
 * ?contentTypeheaders./*  w ww  .ja  v  a 2 s .co 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;
}

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

public boolean generate() throws IOException {
    //First set fixed values. This has to be done first so that they will be
    //considered during generation.
    Map<String, String> fixedValues = fixedValuesMap.get(key);
    if (fixedValues != null) {
        for (Map.Entry<String, String> entry : fixedValues.entrySet()) {
            addFormEntry(entry.getKey(), entry.getValue());
        }/*from w w w  .j a  va2 s  .  c o  m*/
    }

    Constraint constraintContainer = null;
    try {
        constraintContainer = generator.getConstraint(key + "." + GeneratorConstants.ALL_CONSTRAINT);
    } catch (IdNotFoundException e) {
        log.info("No constraint-container found for id " + key);
        return false;
    }

    //get all constraints contained in the FormEntry Map
    String keyPrefix = key + ".";
    String allKeyPrefix = GeneratorConstants.ALL_CONSTRAINT + ".";
    String excludedKey = key + "." + GeneratorConstants.ALL_CONSTRAINT;
    Set<String> ids = constraintContainer.getContainedIds();

    //Reset to generate new values
    resetValues(constraintContainer);
    generateValues(constraintContainer);

    //First of all, all unindexed entries.
    for (String id : ids) {
        if (id.equals(excludedKey)) {
            continue;
        }
        String prefix = id.startsWith(keyPrefix) ? keyPrefix : allKeyPrefix;
        // TODO some parts may get cut off here
        String entryKey = id.substring(prefix.length());

        if (fixedValues != null && fixedValues.containsKey(entryKey)) {
            continue;
        }
        getFormEntry(entryKey);
    }

    //Only indexed values; this way it is ensured, that fields, which represent
    //the number of lines, have already been generated.
    Set<FieldSet> indexedFields = generator.getIndexedFields().getFieldSets(key);

    Map<String, FieldSet> fieldSetCache = Maps.newHashMap();
    for (FieldSet fieldSet : indexedFields) {
        String id = fieldSet.getId();
        fieldSetCache.put(id, fieldSet);
        String dependsOn = fieldSet.getDependsOn();
        /*
         * If a dependency to another FieldSet exists, it has to be in the cache already (order
         * in the xml!)
         */
        FieldSet dependentFieldSet = StringUtils.isNotEmpty(dependsOn) ? fieldSetCache.get(dependsOn) : null;
        if (StringUtils.isNotEmpty(dependsOn) && dependentFieldSet == null) {
            throw new IllegalStateException("The FieldSet with id=" + id + " depends on the FieldSet with id="
                    + dependsOn
                    + ". However, this hasn't been generated yet. Is the order within the Generator-XML correct?");
        }

        int count;
        if (id.startsWith(key)) {
            //The number of indexes is read from a FormEntry.
            try {
                count = getFormEntry(StringUtils.substringAfter(id, ".")).getInteger();
            } catch (NumberFormatException ex) {
                // Not defined for this year, so return 0 lines.
                count = 0;
            }
        } else {
            // The number of indexes is configured as a property.
            count = configuration.getInteger(id, 5);
        }

        Map<String, FormData> dependenciesMap = Maps.newHashMap();

        for (int i = 1; i <= count; ++i) {
            for (String dependency : fieldSet.getDependencies()) {
                FormData depData = new FormData(configuration, fieldGenerators, dependency, generator,
                        fixedValuesMap);
                depData.generate();
                dependenciesMap.put(dependency, depData);
            }

            //Index entries. All entries for one index are generated in a loop so as to
            //consider dependencies between entries.
            for (Field field : fieldSet) {
                FormData data = key.equals(field.getDataKey()) ? this : dependenciesMap.get(field.getDataKey());

                //Index FormEntry
                if (!indexFormEntry(data, field, i, fixedValues)) {
                    //Not unique, try this index again.
                    --i;
                    break;
                }
            }
            //Reset entries for next run when all values for an index have been generated.
            for (Field field : fieldSet) {
                if (!key.equals(field.getDataKey())) {
                    //Not for dependencies, since those are newly generated for each index anyway.
                    continue;
                }

                FormEntry fe = getFormEntry(field.getEntryKey());
                fe.resetValue();
                Constraint constraint = fe.getConstraint();
                if (constraint != null) {
                    constraint.resetValues();
                }
            }
        }
        for (Field field : fieldSet) {
            String className = field.getClassName();
            if (StringUtils.isNotEmpty(className)) {
                FieldGenerator fieldGenerator = fieldGenerators.get(className);
                fieldGenerator.generate(this);
            }
        }
    }
    return true;
}