Java Code Examples for javax.ws.rs.core.UriBuilder#build()

The following examples show how to use javax.ws.rs.core.UriBuilder#build() . 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: BaseRoleConnectHelper.java    From emodb with Apache License 2.0 6 votes vote down vote up
protected List<?> httpGetServicePortAsList(Map<String, Object> params, String... segments) throws Exception {

        Client client = getClient();
        UriBuilder builder = EmoUriBuilder.fromUri(URI.create(getServiceBaseURI()));
        builder.segment(segments);
        for (String lvalue : params.keySet()) {
            builder.queryParam(lvalue, params.get(lvalue));
        }

        URI uri = builder.build();
        System.out.println (uri.toASCIIString());

        return client.resource(uri)
                .accept(MediaType.APPLICATION_JSON_TYPE)
                .get(List.class);
    }
 
Example 2
Source File: DatabusClient.java    From emodb with Apache License 2.0 6 votes vote down vote up
@Override
public String replayAsyncSince(String apiKey, String subscription, Date since) {
    checkNotNull(subscription, "subscription");
    try {
        UriBuilder uriBuilder = _databus.clone().segment(subscription, "replay");
        if (since != null) {
            SimpleDateFormat dateFmt = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZZZ");
            dateFmt.setTimeZone(TimeZone.getTimeZone("UTC"));
            uriBuilder.queryParam("since", dateFmt.format(since));
        }
        URI uri = uriBuilder.build();
        Map<String, Object> response = _client.resource(uri)
                .header(ApiKeyRequest.AUTHENTICATION_HEADER, apiKey)
                .post(new TypeReference<Map<String, Object>>(){}, null);
        return response.get("id").toString();
    } catch (EmoClientException e) {
        throw convertException(e);
    }
}
 
Example 3
Source File: FilterRestServiceImpl.java    From camunda-bpm-platform with Apache License 2.0 6 votes vote down vote up
public ResourceOptionsDto availableOperations(UriInfo context) {

    UriBuilder baseUriBuilder = context.getBaseUriBuilder()
      .path(relativeRootResourcePath)
      .path(FilterRestService.PATH);

    ResourceOptionsDto resourceOptionsDto = new ResourceOptionsDto();

    // GET /
    URI baseUri = baseUriBuilder.build();
    resourceOptionsDto.addReflexiveLink(baseUri, HttpMethod.GET, "list");

    // GET /count
    URI countUri = baseUriBuilder.clone().path("/count").build();
    resourceOptionsDto.addReflexiveLink(countUri, HttpMethod.GET, "count");

    // POST /create
    if (isAuthorized(CREATE)) {
      URI createUri = baseUriBuilder.clone().path("/create").build();
      resourceOptionsDto.addReflexiveLink(createUri, HttpMethod.POST, "create");
    }

    return resourceOptionsDto;
  }
 
Example 4
Source File: OidcRpAuthenticationFilter.java    From cxf with Apache License 2.0 6 votes vote down vote up
public void filter(ContainerRequestContext rc) {
    if (checkSecurityContext(rc)) {
        return;
    } else if (redirectUri != null) {
        final UriBuilder redirectBuilder;
        if (redirectUri.startsWith("/")) {
            String basePath = (String)mc.get("http.base.path");
            redirectBuilder = UriBuilder.fromUri(basePath).path(redirectUri);
        } else if (redirectUri.startsWith("http")) {
            redirectBuilder = UriBuilder.fromUri(URI.create(redirectUri));
        } else {
            redirectBuilder = rc.getUriInfo().getBaseUriBuilder().path(redirectUri);
        }
        if (addRequestUriAsRedirectQuery) {
            redirectBuilder.queryParam("state", rc.getUriInfo().getRequestUri().toString());
        }
        URI redirectAddress = redirectBuilder.build();
        rc.abortWith(Response.seeOther(redirectAddress)
                       .header(HttpHeaders.CACHE_CONTROL, "no-cache, no-store")
                       .header("Pragma", "no-cache")
                       .build());
    } else {
        rc.abortWith(Response.status(401).build());
    }
}
 
