Example usage for org.apache.commons.lang StringUtils chomp

List of usage examples for org.apache.commons.lang StringUtils chomp

Introduction

In this page you can find the example usage for org.apache.commons.lang StringUtils chomp.

Prototype

public static String chomp(String str, String separator) 

Source Link

Document

Removes separator from the end of str if it's there, otherwise leave it alone.

Usage

From source file:com.linkedin.pinot.controller.helix.ControllerRequestURLBuilder.java

public String forTableDelete(String tableName) {
    return StringUtil.join("/", StringUtils.chomp(_baseUrl, "/"), "tables", tableName);
}

From source file:ch.entwine.weblounge.dispatcher.impl.handler.ImageRequestHandlerImpl.java

/**
 * Handles the request for an image resource that is believed to be in the
 * content repository. The handler scales the image as requested, sets the
 * response headers and the writes the image contents to the response.
 * <p>// w w  w .ja v  a2  s . c om
 * This method returns <code>true</code> if the handler is decided to handle
 * the request, <code>false</code> otherwise.
 * 
 * @param request
 *          the weblounge request
 * @param response
 *          the weblounge response
 */
public boolean service(WebloungeRequest request, WebloungeResponse response) {

    WebUrl url = request.getUrl();
    Site site = request.getSite();
    String path = url.getPath();
    String fileName = null;

    // Get hold of the content repository
    ContentRepository contentRepository = site.getContentRepository();
    if (contentRepository == null) {
        logger.warn("No content repository found for site '{}'", site);
        return false;
    } else if (contentRepository.isIndexing()) {
        logger.debug("Content repository of site '{}' is currently being indexed", site);
        DispatchUtils.sendServiceUnavailable(request, response);
        return true;
    }

    // Check if the request uri matches the special uri for images. If so, try
    // to extract the id from the last part of the path. If not, check if there
    // is an image with the current path.
    ResourceURI imageURI = null;
    ImageResource imageResource = null;
    try {
        String id = null;
        String imagePath = null;

        if (path.startsWith(URI_PREFIX)) {
            String uriSuffix = StringUtils.chomp(path.substring(URI_PREFIX.length()), "/");
            uriSuffix = URLDecoder.decode(uriSuffix, "utf-8");

            // Check whether we are looking at a uuid or a url path
            if (uriSuffix.length() == UUID_LENGTH) {
                id = uriSuffix;
            } else if (uriSuffix.length() >= UUID_LENGTH) {
                int lastSeparator = uriSuffix.indexOf('/');
                if (lastSeparator == UUID_LENGTH && uriSuffix.indexOf('/', lastSeparator + 1) < 0) {
                    id = uriSuffix.substring(0, lastSeparator);
                    fileName = uriSuffix.substring(lastSeparator + 1);
                } else {
                    imagePath = uriSuffix;
                    fileName = FilenameUtils.getName(imagePath);
                }
            } else {
                imagePath = "/" + uriSuffix;
                fileName = FilenameUtils.getName(imagePath);
            }
        } else {
            imagePath = path;
            fileName = FilenameUtils.getName(imagePath);
        }

        // Try to load the resource
        imageURI = new ImageResourceURIImpl(site, imagePath, id);
        imageResource = contentRepository.get(imageURI);
        if (imageResource == null) {
            logger.debug("No image found at {}", imageURI);
            return false;
        }
    } catch (ContentRepositoryException e) {
        logger.error("Error loading image from {}: {}", contentRepository, e.getMessage());
        DispatchUtils.sendInternalError(request, response);
        return true;
    } catch (UnsupportedEncodingException e) {
        logger.error("Error decoding image url {} using utf-8: {}", path, e.getMessage());
        DispatchUtils.sendInternalError(request, response);
        return true;
    }

    // Agree to serve the image
    logger.debug("Image handler agrees to handle {}", path);

    // Check the request method. Only GET is supported right now.
    String requestMethod = request.getMethod().toUpperCase();
    if ("OPTIONS".equals(requestMethod)) {
        String verbs = "OPTIONS,GET";
        logger.trace("Answering options request to {} with {}", url, verbs);
        response.setHeader("Allow", verbs);
        response.setContentLength(0);
        return true;
    } else if (!"GET".equals(requestMethod)) {
        logger.debug("Image request handler does not support {} requests", requestMethod);
        DispatchUtils.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED, request, response);
        return true;
    }

    // Is it published?
    // TODO: Fix this. imageResource.isPublished() currently returns false,
    // as both from and to dates are null (see PublishingCtx)
    // if (!imageResource.isPublished()) {
    // logger.debug("Access to unpublished image {}", imageURI);
    // DispatchUtils.sendNotFound(request, response);
    // return true;
    // }

    // Can the image be accessed by the current user?
    User user = request.getUser();
    try {
        // TODO: Check permission
        // PagePermission p = new PagePermission(page, user);
        // AccessController.checkPermission(p);
    } catch (SecurityException e) {
        logger.warn("Access to image {} denied for user {}", imageURI, user);
        DispatchUtils.sendAccessDenied(request, response);
        return true;
    }

    // Determine the response language by filename
    Language language = null;
    if (StringUtils.isNotBlank(fileName)) {
        for (ImageContent c : imageResource.contents()) {
            if (c.getFilename().equalsIgnoreCase(fileName)) {
                if (language != null) {
                    logger.debug("Unable to determine language from ambiguous filename");
                    language = LanguageUtils.getPreferredContentLanguage(imageResource, request, site);
                    break;
                }
                language = c.getLanguage();
            }
        }
        if (language == null)
            language = LanguageUtils.getPreferredContentLanguage(imageResource, request, site);
    } else {
        language = LanguageUtils.getPreferredContentLanguage(imageResource, request, site);
    }

    // If the filename did not lead to a language, apply language resolution
    if (language == null) {
        logger.warn("Image {} does not exist in any supported language", imageURI);
        DispatchUtils.sendNotFound(request, response);
        return true;
    }

    // Extract the image style and scale the image
    String styleId = StringUtils.trimToNull(request.getParameter(OPT_IMAGE_STYLE));
    if (styleId != null) {
        try {
            StringBuffer redirect = new StringBuffer(PathUtils.concat(PreviewRequestHandlerImpl.URI_PREFIX,
                    imageResource.getURI().getIdentifier()));
            redirect.append("?style=").append(styleId);
            response.sendRedirect(redirect.toString());
        } catch (Throwable t) {
            logger.debug("Error sending redirect to the client: {}", t.getMessage());
        }
        return true;
    }

    // Check the modified headers
    long revalidationTime = MS_PER_DAY;
    long expirationDate = System.currentTimeMillis() + revalidationTime;
    if (!ResourceUtils.hasChanged(request, imageResource, language)) {
        logger.debug("Image {} was not modified", imageURI);
        response.setDateHeader("Expires", expirationDate);
        DispatchUtils.sendNotModified(request, response);
        return true;
    }

    // Load the image contents from the repository
    ImageContent imageContents = imageResource.getContent(language);

    // Add mime type header
    String contentType = imageContents.getMimetype();
    if (contentType == null)
        contentType = MediaType.APPLICATION_OCTET_STREAM;

    // Set the content type
    String characterEncoding = response.getCharacterEncoding();
    if (StringUtils.isNotBlank(characterEncoding))
        response.setContentType(contentType + "; charset=" + characterEncoding.toLowerCase());
    else
        response.setContentType(contentType);

    // Browser caches and proxies are allowed to keep a copy
    response.setHeader("Cache-Control", "public, max-age=" + revalidationTime);

    // Set Expires header
    response.setDateHeader("Expires", expirationDate);

    // Determine the resource's modification date
    long resourceLastModified = ResourceUtils.getModificationDate(imageResource, language).getTime();

    // Add last modified header
    response.setDateHeader("Last-Modified", resourceLastModified);

    // Add ETag header
    response.setHeader("ETag", ResourceUtils.getETagValue(imageResource));

    // Load the input stream from the repository
    InputStream imageInputStream = null;
    try {
        imageInputStream = contentRepository.getContent(imageURI, language);
    } catch (Throwable t) {
        logger.error("Error loading {} image '{}' from {}: {}",
                new Object[] { language, imageResource, contentRepository, t.getMessage() });
        logger.error(t.getMessage(), t);
        IOUtils.closeQuietly(imageInputStream);
        return false;
    }

    // Write the image back to the client
    try {
        response.setHeader("Content-Length", Long.toString(imageContents.getSize()));
        response.setHeader("Content-Disposition", "inline; filename=" + imageContents.getFilename());
        IOUtils.copy(imageInputStream, response.getOutputStream());
        response.getOutputStream().flush();
    } catch (EOFException e) {
        logger.debug("Error writing image '{}' back to client: connection closed by client", imageResource);
        return true;
    } catch (IOException e) {
        if (RequestUtils.isCausedByClient(e))
            return true;
        logger.error("Error writing {} image '{}' back to client: {}",
                new Object[] { language, imageResource, e.getMessage() });
    } finally {
        IOUtils.closeQuietly(imageInputStream);
    }
    return true;

}

