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

The following are top voted examples for showing how to use org.springframework.web.util.UriComponents. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: REST-Web-Services   File: SettingsController.java   Source Code and License 7 votes vote down vote up
/**
 * This method activates the e-mail change using a token
 * @param token E-mail change activation token
 * @param uriComponentsBuilder {@link UriComponentsBuilder}
 * @return The ModelAndView for sign in
 */
@PreAuthorize("permitAll()")
@GetMapping(value = "changeEmail/thanks")
public
ModelAndView confirmEmail(
        @RequestParam final String token,
        final UriComponentsBuilder uriComponentsBuilder
) {
    SSLContextHelper.disable();

    final RestTemplate restTemplate = new RestTemplate();
    final HttpEntity<Object> entity = new HttpEntity<>(new HttpHeaders());

    final UriComponents uriComponents
            = uriComponentsBuilder.path("/api/v1.0/settings/changeEmail/token/{token}").buildAndExpand(token);

    ResponseEntity<Void> response;

    try {
        response = restTemplate
                .exchange(uriComponents.toUri(),
                          HttpMethod.PUT,
                          entity,
                          Void.class);
    } catch (HttpClientErrorException e) /* IF 404 */ {
        return new ModelAndView("tokenNotFound");
    }

    /* IF 200 */
    return new ModelAndView("redirect:/signIn");
}
 
Example 2
Project: spring-cloud-vault-connector   File: VaultServiceInfoCreator.java   Source Code and License 6 votes vote down vote up
@Override
public VaultServiceInfo createServiceInfo(String id, String uri) {

	UriComponents uriInfo = UriComponentsBuilder.fromUriString(uri).build();

	String address = UriComponentsBuilder.newInstance() //
			.scheme(uriInfo.getScheme()) //
			.host(uriInfo.getHost()) //
			.port(uriInfo.getPort()) //
			.build().toString();

	MultiValueMap<String, String> queryParams = uriInfo.getQueryParams();

	String token = queryParams.getFirst("token");
	Assert.hasText(token, "Token (token=…) must not be empty");

	Map<String, String> backends = getBackends(queryParams, backendPattern);
	Map<String, String> sharedBackends = getBackends(queryParams,
			sharedBackendPattern);

	return new VaultServiceInfo(id, address, token.toCharArray(), backends,
			sharedBackends);
}
 
Example 3
Project: spring-cloud-dashboard   File: RootController.java   Source Code and License 6 votes vote down vote up
/**
 * Return a {@link ResourceSupport} object containing the resources
 * served by the Data Flow server.
 *
 * @return {@code ResourceSupport} object containing the Data Flow server's resources
 */
@RequestMapping("/")
public ResourceSupport info() {
	ResourceSupport resourceSupport = new ResourceSupport();
	resourceSupport.add(new Link(dashboard(""), "dashboard"));
	resourceSupport.add(entityLinks.linkToCollectionResource(AppRegistrationResource.class).withRel("apps"));

	resourceSupport.add(entityLinks.linkToCollectionResource(AppStatusResource.class).withRel("runtime/apps"));
	resourceSupport.add(unescapeTemplateVariables(entityLinks.linkForSingleResource(AppStatusResource.class, "{appId}").withRel("runtime/apps/app")));
	resourceSupport.add(unescapeTemplateVariables(entityLinks.linkFor(AppInstanceStatusResource.class, UriComponents.UriTemplateVariables.SKIP_VALUE).withRel("runtime/apps/instances")));

	resourceSupport.add(entityLinks.linkToCollectionResource(ApplicationDefinitionResource.class).withRel("applications/definitions"));
	resourceSupport.add(unescapeTemplateVariables(entityLinks.linkToSingleResource(ApplicationDefinitionResource.class, "{name}").withRel("applications/definitions/definition")));
	resourceSupport.add(entityLinks.linkToCollectionResource(ApplicationDeploymentResource.class).withRel("applications/deployments"));
	resourceSupport.add(unescapeTemplateVariables(entityLinks.linkToSingleResource(ApplicationDeploymentResource.class, "{name}").withRel("applications/deployments/deployment")));

	String completionStreamTemplated = entityLinks.linkFor(CompletionProposalsResource.class).withSelfRel().getHref() + ("/stream{?start,detailLevel}");
	resourceSupport.add(new Link(completionStreamTemplated).withRel("completions/stream"));
	String completionTaskTemplated = entityLinks.linkFor(CompletionProposalsResource.class).withSelfRel().getHref() + ("/task{?start,detailLevel}");
	resourceSupport.add(new Link(completionTaskTemplated).withRel("completions/task"));
	return resourceSupport;
}
 
