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

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

Introduction

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

Prototype

public static String substringBefore(String str, String separator) 

Source Link

Document

Gets the substring before the first occurrence of a separator.

Usage

From source file:com.adobe.acs.commons.errorpagehandler.impl.ErrorPageHandlerImpl.java

/**
 * Given the Request path, find the first Real Parent of the Request (even if the resource doesnt exist).
 *
 * @param request the request object// w  ww  .j a  v a  2  s.c  om
 * @param errorResource the error resource
 * @return
 */
private Resource findFirstRealParentOrSelf(SlingHttpServletRequest request, Resource errorResource) {
    if (errorResource == null) {
        log.debug("Error resource is null");
        return null;
    }

    log.trace("Finding first real parent for [ {} ]", errorResource.getPath());

    final ResourceResolver resourceResolver = errorResource.getResourceResolver();

    // Get the lowest aggregate node ancestor for the errorResource
    String path = StringUtils.substringBefore(errorResource.getPath(), JcrConstants.JCR_CONTENT);

    Resource resource = errorResource;

    if (!StringUtils.equals(path, errorResource.getPath())) {
        // Only resolve the resource if the path of the errorResource is different from the cleaned up path; else
        // we know the errorResource and what the path resolves to is the same
        // #1415 - First try to get get the resource at the direct path; this look-up is very fast (compared to rr.resolve and often what's required)
        resource = resourceResolver.getResource(path);

        if (resource == null) {
            // #1415 - If the resource is not available at the direct path, then try to resolve (handle sling:alias).
            // First map the path, as the resolve could duplicate pathing.
            resource = resourceResolver.resolve(request, resourceResolver.map(request, path));
        }
    }

    // If the resource exists, then use it!
    if (!ResourceUtil.isNonExistingResource(resource)) {
        log.debug("Found real aggregate resource at [ {} }", resource.getPath());
        return resource;
    }

    // Quick check for the Parent; Handles common case of deactivated pages
    final Resource parent = resource.getParent();
    if (parent != null && !ResourceUtil.isNonExistingResource(resource)) {
        log.debug("Found real aggregate resource via getParent() at [ {} ]", parent.getPath());
        return parent;
    }

    // Start checking the path until the first real ancestor is found
    final PathInfo pathInfo = new PathInfo(resource.getPath());
    String[] parts = StringUtils.split(pathInfo.getResourcePath(), '/');

    for (int i = parts.length - 1; i >= 0; i--) {
        String[] tmpArray = (String[]) ArrayUtils.subarray(parts, 0, i);
        String candidatePath = "/".concat(StringUtils.join(tmpArray, '/'));

        final Resource candidateResource = resourceResolver.resolve(request, candidatePath);

        if (candidateResource != null && !ResourceUtil.isNonExistingResource(candidateResource)) {
            log.debug("Found first real aggregate parent via path look-up at [ {} ]",
                    candidateResource.getPath());
            return candidateResource;
        }
    }

    log.debug("Could not find real parent for [ {} ]", errorResource.getPath());
    return null;
}

From source file:edu.monash.merc.system.scheduling.impl.TpbDataProcessor.java

public void processGPMData(List<ChromType> chromTypes, Date importedTime) {
    FTPFileGetter ftpFileGetter = new FTPFileGetter();
    GPMRSSReader gpmrssReader = new GPMRSSReader();
    String url = systemPropSettings.getPropValue(SystemPropConts.GPM_RSS_FEED_URL);
    try {/*from w  w w. j a v a2s.c  om*/
        String gpmFtpServer = null;
        String gpmFtpUserName = "anonymous";
        String gpmFtpPassword = null;
        String workingDir = null;
        String gpm2tpbReleasedFile = null;
        GPMSyndEntry gpmSyndEntry = gpmrssReader.readRSS(url);
        if (gpmSyndEntry != null) {
            gpmFtpServer = gpmSyndEntry.getGmpFtpServer();
            workingDir = gpmSyndEntry.getTpbWorkDir();
            gpm2tpbReleasedFile = gpmSyndEntry.getReleasedTpbFileName();
        }
        if (ftpFileGetter.connectAndLogin(gpmFtpServer, gpmFtpUserName, gpmFtpPassword)) {
            ftpFileGetter.changeToWorkingDirectory(workingDir);
            ftpFileGetter.setPassiveMode(true);
            //set the binary download mode
            ftpFileGetter.binary();
            FTPFile[] ftpFiles = ftpFileGetter.listFiles(gpm2tpbReleasedFile);
            //only file exists
            if (ftpFiles != null && ftpFiles.length == 1) {
                String fileLastModifiedTime = ftpFileGetter.getLastModifiedTime(gpm2tpbReleasedFile);
                logger.info("The gpm xml file: " + gpm2tpbReleasedFile + ", last modified time: "
                        + fileLastModifiedTime);
                if (!checkUpToDate(DbAcType.GPM, null, gpm2tpbReleasedFile, fileLastModifiedTime)) {
                    InputStream gpmInputStream = ftpFileGetter.downloadFileStream(gpm2tpbReleasedFile);
                    DMFileGZipper gZipper = new DMFileGZipper();
                    String outFileName = StringUtils.substringBefore(gpm2tpbReleasedFile, ".gz");
                    String storeDir = this.downloadLocation + File.separator;
                    gZipper.unzipFile(gpmInputStream, storeDir + outFileName);

                    //call completePendingCommand to to finish command
                    if (!ftpFileGetter.completePendingCommand()) {
                        ftpFileGetter.logout();
                        ftpFileGetter.disconnect();
                    }
                    processGPMXML(chromTypes, (storeDir + outFileName), gpm2tpbReleasedFile, importedTime,
                            fileLastModifiedTime);
                } else {
                    logger.info("The gpm xml file - " + gpm2tpbReleasedFile + " is already imported.");
                }
            } else {
                logger.warn("The gpm xml file: " + gpm2tpbReleasedFile
                        + " doesn't exist, ignore the data importing for the gpm.");
            }
        }
    } catch (Exception ex) {
        logger.error(ex);
    } finally {
        try {
            gpmrssReader.release();
            ftpFileGetter.logout();
            ftpFileGetter.disconnect();
        } catch (Exception ftpEx) {
            //ignore whatever caught here
        }
    }
}

