Java Code Examples for org.springframework.web.util.UriUtils

The following examples show how to use org.springframework.web.util.UriUtils. These examples are extracted from open source projects. 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 Project: secure-data-service   Source File: URLBuilder.java    License: Apache License 2.0 6 votes vote down vote up
public void addQueryParam(String key, String value) {
    if (url.charAt(url.length() - 1) == '/') {
        url.deleteCharAt(url.length() - 1);
    }
    if (url.indexOf("?") < 0) {
        url.append("?");
    } else if (url.charAt(url.length() - 1) != '&') {
        url.append("&");
    }
    url.append(key).append("=");
    try {
        url.append(UriUtils.encodeQueryParam(value, ENCODING));
    } catch (UnsupportedEncodingException e) {
        url.append(value);
    }
}
 
Example 2
Source Project: spring-analysis-note   Source File: PathResourceResolver.java    License: MIT License 6 votes vote down vote up
private String encodeIfNecessary(String path, @Nullable HttpServletRequest request, Resource location) {
	if (shouldEncodeRelativePath(location) && request != null) {
		Charset charset = this.locationCharsets.getOrDefault(location, StandardCharsets.UTF_8);
		StringBuilder sb = new StringBuilder();
		StringTokenizer tokenizer = new StringTokenizer(path, "/");
		while (tokenizer.hasMoreTokens()) {
			String value = UriUtils.encode(tokenizer.nextToken(), charset);
			sb.append(value);
			sb.append("/");
		}
		if (!path.endsWith("/")) {
			sb.setLength(sb.length() - 1);
		}
		return sb.toString();
	}
	else {
		return path;
	}
}
 
Example 3
Source Project: sinavi-jfw   Source File: TagUtils.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * <p>
 * パスに含まれる置換文字列を指定したパラメータを用いて置換します。<br/>
 * </p>
 * @param uri 基底のパス
 * @param params パラメータ
 * @param pageContext {@link pageContext} インスタンス
 * @return 置換されたパス
 * @throws JspException 不正なエンコーディングが指定された場合
 */
protected static String replaceUriTemplateParams(String uri, Map<String, String[]> params, PageContext pageContext)
        throws JspException {

    String encoding = pageContext.getResponse().getCharacterEncoding();
    Set<String> sets = params.keySet();
    for (String key : sets) {
        String template = URL_TEMPLATE_DELIMITER_PREFIX + key + URL_TEMPLATE_DELIMITER_SUFFIX;
        String[] value = params.get(key);
        if ((value.length == 1) && uri.contains(template)) {
            try {
                uri = uri.replace(template, Matcher.quoteReplacement(UriUtils.encodePath(value[0], encoding)));
            } catch (UnsupportedEncodingException ex) {
                throw new JspException(ex);
            }
        }
    }
    return uri;
}
 
Example 4
String encodeUrlPathSegment(String pathSegment, HttpServletRequest httpServletRequest) {
	log.info("encodeUrlPathSegment()");
	try{
		String enc = httpServletRequest.getCharacterEncoding();
		if (enc == null) {
			enc = WebUtils.DEFAULT_CHARACTER_ENCODING;
		}
		try {
			pathSegment = UriUtils.encodePathSegment(pathSegment, enc);
		} catch (UnsupportedEncodingException uee) {log.error(uee);}
		return pathSegment;
	} catch (Exception e) {
		log.error(e.getMessage(),e);
		throw (new RuntimeException(e));
	}
}
 
Example 5
private static MultiValueMap<String, String> parseQueryParams(URI uri) {
	MultiValueMap<String, String> queryParams = new LinkedMultiValueMap<>();
	String query = uri.getRawQuery();
	if (query != null) {
		Matcher matcher = QUERY_PATTERN.matcher(query);
		while (matcher.find()) {
			String name = UriUtils.decode(matcher.group(1), StandardCharsets.UTF_8);
			String eq = matcher.group(2);
			String value = matcher.group(3);
			if (value != null) {
				value = UriUtils.decode(value, StandardCharsets.UTF_8);
			}
			else {
				value = (StringUtils.hasLength(eq) ? "" : null);
			}
			queryParams.add(name, value);
		}
	}
	return queryParams;
}
 
