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

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

Introduction

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

Prototype

public static String substring(final String str, int start, int end) 

Source Link

Document

Gets a substring from the specified String avoiding exceptions.

A negative start position can be used to start/end n characters from the end of the String.

The returned substring starts with the character in the start position and ends before the end position.

Usage

From source file:com.dgtlrepublic.anitomyj.ParserNumber.java

/**
 * Match type and episode. e.g. "2x01", "S01E03", "S01-02xE001-150".
 *
 * @param word  the word/*from  w  w w.j  a v  a  2 s . c  o m*/
 * @param token the token
 * @return true if the token matched
 */
public boolean matchTypeAndEpisodePattern(String word, Token token) {
    int numberBegin = ParserHelper.indexOfFirstDigit(word);
    String prefix = StringUtils.substring(word, 0, numberBegin);

    AtomicReference<ElementCategory> category = new AtomicReference<>(kElementAnimeType);
    AtomicReference<KeywordOptions> options = new AtomicReference<>();

    if (KeywordManager.getInstance().findAndSet(KeywordManager.normalzie(prefix), category, options)) {
        parser.getElements().add(new Element(kElementAnimeType, prefix));
        String number = StringUtils.substring(word, numberBegin);
        if (matchEpisodePatterns(number, token) || setEpisodeNumber(number, token, true)) {
            int foundIdx = parser.getTokens().indexOf(token);
            if (foundIdx != -1) {
                token.setContent(number);
                parser.getTokens().add(foundIdx, new Token(
                        options.get().isIdentifiable() ? kIdentifier : kUnknown, prefix, token.isEnclosed()));
            }

            return true;
        }
    }

    return false;
}

From source file:io.wcm.config.core.persistence.impl.ToolsConfigPagePersistenceProvider.java

private String getConfigPagePathFromConfigResourcePath(String configResourcePath) {
    int index = StringUtils.indexOf(configResourcePath, "/jcr:content/");
    if (index <= 0) {
        return null;
    }//  w  w w. ja  v a  2s.  c  o  m
    return StringUtils.substring(configResourcePath, 0, index);
}

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

private String toAbsoluteURL(final Referer urlParts, final String newURL) {
    if (!isValidNewURL(newURL)) {
        return null;
    }//from w ww  .java2 s  . co m
    String url = newURL;
    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, "#");

    if (url.length() > maxURLLength) {
        LOG.debug("URL length (" + url.length() + ") exeeding " + "maximum length allowed (" + maxURLLength
                + ") to be extracted. URL (showing first " + LOGGING_MAX_URL_LENGTH + " chars): "
                + StringUtils.substring(url, 0, LOGGING_MAX_URL_LENGTH) + "...");
        return null;
    }
    return url;
}

From source file:com.feilong.core.lang.StringUtil.java

/**
 * [?]?(<code>startIndex</code>),?(<code>length</code>).
 * //from w  ww .  j a v  a  2  s .c  o  m
 * <pre class="code">
 * StringUtil.substring(null, 6, 8)                 =   null
 * StringUtil.substring("jinxin.feilong", 6, 2)     =   .f
 * </pre>
 *
 * @param text
 *            ?
 * @param startIndex
 *            ?,0
 * @param length
 *             {@code >=1}
 * @return  <code>text</code> null, null<br>
 * @see org.apache.commons.lang3.StringUtils#substring(String, int, int)
 */
public static String substring(final String text, int startIndex, int length) {
    return StringUtils.substring(text, startIndex, startIndex + length);
}

From source file:com.erudika.scoold.utils.ScooldUtils.java

public String getSpaceId(String space) {
    String s = StringUtils.contains(space, ":") ? StringUtils.substring(space, 0, space.lastIndexOf(":")) : "";
    return "scooldspace".equals(s) ? space : s;
}

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