Example 4
Project: FastBootWeixin   File: WxApiMethodInfo.java   Source Code and License 6 votes vote down vote up
private UriComponents applyContributors(UriComponentsBuilder builder, Method method, Object... args) {
    CompositeUriComponentsContributor contributor = defaultUriComponentsContributor;
    int paramCount = method.getParameterTypes().length;
    int argCount = args.length;
    if (paramCount != argCount) {
        throw new IllegalArgumentException("方法参数量为" + paramCount + " 与真实参数量不匹配,真实参数量为" + argCount);
    }
    final Map<String, Object> uriVars = new HashMap<>(8);
    for (int i = 0; i < paramCount; i++) {
        MethodParameter param = new SynthesizingMethodParameter(method, i);
        param.initParameterNameDiscovery(parameterNameDiscoverer);
        contributor.contributeMethodArgument(param, args[i], builder, uriVars);
    }
    // We may not have all URI var values, expand only what we have
    return builder.build().expand(name -> uriVars.containsKey(name) ? uriVars.get(name) : UriComponents.UriTemplateVariables.SKIP_VALUE);
}
 
Example 5
Project: rm-common-service   File: RestUtility.java   Source Code and License 6 votes vote down vote up
/**
 * Create Uri Components
 * @param path for uri
 * @param queryParams for uri
 * @param pathParams for uri
 * @return UriComponents from supplied path, queryParams and pathParams
 */
public UriComponents createUriComponents(String path, MultiValueMap<String, String> queryParams,
    Object... pathParams) {
  UriComponents uriComponentsWithOutQueryParams = UriComponentsBuilder.newInstance()
      .scheme(config.getScheme())
      .host(config.getHost())
      .port(config.getPort())
      .path(path)
      .buildAndExpand(pathParams);

  // Have to build UriComponents for query parameters separately as Expand interprets braces in JSON query string
  // values as URI template variables to be replaced.
  UriComponents uriComponents = UriComponentsBuilder.newInstance()
      .uriComponents(uriComponentsWithOutQueryParams)
      .queryParams(queryParams)
      .build()
      .encode();

  return uriComponents;
}
 
Example 6
Project: spring4-understanding   File: RedirectView.java   Source Code and License 6 votes vote down vote up
/**
 * Convert model to request parameters and redirect to the given URL.
 * @see #appendQueryProperties
 * @see #sendRedirect
 */
@Override
protected void renderMergedOutputModel(Map<String, Object> model, HttpServletRequest request,
		HttpServletResponse response) throws IOException {

	String targetUrl = createTargetUrl(model, request);
	targetUrl = updateTargetUrl(targetUrl, model, request, response);

	FlashMap flashMap = RequestContextUtils.getOutputFlashMap(request);
	if (!CollectionUtils.isEmpty(flashMap)) {
		UriComponents uriComponents = UriComponentsBuilder.fromUriString(targetUrl).build();
		flashMap.setTargetRequestPath(uriComponents.getPath());
		flashMap.addTargetRequestParams(uriComponents.getQueryParams());
		FlashMapManager flashMapManager = RequestContextUtils.getFlashMapManager(request);
		if (flashMapManager == null) {
			throw new IllegalStateException("FlashMapManager not found despite output FlashMap having been set");
		}
		flashMapManager.saveOutputFlashMap(flashMap, request, response);
	}

	sendRedirect(request, response, targetUrl, this.http10Compatible);
}
 
Example 7
Project: spring4-understanding   File: AbstractFlashMapManager.java   Source Code and License 6 votes vote down vote up
/**
 * Whether the given FlashMap matches the current request.
 * Uses the expected request path and query parameters saved in the FlashMap.
 */
protected boolean isFlashMapForRequest(FlashMap flashMap, HttpServletRequest request) {
	String expectedPath = flashMap.getTargetRequestPath();
	if (expectedPath != null) {
		String requestUri = getUrlPathHelper().getOriginatingRequestUri(request);
		if (!requestUri.equals(expectedPath) && !requestUri.equals(expectedPath + "/")) {
			return false;
		}
	}
	UriComponents uriComponents = ServletUriComponentsBuilder.fromRequest(request).build();
	MultiValueMap<String, String> actualParams = uriComponents.getQueryParams();
	MultiValueMap<String, String> expectedParams = flashMap.getTargetRequestParams();
	for (String expectedName : expectedParams.keySet()) {
		List<String> actualValues = actualParams.get(expectedName);
		if (actualValues == null) {
			return false;
		}
		for (String expectedValue : expectedParams.get(expectedName)) {
			if (!actualValues.contains(expectedValue)) {
				return false;
			}
		}
	}
	return true;
}
 
Example 8
Project: spring4-understanding   File: ServletUriComponentsBuilder.java   Source Code and License 6 votes vote down vote up
/**
 * Initialize a builder with a scheme, host,and port (but not path and query).
 */
