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

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

Introduction

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

Prototype

public static boolean endsWith(String str, String suffix) 

Source Link

Document

Check if a String ends with a specified suffix.

Usage

From source file:org.apache.archiva.webdav.ArchivaDavResourceFactory.java

private DavResource processRepositoryGroup(final DavServletRequest request,
        ArchivaDavResourceLocator archivaLocator, List<String> repositories, String activePrincipal,
        List<String> resourcesInAbsolutePath, RepositoryGroupConfiguration repoGroupConfig)
        throws DavException {
    DavResource resource = null;/*from   w w  w .  j ava2 s  . c  o  m*/
    List<DavException> storedExceptions = new ArrayList<>();

    String pathInfo = StringUtils.removeEnd(request.getPathInfo(), "/");

    String rootPath = StringUtils.substringBeforeLast(pathInfo, "/");

    if (StringUtils.endsWith(rootPath, repoGroupConfig.getMergedIndexPath())) {
        // we are in the case of index file request
        String requestedFileName = StringUtils.substringAfterLast(pathInfo, "/");
        File temporaryIndexDirectory = buildMergedIndexDirectory(repositories, activePrincipal, request,
                repoGroupConfig);

        File resourceFile = new File(temporaryIndexDirectory, requestedFileName);
        resource = new ArchivaDavResource(resourceFile.getAbsolutePath(), requestedFileName, null,
                request.getRemoteAddr(), activePrincipal, request.getDavSession(), archivaLocator, this,
                mimeTypes, auditListeners, scheduler, fileLockManager);

    } else {
        for (String repositoryId : repositories) {
            ManagedRepositoryContent managedRepositoryContent;
            try {
                managedRepositoryContent = repositoryFactory.getManagedRepositoryContent(repositoryId);
            } catch (RepositoryNotFoundException e) {
                throw new DavException(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e);
            } catch (RepositoryException e) {
                throw new DavException(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e);
            }

            try {
                ManagedRepository managedRepository = managedRepositoryAdmin.getManagedRepository(repositoryId);
                DavResource updatedResource = processRepository(request, archivaLocator, activePrincipal,
                        managedRepositoryContent, managedRepository);
                if (resource == null) {
                    resource = updatedResource;
                }

                String logicalResource = getLogicalResource(archivaLocator, null, false);
                if (logicalResource.endsWith("/")) {
                    logicalResource = logicalResource.substring(1);
                }
                resourcesInAbsolutePath.add(
                        new File(managedRepositoryContent.getRepoRoot(), logicalResource).getAbsolutePath());
            } catch (DavException e) {
                storedExceptions.add(e);
            } catch (RepositoryAdminException e) {
                storedExceptions.add(new DavException(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e));
            }
        }
    }
    if (resource == null) {
        if (!storedExceptions.isEmpty()) {
            // MRM-1232
            for (DavException e : storedExceptions) {
                if (401 == e.getErrorCode()) {
                    throw e;
                }
            }

            throw new DavException(HttpServletResponse.SC_NOT_FOUND);
        } else {
            throw new DavException(HttpServletResponse.SC_NOT_FOUND);
        }
    }
    return resource;
}

From source file:org.apache.archiva.webdav.ArchivaDavResourceFactory.java

private String addHrefPrefix(String contextPath, String path) {
    String prefix = archivaConfiguration.getConfiguration().getWebapp().getUi().getApplicationUrl();
    if (prefix == null || prefix.isEmpty()) {
        prefix = contextPath;/*from   w w w.j a va2  s. c  o  m*/
    }
    return prefix + (StringUtils.startsWith(path, "/") ? "" : (StringUtils.endsWith(prefix, "/") ? "" : "/"))
            + path;
}

From source file:org.apache.archiva.webdav.ArchivaDavResourceFactory.java