private String toCleanAbsoluteURL(final Referer urlParts, final String newURL) {
    String url = StringUtils.trimToNull(newURL);
    if (!isValidNewURL(url)) {
        return null;
    }//from   w  w w . jav  a 2s .co m

    // Decode HTML entities.
    url = StringEscapeUtils.unescapeHtml4(url);

    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;
        }
    }

    if (url.length() > maxURLLength) {
        LOG.debug("URL length (" + url.length() + ") exeeding " + "maximum length allowed (" + maxURLLength
                + ") to be extracted. URL (showing first " + LOGGING_MAX_URL_LENGTH + " chars): "
                + StringUtils.substring(url, 0, LOGGING_MAX_URL_LENGTH) + "...");
        return null;
    }

    return url;
}

From source file:com.nike.cerberus.service.SafeDepositBoxService.java

/**
 * Deletes all of the secrets from Vault stored at the safe deposit box's path.
 *
 * @param path path to start deleting at.
 *//*from   w w  w .  j a  v a 2s.c o  m*/
private void deleteAllSecrets(final String path) {
    try {
        String fixedPath = path;

        if (StringUtils.endsWith(path, "/")) {
            fixedPath = StringUtils.substring(path, 0, StringUtils.lastIndexOf(path, "/"));
        }

        final VaultListResponse listResponse = vaultAdminClient.list(fixedPath);
        final List<String> keys = listResponse.getKeys();

        if (keys == null || keys.isEmpty()) {
            return;
        }

        for (final String key : keys) {
            if (StringUtils.endsWith(key, "/")) {
                final String fixedKey = StringUtils.substring(key, 0, key.lastIndexOf("/"));
                deleteAllSecrets(fixedPath + "/" + fixedKey);
            } else {
                vaultAdminClient.delete(fixedPath + "/" + key);
            }
        }
    } catch (VaultClientException vce) {
        throw ApiException.newBuilder().withApiErrors(DefaultApiError.SERVICE_UNAVAILABLE)
                .withExceptionCause(vce).withExceptionMessage("Failed to delete secrets from Vault.").build();
    }
}

From source file:alfio.manager.system.ConfigurationManager.java

public String getShortReservationID(Event event, String reservationId) {
    return StringUtils.substring(reservationId, 0, getIntConfigValue(
            Configuration.from(event.getOrganizationId(), event.getId(), PARTIAL_RESERVATION_ID_LENGTH), 8))
            .toUpperCase();/*  w  ww  .  ja  va 2s  . co  m*/
}

From source file:com.hybris.mobile.app.commerce.fragment.ProductDetailFragmentBase.java

/**
 * Populate the product//w  w w .ja v  a  2 s.  com
 *
 * @param product
 */