private static ServletUriComponentsBuilder initFromRequest(HttpServletRequest request) {
	HttpRequest httpRequest = new ServletServerHttpRequest(request);
	UriComponents uriComponents = UriComponentsBuilder.fromHttpRequest(httpRequest).build();
	String scheme = uriComponents.getScheme();
	String host = uriComponents.getHost();
	int port = uriComponents.getPort();

	ServletUriComponentsBuilder builder = new ServletUriComponentsBuilder();
	builder.scheme(scheme);
	builder.host(host);
	if (("http".equals(scheme) && port != 80) || ("https".equals(scheme) && port != 443)) {
		builder.port(port);
	}
	return builder;
}
 
Example 9
Project: spring4-understanding   File: ServletUriComponentsBuilderTests.java   Source Code and License 6 votes vote down vote up
@Test
public void fromRequestWithForwardedHostAndPort() {
	MockHttpServletRequest request = new MockHttpServletRequest();
	request.setScheme("http");
	request.setServerName("localhost");
	request.setServerPort(80);
	request.setRequestURI("/mvc-showcase");
	request.addHeader("X-Forwarded-Proto", "https");
	request.addHeader("X-Forwarded-Host", "84.198.58.199");
	request.addHeader("X-Forwarded-Port", "443");

	HttpRequest httpRequest = new ServletServerHttpRequest(request);
	UriComponents result = UriComponentsBuilder.fromHttpRequest(httpRequest).build();

	assertEquals("https://84.198.58.199/mvc-showcase", result.toString());
}
 
Example 10
Project: spring4-understanding   File: HtmlUnitRequestBuilder.java   Source Code and License 6 votes vote down vote up
private void contextPath(MockHttpServletRequest request, UriComponents uriComponents) {
	if (this.contextPath == null) {
		List<String> pathSegments = uriComponents.getPathSegments();
		if (pathSegments.isEmpty()) {
			request.setContextPath("");
		}
		else {
			request.setContextPath("/" + pathSegments.get(0));
		}
	}
	else {
		if (!uriComponents.getPath().startsWith(this.contextPath)) {
			throw new IllegalArgumentException(uriComponents.getPath() + " should start with contextPath "
					+ this.contextPath);
		}
		request.setContextPath(this.contextPath);
	}
}
 
Example 11
Project: spring4-understanding   File: HtmlUnitRequestBuilder.java   Source Code and License 6 votes vote down vote up
private void params(MockHttpServletRequest request, UriComponents uriComponents) {
	for (Entry<String, List<String>> entry : uriComponents.getQueryParams().entrySet()) {
		String name = entry.getKey();
		for (String value : entry.getValue()) {
			try {
				value = (value != null ? URLDecoder.decode(value, "UTF-8") : "");
				request.addParameter(name, value);
			}
			catch (UnsupportedEncodingException e) {
				throw new RuntimeException(e);
			}
		}
	}
	for (NameValuePair param : this.webRequest.getRequestParameters()) {
		request.addParameter(param.getName(), param.getValue());
	}
}
 
Example 12
Project: pivotal-cla   File: AuthenticationTests.java   Source Code and License 6 votes vote down vote up
@Test
public void requiresAuthenticationAndCreatesValidOAuthTokenRequest() throws Exception {
	String redirect = mockMvc.perform(get("/sign/pivotal"))
			.andExpect(status().is3xxRedirection())
			.andReturn().getResponse().getRedirectedUrl();

	UriComponents redirectComponent = UriComponentsBuilder.fromHttpUrl(redirect).build();

	assertThat(redirectComponent.getScheme()).isEqualTo("https");
	assertThat(redirectComponent.getHost()).isEqualTo("github.com");
	MultiValueMap<String, String> params = redirectComponent.getQueryParams();
	assertThat(params.getFirst("client_id")).isEqualTo(config.getMain().getClientId());
	assertThat(urlDecode(params.getFirst("redirect_uri"))).isEqualTo("http://localhost/login/oauth2/github");
	assertThat(params.getFirst("state")).isNotNull();

	String[] scopes = urlDecode(params.getFirst("scope")).split(",");
	assertThat(scopes).containsOnly("user:email");
}
 
Example 13
Project: pivotal-cla   File: AuthenticationTests.java   Source Code and License 6 votes vote down vote up
@Test
public void adminRequiresAuthenticationAndCreatesValidOAuthTokenRequest() throws Exception {
	String redirect = mockMvc.perform(get("/admin/cla/link")).andExpect(status().is3xxRedirection()).andReturn()
			.getResponse().getRedirectedUrl();

	UriComponents redirectComponent = UriComponentsBuilder.fromHttpUrl(redirect).build();

	assertThat(redirectComponent.getScheme()).isEqualTo("https");
	assertThat(redirectComponent.getHost()).isEqualTo("github.com");
	MultiValueMap<String, String> params = redirectComponent.getQueryParams();
	assertThat(params.getFirst("client_id")).isEqualTo(config.getMain().getClientId());
	assertThat(urlDecode(params.getFirst("redirect_uri"))).isEqualTo("http://localhost/login/oauth2/github");
	assertThat(params.getFirst("state")).isNotNull();

	String[] scopes = urlDecode(params.getFirst("scope")).split(",");
	assertThat(scopes).containsOnly("user:email", "repo:status", "admin:repo_hook", "admin:org_hook", "read:org");
}
 
