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

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

Introduction

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

Prototype

public static String removeEnd(String str, String remove) 

Source Link

Document

Removes a substring only if it is at the end of a source string, otherwise returns the source string.

Usage

From source file:org.eclipse.gyrex.boot.internal.logback.LogbackLevelDebugOptionsBridge.java

public static String getLoggerNameForDebugOption(final String debugOption) {
    if (null == debugOption)
        return null;

    // only calculate a logger name for the main bundle debug option
    if (!debugOption.endsWith(MAIN_BUNDLE_DEBUG_OPTION))
        return null;

    return StringUtils.removeEnd(debugOption, MAIN_BUNDLE_DEBUG_OPTION);
}

From source file:org.eclipse.gyrex.cloud.internal.zk.console.PathBasedCmd.java

@Override
protected final void doExecute(final ZooKeeper zk) throws Exception {
    if (!StringUtils.equals(path, "/")) {
        path = StringUtils.removeEnd(path, "/");
    }/*from   ww  w .  j av  a 2s .c o m*/
    doExecute(zk, path);
}

From source file:org.eclipse.gyrex.p2.internal.installer.PackageInstallState.java

public static String getPackageId(final IInstallableUnit unit) {
    if (!Boolean.TRUE.toString().equals(unit.getProperty(IU_PROP_PACKAGE)))
        throw new IllegalArgumentException("not a package IU");
    return StringUtils.removeEnd(unit.getId(), ".package");
}

From source file:org.eclipse.mylyn.internal.gerrit.core.GerritConnector.java

@Override
public String getTaskUrl(String repositoryUrl, String taskId) {
    repositoryUrl = StringUtils.removeEnd(repositoryUrl, "/"); //$NON-NLS-1$
    return repositoryUrl + CHANGE_PREFIX_NEW + taskId + "/"; //$NON-NLS-1$
}

From source file:org.eclipse.mylyn.internal.gerrit.core.remote.ReviewHarness.java

public void pushFileToReview(String refSpec, PrivilegeLevel privilegeLevel, String fileName) throws Exception {
    CommitCommand command = createCommitCommand(changeId);
    addFile(fileName);//from w w  w . j  a v a 2s.c  om
    CommitResult result = commitAndPush(command, refSpec, privilegeLevel);
    shortId = StringUtils.trimToEmpty(StringUtils.substringAfterLast(result.push.getMessages(), "/"));
    shortId = StringUtils.removeEnd(getShortId(), " [DRAFT]");
    commitId = result.commit.getId().toString();
    assertThat("Bad Push: " + result.push.getMessages(), getShortId().length(), greaterThan(0));
}

From source file:org.eclipse.mylyn.reviews.ui.spi.factories.AbstractUiFactory.java

protected void handleExecutionStateError() {
    String message = NLS.bind(//w  w w.j  a va 2s.c  o m
            "Cannot {0}. Try re-synchronizing the review task. If that fails, there may be a problem with your repository connection.", //$NON-NLS-1$
            StringUtils.removeEnd(name, "...")); //$NON-NLS-1$
    StatusManager.getManager().handle(new Status(IStatus.ERROR, ReviewsUiPlugin.PLUGIN_ID, message),
            StatusManager.SHOW | StatusManager.LOG);
}

From source file:org.eclipse.skalli.ext.feed.misc.JenkinsFeedProvider.java

@Override
public List<FeedUpdater> getFeedUpdaters(Project project) {
    List<FeedUpdater> result = new ArrayList<FeedUpdater>();

    DevInfProjectExt ext = project.getExtension(DevInfProjectExt.class);
    if (ext != null) {
        String ciServer = ext.getCiUrl();
        if (StringUtils.isNotBlank(ciServer)) {
            String url = null;/*from   w  w  w  .  jav a  2  s  .c o  m*/
            try {
                url = StringUtils.removeEnd(ciServer, "/") + JENKINS_RSS_ALL; //$NON-NLS-1$
                URLFeedUpdater feedUpdater = new URLFeedUpdater(URLUtils.stringToURL(url), "jenkins", "Jenkins", //$NON-NLS-1$
                        project.getUuid());
                result.add(feedUpdater);
            } catch (MalformedURLException e) {
                LOG.info(MessageFormat.format(
                        "{0} is not a valid URL. Fetching Jenkins feed for {1} not possible.", url,
                        project.getName()));
            }
        } else {
            if (LOG.isDebugEnabled()) {
                LOG.debug(MessageFormat.format("No CI URL defined. Fetching Jenkins feed for {0} not possible.",
                        project.getName()));
            }
        }
    }
    return result;
}

From source file:org.eclipse.skalli.services.extension.PropertyLookup.java

