Java Code Examples for org.springframework.web.util.UriComponentsBuilder#fromHttpUrl()

The following examples show how to use org.springframework.web.util.UriComponentsBuilder#fromHttpUrl() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: OpencpsRestFacade.java    From opencps-v2 with GNU Affero General Public License v3.0 7 votes vote down vote up
/**
 * Helper method to build the url if the url is static and doesn't change
 *
 * @param httpUrl
 * @param pathComplete
 * @param queryParams
 * @return
 */
protected static String buildUrl(String httpUrl, String pathComplete, HashMap<String, String> queryParams) {
	UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(httpUrl);

	builder.path(pathComplete);

	if (null != queryParams) {
		// build the URL with all the params it needs
		builder = buildUrlParams(builder, queryParams);
	}

	UriComponents uriComponents = builder.build();
	return uriComponents.toString();
}
 
Example 2
Source File: GithubAuthServiceImpl.java    From SENS with GNU General Public License v3.0 6 votes vote down vote up
@Override
public Response<String> getOpenId(String accessToken) {
    String url = String.format(USER_INFO_URL, accessToken);
    UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(url);
    URI uri = builder.build().encode().toUri();
    String resp;
    try {
        resp = getRestTemplate().getForObject(uri, String.class);
    } catch (Exception e) {
        log.error("GitHub获得OpenId失败, cause:{}", e);
        return Response.no("access_token无效!");
    }
    if (resp != null && resp.contains("id")) {
        JSONObject data = JSONObject.parseObject(resp);
        String openid = data.getString("id");
        return Response.yes(openid);
    }
    log.error("GitHub获得openid失败,resp:{}", resp);
    return Response.no();
}
 
Example 3
Source File: GithubOAuth2Template.java    From pre with GNU General Public License v3.0 6 votes vote down vote up
@Override
protected AccessGrant postForAccessGrant(String accessTokenUrl, MultiValueMap<String, String> parameters) {

    RestTemplate restTemplate = new RestTemplate();
    // 自己拼接url
    String clientId = parameters.getFirst("client_id");
    String clientSecret = parameters.getFirst("client_secret");
    String code = parameters.getFirst("code");

    String url = String.format("https://github.com/login/oauth/access_token?client_id=%s&client_secret=%s&code=%s", clientId, clientSecret, code);
    UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(url);
    URI uri = builder.build().encode().toUri();
    String responseStr = restTemplate.getForObject(uri, String.class);
    logger.info("获取accessToke的响应:" + responseStr);
    String[] items = StringUtils.splitByWholeSeparatorPreserveAllTokens(responseStr, "&");
    String accessToken = StringUtils.substringAfterLast(items[0], "=");
    logger.info("获取Toke的响应:" + accessToken);
    return new AccessGrant(accessToken, null, null, null);
}
 
Example 4
Source File: DefaultSkipperClient.java    From spring-cloud-skipper with Apache License 2.0 6 votes vote down vote up
@Override
public Collection<Repository> listRepositories() {
	ParameterizedTypeReference<HateoasResponseWrapper<RepositoriesResponseWrapper>> typeReference =
			new ParameterizedTypeReference<HateoasResponseWrapper<RepositoriesResponseWrapper>>() { };
	UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(baseUri + "/repositories");
	builder.queryParam("size", "2000");

	ResponseEntity<HateoasResponseWrapper<RepositoriesResponseWrapper>> resourceResponseEntity =
			restTemplate.exchange(builder.toUriString(),
					HttpMethod.GET,
					null,
					typeReference);
	RepositoriesResponseWrapper embedded = resourceResponseEntity.getBody().getEmbedded();
	if (embedded != null) {
		return embedded.getRepositories();
	}
	else {
		return Collections.emptyList();
	}
}
 
Example 5
Source File: TestKvmReconnectMe.java    From zstack with Apache License 2.0 6 votes vote down vote up
@Test
public void test() throws InterruptedException {
    config.connectCmds.clear();

    UriComponentsBuilder ub = UriComponentsBuilder.fromHttpUrl(restf.getBaseUrl());
    ub.path(RESTConstant.COMMAND_CHANNEL_PATH);
    String url = ub.build().toUriString();
    Map<String, String> header = map(e(RESTConstant.COMMAND_PATH, KVMConstant.KVM_RECONNECT_ME));

    HostInventory host = deployer.hosts.get("host1");
    ReconnectMeCmd cmd = new ReconnectMeCmd();
    cmd.hostUuid = host.getUuid();
    cmd.reason = "on purpose";
    restf.syncJsonPost(url, JSONObjectUtil.toJsonString(cmd), header, String.class);
    TimeUnit.SECONDS.sleep(3);
    Assert.assertEquals(1, config.connectCmds.size());
}
 
