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

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

Introduction

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

Prototype

public static String removeEnd(String str, String remove) 

Source Link

Document

Removes a substring only if it is at the end of a source string, otherwise returns the source string.

Usage

From source file:org.hydracache.server.httpd.handler.BaseHttpMethodHandler.java

protected String extractRequestContext(final String requestUri) {
    String requestString = StringUtils.trim(requestUri);

    requestString = StringUtils.removeStart(requestString, SLASH);
    requestString = StringUtils.removeEnd(requestString, SLASH);

    if (StringUtils.contains(requestString, SLASH)) {
        requestString = StringUtils.substringBefore(requestString, SLASH);
    } else {//from www.  j a  va 2s  .co m
        requestString = "";
    }

    return requestString;
}

From source file:org.jahia.bin.Login.java

protected static boolean isAuthorizedRedirect(HttpServletRequest request, String redirectUrl,
        boolean authorizeNullRedirect) {
    if (redirectUrl == null) {
        return authorizeNullRedirect;
    }/*from w w w .ja  va 2s .  com*/
    if (redirectUrl.contains("://")) {
        if (redirectUrl.startsWith("http://") || redirectUrl.startsWith("https://")) {
            String redirectUrlAfterProtocol = StringUtils.substringAfter(redirectUrl, "://");
            String urlBase = StringUtils.substringAfter(
                    StringUtils.removeEnd(request.getRequestURL().toString(), request.getRequestURI()), "://");
            if (redirectUrlAfterProtocol.startsWith(urlBase)) {
                return true;
            }
            for (String authorizedRedirectHost : SettingsBean.getInstance().getAuthorizedRedirectHosts()) {
                if (redirectUrlAfterProtocol.startsWith(authorizedRedirectHost)) {
                    return true;
                }
            }
        }
        // Block non-HTTP URls, like ftp://...
        return false;
    }
    // Block any other absolute URLs, like mailto:some@mail.com or even http:\\www.somedomain.com, which works on Google Chrome
    // Second part of the test is to allow relative URLs that contain a colon in the end
    int indexOfColon = redirectUrl.indexOf(":");
    int indexOfSlash = redirectUrl.indexOf("/");
    if (indexOfColon >= 0 && (indexOfSlash < 0 || indexOfColon < indexOfSlash)) {
        return false;
    }
    // relative URL
    return true;
}

From source file:org.jahia.modules.external.admin.mount.model.MountPoint.java

public MountPoint(JCRMountPointNode node) throws RepositoryException {
    this.realName = node.getName();
    this.name = StringUtils.removeEnd(node.getName(), JCRMountPointNode.MOUNT_SUFFIX);
    this.path = node.getTargetMountPointPath();

    // check the root node update mount point status
    try {/*  www .  ja  va  2 s .  com*/
        node.getSession().getNode(path);
    } catch (Exception e) {
        // Do nothing
    }
    this.status = node.getMountStatus();
    this.identifier = node.getIdentifier();
    this.nodetype = node.getPrimaryNodeType().getName();
    // update mount point status

    switch (node.getMountStatus()) {
    case unmounted:
        displayStatusClass = "";
        showMountAction = true;
        break;
    case mounted:
        showUnmountAction = true;
        displayStatusClass = "label-success";
        break;
    case error:
        displayStatusClass = "label-important";
        break;
    case waiting:
        displayStatusClass = "label-warning";
        break;
    }
    try {
        Locale locale = LocaleContextHolder.getLocale();
        mountPointProperties = new LinkedHashMap<>();
        JCRValueWrapper[] protectedProperties = node.hasProperty("protectedProperties")
                ? node.getProperty("protectedProperties").getValues()
                : null;
        List<String> protectedPropertiesNames = null;
        if (protectedProperties != null) {
            protectedPropertiesNames = new ArrayList<>();
            for (JCRValueWrapper jcrValueWrapper : protectedProperties) {
                protectedPropertiesNames.add(jcrValueWrapper.getString());
            }
        }

        for (PropertyDefinition def : NodeTypeRegistry.getInstance().getNodeType(nodetype)
                .getDeclaredPropertyDefinitions()) {
            if (node.hasProperty(def.getName())) {
                if (protectedPropertiesNames != null && protectedPropertiesNames.contains(def.getName())) {
                    continue;
                }
                JCRPropertyWrapper mountPointProperty = node.getProperty(def.getName());
                ExtendedPropertyDefinition extPropDef = (ExtendedPropertyDefinition) mountPointProperty
                        .getDefinition();
                if (!extPropDef.isHidden()) {
                    String key = extPropDef.getLabel(locale) + " (" + def.getName() + ")";
                    if (mountPointProperty.isMultiple()) {
                        StringBuilder sb = new StringBuilder();
                        for (Value v : mountPointProperty.getValues()) {
                            if (sb.length() > 0) {
                                sb.append(" - ");
                            }
                            sb.append(v.getString());
                        }
                        mountPointProperties.put(key, sb.toString());
                    } else {
                        mountPointProperties.put(key, mountPointProperty.getValue().getString());
                    }
                }
            }
        }
    } catch (NoSuchNodeTypeException e) {
        logger.warn("unable to get declared properties for " + nodetype);
    }
}

