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

The following examples show how to use javax.ws.rs.core.UriBuilder#replaceQueryParam() . 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: Urls.java    From keycloak with Apache License 2.0 6 votes vote down vote up
public static URI identityProviderAuthnRequest(URI baseUri, String providerId, String realmName, String accessCode, String clientId, String tabId) {
    UriBuilder uriBuilder = realmBase(baseUri).path(RealmsResource.class, "getBrokerService")
            .path(IdentityBrokerService.class, "performLogin");

    if (accessCode != null) {
        uriBuilder.replaceQueryParam(LoginActionsService.SESSION_CODE, accessCode);
    }
    if (clientId != null) {
        uriBuilder.replaceQueryParam(Constants.CLIENT_ID, clientId);
    }
    if (tabId != null) {
        uriBuilder.replaceQueryParam(Constants.TAB_ID, tabId);
    }

    return uriBuilder.build(realmName, providerId);
}
 
Example 2
Source File: SsoService.java    From codenvy with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Restore session cookie if persistent cookie is present, that allow re-login easily. If there is
 * no cookie user login as anonymous or gets error page if anonymous is restricted.
 *
 * @param redirectUrl - url for redirection after successful authentication.
 * @param tokenAccessCookie - cookie with authentication token
 */
@Metered(name = "auth.sso.service_refresh_token")
@Path("refresh")
@GET
public Response refresh(
    @QueryParam("redirect_url") String redirectUrl,
    @CookieParam("token-access-key") Cookie tokenAccessCookie,
    @Context UriInfo uriInfo)
    throws UnsupportedEncodingException {
  Response.ResponseBuilder builder;
  boolean isSecure = uriInfo.getRequestUri().getScheme().equals("https");
  try {
    if (tokenAccessCookie != null) {
      AccessTicket accessTicket = ticketManager.getAccessTicket(tokenAccessCookie.getValue());
      if (accessTicket != null) {

        UriBuilder destination = UriBuilder.fromUri(redirectUrl);
        destination.replaceQueryParam("cookiePresent", true);
        builder = Response.temporaryRedirect(destination.build());

        cookieBuilder.setCookies(builder, tokenAccessCookie.getValue(), isSecure);

        return builder.build();
      }
    }
    builder =
        Response.temporaryRedirect(
            new URI(loginPage + "?redirect_url=" + encode(redirectUrl, "UTF-8")));
  } catch (IOException | URISyntaxException e) {
    LOG.error(e.getLocalizedMessage(), e);
    builder = Response.serverError();
  }

  return builder.build();
}
 
Example 3
Source File: ClientImpl.java    From cxf with Apache License 2.0 5 votes vote down vote up
@Override
public WebTarget queryParam(String name, Object... values) {
    checkClosed();
    checkNullValues(name, values);
    UriBuilder thebuilder = getUriBuilder();
    if (values == null || values.length == 1 && values[0] == null) {
        thebuilder.replaceQueryParam(name, (Object[])null);
    } else {
        thebuilder.queryParam(name, values);
    }
    return newWebTarget(thebuilder);
}
 
Example 4
Source File: LoginFilter.java    From codenvy with Eclipse Public License 1.0 4 votes vote down vote up
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
    throws IOException, ServletException {
  final HttpServletRequest httpReq = (HttpServletRequest) request;
  final HttpServletResponse httpResp = (HttpServletResponse) response;
  if (requestFilter.shouldSkip(httpReq)) {
    chain.doFilter(request, response);
    return;
  }

  final String method = httpReq.getMethod();
  final String clientUrl = clientUrlExtractor.getClientUrl(httpReq);

  // looks like we don't need client_url in queries, have to check it
  if ("GET".equals(method) && httpReq.getParameter("login") != null) {
    // forced sending user to login
    UriBuilder redirectUrlParameter =
        UriBuilder.fromUri(httpReq.getRequestURL().toString())
            .replaceQuery(httpReq.getQueryString());
    redirectUrlParameter.replaceQueryParam("login");

    String redirectUrl =
        UriBuilder.fromUri(loginPageUrl)
            .queryParam("redirect_url", encode(redirectUrlParameter.build().toString(), "UTF-8"))
            .queryParam("client_url", encode(clientUrl, "UTF-8"))
            .build()
            .toString();

    LOG.debug("Redirect to login {} ", redirectUrl);
    httpResp.sendRedirect(redirectUrl);
  } else {
    String token = tokenExtractor.getToken(httpReq);

    HttpSession session;
    if (token != null) {
      // TODO thread safety
      session = sessionStore.getSession(token);
      if (session == null) {
        session = httpReq.getSession();
        sessionStore.saveSession(token, session);
      }

      final SsoClientPrincipal principal = getPrincipal(session, token, clientUrl);
      if (principal == null) {
        tokenHandler.handleBadToken(httpReq, httpResp, chain, token);
      } else {
        tokenHandler.handleValidToken(httpReq, httpResp, chain, session, principal);
      }
    } else {
      // token not exists
      if (httpReq.getParameter("cookiePresent") != null) {
        // we know that token have to be in cookies but it's not there
        httpResp.sendRedirect(cookiesDisabledErrorPageUrl);
      } else {
        tokenHandler.handleMissingToken(httpReq, httpResp, chain);
      }
    }
  }
}
 
