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

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

Introduction

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

Prototype

public static String substringBeforeLast(String str, String separator) 

Source Link

Document

Gets the substring before the last occurrence of a separator.

Usage

From source file:org.beangle.model.transfer.importer.MultiEntityImporter.java

public void transferItem() {
    if (logger.isDebugEnabled()) {
        logger.debug("tranfer index:" + getTranferIndex() + ":" + ArrayUtils.toString(values));
    }//from  w ww  .  j a va 2s.  co  m
    // 
    for (int i = 0; i < attrs.length; i++) {
        Object value = values.get(attrs[i]);
        // 
        if (StringUtils.isBlank(attrs[i]))
            continue;
        // ?trim
        if (value instanceof String) {
            String strValue = (String) value;
            if (StringUtils.isBlank(strValue)) {
                value = null;
            } else {
                value = StringUtils.trim(strValue);
            }
        }
        // ?null
        if (null == value) {
            continue;
        } else {
            if (value.equals(Model.NULL)) {
                value = null;
            }
        }
        Object entity = getCurrent(attrs[i]);
        String attr = processAttr(attrs[i]);
        String entityName = getEntityName(attrs[i]);
        // 
        if (StringUtils.contains(attr, '.')) {
            if (null != foreignerKeys) {
                boolean isForeigner = isForeigner(attr);
                // ,?parentPath?
                // ,?.
                if (isForeigner) {
                    String parentPath = StringUtils.substringBeforeLast(attr, ".");
                    ObjectAndType propertyType = populator.initProperty(entity, entityName, parentPath);
                    Object property = propertyType.getObj();
                    if (property instanceof Entity<?>) {
                        if (((Entity<?>) property).isPersisted()) {
                            populator.populateValue(entity, parentPath, null);
                            populator.initProperty(entity, entityName, parentPath);
                        }
                    }
                }
            }
        }
        populator.populateValue(entity, attr, value);
    }
}

From source file:org.beangle.model.transfer.importer.MultiEntityImporter.java

/**
 * ???? TODO ?name//from w ww .  ja  va  2s. c o m
 * 
 * @return
 */
protected List<String> checkAttrs() {
    List<String> errorAttrs = CollectUtils.newArrayList();
    List<String> rightAttrs = CollectUtils.newArrayList();
    for (int i = 0; i < attrs.length; i++) {
        if (StringUtils.isBlank(attrs[i])) {
            continue;
        }
        try {
            EntityType entityType = getEntityType(attrs[i]);
            Entity<?> example = (Entity<?>) entityType.newInstance();
            String entityName = entityType.getEntityName();
            String attr = processAttr(attrs[i]);
            if (attr.indexOf('.') > -1) {
                populator.initProperty(example, entityName, StringUtils.substringBeforeLast(attr, "."));
            }
            rightAttrs.add(attrs[i]);
        } catch (Exception e) {
            errorAttrs.add(attrs[i]);
        }
    }

    attrs = new String[rightAttrs.size()];
    rightAttrs.toArray(attrs);
    return errorAttrs;
}

From source file:org.beangle.packagekit.maven.MavenUtils.java

public static SimpleResource build(String id) {
    SimpleResource resource = new SimpleResource();
    String name = StringUtils.substringBeforeLast(id, "-");
    resource.setId(id);/*from  w  w  w . j a v  a 2 s .c  om*/
    resource.setName(name);
    return resource;
}

From source file:org.beangle.struts2.convention.config.SmartActionConfigBuilder.java

protected PackageConfig.Builder getPackageConfig(Profile profile,
        final Map<String, PackageConfig.Builder> packageConfigs, Action action, final Class<?> actionClass) {
    // /*from   w w w. j  a v a  2s. co  m*/
    String actionPkg = actionClass.getPackage().getName();
    PackageConfig parentPkg = null;
    while (StringUtils.contains(actionPkg, '.')) {
        parentPkg = configuration.getPackageConfig(actionPkg);
        if (null != parentPkg) {
            break;
        } else {
            actionPkg = StringUtils.substringBeforeLast(actionPkg, ".");
        }
    }
    if (null == parentPkg) {
        actionPkg = defaultParentPackage;
        parentPkg = configuration.getPackageConfig(actionPkg);
    }
    if (parentPkg == null) {
        throw new ConfigurationException(
                "Unable to locate parent package [" + actionClass.getPackage().getName() + "]");
    }
    String actionPackage = actionClass.getPackage().getName();
    PackageConfig.Builder pkgConfig = packageConfigs.get(actionPackage);
    if (pkgConfig == null) {
        PackageConfig myPkg = configuration.getPackageConfig(actionPackage);
        if (null != myPkg) {
            pkgConfig = new PackageConfig.Builder(myPkg);
        } else {
            pkgConfig = new PackageConfig.Builder(actionPackage).namespace(action.getNamespace())
                    .addParent(parentPkg);
            logger.debug("Created package config named {} with a namespace {}", actionPackage,
                    action.getNamespace());
        }
        packageConfigs.put(actionPackage, pkgConfig);
    }
    return pkgConfig;
}