Example 6
Source File: QQAuthServiceImpl.java    From SENS with GNU General Public License v3.0 6 votes vote down vote up
@Override
public Response<String> getAccessToken(String code) {
    String APP_ID = SensConst.OPTIONS.get(BlogPropertiesEnum.bind_qq_app_id.getProp());
    String APP_SECRET = SensConst.OPTIONS.get(BlogPropertiesEnum.bind_qq_app_secret.getProp());
    String CALLBACK_URL = SensConst.OPTIONS.get(BlogPropertiesEnum.bind_qq_callback.getProp());
    String url = String.format(ACCESS_TOKEN_URL, APP_ID, APP_SECRET, code, CALLBACK_URL);
    UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(url);
    URI uri = builder.build().encode().toUri();

    String resp = getRestTemplate().getForObject(uri, String.class);
    if (resp != null && resp.contains("access_token")) {
        Map<String, String> map = getParam(resp);
        String access_token = map.get("access_token");
        return Response.yes(access_token);
    }
    log.error("QQ获得access_token失败,resp:{}", resp);
    return Response.no();
}
 
Example 7
Source File: GithubAuthServiceImpl.java    From SENS with GNU General Public License v3.0 6 votes vote down vote up
@Override
public Response<BindUserDTO> getUserInfo(String accessToken, String openId) {

    String url = String.format(USER_INFO_URL, accessToken);
    UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(url);
    URI uri = builder.build().encode().toUri();
    String resp;
    try {
        resp = getRestTemplate().getForObject(uri, String.class);
    } catch (Exception e) {
        log.error("GitHub获得用户信息失败,access_token无效, cause:{}", e);
        return Response.no("access_token无效!");
    }
    if (resp != null && resp.contains("id")) {
        JSONObject data = JSONObject.parseObject(resp);
        BindUserDTO result = new BindUserDTO();
        result.setOpenId(data.getString("id"));
        result.setAvatar(data.getString("avatar_url"));
        result.setNickname(data.getString("name"));
        return Response.yes(result);
    }
    log.error("GitHub获得用户信息失败,resp:{}", resp);
    return Response.no();
}
 
Example 8
Source File: RESTFacadeImpl.java    From zstack with Apache License 2.0 5 votes vote down vote up
void init() {
    port =  Integer.parseInt(System.getProperty("RESTFacade.port", "8080"));

    IptablesUtils.insertRuleToFilterTable(String.format("-A INPUT -p tcp -m state --state NEW -m tcp --dport %s -j ACCEPT", port));

    if ("AUTO".equals(hostname)) {
        callbackHostName = Platform.getManagementServerIp();
    } else {
        callbackHostName = hostname.trim();
    }

    String url;
    if ("".equals(path) || path == null) {
        url = String.format("http://%s:%s", callbackHostName, port);
    } else {
        url = String.format("http://%s:%s/%s", callbackHostName, port, path);
    }
    UriComponentsBuilder ub = UriComponentsBuilder.fromHttpUrl(url);
    ub.path(RESTConstant.CALLBACK_PATH);
    callbackUrl = ub.build().toUriString();

    ub = UriComponentsBuilder.fromHttpUrl(url);
    baseUrl = ub.build().toUriString();

    ub = UriComponentsBuilder.fromHttpUrl(url);
    ub.path(RESTConstant.COMMAND_CHANNEL_PATH);
    sendCommandUrl = ub.build().toUriString();

    logger.debug(String.format("RESTFacade built callback url: %s", callbackUrl));
    template = RESTFacade.createRestTemplate(CoreGlobalProperty.REST_FACADE_READ_TIMEOUT, CoreGlobalProperty.REST_FACADE_CONNECT_TIMEOUT);
}
 
Example 9
Source File: BirtStatisticsServiceImpl.java    From openemm with GNU Affero General Public License v3.0 5 votes vote down vote up
@Override
public String generateUrlWithParamsForExternalAccess(Map<String, Object> parameters) {
	String birtUrl = getBirtUrl(false);
	
       UriComponentsBuilder uriBuilder = UriComponentsBuilder.fromHttpUrl(birtUrl);
       parameters.forEach(uriBuilder::queryParam);
       return uriBuilder.toUriString();
}
 