Example 5
Source File: HttpRequestHelper.java    From che with Eclipse Public License 2.0 4 votes vote down vote up
public static String requestString(
    int timeout, String url, String method, Object body, Pair<String, ?>... parameters)
    throws IOException, ServerException, ForbiddenException, NotFoundException,
        UnauthorizedException, ConflictException {
  final String authToken = EnvironmentContext.getCurrent().getSubject().getToken();
  if ((parameters != null && parameters.length > 0) || authToken != null) {
    final UriBuilder ub = UriBuilder.fromUri(url);
    // remove sensitive information from url.
    ub.replaceQueryParam("token", null);

    if (parameters != null && parameters.length > 0) {
      for (Pair<String, ?> parameter : parameters) {
        ub.queryParam(parameter.first, parameter.second);
      }
    }
    url = ub.build().toString();
  }
  final HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection();
  conn.setConnectTimeout(timeout > 0 ? timeout : 60000);
  conn.setReadTimeout(timeout > 0 ? timeout : 60000);
  try {
    conn.setRequestMethod(method);
    // drop a hint for server side that we want to receive application/json
    //            conn.addRequestProperty(HttpHeaders.ACCEPT, MediaType.APPLICATION_JSON);
    if (authToken != null) {
      conn.setRequestProperty(HttpHeaders.AUTHORIZATION, authToken);
    }
    if (body != null) {
      //                conn.addRequestProperty(HttpHeaders.CONTENT_TYPE,
      // MediaType.APPLICATION_JSON);
      conn.setDoOutput(true);

      if (HttpMethod.DELETE.equals(method)) { // to avoid jdk bug described here
        // http://bugs.java.com/view_bug.do?bug_id=7157360
        conn.setRequestMethod(HttpMethod.POST);
        conn.setRequestProperty("X-HTTP-Method-Override", HttpMethod.DELETE);
      }

      try (OutputStream output = conn.getOutputStream()) {
        output.write(DtoFactory.getInstance().toJson(body).getBytes());
      }
    }

    final int responseCode = conn.getResponseCode();
    if ((responseCode / 100) != 2) {
      InputStream in = conn.getErrorStream();
      if (in == null) {
        in = conn.getInputStream();
      }
      final String str;
      try (Reader reader = new InputStreamReader(in)) {
        str = CharStreams.toString(reader);
      }
      final String contentType = conn.getContentType();
      if (contentType != null && contentType.startsWith(MediaType.APPLICATION_JSON)) {
        final ServiceError serviceError =
            DtoFactory.getInstance().createDtoFromJson(str, ServiceError.class);
        if (serviceError.getMessage() != null) {
          if (responseCode == Response.Status.FORBIDDEN.getStatusCode()) {
            throw new ForbiddenException(serviceError);
          } else if (responseCode == Response.Status.NOT_FOUND.getStatusCode()) {
            throw new NotFoundException(serviceError);
          } else if (responseCode == Response.Status.UNAUTHORIZED.getStatusCode()) {
            throw new UnauthorizedException(serviceError);
          } else if (responseCode == Response.Status.CONFLICT.getStatusCode()) {
            throw new ConflictException(serviceError);
          } else if (responseCode == Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()) {
            throw new ServerException(serviceError);
          }
          throw new ServerException(serviceError);
        }
      }
      // Can't parse content as json or content has format other we expect for error.
      throw new IOException(
          String.format(
              "Failed access: %s, method: %s, response code: %d, message: %s",
              UriBuilder.fromUri(url).replaceQuery("token").build(), method, responseCode, str));
    }

    //            final String contentType = conn.getContentType();

    //            if (!(contentType == null ||
    // contentType.startsWith(MediaType.APPLICATION_JSON))) {
    //                throw new IOException(conn.getResponseMessage());
    //            }

    try (Reader reader = new InputStreamReader(conn.getInputStream())) {
      return CharStreams.toString(reader);
    }
  } finally {
    conn.disconnect();
  }
}
 
Example 6
Source File: DcJsonFeedFormatWriter.java    From io with Apache License 2.0 4 votes vote down vote up
@Override
public void writeContent(UriInfo uriInfo, JsonWriter jw, EntitiesResponse target) {

    jw.startObject();
    jw.writeName("results");

    jw.startArray();
    boolean isFirst = true;
    for (OEntity oe : target.getEntities()) {

        if (isFirst) {
            isFirst = false;
        } else {
            jw.writeSeparator();
        }

        writeOEntity(uriInfo, jw, oe, target.getEntitySet(), true);
    }

    jw.endArray();

    if (target.getInlineCount() != null) {
        jw.writeSeparator();
        jw.writeName("__count");
        jw.writeString(target.getInlineCount().toString());
    }

    if (target.getSkipToken() != null) {

        // $skip only applies to the first page of results.
        // if $top was given, we have to reduce it by the number of entities
        // we are returning now.
        String tops = uriInfo.getQueryParameters().getFirst("$top");
        int top = -1;
        if (null != tops) {
            // query param value already validated
            top = Integer.parseInt(tops);
            top -= target.getEntities().size();
        }
        UriBuilder uri = uriInfo.getRequestUriBuilder();
        if (top > 0) {
            uri.replaceQueryParam("$top", top);
        } else {
            uri.replaceQueryParam("$top");
        }
        String nextHref = uri
                .replaceQueryParam("$skiptoken", target.getSkipToken())
                .replaceQueryParam("$skip").build().toString();

        jw.writeSeparator();
        jw.writeName("__next");
        jw.writeString(nextHref);
    }
    jw.endObject();
}