Example 6
Source Project: java-technology-stack   Source File: RedirectView.java    License: MIT License 6 votes vote down vote up
/**
 * Replace URI template variables in the target URL with encoded model
 * attributes or URI variables from the current request. Model attributes
 * referenced in the URL are removed from the model.
 * @param targetUrl the redirect URL
 * @param model a Map that contains model attributes
 * @param currentUriVariables current request URI variables to use
 * @param encodingScheme the encoding scheme to use
 * @throws UnsupportedEncodingException if string encoding failed
 */
protected StringBuilder replaceUriTemplateVariables(
		String targetUrl, Map<String, Object> model, Map<String, String> currentUriVariables, String encodingScheme)
		throws UnsupportedEncodingException {

	StringBuilder result = new StringBuilder();
	Matcher matcher = URI_TEMPLATE_VARIABLE_PATTERN.matcher(targetUrl);
	int endLastMatch = 0;
	while (matcher.find()) {
		String name = matcher.group(1);
		Object value = (model.containsKey(name) ? model.remove(name) : currentUriVariables.get(name));
		if (value == null) {
			throw new IllegalArgumentException("Model has no value for key '" + name + "'");
		}
		result.append(targetUrl.substring(endLastMatch, matcher.start()));
		result.append(UriUtils.encodePathSegment(value.toString(), encodingScheme));
		endLastMatch = matcher.end();
	}
	result.append(targetUrl.substring(endLastMatch, targetUrl.length()));
	return result;
}
 
Example 7
Source Project: java-technology-stack   Source File: PathResourceResolver.java    License: MIT License 6 votes vote down vote up
private String encodeIfNecessary(String path, @Nullable HttpServletRequest request, Resource location) {
	if (shouldEncodeRelativePath(location) && request != null) {
		Charset charset = this.locationCharsets.getOrDefault(location, StandardCharsets.UTF_8);
		StringBuilder sb = new StringBuilder();
		StringTokenizer tokenizer = new StringTokenizer(path, "/");
		while (tokenizer.hasMoreTokens()) {
			String value = UriUtils.encode(tokenizer.nextToken(), charset);
			sb.append(value);
			sb.append("/");
		}
		if (!path.endsWith("/")) {
			sb.setLength(sb.length() - 1);
		}
		return sb.toString();
	}
	else {
		return path;
	}
}
 
Example 8
Source Project: JuniperBot   Source File: TextConverter.java    License: GNU General Public License v3.0 6 votes vote down vote up
public void visit(WtImageLink n) {
    if (sectionStarted || hasImage) {
        return;
    }

    if (n.getTarget() != null) {
        WtPageName target = n.getTarget();
        if (!target.isEmpty() && target.get(0) instanceof WtText) {
            String content = ((WtText) target.get(0)).getContent();
            if (StringUtils.isNotEmpty(content)) {
                content = getNamespaceValue(6, content);
                if (StringUtils.isNotEmpty(content)) {
                    builder.setImage(config.getWikiUrl() + "/wiki/ru:Special:Filepath/" + UriUtils.encode(content, "UTF-8"));
                    hasImage = true;
                }
            }
        }
    }
}
 
Example 9
Source Project: JuniperBot   Source File: WikiFurService.java    License: GNU General Public License v3.0 6 votes vote down vote up
private MessageEmbed renderArticle(Article article, boolean redirected) {
    if (article == null || StringUtils.isEmpty(article.getRevisionId())) {
        return null;
    }
    EngProcessedPage processedPage = processedPage(article);
    String redirect = lookupRedirect(processedPage);
    if (redirect != null) {
        if (redirected) {
            return null;
        }
        return renderArticle(getArticle(redirect), true);
    }

    EmbedBuilder embedBuilder = messageService.getBaseEmbed();
    embedBuilder.setTitle(article.getTitle(), WIKI_URL + UriUtils.encode(article.getTitle(), "UTF-8"));
    TextConverter converter = new TextConverter(config, embedBuilder);
    return (MessageEmbed) converter.go(processedPage.getPage());
}
 
