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.hybris.mobile.app.commerce.adapter.ProductListAdapterBase.java

/**
 * Populate the product//from w w w.  ja v  a  2 s .  c om
 *
 * @param product
 */
protected void populateProductExpanded(final ProductBase product) {
    if (product != null) {
        /**
         * Populate the view with data from response and associate it to the right element in the view
         */
        mCurrentSelectedViewHolder.productNameExpanded.setText(product.getName());
        mCurrentSelectedViewHolder.productNoExpanded.setText(product.getCode());

        if (product.getStock() != null) {
            mCurrentSelectedViewHolder.productAvailabilityExpanded.setVisibility(View.VISIBLE);
            if (product.isLowStock() || product.isOutOfStock()) {
                mCurrentSelectedViewHolder.productAvailabilityExpanded
                        .setTextColor(getContext().getResources().getColor(R.color.product_item_low_stock));
                mCurrentSelectedViewHolder.productAvailabilityExpanded
                        .setContentDescription(getContext().getString(R.string.product_item_low_stock));

                if (product.isOutOfStock()) {
                    mCurrentSelectedViewHolder.quantityEditTextExpanded.setEnabled(false);
                    mCurrentSelectedViewHolder.quantityEditTextExpanded.setText("");
                    mCurrentSelectedViewHolder.productAvailabilityExpanded
                            .setText(product.getStock().getStockLevel() + "\n"
                                    + getContext().getResources().getString(R.string.product_detail_in_stock));

                }

            }

            if (product.isInStock()) {
                mCurrentSelectedViewHolder.productAvailabilityExpanded
                        .setText(product.getStock().getStockLevel() + "\n"
                                + getContext().getResources().getString(R.string.product_detail_in_stock));
                mCurrentSelectedViewHolder.productAvailabilityExpanded
                        .setTextColor(getContext().getResources().getColor(R.color.product_item_in_stock));
                mCurrentSelectedViewHolder.quantityEditTextExpanded.setEnabled(true);

            }

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

        mCurrentSelectedViewHolder.productPriceExpanded
                .setText((product.getVolumePrices() != null) ? product.getPriceRangeFormattedValue() + " | "
                        : product.getPriceRangeFormattedValue());

        // Set the price with the default total value
        mCurrentSelectedViewHolder.productPriceTotalExpanded.setText((StringUtils
                .substring(product.getPrice().getFormattedValue(), 0, 1)
                + ProductUtils.calculateQuantityPrice(
                        mCurrentSelectedViewHolder.quantityEditTextExpanded.getText().toString(),
                        (product.getVolumePrices() != null) ? ProductUtils.findVolumePrice(
                                mCurrentSelectedViewHolder.quantityEditTextExpanded.getText().toString(),
                                product.getVolumePrices()) : product.getPrice())));

        // Loading the product image for expanded view
        loadProductImage(product.getImageThumbnailUrl(), mCurrentSelectedViewHolder.productImageExpanded,
                mCurrentSelectedViewHolder.productImageLoadingExpanded, product.getCode());

        /**
         * Add to cart when user click on cartIcon in Product item expanded row
         */
        mCurrentSelectedViewHolder.productImageViewCartIconExpanded.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                addToCart(product.getCode(),
                        mCurrentSelectedViewHolder.quantityEditTextExpanded.getText().toString(),
                        mCurrentSelectedViewHolder);
                mCurrentSelectedViewHolder.quantityEditTextExpanded
                        .setText(getContext().getString(R.string.default_qty));
            }
        });

        mCurrentSelectedViewHolder.quantityEditTextExpanded.setOnEditorActionListener(new SubmitListener() {

            @Override
            public void onSubmitAction() {
                // Perform action on key press
                addToCart(product.getCode(),
                        mCurrentSelectedViewHolder.quantityEditTextExpanded.getText().toString(),
                        mCurrentSelectedViewHolder);
                mCurrentSelectedViewHolder.quantityEditTextExpanded
                        .setText(getContext().getString(R.string.default_qty));
            }
        });
    }
}

From source file:de.gbv.ole.Marc21ToOleBulk.java

