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.grible.excel.ExcelFile.java

private String getStringCellValue(Cell cell) {
    if (cell == null) {
        return "";
    }//from ww w  .j a v a2s .  c o m
    if (cell.getCellType() == Cell.CELL_TYPE_NUMERIC) {
        String result = String.valueOf(cell.getNumericCellValue());
        if (result.endsWith(".0")) {
            result = StringUtils.substringBeforeLast(result, ".0");
        }
        return result;
    }
    if (cell.getCellType() == Cell.CELL_TYPE_BOOLEAN) {
        return String.valueOf(cell.getBooleanCellValue());
    }
    if (cell.getCellType() == Cell.CELL_TYPE_FORMULA) {
        return cell.getCellFormula();
    }
    return cell.getStringCellValue();
}

From source file:org.igov.service.business.action.task.core.ActionTaskService.java

private String addCalculatedFields(String saFieldsCalc, TaskInfo curTask, String currentRow) {
    HistoricTaskInstance details = oHistoryService.createHistoricTaskInstanceQuery().includeProcessVariables()
            .taskId(curTask.getId()).singleResult();
    LOG.info("Process variables of the task {}:{}: {}", curTask.getId(), saFieldsCalc,
            details.getProcessVariables());
    if (details != null && details.getProcessVariables() != null) {
        Set<String> headersExtra = new HashSet<>();
        for (String key : details.getProcessVariables().keySet()) {
            if (!key.startsWith("sBody")) {
                headersExtra.add(key);//w  w  w.  ja  va2s  . c o m
            }
        }
        saFieldsCalc = StringUtils.substringAfter(saFieldsCalc, "\"");
        saFieldsCalc = StringUtils.substringBeforeLast(saFieldsCalc, "\"");
        for (String expression : saFieldsCalc.split(";")) {
            LOG.info("Processing expression: {}", expression);
            String variableName = StringUtils.substringBefore(expression, "=");
            String condition = StringUtils.substringAfter(expression, "=");
            LOG.info("Checking variable with (name={}, condition={}, expression={}) ", variableName, condition,
                    expression);
            try {
                Object conditionResult = getObjectResultofCondition(headersExtra, details, details, condition);
                currentRow = currentRow + ";" + conditionResult;
                LOG.info("Adding calculated field {} with the value {}", variableName, conditionResult);
            } catch (Exception oException) {
                LOG.error("Error: {}, occured while processing (variable={}) ", oException.getMessage(),
                        variableName);
                LOG.debug("FAIL:", oException);
            }
        }
    }
    return currentRow;
}

From source file:org.igov.service.business.action.task.core.ActionTaskService.java

public String formHeader(String saFields, List<HistoricTaskInstance> foundHistoricResults,
        String saFieldsCalc) {/*from w  w  w .  j a  v  a2s  . c  o m*/
    String res = null;
    if (saFields != null && !"".equals(saFields.trim())) {
        LOG.info("Fields have custom header names");
        StringBuilder sb = new StringBuilder();
        String[] fields = saFields.split(";");
        LOG.info("fields: " + fields);
        for (int i = 0; i < fields.length; i++) {
            if (fields[i].contains("\\=")) {
                sb.append(StringUtils.substringBefore(fields[i], "\\="));
                LOG.info("if (fields[i].contains(\"\\\\=\"))_sb: " + sb);
            } else {
                sb.append(fields[i]);
                LOG.info("else_sb: " + sb);
            }
            if (i < fields.length - 1) {
                sb.append(";");
                LOG.info("(i < fields.length - 1)_sb: " + sb);
            }
        }
        res = sb.toString();
        res = res.replaceAll("\\$\\{", "");
        res = res.replaceAll("\\}", "");
        LOG.info("Formed header from list of fields: {}", res);
    } else {
        if (foundHistoricResults != null && !foundHistoricResults.isEmpty()) {
            HistoricTaskInstance historicTask = foundHistoricResults.get(0);
            Set<String> keys = historicTask.getProcessVariables().keySet();
            StringBuilder sb = new StringBuilder();
            Iterator<String> iter = keys.iterator();
            while (iter.hasNext()) {
                sb.append(iter.next());
                if (iter.hasNext()) {
                    sb.append(";");
                }
            }
            res = sb.toString();
            LOG.info("res: " + res);
        }
        LOG.info("Formed header from all the fields of a task: {}", res);
    }
    if (saFieldsCalc != null) {
        saFieldsCalc = StringUtils.substringAfter(saFieldsCalc, "\"");
        saFieldsCalc = StringUtils.substringBeforeLast(saFieldsCalc, "\"");
        String[] params = saFieldsCalc.split(";");
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < params.length; i++) {
            String currParam = params[i];
            String cutHeader = StringUtils.substringBefore(currParam, "=");
            LOG.info("Adding header to the csv file from saFieldsCalc: {}", cutHeader);
            sb.append(cutHeader);
            if (i < params.length - 1) {
                sb.append(";");
            }
        }
        res = res + ";" + sb.toString();
        LOG.info("Header with calculated fields: {}", res);
    }
    return res;
}

