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

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

Introduction

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

Prototype

public static String substringBeforeLast(final String str, final String separator) 

Source Link

Document

Gets the substring before the last occurrence of a separator.

Usage

From source file:org.kawanfw.file.servlet.util.FileTransferManager.java

public boolean download(OutputStream out, FileConfigurator fileConfigurator, String username, String filename,
        long chunkLength) throws FileNotFoundException, IOException {
    InputStream in = null;//from  w w w . j av a 2s  .  c  om

    debug(new Date() + " DOWNLOAD SESSION BEGIN ");

    try {
        filename = HttpConfigurationUtil.addRootPath(fileConfigurator, username, filename);

        debug(new Date() + " DOWNLOAD CHUNK");

        // Do we must download a chunk only ? We will then seek the
        // Random access file and read only one chunk length and send it
        // back to client
        if (filename.endsWith(".kawanfw.chunk")) {

            // We are now in chunk case
            String rawFilename = StringUtils.substringBeforeLast(filename, ".kawanfw.chunk");
            String indexStr = StringUtils.substringAfterLast(rawFilename, ".");
            int index = Integer.parseInt(indexStr);

            // Remove the number
            rawFilename = StringUtils.substringBeforeLast(rawFilename, ".");

            // We seek the total length of previous files, because client
            // method
            // is idempotent and may be replayed
            long lengthToSeek = (index - 1) * chunkLength;

            // debug("index       : " + index);
            // debug("chunkLength : " + chunkLength);
            // debug("lengthToSeek: " + lengthToSeek);

            debug("");
            debug(new Date() + " SESSION " + " " + index);

            RandomAccessFile raf = null;

            try {

                File file = new File(rawFilename);

                if (!file.exists()) {
                    debug("File does not exists: " + file);
                    return false;
                }

                debug(new Date() + " BEFORE SEEK ");

                debug(new Date() + " BEFORE CREATE RAF");
                raf = new RandomAccessFile(file, "rw");
                debug(new Date() + " AFTER  CREATE RAF");

                raf.seek(lengthToSeek);

                debug(new Date() + " BEFORE COPY ");
                long totalRead = copy(raf, out, chunkLength);
                debug(new Date() + " AFTER COPY " + totalRead);

                IOUtils.closeQuietly(raf);

                if (lengthToSeek + totalRead >= file.length()) {
                    // End of operations
                    // Nothing yo do with Random Access File
                }

            } finally {
                IOUtils.closeQuietly(raf);
            }

            return true;

        } else {

            debug(new Date() + " DOWNLOAD FULL FILE");

            File file = new File(filename);

            if (!file.exists()) {
                debug("File does not exists: " + file);
                return false;
            }

            in = new BufferedInputStream(new FileInputStream(file));
            IOUtils.copy(in, out);
        }

        return true;

    } finally {
        IOUtils.closeQuietly(in);
    }

}

From source file:org.kawanfw.file.servlet.util.FileTransferManager.java