From source file:com.egt.ejb.toolkit.ToolKitUtils.java

public static String getWebDir(String root, String project) {
    String sep = System.getProperties().getProperty("file.separator");
    String dir = StringUtils.chomp(root, sep) + sep + project + sep + "web";
    return dir + sep;
}

From source file:com.egt.ejb.toolkit.ToolKitUtils.java

public static String getWebInfDir(String root, String project) {
    String sep = System.getProperties().getProperty("file.separator");
    String dir = StringUtils.chomp(root, sep) + sep + project + sep + "web" + sep + "WEB-INF";
    return dir + sep;
}

From source file:com.linkedin.pinot.controller.helix.ControllerRequestURLBuilder.java

public String forSegmentDelete(String resourceName, String segmentName) {
    return StringUtil.join("/", StringUtils.chomp(_baseUrl, "/"), "datafiles", resourceName, segmentName);
}

From source file:biz.netcentric.cq.tools.actool.configmodel.AceBean.java

public String getActionsString() {
    if (actions != null) {
        final StringBuilder sb = new StringBuilder();
        for (final String action : actions) {
            sb.append(action).append(",");
        }// ww w .j a  va 2 s.  co  m
        return StringUtils.chomp(sb.toString(), ",");
    }
    return "";
}

From source file:com.egt.ejb.toolkit.ToolKitUtils.java