From source file:org.jadira.scanner.core.helper.filenamefilter.AntPathFilter.java

private boolean doMatch(String pattern, String path, boolean fullMatch) {

    final boolean retVal;

    Pattern regex = convertAntPatternToRegex(pattern);
    Matcher matcher = regex.matcher(path);
    matcher.find();/*from   w ww  . jav  a 2 s.  co  m*/

    if (fullMatch) {
        if ((matcher.start() == 0) && (matcher.end() == path.length())) {
            retVal = true;
        } else {
            retVal = false;
        }

    } else {
        if (doMatch(pattern, path, true)) {
            retVal = true;
        } else {
            String nextPattern = StringUtils.substringBeforeLast(pattern, PATH_SEPARATOR);
            if (pattern.equals(nextPattern)) {
                return false;
            } else {
                return doMatch(nextPattern, path, false);
            }
        }
    }
    return retVal;
}

From source file:org.kawanfw.commons.server.util.FileJoiner.java

/**
 * Get the original file name from the file chunkc name
 * @param filePart   the file part name//  w  w  w  .  j  a  v a2s  .  c o  m
 * @return   the file name with path 
 */
public String getFilePathFromPart(String filePart) {

    // Remove generic ext
    String filePath = StringUtils.substringBeforeLast(filePart, ".kawanfw.chunk");
    // Remove file number .1 or .2, etc.
    filePath = StringUtils.substringBeforeLast(filePath, ".");
    return filePath;
}

From source file:org.kawanfw.file.api.client.RemoteFile.java

/**
 * Constructor/*from ww  w  .  j  a  v a  2s . c o m*/
 * 
 * @param remoteSession
 *            the remote session
 * @param pathname
 *            the pathname on host with "/" as file separator. Must be
 *            absolute.
 * 
 * @throws InvalidLoginException
 *             if sessions is closed
 */
public RemoteFile(RemoteSession remoteSession, String pathname) throws InvalidLoginException {

    if (remoteSession == null) {
        throw new IllegalArgumentException("remoteSession is null!");
    }

    if (remoteSession.getUsername() == null || remoteSession.getAuthenticationToken() == null) {
        throw new InvalidLoginException(RemoteSession.REMOTE_SESSION_IS_CLOSED);
    }

    if (pathname == null) {
        throw new IllegalArgumentException("pathname is null!");
    }

    if (!pathname.startsWith("/")) {
        throw new IllegalArgumentException("pathname must be asbsolute and start with \"/\"");
    }

    // Remove last unecessary /
    if (pathname.length() > 1 && pathname.endsWith("/")) {
        pathname = StringUtils.substringBeforeLast(pathname, "/");
    }

    debug("pathname: " + pathname);
    this.remoteSession = remoteSession;
    this.pathname = pathname;
    this.remoteFileExecutor = new RemoteFileListExecutor(this);
}

From source file:org.kawanfw.file.reflection.ClassFileLocatorNew.java

