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

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

Introduction

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

Prototype

public static String stripEnd(final String str, final String stripChars) 

Source Link

Document

Strips any of a set of characters from the end of a String.

A null input String returns null .

Usage

From source file:net.siegmar.japtproxy.JaptProxyServer.java

/**
 * Starts the JaptProxyServer with the given parameters.
 *
 * @param args command line args.//from  ww  w. j a va2 s .  c om
 */
public static void main(final String[] args) {
    if (checkRequiredOptions()) {
        System.exit(1);
    }

    String configFile = System.getProperty(OPT_CONFIG);
    String contextPath = System.getProperty(OPT_CONTEXT_PATH);
    String logConfig = System.getProperty(OPT_LOG_CONFIG);
    final String host = System.getProperty(OPT_HOST);
    String port = System.getProperty(OPT_PORT);

    // Check settings
    if (configFile == null) {
        configFile = OPT_CONFIG_DEFAULT;
    }
    if (contextPath == null) {
        contextPath = OPT_CONTEXT_PATH_DEFAULT;
    }
    if (logConfig == null) {
        logConfig = OPT_LOG_CONFIG_DEFAULT;
    }
    if (port == null) {
        port = OPT_PORT_DEFAULT;
    }

    if (!new File(configFile).exists()) {
        System.err.println("Config file '" + configFile + "' doesn't exist");
        System.exit(1);
    }

    try {
        initializeLogging(logConfig);
    } catch (final RuntimeException e) {
        System.err.println("Couldn't initialize logging");
        e.printStackTrace(System.err);
        System.exit(1);
    }

    final Logger log = LoggerFactory.getLogger(JaptProxyServer.class);

    // Remove PID_FILE if specified
    final String pidFile = System.getenv("PID_FILE");
    if (pidFile != null) {
        log.debug("Will try to delete PID_FILE {} on exit", pidFile);
        new File(pidFile).deleteOnExit();
    }

    try {
        final int portNumber = Integer.parseInt(port);
        startServer(host, portNumber, StringUtils.stripEnd(contextPath, "/"));
    } catch (final NumberFormatException e) {
        log.error("The specified port number {} is not a number", port);
        System.exit(1);
    } catch (final RuntimeException e) {
        log.error("Error while starting server", e);
        System.exit(1);
    }
}

From source file:com.mijecu25.sqlplus.SQLPlus.java