public static String getWebSrcDir(String root, String project) {
    String sep = System.getProperties().getProperty("file.separator");
    String com = PREFIJO_PAQUETE.replace(".", sep);
    String web = getWebPackageName(project).replace(".", sep);
    String dir = StringUtils.chomp(root, sep) + sep + project + sep + "src" + sep + "java" + sep + com + sep
            + web;/*from   ww w .  j  a v  a  2 s.  c  om*/
    return dir + sep;
}

From source file:ch.entwine.weblounge.dispatcher.impl.handler.PreviewRequestHandlerImpl.java

/**
 * Handles the request for an image resource that is believed to be in the
 * content repository. The handler scales the image as requested, sets the
 * response headers and the writes the image contents to the response.
 * <p>/*from  w w w .j ava  2 s  .  c o m*/
 * This method returns <code>true</code> if the handler is decided to handle
 * the request, <code>false</code> otherwise.
 * 
 * @param request
 *          the weblounge request
 * @param response
 *          the weblounge response
 */
public boolean service(WebloungeRequest request, WebloungeResponse response) {

    WebUrl url = request.getUrl();
    Site site = request.getSite();
    String path = url.getPath();
    String fileName = null;

    // This request handler can only be used with the prefix
    if (!path.startsWith(URI_PREFIX))
        return false;

    // Get hold of the content repository
    ContentRepository contentRepository = site.getContentRepository();
    if (contentRepository == null) {
        logger.warn("No content repository found for site '{}'", site);
        return false;
    } else if (contentRepository.isIndexing()) {
        logger.debug("Content repository of site '{}' is currently being indexed", site);
        DispatchUtils.sendServiceUnavailable(request, response);
        return true;
    }

    // Check if the request uri matches the special uri for previews. If so, try
    // to extract the id from the last part of the path. If not, check if there
    // is an image with the current path.
    ResourceURI resourceURI = null;
    Resource<?> resource = null;
    try {
        String id = null;
        String imagePath = null;

        String uriSuffix = StringUtils.chomp(path.substring(URI_PREFIX.length()), "/");
        uriSuffix = URLDecoder.decode(uriSuffix, "utf-8");

        // Check whether we are looking at a uuid or a url path
        if (uriSuffix.length() == UUID_LENGTH) {
            id = uriSuffix;
        } else if (uriSuffix.length() >= UUID_LENGTH) {
            int lastSeparator = uriSuffix.indexOf('/');
            if (lastSeparator == UUID_LENGTH && uriSuffix.indexOf('/', lastSeparator + 1) < 0) {
                id = uriSuffix.substring(0, lastSeparator);
                fileName = uriSuffix.substring(lastSeparator + 1);
            } else {
                imagePath = uriSuffix;
                fileName = FilenameUtils.getName(imagePath);
            }
        } else {
            imagePath = "/" + uriSuffix;
            fileName = FilenameUtils.getName(imagePath);
        }

        // Try to load the resource
        resourceURI = new ResourceURIImpl(null, site, imagePath, id);
        resource = contentRepository.get(resourceURI);
        if (resource == null) {
            logger.debug("No resource found at {}", resourceURI);
            return false;
        }
    } catch (ContentRepositoryException e) {
        logger.error("Error loading resource from {}: {}", contentRepository, e.getMessage());
        DispatchUtils.sendInternalError(request, response);
        return true;
    } catch (UnsupportedEncodingException e) {
        logger.error("Error decoding resource url {} using utf-8: {}", path, e.getMessage());
        DispatchUtils.sendInternalError(request, response);
        return true;
    }

    // Agree to serve the preview
    logger.debug("Preview handler agrees to handle {}", path);

    // Check the request method. Only GET is supported right now.
    String requestMethod = request.getMethod().toUpperCase();
    if ("OPTIONS".equals(requestMethod)) {
        String verbs = "OPTIONS,GET";
        logger.trace("Answering options request to {} with {}", url, verbs);
        response.setHeader("Allow", verbs);
        response.setContentLength(0);
        return true;
    } else if (!"GET".equals(requestMethod)) {
        logger.debug("Image request handler does not support {} requests", requestMethod);
        DispatchUtils.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED, request, response);
        return true;
    }

    // Is it published?
    // TODO: Fix this. imageResource.isPublished() currently returns false,
    // as both from and to dates are null (see PublishingCtx)
    // if (!imageResource.isPublished()) {
    // logger.debug("Access to unpublished image {}", imageURI);
    // DispatchUtils.sendNotFound(request, response);
    // return true;
    // }

    // Can the resource be accessed by the current user?
    User user = request.getUser();
    try {
        // TODO: Check permission
        // PagePermission p = new PagePermission(page, user);
        // AccessController.checkPermission(p);
    } catch (SecurityException e) {
        logger.warn("Access to resource {} denied for user {}", resourceURI, user);
        DispatchUtils.sendAccessDenied(request, response);
        return true;
    }

    // Determine the response language by filename
    Language language = null;
    if (StringUtils.isNotBlank(fileName)) {
        for (ResourceContent c : resource.contents()) {
            if (c.getFilename().equalsIgnoreCase(fileName)) {
                if (language != null) {
                    logger.debug("Unable to determine language from ambiguous filename");
                    language = LanguageUtils.getPreferredContentLanguage(resource, request, site);
                    break;
                }
                language = c.getLanguage();
            }
        }
        if (language == null)
            language = LanguageUtils.getPreferredContentLanguage(resource, request, site);
    } else {
        language = LanguageUtils.getPreferredContentLanguage(resource, request, site);
    }

    // If the filename did not lead to a language, apply language resolution
    if (language == null) {
        logger.warn("Resource {} does not exist in any supported language", resourceURI);
        DispatchUtils.sendNotFound(request, response);
        return true;
    }

    // Find a resource preview generator
    PreviewGenerator previewGenerator = null;
    synchronized (previewGenerators) {
        for (PreviewGenerator generator : previewGenerators) {
            if (generator.supports(resource)) {
                previewGenerator = generator;
                break;
            }
        }
    }

    // If we did not find a preview generator, we need to let go
    if (previewGenerator == null) {
        logger.debug("Unable to generate preview for {} since no suitable preview generator is available",
                resource);
        DispatchUtils.sendServiceUnavailable(request, response);
        return true;
    }

    // Extract the image style
    ImageStyle style = null;
    String styleId = StringUtils.trimToNull(request.getParameter(OPT_IMAGE_STYLE));
    if (styleId != null) {
        style = ImageStyleUtils.findStyle(styleId, site);
        if (style == null) {
            DispatchUtils.sendBadRequest("Image style '" + styleId + "' not found", request, response);
            return true;
        }
    }

    // Get the path to the preview image
    File previewFile = ImageStyleUtils.getScaledFile(resource, language, style);

    // Check the modified headers
    long revalidationTime = MS_PER_DAY;
    long expirationDate = System.currentTimeMillis() + revalidationTime;
    if (!ResourceUtils.hasChanged(request, previewFile)) {
        logger.debug("Scaled preview {} was not modified", resourceURI);
        response.setDateHeader("Expires", expirationDate);
        DispatchUtils.sendNotModified(request, response);
        return true;
    }

    // Load the image contents from the repository
    ResourceContent resourceContents = resource.getContent(language);

    // Add mime type header
    String contentType = resourceContents.getMimetype();
    if (contentType == null)
        contentType = MediaType.APPLICATION_OCTET_STREAM;

    // Set the content type
    String characterEncoding = response.getCharacterEncoding();
    if (StringUtils.isNotBlank(characterEncoding))
        response.setContentType(contentType + "; charset=" + characterEncoding.toLowerCase());
    else
        response.setContentType(contentType);

    // Browser caches and proxies are allowed to keep a copy
    response.setHeader("Cache-Control", "public, max-age=" + revalidationTime);

    // Set Expires header
    response.setDateHeader("Expires", expirationDate);

    // Write the image back to the client
    InputStream previewInputStream = null;
    try {
        if (previewFile.isFile()
                && previewFile.lastModified() >= resourceContents.getCreationDate().getTime()) {
            previewInputStream = new FileInputStream(previewFile);
        } else {
            previewInputStream = createPreview(request, response, resource, language, style, previewGenerator,
                    previewFile, contentRepository);
        }

        if (previewInputStream == null) {
            // Assuming that createPreview() is setting the response header in the
            // case of failure
            return true;
        }

        // Add last modified header
        response.setDateHeader("Last-Modified", previewFile.lastModified());
        response.setHeader("ETag", ResourceUtils.getETagValue(previewFile.lastModified()));
        response.setHeader("Content-Disposition", "inline; filename=" + previewFile.getName());
        response.setHeader("Content-Length", Long.toString(previewFile.length()));
        previewInputStream = new FileInputStream(previewFile);
        IOUtils.copy(previewInputStream, response.getOutputStream());
        response.getOutputStream().flush();
        return true;
    } catch (EOFException e) {
        logger.debug("Error writing image '{}' back to client: connection closed by client", resource);
        return true;
    } catch (IOException e) {
        DispatchUtils.sendInternalError(request, response);
        if (RequestUtils.isCausedByClient(e))
            return true;
        logger.error("Error sending image '{}' to the client: {}", resourceURI, e.getMessage());
        return true;
    } catch (Throwable t) {
        logger.error("Error creating scaled image '{}': {}", resourceURI, t.getMessage());
        DispatchUtils.sendInternalError(request, response);
        return true;
    } finally {
        IOUtils.closeQuietly(previewInputStream);
    }
}

