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

The following examples show how to use org.apache.commons.lang3.StringUtils#startsWithIgnoreCase() . 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: SecurityService.java    From airsonic-advanced with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Returns whether the given file is located in the given folder (or any of its sub-folders).
 * If the given file contains the expression ".." (indicating a reference to the parent directory),
 * this method will return <code>false</code>.
 *
 * @param file   The file in question.
 * @param folder The folder in question.
 * @return Whether the given file is located in the given folder.
 */
protected static boolean isFileInFolder(String file, String folder) {
    // Deny access if file contains ".." surrounded by slashes (or end of line).
    if (file.matches(".*(/|\\\\)\\.\\.(/|\\\\|$).*")) {
        return false;
    }

    // Convert slashes.
    file = file.replace('\\', '/');
    folder = folder.replace('\\', '/');

    return
            // identity matches
            // /a/ == /a, /a == /a/, /a == /a, /a/ == /a/
            StringUtils.equalsIgnoreCase(file, folder)
            || StringUtils.equalsIgnoreCase(file, StringUtils.appendIfMissing(folder, "/"))
            || StringUtils.equalsIgnoreCase(StringUtils.appendIfMissing(file, "/"), folder)
            || StringUtils.equalsIgnoreCase(StringUtils.appendIfMissing(file, "/"), StringUtils.appendIfMissing(folder, "/"))
            // file prefix is folder (MUST append '/', otherwise /a/b2 startswith /a/b)
            || StringUtils.startsWithIgnoreCase(file, StringUtils.appendIfMissing(folder, "/"));
}
 
Example 2
Source File: ResponseUtils.java    From XS2A-Sandbox with Apache License 2.0 6 votes vote down vote up
private String cookie(String cookieStringIn, String name) {
	String cookieString = cookieStringIn;
	if(cookieString==null) {
		return null;
	}

	String cookieParamName=name+"=";

	// Fix Java: rfc2965 want cookie to be separated by comma.
	// SOmehow i am receiving some semicolon separated cookies.
	// Quick Fix: First strip the preceeding cookies if not the first.
	if(!StringUtils.startsWithIgnoreCase(cookieString, cookieParamName)) {
		int indexOfIgnoreCase = StringUtils.indexOfIgnoreCase(cookieString, cookieParamName);
		cookieString = cookieString.substring(indexOfIgnoreCase);
	}
	// The proce
	List<HttpCookie> cookies = HttpCookie.parse(cookieString);
	for (HttpCookie httpCookie : cookies) {
		if(StringUtils.equalsIgnoreCase(httpCookie.getName(), name)){
			return httpCookie.getValue();
		}
	}
	return null;
}
 
Example 3
Source File: TextFilterManage.java    From bbs with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * 处理上传的文件完整路径名称
 * @param html 富文本内容
 * @param item 项目
 * @param newFullFileNameMap 新的完整路径名称 key: 完整路径名称 value: 重定向接口
 * @return
 */
public String processFullFileName(String html,String item,Map<String,String> newFullFileNameMap){
	
	if(!StringUtils.isBlank(html)){
		Document doc = Jsoup.parseBodyFragment(html);

		Elements file_els = doc.select("a[href]");  
		for (Element element : file_els) {  
			String fileUrl = element.attr("href");
			if(fileUrl != null && !"".equals(fileUrl.trim())){
				if(StringUtils.startsWithIgnoreCase(fileUrl, "file/"+item+"/") && newFullFileNameMap.get(fileUrl.trim()) != null){
					element.attr("href",newFullFileNameMap.get(fileUrl.trim()));
					
				}
			}
		}
		//prettyPrint(是否重新格式化)、outline(是否强制所有标签换行)、indentAmount(缩进长度)    doc.outputSettings().indentAmount(0).prettyPrint(false);
		doc.outputSettings().prettyPrint(false);
		html = doc.body().html();
	}
	return html;
}
 
Example 4
Source File: HTMLFormElement.java    From HtmlUnit-Android with Apache License 2.0 6 votes vote down vote up
/**
 * Submits the form (at the end of the current script execution).
 */
@JsxFunction
public void submit() {
    final HtmlPage page = (HtmlPage) getDomNodeOrDie().getPage();
    final WebClient webClient = page.getWebClient();

    final String action = getHtmlForm().getActionAttribute().trim();
    if (StringUtils.startsWithIgnoreCase(action, JavaScriptURLConnection.JAVASCRIPT_PREFIX)) {
        final String js = action.substring(JavaScriptURLConnection.JAVASCRIPT_PREFIX.length());
        webClient.getJavaScriptEngine().execute(page, js, "Form action", 0);
    }
    else {
        // download should be done ASAP, response will be loaded into a window later
        final WebRequest request = getHtmlForm().getWebRequest(null);
        final String target = page.getResolvedTarget(getTarget());
        final boolean forceDownload = webClient.getBrowserVersion().hasFeature(JS_FORM_SUBMIT_FORCES_DOWNLOAD);
        final boolean checkHash =
                !webClient.getBrowserVersion().hasFeature(FORM_SUBMISSION_DOWNLOWDS_ALSO_IF_ONLY_HASH_CHANGED);
        webClient.download(page.getEnclosingWindow(),
                    target, request, checkHash, forceDownload, "JS form.submit()");
    }
}
 
