protected MockHttpServletRequestBuilder createRequestBuilderWithMethodAndUri(Pact.InteractionRequest request) throws Exception { String uri = request.getUri().contains(getServletContextPathWithoutTrailingSlash()) ? StringUtils.substringAfter(request.getUri(), getServletContextPathWithoutTrailingSlash()) : request.getUri(); uri = UriUtils.decode(uri, "UTF-8"); switch (request.getMethod()) { case GET: return get(uri); case POST: return post(uri); case PUT: return put(uri); case DELETE: return delete(uri); default: throw new RuntimeException("Unsupported method " + request.getMethod()); } }
public void visit(WtImageLink n) throws UnsupportedEncodingException { 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; } } } } }
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(); try { embedBuilder.setTitle(article.getTitle(), WIKI_URL + UriUtils.encode(article.getTitle(), "UTF-8")); } catch (UnsupportedEncodingException e) { throw new RuntimeException(e); } TextConverter converter = new TextConverter(config, embedBuilder); return (MessageEmbed) converter.go(processedPage.getPage()); }
/** * Delete a resource of a data set. * * @param did data set id * @param rid resource id * @param claims authenticated credentials * @return data entity */ @Transactional @Override public Data deleteResource(Long did, Long rid, Claims claims) { DataEntity dataEntity = (DataEntity) getDataset(did); checkPermissions(dataEntity, claims); DataResource dataResource = findResourceById(did, rid, claims); if (dataResource != null) { dataEntity.removeResource((DataResourceEntity) dataResource); try { uploadService.deleteUpload(DATA_DIR_KEY, UriUtils.encode(dataEntity.getName(), UTF_ENCODING), dataResource.getUri()); } catch (Exception e) { log.error("Unable to delete {}: {}", dataResource.getUri(), e); throw new DataResourceDeleteException("Unable to delete " + dataResource.getUri()); } log.info("Data resource deleted by {}: {}", claims.getSubject(), dataResource); } DataEntity savedDataEntity = dataRepository.save(dataEntity); log.info(INFO_TEXT, savedDataEntity); return savedDataEntity; }
@Override public void downloadResource(HttpServletResponse response, Long did, Long rid, Claims claims) { DataEntity dataEntity = (DataEntity) getDataset(did); checkAccessibility(dataEntity, claims); if (dataEntity.getVisibility() != DataVisibility.PRIVATE || dataEntity.getContributorId().equals(claims.getSubject())) { DataResource dataResource = findResourceById(did, rid, claims); try { downloadService.getChunks(response, DATA_DIR_KEY, UriUtils.encode(dataEntity.getName(), UTF_ENCODING), dataResource.getUri()); analyticsService.addDataDownloadRecord(did, rid, ZonedDateTime.now(), claims.getSubject()); } catch (IOException e) { log.error("Unable to download resource: {}", e); throw new NotFoundException(); } } else { throw new ForbiddenException(); } }
@Override public void downloadPublicOpenResource(HttpServletResponse response, Long did, Long rid, Long puid) { DataPublicUserEntity userEntity = dataPublicUserRepository.getOne(puid); if (userEntity == null) { throw new DataPublicUserNotFoundException("Public user not found."); } DataEntity dataEntity = (DataEntity) getDataset(did); if (dataEntity.getVisibility() == DataVisibility.PUBLIC && dataEntity.getAccessibility() == DataAccessibility.OPEN) { List<DataResource> dataResourceEntities = dataEntity.getResources(); DataResource dataResource = dataResourceEntities.stream().filter(o -> o.getId().equals(rid)).findFirst().orElse(null); if (dataResource == null) { log.warn(WARN_TEXT); throw new DataResourceNotFoundException(WARN_TEXT); } try { downloadService.getChunks(response, DATA_DIR_KEY, UriUtils.encode(dataEntity.getName(), UTF_ENCODING), dataResource.getUri()); analyticsService.addDataPublicDownloadRecord(did, rid, ZonedDateTime.now(), puid); } catch (IOException e) { log.error("Unable to download resource: {}", e); throw new NotFoundException(); } } else { throw new ForbiddenException(); } }
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); } }
/** * 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; }
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); } }
/** * Creates a {@link URI} from the given string representation and with the given parameters. */ public static URI createUri(String url, RequestParameters parameters) { UriComponentsBuilder builder = UriComponentsBuilder.newInstance().uri(URI.create(url)); if (parameters != null) { parameters.forEach(e -> { try { builder.queryParam(e.getKey(), UriUtils.encodeQueryParam(String.valueOf(e.getValue()), StandardCharsets.UTF_8.name())); } catch (UnsupportedEncodingException ex) { throw new EncodingException(ex); } }); } return builder.build(true).toUri(); }
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); } }
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"); } }
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 } }
private RedirectView redirectViewWithQuery(String redirectUri, String state, String query) { try { 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; } catch (UnsupportedEncodingException e) { throw new RuntimeException(e); } }
private static boolean isDescendentOrEqual(URL collection, URL test) { if(collection == null || test == null){ return false; } if (collection.toString().equals(test.toString())) { return true; } try { String testPathDecoded = UriUtils.decode(test.getPath(), "UTF-8"); String collectionPathDecoded = UriUtils.decode(collection.getPath(), "UTF-8"); return testPathDecoded.startsWith(collectionPathDecoded); } catch (UnsupportedEncodingException e) { return test.getPath().startsWith(collection.getPath()); } }
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)); } }
/** * helper function for encoding paths * @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)); } }
/** * 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)); } }
/** * 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)); } }
/** * Replace template markers in the URL matching available parameters. The * name of matched parameters are added to the used parameters set. * <p>Parameter values are URL encoded. * @param uri the URL with template parameters to replace * @param params parameters used to replace template markers * @param usedParams set of template parameter names that have been replaced * @return the URL with template parameters replaced */ protected String replaceUriTemplateParams(String uri, List<Param> params, Set<String> usedParams) throws JspException { String encoding = pageContext.getResponse().getCharacterEncoding(); for (Param param : params) { String template = URL_TEMPLATE_DELIMITER_PREFIX + param.getName() + URL_TEMPLATE_DELIMITER_SUFFIX; if (uri.contains(template)) { usedParams.add(param.getName()); try { uri = uri.replace(template, UriUtils.encodePath(param.getValue(), encoding)); } catch (UnsupportedEncodingException ex) { throw new JspException(ex); } } } return uri; }
public String buildZuulRequestURI(HttpServletRequest request) { RequestContext context = RequestContext.getCurrentContext(); String uri = request.getRequestURI(); String contextURI = (String) context.get(REQUEST_URI_KEY); if (contextURI != null) { try { uri = UriUtils.encodePath(contextURI, characterEncoding(request)); } catch (Exception e) { log.debug( "unable to encode uri path from context, falling back to uri from request", e); } } return uri; }
/** * <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; }