Example 10
Source File: AviApi.java    From sdk with Apache License 2.0 5 votes vote down vote up
public String buildApiParams(String path, Map<String, String> params) {
	UriComponentsBuilder uriBuilder = UriComponentsBuilder.fromHttpUrl(restTemplate.getUriTemplateHandler().expand("/").toString().concat(path));
	if (null != params) {
		for(String key: params.keySet()) {
			uriBuilder.queryParam(key, params.get(key));
		}
	}
	return uriBuilder.toUriString();
}
 
Example 11
Source File: QQAuthServiceImpl.java    From open-cloud with MIT License 5 votes vote down vote up
@Override
public String getOpenId(String accessToken) {
    String url = String.format(OPEN_ID_URL, accessToken);
    UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(url);
    URI uri = builder.build().encode().toUri();
    String resp = restTemplate.getForObject(uri, String.class);
    if (resp != null && resp.contains("openid")) {
        JSONObject jsonObject = ConvertToJson(resp);
        String openid = jsonObject.getString("openid");
        return openid;
    }
    log.error("QQ获得openid失败,accessToken无效,resp:{}", resp);
    return null;
}
 
Example 12
Source File: LoginUrlAuthenticationEntryPoint.java    From graviteeio-access-management with Apache License 2.0 5 votes vote down vote up
@Override
protected String buildRedirectUrlToLoginPage(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) {
    String url = super.buildRedirectUrlToLoginPage(request, response, authException);

    UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(url);

    String scheme = request.getHeader(HttpHeaders.X_FORWARDED_PROTO);
    if (scheme != null && !scheme.isEmpty()) {
        builder.scheme(scheme);
    }

    String host = request.getHeader(HttpHeaders.X_FORWARDED_HOST);
    if (host != null && !host.isEmpty()) {
        if (host.contains(":")) {
            // Forwarded host contains both host and port
            String [] parts = host.split(":");
            builder.host(parts[0]);
            builder.port(parts[1]);
        } else {
            builder.host(host);
        }
    }

    // handle forwarded path
    String forwardedPath = request.getHeader(X_FORWARDED_PREFIX);
    if (forwardedPath != null && !forwardedPath.isEmpty()) {
        String path = builder.build().getPath();
        // remove trailing slash
        forwardedPath = forwardedPath.substring(0, forwardedPath.length() - (forwardedPath.endsWith("/") ? 1 : 0));
        builder.replacePath(forwardedPath + path);
    }

    return builder.toUriString();
}
 
Example 13
Source File: URLBuilder.java    From zstack with Apache License 2.0 5 votes vote down vote up
public static String buildUrlFromBase(String baseUrl, String...paths) {
    UriComponentsBuilder ub = UriComponentsBuilder.fromHttpUrl(baseUrl);
    for (String p : paths) {
        ub.path(p);
    }
    return ub.build().toString();
}
 
Example 14
Source File: FrontChannelLogoutAction.java    From cas4.0.x-server-wechat with Apache License 2.0 5 votes vote down vote up
@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 && startIndex != 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);

                // redirect to application with SAML logout message
                final UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(logoutRequest.getService().getId());
                builder.queryParam("SAMLRequest",
                        URLEncoder.encode(logoutManager.createFrontChannelLogoutMessage(logoutRequest), "UTF-8"));
                return result(REDIRECT_APP_EVENT, "logoutUrl", builder.build().toUriString());
            }
        }
    }

    // no new service with front-channel logout -> finish logout
    return new Event(this, FINISH_EVENT);
}
 
Example 15
Source File: DefaultSkipperClient.java    From spring-cloud-skipper with Apache License 2.0 5 votes vote down vote up
@Override
public Map<String, Map<String, DeploymentState>> states(String... releaseNames) {
	ParameterizedTypeReference<Map<String, Map<String, DeploymentState>>> typeReference =
			new ParameterizedTypeReference<Map<String, Map<String, DeploymentState>>>() { };

	UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(baseUri + "/release/states");
	builder.queryParam("names", StringUtils.arrayToCommaDelimitedString(releaseNames));

	ResponseEntity<Map<String, Map<String, DeploymentState>>> responseEntity =
			restTemplate.exchange(builder.toUriString(),
					HttpMethod.GET,
					null,
					typeReference);
	return responseEntity.getBody();
}
 