private DavResource getResourceFromGroup(DavServletRequest request, List<String> repositories,
        ArchivaDavResourceLocator locator, RepositoryGroupConfiguration repositoryGroupConfiguration)
        throws DavException, RepositoryAdminException {
    if (repositoryGroupConfiguration.getRepositories() == null
            || repositoryGroupConfiguration.getRepositories().isEmpty()) {
        File file = new File(System.getProperty("appserver.base"),
                "groups/" + repositoryGroupConfiguration.getId());

        return new ArchivaDavResource(file.getPath(), "groups/" + repositoryGroupConfiguration.getId(), null,
                request.getDavSession(), locator, this, mimeTypes, auditListeners, scheduler, fileLockManager);
    }//from  w  ww  .j  a  v a2  s . c o  m
    List<File> mergedRepositoryContents = new ArrayList<>();
    // multiple repo types so we guess they are all the same type
    // so use the first one
    // FIXME add a method with group in the repository storage
    String firstRepoId = repositoryGroupConfiguration.getRepositories().get(0);

    String path = getLogicalResource(locator, managedRepositoryAdmin.getManagedRepository(firstRepoId), false);
    if (path.startsWith("/")) {
        path = path.substring(1);
    }
    LogicalResource logicalResource = new LogicalResource(path);

    // flow:
    // if the current user logged in has permission to any of the repositories, allow user to
    // browse the repo group but displaying only the repositories which the user has permission to access.
    // otherwise, prompt for authentication.

    String activePrincipal = getActivePrincipal(request);

    boolean allow = isAllowedToContinue(request, repositories, activePrincipal);

    // remove last /
    String pathInfo = StringUtils.removeEnd(request.getPathInfo(), "/");

    if (allow) {

        if (StringUtils.endsWith(pathInfo, repositoryGroupConfiguration.getMergedIndexPath())) {
            File mergedRepoDir = buildMergedIndexDirectory(repositories, activePrincipal, request,
                    repositoryGroupConfiguration);
            mergedRepositoryContents.add(mergedRepoDir);
        } else {
            if (StringUtils.equalsIgnoreCase(pathInfo, "/" + repositoryGroupConfiguration.getId())) {
                File tmpDirectory = new File(SystemUtils.getJavaIoTmpDir(), repositoryGroupConfiguration.getId()
                        + "/" + repositoryGroupConfiguration.getMergedIndexPath());
                if (!tmpDirectory.exists()) {
                    synchronized (tmpDirectory.getAbsolutePath()) {
                        if (!tmpDirectory.exists()) {
                            tmpDirectory.mkdirs();
                        }
                    }
                }
                mergedRepositoryContents.add(tmpDirectory.getParentFile());
            }
            for (String repository : repositories) {
                ManagedRepositoryContent managedRepository = null;

                try {
                    managedRepository = repositoryFactory.getManagedRepositoryContent(repository);
                } catch (RepositoryNotFoundException e) {
                    throw new DavException(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                            "Invalid managed repository <" + repository + ">: " + e.getMessage());
                } catch (RepositoryException e) {
                    throw new DavException(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                            "Invalid managed repository <" + repository + ">: " + e.getMessage());
                }

                File resourceFile = new File(managedRepository.getRepoRoot(), logicalResource.getPath());
                if (resourceFile.exists()) {
                    // in case of group displaying index directory doesn't have sense !!
                    String repoIndexDirectory = managedRepository.getRepository().getIndexDirectory();
                    if (StringUtils.isNotEmpty(repoIndexDirectory)) {
                        if (!new File(repoIndexDirectory).isAbsolute()) {
                            repoIndexDirectory = new File(managedRepository.getRepository().getLocation(),
                                    StringUtils.isEmpty(repoIndexDirectory) ? ".indexer" : repoIndexDirectory)
                                            .getAbsolutePath();
                        }
                    }
                    if (StringUtils.isEmpty(repoIndexDirectory)) {
                        repoIndexDirectory = new File(managedRepository.getRepository().getLocation(),
                                ".indexer").getAbsolutePath();
                    }

                    if (!StringUtils.equals(FilenameUtils.normalize(repoIndexDirectory),
                            FilenameUtils.normalize(resourceFile.getAbsolutePath()))) {
                        // for prompted authentication
                        if (httpAuth.getSecuritySession(request.getSession(true)) != null) {
                            try {
                                if (isAuthorized(request, repository)) {
                                    mergedRepositoryContents.add(resourceFile);
                                    log.debug("Repository '{}' accessed by '{}'", repository, activePrincipal);
                                }
                            } catch (DavException e) {
                                // TODO: review exception handling

                                log.debug("Skipping repository '{}' for user '{}': {}", managedRepository,
                                        activePrincipal, e.getMessage());

                            }

                        } else {
                            // for the current user logged in
                            try {
                                if (servletAuth.isAuthorized(activePrincipal, repository,
                                        WebdavMethodUtil.getMethodPermission(request.getMethod()))) {
                                    mergedRepositoryContents.add(resourceFile);
                                    log.debug("Repository '{}' accessed by '{}'", repository, activePrincipal);
                                }
                            } catch (UnauthorizedException e) {
                                // TODO: review exception handling

                                log.debug("Skipping repository '{}' for user '{}': {}", managedRepository,
                                        activePrincipal, e.getMessage());

                            }
                        }
                    }
                }
            }
        }
    } else {
        throw new UnauthorizedDavException(locator.getRepositoryId(), "User not authorized.");
    }

    ArchivaVirtualDavResource resource = new ArchivaVirtualDavResource(mergedRepositoryContents,
            logicalResource.getPath(), mimeTypes, locator, this);

    // compatibility with MRM-440 to ensure browsing the repository group works ok
    if (resource.isCollection() && !request.getRequestURI().endsWith("/")) {
        throw new BrowserRedirectException(resource.getHref());
    }

    return resource;
}