From source file:org.jahia.modules.external.modules.ModulesDataSource.java

private ExternalData getPropertyDefinitionData(String path, ExtendedPropertyDefinition propertyDefinition,
        boolean unstructured) {
    Map<String, String[]> properties = new HashMap<String, String[]>();
    properties.put(J_AUTO_CREATED, new String[] { String.valueOf(propertyDefinition.isAutoCreated()) });
    properties.put(J_MANDATORY, new String[] { String.valueOf(propertyDefinition.isMandatory()) });
    properties.put(J_ON_PARENT_VERSION,/*w w  w .  j a  v  a  2 s  . com*/
            new String[] { OnParentVersionAction.nameFromValue(propertyDefinition.getOnParentVersion()) });
    properties.put(J_PROTECTED, new String[] { String.valueOf(propertyDefinition.isProtected()) });
    properties.put(J_REQUIRED_TYPE,
            new String[] { PropertyType.nameFromValue(propertyDefinition.getRequiredType()) });
    properties.put(J_SELECTOR_TYPE,
            new String[] { SelectorType.nameFromValue(propertyDefinition.getSelector()) });
    Map<String, String> selectorOptions = propertyDefinition.getSelectorOptions();
    List<String> selectorOptionsList = new ArrayList<String>();
    for (Map.Entry<String, String> entry : selectorOptions.entrySet()) {
        String option = entry.getKey();
        String value = entry.getValue();
        if (StringUtils.isNotBlank(value)) {
            option += "='" + value + "'";
        }
        selectorOptionsList.add(option);
    }
    properties.put(J_SELECTOR_OPTIONS, selectorOptionsList.toArray(new String[selectorOptionsList.size()]));
    String[] valueConstraints = propertyDefinition.getValueConstraints();
    if (valueConstraints != null && valueConstraints.length > 0) {
        properties.put(J_VALUE_CONSTRAINTS, valueConstraints);
    }
    Value[] defaultValues = propertyDefinition.getDefaultValuesAsUnexpandedValue();
    if (defaultValues != null && defaultValues.length > 0) {
        try {
            List<String> defaultValuesAsString = JahiaCndWriter.getValuesAsString(defaultValues);
            List<String> unquotedValues = new ArrayList<String>();
            for (String value : defaultValuesAsString) {
                unquotedValues.add(StringUtils.removeEnd(StringUtils.removeStart(value, "'"), "'"));
            }
            properties.put(J_DEFAULT_VALUES, unquotedValues.toArray(new String[unquotedValues.size()]));
        } catch (IOException e) {
            logger.error("Failed to get default values", e);
        }
    }
    properties.put(J_MULTIPLE, new String[] { String.valueOf(propertyDefinition.isMultiple()) });
    String[] availableQueryOperators = propertyDefinition.getAvailableQueryOperators();
    List<String> ops = new ArrayList<String>();
    if (availableQueryOperators != null) {
        for (String op : availableQueryOperators) {
            if (QueryObjectModelConstants.JCR_OPERATOR_EQUAL_TO.equals(op)) {
                ops.add(Lexer.QUEROPS_EQUAL);
            } else if (QueryObjectModelConstants.JCR_OPERATOR_NOT_EQUAL_TO.equals(op)) {
                ops.add(Lexer.QUEROPS_NOTEQUAL);
            } else if (QueryObjectModelConstants.JCR_OPERATOR_LESS_THAN.equals(op)) {
                ops.add(Lexer.QUEROPS_LESSTHAN);
            } else if (QueryObjectModelConstants.JCR_OPERATOR_LESS_THAN_OR_EQUAL_TO.equals(op)) {
                ops.add(Lexer.QUEROPS_LESSTHANOREQUAL);
            } else if (QueryObjectModelConstants.JCR_OPERATOR_GREATER_THAN.equals(op)) {
                ops.add(Lexer.QUEROPS_GREATERTHAN);
            } else if (QueryObjectModelConstants.JCR_OPERATOR_GREATER_THAN_OR_EQUAL_TO.equals(op)) {
                ops.add(Lexer.QUEROPS_GREATERTHANOREQUAL);
            } else if (QueryObjectModelConstants.JCR_OPERATOR_LIKE.equals(op)) {
                ops.add(Lexer.QUEROPS_LIKE);
            }
        }
        if (!ops.isEmpty()) {
            properties.put(J_AVAILABLE_QUERY_OPERATORS, ops.toArray(new String[ops.size()]));
        }
    }
    properties.put(J_IS_FULL_TEXT_SEARCHABLE,
            new String[] { String.valueOf(propertyDefinition.isFullTextSearchable()) });
    properties.put(J_IS_QUERY_ORDERABLE,
            new String[] { String.valueOf(propertyDefinition.isQueryOrderable()) });
    properties.put(J_IS_FACETABLE, new String[] { String.valueOf(propertyDefinition.isFacetable()) });
    properties.put(J_IS_HIERARCHICAL, new String[] { String.valueOf(propertyDefinition.isHierarchical()) });
    properties.put(J_IS_INTERNATIONALIZED,
            new String[] { String.valueOf(propertyDefinition.isInternationalized()) });
    properties.put(J_IS_HIDDEN, new String[] { String.valueOf(propertyDefinition.isHidden()) });
    properties.put(J_INDEX, new String[] { IndexType.nameFromValue(propertyDefinition.getIndex()) });
    properties.put(J_SCOREBOOST, new String[] { String.valueOf(propertyDefinition.getScoreboost()) });
    String analyzer = propertyDefinition.getAnalyzer();
    if (analyzer != null) {
        properties.put(J_ANALYZER, new String[] { analyzer });
    }
    properties.put(J_ON_CONFLICT_ACTION,
            new String[] { OnConflictAction.nameFromValue(propertyDefinition.getOnConflict()) });
    String itemType = propertyDefinition.getLocalItemType();
    if (itemType != null) {
        properties.put(J_ITEM_TYPE, new String[] { itemType });
    }
    ExternalData externalData = new ExternalData(path, path,
            unstructured ? "jnt:unstructuredPropertyDefinition" : "jnt:propertyDefinition", properties);
    Map<String, Map<String, String[]>> i18nProperties = new HashMap<String, Map<String, String[]>>();

    for (Locale locale : LanguageCodeConverters.getAvailableBundleLocales()) {
        Map<String, String[]> value = new HashMap<String, String[]>();
        i18nProperties.put(locale.toString(), value);
        value.put(Constants.JCR_TITLE, new String[] { propertyDefinition.getLabel(locale) });
    }

    externalData.setI18nProperties(i18nProperties);
    return externalData;
}