/**
 * Liest aus Leader und Control Fields sowie dem Ausleihindikator
 * den item type und liefert seine id zurck.
 * @param record    Record, der Leader und Control Fields enthlt
 * @param exemplar  Exemplar mit Ausleihindikator und Ziel fr Item Type.
 * @return  item type id/*  ww  w  .  j  ava  2s  . c om*/
 */
final static int getItemType(Record record, Exemplar exemplar) {
    // Spec siehe http://www.loc.gov/marc/bibliographic/
    String leader = record.getLeader().toString();
    String typeOfRecord = leader.substring(6, 7);
    String bibliographicLevel = leader.substring(7, 8);
    String field007 = getOptionalControlField(record, "007");
    String categoryOfMaterial = empty2space(StringUtils.substring(field007, 0, 1));
    String materialDesignation = empty2space(StringUtils.substring(field007, 1, 2));

    if (typeOfRecord.equals("a") && "mb".contains(bibliographicLevel)) {
        if ("ubc".contains(exemplar.ausleihindikator)) {
            return ItemType.BUA.value;
        }
        if ("sd".contains(exemplar.ausleihindikator)) {
            return ItemType.BUZ.value;
        }
        if ("ifgaoz".contains(exemplar.ausleihindikator)) {
            return ItemType.BUP.value;
        }
    }

    // eBook
    if (typeOfRecord.equals("m") && bibliographicLevel.equals("m") && categoryOfMaterial.equals("c")
            && materialDesignation.equals("r")) {
        return ItemType.BUA.value;
    }

    // Zeitschrift
    if (typeOfRecord.equals("a") && bibliographicLevel.equals("s")) {
        return ItemType.ZSP.value;
    }

    // eZeitschrift
    if (typeOfRecord.equals("m") && bibliographicLevel.equals("s")) {
        return ItemType.BUA.value;
    }

    // Aufsatz
    if (typeOfRecord.equals("a") && bibliographicLevel.equals("a")) {
        return ItemType.ZSP.value;
    }

    // eAufsatz
    if (bibliographicLevel.equals("a")) {
        return ItemType.BUA.value;
    }

    // Handschrift
    if ("dft".contains(typeOfRecord)) {
        return ItemType.BUP.value;
    }

    // Mikroform
    if (categoryOfMaterial.equals("h")) {
        return ItemType.MKP.value;
    }

    // Datentrger, Karte, Film, Tontrger, Spiel/Objekt

    if ("ubc".contains(exemplar.ausleihindikator)) {
        return ItemType.AVA.value;
    }
    if ("sd".contains(exemplar.ausleihindikator)) {
        return ItemType.AVZ.value;
    }

    // ifgaoz
    return ItemType.AVP.value;
}

From source file:main.java.cluster.Cluster.java

public static String[] breakDataIdWithoutReplicaId(int _id) {
    String[] parts = new String[2];

    // Extract the last part from tuple id
    String d_id = Integer.toString(_id);
    int length = d_id.length();

    // Extract primary key and table id from the tuple id string
    parts[0] = StringUtils.substring(d_id, 0, (length - 1));
    parts[1] = StringUtils.substring(d_id, (length - 1), length);

    return parts;
}

From source file:main.java.cluster.Cluster.java

public static String[] breakDataIdWithReplicaId(int _id) {
    String[] parts = new String[3];

    // Extract the last part from tuple id
    String d_id = Integer.toString(_id);
    int length = d_id.length();

    // Extract primary key and table id from the tuple id string
    parts[0] = StringUtils.substring(d_id, 0, (length - 2)); // Tuple Primary Key
    parts[1] = StringUtils.substring(d_id, (length - 2), (length - 1)); // Replica Id
    parts[2] = StringUtils.substring(d_id, (length - 1), length); // Table Id

    return parts;
}

From source file:com.streamsets.pipeline.stage.origin.salesforce.ForceSource.java