From source file:com.healthcit.cacure.model.admin.GeneratedModuleDataDetail.java

/**
 * Static method which returns the specified part of a given questionCombination map key
 */// ww  w .  j  a v  a  2  s.  com
public static String getMapKeyPart(String mapKey, int part) {
    if (part == MAP_KEY_FIRST_PART)
        return StringUtils.substringBefore(mapKey, MAP_KEY_SEPARATOR);

    else if (part == MAP_KEY_SECOND_PART)
        return StringUtils.substringAfter(mapKey, MAP_KEY_SEPARATOR);

    else
        return null;
}

From source file:com.hangum.tadpole.importexport.core.dialogs.CsvToRDBImportDialog.java

private boolean loadObjectDiableStatements(String tableName) {
    try {//from   ww  w.ja  va2 s  . co m
        disableObjectResults.clear();
        SqlMapClient sqlClient = TadpoleSQLManager.getInstance(userDB);

        if (btnTrigger.getSelection()) {
            disableObjectResults = sqlClient.queryForList("triggerListInTable", tableName); //$NON-NLS-1$
        }

        if (btnPk.getSelection()) {
            if (userDB.getDBDefine() == DBDefine.ALTIBASE_DEFAULT) {
                Map<String, String> parameters = new HashMap<String, String>(2);
                parameters.put("user_name", StringUtils.substringBefore(tableName, "."));
                parameters.put("table_name", StringUtils.substringAfter(tableName, "."));
                disableObjectResults = sqlClient.queryForList("primarykeyListInTable", parameters);
            } else {
                disableObjectResults = sqlClient.queryForList("primarykeyListInTable", tableName); //$NON-NLS-1$
            }
        }

        return true;
    } catch (Exception e) {
        logger.error("loadObjectDiableStatements", e); //$NON-NLS-1$
        //appendPreviewSQL("/* Disable Object not support or select. */");
        return false;
    }
}

From source file:edu.arizona.kra.kim.impl.identity.PersonServiceImpl.java

/**
 * @see org.kuali.rice.kim.api.identity.PersonService#resolvePrincipalNamesToPrincipalIds(org.kuali.rice.krad.bo.BusinessObject, java.util.Map)
 *//*from   ww  w  . j  a  v a  2  s .  c o  m*/