From source file:org.jahia.services.content.decorator.JCRMountPointNode.java

public String getTargetMountPointPath() {
    String path;/*from  w ww . ja va 2 s.c o  m*/
    try {
        if (node.hasProperty(MOUNT_POINT_PROPERTY_NAME)) {
            path = node.getProperty(MOUNT_POINT_PROPERTY_NAME).getNode().getPath() + "/"
                    + StringUtils.removeEnd(node.getName(), MOUNT_SUFFIX);
        } else if (node.getPath().endsWith(MOUNT_SUFFIX)) {
            path = StringUtils.removeEnd(node.getPath(), MOUNT_SUFFIX);
        } else {
            path = node.getPath() + MOUNT_POINT_SUFFIX;
        }
    } catch (RepositoryException e) {
        if (!(e instanceof ItemNotFoundException)) {
            logger.error(e.getMessage(), e);
        }
        path = node.getPath() + MOUNT_POINT_SUFFIX;
    }

    return path;
}

From source file:org.jahia.services.seo.jcr.VanityUrlManager.java

private void checkUniqueConstraint(JCRNodeWrapper contentNode, VanityUrl vanityUrl,
        List<Map.Entry<String, VanityUrl>> toDelete, JCRSessionWrapper session)
        throws RepositoryException, NonUniqueUrlMappingException {
    List<VanityUrl> existingUrls = findExistingVanityUrls(vanityUrl.getUrl(), vanityUrl.getSite(), session);
    if (existingUrls != null && !existingUrls.isEmpty()) {
        for (VanityUrl existingUrl : existingUrls) {
            if (!vanityUrl.equals(existingUrl)) {
                boolean oldMatchWillBeDeleted = false;
                if (toDelete != null) {
                    for (Map.Entry<String, VanityUrl> entry : toDelete) {
                        if (existingUrl.equals(entry.getValue())) {
                            oldMatchWillBeDeleted = true;
                            break;
                        }/*from  ww w .ja  v a2 s  .  c  o m*/
                    }
                }
                if (!oldMatchWillBeDeleted) {
                    throw new NonUniqueUrlMappingException(vanityUrl.getUrl(), contentNode.getPath(),
                            StringUtils.removeEnd(
                                    session.getNodeByUUID(existingUrl.getIdentifier()).getParent().getPath(),
                                    "/" + VANITYURLMAPPINGS_NODE),
                            session.getWorkspace().getName());
                }
            }
        }
    }
}

