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

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

Introduction

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

Prototype

public static String substring(String str, int start) 

Source Link

Document

Gets a substring from the specified String avoiding exceptions.

Usage

From source file:org.jahia.services.search.facets.SimpleJahiaJcrFacets.java

private NamedList<Object> sortValuesAfterChoiceListRenderer(NamedList<Object> values,
        ChoiceListRenderer renderer, ExtendedPropertyDefinition fieldPropertyType, Locale locale) {
    try {//w w  w.ja  v  a 2  s .  com
        //use case-insensitive and locale aware collator
        Collator collator = Collator.getInstance(locale);
        collator.setStrength(Collator.TERTIARY);
        Map<String, Integer> sortedLabels = new TreeMap<>(collator);
        int i = 0;
        boolean resolveReference = renderer instanceof NodeReferenceChoiceListRenderer ? true : false;
        JCRSessionWrapper currentUserSession = resolveReference
                ? JCRSessionFactory.getInstance().getCurrentUserSession(session.getWorkspace().getName(),
                        locale)
                : null;

        for (Map.Entry<String, Object> facetValueEntry : values) {
            String facetValueKey = facetValueEntry.getKey();
            sortedLabels.put(renderer.getStringRendering(locale, fieldPropertyType,
                    resolveReference
                            ? currentUserSession
                                    .getNode(StringUtils.substring(facetValueKey, facetValueKey.indexOf('/')))
                            : facetValueKey),
                    i++);
        }

        NamedList<Object> sortedValues = new NamedList<>();
        for (Integer index : sortedLabels.values()) {
            sortedValues.add(values.getName(index), values.getVal(index));
        }
        return sortedValues;
    } catch (RepositoryException | UnsupportedOperationException e) {
        logger.warn("Exception while sorting label rendered facet values, fallback to default sorting", e);
        return values;
    }
}

From source file:org.jboss.loom.utils.as7.AS7CliUtils.java

/**
 *  Parses the index of operation which failed.
 * //  w  w w .  j  a  v  a 2s . c  o  m
 *  "failure-description" => 
 *  {"JBAS014653: Composite operation failed and was rolled back. Steps that failed:" => {
 *      "Operation step-12" => "JBAS014803: Duplicate resource [
        (\"subsystem\" => \"security\"),
        (\"security-domain\" => \"other\") ]"
}}
* 
* @deprecated  Use extractFailedOperationNode().
 */
public static Integer parseFailedOperationIndex(final ModelNode node) throws MigrationException {

    if (ClientConstants.SUCCESS.equals(node.get(ClientConstants.OUTCOME).asString()))
        return 0;

    if (!node.hasDefined(ClientConstants.FAILURE_DESCRIPTION))
        return null;

    ModelNode failDesc = node.get(ClientConstants.FAILURE_DESCRIPTION);
    String key = failDesc.keys().iterator().next();
    // "JBAS014653: Composite operation failed and was rolled back. Steps that failed:" => ...

    ModelNode compositeFailDesc = failDesc.get(key);
    // { "Operation step-1" => "JBAS014803: Duplicate resource ...

    Set<String> keys = compositeFailDesc.keys();
    String opKey = keys.iterator().next();
    // "Operation step-XX"

    if (!opKey.startsWith(OP_KEY_PREFIX))
        return null;

    String opIndex = StringUtils.substring(opKey, OP_KEY_PREFIX.length());

    return Integer.parseInt(opIndex);
}

From source file:org.jboss.loom.utils.as7.AS7CliUtils.java

/**
 * @returns A ModelNode with two properties: "failedOpIndex" and "failureDesc".
 *//*from   ww  w.j  a  v a2 s .  com*/