Example 5
Source File: AbstractClient.java    From cxf with Apache License 2.0 6 votes vote down vote up
private URI calculateNewRequestURI(URI newBaseURI, URI requestURI, boolean proxy) {
    String baseURIPath = newBaseURI.getRawPath();
    String reqURIPath = requestURI.getRawPath();

    UriBuilder builder = new UriBuilderImpl().uri(newBaseURI);
    String basePath = reqURIPath.startsWith(baseURIPath) ? baseURIPath : getBaseURI().getRawPath();
    String relativePath = reqURIPath.equals(basePath) ? ""
            : reqURIPath.startsWith(basePath) ? reqURIPath.substring(basePath.length()) : reqURIPath;
    builder.path(relativePath);

    String newQuery = newBaseURI.getRawQuery();
    if (newQuery == null) {
        builder.replaceQuery(requestURI.getRawQuery());
    } else {
        builder.replaceQuery(newQuery);
    }

    URI newRequestURI = builder.build();

    resetBaseAddress(newBaseURI);
    URI current = proxy ? newBaseURI : newRequestURI;
    resetCurrentBuilder(current);

    return newRequestURI;
}
 
Example 6
Source File: ParamFilter.java    From hadoop with Apache License 2.0 5 votes vote down vote up
/** Rebuild the URI query with lower case parameter names. */
private static URI rebuildQuery(final URI uri,
    final MultivaluedMap<String, String> parameters) {
  UriBuilder b = UriBuilder.fromUri(uri).replaceQuery("");
  for(Map.Entry<String, List<String>> e : parameters.entrySet()) {
    final String key = StringUtils.toLowerCase(e.getKey());
    for(String v : e.getValue()) {
      b = b.queryParam(key, v);
    }
  }
  return b.build();
}
 
Example 7
Source File: ConstructBuildURI.java    From levelup-java-examples with Apache License 2.0 5 votes vote down vote up
@Test
public void construct_uri_template_jersey () {
	
	UriBuilder builder = UriBuilder
			.fromPath("www.leveluplunch.com")
			.path("/{lanuage}/{type}/");
	
	URI uri = builder.build("java", "examples");
	
	assertEquals(
			"www.leveluplunch.com/java/examples/", 
			uri.toString());
}
 
Example 8
Source File: ApplicationPathFilter.java    From jrestless with Apache License 2.0 5 votes vote down vote up
@Override
public void filter(ContainerRequestContext requestContext) throws IOException {
	String applicationPath = getApplicationPath();
	if (applicationPath != null) {
		UriInfo requestUriInfo = requestContext.getUriInfo();
		UriBuilder baseUriBuilder = requestUriInfo.getBaseUriBuilder();
		baseUriBuilder.path(applicationPath);
		// the base URI must end with a trailing slash
		baseUriBuilder.path("/");
		URI updatedBaseUri = baseUriBuilder.build();
		URI requestUri = requestUriInfo.getRequestUri();
		requestContext.setRequestUri(updatedBaseUri, requestUri);
	}
}
 
Example 9
Source File: ApplicationServiceImpl.java    From cxf-fediz with Apache License 2.0 5 votes vote down vote up
@Override
public Response addApplication(UriInfo ui, Application application) {
    LOG.info("add Service config");
    if (application.getRequestedClaims() != null && !application.getRequestedClaims().isEmpty()) {
        LOG.warn("Application resource contains sub resource 'claims'");
        throw new WebApplicationException(Status.BAD_REQUEST);
    }
    Application createdApplication = applicationDAO.addApplication(application);

    UriBuilder uriBuilder = UriBuilder.fromUri(ui.getRequestUri());
    uriBuilder.path("{index}");
    URI location = uriBuilder.build(createdApplication.getRealm());
    return Response.created(location).entity(application).build();
}
 