From source file:org.beangle.struts2.convention.route.Profile.java

public String getSimpleName(String className) {
    String postfix = getActionSuffix();
    String simpleName = className.substring(className.lastIndexOf('.') + 1);
    if (StringUtils.contains(simpleName, postfix)) {
        simpleName = StringUtils.uncapitalize(simpleName.substring(0, simpleName.length() - postfix.length()));
    } else {/*from   ww  w.j a va2 s .  co  m*/
        simpleName = StringUtils.uncapitalize(simpleName);
    }

    StringBuilder infix = new StringBuilder();
    infix.append(StringUtils.substringBeforeLast(className, "."));
    if (infix.length() == 0)
        return simpleName;
    infix.append('.');
    infix.append(simpleName);
    // .??/
    for (int i = 0; i < infix.length(); i++) {
        if (infix.charAt(i) == '.') {
            infix.setCharAt(i, '/');
        }
    }
    return infix.toString();
}

From source file:org.beangle.struts2.convention.route.Profile.java

/**
 * ???.?/<br>//ww w  . j  a  v a2 s.  co m
 * ?/
 * 
 * @param clazz
 * @param profile
 * @return
 */
public String getInfix(String className) {
    String postfix = getActionSuffix();
    String simpleName = className.substring(className.lastIndexOf('.') + 1);
    if (StringUtils.contains(simpleName, postfix)) {
        simpleName = StringUtils.uncapitalize(simpleName.substring(0, simpleName.length() - postfix.length()));
    } else {
        simpleName = StringUtils.uncapitalize(simpleName);
    }

    MatchInfo match = getCtlMatchInfo(className);
    StringBuilder infix = new StringBuilder(match.getReserved().toString());
    if (infix.length() > 0) {
        infix.append('.');
    }
    String remainder = StringUtils.substring(StringUtils.substringBeforeLast(className, "."),
            match.getStartIndex() + 1);
    if (remainder.length() > 0) {
        infix.append(remainder).append('.');
    }
    if (infix.length() == 0)
        return simpleName;
    infix.append(simpleName);

    // .??/
    for (int i = 0; i < infix.length(); i++) {
        if (infix.charAt(i) == '.') {
            infix.setCharAt(i, '/');
        }
    }
    return infix.toString();
}

From source file:org.beangle.struts2.view.component.Navmenu.java

public Navmenu(ValueStack stack) {
    super(stack);
    StringBuilder sb = new StringBuilder(StringUtils.substringBeforeLast(getRequestURI(), "."));
    if (-1 == sb.lastIndexOf("!")) {
        sb.append("!index");
    }//from ww w  .  ja  v  a2  s .  c  o m
    this.uri = sb.toString();
}

From source file:org.betaconceptframework.astroboa.engine.jcr.dao.ContentDao.java

/**
 * @param contetObjectId//from ww w . j  av  a 2s.c o m
 * @return
 */