/**
 * Adds all properties of the given entity to this property lookup.
 * Property names of the entity are scanned and provided as placeholders of the form
 * <tt>${prefix.propertyName}</tt> for the lookup. If the prefix is blank, placeholders
 * of the form <tt>${propertyName}</tt> are used.
 * Extensions of the entity are scanned, too, and added as placeholders of the form
 * <tt>${prefix.extensionName.propertyName}</tt>. If the prefix is blank, placeholders are
 * named <tt>${extensionName.propertyName}</tt>, respectively.
 *
 * @param entity  the entity to add to this property lookup.
 * @param prefix  the prefix for building placeholders.
 *///from w  ww .j  ava  2  s . c  om
public void putAllProperties(EntityBase entity, String prefix) {
    prefix = StringUtils.removeEnd(prefix, "."); //$NON-NLS-1$
    if (entity instanceof ExtensibleEntityBase) {
        putAllProperties((ExtensibleEntityBase) entity, prefix);
    }
    for (String propertyName : entity.getPropertyNames()) {
        properties.put(concat(prefix, propertyName), entity.getProperty(propertyName));
    }
}

From source file:org.eclipse.skalli.view.internal.filter.LoginFilter.java

@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        throws IOException, ServletException {

    long timeBeginnProcessing = System.currentTimeMillis();

    HttpServletRequest httpRequest = (HttpServletRequest) request;

    String pathInfo = httpRequest.getPathInfo();
    String requestURL = httpRequest.getRequestURL().toString();

    // servletUrl = schema://host:port/contextPath/servletPath
    String servletURL = StringUtils.removeEnd(requestURL, pathInfo);
    request.setAttribute(Consts.ATTRIBUTE_SERVLET_URL, servletURL);

    // baseUrl = schema://host:port/contextPath
    String baseURL = StringUtils.removeEnd(servletURL, httpRequest.getServletPath());
    request.setAttribute(Consts.ATTRIBUTE_BASE_URL, baseURL);

    // webLocator = schema://host:port
    String webLocator = StringUtils.removeEnd(requestURL, httpRequest.getRequestURI());
    request.setAttribute(Consts.ATTRIBUTE_WEBLOCATOR, webLocator);

    String paramProjectId = request.getParameter(Consts.PARAM_ID);

    // determine the project from the URL
    Project project = null;//from w  ww.j ava  2  s  .  c o  m
    ProjectService projectService = ((ProjectService) EntityServices.getByEntityClass(Project.class));

    // first check if project can be deduced from pathInfo
    if (StringUtils.isNotBlank(pathInfo)) {
        if (pathInfo.startsWith(FilterUtil.PATH_SEPARATOR)) {
            pathInfo = pathInfo.replaceFirst(FilterUtil.PATH_SEPARATOR, StringUtils.EMPTY);
        }
        if (pathInfo.contains(FilterUtil.PATH_SEPARATOR)) {
            pathInfo = pathInfo.substring(0, pathInfo.indexOf(FilterUtil.PATH_SEPARATOR));
        }
        project = projectService.getProjectByProjectId(pathInfo);

        // project not found by name, search by UUID
        if (project == null && UUIDUtils.isUUID(pathInfo)) {
            UUID uuid = UUIDUtils.asUUID(pathInfo);
            project = projectService.getByUUID(uuid);
            // project not found by UUID, search for deleted project by UUID
            if (project == null) {
                project = projectService.getDeletedProject(uuid);
            }
        }

        if (project == null) {
            request.setAttribute(Consts.ATTRIBUTE_WINDOWNAME, httpRequest.getPathInfo());
        }
    }

    // project not found by pathInfo, check if project is provided via URL parameter
    if (project == null && StringUtils.isNotBlank(paramProjectId)) {
        project = projectService.getProjectByProjectId(paramProjectId);
        if (project == null) {
            // currently we don't support a scenario where projects are passed via UUID
            FilterUtil.handleException(request, response,
                    new FilterException(String.format("Invalid project identifier '%s' specified in query '%s'",
                            paramProjectId, Consts.PARAM_ID)));
            return;
        }
    }

    if (project != null) {
        request.setAttribute(Consts.ATTRIBUTE_PROJECT, project);
        request.setAttribute(Consts.ATTRIBUTE_PROJECTID, project.getProjectId());
        request.setAttribute(Consts.ATTRIBUTE_PROJECTUUID, project.getUuid().toString());
    } else {
        // do nothing if project is null since this filter runs during
        // creation of projects and displaying of search results, too
    }

    // login and ensure that the user is allowed to access
    PermitService permitService = Services.getRequiredService(PermitService.class);
    String userId = permitService.login(httpRequest, project);
    User user = null;
    boolean isAnonymousUser = StringUtils.isBlank(userId);
    if (isAnonymousUser && rejectAnonymousUsers) {
        FilterUtil.handleACException(httpRequest, response,
                new AccessControlException("Forbidden for anonymous users"));
        return;
    }
    if (!isAnonymousUser) {
        request.setAttribute(Consts.ATTRIBUTE_USERID, userId);
        String userDisplayName = userId;
        user = UserServices.getUser(userId);
        if (user != null) {
            userDisplayName = user.getDisplayName();
            request.setAttribute(Consts.ATTRIBUTE_USER, user);
        }
        request.setAttribute(Consts.ATTRIBUTE_USER_DISPLAY_NAME, userDisplayName);
    }

    boolean isProjectAdmin = !isAnonymousUser && project != null
            && (GroupUtils.isAdministrator(userId) || Permits.isAllowed(Permit.ACTION_PUT, project));
    boolean isProjectAdminInParentChain = !isAnonymousUser && project != null
            && ProjectUtils.isProjectAdminInParentChain(userId, project);

    request.setAttribute(Consts.ATTRIBUTE_ANONYMOUS_USER, isAnonymousUser);
    request.setAttribute(Consts.ATTRIBUTE_PROJECTADMIN, isProjectAdmin);
    request.setAttribute(Consts.ATTRIBUTE_PARENTPROJECTADMIN, isProjectAdminInParentChain);

    // track the access
    Statistics statistics = Statistics.getDefault();
    if (user != null) {
        statistics.trackUser(userId, user.getDepartment(), user.getLocation());
    } else if (StringUtils.isNotBlank(userId)) {
        statistics.trackUser(userId, null, null);
    }

    String referer = httpRequest.getHeader("Referer"); //$NON-NLS-1$
    if (StringUtils.isBlank(referer)) {
        referer = request.getParameter("referer"); //$NON-NLS-1$
    }

    if (StringUtils.isNotBlank(referer)) {
        statistics.trackReferer(userId, referer);
    }

    String requestLine = MessageFormat.format("{0} {1}", //$NON-NLS-1$
            httpRequest.getMethod(), httpRequest.getRequestURI());
    if (project != null) {
        requestLine = MessageFormat.format("{0} /projects/{1}", //$NON-NLS-1$
                httpRequest.getMethod(), project.getProjectId());
    }
    statistics.trackUsage(userId, requestLine, referer);

    String browser = httpRequest.getHeader("User-Agent"); //$NON-NLS-1$
    if (StringUtils.isNotBlank(browser)) {
        statistics.trackBrowser(userId, browser);
    }

    // proceed along the chain
    chain.doFilter(request, response);

    // track the overall response time
    long responseTime = System.currentTimeMillis() - timeBeginnProcessing;
    statistics.trackResponseTime(userId, requestLine, responseTime);
    LOG.info(MessageFormat.format("{0}: responseTime={1} milliseconds)", requestLine,
            Long.toString(responseTime)));
}