Example 14
Project: dhis2-core   File: MobileController.java   Source Code and License 6 votes vote down vote up
private void populateContextPath( Model model, HttpServletRequest request )
{
    UriComponents contextPath = ServletUriComponentsBuilder.fromContextPath( request ).build();

    String contextPathString = contextPath.toString();
    String xForwardedProto = request.getHeader( "X-Forwarded-Proto" );

    if ( xForwardedProto != null )
    {
        if ( contextPathString.contains( "http://" ) && xForwardedProto.equalsIgnoreCase( "https" ) )
        {
            contextPathString = contextPathString.replace( "http://", "https://" );
        }
        else if ( contextPathString.contains( "https://" ) && xForwardedProto.equalsIgnoreCase( "http" ) )
        {
            contextPathString = contextPathString.replace( "https://", "http://" );
        }
    }

    model.addAttribute( "contextPath", contextPathString );
}
 
Example 15
Project: netty-cookbook   File: ServletNettyChannelHandler.java   Source Code and License 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 16
Project: citizenship-appointment-server   File: HttpsOnlyFilter.java   Source Code and License 6 votes vote down vote up
String getRedirectUrl(HttpServletRequest request) {
    String requestUrl = request.getRequestURL().toString();
    try {
        URI uri = new URI(requestUrl);
        UriComponents uriComponents = UriComponentsBuilder.newInstance()
            .scheme("https")
            .host(uri.getHost())
            .path(uri.getPath())
            .query(uri.getQuery())
            .fragment(uri.getFragment())
            .build();
        return uriComponents.toUriString();
    } catch (URISyntaxException e) {
        throw new RuntimeException("Could not parse URL [" + requestUrl + "]", e);
    }
}
 
Example 17
Project: moserp   File: ResponseLinksMapper.java   Source Code and License 6 votes vote down vote up
Object fixLink(Object value) {
    if (!(value instanceof String)) {
        return value;
    }
    String href = (String) value;
    Matcher urlWithServiceNameMatcher = urlWithServiceNamePattern.matcher(href);
    Matcher standardUrlMatcher = standardUrlPattern.matcher(href);
    if (!standardUrlMatcher.matches() && urlWithServiceNameMatcher.matches()) {
        String possibleServiceName = urlWithServiceNameMatcher.group(1);
        log.debug("Possible service name: " + possibleServiceName);
        if (services.contains(possibleServiceName)) {
            log.debug("Service found");
            String gatewayPath = serviceRouteMapper.apply(possibleServiceName);
            String originalRestPath = urlWithServiceNameMatcher.group(2);
            ServletUriComponentsBuilder servletUriComponentsBuilder = ServletUriComponentsBuilder.fromCurrentRequest();
            UriComponents uriComponents = servletUriComponentsBuilder.replacePath(gatewayPath).path(originalRestPath).build();
            log.debug("Mapping " + value + " to " +  uriComponents);
            return uriComponents.toString();
        }
    }
    return href;
}
 
Example 18
Project: AgileAlligators   File: MobileController.java   Source Code and License 6 votes vote down vote up
private void populateContextPath( Model model, HttpServletRequest request )
{
    UriComponents contextPath = ServletUriComponentsBuilder.fromContextPath( request ).build();

    String contextPathString = contextPath.toString();
    String xForwardedProto = request.getHeader( "X-Forwarded-Proto" );

    if ( xForwardedProto != null )
    {
        if ( contextPathString.contains( "http://" ) && xForwardedProto.equalsIgnoreCase( "https" ) )
        {
            contextPathString = contextPathString.replace( "http://", "https://" );
        }
        else if ( contextPathString.contains( "https://" ) && xForwardedProto.equalsIgnoreCase( "http" ) )
        {
            contextPathString = contextPathString.replace( "https://", "http://" );
        }
    }

    model.addAttribute( "contextPath", contextPathString );
}
 
Example 19
Project: AgileAlligators   File: ContextUtils.java   Source Code and License 6 votes vote down vote up
public static void populateContextPath( Model model, HttpServletRequest request )
{
    UriComponents contextPath = ServletUriComponentsBuilder.fromContextPath( request ).build();

    String contextPathString = contextPath.toString();
    String xForwardedProto = request.getHeader( "X-Forwarded-Proto" );

    if ( xForwardedProto != null )
    {
        if ( contextPathString.contains( "http://" ) && xForwardedProto.equalsIgnoreCase( "https" ) )
        {
            contextPathString = contextPathString.replace( "http://", "https://" );
        }
        else if ( contextPathString.contains( "https://" ) && xForwardedProto.equalsIgnoreCase( "http" ) )
        {
            contextPathString = contextPathString.replace( "https://", "http://" );
        }
    }

    model.addAttribute( "contextPath", contextPathString );
}
 