Example 10
Source Project: JuniperBot   Source File: CommonUtils.java    License: GNU General Public License v3.0 6 votes vote down vote up
public static String parseVkLinks(String string, boolean noLink) {
    if (StringUtils.isEmpty(string)) return string;
    Matcher m = VK_LINK_TAG.matcher(string);
    StringBuffer sb = new StringBuffer(string.length());
    while (m.find()) {
        m.appendReplacement(sb, noLink ? m.group(2)
                : String.format("[%s](https://vk.com/%s)", m.group(2), m.group(1)));
    }
    m.appendTail(sb);

    string = sb.toString();

    if (!noLink) {
        m = VK_HASH_TAG.matcher(string);
        sb = new StringBuffer(string.length());
        while (m.find()) {
            m.appendReplacement(sb, String.format("[%s](https://vk.com/feed?section=search&q=%s)", m.group(1),
                    UriUtils.encode(m.group(1), "UTF-8")));
        }
        m.appendTail(sb);
        string = sb.toString();
    }
    return string;
}
 
Example 11
Source Project: spring4-understanding   Source File: RedirectView.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Replace URI template variables in the target URL with encoded model
 * attributes or URI variables from the current request. Model attributes
 * referenced in the URL are removed from the model.
 * @param targetUrl the redirect URL
 * @param model Map that contains model attributes
 * @param currentUriVariables current request URI variables to use
 * @param encodingScheme the encoding scheme to use
 * @throws UnsupportedEncodingException if string encoding failed
 */
protected StringBuilder replaceUriTemplateVariables(
		String targetUrl, Map<String, Object> model, Map<String, String> currentUriVariables, String encodingScheme)
		throws UnsupportedEncodingException {

	StringBuilder result = new StringBuilder();
	Matcher matcher = URI_TEMPLATE_VARIABLE_PATTERN.matcher(targetUrl);
	int endLastMatch = 0;
	while (matcher.find()) {
		String name = matcher.group(1);
		Object value = (model.containsKey(name) ? model.remove(name) : currentUriVariables.get(name));
		if (value == null) {
			throw new IllegalArgumentException("Model has no value for key '" + name + "'");
		}
		result.append(targetUrl.substring(endLastMatch, matcher.start()));
		result.append(UriUtils.encodePathSegment(value.toString(), encodingScheme));
		endLastMatch = matcher.end();
	}
	result.append(targetUrl.substring(endLastMatch, targetUrl.length()));
	return result;
}
 
Example 12
protected final String getCallbackParam(ServerHttpRequest request) {
	String query = request.getURI().getQuery();
	MultiValueMap<String, String> params = UriComponentsBuilder.newInstance().query(query).build().getQueryParams();
	String value = params.getFirst("c");
	if (StringUtils.isEmpty(value)) {
		return null;
	}
	try {
		String result = UriUtils.decode(value, "UTF-8");
		return (CALLBACK_PARAM_PATTERN.matcher(result).matches() ? result : null);
	}
	catch (UnsupportedEncodingException ex) {
		// should never happen
		throw new SockJsException("Unable to decode callback query parameter", null, ex);
	}
}
 
Example 13
Source Project: Shop-for-JavaWeb   Source File: UserfilesDownloadServlet.java    License: MIT License 6 votes vote down vote up
public void fileOutputStream(HttpServletRequest req, HttpServletResponse resp) 
		throws ServletException, IOException {
	String filepath = req.getRequestURI();
	int index = filepath.indexOf(Global.USERFILES_BASE_URL);
	if(index >= 0) {
		filepath = filepath.substring(index + Global.USERFILES_BASE_URL.length());
	}
	try {
		filepath = UriUtils.decode(filepath, "UTF-8");
	} catch (UnsupportedEncodingException e1) {
		logger.error(String.format("解释文件路径失败,URL地址为%s", filepath), e1);
	}
	File file = new File(Global.getUserfilesBaseDir() + Global.USERFILES_BASE_URL + filepath);
	try {
		FileCopyUtils.copy(new FileInputStream(file), resp.getOutputStream());
		resp.setHeader("Content-Type", "application/octet-stream");
		return;
	} catch (FileNotFoundException e) {
		req.setAttribute("exception", new FileNotFoundException("请求的文件不存在"));
		req.getRequestDispatcher("/WEB-INF/views/error/404.jsp").forward(req, resp);
	}
}
 
