Ejemplo n.º 1
0
  /**
   * Builds a paged result out of a list of items and additional information.
   *
   * @param <T> result type
   * @param list bare list of items to be returned
   * @param page current page
   * @param size requested size
   * @param totalCount total result size (not considering pagination)
   * @return paged result
   */
  protected <T extends AbstractBaseBean> PagedResult<T> buildPagedResult(
      final List<T> list, final int page, final int size, final int totalCount) {

    PagedResult<T> result = new PagedResult<>();
    result.getResult().addAll(list);

    result.setPage(page);
    result.setSize(result.getResult().size());
    result.setTotalCount(totalCount);

    UriBuilder builder = uriInfo.getAbsolutePathBuilder();
    MultivaluedMap<String, String> queryParams = uriInfo.getQueryParameters();
    for (Map.Entry<String, List<String>> queryParam : queryParams.entrySet()) {
      builder.queryParam(queryParam.getKey(), queryParam.getValue().toArray());
    }

    if (result.getPage() > 1) {
      result.setPrev(
          builder
              .replaceQueryParam(PARAM_PAGE, result.getPage() - 1)
              .replaceQueryParam(PARAM_SIZE, size)
              .build());
    }
    if ((result.getPage() - 1) * size + result.getSize() < totalCount) {
      result.setNext(
          builder
              .replaceQueryParam(PARAM_PAGE, result.getPage() + 1)
              .replaceQueryParam(PARAM_SIZE, size)
              .build());
    }

    return result;
  }
Ejemplo n.º 2
0
  @Override
  public PagedConnObjectTOResult listConnObjects(
      final String key, final String anyTypeKey, final ConnObjectTOListQuery listQuery) {

    Pair<SearchResult, List<ConnObjectTO>> list =
        logic.listConnObjects(
            key,
            anyTypeKey,
            listQuery.getSize(),
            listQuery.getPagedResultsCookie(),
            getOrderByClauses(listQuery.getOrderBy()));

    PagedConnObjectTOResult result = new PagedConnObjectTOResult();
    if (list.getLeft() != null) {
      result.setAllResultsReturned(list.getLeft().isAllResultsReturned());
      result.setPagedResultsCookie(list.getLeft().getPagedResultsCookie());
      result.setRemainingPagedResults(list.getLeft().getRemainingPagedResults());
    }
    result.getResult().addAll(list.getRight());

    UriBuilder builder = uriInfo.getAbsolutePathBuilder();
    MultivaluedMap<String, String> queryParams = uriInfo.getQueryParameters();
    for (Map.Entry<String, List<String>> queryParam : queryParams.entrySet()) {
      builder = builder.queryParam(queryParam.getKey(), queryParam.getValue().toArray());
    }

    if (StringUtils.isNotBlank(result.getPagedResultsCookie())) {
      result.setNext(
          builder
              .replaceQueryParam(PARAM_CONNID_PAGED_RESULTS_COOKIE, result.getPagedResultsCookie())
              .build());
    }

    return result;
  }
Ejemplo n.º 3
0
  @Test
  public void testReplaceQueryParamsEncoded4() throws URISyntaxException {
    UriBuilder ubu =
        UriBuilder.fromUri("http://localhost").replaceQuery("limit=10&sql=select+*+from+users");
    ubu.replaceQueryParam("limit", 100);

    URI uri = ubu.build();
    Assert.assertEquals(URI.create("http://localhost/?limit=100&sql=select+*+from+users"), uri);
  }
Ejemplo n.º 4
0
 @Override
 public WebTarget queryParam(String name, Object... values) {
   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);
 }
Ejemplo n.º 5
0
  public static URI identityProviderAuthnRequest(
      URI baseUri, String providerId, String realmName, String accessCode) {
    UriBuilder uriBuilder =
        realmBase(baseUri)
            .path(RealmsResource.class, "getBrokerService")
            .path(IdentityBrokerService.class, "performLogin");

    if (accessCode != null) {
      uriBuilder.replaceQueryParam(OAuth2Constants.CODE, accessCode);
    }

    return uriBuilder.build(realmName, providerId);
  }
Ejemplo n.º 6
0
  @Test
  public void testReplaceQueryParams() {
    UriBuilder ubu =
        UriBuilder.fromUri("http://localhost:8080/a/b/c?a=x&b=y")
            .replaceQueryParam("a", "z", "zz")
            .queryParam("c", "c");

    {
      URI uri = ubu.build();

      MultivaluedMap<String, String> qps = UriComponent.decodeQuery(uri, true);
      List<String> a = qps.get("a");
      Assert.assertEquals(2, a.size());
      Assert.assertEquals("z", a.get(0));
      Assert.assertEquals("zz", a.get(1));
      List<String> b = qps.get("b");
      Assert.assertEquals(1, b.size());
      Assert.assertEquals("y", b.get(0));
      List<String> c = qps.get("c");
      Assert.assertEquals(1, c.size());
      Assert.assertEquals("c", c.get(0));
    }

    {
      URI uri = ubu.replaceQueryParam("a", "_z_", "_zz_").build();

      MultivaluedMap<String, String> qps = UriComponent.decodeQuery(uri, true);
      List<String> a = qps.get("a");
      Assert.assertEquals(2, a.size());
      Assert.assertEquals("_z_", a.get(0));
      Assert.assertEquals("_zz_", a.get(1));
      List<String> b = qps.get("b");
      Assert.assertEquals(1, b.size());
      Assert.assertEquals("y", b.get(0));
      List<String> c = qps.get("c");
      Assert.assertEquals(1, c.size());
      Assert.assertEquals("c", c.get(0));
    }

    // issue 257 - param is removed after setting it to null
    {
      URI u1 =
          UriBuilder.fromPath("http://localhost:8080")
              .queryParam("x", "10")
              .replaceQueryParam("x", null)
              .build();
      Assert.assertTrue(u1.toString().equals("http://localhost:8080"));

      URI u2 =
          UriBuilder.fromPath("http://localhost:8080")
              .queryParam("x", "10")
              .replaceQueryParam("x")
              .build();
      Assert.assertTrue(u2.toString().equals("http://localhost:8080"));
    }

    // issue 257 - IllegalArgumentException
    {
      boolean caught = false;

      try {
        URI u =
            UriBuilder.fromPath("http://localhost:8080")
                .queryParam("x", "10")
                .replaceQueryParam("x", "1", null, "2")
                .build();
      } catch (IllegalArgumentException iae) {
        caught = true;
      }

      Assert.assertTrue(caught);
    }
  }
Ejemplo n.º 7
0
    public String requestString(
        int timeout, String url, String method, Object body, Pair<String, ?>... parameters)
        throws IOException, ServerException, ForbiddenException, NotFoundException,
            UnauthorizedException, ConflictException {
      final String authToken = getAuthenticationToken();
      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) {
            String name = URLEncoder.encode(parameter.first, "UTF-8");
            String value =
                parameter.second == null
                    ? null
                    : URLEncoder.encode(String.valueOf(parameter.second), "UTF-8");
            ub.replaceQueryParam(name, value);
          }
        }
        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();
      }
    }