From source file:org.apache.atlas.type.AtlasTypeUtil.java

public static boolean isArrayType(String typeName) {
    return StringUtils.startsWith(typeName, ATLAS_TYPE_ARRAY_PREFIX)
            && StringUtils.endsWith(typeName, ATLAS_TYPE_ARRAY_SUFFIX);
}

From source file:org.apache.atlas.type.AtlasTypeUtil.java

public static boolean isMapType(String typeName) {
    return StringUtils.startsWith(typeName, ATLAS_TYPE_MAP_PREFIX)
            && StringUtils.endsWith(typeName, ATLAS_TYPE_MAP_SUFFIX);
}

From source file:org.apache.ctakes.jdl.data.xml.DomUtilTest.java

@Theory
public void nodeToStr(String xml) {
    xml = FileUtil.getFile(xml).toString();
    Document document = DomUtil.srcToDocument(xml);
    Element element = document.getDocumentElement();
    assertThat(StringUtils.startsWith(DomUtil.nodeToStr(element), "<" + Resources.ROOT_LOAD), is(true));
    assertThat(StringUtils.endsWith(DomUtil.nodeToStr(element).trim(), "</" + Resources.ROOT_LOAD + ">"),
            is(true));//from  w  w  w.  ja v  a 2  s  .  co  m
}

From source file:org.apache.hadoop.hive.ql.QTestUtil.java

private int executeClientInternal(String commands) {
    List<String> cmds = CliDriver.splitSemiColon(commands);
    int rc = 0;//  w  w w . ja  v a2 s  .com

    String command = "";
    for (String oneCmd : cmds) {
        if (StringUtils.endsWith(oneCmd, "\\")) {
            command += StringUtils.chop(oneCmd) + "\\;";
            continue;
        } else {
            if (isHiveCommand(oneCmd)) {
                command = oneCmd;
            } else {
                command += oneCmd;
            }
        }
        if (StringUtils.isBlank(command)) {
            continue;
        }

        if (isCommandUsedForTesting(command)) {
            rc = executeTestCommand(command);
        } else {
            rc = cliDriver.processLine(command);
        }

        if (rc != 0 && !ignoreErrors()) {
            break;
        }
        command = "";
    }
    if (rc == 0 && SessionState.get() != null) {
        SessionState.get().setLastCommand(null); // reset
    }
    return rc;
}

From source file:org.apache.hcatalog.cli.HCatCli.java

private static int processLine(String line) {
    int ret = 0;//from w  w  w . j av a2 s. co m

    String command = "";
    for (String oneCmd : line.split(";")) {

        if (StringUtils.endsWith(oneCmd, "\\")) {
            command += StringUtils.chop(oneCmd) + ";";
            continue;
        } else {
            command += oneCmd;
        }
        if (StringUtils.isBlank(command)) {
            continue;
        }

        ret = processCmd(command);
        command = "";
    }
    return ret;
}

From source file:org.apache.hive.jdbc.beeline.HiveBeeline.java