public static BatchFailure extractFailedOperationNode(final ModelNode node) throws MigrationException {

    if (ClientConstants.SUCCESS.equals(node.get(ClientConstants.OUTCOME).asString()))
        return null;

    if (!node.hasDefined(ClientConstants.FAILURE_DESCRIPTION))
        return null;

    ModelNode failDesc = node.get(ClientConstants.FAILURE_DESCRIPTION);
    if (failDesc.getType() != ModelType.OBJECT)
        return null;

    String key = failDesc.keys().iterator().next();
    // "JBAS014653: Composite operation failed and was rolled back. Steps that failed:" => ...

    ModelNode compositeFailDesc = failDesc.get(key);
    // { "Operation step-1" => "JBAS014803: Duplicate resource ...

    Set<String> keys = compositeFailDesc.keys();
    String opKey = keys.iterator().next();
    // "Operation step-XX"

    if (!opKey.startsWith(OP_KEY_PREFIX))
        return null;

    String opIndex = StringUtils.substring(opKey, OP_KEY_PREFIX.length());

    return new BatchFailure(Integer.parseInt(opIndex), compositeFailDesc.get(opKey).toString());
}

From source file:org.kuali.kfs.sys.batch.SemaphoreInputFileType.java

/**
 * Validate that the first line of the file contains a job name and a valid Step (the bean id)
 * in the format jobName.stepName/* w w  w .  jav a  2  s.  c o  m*/
 *
 * @see org.kuali.kfs.sys.batch.BatchInputFileType#validate(Object)
 */
@Override
public boolean validate(Object parsedFileContents) {
    List<String> content = getParsedFileContent(parsedFileContents);

    if (content.size() <= 0) {
        MessageMap errors = new MessageMap();
        errors.putError(KFSConstants.GLOBAL_ERRORS, KFSKeyConstants.Semaphore.ERROR_BATCH_UPLOAD_INVALID_STEP);
        GlobalVariables.mergeErrorMap(errors);
        return false;
    }

    String firstLine = content.get(0);
    String stepName = StringUtils.substring(firstLine,
            StringUtils.lastIndexOf(firstLine, BatchStepFileDescriptor.STEP_FILE_NAME_SEPARATOR) + 1);

    Step step = BatchSpringContext.getStep(stepName);
    if (step == null) {
        LOG.error("Unable to find bean for step: " + stepName);
        MessageMap errors = new MessageMap();
        errors.putError(KFSConstants.GLOBAL_ERRORS, KFSKeyConstants.Semaphore.ERROR_BATCH_UPLOAD_INVALID_STEP);
        GlobalVariables.mergeErrorMap(errors);
        return false;
    }

    return true;
}

From source file:org.kuali.kfs.sys.context.BatchStepFileDescriptor.java

/**
 * Retrieves the extension from the File
 *
 * @param runFile the semaphore file//  w  ww  . j a  v  a 2  s  .co m
 * @return the extension
 */
private String getExtensionFromFile(File runFile) {
    String runFileName = runFile.getName();
    int indexOfExtension = runFileName.lastIndexOf(STEP_FILE_EXTENSION_SEPARATOR);
    String extension = StringUtils.substring(runFileName, indexOfExtension + 1);
    return extension;
}

From source file:org.kuali.maven.plugins.externals.MojoHelper.java

private boolean qualifierContainsVersionedPrefix(String targetPrefix, String qualifier) {

    if (StringUtils.isBlank(qualifier)) {
        return false;
    } else if (qualifier.length() < targetPrefix.length()) {
        return false;
    } else {//from   w  ww  .j av a 2 s .  co m
        if (qualifier.toLowerCase().startsWith(targetPrefix.toLowerCase())) {

            try {
                String suffix = StringUtils.substring(qualifier, targetPrefix.length());
                Integer.parseInt(suffix);
            } catch (NumberFormatException e) {

                return false;
            }

        } else {
            return false;
        }
    }
    return true;
}

From source file:org.kuali.rice.kim.impl.identity.PersonServiceImpl.java

/**
 * @see org.kuali.rice.kim.api.identity.PersonService#resolvePrincipalNamesToPrincipalIds(org.kuali.rice.krad.bo.BusinessObject, java.util.Map)
 *///  w  ww  .  j  a va  2 s.com
