Example usage for org.apache.commons.lang3 StringUtils startsWith

List of usage examples for org.apache.commons.lang3 StringUtils startsWith

Introduction

In this page you can find the example usage for org.apache.commons.lang3 StringUtils startsWith.

Prototype

public static boolean startsWith(final CharSequence str, final CharSequence prefix) 

Source Link

Document

Check if a CharSequence starts with a specified prefix.

null s are handled without exceptions.

Usage

From source file:com.quatico.base.aem.test.api.setup.Pages.java

private String getChildPath(Resource pageResource, String relativePath) {
    String result = pageResource.getPath();
    if (!StringUtils.startsWith(relativePath, "/")) {
        result += "/";
    }/* w  ww.j a v  a 2s.c  om*/
    return result + relativePath;
}

From source file:com.databasepreservation.cli.CLI.java

private void includePluginModules() {
    // find plugins in command line arguments
    String pluginString = null;//from  ww w.jav  a 2 s. c o  m
    Iterator<String> argsIterator = commandLineArguments.iterator();
    while (argsIterator.hasNext()) {
        String arg = argsIterator.next();
        if ("-p".equals(arg) || "--plugin".equals(arg)) {
            pluginString = argsIterator.next();
            break;
        } else if (StringUtils.startsWith(arg, "--plugin=")) {
            // 9 is the size of the string "--plugin="
            pluginString = arg.substring(9);
            break;
        }
    }

    if (pluginString != null) {
        for (String plugin : pluginString.split(";")) {
            PluginManager pm = PluginManagerFactory.createPluginManager();
            try {
                URI pluginURI = new URI(plugin);
                if (pluginURI.getScheme() == null) {
                    pluginURI = new URI("file://" + plugin);
                }
                pm.addPluginsFrom(pluginURI);
            } catch (URISyntaxException e) {
                LOGGER.warn("Plugin not found: " + plugin, e);
            }
            factories.add(pm.getPlugin(DatabaseModuleFactory.class));
        }
    }
}

From source file:io.wcm.tooling.commons.contentpackagebuilder.ValueConverterTest.java

@Test
public void testCalendar() {
    assertTrue(StringUtils.startsWith(underTest.toString("prop", DateUtils.toCalendar(sampleDate)),
            "{Date}2010-09-05T15:10:20"));
}

From source file:com.adguard.filter.rules.UrlFilterRule.java

/**
 * Creates url filter rule//from   w  ww . j  ava  2 s.  co m
 *
 * @param ruleText Rule text
 */
public UrlFilterRule(String ruleText) {
    super(ruleText);

    String urlRuleText = ruleText;

    if (StringUtils.startsWith(urlRuleText, MASK_WHITE_LIST)) {
        urlRuleText = urlRuleText.substring(MASK_WHITE_LIST.length());
        whiteListRule = true;
    }

    int optionsIndex = StringUtils.lastIndexOf(urlRuleText, OPTIONS_DELIMITER);
    if (optionsIndex > -1) {
        urlRuleText = urlRuleText.substring(0, optionsIndex);
    }

    // Transform to punycode
    urlRuleText = toPunycode(urlRuleText);

    // More about regex rules http://jira.performix.ru/browse/AG-6604
    boolean regexRule = urlRuleText.startsWith(MASK_REGEX_RULE) && urlRuleText.endsWith(MASK_REGEX_RULE);
    if (!regexRule) {
        // Searching for shortcut for normal rules
        shortcut = findShortcut(urlRuleText);
    }
}

From source file:com.profiq.techresearch.mule.gitlab.config.ConnectorConfig.java

/**
 * Connect to the Gitlab API. Private token will be obtained if not filled manually.
 *
 * @param username Gitlab user username/*from w  w  w.  j  ava  2s. c  o m*/
 * @param password Gitlab user password
 * @param ignoreCertificationErrors set API to ignore all certification errors (optional)
 * @param requestTimeout manually set request timeout (optional)
 * @throws ConnectionException on connection error
 */
