Java Code Examples for org.apache.commons.lang3.StringUtils#stripStart()

The following examples show how to use org.apache.commons.lang3.StringUtils#stripStart() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: FragmentRedirectStrategy.java    From esigate with Apache License 2.0 6 votes vote down vote up
/**
 * For local redirects, converts to relative urls.
 * 
 * @param request
 *            must be an {@link OutgoingRequest}.
 */
@Override
public URI getLocationURI(HttpRequest request, HttpResponse response, HttpContext context) throws ProtocolException {
    URI uri = this.redirectStrategy.getLocationURI(request, response, context);

    String resultingPageUrl = uri.toString();

    DriverRequest driverRequest = ((OutgoingRequest) request).getOriginalRequest();

    // Remove context if present
    if (StringUtils.startsWith(resultingPageUrl, driverRequest.getVisibleBaseUrl())) {
        resultingPageUrl =
                "/"
                        + StringUtils.stripStart(
                                StringUtils.replace(resultingPageUrl, driverRequest.getVisibleBaseUrl(), ""), "/");
    }
    resultingPageUrl = ResourceUtils.getHttpUrlWithQueryString(resultingPageUrl, driverRequest, false);

    return UriUtils.createURI(ResourceUtils.getHttpUrlWithQueryString(resultingPageUrl, driverRequest, false));
}
 
Example 2
Source File: JavadocCompletionProposal.java    From eclipse.jdt.ls with Eclipse Public License 2.0 6 votes vote down vote up
private String prepareTemplate(String text, String lineDelimiter, boolean addGap) {
	boolean endWithLineDelimiter = text.endsWith(lineDelimiter);
	String[] lines = text.split(lineDelimiter);
	StringBuilder buf = new StringBuilder();
	for (int i = 0; i < lines.length; i++) {
		String line = lines[i];
		if (addGap) {
			String stripped = StringUtils.stripStart(line, WHITESPACES);
			if (stripped.startsWith(ASTERISK)) {
				if (!stripped.equals(ASTERISK)) {
					int index = line.indexOf(ASTERISK);
					buf.append(line.substring(0, index + 1));
					buf.append(" ${0}");
					buf.append(lineDelimiter);
				}
				addGap = false;
			}
		}
		buf.append(StringUtils.stripEnd(line, WHITESPACES));
		if (i < lines.length - 1 || endWithLineDelimiter) {
			buf.append(lineDelimiter);
		}
	}
	return buf.toString();
}
 
Example 3
Source File: AbstractAnnotationContainerReadController.java    From elucidate-server with MIT License 5 votes vote down vote up
private ClientPreference determineClientPreference(HttpServletRequest request) {

        String preferHeader = request.getHeader("Prefer");

        preferHeader = StringUtils.lowerCase(preferHeader);
        if (!StringUtils.startsWith(preferHeader, "return=representation")) {
            return ClientPreference.CONTAINED_DESCRIPTIONS;
        }
        preferHeader = StringUtils.stripStart(preferHeader, "return=representation;");
        preferHeader = StringUtils.strip(preferHeader);
        preferHeader = StringUtils.stripStart(preferHeader, "include=");
        preferHeader = StringUtils.strip(preferHeader, "\"");

        String[] preferences = StringUtils.split(preferHeader);
        if (preferences.length == 0) {
            return ClientPreference.CONTAINED_DESCRIPTIONS;
        }

        if (ArrayUtils.contains(preferences, PREFER_CONTAINED_IRIS) && ArrayUtils.contains(preferences, PREFER_CONTAINED_DESCRIPTIONS)) {
            return null;
        }

        for (String preference : preferences) {
            if (StringUtils.equals(preference, PREFER_CONTAINED_DESCRIPTIONS)) {
                return ClientPreference.CONTAINED_DESCRIPTIONS;
            } else if (StringUtils.equals(preference, PREFER_MINIMAL_CONTAINER)) {
                return ClientPreference.MINIMAL_CONTAINER;
            } else if (StringUtils.equals(preference, PREFER_CONTAINED_IRIS)) {
                return ClientPreference.CONTAINED_IRIS;
            }
        }

        return null;
    }
 