@Override
@SuppressWarnings("unchecked")
public Map<String, String> resolvePrincipalNamesToPrincipalIds(BusinessObject businessObject,
        Map<String, String> fieldValues) {
    if (fieldValues == null) {
        return null;
    }
    if (businessObject == null) {
        return fieldValues;
    }
    StringBuffer resolvedPrincipalIdPropertyName = new StringBuffer();
    // save off all criteria which are not references to Person properties
    // leave person properties out so they can be resolved and replaced by this method
    Map<String, String> processedFieldValues = getNonPersonSearchCriteria(businessObject, fieldValues);
    for (String propertyName : fieldValues.keySet()) {
        if (!StringUtils.isBlank(fieldValues.get(propertyName)) // property has a value
                && isPersonProperty(businessObject, propertyName) // is a property on a Person object
        ) {
            // strip off the prefix on the property
            int lastPropertyIndex = PropertyAccessorUtils.getLastNestedPropertySeparatorIndex(propertyName);
            String personPropertyName = lastPropertyIndex != -1
                    ? StringUtils.substring(propertyName, lastPropertyIndex + 1)
                    : propertyName;
            // special case - the user ID
            if (StringUtils.equals(KIMPropertyConstants.Person.PRINCIPAL_NAME, personPropertyName)) {
                Class targetBusinessObjectClass = null;
                BusinessObject targetBusinessObject = null;
                resolvedPrincipalIdPropertyName.setLength(0); // clear the buffer without requiring a new object allocation on each iteration
                // get the property name up until the ".principalName"
                // this should be a reference to the Person object attached to the BusinessObject
                String personReferenceObjectPropertyName = lastPropertyIndex != -1
                        ? StringUtils.substring(propertyName, 0, lastPropertyIndex)
                        : StringUtils.EMPTY;
                // check if the person was nested within another BO under the master BO.  If so, go up one more level
                // otherwise, use the passed in BO class as the target class
                if (PropertyAccessorUtils.isNestedOrIndexedProperty(personReferenceObjectPropertyName)) {
                    int lastTargetIndex = PropertyAccessorUtils
                            .getLastNestedPropertySeparatorIndex(personReferenceObjectPropertyName);
                    String targetBusinessObjectPropertyName = lastTargetIndex != -1
                            ? StringUtils.substring(personReferenceObjectPropertyName, 0, lastTargetIndex)
                            : StringUtils.EMPTY;
                    DataObjectWrapper<BusinessObject> wrapper = KradDataServiceLocator.getDataObjectService()
                            .wrap(businessObject);
                    targetBusinessObject = (BusinessObject) wrapper
                            .getPropertyValueNullSafe(targetBusinessObjectPropertyName);
                    if (targetBusinessObject != null) {
                        targetBusinessObjectClass = targetBusinessObject.getClass();
                        resolvedPrincipalIdPropertyName.append(targetBusinessObjectPropertyName).append(".");
                    } else {
                        LOG.error("Could not find target property '" + propertyName + "' in class "
                                + businessObject.getClass().getName() + ". Property value was null.");
                    }
                } else { // not a nested Person property
                    targetBusinessObjectClass = businessObject.getClass();
                    targetBusinessObject = businessObject;
                }

                if (targetBusinessObjectClass != null) {
                    // use the relationship metadata in the KNS to determine the property on the
                    // host business object to put back into the map now that the principal ID
                    // (the value stored in application tables) has been resolved
                    int lastIndex = PropertyAccessorUtils
                            .getLastNestedPropertySeparatorIndex(personReferenceObjectPropertyName);
                    String propName = lastIndex != -1
                            ? StringUtils.substring(personReferenceObjectPropertyName, lastIndex + 1)
                            : personReferenceObjectPropertyName;
                    DataObjectRelationship rel = getBusinessObjectMetaDataService()
                            .getBusinessObjectRelationship(targetBusinessObject, propName);
                    if (rel != null) {
                        String sourcePrimitivePropertyName = rel
                                .getParentAttributeForChildAttribute(KIMPropertyConstants.Person.PRINCIPAL_ID);
                        resolvedPrincipalIdPropertyName.append(sourcePrimitivePropertyName);
                        // get the principal - for translation of the principalName to principalId
                        String principalName = fieldValues.get(propertyName);
                        Principal principal = getIdentityService().getPrincipalByPrincipalName(principalName);
                        if (principal != null) {
                            processedFieldValues.put(resolvedPrincipalIdPropertyName.toString(),
                                    principal.getPrincipalId());
                        } else {
                            processedFieldValues.put(resolvedPrincipalIdPropertyName.toString(), null);
                            try {
                                // if the principalName is bad, then we need to clear out the Person object
                                // and base principalId property
                                // so that their values are no longer accidentally used or re-populate
                                // the object
                                KRADUtils.setObjectProperty(targetBusinessObject,
                                        resolvedPrincipalIdPropertyName.toString(), null);
                                KRADUtils.setObjectProperty(targetBusinessObject, propName, null);
                                KRADUtils.setObjectProperty(targetBusinessObject, propName + ".principalName",
                                        principalName);
                            } catch (Exception ex) {
                                LOG.error(
                                        "Unable to blank out the person object after finding that the person with the given principalName does not exist.",
                                        ex);
                            }
                        }
                    } else {
                        LOG.error("Missing relationship for " + propName + " on "
                                + targetBusinessObjectClass.getName());
                    }
                } else { // no target BO class - the code below probably will not work
                    processedFieldValues.put(resolvedPrincipalIdPropertyName.toString(), null);
                }
            }
            // if the property does not seem to match the definition of a Person property but it
            // does end in principalName then...
            // this is to handle the case where the user ID is on an ADD line - a case excluded from isPersonProperty()
        } else if (propertyName.endsWith("." + KIMPropertyConstants.Person.PRINCIPAL_NAME)) {
            // if we're adding to a collection and we've got the principalName; let's populate universalUser
            String principalName = fieldValues.get(propertyName);
            if (StringUtils.isNotEmpty(principalName)) {
                String containerPropertyName = propertyName;
                if (containerPropertyName.startsWith(KRADConstants.MAINTENANCE_ADD_PREFIX)) {
                    containerPropertyName = StringUtils.substringAfter(propertyName,
                            KRADConstants.MAINTENANCE_ADD_PREFIX);
                }
                // get the class of the object that is referenced by the property name
                // if this is not true then there's a principalName collection or primitive attribute
                // directly on the BO on the add line, so we just ignore that since something is wrong here
                if (PropertyAccessorUtils.isNestedOrIndexedProperty(containerPropertyName)) {
                    // the first part of the property is the collection name
                    String collectionName = StringUtils.substringBefore(containerPropertyName, ".");
                    // what is the class held by that collection?
                    // JHK: I don't like this.  This assumes that this method is only used by the maintenance
                    // document service.  If that will always be the case, this method should be moved over there.
                    Class<? extends BusinessObject> collectionBusinessObjectClass = getMaintenanceDocumentDictionaryService()
                            .getCollectionBusinessObjectClass(getMaintenanceDocumentDictionaryService()
                                    .getDocumentTypeName(businessObject.getClass()), collectionName);
                    if (collectionBusinessObjectClass != null) {
                        // we are adding to a collection; get the relationships for that object;
                        // is there one for personUniversalIdentifier?
                        List<DataObjectRelationship> relationships = getBusinessObjectMetaDataService()
                                .getBusinessObjectRelationships(collectionBusinessObjectClass);
                        // JHK: this seems like a hack - looking at all relationships for a BO does not guarantee that we get the right one
                        // JHK: why not inspect the objects like above?  Is it the property path problems because of the .add. portion?
                        for (DataObjectRelationship rel : relationships) {
                            String parentAttribute = rel.getParentAttributeForChildAttribute(
                                    KIMPropertyConstants.Person.PRINCIPAL_ID);
                            if (parentAttribute == null) {
                                continue;
                            }
                            // there is a relationship for personUserIdentifier; use that to find the universal user
                            processedFieldValues.remove(propertyName);
                            String fieldPrefix = StringUtils
                                    .substringBeforeLast(StringUtils.substringBeforeLast(propertyName,
                                            "." + KIMPropertyConstants.Person.PRINCIPAL_NAME), ".");
                            String relatedPrincipalIdPropertyName = fieldPrefix + "." + parentAttribute;
                            // KR-683 Special handling for extension objects
                            if (EXTENSION.equals(StringUtils.substringAfterLast(fieldPrefix, "."))
                                    && EXTENSION.equals(StringUtils.substringBefore(parentAttribute, "."))) {
                                relatedPrincipalIdPropertyName = fieldPrefix + "."
                                        + StringUtils.substringAfter(parentAttribute, ".");
                            }
                            String currRelatedPersonPrincipalId = processedFieldValues
                                    .get(relatedPrincipalIdPropertyName);
                            if (StringUtils.isBlank(currRelatedPersonPrincipalId)) {
                                Principal principal = getIdentityService()
                                        .getPrincipalByPrincipalName(principalName);
                                if (principal != null) {
                                    processedFieldValues.put(relatedPrincipalIdPropertyName,
                                            principal.getPrincipalId());
                                } else {
                                    processedFieldValues.put(relatedPrincipalIdPropertyName, null);
                                }
                            }
                        } // relationship loop
                    } else {
                        if (LOG.isDebugEnabled()) {
                            LOG.debug(
                                    "Unable to determine class for collection referenced as part of property: "
                                            + containerPropertyName + " on "
                                            + businessObject.getClass().getName());
                        }
                    }
                } else {
                    if (LOG.isDebugEnabled()) {
                        LOG.debug("Non-nested property ending with 'principalName': " + containerPropertyName
                                + " on " + businessObject.getClass().getName());
                    }
                }
            }
        }
    }
    return processedFieldValues;
}