@Connect(strategy = ConnectStrategy.SINGLE_INSTANCE)
public void connect(@ConnectionKey final String username, @Password final String password,
        @Optional final Boolean ignoreCertificationErrors, @Optional final Integer requestTimeout)
        throws ConnectionException {

    LOGGER.trace("Checking for empty Gitlab host...");
    if (StringUtils.isBlank(this.gitlabHost)) {
        LOGGER.error("Host cannot be empty.");
        throw new ConnectionException(ConnectionExceptionCode.UNKNOWN_HOST, null, "Host cannot be empty.");
    }
    LOGGER.trace("Gitlab host is not empty.");

    LOGGER.trace("Checking for Gitlab host protocol...");
    if (!(StringUtils.startsWith(this.gitlabHost, "https://")
            || StringUtils.startsWith(this.gitlabHost, "http://"))) {
        LOGGER.error("Host has to begin with protocol \"https\" or \"http\".");
        throw new ConnectionException(ConnectionExceptionCode.UNKNOWN_HOST, null,
                "Host has to begin with protocol \"https\" or \"http\".");
    }
    LOGGER.trace("Gitlab host protocol is correct.");

    LOGGER.trace("Checking for empty private token...");
    if (StringUtils.isBlank(this.privateToken)) {
        LOGGER.trace("Private token is empty. Username and password will be used to obtain private token.");

        LOGGER.trace("Checking for empty username...");
        if (StringUtils.isBlank(username)) {
            LOGGER.error("Username cannot be empty.");
            throw new ConnectionException(ConnectionExceptionCode.INCORRECT_CREDENTIALS, null,
                    "Username cannot be empty.");
        }
        LOGGER.trace("Username is not empty.");

        LOGGER.trace("Checking for empty password...");
        if (StringUtils.isBlank(password)) {
            LOGGER.error("Password cannot be empty.");
            throw new ConnectionException(ConnectionExceptionCode.INCORRECT_CREDENTIALS, null,
                    "Password cannot be empty.");
        }
        LOGGER.trace("Password is not empty.");

        try {
            LOGGER.trace("Trying to connect to the Gitlab and obtain private token.");
            this.privateToken = GitlabAPI.connect(this.gitlabHost, username, password).getPrivateToken();
        } catch (final IOException e) {
            LOGGER.error("Connection to the Gitlab failed.");
            throw new ConnectionException(ConnectionExceptionCode.CANNOT_REACH, e.getMessage(),
                    "Cannot connect to the \"" + this.gitlabHost + "\".");
        }

        LOGGER.trace("Checking the new private token...");
        if (StringUtils.isBlank(this.privateToken)) {
            LOGGER.error("Something went wrong and private token is still empty.");
            throw new ConnectionException(ConnectionExceptionCode.UNKNOWN, null, "Private token is blank.");
        }
    }
    LOGGER.trace("Private token is correct.");

    this.apiHandler = GitlabAPI.connect(this.gitlabHost, this.privateToken);
    LOGGER.trace("API handler for Gitlab API created.");

    LOGGER.trace("Setting Ignore certification errors...");
    if (ignoreCertificationErrors != null) {
        LOGGER.trace("Ignore certification errors is not \"null\".");
        this.apiHandler = this.apiHandler.ignoreCertificateErrors(ignoreCertificationErrors);
        LOGGER.trace("Ignore certification errors is set to: {}", ignoreCertificationErrors);
    } else {
        LOGGER.trace("Ignore certificate errors is \"null\". Using default value.");
    }

    LOGGER.trace("Setting Request timeout...");
    if (requestTimeout != null) {
        LOGGER.trace("Request timeout is not \"null\".");
        this.apiHandler = this.apiHandler.setRequestTimeout(requestTimeout);
        LOGGER.trace("Request timeout is set to: {}", requestTimeout);
    } else {
        LOGGER.trace("Request timeout is \"null\". Using default value.");
    }
}

From source file:com.glaf.core.interceptor.MethodInterceptor.java

public void beforeInvoke(JoinPoint invocation) throws Throwable {
    logger.debug("-------------MethodInterceptor.beforeInvoke------------");
    String targetName = invocation.getSignature().getDeclaringType().getName();
    String methodName = invocation.getSignature().getName();
    Object[] args = invocation.getArgs();
    logger.debug("target:" + targetName);
    logger.debug("method:" + methodName);
    if (StringUtils.startsWith(targetName, "org.springframework.web.servlet.view")) {
        return;//  www  . j a  v a  2 s .  c  o m
    }
    String ip = null;
    String actorId = Authentication.getAuthenticatedActorId();

    for (int i = 0; i < args.length; i++) {
        logger.debug("args:" + args[i]);
        if (args[i] instanceof HttpServletRequest) {
            HttpServletRequest request = (HttpServletRequest) args[i];
            if (request != null) {
                ip = RequestUtils.getIPAddress(request);
                actorId = RequestUtils.getActorId(request);
                logger.debug("IP:" + ip + ", actorId:" + actorId);
            }
        }
    }

    String operation = targetName + "." + methodName;

    boolean authorized = false;

    // 
    if (checkSystemFunction(operation)) {
        // 
        if (checkUserFunction(actorId, methodName)) {
            logger.debug("method is in user functions");
            authorized = true;
        }
    } else {// ?
        logger.debug("method isn't in system functions");
        authorized = true;
    }

    try {
        LoginContext loginContext = IdentityFactory.getLoginContext(actorId);
        if (loginContext.isSystemAdministrator()) {
            /**
             * ???
             */
            authorized = true;
        }
        User user = loginContext.getUser();
        SysLog sysLog = new SysLog();
        sysLog.setAccount(user.getActorId());
        sysLog.setOperate(operation);
        sysLog.setIp(ip);
        sysLog.setCreateTime(new Date());
        sysLog.setFlag(authorized ? 1 : 0);
        ISysLogService sysLogService = ContextFactory.getBean("sysLogService");
        sysLogService.create(sysLog);
    } catch (Exception ex) {
        ex.printStackTrace();
    }

    if (!authorized) {
        throw new AthenticationException("No Privileges.");
    }
}

From source file:com.nridge.core.app.mail.MailManager.java