@SuppressWarnings("unchecked")
@Override
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
            String personPropertyName = ObjectUtils.getNestedAttributePrimitive(propertyName);
            // special case - the user ID 
            if (StringUtils.equals(KIMPropertyConstants.Person.PRINCIPAL_NAME, personPropertyName)) {
                @SuppressWarnings("rawtypes")
                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 = ObjectUtils.getNestedAttributePrefix(propertyName);
                // 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 (ObjectUtils.isNestedAttribute(personReferenceObjectPropertyName)) {
                    String targetBusinessObjectPropertyName = ObjectUtils
                            .getNestedAttributePrefix(personReferenceObjectPropertyName);
                    targetBusinessObject = (BusinessObject) ObjectUtils.getPropertyValue(businessObject,
                            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
                    String propName = ObjectUtils
                            .getNestedAttributePrimitive(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
                                ObjectUtils.setObjectProperty(targetBusinessObject,
                                        resolvedPrincipalIdPropertyName.toString(), null);
                                ObjectUtils.setObjectProperty(targetBusinessObject, propName, null);
                                ObjectUtils.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 (ObjectUtils.isNestedAttribute(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:com.hangum.tadpole.importexport.core.dialogs.CsvToRDBImportDialog.java

private HashMap<String, Object> loadPrimaryKeyColumns(String tableName) {
    List<HashMap> showIndexColumns = null;
    HashMap<String, Object> result = new HashMap<String, Object>();
    String columns = ""; //$NON-NLS-1$
    try {//from   w  w w . ja  va  2s .  c  o  m
        SqlMapClient sqlClient = TadpoleSQLManager.getInstance(userDB);
        if (userDB.getDBDefine() == DBDefine.ALTIBASE_DEFAULT) {
            Map<String, String> parameters = new HashMap<String, String>(2);
            parameters.put("user_name", StringUtils.substringBefore(tableName, "."));
            parameters.put("table_name", StringUtils.substringAfter(tableName, "."));

            showIndexColumns = sqlClient.queryForList("primarykeyListInTable", parameters);
        } else {
            showIndexColumns = sqlClient.queryForList("primarykeyListInTable", tableName); //$NON-NLS-1$
        }

        for (HashMap dao : showIndexColumns) {
            if (userDB.getDBDefine() == DBDefine.SQLite_DEFAULT) {
                /* cid, name, type, notnull, dflt_value, pk */
                if ("1".equals(dao.get("pk").toString())) { //$NON-NLS-1$ //$NON-NLS-2$
                    result.put(dao.get("name").toString(), (Integer) dao.get("cid") + 1); //$NON-NLS-1$ //$NON-NLS-2$
                    columns += dao.get("name").toString() + ","; //$NON-NLS-1$ //$NON-NLS-2$
                }
            } else {
                result.put(dao.get("column_name").toString(), //$NON-NLS-1$
                        Integer.parseInt(dao.get("column_order").toString())); //$NON-NLS-1$
                columns += dao.get("column_name").toString() + ","; //$NON-NLS-1$ //$NON-NLS-2$
            }
        }
    } catch (Exception e) {
        logger.error("loadObjectDiableStatements", e); //$NON-NLS-1$
        appendPreviewSQL("/* Disable Object not support or select. */"); //$NON-NLS-1$
    }

    result.put("all_key_columns", StringUtils.split(columns, ",")); //$NON-NLS-1$ //$NON-NLS-2$

    return result;
}

From source file:com.abssh.util.GenericDao.java

/**
 * countHql.hql??select count(*)?//  w w w .ja  v  a 2  s  .c  o  m
 * 
 * <br/>
 * ???hql?,??hql?count?.
 */
protected long countHqlResult(final String hql, final Object... params) {
    String fromHql = hql;
    // select??order by???count,?.
    fromHql = "from " + StringUtils.substringAfter(fromHql, "from");
    if (fromHql.indexOf("order by") > 0) {
        fromHql = StringUtils.substringBefore(fromHql, "order by");
    }

    String countHql = "select count(*) " + fromHql;

    try {
        Long count = findUnique(countHql, params);
        return count;
    } catch (Exception e) {
        throw new RuntimeException("can't auto count,hql is:" + countHql, e);
    }
}

From source file:com.abssh.util.GenericDao.java

/**
 * countHql.hql??select count(*)?//ww w  .  j ava 2s .c o m
 * 
 * ???hql?,??hql?count?.
 */
protected long countHqlResult(final String hql, final Map<String, Object> values) {
    String fromHql = hql;
    // select??order by???count,?.
    fromHql = "from " + StringUtils.substringAfter(fromHql, "from");
    if (fromHql.indexOf("order by") > 0) {
        fromHql = StringUtils.substringBefore(fromHql, "order by");
    }

    String countHql = "select count(*) " + fromHql;

    try {
        Long count = findUnique(countHql, values);
        return count;
    } catch (Exception e) {
        throw new RuntimeException("can't auto count,hql is:" + countHql, e);
    }
}

From source file:net.di2e.ecdr.commons.endpoint.rest.AbstractRestSearchEndpoint.java

protected String getURLScheme() {
    return StringUtils.substringBefore(SystemBaseUrl.getProtocol(), ":");
}

From source file:com.abssh.util.GenericDao.java

/**
 * countSQL.hql??select count(*)?/*  w  w  w .  j  a va2s .  c  o  m*/
 * 
 * <br/>
 * ???sql?,??sql?count?.
 * 
 * @author zhirong
 */
protected long countSqlResult(final String sql, final Object... params) {
    String fromSql = sql;
    // select??order by???count,?.
    fromSql = "from " + StringUtils.substringAfter(fromSql, "from");
    if (fromSql.indexOf("order by") > 0) {
        fromSql = StringUtils.substringBefore(fromSql, "order by");
    }

    String countSql = "select count(*) " + fromSql;

    try {
        Long count = null;
        Object obj = findUniqueSQL(countSql, params);
        if (obj instanceof BigInteger) {
            count = ((BigInteger) obj).longValue();
        } else if (obj instanceof BigDecimal) {
            count = ((BigDecimal) obj).longValue();
        }
        return count;
    } catch (Exception e) {
        e.printStackTrace();
        throw new RuntimeException("can't auto count,sql is:" + countSql, e);
    }
}