private String soapProduce(String lastSourceOffset, int maxBatchSize, BatchMaker batchMaker)
        throws StageException {

    String nextSourceOffset = (null == lastSourceOffset) ? RECORD_ID_OFFSET_PREFIX + conf.initialOffset
            : lastSourceOffset;//from   w  w w .  j a  v  a 2  s .  c o  m

    if (queryResult == null) {
        try {
            String id = (lastSourceOffset == null) ? null
                    : lastSourceOffset.substring(lastSourceOffset.indexOf(':') + 1);
            final String preparedQuery = prepareQuery(conf.soqlQuery, id);
            LOG.info("preparedQuery: {}", preparedQuery);
            queryResult = conf.queryAll ? partnerConnection.queryAll(preparedQuery)
                    : partnerConnection.query(preparedQuery);
            recordIndex = 0;
        } catch (ConnectionException e) {
            throw new StageException(Errors.FORCE_08, e);
        }
    }

    SObject[] records = queryResult.getRecords();

    LOG.info("Retrieved {} records", records.length);

    if (recordCreator.isCountQuery()) {
        // Special case for old-style COUNT() query
        Record rec = getContext().createRecord(conf.soqlQuery);
        LinkedHashMap<String, Field> map = new LinkedHashMap<>();
        map.put(COUNT, Field.create(Field.Type.INTEGER, queryResult.getSize()));
        rec.set(Field.createListMap(map));
        rec.getHeader().setAttribute(ForceRecordCreator.SOBJECT_TYPE_ATTRIBUTE, sobjectType);

        batchMaker.addRecord(rec);
    } else {
        int endIndex = Math.min(recordIndex + maxBatchSize, records.length);

        for (; recordIndex < endIndex; recordIndex++) {
            SObject record = records[recordIndex];

            String offsetColumn = StringUtils.defaultIfEmpty(conf.offsetColumn, ID);
            XmlObject offsetField = getChildIgnoreCase(record, offsetColumn);
            String offset;
            if (offsetField == null || offsetField.getValue() == null) {
                if (!conf.disableValidation) {
                    throw new StageException(Errors.FORCE_22, offsetColumn);
                }
                // Aggregate query - set the offset to the record index, since we have no offset column
                offset = String.valueOf(recordIndex);
            } else {
                offset = fixOffset(offsetColumn, offsetField.getValue().toString());
                nextSourceOffset = RECORD_ID_OFFSET_PREFIX + offset;
            }
            final String sourceId = StringUtils.substring(conf.soqlQuery.replaceAll("[\n\r]", " "), 0, 100)
                    + "::rowCount:" + recordIndex
                    + (StringUtils.isEmpty(conf.offsetColumn) ? "" : ":" + offset);
            Record rec = recordCreator.createRecord(sourceId, record);

            batchMaker.addRecord(rec);
        }
    }

    if (recordIndex == records.length) {
        try {
            if (queryResult.isDone()) {
                // We're out of results
                queryResult = null;
                lastQueryCompletedTime = System.currentTimeMillis();
                LOG.info("Query completed at: {}", lastQueryCompletedTime);
                shouldSendNoMoreDataEvent = true;
                if (conf.subscribeToStreaming) {
                    // Switch to processing events
                    nextSourceOffset = READ_EVENTS_FROM_NOW;
                } else if (conf.repeatQuery == ForceRepeatQuery.FULL) {
                    nextSourceOffset = RECORD_ID_OFFSET_PREFIX + conf.initialOffset;
                } else if (conf.repeatQuery == ForceRepeatQuery.NO_REPEAT) {
                    nextSourceOffset = null;
                }
            } else {
                queryResult = partnerConnection.queryMore(queryResult.getQueryLocator());
                recordIndex = 0;
            }
        } catch (ConnectionException e) {
            throw new StageException(Errors.FORCE_08, e);
        }
    }

    return nextSourceOffset;
}

From source file:com.evolveum.midpoint.model.impl.lens.TestAssignmentProcessor2.java

private void addConditionToRoles(String text) {
    for (String item : getList(text)) {
        String name = StringUtils.substring(item, 0, -1);
        char conditionType = item.charAt(item.length() - 1);
        AbstractRoleType role = findRole(name);
        role.setCondition(createCondition(item, conditionType));
    }/*  w w w.  ja v a2s  . co  m*/
}

From source file:com.evolveum.midpoint.model.impl.lens.TestAssignmentProcessor2.java