From source file:org.jahia.services.templates.GitSourceControlManagement.java

private Map<String, Status> createStatusMap(boolean folder) throws IOException {
    Map<String, Status> newMap = new HashMap<String, Status>();
    List<String> paths = readLines(
            executeCommand(executable, new String[] { "rev-parse", "--show-prefix" }).out);
    String relPath = paths.isEmpty() ? "" : paths.get(0);
    ExecutionResult result = executeCommand(executable, new String[] { "status", "--porcelain" });
    for (String line : readLines(result.out)) {
        if (StringUtils.isBlank(line)) {
            continue;
        }/*from   w  w w  .  j a va2 s  . com*/
        String path = line.substring(3);
        if (path.contains(" -> ")) {
            path = StringUtils.substringAfter(path, " -> ");
        }
        path = StringUtils.removeEnd(path, "/");
        path = StringUtils.removeStart(path, relPath);
        char indexStatus = line.charAt(0);
        char workTreeStatus = line.charAt(1);
        Status status = null;
        if (workTreeStatus == ' ') {
            if (indexStatus == 'M') {
                status = Status.MODIFIED;
            } else if (indexStatus == 'A') {
                status = Status.ADDED;
            } else if (indexStatus == 'D') {
                status = Status.DELETED;
            } else if (indexStatus == 'R') {
                status = Status.RENAMED;
            } else if (indexStatus == 'C') {
                status = Status.COPIED;
            }
        } else if (workTreeStatus == 'M') {
            status = Status.MODIFIED;
        } else if (workTreeStatus == 'D') {
            if (indexStatus == 'D' || indexStatus == 'U') {
                status = Status.UNMERGED;
            } else {
                status = Status.DELETED;
            }
        } else if (workTreeStatus == 'A' || workTreeStatus == 'U') {
            status = Status.UNMERGED;
        } else if (workTreeStatus == '?') {
            status = Status.UNTRACKED;
        }
        if (status != null) {
            // put resource status
            if (!path.startsWith("/")) {
                path = "/" + path;
            }
            newMap.put(path, status);
            if (folder) {
                // store intermediate folder status as MODIFIED 
                StringBuilder subPath = new StringBuilder();
                for (String segment : StringUtils.split(path, '/')) {
                    newMap.put(subPath.length() == 0 ? "/" : subPath.toString(), Status.MODIFIED);
                    subPath.append('/');
                    subPath.append(segment);
                }
            }
        }
    }
    return newMap;
}