Example 4
Source File: LTrimRTrim.java    From tutorials with MIT License 5 votes vote down vote up
@Benchmark
public boolean apacheCommonsStringUtils() {
    String ltrim = StringUtils.stripStart(src, null);
    String rtrim = StringUtils.stripEnd(src, null);

    return checkStrings(ltrim, rtrim);
}
 
Example 5
Source File: LTrimRTrimUnitTest.java    From tutorials with MIT License 5 votes vote down vote up
@Test
public void givenString_whenCallingStringUtilsStripStartEnd_thenReturnsTrue() {
    // Use StringUtils containsIgnoreCase to avoid case insensitive issues
    String ltrim = StringUtils.stripStart(src, null);
    String rtrim = StringUtils.stripEnd(src, null);

    // Compare the Strings obtained and the expected
    Assert.assertTrue(ltrimResult.equalsIgnoreCase(ltrim));
    Assert.assertTrue(rtrimResult.equalsIgnoreCase(rtrim));
}
 
Example 6
Source File: TextToken.java    From jinjava with Apache License 2.0 5 votes vote down vote up
public String output() {
  if (isLeftTrim() && isRightTrim()) {
    return trim();
  } else if (isLeftTrim()) {
    return StringUtils.stripStart(content, null);
  } else if (isRightTrim()) {
    return StringUtils.stripEnd(content, null);
  }
  return content;
}
 
Example 7
Source File: RemoveLeadingAndTrailingZeroes.java    From tutorials with MIT License 5 votes vote down vote up
public static String removeLeadingZeroesWithApacheCommonsStripStart(String s) {
    String stripped = StringUtils.stripStart(s, "0");

    if (stripped.isEmpty() && !s.isEmpty()) {
        return "0";
    }

    return stripped;
}
 
Example 8
Source File: Function.java    From DataDefender with Apache License 2.0 5 votes vote down vote up
/**
 * Looks for a class/method in the passed Function parameter in the form
 * com.package.Class#methodName, com.package.Class.methodName, or
 * com.package.Class::methodName.
 *
 * @return
 * @throws ClassNotFoundException
 */
private List<Method> getFunctionCandidates(Class<?> returnType) 
    throws ClassNotFoundException {

    int index = StringUtils.lastIndexOfAny(functionName, "#", ".", "::");
    if (index == -1) {
        throw new IllegalArgumentException(
            "Function element is empty or incomplete: " + functionName
        );
    }

    String cn = functionName.substring(0, index);
    String fn = StringUtils.stripStart(functionName.substring(index), "#.:");
    int argCount = CollectionUtils.size(arguments);

    log.debug("Looking for function in class {} with name {} and {} parameters", cn, fn, argCount);
    Class<?> clazz = registry.getClassForName(cn);
    List<Method> methods = Arrays.asList(clazz.getMethods());

    return methods
        .stream()
        .filter((m) -> {
            if (!StringUtils.equals(fn, m.getName()) || !Modifier.isPublic(m.getModifiers())) {
                return false;
            }
            final int ac = (!isCombinerFunction || Modifier.isStatic(m.getModifiers())) ? argCount : 1;
            log.debug(
                "Candidate function {} needs {} parameters and gives {} return type, "
                + "looking for {} arguments and {} return type",
                () -> m.getName(),
                () -> m.getParameterCount(),
                () -> m.getReturnType(),
                () -> ac,
                () -> returnType
            );
            return (m.getParameterCount() == ac
                && TypeConverter.isConvertible(m.getReturnType(), returnType));
        })
        .collect(Collectors.toList());
}
 
Example 9
Source File: LeftTrimString.java    From levelup-java-examples with Apache License 2.0 5 votes vote down vote up
@Test
public void trim_leading_spaces_from_string_apache_commons() {

	String leftTrimmedString = StringUtils.stripStart(
			"           The Waiting          ", " ");

	assertEquals("The Waiting          ", leftTrimmedString);
}
 
Example 10
Source File: URLSearchParams.java    From htmlunit with Apache License 2.0 5 votes vote down vote up
private void splitQuery(String params) {
    params = StringUtils.stripStart(params, "?");
    if (StringUtils.isEmpty(params)) {
        return;
    }

    // TODO: encoding
    final String[] parts = StringUtils.split(params, '&');
    for (String part : parts) {
        params_.add(splitQueryParameter(part));
    }
}
 