From source file:org.eclipse.skalli.view.internal.servlet.StaticContentServlet.java

/**
 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
 *//* w  w  w  .j  ava2s .  c o  m*/
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    String requestURI = request.getRequestURI();
    if (requestURI.startsWith("/content/")) {
        String path = request.getPathInfo();
        if (!path.startsWith("/")) {
            path = "/" + path;
        }
        InputStream in = getContent(path);
        if (in != null) {
            response.setContentType(getContentType(path));
            try {
                OutputStream out = response.getOutputStream();
                IOUtils.copy(in, out);
            } finally {
                IOUtils.closeQuietly(in);
            }
            return;
        }
    } else if (requestURI.startsWith("/schemas/")) {
        // otherwise check the bundles for a matching schema resource
        URL schema = RestUtils.findSchemaResource(requestURI);
        if (schema != null) {
            response.setContentType(getContentType(requestURI));
            InputStream in = schema.openStream();
            OutputStream out = response.getOutputStream();
            try {
                resolveIncludes(in, out);
            } catch (Exception ex) {
                throw new IOException("Failed to resolve schema resource", ex);
            } finally {
                IOUtils.closeQuietly(in);
            }
            return;
        }
    } else if (requestURI.equals(Consts.URL_SEARCH_PLUGIN)) {
        URL searchPluginXML = getSearchPluginXML();
        if (searchPluginXML != null) {
            response.setContentType("application/opensearchdescription+xml"); //$NON-NLS-1$
            Properties properties = new Properties();
            properties.put(Consts.ATTRIBUTE_SEARCH_PLUGIN_TITLE,
                    request.getAttribute(Consts.ATTRIBUTE_SEARCH_PLUGIN_TITLE));
            properties.put(Consts.ATTRIBUTE_SEARCH_PLUGIN_DESCRIPTION,
                    request.getAttribute(Consts.ATTRIBUTE_SEARCH_PLUGIN_DESCRIPTION));
            properties.put(Consts.ATTRIBUTE_WEBLOCATOR,
                    StringUtils.removeEnd(request.getRequestURL().toString(), requestURI));
            InputStream in = searchPluginXML.openStream();
            try {
                String content = IOUtils.toString(in, "UTF-8"); //$NON-NLS-1$
                StrSubstitutor subst = new StrSubstitutor(properties);
                content = subst.replace(content);
                OutputStream out = response.getOutputStream();
                IOUtils.write(content, out, "UTF-8"); //$NON-NLS-1$
            } finally {
                IOUtils.closeQuietly(in);
            }
            return;
        }
    }
    response.sendError(HttpServletResponse.SC_NOT_FOUND);
}