Example 5
Source File: KyeroUtils.java    From OpenEstate-IO with Apache License 2.0 6 votes vote down vote up
public static URI parseImageUrlType(String value) {
    value = StringUtils.trimToNull(value);
    if (value == null) return null;
    try {
        if (StringUtils.startsWithIgnoreCase(value, "http://"))
            return new URI(value);
        else if (StringUtils.startsWithIgnoreCase(value, "https://"))
            return new URI(value);
        else if (StringUtils.startsWithIgnoreCase(value, "ftp://"))
            return new URI(value);
        else
            return new URI("http://" + value);
    } catch (URISyntaxException ex) {
        throw new IllegalArgumentException("Can't parse URI value '" + value + "'!", ex);
    }
}
 
Example 6
Source File: LanguageProcessingHelper.java    From o2oa with GNU Affero General Public License v3.0 6 votes vote down vote up
private boolean skip(Item o) {
	if ((StringUtils.length(o.getValue()) > 1) && (!StringUtils.startsWithAny(o.getValue(), SKIP_START_WITH))
			&& (!StringUtils.endsWithAny(o.getValue(), SKIP_END_WITH))
			&& (!StringUtils.startsWithIgnoreCase(o.getLabel(), "b"))
			&& (!StringUtils.startsWithIgnoreCase(o.getLabel(), "c"))
			&& (!StringUtils.startsWithIgnoreCase(o.getLabel(), "d"))
			&& (!StringUtils.startsWithIgnoreCase(o.getLabel(), "e"))
			&& (!StringUtils.startsWithIgnoreCase(o.getLabel(), "f"))
			&& (!StringUtils.startsWithIgnoreCase(o.getLabel(), "h"))
			&& (!StringUtils.startsWithIgnoreCase(o.getLabel(), "k"))
			&& (!StringUtils.startsWithIgnoreCase(o.getLabel(), "o"))
			&& (!StringUtils.startsWithIgnoreCase(o.getLabel(), "p"))
			&& (!StringUtils.startsWithIgnoreCase(o.getLabel(), "q"))
			&& (!StringUtils.startsWithIgnoreCase(o.getLabel(), "r"))
			&& (!StringUtils.startsWithIgnoreCase(o.getLabel(), "u"))
			&& (!StringUtils.startsWithIgnoreCase(o.getLabel(), "w")) && (!label_skip_m(o))) {
		return false;
	}
	return true;
}
 
Example 7
Source File: CookiesUtils.java    From XS2A-Sandbox with Apache License 2.0 5 votes vote down vote up
public String readCookie(List<String> cookieHeaders, String cookieName) {
	for (String httpCookie : cookieHeaders) {
		if(StringUtils.startsWithIgnoreCase(httpCookie.trim(), cookieName)){
			return httpCookie.trim();
		}
	}
	return null;
}
 
Example 8
Source File: User.java    From para with Apache License 2.0 5 votes vote down vote up
/**
 * Is the main identifier from a generic OAuth 2.0/OpenID Connect provider.
 * @return true if user is signed in with a generic OAauth 2.0 account
 */
@JsonIgnore
public boolean isOAuth2User() {
	return StringUtils.startsWithIgnoreCase(identifier, Config.OAUTH2_PREFIX) ||
			StringUtils.startsWithIgnoreCase(identifier, Config.OAUTH2_SECOND_PREFIX) ||
			StringUtils.startsWithIgnoreCase(identifier, Config.OAUTH2_THIRD_PREFIX);
}
 
Example 9
Source File: GitRepoService.java    From tac with MIT License 5 votes vote down vote up
/**
 * 修改为http链接
 *
 * @param gitURL
 * @return
 */
private String change2Http(String gitURL) {

    String realURL = gitURL;
    if (StringUtils.startsWithIgnoreCase(gitURL, "git@")) {
        Matcher matcher = gitPattern.matcher(gitURL);

        if (!matcher.matches()) {

            throw new IllegalStateException("invalid git url" + gitURL);

        }

        String hostName = matcher.group("hostName");
        String port = matcher.group("port");
        String tail = matcher.group("tail");

        if (StringUtils.isEmpty(port)) {
            realURL = String.format("http://%s/%s", hostName, tail);
        } else {
            realURL = String.format("http://%s:%s/%s", hostName, port, tail);
        }

    }

    return realURL;
}
 
