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

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

Introduction

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

Prototype

public static String mid(final String str, int pos, final int len) 

Source Link

Document

Gets len characters from the middle of a String.

If len characters are not available, the remainder of the String will be returned without an exception.

Usage

From source file:com.ibm.dbwkl.request.internal.LoggingHandler.java

@Override
public STAFResult execute() {
    StringBuilder resultString = new StringBuilder();

    // user for db logger
    String logdbuser = getRequestOption(Options.DB_USER);

    // password for db logger
    String logdbpassword = getRequestOption(Options.DB_PASSWORD);

    // URL for db logger
    String logdburl = getRequestOption(Options.DB_URL);

    if (hasRequestOption(Options.LOG_LOGTEST)) {
        for (int i = 0; i <= 25; i++) {
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                //ignore
            }/*from  ww  w .j ava2s  .  co  m*/
            Logger.log("LOGTEST:" + i, LogLevel.Debug);
        }
        return new STAFResult(STAFResult.Ok, "Logtest at Loglevel Debug executed!");
    }

    /*
     * everything went fine, thus do the changes and hope that all values are allowed
     */

    // level
    if (hasRequestOption(Options.LOG_LEVEL)) {
        String level = getRequestOption(Options.LOG_LEVEL);
        try {
            Logger.logLevel = LogLevel.getLevel(level);
            resultString.append("Log Level set to " + level + "\n");
        } catch (Exception e) {
            return new STAFResult(STAFResult.InvalidValue, "The value '" + level
                    + "' is not allowed as log level. Use one of the following instead: Debug Info Warning Error");
        }
    }

    // details
    if (hasRequestOption(Options.LOG_DETAILS)) {
        String details = getRequestOption(Options.LOG_DETAILS);
        try {
            Logger.details = new Boolean(details).booleanValue();
            resultString.append("Log Details now " + (Logger.details == true ? "ON" : "OFF") + "\n");
        } catch (Exception e) {
            return new STAFResult(STAFResult.InvalidValue, "The value '" + details
                    + "' is not allowed as detailed logging settings. Use either true or false as value.");
        }
    }

    // Cleaning the logger
    if (hasRequestOption(Options.LOG_CLEAN)) {
        String clean = getRequestOption(Options.LOG_CLEAN).trim();

        try {
            ILoggerService logger = getLoggerByName(clean);
            if (logger == null)
                return new STAFResult(STAFResult.DoesNotExist, "Logger could not be found!");

            logger.term();
            logger.clean();
            Logger.registeredLoggers.remove(logger);

            logger = logger.getClass().newInstance();
            Logger.addLogger(logger);

            resultString.append("Logger " + clean + " has been cleaned!");

        } catch (Exception e) {
            return new STAFResult(STAFResult.InvalidValue, "The logger '" + clean
                    + "' is unknown. Use one of the following: htmllogger filelogger dblogger sysout livelog livelogreceiver");
        }
    }

    // remove logger
    else if (hasRequestOption(Options.LOG_REMOVE)) {
        String remove = getRequestOption(Options.LOG_REMOVE).trim();

        try {
            if (remove.equalsIgnoreCase("LIVELOG")) {
                LiveLogger.getInstance().term();
                Logger.registeredLoggers.remove(LiveLogger.getInstance());
                resultString.append("Logger " + remove + " has been removed \n");
            } else {
                ILoggerService logger = getLoggerByName(remove);

                if (logger == null)
                    return new STAFResult(STAFResult.DoesNotExist, "Logger could not be found!");

                logger.term();
                Logger.registeredLoggers.remove(logger);

                resultString.append("Logger has been removed!");
            }

        } catch (Exception e) {
            return new STAFResult(STAFResult.InvalidValue,
                    "The logger '" + remove + "' to be removed is unknown.");
        }
    }

    // add logger
    else if (hasRequestOption(Options.LOG_ADD)) {
        String add = getRequestOption(Options.LOG_ADD);

        if (add.equalsIgnoreCase("FILELOGGER"))
            try {
                Logger.addLogger(new TextLogger());
            } catch (IOException e1) {
                return new STAFResult(STAFResult.JavaError, "Exception occurs while adding a FileLogger.");
            }
        else if (add.equalsIgnoreCase("DBLOGGER")) {
            try {
                Logger.addLogger(new DatabaseLogger(logdbuser, logdbpassword, logdburl));
            } catch (IOException e) {
                return new STAFResult(STAFResult.JavaError,
                        "Exception occurs while adding a DBLogger: " + e.getMessage());
            } catch (InterruptedException e) {
                //
            }
        }

        else if (add.equalsIgnoreCase("HTMLLOGGER"))
            try {
                Logger.addLogger(new HTMLLogger());
            } catch (IOException e) {
                return new STAFResult(STAFResult.JavaError, "Exception occurs while adding a HTMLLogger.");
            }
        else if (add.equalsIgnoreCase("LIVELOG")) {
            if (hasRequestOption(Options.SOCKET_HOST)) {
                if (getRequestOption(Options.SOCKET_HOST).length() != 0) {
                    LiveLogger liveLogger = LiveLogger.getInstance();
                    if (!Logger.getCopyOfLoggers().contains(liveLogger))
                        Logger.addLogger(liveLogger);
                    liveLogger.openServer(getRequestOption(Options.SOCKET_HOST).trim());
                    return new STAFResult(STAFResult.Ok,
                            "LiveLogger added, it will now accept a live logging connection!");
                }
            }
            Logger.log("Adding LiveLog not possible: Invalid Host", LogLevel.Error);
            return new STAFResult(STAFResult.JavaError, "Adding LiveLog not possible: Invalid Host");
        }

        else {
            Logger.log("Adding Logger failed: no such logger to add found: " + add, LogLevel.Error);
            return new STAFResult(STAFResult.JavaError,
                    "Adding Logger failed: no such logger to add found: " + add);
        }
        resultString.append("Logger " + add + " has been added \n");
    }

    else if (hasRequestOption(Options.LOG_SCHEMA)) {
        String xsd = null;
        try {
            xsd = XMLSerializer.createXMLSchema(LoggerEntry.class);
        } catch (IOException e) {
            Logger.log(e.getMessage(), LogLevel.Error);
            return new STAFResult(STAFResult.JavaError, e.getMessage());
        } catch (JAXBException e) {
            Logger.log(e.getMessage(), LogLevel.Error);
            return new STAFResult(STAFResult.JavaError, e.getMessage());
        }

        if (xsd != null)
            return new STAFResult(STAFResult.Ok, xsd);

        return new STAFResult(STAFResult.JavaError, "Error while creating the Schema");
    }

    // LIST shows logs on the console
    // schema:
    //      LIST <what> [FILTER <filter>] [COLUMNS <columns>]
    //          <what> = { , n} (empty=all, n=last n)
    //          <filter> = {LEVEL={DEBUG, INFO, WARNING, ERROR}*;REQID=<reqid>}
    //          <columns> = {REQUEST, THREAD, LOGLEVEL, MESSAGE}
    else if (hasRequestOption(Options.LOG_LIST)) {
        //read <what>
        String listValue = getRequestOption(Options.LOG_LIST);
        //the number of latest entries to retrieve
        int n = 0;
        if (listValue.equalsIgnoreCase("")) {
            //when n<=0, all entries are retrieved
            n = 0;
        } else {
            try {
                n = Integer.parseInt(listValue);
            } catch (NumberFormatException e) {
                return new STAFResult(STAFResult.InvalidValue,
                        "List option needs to be a positive number or empty");
            }
            if (n <= 0) {
                return new STAFResult(STAFResult.InvalidValue,
                        "List option needs to be a positive number or empty");
            }
        }

        //read <filter>
        String levels[] = null;
        int reqid = 0;
        if (hasRequestOption(Options.LOG_LIST_FILTER)) {
            String filter = getRequestOption(Options.LOG_LIST_FILTER).toLowerCase();
            StringTokenizer tokenizer = new StringTokenizer(filter, ";");
            while (tokenizer.hasMoreElements()) {
                String option = (String) tokenizer.nextElement();
                // an option is of the form key=value
                if (option.contains("=")) {
                    String key = option.substring(0, option.indexOf("="));
                    //read LEVEL={DEBUG,INFO,WARNING,ERROR}*
                    if (key.equalsIgnoreCase("level")) {
                        levels = option.substring(option.indexOf("=") + 1).split(",");
                        //Check if the given levels are supported.
                        if (!StringUtility.arrayContainsOnlyIgnoreCase(levels, LogLevel.Debug.toString().trim(),
                                LogLevel.Warning.toString().trim(), LogLevel.Error.toString().trim(),
                                LogLevel.Info.toString().trim())) {
                            return new STAFResult(STAFResult.InvalidValue,
                                    "Supporting only Log Levels: " + LogLevel.Debug.toString().trim() + ","
                                            + LogLevel.Warning.toString().trim() + ","
                                            + LogLevel.Error.toString().trim() + ","
                                            + LogLevel.Info.toString().trim());
                        }
                        //read REQID=<reqid>      
                    } else if (key.equals("reqid")) {
                        try {
                            reqid = Integer.parseInt(option.substring(option.indexOf("=") + 1));
                        } catch (NumberFormatException e) {
                            return new STAFResult(STAFResult.InvalidValue,
                                    "REQID needs to be a positive number.");
                        }
                        if (reqid <= 0) {
                            return new STAFResult(STAFResult.InvalidValue,
                                    "REQID needs to be a positive number.");
                        }
                    } else {
                        //option is not level= or reqid=
                        return new STAFResult(STAFResult.InvalidValue,
                                "Invalid option in the filter: " + option);
                    }
                } else {
                    //option doesn't have '='
                    return new STAFResult(STAFResult.InvalidValue,
                            "Invalid requestOptions in the filter: " + option);
                }
            }
        }

        //read <columns>
        String[] cols = null;
        if (hasRequestOption(Options.LOG_LIST_COL)) {
            cols = getRequestOption(Options.LOG_LIST_COL).toLowerCase().split(",");
            if (!StringUtility.arrayContainsOnlyIgnoreCase(cols, "request", "thread", "level", "message"))
                return new STAFResult(STAFResult.InvalidValue,
                        "Supporting only Columns: Request, Thread, Level, Message.");
        }

        // filter the entries accordingly
        List<LoggerEntry> logEntries = null;

        if (levels == null || levels.length == 0) {
            if (reqid == 0) {
                logEntries = Logger.getLogEntries(n);
            } else {
                logEntries = Logger.getLogEntries(n, reqid);
            }
        } else {
            if (reqid == 0) {
                logEntries = Logger.getLogEntries(n, levels);
            } else {
                logEntries = Logger.getLogEntries(n, levels, reqid);
            }
        }

        // print the lines, with selected columns.
        String ALLCOLUMNS[] = { "Request", "Thread", "Level", "Message" };
        String formats[] = { "%1$-8s", " %2$-12s", " %3$-7s", " %4$-100s" };

        //if no columns is set, display all columns
        if (cols == null || cols.length == 0) {
            cols = ALLCOLUMNS;
        }

        //check is one of the four columns exists, and construct the format string.
        boolean[] colExists = new boolean[ALLCOLUMNS.length];
        String format = "";

        for (int i = 0; i < ALLCOLUMNS.length; i++) {
            if (StringUtility.arrayContainsIgnoreCase(cols, ALLCOLUMNS[i])) {
                colExists[i] = true;
                format += formats[i];
            }
        }
        format += "\n";

        //print the table head
        resultString.append(String.format(format, colExists[0] ? "Request" : "", colExists[1] ? "Thread" : "",
                colExists[2] ? "Level" : "", colExists[3] ? "Message" : ""));

        resultString.append(String.format(format, colExists[0] ? "-------" : "", colExists[1] ? "------" : "",
                colExists[2] ? "-----" : "", colExists[3] ? "-------" : ""));

        //print the log entries
        for (LoggerEntry logEntry : logEntries) {

            if (colExists[3]) {
                //number of chars per row in the message column
                int charsPerRow = 100;
                //in case the message contains multiple lines.
                String msg = logEntry.getMessage();
                String[] lines = msg.split("\\n");
                for (int i = 0; i < lines.length; i++) {
                    //other columns should only appear once on the first row.
                    String formatedString = String.format(format,
                            (i == 0 && colExists[0]) ? logEntry.getRequestName() : "",
                            (i == 0 && colExists[1]) ? logEntry.getThread() : "",
                            (i == 0 && colExists[2]) ? logEntry.getLevel() : "",
                            StringUtils.left(lines[i], charsPerRow));
                    resultString.append(formatedString);

                    //if the line is longer than 'charsPerRow', split it into multiple rows
                    if (lines[i].length() > charsPerRow) {
                        //cut every 'charsPerRow' chars out, and put it in a new row.
                        String txt = "";
                        int j = 1;
                        while ((txt = StringUtils.mid(lines[i], charsPerRow * j, charsPerRow)).length() != 0) {
                            resultString.append(String.format(format, "", "", "", txt));
                            j++;
                        }
                    }
                }
            } else {
                String formatedString = String.format(format, colExists[0] ? logEntry.getRequestName() : "",
                        colExists[1] ? logEntry.getThread() : "", colExists[2] ? logEntry.getLevel() : "", "");
                resultString.append(formatedString);
            }
        }

    }

    return new STAFResult(STAFResult.Ok, resultString.toString());
}