/**
 * Returns the pathname with "/" file separator notation corresponding to the package organization.
 * <br>//from w  w w.  jav a 2s.  co  m
 * Example : for class org.kawanfw.file.reflection.ClassFileLocator, will
 * return /org/kawanfw/file/reflection/ 
 * @return the pathname corresponding to the package organization
 */
public static String getClassSubdirectories(String className) {

    if (className == null) {
        throw new IllegalArgumentException("className is null!");
    }

    String directoryPath = className;
    if (!directoryPath.contains(".")) {
        return ""; // No subdirectories. it's a default package class
    }

    directoryPath = StringUtils.substringBeforeLast(directoryPath, ".");
    directoryPath = directoryPath.replace('.', '/');
    directoryPath = "/" + directoryPath + "/";
    return directoryPath;
}

From source file:org.kawanfw.file.servlet.ServerCallAction.java

/**
 * //from   ww w . j a v  a  2s .  c  o  m
 * Calls a remote method from the client side <br>
 * Please note that all invocation are trapped and routed as code string to
 * the client side.
 * 
 * @param request
 *            the http request
 * @param commonsConfigurator
 *            the commons configurator defined by the user
 * @param fileConfigurator
 *            the file configurator defined by the user
 * @param out
 *            the servlet output stream
 * @param username
 *            the client login (for security check)
 * 
 * 
 * @throws IOException
 *             all framework, network, etc. errors
 * @throws ClassNotFoundException
 * @throws IllegalAccessException
 * @throws InstantiationException
 * @throws NoSuchMethodException
 * @throws InvocationTargetException
 * @throws IllegalArgumentException
 */