Example 10
Source File: AuthenticationProcessor.java    From keycloak with Apache License 2.0 5 votes vote down vote up
@Override
public URI getActionUrl(String code) {
    UriBuilder uriBuilder = LoginActionsService.loginActionsBaseUrl(getUriInfo())
            .path(AuthenticationProcessor.this.flowPath)
            .queryParam(LoginActionsService.SESSION_CODE, code)
            .queryParam(Constants.EXECUTION, getExecution().getId())
            .queryParam(Constants.CLIENT_ID, getAuthenticationSession().getClient().getClientId())
            .queryParam(Constants.TAB_ID, getAuthenticationSession().getTabId());
    if (getUriInfo().getQueryParameters().containsKey(LoginActionsService.AUTH_SESSION_ID)) {
        uriBuilder.queryParam(LoginActionsService.AUTH_SESSION_ID, getAuthenticationSession().getParentSession().getId());
    }
    return uriBuilder
            .build(getRealm().getName());
}
 
Example 11
Source File: ResourceUtil.java    From secure-data-service with Apache License 2.0 5 votes vote down vote up
/**
 * Returns a URI based on the supplied URI with the paths appended to the base URI.
 * 
 * @param uriInfo
 *            URI of current actions
 * @param paths
 *            Paths that need to be appended
 * @return
 */
public static URI getURI(UriInfo uriInfo, String... paths) {
    UriBuilder builder = uriInfo.getBaseUriBuilder();

    for (String path : paths) {
        if (path != null) {
            builder.path(path);
        }
    }

    return builder.build();
}
 
Example 12
Source File: AuthorizationRequestHandler.java    From cxf with Apache License 2.0 5 votes vote down vote up
private URI buildCallbackURI(String callback, final Map<String, String> queryParams) {

        UriBuilder builder = UriBuilder.fromUri(callback);
        for (Map.Entry<String, String> entry : queryParams.entrySet()) {
            builder.queryParam(entry.getKey(), entry.getValue());
        }

        return builder.build();
    }
 
Example 13
Source File: AuthenticationProcessor.java    From keycloak with Apache License 2.0 5 votes vote down vote up
@Override
public URI getActionTokenUrl(String tokenString) {
    UriBuilder uriBuilder = LoginActionsService.actionTokenProcessor(getUriInfo())
            .queryParam(Constants.KEY, tokenString)
            .queryParam(Constants.EXECUTION, getExecution().getId())
            .queryParam(Constants.CLIENT_ID, getAuthenticationSession().getClient().getClientId())
            .queryParam(Constants.TAB_ID, getAuthenticationSession().getTabId());
    if (getUriInfo().getQueryParameters().containsKey(LoginActionsService.AUTH_SESSION_ID)) {
        uriBuilder.queryParam(LoginActionsService.AUTH_SESSION_ID, getAuthenticationSession().getParentSession().getId());
    }
    return uriBuilder
            .build(getRealm().getName());
}
 
Example 14
Source File: UriUtil.java    From container with Apache License 2.0 5 votes vote down vote up
public static URI encode(final URI uri) {
    final List<PathSegment> pathSegments = UriComponent.decodePath(uri, false);
    final UriBuilder uriBuilder = RuntimeDelegate.getInstance().createUriBuilder();
    // Build base URL
    uriBuilder.scheme(uri.getScheme()).host(uri.getHost()).port(uri.getPort());
    // Iterate over path segments and encode it if necessary
    for (final PathSegment ps : pathSegments) {
        uriBuilder.path(UriComponent.encode(ps.toString(), UriComponent.Type.PATH_SEGMENT));
    }
    logger.debug("URL before encoding: {}", uri.toString());
    URI result = uriBuilder.build();
    logger.debug("URL after encoding:  {}", result.toString());
    return result;
}
 
