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

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

Introduction

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

Prototype

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

Source Link

Document

Gets the substring after the last occurrence of a separator.

Usage

From source file:org.jboss.seam.social.SeamSocialExtension.java

public void processAfterDeploymentValidation(@Observes AfterDeploymentValidation adv) {
    log.info("validation phase");
    for (Annotation qual : servicesQualifiersAvailable) {
        String path = qual.annotationType().getName();
        String name = "";
        log.infof("Found service qualifier : %s", path);
        try {/*from   w  w  w  .  ja v a 2 s.com*/
            ResourceBundle bundle = ResourceBundle.getBundle(path);
            name = bundle.getString("service.name");
        } catch (MissingResourceException e) {
            log.warnf("No properties configuration file found for %s creating default service name", path);
            name = StringUtils.substringAfterLast(path, ".");
        } finally {
            servicesToQualifier.put(qual, name);
        }

    }
    for (Annotation annot : servicesQualifiersConfigured) {
        servicesNames.add(servicesToQualifier.get(annot));
    }

}

From source file:org.kawanfw.commons.api.server.DefaultCommonsConfigurator.java

/**
 * Returns the current executing servlet name extracted from the servlet path
 * @return   the current executing  servlet name extracted from the servlet path
 *//*from   w w w  .  j a va 2 s  . c  om*/
private String getServletNameFromServletPath() {
    HttpServletRequestStore httpServletRequestStore = new HttpServletRequestStore();
    HttpServletRequest httpServletRequest = httpServletRequestStore.getHttpServletRequest();

    String servletName = httpServletRequest.getServletPath();
    servletName = servletName.trim();
    servletName = StringUtils.substringAfterLast(servletName, "/");
    return servletName;
}

From source file:org.kawanfw.commons.util.FrameworkDebug.java

/**
 * Says if a class must be in debug mode
 * //ww  w.  j  ava  2  s  . c o  m
 * @param clazz
 *            the class to analyze if debug must be on
 * @return true if the class must be on debug mode, else false
 */
public static boolean isSet(Class<?> clazz) {
    load();

    String className = clazz.getName();
    String rawClassName = StringUtils.substringAfterLast(className, ".");

    if (CLASSES_TO_DEBUG.contains(className) || CLASSES_TO_DEBUG.contains(rawClassName)) {
        return true;
    } else {
        return false;
    }
}

From source file:org.kawanfw.file.api.util.client.UniqueFileCreator.java

/**
 * Create our own unique file and always the same temp file in function of (username, remote file name).
 * Must be always the same because of recovery mechanism.
 * /* w ww  .  ja va  2 s .c o m*/
 * @param username   the username of client 
 * @param remoreFile   the remote filename with full path 
 * 
 * @return the tempfile to create
 */
public static synchronized File createUnique(String username, String remoteFile) throws IOException {

    Sha1Util sha1Util = new Sha1Util();
    String hexId = null;

    try {
        hexId = sha1Util.getHexHash((username + remoteFile).getBytes());
    } catch (Exception e) {
        throw new IOException(e);
    }

    String uniqueFilename = remoteFile;

    if (uniqueFilename.contains("/")) {
        uniqueFilename = StringUtils.substringAfterLast(uniqueFilename, "/");
    }

    uniqueFilename += "-" + username + "-" + hexId;

    String tempDir = FrameworkFileUtil.getKawansoftTempDir();
    String tempFile = tempDir + File.separator + "remote-" + uniqueFilename + ".kawanfw";

    // Beware of resutling length because of OS limit length...
    tempFile = StringUtil.cut(tempFile, 255);

    return new File(tempFile);
}

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

/**
 * Get the file corresponding to our class stored in .class file
 * @return   file corresponding to our class stored in .class file
 * @throws FileNotFoundException/* w  w  w.  j  av  a 2s.  c o m*/
 * @throws IOException 
 */
public File getDotClassFile() throws FileNotFoundException, IOException {

    if (!isContainerDotClass()) {
        throw new IllegalArgumentException("class is stored in a jar file. No \".class\" file exists!");
    }

    File file = null;
    try {
        file = new File(getUrl().toURI());
    } catch (URISyntaxException e) {
        throw new IOException(e);
    }

    debug("file: " + file);

    if (file.isFile()) {
        return file;
    }

    debug("dir: " + file);

    if (!file.exists()) {
        throw new FileNotFoundException("Class file does nots exists: " + file);
    }

    // It is a directory ==> Find all classe that matches name

    // Its not a regular class but a private static inner class whose name
    // ends with $
    // Get the first one we find in the directory

    FilenameFilter filenameFilter = new FilenameFilter() {

        @Override
        public boolean accept(File dir, String name) {
            if (name.endsWith("$" + clazz.getSimpleName() + ".class"))
                return true;
            else
                return false;
        }
    };

    File[] files = file.listFiles(filenameFilter);
    if (files == null || files.length == 0) {
        throw new FileNotFoundException(
                Tag.PRODUCT + " Impossible to find the static inner class file for " + clazz.getSimpleName());
    }

    for (File file2 : files) {
        debug("file2 : " + file2);
    }

    // Easy case
    if (files.length == 1) {
        debug("OK: returning " + files[0]);
        return files[0];
    }

    if (callerClassName == null) {
        throw new FileNotFoundException(Tag.PRODUCT + " More than one inner class matching inner class name. "
                + "Impossible to find the correct static inner class file for " + clazz.getSimpleName()
                + " without the caller class name.");
    }

    // More that one class and we know the caller
    if (callerClassName.contains(".")) {
        callerClassName = StringUtils.substringAfterLast(callerClassName, ".");
    }

    for (File theFile : files) {
        String filename = theFile.getName();
        if (filename.startsWith(callerClassName)) {
            debug("OK: returning " + theFile);
            return theFile;
        }
    }

    throw new FileNotFoundException(Tag.PRODUCT
            + " More than one inner class matching inner class name. Impossible to find the correct static inner class file for "
            + clazz.getSimpleName());

}

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

private byte[] loadClassData(String className) throws IOException, ClassNotFoundException {

    DataInputStream dis = null;/*from  w  w w . j a v a 2 s  . c  om*/

    try {

        debug("className: " + className);

        /*
         * get the actual path using the original class loader
         */
        Class<?> clazz = orig.loadClass(className);

        String simpleName = StringUtils.substringAfterLast(className, ".");
        debug("clazz                : " + clazz);
        debug("clazz.getSimpleName(): " + simpleName);

        url = clazz.getResource(simpleName + ".class");
        debug("url: " + url);

        /*
         * force reload
         */
        File file = new File(url.toURI());
        int size = (int) file.length();
        byte buff[] = new byte[size];
        dis = new DataInputStream(new FileInputStream(file));
        dis.readFully(buff);

        return buff;
    } catch (ClassNotFoundException ex) {
        throw ex;
    } catch (Exception ex) {
        throw new IOException(ex);
    } finally {
        if (dis != null) {
            dis.close();
        }
    }
}

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

/**
 * /*from  w  ww. j  a v a  2s. com*/
 * 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.ServerUserThrowable.java

/**
 * Return the class where the Exception has been thrown
 * //from w w  w . j a va2  s.com
 * @param e
 *            the exception thrown
 * @return the class that throws the Exception
 */
private static String extractThrowingMethodNameFromException(Throwable e) {

    String statckTrace = ExceptionUtils.getStackTrace(e);
    String className = StringUtils.substringAfter(statckTrace, "at ");
    className = StringUtils.substringBefore(className, "(");

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

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

    return methodName;

}

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 ava2  s .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 ww w .  java 2 s.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);
        }
    }

}