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:org.elassandra.index.ElasticSecondaryIndex.java

public static Pair<ColumnDefinition, IndexTarget.Type> parseTarget(CFMetaData cfm, IndexMetadata indexDef) {
    String target = indexDef.options.get("target");
    assert target != null : String.format(Locale.ROOT, "No target definition found for index %s",
            indexDef.name);//from w  w  w .  ja v a  2s. co  m

    // if the regex matches then the target is in the form "keys(foo)", "entries(bar)" etc
    // if not, then it must be a simple column name and implictly its type is VALUES
    Matcher matcher = TARGET_REGEX.matcher(target);
    String columnName;
    IndexTarget.Type targetType;
    if (matcher.matches()) {
        targetType = IndexTarget.Type.fromString(matcher.group(1));
        columnName = matcher.group(2);
    } else {
        columnName = target;
        targetType = IndexTarget.Type.VALUES;
    }

    // in the case of a quoted column name the name in the target string
    // will be enclosed in quotes, which we need to unwrap. It may also
    // include quote characters internally, escaped like so:
    //      abc"def -> abc""def.
    // Because the target string is stored in a CQL compatible form, we
    // need to un-escape any such quotes to get the actual column name
    if (columnName.startsWith("\"")) {
        columnName = StringUtils.substring(StringUtils.substring(columnName, 1), 0, -1);
        columnName = columnName.replaceAll("\"\"", "\"");
    }

    // if it's not a CQL table, we can't assume that the column name is utf8, so
    // in that case we have to do a linear scan of the cfm's columns to get the matching one
    if (cfm.isCQLTable())
        return Pair.create(cfm.getColumnDefinition(new ColumnIdentifier(columnName, true)), targetType);
    else
        for (ColumnDefinition column : cfm.allColumns())
            if (column.name.toString().equals(columnName))
                return Pair.create(column, targetType);

    throw new RuntimeException(
            String.format(Locale.ROOT, "Unable to parse targets for index %s (%s)", indexDef.name, target));
}

From source file:org.fcrepo.kernel.modeshape.utils.NodePropertiesTools.java

/**
 * Given a JCR node, property and value, remove the value (if it exists)
 * from the property, and remove the//ww  w  . j a  v  a  2 s  .  com
 * property if no values remove
 *
 * @param node the JCR node
 * @param propertyName a name of a JCR property (either pre-existing or
 *   otherwise)
 * @param valueToRemove the JCR value to remove
 * @throws RepositoryException if repository exception occurred
 */
public void removeNodeProperty(final Node node, final String propertyName, final Value valueToRemove)
        throws RepositoryException {
    LOGGER.debug("Request to remove {}", valueToRemove);
    // if the property doesn't exist, we don't need to worry about it.
    if (node.hasProperty(propertyName)) {

        final Property property = node.getProperty(propertyName);
        final String strValueToRemove = valueToRemove.getString();

        if (property.isMultiple()) {
            final AtomicBoolean remove = new AtomicBoolean();
            final Value[] newValues = stream(node.getProperty(propertyName).getValues()).filter(uncheck(v -> {
                final String strVal = v.getString();

                LOGGER.debug("v is '{}', valueToRemove is '{}'", v, strValueToRemove);
                if (strVal.equals(strValueToRemove)) {
                    remove.set(true);
                    return false;
                }

                return true;
            })).toArray(Value[]::new);

            // we only need to update the property if we did anything.
            if (remove.get()) {
                if (newValues.length == 0) {
                    LOGGER.debug("Removing property '{}'", propertyName);
                    property.remove();
                } else {
                    LOGGER.debug("Removing value '{}' from property '{}'", strValueToRemove, propertyName);
                    property.setValue(newValues);
                }
            } else {
                LOGGER.debug("Value not removed from property name '{}' (value '{}')", propertyName,
                        strValueToRemove);
                throw new RepositoryException("Property '" + propertyName + "': Unable to remove value '"
                        + StringUtils.substring(strValueToRemove, 0, 50) + "...'");
            }
        } else {

            final String strPropVal = property.getValue().getString();

            LOGGER.debug("Removing string '{}'", strValueToRemove);
            if (StringUtils.equals(strPropVal, strValueToRemove)) {
                LOGGER.debug("single value: Removing value from property '{}'", propertyName);
                property.remove();
            } else {
                LOGGER.debug(
                        "Value not removed from property name '{}' (property value: '{}';compare value: '{}')",
                        propertyName, strPropVal, strValueToRemove);
                throw new RepositoryException("Property '" + propertyName + "': Unable to remove value '"
                        + StringUtils.substring(strValueToRemove, 0, 50) + "'");
            }
        }
    }
}

