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

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

Introduction

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

Prototype

public static String removeStart(String str, String remove) 

Source Link

Document

Removes a substring only if it is at the begining 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   w  w w .jav  a 2 s. c om*/
        requestString = "";
    }

    return requestString;
}

From source file:org.intermine.webservice.server.WebService.java

/**
 * If user name and password is specified in request, then it setups user
 * profile in session. User was authenticated. It uses HTTP basic access
 * authentication./*from   www.j  av a2 s.  c om*/
 * {@link "http://en.wikipedia.org/wiki/Basic_access_authentication"}
 */
private void authenticate() {

    String authToken = request.getParameter(AUTH_TOKEN_PARAM_KEY);
    final String authString = request.getHeader(AUTHENTICATION_FIELD_NAME);
    final ProfileManager pm = im.getProfileManager();

    if (StringUtils.isEmpty(authToken) && StringUtils.isEmpty(authString)) {
        return; // Not Authenticated.
    }
    // Accept tokens passed in the Authorization header.
    if (StringUtils.isEmpty(authToken) && StringUtils.startsWith(authString, "Token ")) {
        authToken = StringUtils.removeStart(authString, "Token ");
    }

    try {
        // Use a token if provided.
        if (StringUtils.isNotEmpty(authToken)) {
            permission = pm.getPermission(authToken, im.getClassKeys());
        } else {
            // Try and read the authString as a basic auth header.
            // Strip off the "Basic" part - but don't require it.
            final String encoded = StringUtils.removeStart(authString, "Basic ");
            final String decoded = new String(Base64.decodeBase64(encoded.getBytes()));
            final String[] parts = decoded.split(":", 2);
            if (parts.length != 2) {
                throw new UnauthorizedException(
                        "Invalid request authentication. " + "Authorization field contains invalid value. "
                                + "Decoded authorization value: " + parts[0]);
            }
            final String username = StringUtils.lowerCase(parts[0]);
            final String password = parts[1];

            permission = pm.getPermission(username, password, im.getClassKeys());
        }
    } catch (AuthenticationException e) {
        throw new UnauthorizedException(e.getMessage());
    }

    LoginHandler.setUpPermission(im, permission);
}

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

public Session getExtensionSession() throws RepositoryException {
    if (extensionSession == null) {
        JCRStoreProvider extensionProvider = getRepository().getStoreProvider().getExtensionProvider();
        if (extensionProvider != null) {
            extensionSession = extensionProvider.getSession(
                    JahiaLoginModule.getSystemCredentials(
                            StringUtils.removeStart(getUserID(), JahiaLoginModule.SYSTEM), getRealm()),
                    "default");
        }/*  w  w w . j  ava  2s  .co  m*/
    }
    return extensionSession;
}

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,//from   w w  w . jav a 2  s  .  c  om
            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.modules.external.modules.ModulesImportExportHelper.java