Example 15
Source File: AccountFormService.java    From keycloak with Apache License 2.0 5 votes vote down vote up
@Path("sessions")
@POST
public Response processSessionsLogout(final MultivaluedMap<String, String> formData) {
    if (auth == null) {
        return login("sessions");
    }

    auth.require(AccountRoles.MANAGE_ACCOUNT);
    csrfCheck(formData);

    UserModel user = auth.getUser();

    // Rather decrease time a bit. To avoid situation when user is immediatelly redirected to login screen, then automatically authenticated (eg. with Kerberos) and then seeing issues due the stale token
    // as time on the token will be same like notBefore
    session.users().setNotBeforeForUser(realm, user, Time.currentTime() - 1);

    List<UserSessionModel> userSessions = session.sessions().getUserSessions(realm, user);
    for (UserSessionModel userSession : userSessions) {
        AuthenticationManager.backchannelLogout(session, realm, userSession, session.getContext().getUri(), clientConnection, headers, true);
    }

    UriBuilder builder = Urls.accountBase(session.getContext().getUri().getBaseUri()).path(AccountFormService.class, "sessionsPage");
    String referrer = session.getContext().getUri().getQueryParameters().getFirst("referrer");
    if (referrer != null) {
        builder.queryParam("referrer", referrer);

    }
    URI location = builder.build(realm.getName());
    return Response.seeOther(location).build();
}
 
Example 16
Source File: AuthenticationProcessor.java    From keycloak with Apache License 2.0 5 votes vote down vote up
@Override
public URI getActionUrl(String code, boolean authSessionIdParam) {
    UriBuilder uriBuilder = LoginActionsService.loginActionsBaseUrl(getUriInfo())
            .path(AuthenticationProcessor.this.flowPath)
            .queryParam(LoginActionsService.SESSION_CODE, code)
            .queryParam(Constants.EXECUTION, getExecution().getId())
            .queryParam(Constants.CLIENT_ID, getAuthenticationSession().getClient().getClientId())
            .queryParam(Constants.TAB_ID, getAuthenticationSession().getTabId());
    if (authSessionIdParam) {
        uriBuilder.queryParam(LoginActionsService.AUTH_SESSION_ID, getAuthenticationSession().getParentSession().getId());
    }
    return uriBuilder
            .build(getRealm().getName());
}
 
Example 17
Source File: RedirectResourceFilter.java    From localization_nifi with Apache License 2.0 5 votes vote down vote up
/**
 * This method checks path of the incoming request, and
 * redirects following URIs:
 * <li>/controller -> SiteToSiteResource
 * @param containerRequest request to be modified
 * @return modified request
 */
@Override
public ContainerRequest filter(ContainerRequest containerRequest) {

    if(containerRequest.getPath().equals("controller")){
        UriBuilder builder = UriBuilder.fromUri(containerRequest.getBaseUri())
                .path(SiteToSiteResource.class)
                .replaceQuery(containerRequest.getRequestUri().getRawQuery());

        URI redirectTo = builder.build();
        containerRequest.setUris(containerRequest.getBaseUri(), redirectTo);
    }
    return containerRequest;
}
 
Example 18
Source File: UrisSerializer.java    From cloudstack with Apache License 2.0 4 votes vote down vote up
protected String buildUri(Class<?> clazz, String method, Object id) {
    ThreadLocalUriInfo uriInfo = new ThreadLocalUriInfo();
    UriBuilder ub = uriInfo.getAbsolutePathBuilder().path(clazz, method);
    ub.build(id);
    return ub.toString();
}
 
Example 19
Source File: UriBuilderImplTest.java    From cxf with Apache License 2.0 4 votes vote down vote up
@Test
public void testUriTemplate() throws Exception {
    UriBuilder builder = UriBuilder.fromUri("http://localhost:8080/{a}/{b}");
    URI uri = builder.build("1", "2");
    assertEquals("http://localhost:8080/1/2", uri.toString());
}
 
Example 20
Source File: GetFileNameFromURL.java    From levelup-java-examples with Apache License 2.0 3 votes vote down vote up
@Test
public void uri_with_parameters_jersey() {

	UriBuilder buildURI = UriBuilder.fromUri(IMAGE_URL_WITH_PARAMS);

	URI uri = buildURI.build();

	assertEquals("logo11w.png", Paths.get(uri.getPath()).getFileName()
			.toString());
}