Example 20
Project: socialDocumentLibrary   File: AdminDocumentlibraryClientApplicationTests.java   Source Code and License 6 votes vote down vote up
protected String genericPost(UriComponents uriComponents,int status,MediaType mediaType,String requestBodyCotnent) throws Exception {
	MockHttpServletRequestBuilder content = post(uriComponents.toUri());
	if(mediaType!=null){
		content.contentType(mediaType);
	}

	if(requestBodyCotnent!=null){
		content.content(requestBodyCotnent);
	}

	MvcResult mvcResult = mockMvc.perform(content).
			andExpect(status().is(status)).
			andReturn();

	String contentAsString = mvcResult.getResponse().getContentAsString();

	return contentAsString;
}
 
Example 21
Project: socialDocumentLibrary   File: BookSocialMetadataServiceApplicationTests.java   Source Code and License 6 votes vote down vote up
protected String genericGet(UriComponents uriComponents,MediaType mediaType,String requestBodyCotnent) throws Exception {
    MockHttpServletRequestBuilder content = get(uriComponents.toUri());

    if(mediaType!=null){
        content.contentType(mediaType);
    }

    if(requestBodyCotnent!=null){
        content.content(requestBodyCotnent);
    }

    MvcResult mvcResult = mockMvc.perform(content).
            andExpect(status().isOk()).
            andReturn();

    MockHttpServletResponse response = mvcResult.getResponse();
    String contentAsString = response.getContentAsString();

    LOGGER.info("post location header: " + response.getHeaderValue("LOCATION"));
    LOGGER.info("post contentAsString: " + contentAsString);

    return contentAsString;
}
 
Example 22
Project: socialDocumentLibrary   File: BookSocialMetadataServiceApplicationTests.java   Source Code and License 6 votes vote down vote up
protected String genericPost(UriComponents uriComponents,int status,MediaType mediaType,String requestBodyCotnent) throws Exception {
    MockHttpServletRequestBuilder content = post(uriComponents.toUri());
    if(mediaType!=null){
        content.contentType(mediaType);
    }

    if(requestBodyCotnent!=null){
        content.content(requestBodyCotnent);
    }

    MvcResult mvcResult = mockMvc.perform(content).
            andExpect(status().is(status)).
            andReturn();

    MockHttpServletResponse response = mvcResult.getResponse();
    String contentAsString = response.getContentAsString();

    LOGGER.info("post location header: " + response.getHeaderValue("LOCATION"));
    LOGGER.info("post contentAsString: " + contentAsString);

    return contentAsString;
}
 
Example 23
Project: socialDocumentLibrary   File: FeedBackServiceTests.java   Source Code and License 6 votes vote down vote up
@Test
public void updateFeedBackNotModifiedTest() throws Exception {
    FeedBack feedBack = createFeedBack(USER_NAME, BOOK_ID);
    FeedBack save = feedBackRepository.save(feedBack);

    feedBack.setFeedbackBody("new FeedBack body");

    UriComponents updateFeedBackTestUriComponents = UriComponentsBuilder.fromPath("/feedBack/{feedBackId}").buildAndExpand(save.getId());
    mockMvc.perform(put(updateFeedBackTestUriComponents.toUri())
                    .contentType(MediaType.APPLICATION_JSON)
            .content(objectMapper.writeValueAsString(feedBack)))
            .andExpect(status().isNoContent());


    List<FeedBack> feedBackAux = feedBackRepository.getFeedBack(USER_NAME, BOOK_ID);
    assertNotNull(feedBackAux);
    assertEquals(1, feedBackAux.size());
    assertEquals(feedBackAux.get(0).getFeedbackBody(), feedBack.getFeedbackBody());

    LOGGER.info(feedBackAux.toString());
}
 
Example 24
Project: socialDocumentLibrary   File: FeedBackServiceTests.java   Source Code and License 6 votes vote down vote up
@Test
public void getFeedBackByBookIdWithFiltringTest() throws Exception {
    FeedBack feedBack = createFeedBack(USER_NAME, BOOK_ID);
    FeedBack save = feedBackRepository.save(feedBack);

    UriComponents getFeedBackTestUriComponents = UriComponentsBuilder.fromPath("/feedBack/bookId/{bookId}/data")
            .queryParam("filterQuery", "score")
            .buildAndExpand(save.getBookId());
    String result = genericGet(getFeedBackTestUriComponents);

    List<Map<String,Object>> scores = new ArrayList<>();
    Map<String,Object> resultMap = new HashMap<>();
    resultMap.put("score",feedBack.getScore());
    scores.add(resultMap);

    assertEquals(objectMapper.writeValueAsString(scores), result);
}
 
