Java 类org.springframework.web.util.UriComponentsBuilder 实例源码

项目:Settings    文件:ApplicationsApi.java   
/**
 * 
 * 
 * <p><b>200</b> - Success
 * @param applicationName The applicationName parameter
 * @return HierarchicalModel
 * @throws RestClientException if an error occurs while attempting to invoke the API
 */
public HierarchicalModel apiApplicationsByApplicationNameGet(String applicationName) throws RestClientException {
    Object postBody = null;

    // verify the required parameter 'applicationName' is set
    if (applicationName == null) {
        throw new HttpClientErrorException(HttpStatus.BAD_REQUEST, "Missing the required parameter 'applicationName' when calling apiApplicationsByApplicationNameGet");
    }

    // create path and map variables
    final Map<String, Object> uriVariables = new HashMap<String, Object>();
    uriVariables.put("applicationName", applicationName);
    String path = UriComponentsBuilder.fromPath("/api/applications/{applicationName}").buildAndExpand(uriVariables).toUriString();

    final MultiValueMap<String, String> queryParams = new LinkedMultiValueMap<String, String>();
    final HttpHeaders headerParams = new HttpHeaders();
    final MultiValueMap<String, Object> formParams = new LinkedMultiValueMap<String, Object>();

    final String[] accepts = { 
        "text/plain", "application/json", "text/json"
    };
    final List<MediaType> accept = apiClient.selectHeaderAccept(accepts);
    final String[] contentTypes = { };
    final MediaType contentType = apiClient.selectHeaderContentType(contentTypes);

    String[] authNames = new String[] {  };

    ParameterizedTypeReference<HierarchicalModel> returnType = new ParameterizedTypeReference<HierarchicalModel>() {};
    return apiClient.invokeAPI(path, HttpMethod.GET, queryParams, postBody, headerParams, formParams, accept, contentType, authNames, returnType);
}
项目:role-api    文件:HateoasLinkHeaderBuilderTest.java   
@BeforeClass
public static void setup() {
    UriComponentsBuilder builder = ServletUriComponentsBuilder.fromUriString("dummy");
    linkHeaderBuilder = new HateoasLinkHeaderBuilder(builder);

    Pageable nextPageable = mock(Pageable.class);
    when(nextPageable.getPageNumber()).thenReturn(4);

    Pageable prevPageable = mock(Pageable.class);
    when(prevPageable.getPageNumber()).thenReturn(2);

    page = mock(Page.class);
    when(page.nextPageable()).thenReturn(nextPageable);
    when(page.previousPageable()).thenReturn(prevPageable);
    when(page.getTotalPages()).thenReturn(6);
}
项目:Settings    文件:ApplicationsApi.java   
/**
 * 
 * 
 * <p><b>200</b> - Success
 * @return HierarchicalModel
 * @throws RestClientException if an error occurs while attempting to invoke the API
 */
public HierarchicalModel apiApplicationsGet() throws RestClientException {
    Object postBody = null;

    String path = UriComponentsBuilder.fromPath("/api/applications").build().toUriString();

    final MultiValueMap<String, String> queryParams = new LinkedMultiValueMap<String, String>();
    final HttpHeaders headerParams = new HttpHeaders();
    final MultiValueMap<String, Object> formParams = new LinkedMultiValueMap<String, Object>();

    final String[] accepts = { 
        "text/plain", "application/json", "text/json"
    };
    final List<MediaType> accept = apiClient.selectHeaderAccept(accepts);
    final String[] contentTypes = { };
    final MediaType contentType = apiClient.selectHeaderContentType(contentTypes);

    String[] authNames = new String[] {  };

    ParameterizedTypeReference<HierarchicalModel> returnType = new ParameterizedTypeReference<HierarchicalModel>() {};
    return apiClient.invokeAPI(path, HttpMethod.GET, queryParams, postBody, headerParams, formParams, accept, contentType, authNames, returnType);
}
项目:Settings    文件:AuthorizationApi.java   
/**
 * 
 * 
 * <p><b>200</b> - Success
 * @param model The model parameter
 * @throws RestClientException if an error occurs while attempting to invoke the API
 */