protected void populateProduct(ProductBase product) {
    if (product != null) {

        mProduct = product;

        /**
         * Populate the view with data from response and associate it to the right element in the view
         */
        mProductDetaiNameText.setText(product.getName() + " (" + product.getCode() + ")");

        if (StringUtils.isNotBlank(product.getDescription())) {

            mProductDetailExpandableText.setText(Html.fromHtml(product.getDescription()));
        }

        if (StringUtils.isNotBlank(product.getSummary())) {
            mProductDetailDescriptionLayout.setVisibility(View.VISIBLE);
            mProductShortDescription.setText(Html.fromHtml(product.getSummary()));
        }

        if (product.getStock() != null) {

            boolean resetAddToCart = true;

            mStocklevelText.setVisibility(View.VISIBLE);
            if (product.isLowStock() || product.isOutOfStock()) {
                mStocklevelText.setTextColor(getResources().getColor(R.color.product_item_low_stock));
                mStocklevelText.setContentDescription(getString(R.string.product_item_low_stock));

                if (product.isOutOfStock()) {
                    resetAddToCart = false;
                    mQuantityEditText.setEnabled(false);
                    mQuantityEditText.setText("");
                    mStocklevelText.setText(product.getStock().getStockLevel() + "\n"
                            + getString(R.string.product_detail_in_stock));
                }
            }

            if (product.isInStock()) {
                mStocklevelText.setText(product.getStock().getStockLevel() + "\n"
                        + getString(R.string.product_detail_in_stock));
                mStocklevelText.setTextColor(getResources().getColor(R.color.product_item_in_stock));
            }

            if (resetAddToCart) {
                mQuantityEditText.setEnabled(true);
                mQuantityEditText.setText(getString(R.string.default_qty));
            }

        } else {
            Log.d(TAG, "Stock is null");
        }

        if (product.getPrice() != null) {
            // to show pipe
            mProductPrice
                    .setText((product.getVolumePrices() != null) ? product.getPriceRangeFormattedValue() + " | "
                            : product.getPriceRangeFormattedValue());

            // Set the price with the default total value with currency sign
            mTotalPriceText
                    .setText((StringUtils.substring(product.getPrice().getFormattedValue(), 0, 1)
                            + ProductUtils.calculateQuantityPrice(mQuantityEditText.getText().toString(),
                                    (product.getVolumePrices() != null) ? ProductUtils.findVolumePrice(
                                            mQuantityEditText.getText().toString(), product.getVolumePrices())
                                            : product.getPrice())));
        } else {
            Log.d(TAG, "Price is null");
        }

        if (product.getVolumePrices() != null) {
            mVolumePricingExpandableButton.setVisibility(View.VISIBLE);

        }

        //Rating
        if (product.getAverageRating() != null) {
            mRatingBar.setVisibility(View.VISIBLE);
            mRatingBar.setRating(product.getAverageRating().floatValue());
        } else {
            mRatingBar.setVisibility(View.GONE);
        }

        //Reviews
        if (product.getReviews() != null && !product.getReviews().isEmpty()) {
            mReviews.setVisibility(View.VISIBLE);
            mReviews.setText(getString(R.string.product_detail_reviews, product.getNumberOfReviews()));
        } else {
            mReviews.setVisibility(View.GONE);
        }

        setClickableAddToCartButton();

        // Updating images
        updateImageViewPagerIndicator(product.getImagesGallery());

    }
}

From source file:com.streamsets.pipeline.stage.origin.jdbc.JdbcSource.java

private Record processRow(ResultSet resultSet, long rowCount) throws SQLException, StageException {
    Source.Context context = getContext();
    ResultSetMetaData md = resultSet.getMetaData();
    int numColumns = md.getColumnCount();

    LinkedHashMap<String, Field> fields = jdbcUtil.resultSetToFields(resultSet, commonSourceConfigBean,
            errorRecordHandler, unknownTypeAction, null);

    if (fields.size() != numColumns) {
        errorRecordHandler.onError(JdbcErrors.JDBC_35, fields.size(), numColumns);
        return null; // Don't output this record.
    }// www  .  j  av a  2 s  .  com

    final String recordContext = StringUtils.substring(query.replaceAll("[\n\r]", ""), 0, 100) + "::rowCount:"
            + rowCount + (StringUtils.isEmpty(offsetColumn) ? "" : ":" + resultSet.getString(offsetColumn));
    Record record = context.createRecord(recordContext);
    if (jdbcRecordType == JdbcRecordType.LIST_MAP) {
        record.set(Field.createListMap(fields));
    } else if (jdbcRecordType == JdbcRecordType.MAP) {
        record.set(Field.create(fields));
    } else {
        // type is LIST
        List<Field> row = new ArrayList<>();
        for (Map.Entry<String, Field> fieldInfo : fields.entrySet()) {
            Map<String, Field> cell = new HashMap<>();
            cell.put("header", Field.create(fieldInfo.getKey()));
            cell.put("value", fieldInfo.getValue());
            row.add(Field.create(cell));
        }
        record.set(Field.create(row));
    }
    if (createJDBCNsHeaders) {
        jdbcUtil.setColumnSpecificHeaders(record, Collections.<String>emptySet(), md, jdbcNsHeaderPrefix);
    }
    // We will add cdc operation type to record header even if createJDBCNsHeaders is false
    // we currently support CDC on only MS SQL.
    if (hikariConfigBean.getConnectionString().startsWith("jdbc:sqlserver")) {
        MSOperationCode.addOperationCodeToRecordHeader(record);
    }

    return record;
}