Example 25
Project: socialDocumentLibrary   File: FeedBackServiceTests.java   Source Code and License 6 votes vote down vote up
@Test
public void getFeedBackBatchWithoutFiltringTest() throws Exception {
    FeedBack save;
    Random random = new Random();

    List<Map<String,String>> mapList = new ArrayList<>();
    Map<String,String> stringStringMap;

    List<FeedBack> expectedFeedBackResult = new ArrayList<>();

    for(int j = 0 ; j < 10 ; j++) {
        save = feedBackRepository.save(createFeedBack(USER_NAME, String.valueOf(random.nextLong())));
        stringStringMap = new HashMap<>();
        stringStringMap.put("userName", save.getUserName());
        stringStringMap.put("bookId", save.getBookId());

        expectedFeedBackResult.add(save);
        mapList.add(stringStringMap);
    }

    UriComponents getFeedBackTestUriComponents = UriComponentsBuilder.fromPath("/feedBack/batch").build();
    String result = genericGet(getFeedBackTestUriComponents,MediaType.APPLICATION_JSON,objectMapper.writeValueAsString(mapList));
    assertEquals(objectMapper.writeValueAsString(expectedFeedBackResult), result);
}
 
Example 26
Project: socialDocumentLibrary   File: FeedBackServiceFailureTests.java   Source Code and License 6 votes vote down vote up
@Test
public void getFeedBackBatchWithoutFiltringTest() throws Exception {
    Random random = new Random();

    List<Map<String,String>> mapList = new ArrayList<>();

    Map<String,String> stringStringMap = new HashMap<>();

    for(int j = 0 ; j < 10 ; j++) {
        stringStringMap.put("userName", String.valueOf(random.nextInt()));
        stringStringMap.put("bookId", String.valueOf(random.nextInt()));

        mapList.add(stringStringMap);
    }

    UriComponents getFeedBackTestUriComponents = UriComponentsBuilder.fromPath("/feedBack/batch").build();
    String result = genericGet(getFeedBackTestUriComponents,MediaType.APPLICATION_JSON,objectMapper.writeValueAsString(mapList));
    Assert.assertEquals(result, "[]");
}
 
Example 27
Project: socialDocumentLibrary   File: MongoGridFsApplicationTests.java   Source Code and License 6 votes vote down vote up
protected String genericPost(UriComponents uriComponents,int status,MediaType mediaType,String requestBodyCotnent) throws Exception {
	MockHttpServletRequestBuilder content = post(uriComponents.toUri());
	if(mediaType!=null){
		content.contentType(mediaType);
	}

	if(requestBodyCotnent!=null){
		content.content(requestBodyCotnent);
	}

	MvcResult mvcResult = mockMvc.perform(content).
									andExpect(status().is(status)).
									andReturn();

	String contentAsString = mvcResult.getResponse().getContentAsString();

	return contentAsString;
}
 
Example 28
Project: socialDocumentLibrary   File: BookServiceEndPointTests.java   Source Code and License 6 votes vote down vote up
@Test
public void successfulSaveBookTest() throws Exception {
    PdfBookMaster activeMqPdfBookMaster = PdfBookMasterTestFactory.pdfBookMaster(BookTestFactory.testBookWithExtensions);
    UriComponents uriComponents = fromPath("/bookService/book").build();

    mockMvc.perform(fileUpload(uriComponents.toUri())
            .file((MockMultipartFile) activeMqPdfBookMaster.getBookFile())
            .param("bookName", activeMqPdfBookMaster.getBookName())
            .param("author", activeMqPdfBookMaster.getAuthor())
            .param("contentType", activeMqPdfBookMaster.getBookFile().getContentType())
            .param("description", activeMqPdfBookMaster.getDescription())
            .accept(MediaType.MULTIPART_FORM_DATA))
            .andExpect(status().isAccepted());

    LOGGER.info("please wait for the job completes");
    Message receiveMessage = jmsTemplate.receive("createBookResultQueue");
    LOGGER.info(receiveMessage.toString());
}
 
Example 29
Project: socialDocumentLibrary   File: UserDocumentLibraryClientApplicationAbstractTests.java   Source Code and License 6 votes vote down vote up
protected String genericPost(UriComponents uriComponents, int status, MediaType mediaType, String requestBodyCotnent) throws Exception {
	MockHttpServletRequestBuilder content = post(uriComponents.toUri());
	if (mediaType != null) {
		content.contentType(mediaType);
	}

	if (requestBodyCotnent != null) {
		content.content(requestBodyCotnent);
	}

	MvcResult mvcResult = mockMvc.perform(content).
			andExpect(status().is(status)).
			andReturn();

	return mvcResult.getResponse().getContentAsString();
}
 