public void updateImportFileNodes(final List<File> files, final String importFilesRootFolder,
        final String filesNodePath) {
    synchronized (syncObject) {
        try {//  w w  w . ja v a 2 s .  com
            JCRTemplate.getInstance().doExecuteWithSystemSession(new JCRCallback<Object>() {
                @Override
                public Object doInJCR(JCRSessionWrapper session) throws RepositoryException {
                    JCRNodeWrapper filesNode = session.getNode(filesNodePath);
                    for (File file : files) {
                        if (!file.exists()) {
                            String relPath = StringUtils.removeStart(file.getPath(), importFilesRootFolder);
                            if (relPath.endsWith(file.getName() + File.separator + file.getName())) {
                                relPath = StringUtils.substringBeforeLast(relPath, File.separator);
                            }
                            if (filesNode.hasNode(relPath)) {
                                JCRNodeWrapper node = filesNode.getNode(relPath);
                                boolean removeEmptyFolder = !node.hasNodes() && !node.equals(filesNode);
                                node.remove();
                                while (removeEmptyFolder) {
                                    JCRNodeWrapper parent = node.getParent();
                                    removeEmptyFolder = !node.hasNodes() && !node.equals(filesNode);
                                    node.remove();
                                    node = parent;
                                }
                            }
                        } else if (file.isFile()) {
                            JCRNodeWrapper node = filesNode;
                            String[] pathSegments = (File.separatorChar == '\\' ? Patterns.BACKSLASH
                                    : Patterns.SLASH).split(
                                            StringUtils.removeStart(file.getPath(), importFilesRootFolder));
                            int endIndex;
                            if (pathSegments.length >= 2 && pathSegments[pathSegments.length - 1]
                                    .equals(pathSegments[pathSegments.length - 2])) {
                                endIndex = pathSegments.length - 2;
                            } else {
                                endIndex = pathSegments.length - 1;
                            }

                            for (int i = 0; i < endIndex; i++) {
                                String pathSegment = pathSegments[i];
                                if (node.hasNode(pathSegment)) {
                                    node = node.getNode(pathSegment);
                                } else {
                                    node = node.addNode(pathSegment, Constants.JAHIANT_FOLDER);
                                }
                            }

                            InputStream is = null;
                            try {
                                is = new BufferedInputStream(new FileInputStream(file));
                                node.uploadFile(file.getName(), is,
                                        JCRContentUtils.getMimeType(file.getName()));
                            } catch (FileNotFoundException e) {
                                logger.error("Failed to upload import file", e);
                            } finally {
                                IOUtils.closeQuietly(is);
                            }
                        }
                    }
                    session.save();
                    return null;
                }
            });
        } catch (RepositoryException e) {
            logger.error("Failed to update import files", e);
        }
    }
}

From source file:org.jahia.modules.modulemanager.flow.ModuleManagementFlowHandler.java

public String guessBranchOrTag(String moduleVersion, String scmURI, Map<String, String> branchOrTags,
        String defaultBranchOrTag) {
    String branchOrTag = templateManagerService.guessBranchOrTag(moduleVersion,
            StringUtils.substringBefore(StringUtils.removeStart(scmURI, "scm:"), ":"), branchOrTags.keySet());
    return branchOrTag != null ? branchOrTag : defaultBranchOrTag;
}

From source file:org.jahia.services.importexport.validation.ProviderAvailabilityValidator.java

@Override
public void validate(String decodedLocalName, String decodedQName, String currentPath, Attributes atts) {
    String path = StringUtils.removeStart(currentPath, "/content");
    if (StringUtils.isNotBlank(path)) {
        visitedPaths.add(path);/*from  www. ja  va 2s .  co m*/
    }
    String type = atts.getValue("jcr:primaryType");
    try {
        if (type != null
                && NodeTypeRegistry.getInstance().getNodeType(type).isNodeType(Constants.JAHIANT_MOUNTPOINT)) {
            neededMountPoint.add(type);
        }
    } catch (NoSuchNodeTypeException e) {
        // Ignore
    }
    if (atts.getIndex(ImportExportBaseService.STATIC_MOUNT_POINT_ATTR) > -1) {
        neededStaticProviders.add(atts.getValue(ImportExportBaseService.STATIC_MOUNT_POINT_ATTR));
    }
    if (atts.getIndex(ImportExportBaseService.DYNAMIC_MOUNT_POINT_ATTR) > -1) {
        neededDynamicProviders.add(atts.getValue(ImportExportBaseService.DYNAMIC_MOUNT_POINT_ATTR));
    }
}

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;
        }//  ww w . j  av a 2s  . c o m
        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.jboss.loom.MigratorApp.java

/**
 *  Parses app's arguments./*w  ww.  j  ava2s  .  c o m*/
 *  @returns  Configuration initialized according to args.
 */