From source file:org.jahia.services.templates.SourceControlHelper.java

public String guessBranchOrTag(String moduleVersion, String scm, Set<String> branchOrTags) {
    String[] splitVersion = StringUtils.split(StringUtils.removeEnd(moduleVersion, "-SNAPSHOT"), ".");
    if (moduleVersion.endsWith("-SNAPSHOT")) {
        String branch;//from w  w w .ja  v  a 2  s .  co m
        if (splitVersion.length >= 3) {
            branch = String.format("JAHIA-%s-%s-%s-X-BRANCH", splitVersion);
            if (branchOrTags.contains(branch)) {
                return branch;
            }
        }
        if (splitVersion.length >= 2) {
            branch = String.format("JAHIA-%s-%s-X-X-BRANCH", splitVersion);
            if (branchOrTags.contains(branch)) {
                return branch;
            }
        }
        if (splitVersion.length >= 1) {
            branch = splitVersion[0] + "_x";
            if (branchOrTags.contains(branch)) {
                return branch;
            }
        }
        if ("svn".equals(scm)) {
            branch = "trunk";
            if (branchOrTags.contains(branch)) {
                return branch;
            }
        } else if ("git".equals(scm)) {
            branch = "master";
            if (branchOrTags.contains(branch)) {
                return branch;
            }
        }
    } else {
        String tag = StringUtils.join(splitVersion, '_');
        if (branchOrTags.contains(tag)) {
            return tag;
        }
        tag = "JAHIA_" + tag;
        if (branchOrTags.contains(tag)) {
            return tag;
        }
    }
    return null;
}

From source file:org.jahia.services.templates.SvnSourceControlManagement.java

@Override
public Map<String, String> getTagInfos(String uri) throws IOException {
    String separator = "/trunk";
    Iterator<String> it = Arrays.asList("/branches", "/tags").iterator();
    while (!StringUtils.contains(uri, separator) && it.hasNext()) {
        separator = it.next();/*w  ww.j  a va2  s. c  o m*/
    }
    String base = StringUtils.substringBeforeLast(uri, separator) + "/tags/";
    String path = StringUtils.substringAfterLast(uri, separator + "/");
    if (!separator.equals("/trunk")) {
        path = StringUtils.substringAfter(path, "/");
    }
    Map<String, String> infos = new LinkedHashMap<>();
    ExecutionResult result = executeCommand(executable, new String[] { "list", base });
    List<String> lines = readLines(result.out);
    Collections.reverse(lines);
    for (String line : lines) {
        String tag = StringUtils.removeEnd(line, "/");
        infos.put(tag, "scm:svn:" + base + tag + (path.length() > 0 ? "/" + path : ""));
    }
    return infos;
}

From source file:org.jahia.services.templates.SvnSourceControlManagement.java

@Override
public Map<String, String> getBranchInfos(String uri) throws IOException {
    String separator = "/trunk";
    Iterator<String> it = Arrays.asList("/branches", "/tags").iterator();
    while (!StringUtils.contains(uri, separator) && it.hasNext()) {
        separator = it.next();/*from  w  ww  .j  av a2  s  .c om*/
    }
    String base = StringUtils.substringBeforeLast(uri, separator) + "/branches/";
    String path = StringUtils.substringAfterLast(uri, separator + "/");
    if (!separator.equals("/trunk")) {
        path = StringUtils.substringAfter(path, "/");
    }
    Map<String, String> infos = new LinkedHashMap<>();
    ExecutionResult result = executeCommand(executable, new String[] { "list", base });
    List<String> lines = readLines(result.out);
    Collections.reverse(lines);
    infos.put("trunk", uri);
    for (String line : lines) {
        String branch = StringUtils.removeEnd(line, "/");
        infos.put(branch, "scm:svn:" + base + branch + (path.length() > 0 ? "/" + path : ""));
    }
    return infos;
}