public void upload(FileConfigurator fileConfigurator, InputStream inputStream, String username, String filename,
        long chunkLength) throws IOException {

    debug(new Date() + " UPLOAD SESSION BEGIN ");

    filename = HttpConfigurationUtil.addRootPath(fileConfigurator, username, filename);

    // is it a file chunk? If yes append to filename
    if (filename.endsWith(".kawanfw.chunk") || filename.endsWith(".kawanfw.chunk.LASTCHUNK")) {

        RandomAccessFile raf = null;

        try {/*from w ww  .j ava  2s.c o m*/

            boolean lastChunk = false;

            if (filename.endsWith(".LASTCHUNK")) {
                debug(new Date() + " RENAME DONE");
                filename = StringUtils.substringBeforeLast(filename, ".LASTCHUNK");
                lastChunk = true;
            }

            initFileIfFirstChunk(username, filename);

            String rawFilename = StringUtils.substringBeforeLast(filename, ".kawanfw.chunk");
            String indexStr = StringUtils.substringAfterLast(rawFilename, ".");

            // Remove the number
            rawFilename = StringUtils.substringBeforeLast(rawFilename, ".");

            int index = Integer.parseInt(indexStr);

            File file = new File(rawFilename);

            debug(new Date() + " SESSION INDEX" + " " + index);

            // We must create, if necessary, the path to the file
            createParentDir(file);

            debug(new Date() + " BEFORE CREATE RAF");
            raf = new RandomAccessFile(file, "rw");
            debug(new Date() + " AFTER CREATE RAF");

            // We seek the total length of previous files, because client
            // method
            // is idempotent and may be replayed
            long lengthToSeek = (index - 1) * chunkLength;

            // debug("index       : " + index);
            // debug("chunkLength : " + chunkLength);
            // debug("lengthToSeek: " + lengthToSeek);

            debug(new Date() + " BEFORE SEEK ");
            raf.seek(lengthToSeek);

            debug(new Date() + " BEFORE COPY ");
            copy(inputStream, raf, new byte[DEFAULT_BUFFER_SIZE]);
            debug(new Date() + " AFTER COPY ");

            IOUtils.closeQuietly(raf);

            if (lastChunk) {
                // End of operations
                // Do nothing with Random Access Files
            }

        } finally {
            IOUtils.closeQuietly(raf);
        }

    } else {

        OutputStream out = null;

        try {
            File file = new File(filename);

            // We must create, if necessary, the path to the file
            createParentDir(file);

            out = new BufferedOutputStream(new FileOutputStream(file));
            IOUtils.copy(inputStream, out);

            debug("file created : " + file);
            debug("file.length(): " + file.length());
        } finally {
            IOUtils.closeQuietly(out);
        }
    }

}

From source file:org.kawanfw.file.servlet.util.FileTransferManager.java

/**
 * Delete the raw file if first chunk/* ww  w. j a v  a  2  s.c  o  m*/
 * 
 * @param username
 *            the client username
 * @param filename
 *            the chunk file name
 */
private void initFileIfFirstChunk(String username, String filename) throws IOException {

    if (filename.endsWith(".1.kawanfw.chunk")) {
        String rawFilename = StringUtils.substringBeforeLast(filename, ".kawanfw.chunk");
        rawFilename = StringUtils.substringBeforeLast(rawFilename, "."); // Remove
        // the
        // number

        File file = new File(rawFilename);

        if (file.exists()) {
            boolean deleted = file.delete();
            if (!deleted) {
                throw new IOException(
                        "File delete required because of upload of first chunk. Impossible to delete file: "
                                + file);
            }
        }
    }

}

From source file:org.kawanfw.sql.servlet.ServerSqlManager.java

/**
 * Init/*from   w  w w . j  a v a  2  s.  c  o m*/
 */