From source file:org.goko.common.bindings.AbstractController.java

/**
 * Make sure the getter for the given property exists
 * @param source the source object/*w  w w . j  a  v a 2  s .c  o m*/
 * @param property the property to search for
 * @return the {@link Method}
 * @throws GkException GkException
 */
private Method verifyGetter(Object source, String property) throws GkException {
    String firstLetter = StringUtils.substring(property, 0, 1);
    String otherLetters = StringUtils.substring(property, 1);

    String getGetterName = "^get" + StringUtils.upperCase(firstLetter) + otherLetters + "$";
    String isGetterName = "^is" + StringUtils.upperCase(firstLetter) + otherLetters + "$";

    Method[] methodArray = source.getClass().getMethods();
    for (Method method : methodArray) {
        //if(StringUtils.equals(getterName, method.getName())){
        if (method.getName().matches(getGetterName) || method.getName().matches(isGetterName)) {
            return method;
        }
    }

    String getterNameDisplay = "get" + StringUtils.upperCase(firstLetter) + otherLetters + "/is"
            + StringUtils.upperCase(firstLetter) + otherLetters;
    throw new GkTechnicalException("Cannot find getter (looking for '" + getterNameDisplay + "') for property '"
            + property + "' on object " + source.getClass() + ". Make sure it's public and correctly spelled");

}

From source file:org.goko.common.bindings.AbstractController.java

/**
 * Make sure the setter for the given property exists
 * @param source the source object// w ww.  j a  v a  2  s.  c  o  m
 * @param property the property to search for
 * @throws GkException GkException
 */
private void verifySetter(Object source, String property) throws GkException {
    String firstLetter = StringUtils.substring(property, 0, 1);
    String otherLetters = StringUtils.substring(property, 1);
    String setterName = "set" + StringUtils.upperCase(firstLetter) + otherLetters;
    boolean found = false;

    Method getMethod = verifyGetter(source, property);
    Method[] methodArray = source.getClass().getMethods();
    for (Method method : methodArray) {
        if (StringUtils.equals(setterName, method.getName())) {
            Class<?>[] paramsArray = method.getParameterTypes();
            if (paramsArray != null && paramsArray.length == 1 && paramsArray[0] == getMethod.getReturnType()) {
                found = true;
                break;
            }

        }
    }
    //source.getClass().getDeclaredMethod(setterName, getMethod.getReturnType());

    if (!found) {
        throw new GkTechnicalException(
                "Cannot find setter (looking for '" + setterName + "') for property '" + property
                        + "' on object " + source.getClass() + ". Make sure it's public and correctly spelled");
    }
}

From source file:org.goko.controller.grbl.v08.GrblCommunicator.java

/**
 * Create a status report from the given string
 * @param strStatusReport the String representing the status report
 * @return {@link StatusReport}//from  w w  w . ja v a  2  s .  c om
 * @throws GkException
 */