/**
 * Convenience method that returns the value of an application
 * manager configuration property using the concatenation of
 * the property prefix and suffix values.  If the property is
 * not found, then the default value parameter will be returned.
 *
 * @param aSuffix Property name suffix.//from w  w  w  . j  a v  a  2 s.c om
 * @param aDefaultValue Default value.
 *
 * @return Matching property value or the default value.
 */
public String getCfgString(String aSuffix, String aDefaultValue) {
    String propertyName;

    if (StringUtils.startsWith(aSuffix, "."))
        propertyName = mCfgPropertyPrefix + aSuffix;
    else
        propertyName = mCfgPropertyPrefix + "." + aSuffix;

    return mAppMgr.getString(propertyName, aDefaultValue);
}

From source file:ch.cyberduck.core.local.FileWatcher.java

protected Local normalize(final Local parent, final String name) {
    if (StringUtils.startsWith(name, String.valueOf(parent.getDelimiter()))) {
        return normalize(LocalFactory.get(name));
    }//from w w w.ja  v a  2s .c o  m
    return normalize(LocalFactory.get(parent, name));
}

From source file:eu.openanalytics.rsb.component.DataDirectoriesResource.java

@Path("/{rootId}{b64extension : (/b64extension)?}")
@GET/*from  w ww  .j a  v a  2s. co m*/
public Directory browsePath(@PathParam("rootId") final String rootId,
        @PathParam("b64extension") final String b64extension, @Context final HttpHeaders httpHeaders,
        @Context final UriInfo uriInfo) throws URISyntaxException, IOException {

    final File rootDataDir = rootMap.get(rootId);
    if (rootDataDir == null) {
        throw new NotFoundException(new RuntimeException("No root data dir configured"));
    }

    final String extension = (b64extension != null ? new String(Base64.decodeBase64(b64extension)) : "");
    final File targetDataDir = new File(rootDataDir, extension);

    if (!targetDataDir.exists()) {
        throw new NotFoundException(new RuntimeException("Invalid root data dir: " + targetDataDir));
    }

    // ensure the target data dir is below the root dir to prevent tampering
    final String rootDataDirCanonicalPath = rootDataDir.getCanonicalPath();
    final String targetDataDirCanonicalPath = targetDataDir.getCanonicalPath();
    if (!StringUtils.startsWith(targetDataDirCanonicalPath, rootDataDirCanonicalPath)) {
        throw new AccessDeniedException("Target data dir: " + targetDataDirCanonicalPath
                + " is not below root dir: " + rootDataDirCanonicalPath);
    }

    final Directory result = Util.REST_OBJECT_FACTORY.createDirectory();
    result.setPath(rootDataDirCanonicalPath + extension);
    result.setName(targetDataDir.getName());
    result.setUri(Util.buildDataDirectoryUri(httpHeaders, uriInfo, rootId, b64extension).toString());

    final File[] targetDataDirFiles = targetDataDir.listFiles();
    result.setEmpty(targetDataDirFiles.length == 0);

    for (final File child : targetDataDirFiles) {
        if (FileUtils.isSymlink(child)) {
            getLogger().warn("Symlinks are not supported: " + child);
        } else if (child.isFile()) {
            final FileType fileType = Util.REST_OBJECT_FACTORY.createFileType();
            fileType.setPath(child.getCanonicalPath());
            fileType.setName(child.getName());
            result.getFiles().add(fileType);
        } else if (child.isDirectory()) {
            final Directory childDir = Util.REST_OBJECT_FACTORY.createDirectory();
            childDir.setPath(child.getCanonicalPath());
            childDir.setName(child.getName());
            final String childB64extension = Base64.encodeBase64URLSafeString(
                    StringUtils.difference(rootDataDirCanonicalPath, child.getCanonicalPath()).getBytes());
            childDir.setUri(
                    Util.buildDataDirectoryUri(httpHeaders, uriInfo, rootId, childB64extension).toString());
            childDir.setEmpty(isDirectoryEmpty(child));
            result.getDirectories().add(childDir);
        } else {
            getLogger().warn("Unsupported file type: " + child);
        }
    }

    return result;
}

From source file:com.nridge.ds.solr.SolrConfig.java

private void update(StringBuilder aStringBuilder, Document aDocument) throws DSException {
    Logger appLogger = mAppMgr.getLogger(this, "update");

    appLogger.trace(mAppMgr.LOGMSG_TRACE_ENTER);

    initialize();//  w  w  w  .  ja  v  a 2s . c o m

    SolrConfigJSON solrConfigJSON = new SolrConfigJSON(mAppMgr);

    String docType = aDocument.getType();
    if (StringUtils.equals(docType, Solr.RESPONSE_CONFIG_RH_SN))
        solrConfigJSON.convert(aStringBuilder, aDocument);
    else if (StringUtils.startsWith(docType, Solr.RESPONSE_CONFIG_SEARCH_COMPONENT))
        solrConfigJSON.convert(aStringBuilder, aDocument);
    else
        throw new DSException(
                String.format("Unknown document type '%s' - cannot update Solr configuration.", docType));

    appLogger.trace(mAppMgr.LOGMSG_TRACE_DEPART);
}