public void init(ServletConfig config) throws ServletException {
    super.init(config);

    // Variable use to store the current name when loading, used to
    // detail
    // the exception in the catch clauses
    String classNameToLoad = null;

    String commonsConfiguratorClassName;
    String fileConfiguratorClassName;
    String sqlConfiguratorClassName;

    String servletName = this.getServletName();

    String index = null;

    if (!TomcatModeStore.isTomcatEmbedded()) {
        System.out.println(SqlTag.SQL_PRODUCT_START + " " + Version.getServerVersion());
    }

    // We are in SQL Framework
    TomcatModeStore.setFrameworkSql(true);

    try {

        if (!TomcatModeStore.isTomcatEmbedded()) {
            String propertiesFileStr = config.getInitParameter("properties");

            if (propertiesFileStr == null || propertiesFileStr.isEmpty()) {

                String aceqlHome = System.getenv("ACEQL_HOME");

                if (aceqlHome != null) {

                    // Remove surrounding " if present
                    aceqlHome = aceqlHome.replaceAll("\"", "");

                    if (aceqlHome.endsWith(File.separator)) {
                        aceqlHome = StringUtils.substringBeforeLast(aceqlHome, File.separator);
                    }
                    propertiesFileStr = aceqlHome + File.separator + "conf" + File.separator
                            + "aceql-server.properties";
                } else {
                    throw new SqlConfigurationException(Tag.PRODUCT_USER_CONFIG_FAIL
                            + " ACEQL_HOME property not set. Impossible to use the default ACEQL_HOME"
                            + File.separator + "conf" + File.separator + "aceql-server.properties file");
                }

                //          throw new SqlConfigurationException(
                //             Tag.PRODUCT_USER_CONFIG_FAIL
                //                + " <param-name> \"properties\" not found for servlet "
                //                + servletName);
            }

            File propertiesFile = new File(propertiesFileStr);

            if (!propertiesFile.exists()) {
                throw new SqlConfigurationException(
                        Tag.PRODUCT_USER_CONFIG_FAIL + " properties file not found: " + propertiesFile);
            }

            System.out.println(SqlTag.SQL_PRODUCT_START + " " + "Using properties file: " + propertiesFile);

            properties = TomcatStarterUtil.getProperties(propertiesFile);

            index = TomcatStarterUtil.getIndexFromServletName(properties, servletName);

            TomcatStarterUtil.setInitParametersInStore(properties, index);

            // Create the default DataSource if necessary
            TomcatStarterUtil.createAndStoreDataSource(properties, index);
        }

        commonsConfiguratorClassName = ServletParametersStore.getInitParameter(servletName,
                COMMONS_CONFIGURATOR_CLASS_NAME);
        fileConfiguratorClassName = ServletParametersStore.getInitParameter(servletName,
                FILE_CONFIGURATOR_CLASS_NAME);
        sqlConfiguratorClassName = ServletParametersStore.getInitParameter(servletName,
                SQL_CONFIGURATOR_CLASS_NAME);

        debug("commonsConfiguratorClassName: " + commonsConfiguratorClassName);
        debug("fileConfiguratorClassName   : " + fileConfiguratorClassName);
        debug("sqlConfiguratorClassName    : " + sqlConfiguratorClassName);

        // Check spelling with first letter capitalized

        if (commonsConfiguratorClassName == null || commonsConfiguratorClassName.isEmpty()) {
            String capitalized = StringUtils.capitalize(ServerFileManager.COMMONS_CONFIGURATOR_CLASS_NAME);
            commonsConfiguratorClassName = ServletParametersStore.getInitParameter(servletName, capitalized);
        }

        if (fileConfiguratorClassName == null || fileConfiguratorClassName.isEmpty()) {
            String capitalized = StringUtils.capitalize(ServerFileManager.FILE_CONFIGURATOR_CLASS_NAME);
            fileConfiguratorClassName = ServletParametersStore.getInitParameter(servletName, capitalized);
        }

        if (sqlConfiguratorClassName == null || sqlConfiguratorClassName.isEmpty()) {
            String capitalized = StringUtils.capitalize(SQL_CONFIGURATOR_CLASS_NAME);
            sqlConfiguratorClassName = ServletParametersStore.getInitParameter(servletName, capitalized);
        }

        // Call the specific Configurator class to use

        classNameToLoad = commonsConfiguratorClassName;
        if (commonsConfiguratorClassName != null && !commonsConfiguratorClassName.isEmpty()) {
            Class<?> c = Class.forName(commonsConfiguratorClassName);
            commonsConfigurator = (CommonsConfigurator) c.newInstance();
        } else {

            commonsConfigurator = new DefaultCommonsConfigurator();

        }

        // Immediately create the ServerLogger
        Logger logger = null;
        try {
            logger = commonsConfigurator.getLogger();
            ServerLogger.createLogger(logger);
            serverLoggerOk = true;
        } catch (Exception e) {
            exception = e;
            initErrrorMesage = Tag.PRODUCT_USER_CONFIG_FAIL + " Impossible to create the Logger: " + logger
                    + ". Reason: " + e.getMessage();
        }

        classNameToLoad = fileConfiguratorClassName;
        if (fileConfiguratorClassName != null && !fileConfiguratorClassName.isEmpty()) {
            Class<?> c = Class.forName(fileConfiguratorClassName);
            fileConfigurator = (FileConfigurator) c.newInstance();
        } else {
            fileConfigurator = new DefaultFileConfigurator();
        }

        classNameToLoad = sqlConfiguratorClassName;
        if (sqlConfiguratorClassName != null && !sqlConfiguratorClassName.isEmpty()) {
            Class<?> c = Class.forName(sqlConfiguratorClassName);
            sqlConfigurator = (SqlConfigurator) c.newInstance();
        } else {
            sqlConfigurator = new DefaultSqlConfigurator();
        }

    } catch (ClassNotFoundException e) {
        initErrrorMesage = Tag.PRODUCT_USER_CONFIG_FAIL
                + " Impossible to load (ClassNotFoundException) Configurator class: " + classNameToLoad;
        exception = e;
    } catch (InstantiationException e) {
        initErrrorMesage = Tag.PRODUCT_USER_CONFIG_FAIL
                + " Impossible to load (InstantiationException) Configurator class: " + classNameToLoad;
        exception = e;
    } catch (IllegalAccessException e) {
        initErrrorMesage = Tag.PRODUCT_USER_CONFIG_FAIL
                + " Impossible to load (IllegalAccessException) Configurator class: " + classNameToLoad;
        exception = e;
    } catch (SqlConfigurationException e) {
        initErrrorMesage = e.getMessage();
        exception = e;
    } catch (Exception e) {
        initErrrorMesage = Tag.PRODUCT_PRODUCT_FAIL + " Please contact support at: support@kawansoft.com";
        exception = e;
    }

    if (commonsConfigurator == null) {
        commonsConfiguratorClassName = COMMONS_CONFIGURATOR_CLASS_NAME;
    } else {
        commonsConfiguratorClassName = commonsConfigurator.getClass().getName();
    }

    if (fileConfigurator == null) {
        fileConfiguratorClassName = FILE_CONFIGURATOR_CLASS_NAME;
    } else {
        fileConfiguratorClassName = fileConfigurator.getClass().getName();
    }

    if (sqlConfigurator == null) {
        sqlConfiguratorClassName = SQL_CONFIGURATOR_CLASS_NAME;
    } else {
        sqlConfiguratorClassName = sqlConfigurator.getClass().getName();
    }

    System.out.println(SqlTag.SQL_PRODUCT_START + " " + servletName + " Servlet Configurators:");
    System.out.println(
            SqlTag.SQL_PRODUCT_START + "  -> commonsConfiguratorClassName: " + commonsConfiguratorClassName);
    System.out.println(
            SqlTag.SQL_PRODUCT_START + "  -> sqlConfiguratorClassName    : " + sqlConfiguratorClassName);
    System.out.println(
            SqlTag.SQL_PRODUCT_START + "  -> fileConfiguratorClassName   : " + fileConfiguratorClassName);

    if (exception == null) {
        System.out.println(SqlTag.SQL_PRODUCT_START + "  -> Configurators Status: OK.");
    } else {

        if (!TomcatModeStore.isTomcatEmbedded()) {
            String errorMessage1 = SqlTag.SQL_PRODUCT_START + "  -> Configurators Status: KO.";
            String errorMessage2 = initErrrorMesage;
            String errorMessage3 = ExceptionUtils.getStackTrace(exception);

            System.out.println(errorMessage1);
            System.out.println(errorMessage2);
            System.out.println(errorMessage3);

            if (serverLoggerOk) {
                ServerLogger.getLogger().log(Level.WARNING, errorMessage1);
                ServerLogger.getLogger().log(Level.WARNING, errorMessage2);
                ServerLogger.getLogger().log(Level.WARNING, errorMessage3);
            }

            System.out.println();
        }

    }
}