public static void main(String[] args) throws IOException {
    // Create and load the properties from the application properties file
    Properties properties = new Properties();
    properties.load(SQLPlus.class.getClassLoader().getResourceAsStream(SQLPlus.APPLICATION_PROPERTIES_FILE));

    SQLPlus.logger.info("Initializing " + SQLPlus.PROGRAM_NAME + " version "
            + properties.getProperty(SQLPlus.APPLICATION_PROPERTIES_FILE_VERSION));

    // Check if the user is using a valid console (i.e. not from Eclipse)
    if (System.console() == null) {
        // The Console object for the JVM could not be found. Alert the user 
        SQLPlus.logger.fatal(Messages.FATAL + "A JVM Console object was not found. Try running "
                + SQLPlus.PROGRAM_NAME + "from the command line");
        System.out.println(/*from w w  w.  ja  v a  2s.c om*/
                Messages.FATAL + SQLPlus.PROGRAM_NAME + " was not able to find your JVM's Console object. "
                        + "Try running " + SQLPlus.PROGRAM_NAME + " from the command line.");

        SQLPlus.exitSQLPlus();

        SQLPlus.logger.fatal(Messages.FATAL + Messages.QUIT_PROGRAM_ERROR(PROGRAM_NAME));
        return;
    }

    // UI intro
    System.out.println("Welcome to " + SQLPlus.PROGRAM_NAME
            + "! This program has a DSL to add alerts to various SQL DML events.");
    System.out.println("Be sure to use " + SQLPlus.PROGRAM_NAME + " from the command line.");
    System.out.println();

    // Get the version
    System.out.println("Version: " + properties.getProperty(SQLPlus.APPLICATION_PROPERTIES_FILE_VERSION));
    System.out.println();

    // Read the license file
    BufferedReader bufferedReader;
    bufferedReader = new BufferedReader(new FileReader(SQLPlus.LICENSE_FILE));

    // Read a line
    String line = bufferedReader.readLine();

    // While the line is not null
    while (line != null) {
        System.out.println(line);

        // Read a new lines
        line = bufferedReader.readLine();
    }

    // Close the buffer
    bufferedReader.close();
    System.out.println();

    // Create the jline console that allows us to remember commands, use arrow keys, and catch interruptions
    // from the user
    SQLPlus.console = new ConsoleReader();
    SQLPlus.console.setHandleUserInterrupt(true);

    try {
        // Get credentials from the user
        SQLPlus.logger.info("Create SQLPlusConnection");
        SQLPlus.createSQLPlusConnection();
    } catch (NullPointerException | SQLException | IllegalArgumentException e) {
        // NPE: This exception can occur if the user is running the program where the JVM Console
        // object cannot be found.
        // SQLE: TODO should I add here the error code?
        // This exception can occur when trying to establish a connection
        // IAE: This exception can occur when trying to establish a connection
        SQLPlus.logger
                .fatal(Messages.FATAL + Messages.FATAL_EXIT(SQLPlus.PROGRAM_NAME, e.getClass().getName()));
        System.out.println(Messages.FATAL + Messages.FATAL_EXCEPTION_ACTION(e.getClass().getSimpleName()) + " "
                + Messages.CHECK_LOG_FILES);
        SQLPlus.exitSQLPlus();

        SQLPlus.logger.fatal(Messages.FATAL + Messages.QUIT_PROGRAM_ERROR(SQLPlus.PROGRAM_NAME));
        return;
    } catch (UserInterruptException uie) {
        SQLPlus.logger.warn(Messages.WARNING + "The user typed an interrupt instruction.");
        SQLPlus.exitSQLPlus();

        return;
    }

    System.out.println("Connection established! Commands end with " + SQLPlus.END_OF_COMMAND);
    System.out.println("Type " + SQLPlus.EXIT + " or " + SQLPlus.QUIT + " to exit the application ");

    try {
        // Execute the input scanner
        while (true) {
            // Get a line from the user until the hit enter (carriage return, line feed/ new line).
            System.out.print(SQLPlus.PROMPT);
            try {
                line = SQLPlus.console.readLine().trim();
            } catch (NullPointerException npe) {
                // TODO test this behavior
                // If this exception is catch, it is very likely that the user entered the end of line command.
                // This means that the program should quit.
                SQLPlus.logger.warn(Messages.WARNING + "The input from the user is null. It is very likely that"
                        + "the user entered the end of line command and they want to quit.");
                SQLPlus.exitSQLPlus();

                return;
            }

            // If the user did not enter anything
            if (line.isEmpty()) {
                // Continue to the next iteration
                continue;
            }

            if (line.equals(".")) {
                line = "use courses;";
            }

            if (line.equals("-")) {
                line = "select created_at from classes;";
            }

            if (line.equals("--")) {
                line = "select name, year from classes;";
            }

            if (line.equals("*")) {
                line = "select * from classes;";
            }

            if (line.equals("x")) {
                line = "select name from classes, classes;";
            }

            if (line.equals("e")) {
                line = "select * feom classes;";
            }

            // Logic to quit
            if (line.equals(SQLPlus.QUIT) || line.equals(SQLPlus.EXIT)) {
                SQLPlus.logger.info("The user wants to quit " + SQLPlus.PROGRAM_NAME);
                SQLPlus.exitSQLPlus();
                break;
            }

            // Use a StringBuilder since jline works weird when it has read a line. The issue we were having was with the
            // end of command logic. jline does not keep the input from the user in the variable that was stored in. Each
            // time jline reads a new line, the variable is empty
            StringBuilder query = new StringBuilder();
            query.append(line);

            // While the user does not finish the command with the SQLPlus.END_OF_COMMAND
            while (query.charAt(query.length() - 1) != SQLPlus.END_OF_COMMAND) {
                // Print the wait for command prompt and get the next line for the user
                System.out.print(SQLPlus.WAIT_FOR_END_OF_COMMAND);
                query.append(" ");
                line = StringUtils.stripEnd(SQLPlus.console.readLine(), null);
                query.append(line);
            }

            SQLPlus.logger.info("Raw input from the user: " + query);

            try {
                Statement statement;

                try {
                    // Execute the antlr code to parse the user input
                    SQLPlus.logger.info("Will parse the user input to determine what to execute");
                    ANTLRStringStream input = new ANTLRStringStream(query.toString());
                    SQLPlusLex lexer = new SQLPlusLex(input);
                    CommonTokenStream tokens = new CommonTokenStream(lexer);
                    SQLPlusParser parser = new SQLPlusParser(tokens);

                    statement = parser.sqlplus();
                } catch (RecognitionException re) {
                    // TODO move this to somehwere else
                    //                        String message = Messages.WARNING + "You have an error in your SQL syntax. Check the manual"
                    //                                + " that corresponds to your " + SQLPlus.sqlPlusConnection.getCurrentDatabase()
                    //                                + " server or " + SQLPlus.PROGRAM_NAME + " for the correct syntax";
                    //                        SQLPlus.logger.warn(message);
                    //                        System.out.println(message);
                    statement = new StatementDefault();
                }

                statement.setStatement(query.toString());
                SQLPlus.sqlPlusConnection.execute(statement);
            } catch (UnsupportedOperationException uoe) {
                // This exception can occur when the user entered a command allowed by the parsers, but not currently
                // supported by SQLPlus. This can occur because the parser is written in such a way that supports
                // the addition of features.
                SQLPlus.logger.warn(Messages.WARNING + uoe);
                System.out.println(
                        Messages.WARNING + Messages.FATAL_EXCEPTION_ACTION(uoe.getClass().getSimpleName()) + " "
                                + Messages.CHECK_LOG_FILES);
                SQLPlus.logger.warn(Messages.WARNING + "The previous command is not currently supported.");
            }

        }
    } catch (IllegalArgumentException iae) {
        // This exception can occur when a command is executed but it had illegal arguments. Most likely
        // it is a programmer's error and should be addressed by the developer.
        SQLPlus.logger
                .fatal(Messages.FATAL + Messages.FATAL_EXIT(SQLPlus.PROGRAM_NAME, iae.getClass().getName()));
        SQLPlus.exitSQLPlus();

        SQLPlus.logger.fatal(Messages.FATAL + Messages.QUIT_PROGRAM_ERROR(SQLPlus.PROGRAM_NAME));
    } catch (UserInterruptException uie) {
        SQLPlus.logger.warn(Messages.WARNING + "The user typed an interrupt instruction.");
        SQLPlus.exitSQLPlus();
    }
}