public void apiAuthorizationLoginPost(LoginModel model) throws RestClientException {
    Object postBody = model;

    String path = UriComponentsBuilder.fromPath("/api/authorization/login").build().toUriString();

    final MultiValueMap<String, String> queryParams = new LinkedMultiValueMap<String, String>();
    final HttpHeaders headerParams = new HttpHeaders();
    final MultiValueMap<String, Object> formParams = new LinkedMultiValueMap<String, Object>();

    final String[] accepts = { };
    final List<MediaType> accept = apiClient.selectHeaderAccept(accepts);
    final String[] contentTypes = { 
        "application/json-patch+json", "application/json", "text/json", "application/_*+json"
    };
    final MediaType contentType = apiClient.selectHeaderContentType(contentTypes);

    String[] authNames = new String[] {  };

    ParameterizedTypeReference<Void> returnType = new ParameterizedTypeReference<Void>() {};
    apiClient.invokeAPI(path, HttpMethod.POST, queryParams, postBody, headerParams, formParams, accept, contentType, authNames, returnType);
}
项目:FastBootWeixin    文件:WxApiExecutor.java   
private RequestEntity buildHttpRequestEntity(WxApiMethodInfo wxApiMethodInfo, Object[] args) {
        UriComponentsBuilder builder = wxApiMethodInfo.fromArgs(args);
        // 替换accessToken
        builder.replaceQueryParam(WX_ACCESS_TOKEN_PARAM_NAME, wxAccessTokenManager.getToken());
        HttpHeaders httpHeaders = null;
        Object body = null;
        if (wxApiMethodInfo.getRequestMethod() == WxApiRequest.Method.JSON) {
            httpHeaders = buildJsonHeaders();
//            body = getStringBody(wxApiMethodInfo, args);
            body = getObjectBody(wxApiMethodInfo, args);
        } else if (wxApiMethodInfo.getRequestMethod() == WxApiRequest.Method.XML) {
            httpHeaders = buildXmlHeaders();
            // 暂时不支持xml转换。。。
            body = getObjectBody(wxApiMethodInfo, args);
        } else if (wxApiMethodInfo.getRequestMethod() == WxApiRequest.Method.FORM) {
            body = getFormBody(wxApiMethodInfo, args);
        }
        return new RequestEntity(body, httpHeaders, wxApiMethodInfo.getRequestMethod().getHttpMethod(), builder.build().toUri());
    }