Example 11
Source File: UserUtil.java    From sunbird-lms-service with MIT License 5 votes vote down vote up
private static String baseN(BigDecimal num, int base) {
  if (num.doubleValue() == 0) {
    return "0";
  }
  double div = Math.floor(num.doubleValue() / base);
  String val = baseN(new BigDecimal(div), base);
  return StringUtils.stripStart(val, stripChars)
      + alphabet[num.remainder(new BigDecimal(base)).intValue()];
}
 
Example 12
Source File: InviteModeratedSenderTest.java    From alfresco-repository with GNU Lesser General Public License v3.0 5 votes vote down vote up
@SuppressWarnings("rawtypes")
/**
 * Test that the mail action is correctly constructed when sending notifications emails about users requesting access to a specific site
 * @throws Exception
 */
public void testSendModeratedEmail() throws Exception
{                  
    Map<String, String> properties = buildDefaultProperties();
    inviteModeratedSender.sendMail(ENTERPRISE_EMAIL_TEMPLATE_PATH, SendModeratedInviteDelegate.EMAIL_SUBJECT_KEY, properties);

    verify(mailAction).setParameterValue(eq(MailActionExecuter.PARAM_FROM), eq(requesterMail));
    verify(mailAction).setParameterValue(eq(MailActionExecuter.PARAM_TO_MANY), eq(SiteManagerGroup));
    verify(mailAction).setParameterValue(eq(MailActionExecuter.PARAM_SUBJECT), eq(SendModeratedInviteDelegate.EMAIL_SUBJECT_KEY));
    verify(mailAction).setParameterValue(eq(MailActionExecuter.PARAM_SUBJECT_PARAMS), eq(new Object[]{fullSiteName}));
    verify(mailAction).setParameterValue(eq(MailActionExecuter.PARAM_TEMPLATE), eq(emailTemplateNodeRef));

    ArgumentCaptor<Map> modelC = ArgumentCaptor.forClass(Map.class);
    verify(mailAction).setParameterValue(eq(MailActionExecuter.PARAM_TEMPLATE_MODEL), (Serializable)modelC.capture());

    String pendingInvitesLink = StringUtils.stripStart(MessageFormat.format(InviteModeratedSender.SHARE_PENDING_INVITES_LINK, StringUtils.EMPTY, shortSiteName), "/");
    
    // Check the model
    Map model = modelC.getValue();
    assertNotNull(model);
    assertEquals(false, model.isEmpty());
    assertNotNull(model.get("productName"));
    assertEquals(model.get("inviteeName"), requesterFirstName + " " + requesterLastName);
    assertEquals(model.get("siteName"), fullSiteName);
    assertEquals(model.get("sharePendingInvitesLink"), pendingInvitesLink);
 
}
 
Example 13
Source File: HdfFile.java    From jhdf with MIT License 5 votes vote down vote up
@Override
public Dataset getDatasetByPath(String path) {
	// As its the file its ok to have a leading slash but strip it here to be
	// consistent with other groups
	path = StringUtils.stripStart(path, Constants.PATH_SEPARATOR);
	return rootGroup.getDatasetByPath(path);
}
 
Example 14
Source File: HdfFile.java    From jhdf with MIT License 5 votes vote down vote up
@Override
public Node getByPath(String path) {
	// As its the file its ok to have a leading slash but strip it here to be
	// consistent with other groups
	path = StringUtils.stripStart(path, Constants.PATH_SEPARATOR);
	return rootGroup.getByPath(path);
}
 
Example 15
Source File: S3Prefix.java    From engine with GNU General Public License v3.0 5 votes vote down vote up
public S3Prefix(String prefix) {
    if (!prefix.equals(DELIMITER)) {
        prefix = StringUtils.stripStart(prefix, DELIMITER);
        prefix = StringUtils.appendIfMissing(prefix, DELIMITER);
    }

    this.prefix = prefix;
}
 