From source file:groovy.com.robotics.api.FastScreenshot.java

/**
 * Take screenshots and store them a directory.
 * Directory path should NOT be a multi level path.
 * @param directory Directory to store screenshots in.
 * @param n_shots Number of screenshots to take.
 * @param n_threads Number of threads to use.
 * @param delay_us Delay before first screenshot is taken.
 * @param interval_us Delay between screenshots.
 *//*from  w ww.j  a  va2  s.c  o m*/
public static void takeScreenshots(String directory, int n_shots, int n_threads, int delay_us,
        int interval_us) {
    _takeScreenshots(StringUtils.stripEnd(StringUtils.stripStart(directory, "/"), "/"), n_shots,
            Math.min(n_threads, n_shots), delay_us, interval_us);
}

From source file:com.sangupta.codefix.RightTrim.java

protected String processEachFile(File file) throws IOException {
    final List<String> lines = new ArrayList<String>();
    LineIterator iterator = FileUtils.lineIterator(file);
    boolean modified = false;
    while (iterator.hasNext()) {
        String line = iterator.next();

        String newline = StringUtils.stripEnd(line, null);
        if (line.length() != newline.length()) {
            modified = true;/* w w  w  . ja  va2s  . c  o  m*/
        }

        lines.add(newline);
    }

    FileUtils.writeLines(file, lines);
    return String.valueOf(modified);
}

From source file:com.flysystem.core.adapter.AbstractAdapter.java

public void setPathPrefix(String prefix) {
    boolean isEmpty = Strings.isNullOrEmpty(prefix);
    if (!isEmpty) {
        prefix = StringUtils.stripEnd(prefix, File.separator) + File.separator;
    }/* w ww . j av a  2  s. co m*/
    this.pathPrefix = isEmpty ? null : prefix;
}

From source file:com.adobe.acs.commons.util.datadefinitions.impl.LowercaseWithDashesDefinitionBuilderImpl.java

@Override
public final ResourceDefinition convert(final String data) {
    final String title = data;

    String name = data;/*www .ja v  a  2 s  .co m*/
    name = StringUtils.stripToEmpty(name);
    name = StringUtils.lowerCase(name);
    name = StringUtils.replace(name, "&", " and ");
    name = StringUtils.replace(name, "/", " or ");
    name = StringUtils.replace(name, "%", " percent ");
    name = name.replaceAll("[^a-z0-9-]+", "-");
    name = StringUtils.stripEnd(name, "-");
    name = StringUtils.stripStart(name, "-");

    final BasicResourceDefinition dataDefinition = new BasicResourceDefinition(name);

    dataDefinition.setTitle(title);

    return dataDefinition;
}

From source file:com.nridge.connector.fs.con_fs.core.Constants.java