Example 16
Source File: DefaultSkipperClient.java    From spring-cloud-skipper with Apache License 2.0 5 votes vote down vote up
@Override
public Collection<PackageMetadata> search(String name, boolean details) {
	ParameterizedTypeReference<HateoasResponseWrapper<PackageMetadatasResponseWrapper>> typeReference =
			new ParameterizedTypeReference<HateoasResponseWrapper<PackageMetadatasResponseWrapper>>() { };
	Map<String, String> uriVariables = new HashMap<String, String>();
	uriVariables.put("size", "2000");
	String url = baseUri + "/packageMetadata";
	UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(url);
	builder.queryParam("size", "2000");
	if (StringUtils.hasText(name)) {
		uriVariables.put("name", name);
		builder.pathSegment("search", "findByNameContainingIgnoreCase");
		builder.queryParam("name", name);
	}
	if (!details) {
		builder.queryParam("projection", "summary");
		builder.queryParam("sort", "name,asc");
	}

	ResponseEntity<HateoasResponseWrapper<PackageMetadatasResponseWrapper>> resourceResponseEntity =
			restTemplate.exchange(builder.toUriString(),
					HttpMethod.GET,
					null,
					typeReference,
					uriVariables);
	PackageMetadatasResponseWrapper embedded = resourceResponseEntity.getBody().getEmbedded();
	if (embedded != null) {
		return embedded.getPackageMetadata();
	}
	else {
		return Collections.emptyList();
	}
}
 
Example 17
Source File: RestServer.java    From zstack with Apache License 2.0 5 votes vote down vote up
private void sendMessage(APIMessage msg, Api api, HttpServletResponse rsp) throws IOException, IllegalAccessException, NoSuchMethodException, InvocationTargetException {
    if (msg instanceof APISyncCallMessage) {
        MessageReply reply = bus.call(msg);
        sendReplyResponse(reply, api, rsp);
    } else {
        RequestData d = new RequestData();
        d.apiMessage = msg;
        d.requestInfo = requestInfo.get();
        List<String> webHook = requestInfo.get().headers.get(RestConstants.HEADER_WEBHOOK);
        if (webHook != null && !webHook.isEmpty()) {
            d.webHook = webHook.get(0);
        }

        asyncStore.save(d);
        UriComponentsBuilder ub = UriComponentsBuilder.fromHttpUrl(restf.getBaseUrl());
        ub.path(RestConstants.API_VERSION);
        ub.path(RestConstants.ASYNC_JOB_PATH);
        ub.path("/" + msg.getId());

        ApiResponse response = new ApiResponse();
        response.setLocation(ub.build().toUriString());

        bus.send(msg);

        sendResponse(HttpStatus.ACCEPTED.value(), response, rsp);
    }
}
 
Example 18
Source File: MethodToUrlTest.java    From FastBootWeixin with Apache License 2.0 4 votes vote down vote up
public static void main(String[] args) throws JsonProcessingException {
    UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl("http://api.wx.com");
    MvcUriComponentsBuilder.fromMethod(builder, WxBuildinVerifyService.class, ClassUtils.getMethod(WxBuildinVerifyService.class, "verify", null), "a", "a", "a", "a");
    System.out.println(builder);
}
 
Example 19
Source File: XForwardedAwareRedirectStrategy.java    From graviteeio-access-management with Apache License 2.0 4 votes vote down vote up
@Override
public void sendRedirect(HttpServletRequest request, HttpServletResponse response, String url) throws IOException {
    String redirectUrl = calculateRedirectUrl(request.getContextPath(), url);

    UriComponentsBuilder builder;
    if (UrlUtils.isAbsoluteUrl(redirectUrl)) {
        builder = UriComponentsBuilder.fromHttpUrl(redirectUrl);
    } else {
        builder = UriComponentsBuilder.fromUriString(redirectUrl);
    }

    String scheme = request.getHeader(HttpHeaders.X_FORWARDED_PROTO);
    if (scheme != null && !scheme.isEmpty()) {
        builder.scheme(scheme);
    }

    String host = request.getHeader(HttpHeaders.X_FORWARDED_HOST);
    if (host != null && !host.isEmpty()) {
        if (host.contains(":")) {
            // Forwarded host contains both host and port
            String [] parts = host.split(":");
            builder.host(parts[0]);
            builder.port(parts[1]);
        } else {
            builder.host(host);
        }
    }

    // handle forwarded path
    String forwardedPath = request.getHeader(X_FORWARDED_PREFIX);
    if (forwardedPath != null && !forwardedPath.isEmpty()) {
        String path = builder.build().getPath();
        // remove trailing slash
        forwardedPath = forwardedPath.substring(0, forwardedPath.length() - (forwardedPath.endsWith("/") ? 1 : 0));
        builder.replacePath(forwardedPath + path);
    }

    redirectUrl = response.encodeRedirectURL(builder.build(false).toUriString());

    if (logger.isDebugEnabled()) {
        logger.debug("Redirecting to '{}'", redirectUrl);
    }

    response.sendRedirect(redirectUrl);
}
 