From source file:org.kawanfw.sql.tomcat.PoolPropertiesCreator.java

/**
 * Creates the PoolProperties from the properties passed on constructor.
 * /*from   w  w  w. j a  v  a  2s . c  o  m*/
 * @return a PoolProperties
 * @throws ClassNotFoundException
 * @throws IllegalAccessException
 * @throws InstantiationException
 * @throws InvocationTargetException
 * @throws NoSuchMethodException
 * @throws IllegalArgumentException
 * @throws SecurityException
 * 
 * @throws NumberFormatException
 *             if a numeric property is with letters
 * @throws Exception
 *             for all others cases
 */
public PoolProperties create() throws ClassNotFoundException, InstantiationException, IllegalAccessException,
        SecurityException, IllegalArgumentException, NoSuchMethodException, InvocationTargetException {

    theClass = Class.forName("org.apache.tomcat.jdbc.pool.PoolProperties");
    theObject = theClass.newInstance();

    Method[] allMethods = theClass.getDeclaredMethods();
    Field[] fieldsArray = theClass.getDeclaredFields();

    Set<String> fields = new HashSet<String>();

    for (Field theField : fieldsArray) {
        String fieldName = theField.getName();
        fields.add(fieldName);
    }

    methodNamesAndParms = new HashMap<String, Class<?>[]>();

    for (Method m : allMethods) {
        String methodName = m.getName();
        Class<?>[] pType = m.getParameterTypes();
        methodNamesAndParms.put(methodName, pType);
    }

    // First step: build the map httpClientParams
    for (Enumeration<?> e = properties.propertyNames(); e.hasMoreElements();) {

        String propertyName = (String) e.nextElement();
        String propertyValue = properties.getProperty(propertyName);

        if (propertyValue != null) {
            propertyValue = propertyValue.trim();
        }

        // Test that the property is a field of PoolProperties
        // Property name must end with "", or ".2, ".3", etc.
        if (propertyName.endsWith(index)) {

            propertyName = StringUtils.substringBeforeLast(propertyName, index);

            if (fields.contains(propertyName)) {
                try {
                    callMethod(propertyName, propertyValue);
                } catch (NumberFormatException e1) {
                    throw new SqlConfigurationException(
                            "The " + propertyName + " value is not numeric: " + propertyValue);
                }
            }
            // No! Does not work because all properties in
            // server-sql.properties are not Tomcat JDBC pool properties
            // else {
            // throw new SqlConfigurationException("The property " +
            // propertyName +
            // " does not match a Tomcat JDBC Pool property.");
            // }
        }

    }

    PoolProperties poolProperties = (PoolProperties) theObject;
    return poolProperties;
}