项目:FastBootWeixin    文件:WxApiParamContributor.java   
@Override
public void contributeMethodArgument(MethodParameter parameter, Object value, UriComponentsBuilder builder, Map<String, Object> uriVariables, ConversionService conversionService) {
    Class<?> paramType = parameter.getNestedParameterType();
    if (Map.class.isAssignableFrom(paramType)) {
        return;
    }
    WxApiParam wxApiParam = parameter.getParameterAnnotation(WxApiParam.class);
    String name = (wxApiParam == null || StringUtils.isEmpty(wxApiParam.name()) ? parameter.getParameterName() : wxApiParam.name());
    WxAppAssert.notNull(name, "请添加编译器的-parameter或者为参数添加注解名称");
    if (value == null) {
        if (wxApiParam != null) {
            if (!wxApiParam.required() || !wxApiParam.defaultValue().equals(ValueConstants.DEFAULT_NONE)) {
                return;
            }
        }
        builder.queryParam(name);
    } else if (value instanceof Collection) {
        for (Object element : (Collection<?>) value) {
            element = formatUriValue(conversionService, TypeDescriptor.nested(parameter, 1), element);
            builder.queryParam(name, element);
        }
    } else {
        builder.queryParam(name, formatUriValue(conversionService, new TypeDescriptor(parameter), value));
    }
}
项目:atsea-sample-shop-app    文件:CustomerController.java   
@SuppressWarnings({ "unchecked", "rawtypes" })
@RequestMapping(value = "/customer/", method = RequestMethod.POST)
public ResponseEntity<?> createCustomer(@RequestBody Customer customer, UriComponentsBuilder ucBuilder) {
    logger.info("Creating Customer : {}", customer);

    System.out.println(customerService.customerExist(customer));

    if (customerService.customerExist(customer)) {
        logger.error("Unable to create a customer with username {}", customer.getUsername());
        return new ResponseEntity(new CustomErrorType("A customer with username " + 
        customer.getUsername() + " already exists."),HttpStatus.CONFLICT);
    }

    Customer currentCustomer = customerService.createCustomer(customer);
    Long currentCustomerId = currentCustomer.getCustomerId();
    JSONObject customerInfo = new JSONObject();
    customerInfo.put("customerId", currentCustomerId);

    HttpHeaders headers = new HttpHeaders();
    headers.setLocation(ucBuilder.path("/api/customer/{customerId").buildAndExpand(customer.getCustomerId()).toUri());;
    return new ResponseEntity<JSONObject>(customerInfo, HttpStatus.CREATED);
}
项目:BittrexGatherer    文件:BittrexRemoteVerticle.java   
private void setupHttpClient(String connectionToken, String protocolVersion){

 if(client != null){
  client.close();
 }

 UriComponentsBuilder urlBuilder = UriComponentsBuilder.fromUriString("/signalr/connect");
      urlBuilder.queryParam("transport", "webSockets");
      urlBuilder.queryParam("clientProtocol", protocolVersion);
      urlBuilder.queryParam("connectionToken", connectionToken);
      urlBuilder.queryParam("connectionData", "[{\"name\":\"corehub\"}]");

      String endPoint = urlBuilder.build().encode().toUriString();

 HttpClientOptions options = new HttpClientOptions();

 options.setMaxWebsocketFrameSize(1000000);
 options.setMaxWebsocketMessageSize(1000000);

 client = vertx.createHttpClient(options);
 connectToBittrex(endPoint);
}
项目:FastBootWeixin    文件:WxTokenServer.java   
public WxAccessToken refreshToken() {
    UriComponentsBuilder builder = UriComponentsBuilder.newInstance()
            .scheme("https").host(wxProperties.getUrl().getHost()).path(wxProperties.getUrl().getRefreshToken())
            .queryParam("grant_type", "client_credential")
            .queryParam("appid", wxProperties.getAppid())
            .queryParam("secret", wxProperties.getAppsecret());
    String result = wxApiTemplate.getForObject(builder.toUriString(), String.class);
    if (WxAccessTokenException.hasException(result)) {
        throw new WxAccessTokenException(result);
    } else {
        try {
            return jsonConverter.readValue(result, WxAccessToken.class);
        } catch (IOException e) {
            logger.error(e.getMessage(), e);
            throw new WxAppException("获取Token时转换Json失败");
        }
    }
}
项目:Spring-Shiro-Spark    文件:AuthController.java   
@PostMapping(value = SUBPATH_LOGIN)
public ResponseEntity<UserDto> login(@RequestBody UserDto userDto,
                                     UriComponentsBuilder uriComponentsBuilder){
    HttpHeaders headers = ApplicationUtil.getHttpHeaders(uriComponentsBuilder,SUBPATH_LOGIN);
    logger.info("================userInfo================username: " + userDto.getUsername() + ",pw: " + userDto.getPassword());
    Subject subject = SecurityUtils.getSubject();
    UsernamePasswordToken token = new UsernamePasswordToken(userDto.getUsername(),userDto.getPassword());
    //User user = new User("root","root","root","root");
    //userDao.save(user);
    try{
        subject.login(token);
    } catch (AuthenticationException e){
        logger.error("======登录失败======");
        throw new ResultException(ErrorCode.USERNAMEORPASSWORD.getDesc(),ErrorCode.USERNAMEORPASSWORD);
    }
    UserDto loginUserDto = (UserDto) SecurityUtils.getSubject().getSession().getAttribute("user");

    return new ResponseEntity<>(loginUserDto,headers, HttpStatus.OK);
}
项目:airsonic    文件:HLSController.java   
private void generateVariantPlaylist(HttpServletRequest request, int id, Player player, List<Pair<Integer, Dimension>> bitRates, PrintWriter writer) {
        writer.println("#EXTM3U");
        writer.println("#EXT-X-VERSION:1");
//        writer.println("#EXT-X-TARGETDURATION:" + SEGMENT_DURATION);

        String contextPath = getContextPath(request);
        for (Pair<Integer, Dimension> bitRate : bitRates) {
            Integer kbps = bitRate.getFirst();
            writer.println("#EXT-X-STREAM-INF:PROGRAM-ID=1,BANDWIDTH=" + kbps * 1000L);
            UriComponentsBuilder url = (UriComponentsBuilder.fromUriString(contextPath + "ext/hls/hls.m3u8")
                    .queryParam("id", id)
                    .queryParam("player", player.getId())
                    .queryParam("bitRate", kbps));
            jwtSecurityService.addJWTToken(url);
            writer.print(url.toUriString());
            Dimension dimension = bitRate.getSecond();
            if (dimension != null) {
                writer.print("@" + dimension.width + "x" + dimension.height);
            }
            writer.println();
        }
//        writer.println("#EXT-X-ENDLIST");
    }