private StatusReport parseStatusReport(String strStatusReport) throws GkException {
    StatusReport result = new StatusReport();
    int comma = StringUtils.indexOf(strStatusReport, ",");
    String state = StringUtils.substring(strStatusReport, 1, comma);
    GrblMachineState grblState = grbl.getGrblStateFromString(state);
    result.setState(grblState);

    // Looking for MPosition
    String mpos = StringUtils.substringBetween(strStatusReport, "MPos:", ",WPos");
    String wpos = StringUtils.substringBetween(strStatusReport, "WPos:", ">");
    Tuple6b machinePosition = new Tuple6b().setNull();
    Tuple6b workPosition = new Tuple6b().setNull();
    String[] machineCoordinates = StringUtils.split(mpos, ",");

    parseTuple(machineCoordinates, machinePosition);
    result.setMachinePosition(machinePosition);

    String[] workCoordinates = StringUtils.split(wpos, ",");
    parseTuple(workCoordinates, workPosition);
    result.setWorkPosition(workPosition);

    return result;
}

From source file:org.goko.controller.grbl.v09.GrblCommunicator.java

/**
 * Create a status report from the given string
 * @param strStatusReport the String representing the status report
 * @return {@link StatusReport}//  ww  w  . j a  v  a  2 s .c  o m
 * @throws GkException
 */
private StatusReport parseStatusReport(String strStatusReport) throws GkException {
    StatusReport result = new StatusReport();
    int comma = StringUtils.indexOf(strStatusReport, ",");
    String state = StringUtils.substring(strStatusReport, 1, comma);
    GrblMachineState grblState = grbl.getGrblStateFromString(state);
    result.setState(grblState);

    Tuple6b machinePosition = new Tuple6b().setNull();
    Tuple6b workPosition = new Tuple6b().setNull();
    // Looking for MPosition
    Matcher mposMatcher = PATTERN_MPOS.matcher(strStatusReport);
    if (mposMatcher.matches()) {
        String mposX = mposMatcher.group(1);
        String mposY = mposMatcher.group(2);
        String mposZ = mposMatcher.group(3);
        parseTuple(machinePosition, mposX, mposY, mposZ);
        result.setMachinePosition(machinePosition);
    }
    // Looking for WPosition
    Matcher wposMatcher = PATTERN_WPOS.matcher(strStatusReport);
    if (wposMatcher.matches()) {
        int t = wposMatcher.groupCount();
        String wposX = wposMatcher.group(1);
        String wposY = wposMatcher.group(2);
        String wposZ = wposMatcher.group(3);
        parseTuple(workPosition, wposX, wposY, wposZ);
        result.setWorkPosition(workPosition);
    }

    // Looking for buffer planner occupation      
    Matcher bufMatcher = PATTERN_BUF.matcher(strStatusReport);
    if (bufMatcher.matches()) {
        Integer plannerBuffer = Integer.valueOf(bufMatcher.group(1));
        result.setPlannerBuffer(plannerBuffer);
    }
    return result;
}

From source file:org.goko.core.gcode.bean.GCodeWord.java

/**
 * @return the letter
 */
public String getLetter() {
    return StringUtils.substring(stringValue, 0, 1);
}

From source file:org.goko.core.rs274ngcv3.RS274.java

public static String getTokenLetter(GCodeToken token) {
    return StringUtils.substring(token.getValue(), 0, 1);
}

From source file:org.graylog.plugins.pipelineprocessor.functions.strings.Substring.java

@Override
public String evaluate(FunctionArgs args, EvaluationContext context) {
    final String value = valueParam.required(args, context);
    final Long startValue = startParam.required(args, context);
    if (value == null || startValue == null) {
        return null;
    }//w  w w  . ja  v a  2  s  .c  o  m
    final int start = Ints.saturatedCast(startValue);
    final int end = Ints.saturatedCast(endParam.optional(args, context).orElse((long) value.length()));

    return StringUtils.substring(value, start, end);
}

From source file:org.grible.model.Table.java

public Date getModifiedTime() {
    if (file != null) {
        String strTime = StringUtils.substring(String.valueOf(file.lastModified()), 0,
                String.valueOf(file.lastModified()).length() - 3) + "000";
        return new Date(Long.parseLong(strTime));
    }/*from  w w w .ja va  2  s  .  c  o m*/
    return modifiedTime;
}