Example 30
Project: socialDocumentLibrary   File: SearchBookServiceApplicationTests.java   Source Code and License 6 votes vote down vote up
protected String genericGet(UriComponents uriComponents,MediaType mediaType,String requestBodyCotnent) throws Exception {
	MockHttpServletRequestBuilder content = get(uriComponents.toUri());

	if(mediaType!=null){
		content.contentType(mediaType);
	}

	if(requestBodyCotnent!=null){
		content.content(requestBodyCotnent);
	}

	MvcResult mvcResult = mockMvc.perform(content).
			andExpect(status().isOk()).
			andReturn();

	MockHttpServletResponse response = mvcResult.getResponse();
	String contentAsString = response.getContentAsString();

	LOGGER.info("post location header: " + response.getHeaderValue("LOCATION"));
	LOGGER.info("post contentAsString: " + contentAsString);

	return contentAsString;
}
 
Example 31
Project: socialDocumentLibrary   File: SearchBookServiceApplicationTests.java   Source Code and License 6 votes vote down vote up
protected String genericPost(UriComponents uriComponents,int status,MediaType mediaType,String requestBodyCotnent) throws Exception {
	MockHttpServletRequestBuilder content = post(uriComponents.toUri());
	if(mediaType!=null){
		content.contentType(mediaType);
	}

	if(requestBodyCotnent!=null){
		content.content(requestBodyCotnent);
	}

	MvcResult mvcResult = mockMvc.perform(content).
			andExpect(status().is(status)).
			andReturn();

	MockHttpServletResponse response = mvcResult.getResponse();

	LOGGER.info("post location header: " + response.getHeaderValue("LOCATION"));

	return response.getContentAsString();
}
 
Example 32
Project: eHMP   File: Main.java   Source Code and License 6 votes vote down vote up
private static void testConnection(VistaAccount vac, String rpcContext, String rpcName) throws Exception {
    System.out.println("Testing account: "+vac.name);
    UriComponents uri = UriComponentsBuilder.newInstance()
            .scheme(VISTA_RPC_BROKER_SCHEME)
            .userInfo(vac.accessCode + ";" + vac.verifyCode)
            .host(vac.host)
            .port(vac.port)
            .pathSegment(rpcContext, rpcName).build();

    RpcTemplate t = new RpcTemplate();
    try {
        RpcResponse r = t.execute(uri.toUriString());

        System.out.println("CONNECTION SUCCESSFUL: elapsed millis=" + r.getElapsedMillis());
    } catch (DataAccessException e) {
        System.out.println("CONNECTION FAILURE: " + e.getCause().getMessage());
    } finally {
        t.destroy();
    }
}
 
Example 33
Project: appverse-server   File: EurekaSwaggerResourcesProvider.java   Source Code and License 6 votes vote down vote up
private static  String obtainUrlLocation(ServiceInstance instance, UriComponents current, String path, String swaggerHost){
    String managementPath = "";
    if (instance.getMetadata().containsKey("managementPath")) {
        managementPath = instance.getMetadata().get("managementPath");
    }
    String hostUrl;
    if (swaggerHost!=null && swaggerHost.length()>0){
        hostUrl=swaggerHost;
    }else {
        //tries to findout the host
        if (("https".equals(current.getScheme()) && 443 == current.getPort()) || ("http".equals(current.getScheme()) && 80 == current.getPort()) || -1 == current.getPort()) {
            //default ports
            hostUrl = String.format("%s://%s", current.getScheme(), current.getHost());
        } else {
            //custom ports
            hostUrl = String.format("%s://%s:%d", current.getScheme(), current.getHost(), current.getPort());
        }
    }
    return hostUrl + managementPath + path;
}
 
Example 34
Project: class-guard   File: RedirectView.java   Source Code and License 6 votes vote down vote up
/**
 * Convert model to request parameters and redirect to the given URL.
 * @see #appendQueryProperties
 * @see #sendRedirect
 */
@Override
protected void renderMergedOutputModel(Map<String, Object> model, HttpServletRequest request,
		HttpServletResponse response) throws IOException {

	String targetUrl = createTargetUrl(model, request);
	targetUrl = updateTargetUrl(targetUrl, model, request, response);

	FlashMap flashMap = RequestContextUtils.getOutputFlashMap(request);
	if (!CollectionUtils.isEmpty(flashMap)) {
		UriComponents uriComponents = UriComponentsBuilder.fromUriString(targetUrl).build();
		flashMap.setTargetRequestPath(uriComponents.getPath());
		flashMap.addTargetRequestParams(uriComponents.getQueryParams());
		FlashMapManager flashMapManager = RequestContextUtils.getFlashMapManager(request);
		if (flashMapManager == null) {
			throw new IllegalStateException("FlashMapManager not found despite output FlashMap having been set");
		}
		flashMapManager.saveOutputFlashMap(flashMap, request, response);
	}

	sendRedirect(request, response, targetUrl, this.http10Compatible);
}
 