项目:airsonic    文件:HLSController.java   
private String createStreamUrl(HttpServletRequest request, Player player, int id, int offset, int duration, Pair<Integer, Dimension> bitRate) {
    UriComponentsBuilder builder = UriComponentsBuilder.fromUriString(getContextPath(request) + "ext/stream/stream.ts");
    builder.queryParam("id", id);
    builder.queryParam("hls", "true");
    builder.queryParam("timeOffset", offset);
    builder.queryParam("player", player.getId());
    builder.queryParam("duration", duration);
    if (bitRate != null) {
        builder.queryParam("maxBitRate", bitRate.getFirst());
        Dimension dimension = bitRate.getSecond();
        if (dimension != null) {
            builder.queryParam("size", dimension.width);
            builder.queryParam("x", dimension.height);
        }
    }
    jwtSecurityService.addJWTToken(builder);
    return builder.toUriString();
}
项目:lams    文件:RequestParamMethodArgumentResolver.java   
@Override
public void contributeMethodArgument(MethodParameter parameter, Object value,
        UriComponentsBuilder builder, Map<String, Object> uriVariables, ConversionService conversionService) {

    Class<?> paramType = parameter.getParameterType();
    if (Map.class.isAssignableFrom(paramType) || MultipartFile.class.equals(paramType) ||
            "javax.servlet.http.Part".equals(paramType.getName())) {
        return;
    }

    RequestParam annot = parameter.getParameterAnnotation(RequestParam.class);
    String name = StringUtils.isEmpty(annot.value()) ? parameter.getParameterName() : annot.value();

    if (value == null) {
        builder.queryParam(name);
    }
    else if (value instanceof Collection) {
        for (Object element : (Collection<?>) value) {
            element = formatUriValue(conversionService, TypeDescriptor.nested(parameter, 1), element);
            builder.queryParam(name, element);
        }
    }
    else {
        builder.queryParam(name, formatUriValue(conversionService, new TypeDescriptor(parameter), value));
    }
}
项目:atsea-sample-shop-app    文件:OrderController.java   
@SuppressWarnings({ "unchecked", "rawtypes" })
@RequestMapping(value = "/order/", method = RequestMethod.POST)
public ResponseEntity<?> createOrder(@RequestBody Order order, UriComponentsBuilder ucBuilder) {
    logger.info("Creating order : {}", order);

    if (orderService.orderExists(order)) {
        logger.error("Unable to create. An order with id {} already exist", order.getOrderId());
        return new ResponseEntity(new CustomErrorType("Unable to create. An order with id " + 
        order.getOrderId() + " already exists."),HttpStatus.CONFLICT);
    }

    Order currentOrder = orderService.createOrder(order);
    Long currentOrderId = currentOrder.getOrderId();
    JSONObject orderInfo = new JSONObject();
    orderInfo.put("orderId", currentOrderId);

    HttpHeaders headers = new HttpHeaders();
    headers.setLocation(ucBuilder.path("/api/order/").buildAndExpand(order.getOrderId()).toUri());
    return new ResponseEntity<JSONObject>(orderInfo, HttpStatus.CREATED);
}
项目:FastBootWeixin    文件:WxApiMethodInfo.java   
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);
}
项目:TARA-Server    文件:TaraProperties.java   
public String getLocaleUrl(String locale) throws Exception {
    UriComponentsBuilder builder = ServletUriComponentsBuilder.fromCurrentRequest().replaceQueryParam("locale", locale);
    RequestAttributes attributes = org.springframework.web.context.request.RequestContextHolder.currentRequestAttributes();
    if (attributes instanceof ServletRequestAttributes) {
        int statusCode = ((ServletRequestAttributes) attributes).getResponse().getStatus();
        switch (statusCode) {
            case 200:
                break;
            case 404:
                builder.replacePath("" + statusCode);
                break;
            default:
                builder.replacePath("error");
        }
    }
    URI serverUri = new URI(this.casConfigurationProperties.getServer().getName());
    if ("https".equalsIgnoreCase(serverUri.getScheme())) {
        builder.port((serverUri.getPort() == -1) ? 443 : serverUri.getPort());
    }
    return builder.scheme(serverUri.getScheme()).host(serverUri.getHost()).build(true).toUriString();
}
项目:spring-boot-tus    文件:StorageController.java   
@RequestMapping(method = RequestMethod.POST)
ResponseEntity<?> processPost(@RequestHeader("Upload-Length") Integer uploadLength,
                              UriComponentsBuilder uriComponentsBuilder,
                              HttpServletResponse response) throws Exception {

    log.debug("POST START");
    log.debug("Final-Length header value: " + Long.toString(uploadLength));

    if(uploadLength < 1){
        throw new TusBadRequestException("Wrong Final-Length Header");
    }

    if(uploadLength > Long.parseLong(environment.getProperty("tusserver.tusmaxsize"))){
        throw new TusBadRequestException("wrong Final-Length Header, max is: " + environment.getProperty("tusserver.tusmaxsize"));
    }

    TusFile file = new TusFile();
    file.setUploadLength(uploadLength);
    file.setOffset(0);
    file.setCompleted(false);
    file = repo.save(file);

    log.debug("POST END");

    response.setHeader("Access-Control-Expose-Headers", "Location, Tus-Resumable");
    response.setHeader("Location", uriComponentsBuilder.path("/" + file.getUuid()).build().toString());
    response.setHeader("Tus-Resumable", "1.0.0");
    response.setStatus(201);
    return null;
}
项目:lams    文件:CompositeUriComponentsContributor.java   
@Override
public void contributeMethodArgument(MethodParameter parameter, Object value,
        UriComponentsBuilder builder, Map<String, Object> uriVariables, ConversionService conversionService) {

    for (UriComponentsContributor contributor : this.contributors) {
        if (contributor.supportsParameter(parameter)) {
            contributor.contributeMethodArgument(parameter, value, builder, uriVariables, conversionService);
            break;
        }
    }
}
项目:Spring-Shiro-Spark    文件:AdminController.java   
@DeleteMapping(value = SUBPATH_USER + PATHVARIABLE_ID)
public ResponseEntity<Long> deleteUserById(UriComponentsBuilder uriComponentsBuilder,
                                                 @PathVariable long id){
    HttpHeaders headers = ApplicationUtil.getHttpHeaders(uriComponentsBuilder,PATH + SUBPATH_USER + "/" + id);
    userService.delUserById(id);
    return new ResponseEntity<Long>(id,headers,HttpStatus.OK);
}
项目:restdocs-raml    文件:RamlResourceSnippet.java   
private String getUriPath(Operation operation) {
    String urlTemplate = (String) operation.getAttributes().get(ATTRIBUTE_NAME_URL_TEMPLATE);
    if (StringUtils.isEmpty(urlTemplate)) {
        throw new MissingUrlTemplateException();
    }
    return UriComponentsBuilder.fromUriString(urlTemplate).build().getPath();
}
项目:REST-Web-Services    文件:RegisterController.java   
/**
 * This method activates the account with a token.
 *
 * @param token Account activation token
 * @param uriComponentsBuilder {@link UriComponentsBuilder}
 * @return The ModelAndView for sign in
 */