From source file:org.kawanfw.sql.WebServer.java

/**
 * Starts or stops the AceQL Web Server.
 * //from  w  ww .j a  v a2 s  . c o m
 * @param args   the arguments of Web Server start/stop.
 * 
 * @throws ParseException      if any Exception when parsing command line
 * @throws IOException      if any I/O Exception
 * @throws ConnectException      if server is unable to connect to specified or default 9090 port
 * @throws SqlConfigurationException if any error in configuration properties file
 */
public static void main(String[] args)
        throws ParseException, IOException, ConnectException, SqlConfigurationException {

    if (args.length > 0) {
        debug("args[0]: " + args[0] + ":");
    }

    if (args.length > 1) {
        debug("args[1]: " + args[1] + ":");
    }

    Options options = createOptions();
    CommandLineParser parser = new GnuParser();

    CommandLine cmd = null;
    try {
        cmd = parser.parse(options, args);
    } catch (UnrecognizedOptionException e) {
        System.out.println(e.getMessage());
        System.out.println();
        printUsage(options);
        System.exit(-1);
    }

    if (cmd.hasOption("help")) {
        printUsage(options);
        System.exit(-1);
    }

    if (cmd.hasOption("version")) {
        System.out.println(Version.getServerVersion());
        System.out.println();
        System.exit(-1);
    }

    if (!cmd.hasOption("start") && !cmd.hasOption("stop")) {
        System.err.println("Missing start or stop option." + " " + SqlTag.PLEASE_CORRECT);
        System.out.println();
        printUsage(options);
        System.exit(-1);
    }

    int port = WebServerApi.DEFAULT_PORT;

    if (cmd.hasOption("port")) {
        String portStr = cmd.getOptionValue("port");

        try {
            port = Integer.parseInt(portStr);
        } catch (Exception e) {
            displayErrorAndExit("The port parameter is not numeric: " + portStr + ".", options);
        }
    }

    if (cmd.hasOption("start")) {

        if (!cmd.hasOption("host")) {
            displayErrorAndExit("Missing host option.", options);
        }

        String host = cmd.getOptionValue("host");

        File propertiesFile = null;

        if (!cmd.hasOption("properties")) {

            String aceqlHome = System.getenv("ACEQL_HOME");

            if (aceqlHome != null) {

                // Remove surrounding " if present
                aceqlHome = aceqlHome.replaceAll("\"", "");

                if (aceqlHome.endsWith(File.separator)) {
                    aceqlHome = StringUtils.substringBeforeLast(aceqlHome, File.separator);
                }
                propertiesFile = new File(
                        aceqlHome + File.separator + "conf" + File.separator + "aceql-server.properties");
            } else {
                displayErrorAndExit("Missing properties option.", options);
            }

        } else {
            propertiesFile = new File(cmd.getOptionValue("properties"));
        }

        WebServerApi webServerApi = new WebServerApi();
        try {
            webServerApi.startServer(host, port, propertiesFile);
        } catch (SqlConfigurationException e) {
            System.err.println(SqlTag.SQL_PRODUCT_START_FAILURE + " " + SqlTag.USER_CONFIGURATION_FAILURE + " "
                    + e.getMessage());
            System.err.println();
            System.exit((-1));
        }

        catch (ConnectException e) {
            System.err.println(SqlTag.SQL_PRODUCT_START_FAILURE + " " + e.getMessage());
            System.err.println();
            System.exit((-1));
        }

        catch (IOException e) {

            if (e instanceof UnknownHostException) {
                System.err.println(SqlTag.SQL_PRODUCT_START_FAILURE + " " + "Unknow host: " + e.getMessage());
            } else {
                System.err.println(SqlTag.SQL_PRODUCT_START_FAILURE + " " + e.getMessage());
            }

            if (e.getCause() != null) {
                e.printStackTrace();
            }

            System.err.println();
            System.exit(-1);
        } catch (Exception e) {
            System.err.println(SqlTag.SQL_PRODUCT_START_FAILURE);
            e.printStackTrace();
            System.err.println();
            System.exit(-1);
        }

    } else {

        WebServerApi webServerApi = new WebServerApi();
        try {
            webServerApi.stopServer(port);

            System.out.println("SQL Web server running on port " + port + " successfully stopped!");
            System.out.println();
            System.exit(-1);
        } catch (IOException e) {

            if (e instanceof ConnectException) {
                System.err.println(e.getMessage());
            } else {
                System.err.println("Impossible to stop the SQL Web server running on port " + port);
                System.err.println(e.getMessage());

                if (e.getCause() != null) {
                    System.err.println("Java Exception Stack Trace:");
                    e.printStackTrace();
                }

            }

            System.err.println();
            System.exit(-1);
        }
    }

}