Example 14
public void createAppDefinitionBar(HttpServletResponse response, Model appModel, AppDefinitionRepresentation appDefinition) {

        try {
            response.setHeader("Content-Disposition", "attachment; filename=\"" + appDefinition.getName() + ".bar\"; filename*=utf-8''" + UriUtils.encode(appDefinition.getName() + ".bar", "utf-8"));

            byte[] deployZipArtifact = createDeployableZipArtifact(appModel, appDefinition.getDefinition());

            ServletOutputStream servletOutputStream = response.getOutputStream();
            response.setContentType("application/zip");
            servletOutputStream.write(deployZipArtifact);

            // Flush and close stream
            servletOutputStream.flush();
            servletOutputStream.close();

        } catch (Exception e) {
            LOGGER.error("Could not generate app definition bar archive", e);
            throw new InternalServerErrorException("Could not generate app definition bar archive");
        }
    }
 
Example 15
Source Project: kaif   Source File: OauthController.java    License: Apache License 2.0 6 votes vote down vote up
private RedirectView redirectViewWithQuery(String redirectUri, String state, String query) {
  if (!Strings.isNullOrEmpty(state)) {
    query += "&state=" + state;
  }
  String encoded = UriUtils.encodeQuery(query, Charsets.UTF_8.name());
  String locationUri = redirectUri;
  if (redirectUri.contains("?")) {
    locationUri += "&" + encoded;
  } else {
    locationUri += "?" + encoded;
  }
  RedirectView redirectView = new RedirectView(locationUri);
  redirectView.setStatusCode(HttpStatus.FOUND);
  redirectView.setExposeModelAttributes(false);
  redirectView.setPropagateQueryParams(false);
  return redirectView;
}
 
Example 16
Source Project: netty-cookbook   Source File: ServletNettyChannelHandler.java    License: Apache License 2.0 6 votes vote down vote up
void copyQueryParams(UriComponents uriComponents, MockHttpServletRequest servletRequest){
	try {
		if (uriComponents.getQuery() != null) {
			String query = UriUtils.decode(uriComponents.getQuery(), UTF_8);
			servletRequest.setQueryString(query);
		}

		for (Entry<String, List<String>> entry : uriComponents.getQueryParams().entrySet()) {
			for (String value : entry.getValue()) {
				servletRequest.addParameter(
						UriUtils.decode(entry.getKey(), UTF_8),
						UriUtils.decode(value, UTF_8));
			}
		}
	}
	catch (UnsupportedEncodingException ex) {
		// shouldn't happen
	}
}
 
Example 17
String encodeUrlPathSegment(String pathSegment, HttpServletRequest httpServletRequest) {
	log.info("encodeUrlPathSegment()");
	try{
		String enc = httpServletRequest.getCharacterEncoding();
		if (enc == null) {
			enc = WebUtils.DEFAULT_CHARACTER_ENCODING;
		}
		try {
			pathSegment = UriUtils.encodePathSegment(pathSegment, enc);
		} catch (UnsupportedEncodingException uee) {log.error(uee);}
		return pathSegment;
	} catch (Exception e) {
		log.error(e.getMessage(),e);
		throw (new RuntimeException(e));
	}
}
 
Example 18
String encodeUrlPathSegment(String pathSegment, HttpServletRequest httpServletRequest) {
	log.info("encodeUrlPathSegment()");
	try{
		String enc = httpServletRequest.getCharacterEncoding();
		if (enc == null) {
			enc = WebUtils.DEFAULT_CHARACTER_ENCODING;
		}
		try {
			pathSegment = UriUtils.encodePathSegment(pathSegment, enc);
		} catch (UnsupportedEncodingException uee) {log.error(uee);}
		return pathSegment;
	} catch (Exception e) {
		log.error(e.getMessage(),e);
		throw (new RuntimeException(e));
	}
}
 