public ContentObject copyContentObject(String contentObjectId) {

    if (StringUtils.isBlank(contentObjectId)) {
        return null;
    }

    ContentObject contentObjectToBeCopied = serializeContentObject(contentObjectId, CacheRegion.NONE,
            ResourceRepresentationType.CONTENT_OBJECT_INSTANCE, null, FetchLevel.FULL, true, false);

    if (contentObjectToBeCopied == null) {
        logger.warn("Could not retrieve content object with id {}. Copy operation cannot continue",
                contentObjectId);
        return null;
    }

    ((ContentObjectImpl) contentObjectToBeCopied).clean();

    int index = 0;

    String systemNameToSearch = null;
    if (StringUtils.isNotBlank(contentObjectToBeCopied.getSystemName())) {
        systemNameToSearch = new String(contentObjectToBeCopied.getSystemName().getBytes());

        if (systemNameToSearch.startsWith("copy")) {
            systemNameToSearch = systemNameToSearch.replaceFirst("copy[0-9]*", "");
        }

        //Locate other copies in order to provide the correct copy index
        ContentObjectCriteria contentObjectCriteria = CmsCriteriaFactory.newContentObjectCriteria();
        contentObjectCriteria.addSystemNameContainsCriterion("*" + systemNameToSearch);
        contentObjectCriteria.setOffsetAndLimit(0, 0);
        contentObjectCriteria.setCacheable(CacheRegion.NONE);

        CmsOutcome<ContentObject> outcome = searchContentObjects(contentObjectCriteria,
                ResourceRepresentationType.CONTENT_OBJECT_LIST);

        if (outcome != null) {
            index = (int) outcome.getCount();
        }
    }

    String newIndexAsString = index == 0 ? "" : String.valueOf(index + 1);

    //Adjust systemName
    if (contentObjectToBeCopied.getSystemName() == null) {
        contentObjectToBeCopied.setSystemName("copy" + newIndexAsString);
    } else {
        if (contentObjectToBeCopied.getSystemName().startsWith("copy")) {
            contentObjectToBeCopied.setSystemName(contentObjectToBeCopied.getSystemName()
                    .replaceFirst("copy[0-9]*", "copy" + newIndexAsString));
        } else {
            contentObjectToBeCopied
                    .setSystemName("copy" + newIndexAsString + contentObjectToBeCopied.getSystemName());
        }
    }

    //Adjust title
    StringProperty titleProperty = (StringProperty) contentObjectToBeCopied.getCmsProperty("profile.title");

    String title = titleProperty.getSimpleTypeValue();

    boolean titleHasChanged = false;

    for (int i = 1; i <= index; i++) {
        if (title.endsWith(" " + String.valueOf(i))) {
            titleProperty.setSimpleTypeValue(
                    StringUtils.substringBeforeLast(title, String.valueOf(i)) + newIndexAsString);
            titleHasChanged = true;
            break;
        }
    }

    if (!titleHasChanged) {
        titleProperty.setSimpleTypeValue(title + " " + newIndexAsString);
    }

    return contentObjectToBeCopied;

}

From source file:org.betaconceptframework.astroboa.engine.jcr.identitystore.jackrabbit.JackrabbitIdentityStoreDao.java