From source file:org.kuali.kra.external.Cfda.service.impl.CfdaServiceImpl.java

/**
 * This method gets the url from the parameter and creates the fileName and 
 * the actual URL used to FTP./* w ww . j  a va2 s  . com*/
 */
protected void createGovURL() {
    // Example url ftp://ftp.cfda.gov/programs09187.csv
    String url = getParameterService().getParameterValueAsString(Constants.MODULE_NAMESPACE_AWARD,
            Constants.PARAMETER_COMPONENT_DOCUMENT, Constants.CFDA_GOV_URL_PARAMETER);
    String fileName = StringUtils.substringAfterLast(url, "/");
    url = StringUtils.substringBeforeLast(url, "/");

    if (StringUtils.contains(url, FTP_PREFIX)) {
        url = StringUtils.remove(url, FTP_PREFIX);
    }

    Calendar calendar = dateTimeService.getCurrentCalendar();
    // need to pull off the '20' in 2009
    String year = "" + calendar.get(Calendar.YEAR);
    year = year.substring(2, 4);
    fileName = fileName + year;

    // the last 3 numbers in the file name are the day of the year, but the files are from "yesterday"
    fileName = fileName + String.format("%03d", calendar.get(Calendar.DAY_OF_YEAR) - 1);
    fileName = fileName + ".csv";

    setGovURL(url);
    setCfdaFileName(fileName);
}

From source file:org.lockss.plugin.projmuse.ProjectMuseUrlNormalizer.java