Example 19
String encodeUrlPathSegment(String pathSegment, HttpServletRequest httpServletRequest) {
	log.info("encodeUrlPathSegment()");
	try{
		String enc = httpServletRequest.getCharacterEncoding();
		if (enc == null) {
			enc = WebUtils.DEFAULT_CHARACTER_ENCODING;
		}
		try {
			pathSegment = UriUtils.encodePathSegment(pathSegment, enc);
		} catch (UnsupportedEncodingException uee) {log.error(uee);}
		return pathSegment;
	} catch (Exception e) {
		log.error(e.getMessage(),e);
		throw (new RuntimeException(e));
	}
}
 
Example 20
String encodeUrlPathSegment(String pathSegment, HttpServletRequest httpServletRequest) {
	log.info("encodeUrlPathSegment()");
	try{
		String enc = httpServletRequest.getCharacterEncoding();
		if (enc == null) {
			enc = WebUtils.DEFAULT_CHARACTER_ENCODING;
		}
		try {
			pathSegment = UriUtils.encodePathSegment(pathSegment, enc);
		} catch (UnsupportedEncodingException uee) {log.error(uee);}
		return pathSegment;
	} catch (Exception e) {
		log.error(e.getMessage(),e);
		throw (new RuntimeException(e));
	}
}
 
Example 21
String encodeUrlPathSegment(String pathSegment, HttpServletRequest httpServletRequest) {
	log.info("encodeUrlPathSegment()");
	try{
		String enc = httpServletRequest.getCharacterEncoding();
		if (enc == null) {
			enc = WebUtils.DEFAULT_CHARACTER_ENCODING;
		}
		try {
			pathSegment = UriUtils.encodePathSegment(pathSegment, enc);
		} catch (UnsupportedEncodingException uee) {log.error(uee);}
		return pathSegment;
	} catch (Exception e) {
		log.error(e.getMessage(),e);
		throw (new RuntimeException(e));
	}
}
 
Example 22
/**
 * Helper method that encodes a string
 * @param pathSegment
 * @param httpServletRequest
 * @return
 */
String encodeUrlPathSegment(String pathSegment, HttpServletRequest httpServletRequest) {
	log.info("encodeUrlPathSegment()");
	try{
		String enc = httpServletRequest.getCharacterEncoding();
		if (enc == null) {
			enc = WebUtils.DEFAULT_CHARACTER_ENCODING;
		}
		try {
			pathSegment = UriUtils.encodePathSegment(pathSegment, enc);
		} catch (UnsupportedEncodingException uee) {log.error(uee);}
		return pathSegment;
	} catch (Exception e) {
		log.error(e.getMessage(),e);
		throw (new RuntimeException(e));
	}
}
 
Example 23
String encodeUrlPathSegment(String pathSegment, HttpServletRequest httpServletRequest) {
	log.info("encodeUrlPathSegment()");
	try{
		String enc = httpServletRequest.getCharacterEncoding();
		if (enc == null) {
			enc = WebUtils.DEFAULT_CHARACTER_ENCODING;
		}
		try {
			pathSegment = UriUtils.encodePathSegment(pathSegment, enc);
		} catch (UnsupportedEncodingException uee) {log.error(uee);}
		return pathSegment;
	} catch (Exception e) {
		log.error(e.getMessage(),e);
		throw (new RuntimeException(e));
	}
}
 
Example 24
String encodeUrlPathSegment(String pathSegment, HttpServletRequest httpServletRequest) {
	log.info("encodeUrlPathSegment()");
	try{
		String enc = httpServletRequest.getCharacterEncoding();
		if (enc == null) {
			enc = WebUtils.DEFAULT_CHARACTER_ENCODING;
		}
		try {
			pathSegment = UriUtils.encodePathSegment(pathSegment, enc);
		} catch (UnsupportedEncodingException uee) {log.error(uee);}
		return pathSegment;
	} catch (Exception e) {
		log.error(e.getMessage(),e);
		throw (new RuntimeException(e));
	}
}
 