private ContentObject importRole(Resource roleXmlResource, String systemUserId, String cmsRepositoryId,
        String idOfTheRepositoryWhichRepresentsTheIdentityStore) throws Exception {

    if (roleXmlResource == null || !roleXmlResource.exists()) {
        throw new CmsException("No roles xml file found");
    } else {//from  w w w.ja va  2 s.co  m

        String roleName = StringUtils.substringBeforeLast(roleXmlResource.getFilename(),
                CmsConstants.PERIOD_DELIM);

        String roleAffilitation = CmsRoleAffiliationFactory.INSTANCE
                .getCmsRoleAffiliationForRepository(CmsRole.valueOf(roleName), cmsRepositoryId);

        CmsOutcome<ContentObject> outcome = findRole(roleAffilitation);

        if (outcome != null && outcome.getCount() > 0) {

            if (outcome.getCount() > 1) {
                logger.warn("Found more than one roles with system name " + roleAffilitation
                        + " Will use first role available");
            }

            return outcome.getResults().get(0);
        }

        logger.info("Role {} for identity store not found. Creating one", roleAffilitation);

        InputStream inputStream = null;

        try {
            inputStream = roleXmlResource.getInputStream();

            String roleXml = IOUtils.toString(inputStream, "UTF-8");

            //Replace ids
            roleXml = StringUtils.replace(roleXml, SYSTEM_USER_ID, systemUserId);
            roleXml = StringUtils.replace(roleXml, roleName, roleAffilitation);
            roleXml = StringUtils.replace(roleXml, IDENTITY_STORE_REPOSITORY_ID,
                    idOfTheRepositoryWhichRepresentsTheIdentityStore);

            /*
             * Currently, the identifier of the repository which represents the identity store
             * is used in accessibility.canBeUpdated / accessibility.canBeDeleted properties
             * whose value follows the pattern ROLE_CMS_IDENTITY_STORE_EDITOR@IDENTITY_STORE_REPOSITORY_ID. 
             * In the case of the ROLE_CMS_IDENTITY_STORE_EDITOR.xml template, 
             * the replacements above will generate the outcome 
             * ROLE_CMS_IDENTITY_STORE_EDITOR@<cmsRepositoryId>@<idOfTheRepositoryWhichRepresentsTheIdentityStore>
             * 
             * That is happening because the role name ROLE_CMS_IDENTITY_STORE_EDITOR is replaced once
             * by the roleAffiliation (roleName + repositoryId)   
             * 
             *    roleXml = StringUtils.replace(roleXml, roleName, roleAffilitation);
             * 
             *     ROLE_CMS_IDENTITY_STORE_EDITOR@IDENTITY_STORE_REPOSITORY_ID becomes
             * 
             * ROLE_CMS_IDENTITY_STORE_EDITOR@<cmsRepositoryId>@IDENTITY_STORE_REPOSITORY_ID
             * 
             * and then the following replacement is executed
             * 
             * roleXml = StringUtils.replace(roleXml, IDENTITY_STORE_REPOSITORY_ID, idOfTheRepositoryWhichRepresentsTheIdentityStore);
             * 
             * to produce the following result 
             * 
             * ROLE_CMS_IDENTITY_STORE_EDITOR@<cmsRepositoryId>@<idOfTheRepositoryWhichRepresentsTheIdentityStore>
             */

            if (StringUtils.contains(roleXml,
                    "@" + cmsRepositoryId + "@" + idOfTheRepositoryWhichRepresentsTheIdentityStore)) {
                roleXml = StringUtils.replace(roleXml,
                        "@" + cmsRepositoryId + "@" + idOfTheRepositoryWhichRepresentsTheIdentityStore,
                        "@" + idOfTheRepositoryWhichRepresentsTheIdentityStore);
            }

            //Obtain content object
            ImportConfiguration configuration = ImportConfiguration.object().persist(PersistMode.DO_NOT_PERSIST)
                    .build();

            ContentObject roleObject = importDao.importContentObject(roleXml, configuration);

            if (roleObject == null) {
                throw new CmsException("Could not create a content object from provided source");
            }

            //fix system name
            roleObject.setSystemName(cmsRepositoryEntityUtils.fixSystemName(roleObject.getSystemName()));

            return roleObject;
        } finally {
            if (inputStream != null) {
                IOUtils.closeQuietly(inputStream);
            }
        }

    }

}

From source file:org.betaconceptframework.astroboa.engine.jcr.util.JcrNodeUtils.java

public static String getYearMonthDayPathForContentObjectNode(Node contentObjectNode)
        throws RepositoryException {

    if (contentObjectNode == null || contentObjectNode.getParent() == null) {
        return "";
    }/*from   w w w .j ava  2 s  .  c om*/

    //In  releases prior to 3 (2.x.x) content object nodes were stored
    //under path  contentTypeFolder/year/month/day
    //where as from release 3 and onwards content object nodes are stored under path
    //contentTypeFolder/year/month/day/hour/minute

    //This method takes under consideration both structures for compatibility reasons

    //Find content object type folder
    Node contentObjectTypeFolderNode = contentObjectNode.getParent();
    //Try to find contentObjectTypeFolder node
    while (contentObjectTypeFolderNode != null
            && !contentObjectTypeFolderNode.isNodeType(CmsBuiltInItem.GenericContentTypeFolder.getJcrName())) {
        contentObjectTypeFolderNode = contentObjectTypeFolderNode.getParent();
    }

    if (contentObjectTypeFolderNode == null) {
        return "";
    }

    String contentObjectNodeParentPath = contentObjectNode.getParent().getPath();
    String contentObjectTypeFolderPath = contentObjectTypeFolderNode.getPath();
    String path = StringUtils.difference(contentObjectTypeFolderPath + "/", contentObjectNodeParentPath);

    logger.debug("CO Parent Path {} \n Type Folder Path {}\n Difference {}",
            new Object[] { contentObjectNodeParentPath, contentObjectTypeFolderPath, path });

    //Path has either the format  year/month/day or year/month/day/hour/minute
    int count = StringUtils.countMatches(path, "/");

    if (count == 2) {
        return path;
    } else {
        //Must return the first two
        path = StringUtils.substringBeforeLast(path, "/");
        return StringUtils.substringBeforeLast(path, "/");
    }

}