Example 20
Source File: TestKvmVmTracer.java    From zstack with Apache License 2.0 4 votes vote down vote up
@Test
public void test() throws InterruptedException {
    VmInstanceInventory vm = deployer.vms.get("TestVm");
    String hostUuid = vm.getHostUuid();

    HostCapacityVO cap1 = dbf.findByUuid(hostUuid, HostCapacityVO.class);
    ReportVmStateCmd cmd = new ReportVmStateCmd();
    cmd.hostUuid = hostUuid;
    cmd.vmState = KvmVmState.Shutdown.toString();
    cmd.vmUuid = vm.getUuid();
    Map<String, String> header = map(e(RESTConstant.COMMAND_PATH, KVMConstant.KVM_REPORT_VM_STATE));

    UriComponentsBuilder ub = UriComponentsBuilder.fromHttpUrl(restf.getBaseUrl());
    ub.path(RESTConstant.COMMAND_CHANNEL_PATH);
    String url = ub.build().toUriString();

    restf.syncJsonPost(url, JSONObjectUtil.toJsonString(cmd), header, String.class);
    TimeUnit.SECONDS.sleep(3);

    VmInstanceVO vmvo = dbf.findByUuid(vm.getUuid(), VmInstanceVO.class);
    Assert.assertEquals(VmInstanceState.Stopped, vmvo.getState());
    Assert.assertNull(vmvo.getHostUuid());

    long cpu = vmvo.getCpuNum();
    HostCapacityVO cap2 = dbf.findByUuid(hostUuid, HostCapacityVO.class);
    Assert.assertEquals(cap2.getAvailableCpu(), cap1.getAvailableCpu() + cpu);
    Assert.assertEquals(cap2.getAvailableMemory(), cap1.getAvailableMemory() + vmvo.getMemorySize());

    cmd.vmState = KvmVmState.Running.toString();
    restf.syncJsonPost(url, JSONObjectUtil.toJsonString(cmd), header, String.class);
    TimeUnit.SECONDS.sleep(3);
    vmvo = dbf.findByUuid(vm.getUuid(), VmInstanceVO.class);
    Assert.assertEquals(VmInstanceState.Running, vmvo.getState());
    Assert.assertEquals(hostUuid, vmvo.getHostUuid());
    cap2 = dbf.findByUuid(hostUuid, HostCapacityVO.class);
    Assert.assertEquals(cap2.getAvailableCpu(), cap1.getAvailableCpu());
    Assert.assertEquals(cap2.getAvailableMemory(), cap1.getAvailableMemory());

    HostInventory host2 = deployer.hosts.get("host2");
    cmd = new ReportVmStateCmd();
    cmd.hostUuid = host2.getUuid();
    cmd.vmState = KvmVmState.Running.toString();
    cmd.vmUuid = vm.getUuid();
    restf.syncJsonPost(url, JSONObjectUtil.toJsonString(cmd), header, String.class);
    TimeUnit.SECONDS.sleep(3);
    vmvo = dbf.findByUuid(vm.getUuid(), VmInstanceVO.class);
    Assert.assertEquals(VmInstanceState.Running, vmvo.getState());
    Assert.assertEquals(host2.getUuid(), vmvo.getHostUuid());
    HostCapacityVO host1cap = dbf.findByUuid(hostUuid, HostCapacityVO.class);
    Assert.assertEquals(host1cap.getAvailableCpu(), cap1.getAvailableCpu() + cpu);
    Assert.assertEquals(host1cap.getAvailableMemory(), cap1.getAvailableMemory() + vmvo.getMemorySize());

    HostCapacityVO host2cap = dbf.findByUuid(host2.getUuid(), HostCapacityVO.class);
    Assert.assertEquals(host2cap.getAvailableCpu(), host2cap.getTotalCpu() - cpu);
    Assert.assertEquals(host2cap.getAvailableMemory(), host2cap.getTotalMemory() - vmvo.getMemorySize());

    cmd.vmState = KvmVmState.Paused.toString();
    restf.syncJsonPost(url, JSONObjectUtil.toJsonString(cmd), header, String.class);
    TimeUnit.SECONDS.sleep(3);
    vmvo = dbf.findByUuid(vm.getUuid(), VmInstanceVO.class);
    Assert.assertEquals(VmInstanceState.Paused, vmvo.getState());
    Assert.assertEquals(host2.getUuid(), vmvo.getHostUuid());
}