static Configuration parseArguments(String[] args) {

    // Global config
    GlobalConfiguration globalConfig = new GlobalConfiguration();

    // Module-specific options.
    List<ModuleSpecificProperty> moduleConfigs = new LinkedList<>();

    // For each argument...
    for (String arg : args) {
        arg = StringUtils.removeStart(arg, "--");

        if (arg.equals("help")) {
            Utils.writeHelp();
            return null;
        }
        if (arg.startsWith("as5.dir=") || arg.startsWith("eap5.dir=") || arg.startsWith("src.dir=")) {
            globalConfig.getAS5Config().setDir(StringUtils.substringAfter(arg, "="));
            continue;
        }

        if (arg.startsWith("dest.dir=") || arg.startsWith("eap6.dir=") || arg.startsWith("dest.dir=")
                || arg.startsWith("wfly.dir=")) {
            globalConfig.getAS7Config().setDir(StringUtils.substringAfter(arg, "="));
            continue;
        }

        if (arg.startsWith("as5.profile=") || arg.startsWith("eap5.profile=")
                || arg.startsWith("src.profile=")) {
            globalConfig.getAS5Config().setProfileName(StringUtils.substringAfter(arg, "="));
            continue;
        }

        if (arg.startsWith("dest.confPath=") || arg.startsWith("eap6.confPath=")
                || arg.startsWith("dest.conf.file=") || arg.startsWith("wfly.confPath=")) {
            globalConfig.getAS7Config().setConfigPath(StringUtils.substringAfter(arg, "="));
            continue;
        }

        if (arg.startsWith("dest.mgmt=") || arg.startsWith("eap6.mgmt=") || arg.startsWith("dest.mgmt=")
                || arg.startsWith("wfly.mgmt=")) {
            parseMgmtConn(StringUtils.substringAfter(arg, "="), globalConfig.getAS7Config());
            continue;
        }

        if (arg.startsWith("app.path=")) {
            globalConfig.addDeploymentPath(StringUtils.substringAfter(arg, "="));
            continue;
        }

        if (arg.startsWith("valid.skip")) {
            globalConfig.setSkipValidation(true);
            continue;
        }

        if (arg.equals("dry") || arg.equals("dryRun") || arg.equals("dry-run")) {
            globalConfig.setDryRun(true);
            continue;
        }

        if (arg.equals("test") || arg.equals("testRun") || arg.equals("test-run")) {
            globalConfig.setTestRun(true);
            continue;
        }

        if (arg.startsWith("report.dir=")) {
            globalConfig.setReportDir(StringUtils.substringAfter(arg, "="));
            continue;
        }

        if (arg.startsWith("migrators.dir=") || arg.startsWith("migr.dir=")) {
            globalConfig.setExternalMigratorsDir(StringUtils.substringAfter(arg, "="));
            continue;
        }

        // User variables available in EL and Groovy in external migrators.
        if (arg.startsWith("userVar.")) {

            // --userVar.<property.name>=<value>
            String rest = StringUtils.substringAfter(arg, ".");
            String name = StringUtils.substringBefore(rest, "=");
            String value = StringUtils.substringAfter(rest, "=");

            globalConfig.getUserVars().put(name, value);
        }

        // Module-specific configurations.
        // TODO: Process by calling IMigrator instances' callback.
        if (arg.startsWith("conf.")) {

            // --conf.<module>.<property.name>[=<value>]
            String conf = StringUtils.substringAfter(arg, ".");
            String module = StringUtils.substringBefore(conf, ".");
            String propName = StringUtils.substringAfter(conf, ".");
            int pos = propName.indexOf('=');
            String value = null;
            if (pos == -1) {
                value = propName.substring(pos + 1);
                propName = propName.substring(0, pos);
            }

            moduleConfigs.add(new ModuleSpecificProperty(module, propName, value));
        }

        // Unrecognized.

        if (!arg.contains("=")) {
            // TODO: Could be AS5 or AS7 dir.
        }

        System.err.println("Warning: Unknown argument: " + arg + " !");
        Utils.writeHelp();
        continue;
    }

    Configuration configuration = new Configuration();
    configuration.setModuleConfigs(moduleConfigs);
    configuration.setGlobalConfig(globalConfig);

    return configuration;

}

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

/**
 *  Changes "foo\"bar" to foo"bar.//w  ww  .ja v  a2  s  .  c om
 *  Is tolerant - doesn't check if the quotes are really present.
 */
public static String unquote(String string) {
    string = StringUtils.removeStart(string, "\"");
    string = StringUtils.removeEnd(string, "\"");
    return StringEscapeUtils.unescapeJava(string);
}