Example 25
String encodeUrlPathSegment(String pathSegment, HttpServletRequest httpServletRequest) {
	log.info("encodeUrlPathSegment()");
	try{
		String enc = httpServletRequest.getCharacterEncoding();
		if (enc == null) {
			enc = WebUtils.DEFAULT_CHARACTER_ENCODING;
		}
		try {
			pathSegment = UriUtils.encodePathSegment(pathSegment, enc);
		} catch (UnsupportedEncodingException uee) {log.error(uee);}
		return pathSegment;
	} catch (Exception e) {
		log.error(e.getMessage(),e);
		throw (new RuntimeException(e));
	}
}
 
Example 26
/**
 * Encodes a string path suing the  httpServletRequest Character Encoding
 * @param pathSegment
 * @param httpServletRequest
 * @return
 */
String encodeUrlPathSegment(String pathSegment, HttpServletRequest httpServletRequest) {
	log.info("encodeUrlPathSegment()");
	try{
		String enc = httpServletRequest.getCharacterEncoding();
		if (enc == null) {
			enc = WebUtils.DEFAULT_CHARACTER_ENCODING;
		}
		try {
			pathSegment = UriUtils.encodePathSegment(pathSegment, enc);
		} catch (UnsupportedEncodingException uee) {log.error(uee);}
		return pathSegment;
	} catch (Exception e) {
		log.error(e.getMessage(),e);
		throw (new RuntimeException(e));
	}
}
 
Example 27
String encodeUrlPathSegment(String pathSegment, HttpServletRequest httpServletRequest) {
	log.info("encodeUrlPathSegment()");
	try{
		String enc = httpServletRequest.getCharacterEncoding();
		if (enc == null) {
			enc = WebUtils.DEFAULT_CHARACTER_ENCODING;
		}
		try {
			pathSegment = UriUtils.encodePathSegment(pathSegment, enc);
		} catch (UnsupportedEncodingException uee) {log.error(uee);}
		return pathSegment;
	} catch (Exception e) {
		log.error(e.getMessage(),e);
		throw (new RuntimeException(e));
	}
}
 
Example 28
String encodeUrlPathSegment(String pathSegment, HttpServletRequest httpServletRequest) {
	log.info("encodeUrlPathSegment()");
	try{
		String enc = httpServletRequest.getCharacterEncoding();
		if (enc == null) {
			enc = WebUtils.DEFAULT_CHARACTER_ENCODING;
		}
		try {
			pathSegment = UriUtils.encodePathSegment(pathSegment, enc);
		} catch (UnsupportedEncodingException uee) {log.error(uee);}
		return pathSegment;
	} catch (Exception e) {
		log.error(e.getMessage(),e);
		throw (new RuntimeException(e));
	}
}
 
Example 29
String encodeUrlPathSegment(String pathSegment, HttpServletRequest httpServletRequest) {
	log.info("encodeUrlPathSegment()");
	try{
		String enc = httpServletRequest.getCharacterEncoding();
		if (enc == null) {
			enc = WebUtils.DEFAULT_CHARACTER_ENCODING;
		}
		try {
			pathSegment = UriUtils.encodePathSegment(pathSegment, enc);
		} catch (UnsupportedEncodingException uee) {log.error(uee);}
		return pathSegment;
	} catch (Exception e) {
		log.error(e.getMessage(),e);
		throw (new RuntimeException(e));
	}
}
 
Example 30
String encodeUrlPathSegment(String pathSegment, HttpServletRequest httpServletRequest) {
	log.info("encodeUrlPathSegment()");
	try{
		String enc = httpServletRequest.getCharacterEncoding();
		if (enc == null) {
			enc = WebUtils.DEFAULT_CHARACTER_ENCODING;
		}
		try {
			pathSegment = UriUtils.encodePathSegment(pathSegment, enc);
		} catch (UnsupportedEncodingException uee) {log.error(uee);}
		return pathSegment;
	} catch (Exception e) {
		log.error(e.getMessage(),e);
		throw (new RuntimeException(e));
	}
}