Example 10
Source File: BaseFrameElement.java    From htmlunit with Apache License 2.0 5 votes vote down vote up
/**
 * <span style="color:red">INTERNAL API - SUBJECT TO CHANGE AT ANY TIME - USE AT YOUR OWN RISK.</span><br>
 *
 * Called after the node for the {@code frame} or {@code iframe} has been added to the containing page.
 * The node needs to be added first to allow JavaScript in the frame to see the frame in the parent.
 * @throws FailingHttpStatusCodeException if the server returns a failing status code AND the property
 *      {@link com.gargoylesoftware.htmlunit.WebClientOptions#setThrowExceptionOnFailingStatusCode(boolean)} is
 *      set to true
 */

public void loadInnerPage() throws FailingHttpStatusCodeException {
    String source = getSrcAttribute();
    if (source.isEmpty() || StringUtils.startsWithIgnoreCase(source, WebClient.ABOUT_SCHEME)) {
        source = WebClient.ABOUT_BLANK;
    }

    loadInnerPageIfPossible(source);

    final Page enclosedPage = getEnclosedPage();
    if (enclosedPage != null && enclosedPage.isHtmlPage()) {
        final HtmlPage htmlPage = (HtmlPage) enclosedPage;

        final AbstractJavaScriptEngine<?> jsEngine = getPage().getWebClient().getJavaScriptEngine();
        if (jsEngine != null && jsEngine.isScriptRunning()) {
            final PostponedAction action = new PostponedAction(getPage()) {
                @Override
                public void execute() throws Exception {
                    htmlPage.setReadyState(READY_STATE_COMPLETE);
                }
            };
            jsEngine.addPostponedAction(action);
        }
        else {
            htmlPage.setReadyState(READY_STATE_COMPLETE);
        }
    }
}
 
Example 11
Source File: ComLogonServiceImpl.java    From openemm with GNU Affero General Public License v3.0 5 votes vote down vote up
private String getPasswordResetLink(String linkPattern, String username, String token) {
	try {
		String baseUrl = configService.getValue(ConfigValue.SystemUrl);
		String link = linkPattern.replace("{token}", URLEncoder.encode(token, "UTF-8"))
				.replace("{username}", URLEncoder.encode(username, "UTF-8"));

		if (StringUtils.startsWithIgnoreCase(link, "http://") || StringUtils.startsWithIgnoreCase(link, "https://")) {
			return link;
		} else {
			return StringUtils.removeEnd(baseUrl, "/") + "/" + StringUtils.removeStart(link, "/");
		}
	} catch (UnsupportedEncodingException e) {
		throw new RuntimeException(e);
	}
}
 
Example 12
Source File: ArticleParser.java    From json-wikipedia with Apache License 2.0 5 votes vote down vote up
private void setIsList(Article.Builder article) {
  for (final String list : locale.getListIdentifiers()) {
    if (StringUtils.startsWithIgnoreCase(article.getTitle(), list)) {
      article.setType(ArticleType.LIST);
    }
  }
}
 
Example 13
Source File: StartsWith.java    From vscrawler with Apache License 2.0 5 votes vote down vote up
@Override
protected boolean handle(String input, String searchString, boolean ignoreCase) {
    if (ignoreCase) {
        return StringUtils.startsWithIgnoreCase(input, searchString);
    } else {
        return StringUtils.startsWith(input, searchString);
    }
}
 
Example 14
Source File: AccountInfoController.java    From WeBASE-Collect-Bee with Apache License 2.0 5 votes vote down vote up
@PostMapping("address/get")
@ApiOperation(value = "get by address", httpMethod = "POST")
public CommonResponse getAccountInfoByContractAddress(@RequestBody @Valid String contractAddress,
        BindingResult result) {
    if (result.hasErrors()) {
        return ResponseUtils.validateError(result);
    }
    if (!StringUtils.startsWithIgnoreCase(contractAddress, "0x")) {
        return ResponseUtils.paramError("Contract address is not valid.");
    }
    return accountInfoApiManager.getAccountInfoByContractAddresss(contractAddress);
}
 
Example 15
Source File: ArticleParser.java    From json-wikipedia with Apache License 2.0 5 votes vote down vote up
private void setRedirect(Article.Builder article, String mediawiki) {
  for (final String redirect : redirects) {
    if (StringUtils.startsWithIgnoreCase(mediawiki, redirect)) {
      final int start = mediawiki.indexOf("[[") + 2;
      final int end = mediawiki.indexOf("]]");
      if ((start < 0) || (end < 0)) {
        logger.warn("cannot find the redirect {}\n mediawiki: {}", article.getTitle(), mediawiki);
        continue;
      }
      final String r = ArticleHelper.getTitleInWikistyle(mediawiki.substring(start, end));
      article.setRedirect(r);
      article.setType(ArticleType.REDIRECT);
    }
  }
}
 