public void call(HttpServletRequest request, CommonsConfigurator commonsConfigurator,
        FileConfigurator fileConfigurator, OutputStream out, String username) throws SQLException, IOException,
        ClassNotFoundException, InstantiationException, IllegalAccessException, NoSuchMethodException,
        IllegalArgumentException, InvocationTargetException, Exception {

    Connection connection = null;

    try {

        debug("in actionCall");

        // The method name
        String methodName = request.getParameter(Parameter.METHOD_NAME);

        // The parms name
        String paramsTypes = request.getParameter(Parameter.PARAMS_TYPES);
        String paramsValues = request.getParameter(Parameter.PARAMS_VALUES);

        // Make sure all values are not null and trimed

        methodName = StringUtil.getTrimValue(methodName);
        paramsTypes = StringUtil.getTrimValue(paramsTypes);
        paramsValues = StringUtil.getTrimValue(paramsValues);

        if (request instanceof HttpServletRequestConvertor) {
            debug("request instanceof HttpServletRequestConvertor");
        } else {
            debug("request NOT instanceof HttpServletRequestConvertor");
        }

        debug("methodName: " + methodName);
        debug("username  : " + username);

        String className = StringUtils.substringBeforeLast(methodName, ".");
        Class<?> c = Class.forName(className);
        CallUtil callUtil = new CallUtil(c, fileConfigurator);
        boolean callAllowed = callUtil.isCallable();

        if (!callAllowed) {
            throw new SecurityException(
                    Tag.PRODUCT_SECURITY + " Class is forbiden for remote call: " + className);
        }

        String action = request.getParameter(Parameter.ACTION);

        // Legacy Action.CALL_ACTION call with Base64 conversion
        // Corresponds to RemoteSession.setUseBase64EncodingForCall()
        // setting
        // on client side
        if (action.equals(Action.CALL_ACTION)) {
            paramsTypes = StringUtil.fromBase64(paramsTypes);
            paramsValues = StringUtil.fromBase64(paramsValues);
        }

        debug("paramsTypes     : " + paramsTypes);
        debug("paramsValues    : " + paramsValues);

        List<String> listParamsTypes = ListOfStringTransport.fromJson(paramsTypes);
        List<String> listParamsValues = ListOfStringTransport.fromJson(paramsValues);

        debug("actionInvokeRemoteMethod:listParamsTypes      : " + listParamsTypes);
        debug("actionInvokeRemoteMethod:listParamsValues     : " + listParamsValues);

        Class<?>[] argTypes = new Class[listParamsTypes.size()];
        Object[] values = new Object[listParamsValues.size()];

        List<Object> valuesList = new Vector<Object>();
        for (int i = 0; i < listParamsTypes.size(); i++) {

            String value = listParamsValues.get(i);
            String javaType = listParamsTypes.get(i);

            JavaValueBuilder javaValueBuilder = new JavaValueBuilder(javaType, value);
            argTypes[i] = javaValueBuilder.getClassOfValue();
            values[i] = javaValueBuilder.getValue();

            // Special treatement if argTypes[i] is a Connection
            if (argTypes[i] == Connection.class) {
                connection = commonsConfigurator.getConnection();
                values[i] = connection;
            }

            valuesList.add(values[i]);
        }

        // Try to get A connection. Will be null if user has not configured a Connection
        try {
            if (connection == null) {
                connection = commonsConfigurator.getConnection();
            }

        } catch (Exception e) {
            debug("commonsConfigurator.getConnection() exception: " + e.toString());
            if (connection != null)
                connection.close();
            connection = null;
        }

        boolean isAllowed = fileConfigurator.allowCallAfterAnalysis(username, connection, methodName,
                valuesList);

        if (!isAllowed) {

            String ipAddress = request.getRemoteAddr();

            // Run the runIfCallDisallowed() configured by the user
            fileConfigurator.runIfCallRefused(username, connection, ipAddress, methodName, valuesList);

            throw new SecurityException(
                    Tag.PRODUCT_SECURITY + " Method not authorized for execution by Security Checker: "
                            + methodName + " parameters: " + valuesList.toString());
        }

        String rawMethodName = StringUtils.substringAfterLast(methodName, ".");

        // Invoke the method
        Object resultObj = null;

        debug("Before  Object theObject = c.newInstance()");
        Object theObject = c.newInstance();

        debug("Before  c.getDeclaredMethod(rawMethodName, argTypes)");
        Method main = c.getDeclaredMethod(rawMethodName, argTypes);

        debug("Before  main.invoke(theObject, values)");
        resultObj = main.invoke(theObject, values);

        String result = null;
        if (resultObj != null)
            result = resultObj.toString();

        debug("result before conversion: " + result);

        if (result != null) {

            // Legacy Action.CALL_ACTION call with Base64 conversion
            // Corresponds to RemoteSession.setUseBase64EncodingForCall()
            // setting on client side
            if (action.equals(Action.CALL_ACTION)) {
                result = StringUtil.toBase64(result);
            } else if (action.equals(Action.CALL_ACTION_HTML_ENCODED)) {
                result = HtmlConverter.toHtml(result);
            } else {
                throw new IllegalArgumentException("call action is invalid: " + action);
            }
        }

        debug("actionInvokeRemoteMethod:result: " + result);

        writeLine(out, TransferStatus.SEND_OK);
        writeLine(out, result);
    } finally {
        if (connection != null) {
            connection.close();
        }
    }
}

From source file:org.kawanfw.file.servlet.ServerFileDispatch.java

/**
 * //  www .j  a  v a 2  s . c o  m
 * Execute the dispatched request
 * 
 * @param request
 *            the http request
 * @param response
 *            the http response
 * @param servletContextTempDir
 *            The temp dir used by Servlets
 * @param commonsConfigurator
 *            the client commons configurator
 * @param fileConfigurator
 *            the client configurator for files
 * @throws IOException
 *             if any Servlet Exception occurs
 */