private void addConditionToAssignments(String text) {
    for (String item : getList(text)) {
        String assignmentText = StringUtils.substring(item, 0, -1);
        char conditionType = item.charAt(item.length() - 1);
        AssignmentType assignment = findAssignmentOrInducement(assignmentText);
        assignment.setCondition(createCondition(item, conditionType));
    }/*w w w .  ja v a 2s .  c  o m*/
}

From source file:nl.sidn.pcap.util.GeoLookupUtil.java

/**
 * parse maxmind asn result/*from w  w  w.ja v  a  2 s .c  o  m*/
 * @return ASXXXX formatted string
 */
private String parseASN(String asn) {

    if (asn != null) {
        int pos = StringUtils.indexOf(asn, ' ');
        if (pos != -1) {
            return StringUtils.substring(asn, 0, pos);
        }
        //not a valid asn string
        return "UNKN";
    }
    //not found
    return null;
}

From source file:nl.vpro.jcr.criteria.query.xpath.utils.XPathTextUtils.java

/**
 * @param path to encode eg //my//path/2009//*
 * @return String encoded path eg //my//path/_x0032_009//*
 *//*from  w  w w . ja  va 2  s.  c  om*/
public static String encodeDigitsInPath(String path) {
    LOG.debug("path to encode is {}", path);
    if (StringUtils.isBlank(path)) {
        String msg = "path cannot be a null or empty string";
        LOG.error(msg);
        throw new IllegalArgumentException(msg);
    }

    StringBuilder encodedPath = new StringBuilder(path.length());

    int inXpathCondition = 0;
    boolean xpathWithFunction = false;

    // TODO maybe a more robust check is needed
    for (int i = 0; i < path.length(); ++i) {
        char ch = path.charAt(i);

        if (i > 0 && path.charAt(i - 1) == '/' && Character.isDigit(ch)) {
            encodedPath.append("_x").append(StringUtils.leftPad(Integer.toHexString(ch), 4, '0')).append("_");
        } else if (i > 0 && path.charAt(i - 1) == '/' && ch == '-') {
            encodedPath.append("_x002d_");
        } else if (inXpathCondition <= 0 && ch == ' ') {
            encodedPath.append("_x0020_");
        } else if (inXpathCondition <= 0 && ch == ',') {
            encodedPath.append("_x002c_");
        } else if (inXpathCondition <= 0 && ch == '\u00b0') { // CRIT-53
            encodedPath.append("_x00b0_");
        } else if (inXpathCondition <= 0 && ch == '$') { // CRIT-54
            encodedPath.append("_x0024_");
        } else {
            if (ch == '[') {
                inXpathCondition++;
            } else if (ch == '(') {
                // "(" is the beginning of an expression only when used with the element() function
                if (StringUtils.endsWith(StringUtils.substring(path, 0, i), "element")) {
                    inXpathCondition++;
                    xpathWithFunction = true;
                } else if (inXpathCondition == 0) {
                    encodedPath.append("_x0028_");
                    continue;
                }
            } else if (inXpathCondition > 0 && ch == ']') {
                inXpathCondition--;
            } else if (ch == ')') {
                if (inXpathCondition > 0 && xpathWithFunction) {
                    inXpathCondition--;
                    xpathWithFunction = false;
                } else if (inXpathCondition == 0) {
                    encodedPath.append("_x0029_");
                    continue;
                }
            }
            encodedPath.append(ch);
        }
    }
    LOG.debug("returning encoded path {}", encodedPath);
    return encodedPath.toString();
}

From source file:nl.vpro.jcr.criteria.query.xpath.utils.XPathTextUtils.java

/**
 * Get a date in the XSD format "yyyy-MM-ddThh:mm:ss.SSS:+01:00"
 * @param date input calendar//www  .  ja va2  s . com
 * @return XSD formatted date
 */
public static String toXsdDate(Calendar date) {
    if (date == null) {
        return null;
    }

    String xsdDate = DATE_FORMAT.format(date);
    int length = xsdDate.length();

    return StringUtils.substring(xsdDate, 0, length - 2) + ":"
            + StringUtils.substring(xsdDate, length - 2, length);
}