Example 16
Source File: RequestEntityRestStorageService.java    From cyberduck with GNU General Public License v3.0 5 votes vote down vote up
@Override
protected boolean isXmlContentType(final String contentType) {
    if(null == contentType) {
        return false;
    }
    if(StringUtils.startsWithIgnoreCase(contentType, "application/xml")) {
        return true;
    }
    if(StringUtils.startsWithIgnoreCase(contentType, "text/xml")) {
        return true;
    }
    return false;
}
 
Example 17
Source File: Signer.java    From para with Apache License 2.0 4 votes vote down vote up
/**
 * Builds, signs and executes a request to an API endpoint using the provided credentials.
 * Signs the request using the Amazon Signature 4 algorithm and returns the response.
 * @param apiClient Jersey Client object
 * @param accessKey access key
 * @param secretKey secret key
 * @param httpMethod the method (GET, POST...)
 * @param endpointURL protocol://host:port
 * @param reqPath the API resource path relative to the endpointURL
 * @param headers headers map
 * @param params parameters map
 * @param jsonEntity an object serialized to JSON byte array (payload), could be null
 * @return a response object
 */
public Response invokeSignedRequest(Client apiClient, String accessKey, String secretKey,
		String httpMethod, String endpointURL, String reqPath,
		Map<String, String> headers, MultivaluedMap<String, String> params, byte[] jsonEntity) {

	boolean isJWT = StringUtils.startsWithIgnoreCase(secretKey, "Bearer");

	WebTarget target = apiClient.target(endpointURL).path(reqPath);
	Map<String, String> signedHeaders = new HashMap<>();
	if (!isJWT) {
		signedHeaders = signRequest(accessKey, secretKey, httpMethod, endpointURL, reqPath,
				headers, params, jsonEntity);
	}

	if (params != null) {
		for (Map.Entry<String, List<String>> param : params.entrySet()) {
			String key = param.getKey();
			List<String> value = param.getValue();
			if (value != null && !value.isEmpty() && value.get(0) != null) {
				target = target.queryParam(key, value.toArray());
			}
		}
	}

	Invocation.Builder builder = target.request(MediaType.APPLICATION_JSON);

	if (headers != null) {
		for (Map.Entry<String, String> header : headers.entrySet()) {
			builder.header(header.getKey(), header.getValue());
		}
	}

	Entity<?> jsonPayload = null;
	if (jsonEntity != null && jsonEntity.length > 0) {
		try {
			jsonPayload = Entity.json(new String(jsonEntity, Config.DEFAULT_ENCODING));
		} catch (IOException ex) {
			logger.error(null, ex);
		}
	}

	if (isJWT) {
		builder.header(HttpHeaders.AUTHORIZATION, secretKey);
	} else {
		builder.header(HttpHeaders.AUTHORIZATION, signedHeaders.get(HttpHeaders.AUTHORIZATION)).
				header("X-Amz-Date", signedHeaders.get("X-Amz-Date"));
	}

	if (Config.getConfigBoolean("user_agent_id_enabled", true)) {
		String userAgent = new StringBuilder("Para client ").append(Para.getVersion()).append(" ").append(accessKey).
				append(" (Java ").append(System.getProperty("java.runtime.version")).append(")").toString();
		builder.header(HttpHeaders.USER_AGENT, userAgent);
	}

	if (jsonPayload != null) {
		return builder.method(httpMethod, jsonPayload);
	} else {
		return builder.method(httpMethod);
	}
}
 
Example 18
Source File: AgnUtils.java    From openemm with GNU Affero General Public License v3.0 4 votes vote down vote up
/**
 * @deprecated please use {@link org.apache.commons.lang3.StringUtils#startsWithIgnoreCase(String, String)} instead.
 */
@Deprecated
public static boolean startsWithIgnoreCase(String str, String prefix) {
	return StringUtils.startsWithIgnoreCase(str, prefix);
}
 
Example 19
Source File: ClassicModifiedLeelazAnalyzer.java    From mylizzie with GNU General Public License v3.0 4 votes vote down vote up
@Override
protected boolean isAnalyzingOngoingAfterCommand(String command) {
    return StringUtils.startsWithIgnoreCase(command, "time_left b 0 0");
}
 
Example 20
Source File: SecurityConfiguration.java    From multiapps-controller with Apache License 2.0 4 votes vote down vote up
private boolean containsBearerAuthorizationHeader(HttpServletRequest request) {
    String authorizationHeader = request.getHeader(HttpHeaders.AUTHORIZATION);
    return StringUtils.startsWithIgnoreCase(authorizationHeader, "bearer");
}