public void executeRequest(HttpServletRequest request, HttpServletResponse response, File servletContextTempDir,
        CommonsConfigurator commonsConfigurator, FileConfigurator fileConfigurator) throws IOException {
    OutputStream out = null;

    try {

        // Immediate catch if we are asking a file upload, because
        // parameters are
        // in unknown sequence. We know it's a upload action if it's mime
        // multipart
        if (ServletFileUpload.isMultipartContent(request)) {
            ServerFileUploadAction serverFileUploadAction = new ServerFileUploadAction();
            serverFileUploadAction.executeAction(request, response, servletContextTempDir, commonsConfigurator,
                    fileConfigurator);
            return;
        }

        debug("ServerFileDispatch begin 2");

        // The action & filename (for file size ask)
        String action = null;

        // We must trap the IllegalArgumentException to rethrow properly to
        // client
        // This happens if there is an encryption problem
        try {
            action = request.getParameter(Parameter.ACTION);
        } catch (IllegalArgumentException e) {
            out = response.getOutputStream();
            throw e;
        }

        action = StringUtil.getTrimValue(action);

        debug("ACTION : " + action);

        // Special action for Login, because Token does not exists and must
        // be built
        if (action.equals(Action.LOGIN_ACTION) || action.equals(Action.BEFORE_LOGIN_ACTION)) {

            ServerLoginAction serverLoginAction = new ServerLoginAction();
            serverLoginAction.executeAction(request, response, commonsConfigurator, action);
            return;
        }

        out = response.getOutputStream();

        // Only if there is a call action, we may execute authorized classes
        // without authentication/login
        if (action.equals(Action.CALL_ACTION) || action.equals(Action.CALL_ACTION_HTML_ENCODED)) {
            // The class name
            String methodName = request.getParameter(Parameter.METHOD_NAME);
            methodName = StringUtil.getTrimValue(methodName);

            String className = StringUtils.substringBeforeLast(methodName, ".");
            Class<?> c = Class.forName(className);
            CallUtil callUtil = new CallUtil(c, fileConfigurator);
            boolean callAllowed = callUtil.isCallableNotAuthenticated();

            if (callAllowed) {
                if (action.equals(Action.CALL_ACTION) || action.equals(Action.CALL_ACTION_HTML_ENCODED)) {

                    ServerCallAction serverCallAction = new ServerCallAction();
                    serverCallAction.call(request, commonsConfigurator, fileConfigurator, out, null);
                }

                return;
            }
        }

        // For all other actions, we check the parameters

        // The username (used for token re-compilation)
        String username = request.getParameter(Parameter.USERNAME);
        username = StringUtil.getTrimValue(username);

        debug("username : " + username);

        // // For old call():
        // try {
        // username = StringUtil.fromBase64(username);
        // } catch (Exception e) {
        // } // The login may be in clear

        // Authentication Token with SHA-1(login + secret value)
        String token = request.getParameter(Parameter.TOKEN);
        token = StringUtil.getTrimValue(token);

        if (!ServerFileDispatch.isTokenValid(username, token, commonsConfigurator)) {
            debug("invalid token!");
            debug("username: " + username);
            debug("token   : " + token);

            writeLine(out, TransferStatus.SEND_OK);
            writeLine(out, ReturnCode.INVALID_LOGIN_OR_PASSWORD);

            return;
        }

        // Notify to Kawan in async mode using a secured Thread that
        // the user has successfully logged (done once in JVM session per
        // username).
        // No notification is done if user.home/.kawansoft/no_notify.txt
        // exists
        // or web server name is localhost or 127.0.0.1
        if (!KawanNotifier.existsNoNotifyTxt() && !KawanNotifier.usernameAlreadyLogged(username)
                && !KawanNotifier.serverNameIsLocalhost()) {
            KawanNotifier kawanNotifier = new KawanNotifier(username, "AwakeFile_" + FileVersionValues.VERSION);
            kawanNotifier.start();
        }

        // Ok, install our security manager
        //installSecurityManager(fileConfigurator);

        // Displays class path
        if (DEBUG)
            ClassPathUtil.displayClasspath();

        // The filename
        String filename = request.getParameter(Parameter.FILENAME);
        filename = StringUtil.getTrimValue(filename);

        // Call to a File method that returns one result (no list return)
        if (action.equals(Action.FILE_METHOD_ONE_RETURN_ACTION)) {
            FileMethodOneReturnAction fileMethodOneReturnAction = new FileMethodOneReturnAction();
            fileMethodOneReturnAction.call(request, commonsConfigurator, fileConfigurator, out, username,
                    filename);

            return;
        }
        // Call to a File.list() or File.list(FilenameFilter)
        else if (action.equals(Action.FILE_LIST_ACTION)) {

            FileListAction fileListAction = new FileListAction();
            fileListAction.list(request, commonsConfigurator, fileConfigurator, out, username, filename);
            return;
        }
        // Call to a File.listFiles() or File.listFiles(FileFilter)
        // or File.listFiles(FilenameFilter)
        else if (action.equals(Action.FILE_LIST_FILES_ACTION)) {

            FileListFilesAction fileListFilesAction = new FileListFilesAction();
            fileListFilesAction.listFiles(request, commonsConfigurator, fileConfigurator, out, username,
                    filename);
            return;
        } else if (action.equals(Action.CALL_ACTION) || action.equals(Action.CALL_ACTION_HTML_ENCODED)) {
            ServerCallAction serverCallAction = new ServerCallAction();
            serverCallAction.call(request, commonsConfigurator, fileConfigurator, out, username);
            return;
        } else if (action.equals(Action.GET_FILE_LENGTH_ACTION)) {
            long result = actionGetListFileLength(fileConfigurator, username, filename);

            writeLine(out, TransferStatus.SEND_OK);
            writeLine(out, Long.toString(result));
        } else if (action.equals(Action.GET_JAVA_VERSION)) {
            String javaVersion = System.getProperty("java.version");
            writeLine(out, TransferStatus.SEND_OK);
            writeLine(out, javaVersion);
        } else if (action.equals(Action.DOWNLOAD_FILE_ACTION)) {

            String chunkLengtgStr = request.getParameter(Parameter.CHUNKLENGTH);
            long chunkLength = Long.parseLong(chunkLengtgStr);

            boolean result = new FileTransferManager().download(out, fileConfigurator, username, filename,
                    chunkLength);

            if (!result) {
                // Impossible to find the file on server
                writeLine(out, TransferStatus.SEND_OK);
                writeLine(out, Tag.FileNotFoundException);
                // throw new FileNotFoundException(
                // "File not found on remote server: " + filename);
            }
        } else {
            throw new IllegalArgumentException("Invalid Client Action: " + action);
        }

        return;
    } catch (Throwable throwable) {

        if (DEBUG)
            throwable.printStackTrace(System.out);

        Throwable finalThrowable = getFinalThrowable(throwable);

        writeLine(out, TransferStatus.SEND_FAILED);
        writeLine(out, finalThrowable.getClass().getName()); // Exception class name
        writeLine(out, ServerUserThrowable.getMessage(finalThrowable)); // Exception
        // message
        writeLine(out, ExceptionUtils.getStackTrace(finalThrowable)); // stack trace

        try {
            ServerLogger.getLogger().log(Level.WARNING,
                    Tag.PRODUCT_EXCEPTION_RAISED + " " + ServerUserThrowable.getMessage(finalThrowable));
            ServerLogger.getLogger().log(Level.WARNING,
                    Tag.PRODUCT_EXCEPTION_RAISED + " " + ExceptionUtils.getStackTrace(finalThrowable));
        } catch (Exception e1) {
            e1.printStackTrace();
            e1.printStackTrace(System.out);
        }

    }
}

From source file:org.kawanfw.file.servlet.ServerUserThrowable.java

/**
 * Return the class where the Exception has been thrown
 * //from ww  w.j  a v  a2  s .c  o  m
 * @param throwable
 *            the exception thrown
 * @return the class that throws the Exception
 */
private static Class<?> extractThrowingClassFromThrowable(Throwable throwable) {

    try {
        String statckTrace = ExceptionUtils.getStackTrace(throwable);
        String className = StringUtils.substringAfter(statckTrace, "at ");
        className = StringUtils.substringBefore(className, "(");
        className = StringUtils.substringBeforeLast(className, ".");

        debug("className: " + ":" + className + ":");

        Class<?> theClass = Class.forName(className);
        return theClass;
    } catch (ClassNotFoundException e1) {
        e1.printStackTrace(System.out);
        return null;
    }

}