@GetMapping(value = "/thanks")
public
ModelAndView confirmAccount(
        @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/register/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");
}
项目:REST-Web-Services    文件:SettingsController.java   
/**
 * 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");
}
项目:REST-Web-Services    文件:MessageRestController.java   
@ApiOperation(value = "Create a message")
@ApiResponses(value = {
        @ApiResponse(code = 400, message = "Incorrect data in the form"),
        @ApiResponse(code = 403, message = "Forbidden command"),
        @ApiResponse(code = 409, message = "Conflict with user ID")
})
@PostMapping(consumes = MediaType.APPLICATION_JSON_VALUE)
@ResponseStatus(HttpStatus.CREATED)
public
ResponseEntity<Void> createMessage(
        @ApiParam(value = "New message", required = true)
        @RequestBody @Valid final SendMessageDTO sendMessageDTO,
        final UriComponentsBuilder uriComponentsBuilder
) {
    log.info("Called with {}", sendMessageDTO);

    this.validUsername(sendMessageDTO.getTo());

    this.messagePersistenceService.createMessage(this.authorizationService.getUserId(), sendMessageDTO);

    final UriComponents uriComponents
            = uriComponentsBuilder.path("/profile/{username}").buildAndExpand(sendMessageDTO.getTo());

    final HttpHeaders httpHeaders = new HttpHeaders();
    httpHeaders.setLocation(uriComponents.toUri());

    return new ResponseEntity<>(httpHeaders, HttpStatus.CREATED);
}
项目:gauravbytes    文件:UserController.java   
@PostMapping
public ResponseEntity<Void> createUser(@RequestBody User user, UriComponentsBuilder ucBuilder) {
    logger.info("Registering user: {} ", user);
    if (userService.userExists(user)) {
        logger.warn("User with username: {} already exists...", user.getUsername());
        return new ResponseEntity<Void>(HttpStatus.CONFLICT);
    }

    userService.saveUser(user);

    URI uri = ucBuilder.path("/users/{id}").buildAndExpand(user.getId()).toUri();
    return ResponseEntity.created(uri).build();
}
项目:REST-Web-Services    文件:RegisterRestController.java   
/**
 * Check ReCaptcha.
 *
 * @param reCaptcha ReCaptcha
 * @throws FormBadRequestException if the reCaptcha is incorrect
 */