From source file:com.microsoft.alm.plugin.idea.common.utils.IdeaHelper.java

/**
 * Finds the full path to a resource whether it's installed by the idea or being run inside the idea
 *
 * @param resourceUrl  the URL for the resource
 * @param resourceName name of the resource
 * @param directory    the directory under the idea.plugin/resource directory to for the resource
 * @return the path to the resource//w w  w  .  j  a va 2s  .co m
 * @throws UnsupportedEncodingException
 */
public static String getResourcePath(final URL resourceUrl, final String resourceName, final String directory)
        throws UnsupportedEncodingException {
    // find location of the resource
    String resourcePath = resourceUrl.getPath();
    resourcePath = URLDecoder.decode(resourcePath, CHARSET_UTF8);
    resourcePath = StringUtils.chomp(resourcePath, "/");

    // When running the plugin inside of the idea for test, the path to the app needs to be
    // manipulated to look in a different location than where the resource resides in production.
    // For prod the url is .../../.IdeaIC15/config/plugins/com.microsoft.alm/lib but for test
    // the url is ../.IdeaIC15/system/plugins-sandbox/plugins/com.microsoft.alm.plugin.idea/classes
    if (resourcePath != null && resourcePath.endsWith(PROD_RESOURCES_SUB_PATH)) {
        return resourcePath + "/" + directory + "/" + resourceName;
    } else {
        return resourcePath + TEST_RESOURCES_SUB_PATH + directory + "/" + resourceName;
    }
}