public static int getCfgSleepValue(AppMgr anAppMgr, String aCfgName, int aDefaultValue) {
    int sleepInSeconds = aDefaultValue;

    String timeString = anAppMgr.getString(aCfgName);
    if (StringUtils.isNotEmpty(timeString)) {
        if (StringUtils.endsWithIgnoreCase(timeString, "m")) {
            String minuteString = StringUtils.stripEnd(timeString, "m");
            if ((StringUtils.isNotEmpty(minuteString)) && (StringUtils.isNumeric(minuteString))) {
                int minuteAmount = Integer.parseInt(minuteString);
                sleepInSeconds = minuteAmount * 60;
            }//from   ww  w.  j a v a2  s.c om
        } else if (StringUtils.endsWithIgnoreCase(timeString, "h")) {
            String hourString = StringUtils.stripEnd(timeString, "h");
            if ((StringUtils.isNotEmpty(hourString)) && (StringUtils.isNumeric(hourString))) {
                int hourAmount = Integer.parseInt(hourString);
                sleepInSeconds = hourAmount * 60 * 60;
            }
        } else if (StringUtils.endsWithIgnoreCase(timeString, "d")) {
            String dayString = StringUtils.stripEnd(timeString, "d");
            if ((StringUtils.isNotEmpty(dayString)) && (StringUtils.isNumeric(dayString))) {
                int dayAmount = Integer.parseInt(dayString);
                sleepInSeconds = dayAmount * 60 * 60 * 24;
            }
        } else // we assume seconds
        {
            String secondString = StringUtils.stripEnd(timeString, "s");
            if ((StringUtils.isNotEmpty(secondString)) && (StringUtils.isNumeric(secondString))) {
                sleepInSeconds = Integer.parseInt(secondString);
            }
        }
    }

    return sleepInSeconds;
}

From source file:com.technophobia.substeps.model.Arguments.java

public static Object evaluateExpression(String expressionWithDelimiters) {

    ParameterSubstitution parameterSubstituionConfig = NewSubstepsExecutionConfig
            .getParameterSubstituionConfig();

    // TODO - check that the expression doesn't contain any of the bad words
    // or and eq ne lt gt le ge div mod not null true false new var return
    // any of those words need to be qutoed or ['  ']
    // http://commons.apache.org/proper/commons-jexl/reference/syntax.html

    // try evaluating this expression against the executionContext

    // TODO check flag to see whether we can evaluate things from the ec

    if (expressionWithDelimiters != null && parameterSubstituionConfig.substituteParameters()
            && expressionWithDelimiters.startsWith(parameterSubstituionConfig.startDelimiter())) {
        String expression = StringUtils.stripStart(
                StringUtils.stripEnd(expressionWithDelimiters, parameterSubstituionConfig.endDelimiter()),
                parameterSubstituionConfig.startDelimiter());

        JexlContext context = new MapContext(ExecutionContext.flatten());

        JexlExpression e = jexl.createExpression(expression);

        return e.evaluate(context);
    } else {/* w  w w. j ava 2  s .  co m*/
        return expressionWithDelimiters;
    }
}

From source file:com.alibaba.dubbo.qos.textui.TKv.java

private String filterEmptyLine(String content) {
    final StringBuilder sb = new StringBuilder();
    Scanner scanner = null;// ww w.  j a  v a2s.co m
    try {
        scanner = new Scanner(content);
        while (scanner.hasNextLine()) {
            String line = scanner.nextLine();
            if (line != null) {
                // remove extra space at line's end
                line = StringUtils.stripEnd(line, " ");
                if (line.isEmpty()) {
                    line = " ";
                }
            }
            sb.append(line).append('\n');
        }
    } finally {
        if (null != scanner) {
            scanner.close();
        }
    }

    return sb.toString();
}

From source file:com.sangupta.clitools.file.RightTrim.java

@Override
protected boolean processFile(File file) throws IOException {
    // read entire file in memory
    List<String> contents = FileUtils.readLines(file);
    final long initial = file.length();

    // now for each string - trim from end
    for (int index = 0; index < contents.size(); index++) {
        String line = contents.get(index);
        line = StringUtils.stripEnd(line, null);
        contents.set(index, line);/*from   www  .  j  av  a2s . c om*/
    }

    // write back contents of file
    FileUtils.writeLines(file, contents);
    long current = file.length();

    this.bytesSaved.addAndGet(initial - current);
    System.out.println("File " + file.getAbsoluteFile().getAbsolutePath() + " right-trimmed and saved "
            + (initial - current) + " bytes.");
    return true;
}