@Override
public String additionalNormalization(String url, ArchivalUnit au) throws PluginException {
    log.debug3("in: " + url);
    if (url == null) {
        return url;
    }/*w ww.j  av a2s  . co  m*/

    url = StringUtils.substringBeforeLast(url, VERSION_SUFFIX);

    final String musehost = "://muse.jhu.edu/";
    int ix = url.indexOf(musehost);
    if (ix >= 0) {
        int slash = ix + musehost.length() - 1;
        String path = url.substring(slash);
        if (path.endsWith("/")) {
            path = path.substring(0, path.length() - 1);
        }
        String oldPath = paths.get(path);
        if (oldPath != null) {
            url = url.substring(0, slash) + oldPath;
        }
    }

    log.debug3("out: " + url);
    return url;
}

From source file:org.mortbay.jetty.load.generator.jenkins.result.LoadResultProjectAction.java

public static List<RunInformations> searchRunInformations(String jettyVersion, ElasticHost elasticHost,
        int maxResult) throws IOException {

    String originalJettyVersion = jettyVersion;

    // jettyVersion 9.4.9*
    //in case jettyVersion is 9.4.9.v20180320 we need to replace with 9.4.9*
    if (StringUtils.contains(jettyVersion, 'v')) {
        jettyVersion = StringUtils.substringBeforeLast(jettyVersion, ".v");
    }//from  w ww  . j  a v  a 2  s.  c  om
    // FIXME investigate elastic but query such 9.4.10-SNAPSHOT doesn't work...
    // so using 9.4.10* then filter response back....
    if (StringUtils.contains(jettyVersion, "-SNAPSHOT")) {
        jettyVersion = StringUtils.substringBeforeLast(jettyVersion, "-SNAPSHOT");
    }

    // in case of 9.4.11-NO-LOGGER-SNAPSHOT still not working with elastic
    // here we must have only number or . so remove everything else

    StringBuilder versionQuery = new StringBuilder();
    CharacterIterator ci = new StringCharacterIterator(jettyVersion);
    for (char c = ci.first(); c != CharacterIterator.DONE; c = ci.next()) {
        if (NumberUtils.isCreatable(Character.toString(c)) || c == '.') {
            versionQuery.append(c);
        }
    }

    jettyVersion = versionQuery.toString() + "*";

    try (ElasticResultStore elasticResultStore = elasticHost.buildElasticResultStore(); //
            InputStream inputStream = LoadResultProjectAction.class
                    .getResourceAsStream("/versionResult.json")) {
        String versionResultQuery = IOUtils.toString(inputStream);
        Map<String, String> map = new HashMap<>(1);
        map.put("jettyVersion", jettyVersion);
        map.put("maxResult", Integer.toString(maxResult));
        versionResultQuery = StrSubstitutor.replace(versionResultQuery, map);

        String results = elasticResultStore.search(versionResultQuery);

        List<LoadResult> loadResults = ElasticResultStore
                .map(new HttpContentResponse(null, results.getBytes(), null, null));

        List<RunInformations> runInformations = //
                loadResults.stream() //
                        .filter(loadResult -> StringUtils.equalsIgnoreCase(originalJettyVersion, //
                                loadResult.getServerInfo().getJettyVersion())) //
                        .map(loadResult -> new RunInformations(
                                loadResult.getServerInfo().getJettyVersion() + ":"
                                        + loadResult.getServerInfo().getGitHash(), //
                                loadResult.getCollectorInformations(),
                                StringUtils.lowerCase(loadResult.getTransport())) //
                                        .jettyVersion(loadResult.getServerInfo().getJettyVersion()) //
                                        .estimatedQps(LoadTestResultBuildAction.estimatedQps(
                                                LoadTestResultBuildAction.getLoaderConfig(loadResult))) //
                                        .serverInfo(loadResult.getServerInfo())) //
                        .collect(Collectors.toList());

        Collections.sort(runInformations, Comparator.comparing(o -> o.getStartTimeStamp()));
        return runInformations;
    }

}

From source file:org.neomatrix369.apiworld.util.Utils.java

/**
 * Removes the trailing separator using apache commons lang.
 *
 * @param urlParameterTokens String//w  ww.  j a  v  a2s.  c  o m
 * @param paramSeparator     String
 * @return String
 */
public static String dropTrailingSeparator(String urlParameterTokens, String paramSeparator) {
    return StringUtils.substringBeforeLast(urlParameterTokens, paramSeparator);
}