From source file:net.sf.firemox.xml.XmlConfiguration.java

/**
 * Return the method name corresponding to the specified TAG.
 * /*from  ww w .  ja  v a  2  s  .  c  o  m*/
 * @param tagName
 * @return the method name corresponding to the specified TAG.
 */
static XmlToMDB getXmlClass(String tagName, Map<String, XmlToMDB> instances, Class<?> nameSpaceCall) {
    if (!nameSpaceCall.getSimpleName().startsWith("Xml"))
        throw new InternalError("Caller should be an Xml class : " + nameSpaceCall);

    XmlToMDB nodeClass = instances.get(tagName);
    if (nodeClass != null) {
        return nodeClass;
    }

    String simpleClassName = StringUtils.capitalize(tagName.replaceAll("-", ""));
    String packageName = nameSpaceCall.getPackage().getName();
    String namespace = nameSpaceCall.getSimpleName().substring(3).toLowerCase();
    String className = packageName + "." + namespace + "." + simpleClassName;
    XmlToMDB result;
    try {
        result = (XmlToMDB) Class.forName(className).newInstance();
    } catch (Throwable e) {
        Class<?> mdbClass = null;
        simpleClassName = WordUtils.capitalize(tagName.replaceAll("-", " ")).replaceAll(" ", "");
        try {
            result = (XmlToMDB) Class.forName(packageName + "." + namespace + "." + simpleClassName)
                    .newInstance();
        } catch (Throwable e1) {
            try {
                className = StringUtils.chomp(packageName, ".xml") + "." + namespace + "." + simpleClassName;
                mdbClass = Class.forName(className);
                if (!mdbClass.isAnnotationPresent(XmlTestElement.class)) {
                    result = (XmlToMDB) mdbClass.newInstance();
                } else {
                    result = getAnnotedBuilder(mdbClass, tagName, packageName, namespace);
                }
            } catch (Throwable ei2) {
                error("Unsupported " + namespace + " '" + tagName + "'");
                result = DummyBuilder.instance();
            }
        }
    }
    instances.put(tagName, result);
    return result;
}