Example 35
Project: Harvest-JP   File: SuisController.java   Source Code and License 6 votes vote down vote up
/** {@inheritDoc} */
@Override
@RequestMapping(value = "", method = RequestMethod.GET)
public String render(@SessionAttribute(Constants.SESS_ORGANIZATION_CODE) String orgCode, @SessionAttribute(Constants.SESS_BUSINESS_DAY) Date businessDay, @PathVariable String proGNo) {
	if (logger.isDebugEnabled()) {
		logger.debug("Redering suis report...");
	}
	
	// 自動的にリダイレクトリンクを構築
	UriComponents uriComponents = UriComponentsBuilder.fromUriString(Constants.SUIS_PATH + "/{orgCode}/{currentQuarter}").build();
	String yearQuater = DateUtil.getCurrentQuarter(businessDay);
	URI uri = uriComponents.expand(proGNo, orgCode, yearQuater).encode().toUri();

	logger.info("Redirect to suis screen with params in session...");
	return "redirect:" + uri.toString();
}
 
Example 36
Project: java-util-examples   File: ConstructBuildURI.java   Source Code and License 6 votes vote down vote up
@Test
public void construct_uri_queryparmeter_spring () {
	
	UriComponents uriComponents =
	        UriComponentsBuilder.newInstance()
	            .scheme("http")
	            .host("www.leveluplunch.com")
	            .path("/{lanuage}/{type}/")
	            .queryParam("test", "a", "b")
	            .build()
	            .expand("java", "examples")
	            .encode();
	
	assertEquals("http://www.leveluplunch.com/java/examples/?test=a&test=b", 
			uriComponents.toUriString());
}
 
Example 37
Project: java-util-examples   File: BuildURIFromHttpRequest.java   Source Code and License 6 votes vote down vote up
@Test
public void replace_query_parameter () {
	
	MockHttpServletRequest request = new MockHttpServletRequest();
	request.setQueryString("primaryKey=987");
	
	UriComponents ucb =
	        ServletUriComponentsBuilder
		        .fromRequest(request)
		        .replaceQueryParam("primaryKey", "{id}")
	        	.build()
	            .expand("123")
	            .encode();
	
	assertEquals("http://localhost?primaryKey=123", ucb.toString());
}
 
Example 38
Project: java-util-examples   File: BuildURIFromHttpRequest.java   Source Code and License 6 votes vote down vote up
@Test
public void replace_path () {

	MockHttpServletRequest request = new MockHttpServletRequest();
	request.setPathInfo("/java/examples");

	UriComponents ucb =
	        ServletUriComponentsBuilder
		        .fromRequest(request)
		        .replacePath("/java/exercises")
		        .build()
	            .encode();
	
	URI uri = ucb.toUri();
	
	assertEquals("http://localhost/java/exercises", uri.toString());
}
 
Example 39
Project: spring-social-slideshare   File: SlideShareTemplate.java   Source Code and License 6 votes vote down vote up
public ClientHttpResponse intercept(final HttpRequest request, final byte[] body,
									ClientHttpRequestExecution execution) throws
																		  IOException {
	HttpRequest protectedResourceRequest = new HttpRequestDecorator(request) {
		@Override
		public URI getURI() {

			String ts = Long.toString(TimeUnit.MILLISECONDS.toSeconds(System.currentTimeMillis()));
			String hash = DigestUtils.sha1Hex(sharedSecret + ts).toLowerCase();

			UriComponentsBuilder builder = UriComponentsBuilder.fromUri(super.getURI());
			builder.queryParam("api_key", apiKey);
			builder.queryParam("ts", ts);
			builder.queryParam("hash", hash);

			// all params are already encoded at this point
			UriComponents uriComponents = builder.build(true);
			logger.debug("requesting SlideShare API: " + uriComponents.toUriString());

			return uriComponents.toUri();
		}
	};

	return execution.execute(protectedResourceRequest, body);
}
 
Example 40
Project: jakduk-api   File: AuthUtils.java   Source Code and License 6 votes vote down vote up
/**
 * 회원 프로필 이미지 URL을 생성한다.
 *
 * @param sizeType size 타입
 * @param id UserImage의 ID
 */
public String generateUserPictureUrl(Constants.IMAGE_SIZE_TYPE sizeType, String id) {

    if (StringUtils.isBlank(id))
        return null;

    String urlPathUserPicture = null;

    switch (sizeType) {
        case LARGE:
            urlPathUserPicture = jakdukProperties.getApiUrlPath().getUserPictureLarge();
            break;
        case SMALL:
            urlPathUserPicture = jakdukProperties.getApiUrlPath().getUserPictureSmall();
            break;
    }

    UriComponents uriComponents = UriComponentsBuilder.fromHttpUrl(jakdukProperties.getApiServerUrl())
            .path("/{urlPathGallery}/{id}")
            .buildAndExpand(urlPathUserPicture, id);

    return uriComponents.toUriString();
}