From source file:org.kuali.rice.krad.util.KRADUtils.java

/**
 * Returns the primitive part of an attribute name string.
 *
 * @param attributeName/*  ww  w .ja  v  a  2  s  .  c  o m*/
 * @return everything AFTER the last "." character in attributeName
 */
public static String getNestedAttributePrimitive(String attributeName) {
    int lastIndex = PropertyAccessorUtils.getLastNestedPropertySeparatorIndex(attributeName);

    return lastIndex != -1 ? StringUtils.substring(attributeName, lastIndex + 1) : attributeName;
}

From source file:org.okj.commons.net.FtpUtils.java

/**
 * FTP//from   w ww.ja  v  a  2s.  c  om
 * @param path
 */
public void changeWorkingDirectory(String path) {
    try {
        boolean flag = ftp.changeWorkingDirectory(path);
        if (flag) {
            //
            return;
        } else {
            //
            if (StringUtils.startsWith(path, File.separator)) {
                path = StringUtils.substring(path, 1);
            }
            String[] dirs = StringUtils.split(path, File.separator);
            if (dirs.length <= 0) {
                //
                return;
            } else {
                boolean success = ftp.changeWorkingDirectory(dirs[0]);
                if (LOGGER.isInfoEnabled()) {
                    LOGGER.info("[FTPHelper] current.path=" + dirs[0]
                            + ", success=" + success + ", working.dir=" + ftp.printWorkingDirectory());
                }
                //
                String next = StringUtils.substring(path,
                        StringUtils.indexOf(path, dirs[0]) + dirs[0].length());
                changeWorkingDirectory(next);
            }
        }
    } catch (IOException ex) {
        LogUtils.error(LOGGER, "", ex);
    }
}

From source file:org.okj.commons.net.FtpUtils.java

/**
 * FTP//from w w w.  j  ava2 s.c  om
 * @param path
 */
public void createDirectory(String path) {
    try {
        boolean flag = ftp.changeWorkingDirectory(path);
        if (flag) {
            //
            return;
        } else {
            //
            if (StringUtils.startsWith(path, File.separator)) {
                path = StringUtils.substring(path, 1);
            }
            String[] dirs = StringUtils.split(path, File.separator);
            if (dirs.length <= 0) {
                //
                return;
            } else {
                if (!ftp.changeWorkingDirectory(dirs[0])) {
                    ftp.makeDirectory(dirs[0]);
                    ftp.changeWorkingDirectory(dirs[0]); //
                }

                //
                String next = StringUtils.substring(path,
                        StringUtils.indexOf(path, dirs[0]) + dirs[0].length());
                createDirectory(next);
            }
        }
    } catch (IOException ex) {
        LogUtils.error(LOGGER, "", ex);
    }
}