private void validReCaptcha(final String reCaptcha) {
    final ValidationErrorDTO validationErrorDTO = new ValidationErrorDTO();

    if (reCaptcha == null || reCaptcha.equals("")) {
        validationErrorDTO.addFieldError("reCaptcha", this.bundle.getString("validation.notNull.reCaptcha"));
        throw new FormBadRequestException(validationErrorDTO);
    }

    try {
        final RestTemplate restTemplate = new RestTemplate();
        final HttpHeaders headers = new HttpHeaders();
        headers.set("Accept", MediaType.APPLICATION_JSON_VALUE);

        final UriComponentsBuilder builder = UriComponentsBuilder
                .fromHttpUrl(reCaptchaProperties.getApiUrl()).queryParam("secret", reCaptchaProperties.getSecretKey())
                .queryParam("response", reCaptcha);
        HttpEntity<String> entity = new HttpEntity<>(headers);

        final ResponseEntity<ReCaptchaResponse> response = restTemplate.exchange(builder
                        .build().encode().toUri(), HttpMethod.GET, entity,
                ReCaptchaResponse.class);

        if(!response.getStatusCode().toString().equals("200")) {
            validationErrorDTO.addFieldError("reCaptcha", bundle.getString("validation.incorrect.reCaptcha"));
            throw new FormBadRequestException(validationErrorDTO);
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}
项目:Spring-Shiro-Spark    文件:AdminController.java   
@PostMapping(value = SUBPATH_USER)
public ResponseEntity<UserDto> addUser(@RequestBody UserDto userDto,
                                       UriComponentsBuilder uriComponentsBuilder){
    HttpHeaders headers = ApplicationUtil.getHttpHeaders(uriComponentsBuilder,PATH + SUBPATH_USER);
    User user = convertToEntity(userDto);
    userService.addUser(user);
    return new ResponseEntity<UserDto>(headers,HttpStatus.OK);
}
项目:Settings    文件:EnvironmentsApi.java   
/**
 * 
 * 
 * <p><b>200</b> - Success
 * @param name The name parameter
 * @param parentEnvId The parentEnvId parameter
 * @return HierarchicalModel
 * @throws RestClientException if an error occurs while attempting to invoke the API
 */
public HierarchicalModel apiEnvironmentsAddParentparentEnvIdNewnamePost(String name, Integer parentEnvId) throws RestClientException {
    Object postBody = null;

    // verify the required parameter 'name' is set
    if (name == null) {
        throw new HttpClientErrorException(HttpStatus.BAD_REQUEST, "Missing the required parameter 'name' when calling apiEnvironmentsAddParentparentEnvIdNewnamePost");
    }

    // verify the required parameter 'parentEnvId' is set
    if (parentEnvId == null) {
        throw new HttpClientErrorException(HttpStatus.BAD_REQUEST, "Missing the required parameter 'parentEnvId' when calling apiEnvironmentsAddParentparentEnvIdNewnamePost");
    }

    // create path and map variables
    final Map<String, Object> uriVariables = new HashMap<String, Object>();
    uriVariables.put("name", name);
    uriVariables.put("parentEnvId", parentEnvId);
    String path = UriComponentsBuilder.fromPath("/api/environments/add/parent-{parentEnvId}/new-{name}").buildAndExpand(uriVariables).toUriString();

    final MultiValueMap<String, String> queryParams = new LinkedMultiValueMap<String, String>();
    final HttpHeaders headerParams = new HttpHeaders();
    final MultiValueMap<String, Object> formParams = new LinkedMultiValueMap<String, Object>();

    final String[] accepts = { 
        "text/plain", "application/json", "text/json"
    };
    final List<MediaType> accept = apiClient.selectHeaderAccept(accepts);
    final String[] contentTypes = { };
    final MediaType contentType = apiClient.selectHeaderContentType(contentTypes);

    String[] authNames = new String[] {  };

    ParameterizedTypeReference<HierarchicalModel> returnType = new ParameterizedTypeReference<HierarchicalModel>() {};
    return apiClient.invokeAPI(path, HttpMethod.POST, queryParams, postBody, headerParams, formParams, accept, contentType, authNames, returnType);
}
项目:Settings    文件:EnvironmentsApi.java   
/**
 * 
 * 
 * <p><b>200</b> - Success
 * @param environmentName The environmentName parameter
 * @return HierarchicalModel
 * @throws RestClientException if an error occurs while attempting to invoke the API
 */
public HierarchicalModel apiEnvironmentsByEnvironmentNameGet(String environmentName) throws RestClientException {
    Object postBody = null;

    // verify the required parameter 'environmentName' is set
    if (environmentName == null) {
        throw new HttpClientErrorException(HttpStatus.BAD_REQUEST, "Missing the required parameter 'environmentName' when calling apiEnvironmentsByEnvironmentNameGet");
    }

    // create path and map variables
    final Map<String, Object> uriVariables = new HashMap<String, Object>();
    uriVariables.put("environmentName", environmentName);
    String path = UriComponentsBuilder.fromPath("/api/environments/{environmentName}").buildAndExpand(uriVariables).toUriString();

    final MultiValueMap<String, String> queryParams = new LinkedMultiValueMap<String, String>();
    final HttpHeaders headerParams = new HttpHeaders();
    final MultiValueMap<String, Object> formParams = new LinkedMultiValueMap<String, Object>();

    final String[] accepts = { 
        "text/plain", "application/json", "text/json"
    };
    final List<MediaType> accept = apiClient.selectHeaderAccept(accepts);
    final String[] contentTypes = { };
    final MediaType contentType = apiClient.selectHeaderContentType(contentTypes);

    String[] authNames = new String[] {  };

    ParameterizedTypeReference<HierarchicalModel> returnType = new ParameterizedTypeReference<HierarchicalModel>() {};
    return apiClient.invokeAPI(path, HttpMethod.GET, queryParams, postBody, headerParams, formParams, accept, contentType, authNames, returnType);
}
项目:Spring-Shiro-Spark    文件:AdminController.java   
@DeleteMapping(value = SUBPATH_ROLE + PATHVARIABLE_ID)
public ResponseEntity<Long> deleteRoleById(UriComponentsBuilder uriComponentsBuilder,
                                                 @PathVariable long id){
    HttpHeaders headers = ApplicationUtil.getHttpHeaders(uriComponentsBuilder,PATH + SUBPATH_ROLE + "/" + id);
    roleService.delRoleById(id);
    return new ResponseEntity<Long>(id,headers,HttpStatus.OK);
}
项目:simple-openid-provider    文件:ClientRegistrationConfiguration.java   
private String registrationUriTemplate() {
    // @formatter:off
    return UriComponentsBuilder.fromHttpUrl(this.properties.getIssuer().getValue())
            .path(ClientRegistrationEndpoint.PATH_MAPPING)
            .path("/{id}")
            .build()
            .toUriString();
    // @formatter:on
}
项目:FastBootWeixin    文件:WxApiTypeInfo.java   
/**
 * @param clazz       代理类
 * @param defaultHost 默认host
 */
public WxApiTypeInfo(Class clazz, String defaultHost) {
    this.clazz = clazz;
    WxApiRequest wxApiRequest = AnnotatedElementUtils.findMergedAnnotation(clazz, WxApiRequest.class);
    String host = getTypeWxApiHost(wxApiRequest, defaultHost);
    String typePath = getTypeWxApiRequestPath(wxApiRequest);
    // 固定https请求
    propertyPrefix = getTypeWxApiPropertyPrefix(wxApiRequest);
    baseBuilder = UriComponentsBuilder.newInstance().scheme("https").host(host).path(typePath);
}
项目:mirrorgate    文件:SlackServiceImpl.java   
@Override
public SlackDTO getToken(String team, String client_id, String client_secret, String code) {
    UriComponents uri = UriComponentsBuilder.newInstance()
            .scheme("https")
            .host(team + ".slack.com")
            .path("/api/oauth.access")
            .queryParam("client_id", client_id)
            .queryParam("client_secret", client_secret)
            .queryParam("code", code)
            .build()
            .encode();

    return restTemplate.getForObject(uri.toUriString(), SlackDTO.class);
}
项目:mirrorgate    文件:SlackServiceImpl.java   
@Override
public SlackDTO getWebSocket(String team, String token) {

    UriComponents uri = UriComponentsBuilder.newInstance()
            .scheme("https")
            .host(team + ".slack.com")
            .path("/api/rtm.connect")
            .queryParam("token", token)
            .build()
            .encode();

    return restTemplate.getForObject(uri.toUriString(), SlackDTO.class);
}
项目:springboot-shiro-cas-mybatis    文件:FrontChannelLogoutAction.java   
@Override
protected Event doInternalExecute(final HttpServletRequest request, final HttpServletResponse response,
        final RequestContext context) throws Exception {

    final List<LogoutRequest> logoutRequests = WebUtils.getLogoutRequests(context);
    final Integer startIndex = getLogoutIndex(context);
    if (logoutRequests != null) {
        for (int i = startIndex; i < logoutRequests.size(); i++) {
            final LogoutRequest logoutRequest = logoutRequests.get(i);
            if (logoutRequest.getStatus() == LogoutRequestStatus.NOT_ATTEMPTED) {
                // assume it has been successful
                logoutRequest.setStatus(LogoutRequestStatus.SUCCESS);

                // save updated index
                putLogoutIndex(context, i + 1);

                final String logoutUrl = logoutRequest.getLogoutUrl().toExternalForm();
                LOGGER.debug("Using logout url [{}] for front-channel logout requests", logoutUrl);

                final String logoutMessage = logoutManager.createFrontChannelLogoutMessage(logoutRequest);
                LOGGER.debug("Front-channel logout message to send under [{}] is [{}]",
                        this.logoutRequestParameter, logoutMessage);

                // redirect to application with SAML logout message
                final UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(logoutUrl);
                builder.queryParam(this.logoutRequestParameter, URLEncoder.encode(logoutMessage, "UTF-8"));

                return result(REDIRECT_APP_EVENT, DEFAULT_FLOW_ATTRIBUTE_LOGOUT_URL, builder.build().toUriString());
            }
        }
    }

    // no new service with front-channel logout -> finish logout
    return new Event(this, FINISH_EVENT);
}
项目:springboot-shiro-cas-mybatis    文件:FrontChannelLogoutAction.java   
@Override
protected Event doInternalExecute(final HttpServletRequest request, final HttpServletResponse response,
        final RequestContext context) throws Exception {

    final List<LogoutRequest> logoutRequests = WebUtils.getLogoutRequests(context);
    final Integer startIndex = getLogoutIndex(context);
    if (logoutRequests != null) {
        for (int i = startIndex; i < logoutRequests.size(); i++) {
            final LogoutRequest logoutRequest = logoutRequests.get(i);
            if (logoutRequest.getStatus() == LogoutRequestStatus.NOT_ATTEMPTED) {
                // assume it has been successful
                logoutRequest.setStatus(LogoutRequestStatus.SUCCESS);

                // save updated index
                putLogoutIndex(context, i + 1);

                final String logoutUrl = logoutRequest.getLogoutUrl().toExternalForm();
                LOGGER.debug("Using logout url [{}] for front-channel logout requests", logoutUrl);

                final String logoutMessage = logoutManager.createFrontChannelLogoutMessage(logoutRequest);
                LOGGER.debug("Front-channel logout message to send under [{}] is [{}]",
                        this.logoutRequestParameter, logoutMessage);

                // redirect to application with SAML logout message
                final UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(logoutUrl);
                builder.queryParam(this.logoutRequestParameter, URLEncoder.encode(logoutMessage, "UTF-8"));

                return result(REDIRECT_APP_EVENT, DEFAULT_FLOW_ATTRIBUTE_LOGOUT_URL, builder.build().toUriString());
            }
        }
    }

    // no new service with front-channel logout -> finish logout
    return new Event(this, FINISH_EVENT);
}
项目:FRDRV    文件:OfferParser.java   
private StarcarOffer parseStarcars(Elements elements, String url) {
    String id = UriComponentsBuilder.fromHttpUrl(url).build().getQueryParams().getFirst("offer");
    if (elements != null && elements.size() == 5) {
        return getStarcarOfferWithoutAge(elements, url, id);
    }
    if (elements != null && elements.size() == 6) {
        return getStarcarOfferWithAge(elements, url, id);
    }
    return null;
}
项目:Spring-Shiro-Spark    文件:JobController.java   
@PostMapping(value = SUBPATH_WORDCOUNT)
public ResponseEntity<List<Count>> getCounts(@RequestBody TextDto words,
                                             UriComponentsBuilder uriComponentsBuilder) throws ResultException{
    HttpHeaders headers = ApplicationUtil.getHttpHeaders(uriComponentsBuilder,PATH);
    Subject subject = SecurityUtils.getSubject();
    /**if(!subject.isPermitted("WORDCOUNT:CREATE")){
        throw  new ResultException("fuck shiro");
    } else {
        throw  new ResultException("fuck");
    }*/
    return new ResponseEntity<>(wordCountService.wordCount(words.getWords()),HttpStatus.OK);
}
项目:cereebro    文件:EurekaMetadataPopulator.java   
/**
 * Get the endpoint location of the current cereebro instance.
 * 
 * @return Absolute Snitch URI.
 */
protected URI getEndpointUri() {
    if (!StringUtils.isEmpty(properties.getEndpointUrl())) {
        return URI.create(properties.getEndpointUrl());
    }
    // @formatter:off
    return UriComponentsBuilder.newInstance()
            .scheme("http")
            .host(appInfoManager.getEurekaInstanceConfig().getHostName(true))
            .port(appInfoManager.getEurekaInstanceConfig().getNonSecurePort())
            .path(StringUtils.isEmpty(properties.getEndpointUrlPath()) ? snitch.getUri().toString() : properties.getEndpointUrlPath())
            .build()
            .toUri();
    // @formatter:on
}
项目:FastBootWeixin    文件:WxMediaResource.java   
public void setURL(URI uri) {
    try {
        this.url = uri.toURL();
    } catch (MalformedURLException e) {
        // ignore it
    }
    this.mediaId = UriComponentsBuilder.fromUri(uri).build().getQueryParams().getFirst("media_id");
}
项目:mirrorgate-jira-stories-collector    文件:SprintService.java   
public ResponseEntity<List> sendIssues(List<IssueDTO> issues) {
    MultiValueMap<String, String> params = new LinkedMultiValueMap<String, String>();
    params.set("collectorId", collectorId);

    UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(mirrorGateUrl + MIRROR_GATE_SEND_ISSUES_ENDPOINT).queryParams(params);

    return restTemplate.postForEntity(builder.build().toUriString(), issues, List.class);
}