public static void main(String[] args) throws Exception {
    OptionsProcessor oproc = new OptionsProcessor();
    if (!oproc.processArgs(args)) {
        System.exit(1);/*  ww w. j av  a 2  s. co  m*/
    }

    // assemble connection URL
    String jdbcURL = URI_PREFIX;
    if (oproc.getHost() != null) {
        // no, host name indicates an embbeded hive invocation
        jdbcURL += oproc.getHost() + ":" + oproc.getPort();
    }

    if (!oproc.getDatabase().isEmpty()) {
        jdbcURL += URL_DB_MARKER + oproc.getDatabase();
    }
    if (!oproc.getSessVars().isEmpty()) {
        jdbcURL += URL_SESS_VAR_MARKER + oproc.getSessVars();
    }
    if (!oproc.getHiveConfs().isEmpty()) {
        jdbcURL += URL_HIVE_CONF_MARKER + oproc.getHiveConfs();
    }
    if (!oproc.getHiveVars().isEmpty()) {
        jdbcURL += URL_HIVE_VAR_MARKER + oproc.getHiveVars();
    }

    // setup input file or string
    InputStream sqlLineInput = null;
    if (oproc.getFileName() != null) {
        String scriptCmd = SQLLINE_SCRIPT_CMD + " " + oproc.getFileName().trim() + "\n";
        sqlLineInput = new ByteArrayInputStream(scriptCmd.getBytes());
    } else if (oproc.getExecString() != null) {
        // process the string to make each stmt a separate line
        String execString = oproc.getExecString().trim();
        String execCommand = "";
        String command = "";
        for (String oneCmd : execString.split(";")) {
            if (StringUtils.endsWith(oneCmd, "\\")) {
                command += StringUtils.chop(oneCmd) + ";";
                continue;
            } else {
                command += oneCmd;
            }
            if (StringUtils.isBlank(command)) {
                continue;
            }
            execCommand += command + ";\n"; // stmt should end with ';' for sqlLine
            command = "";
        }
        sqlLineInput = new ByteArrayInputStream(execCommand.getBytes());
    }

    // setup SQLLine args
    List<String> argList = new ArrayList<String>();
    argList.add("-u");
    argList.add(jdbcURL);
    argList.add("-d");
    argList.add(HIVE_JDBC_DRIVER); // TODO: make it configurable for HS or HS2
    if (oproc.getpMode() == PrintMode.SILENT) {
        argList.add(SQLLINE_SILENT);
    } else if (oproc.getpMode() == PrintMode.VERBOSE) {
        argList.add(SQLLINE_VERBOSE);
    }

    // Invoke sqlline
    SqlLine.mainWithInputRedirection(argList.toArray(new String[0]), sqlLineInput);
}

From source file:org.apache.maven.scm.provider.svn.svnexe.command.remoteinfo.SvnRemoteInfoCommand.java

@Override
public RemoteInfoScmResult executeRemoteInfoCommand(ScmProviderRepository repository, ScmFileSet fileSet,
        CommandParameters parameters) throws ScmException {

    String url = ((SvnScmProviderRepository) repository).getUrl();
    // use a default svn layout, url is here http://svn.apache.org/repos/asf/maven/maven-3/trunk
    // so as we presume we have good users using standard svn layout, we calculate tags and branches url
    String baseUrl = StringUtils.endsWith(url, "/")
            ? StringUtils.substringAfter(StringUtils.removeEnd(url, "/"), "/")
            : StringUtils.substringBeforeLast(url, "/");

    Commandline cl = SvnCommandLineUtils.getBaseSvnCommandLine(fileSet == null ? null : fileSet.getBasedir(),
            (SvnScmProviderRepository) repository);

    cl.createArg().setValue("ls");

    cl.createArg().setValue(baseUrl + "/tags");

    CommandLineUtils.StringStreamConsumer stderr = new CommandLineUtils.StringStreamConsumer();

    LsConsumer consumer = new LsConsumer(getLogger(), baseUrl);

    int exitCode = 0;

    Map<String, String> tagsInfos = null;

    try {//from w  ww.j  a  v  a  2s. c om
        exitCode = SvnCommandLineUtils.execute(cl, consumer, stderr, getLogger());
        tagsInfos = consumer.infos;

    } catch (CommandLineException ex) {
        throw new ScmException("Error while executing svn command.", ex);
    }

    if (exitCode != 0) {
        return new RemoteInfoScmResult(cl.toString(), "The svn command failed.", stderr.getOutput(), false);
    }

    cl = SvnCommandLineUtils.getBaseSvnCommandLine(fileSet == null ? null : fileSet.getBasedir(),
            (SvnScmProviderRepository) repository);

    cl.createArg().setValue("ls");

    cl.createArg().setValue(baseUrl + "/tags");

    stderr = new CommandLineUtils.StringStreamConsumer();

    consumer = new LsConsumer(getLogger(), baseUrl);

    Map<String, String> branchesInfos = null;

    try {
        exitCode = SvnCommandLineUtils.execute(cl, consumer, stderr, getLogger());
        branchesInfos = consumer.infos;

    } catch (CommandLineException ex) {
        throw new ScmException("Error while executing svn command.", ex);
    }

    if (exitCode != 0) {
        return new RemoteInfoScmResult(cl.toString(), "The svn command failed.", stderr.getOutput(), false);
    }

    return new RemoteInfoScmResult(cl.toString(), branchesInfos, tagsInfos);
}