Example 16
Source File: GitFilter.java    From onedev with MIT License 5 votes vote down vote up
protected void processRefs(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
	File gitDir;
	boolean upload;
	
	sessionManager.openSession();
	try {
		String pathInfo = request.getRequestURI().substring(request.getContextPath().length());
		pathInfo = StringUtils.stripStart(pathInfo, "/");

		String projectInfo = pathInfo.substring(0, pathInfo.length() - INFO_REFS.length());
		Project project = getProject(request, response, projectInfo);
		String service = request.getParameter("service");
		
		gitDir = storageManager.getProjectGitDir(project.getId());

		if (service.contains("upload")) {
			checkPullPermission(request, project);
			writeInitial(response, service);
			upload = true;
		} else {
			if (!SecurityUtils.canWriteCode(project))
				throw new UnauthorizedException("You do not have permission to push to this project.");
			writeInitial(response, service);
			upload = false;
		}
	} finally {
		sessionManager.closeSession();
	}
	if (upload)
		new AdvertiseUploadRefsCommand(gitDir).output(response.getOutputStream()).call();
	else
		new AdvertiseReceiveRefsCommand(gitDir).output(response.getOutputStream()).call();
}
 
Example 17
Source File: URLSearchParams.java    From HtmlUnit-Android with Apache License 2.0 5 votes vote down vote up
private void splitQuery(String params) {
    params = StringUtils.stripStart(params, "?");
    if (StringUtils.isEmpty(params)) {
        return;
    }

    // TODO: encoding
    final String[] parts = StringUtils.split(params, '&');
    for (int i = 0; i < parts.length; i++) {
        params_.add(splitQueryParameter(parts[i]));
    }
}
 
Example 18
Source File: RPathUtils.java    From nexus-repository-r with Eclipse Public License 1.0 4 votes vote down vote up
/**
 * Removes slash if path starts with it
 */
public static String removeInitialSlashFromPath(final String path) {
  return StringUtils.stripStart(path, "/");
}
 
Example 19
Source File: OntologyGeneralSolrDocumentLoader.java    From owltools with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
private SolrInputDocument collectClass(OWLGraphWrapper graph, OWLClass c) {

		String def = graph.getDef(c);
		String com = graph.getComment(c);
		String syns = StringUtils.join(graph.getOBOSynonymStrings(c, null), " ");
		String subs = StringUtils.join(graph.getSubsets(c), " ");
		
		ArrayList<String> alt_pps = new ArrayList<String>();
		alt_pps.add("alt_id");
		String alts = StringUtils.join(graph.getAnnotationPropertyValues(c, alt_pps), " ");

		ArrayList<String> rep_pps = new ArrayList<String>();
		rep_pps.add("replaced_by");
		String reps = StringUtils.join(graph.getAnnotationPropertyValues(c, rep_pps), " ");

		ArrayList<String> con_pps = new ArrayList<String>();
		con_pps.add("consider");
		String cons = StringUtils.join(graph.getAnnotationPropertyValues(c, con_pps), " ");

		// Okay, pull out all of the variations on the ID for what people might expect in the ontology.
		String gid = graph.getIdentifier(c);
		String gid_no_namespace = StringUtils.substringAfter(gid, ":");
		String gid_no_namespace_or_leading_zeros = StringUtils.stripStart(gid_no_namespace, "0");
		
		// All together now.
		ArrayList<String> all = new ArrayList<String>();
		all.add(gid_no_namespace);
		all.add(gid_no_namespace_or_leading_zeros);
		all.add(def);
		all.add(com);
		all.add(syns);
		all.add(subs);
		all.add(alts);
		all.add(reps);
		all.add(cons);

		// Watch out for "id" collision!
		SolrInputDocument general_doc = new SolrInputDocument();
		general_doc.addField("id", "general_ontology_class_" + gid);
		general_doc.addField("entity", graph.getIdentifier(c));
		general_doc.addField("entity_label", graph.getLabel(c));
		general_doc.addField("document_category", "general");
		general_doc.addField("category", "ontology_class");
		general_doc.addField("general_blob", StringUtils.join(all, " "));
		
		return general_doc;
	}
 
Example 20
Source File: GitFilter.java    From onedev with MIT License 4 votes vote down vote up
private String getPathInfo(HttpServletRequest request) {
	String pathInfo = request.getRequestURI().substring(request.getContextPath().length());
	return StringUtils.stripStart(pathInfo, "/");
}