Example #1
2
  /*
   * curl --data "[email protected]&password=test" http://localhost:8080/prostalytics/rest/auth/login
   *
   */
  @Path("/login")
  @POST
  @Consumes(MediaType.APPLICATION_FORM_URLENCODED)
  @Produces(MediaType.TEXT_HTML)
  public Response login(
      @FormParam("email") String email,
      @FormParam("password") String password,
      @HeaderParam("Auth-Token") String token)
      throws URISyntaxException {

    String newToken = null;
    try {
      User user = dao.authenticate(email, hashPassword(password));
      if (user != null) {
        newToken = auth.loggedIn(user, token);
      }

      URI redir =
          uriInfo
              .getBaseUri()
              .resolve(Navigation.fromLogin(user != null ? Navigation.OK : Navigation.ERROR));
      URI uri = UriBuilder.fromUri(redir).build();
      Response.ResponseBuilder res = Response.seeOther(uri);
      if (newToken != null) {
        res.header("Auth-Token", newToken);
      }
      return res.build();
    } catch (Throwable e) {
      URI uri =
          UriBuilder.fromUri(
                  uriInfo.getBaseUri().resolve(Navigation.fromLogin(Navigation.ERROR, e)))
              .build();
      return Response.seeOther(uri).build();
    }
  }
  /**
   * Creates and installs a new filtering objective for the specified device.
   *
   * @param appId application identifier
   * @param deviceId device identifier
   * @param stream filtering objective JSON
   * @return status of the request - CREATED if the JSON is correct, BAD_REQUEST if the JSON is
   *     invalid
   * @onos.rsModel FilteringObjective
   */
  @POST
  @Path("{deviceId}/filter")
  @Consumes(MediaType.APPLICATION_JSON)
  @Produces(MediaType.APPLICATION_JSON)
  public Response createFilteringObjective(
      @QueryParam("appId") String appId,
      @PathParam("deviceId") String deviceId,
      InputStream stream) {
    try {
      UriBuilder locationBuilder = null;
      ObjectNode jsonTree = (ObjectNode) mapper().readTree(stream);
      if (validateDeviceId(deviceId, jsonTree)) {

        if (appId != null) {
          jsonTree.put("appId", appId);
        }

        DeviceId did = DeviceId.deviceId(deviceId);
        FilteringObjective filteringObjective =
            codec(FilteringObjective.class).decode(jsonTree, this);
        flowObjectiveService.filter(did, filteringObjective);
        locationBuilder =
            uriInfo
                .getBaseUriBuilder()
                .path("flowobjectives")
                .path(did.toString())
                .path("filter")
                .path(Integer.toString(filteringObjective.id()));
      }
      return Response.created(locationBuilder.build()).build();
    } catch (IOException e) {
      throw new IllegalArgumentException(e);
    }
  }
 /**
  * Builds a URI.
  *
  * @param baseUri the base URI, not null
  * @param uniqueId the unique identifier, may be null
  * @return the URI, not null
  */
 public static URI uriGet(URI baseUri, UniqueId uniqueId) {
   UriBuilder bld = UriBuilder.fromUri(baseUri).path("exchanges/{exchangeId}");
   if (uniqueId.getVersion() != null) {
     bld.queryParam("version", uniqueId.getVersion());
   }
   return bld.build(uniqueId.getObjectId());
 }
Example #4
0
 /**
  * Builds a URI for holiday meta-data.
  *
  * @param baseUri the base URI, not null
  * @param request the request, may be null
  * @return the URI, not null
  */
 public static URI uriMetaData(URI baseUri, HolidayMetaDataRequest request) {
   UriBuilder bld = UriBuilder.fromUri(baseUri).path("metaData");
   if (request != null) {
     RestUtils.encodeQueryParams(bld, request);
   }
   return bld.build();
 }
  public static void main(String[] args) {

    URI uriAmazon =
        UriBuilder.fromUri("http://free.apisigning.com/onca/xml")
            .queryParam("Service", "AWSECommerceService")
            .queryParam("AWSAccessKeyId", "AKIAIYNLC7WME6YSY66A")
            .build();
    URI uriSearch = UriBuilder.fromUri(uriAmazon).queryParam("Operation", "ItemSearch").build();
    URI uriSearchBooks = UriBuilder.fromUri(uriSearch).queryParam("SearchIndex", "Books").build();
    Client client = ClientBuilder.newClient();

    URI uriSearchBooksByKeyword =
        UriBuilder.fromUri(uriSearchBooks).queryParam("Keywords", "Java EE 7").build();
    URI uriSearchBooksWithImages =
        UriBuilder.fromUri(uriSearchBooks)
            .queryParam("Condition", "All")
            .queryParam("ResponseGroup", "Images")
            .queryParam("Title", "Java EE 7")
            .build();

    System.out.println(uriSearchBooksByKeyword.toString());
    System.out.println(uriSearchBooksWithImages.toString());

    Response response = client.target(uriSearchBooksByKeyword).request().get();
    System.out.println(response.getStatus());
    response = client.target(uriSearchBooksWithImages).request().get();
    System.out.println(response.getStatus());
  }
 @Override
 public Response keycloakInitiatedBrowserLogout(
     UserSessionModel userSession, UriInfo uriInfo, RealmModel realm) {
   if (getConfig().getLogoutUrl() == null || getConfig().getLogoutUrl().trim().equals(""))
     return null;
   String idToken = userSession.getNote(FEDERATED_ID_TOKEN);
   if (idToken != null && getConfig().isBackchannelSupported()) {
     backchannelLogout(userSession, idToken);
     return null;
   } else {
     String sessionId = userSession.getId();
     UriBuilder logoutUri =
         UriBuilder.fromUri(getConfig().getLogoutUrl()).queryParam("state", sessionId);
     if (idToken != null) logoutUri.queryParam("id_token_hint", idToken);
     String redirect =
         RealmsResource.brokerUrl(uriInfo)
             .path(IdentityBrokerService.class, "getEndpoint")
             .path(OIDCEndpoint.class, "logoutResponse")
             .build(realm.getName(), getConfig().getAlias())
             .toString();
     logoutUri.queryParam("post_logout_redirect_uri", redirect);
     Response response = Response.status(302).location(logoutUri.build()).build();
     return response;
   }
 }
Example #7
0
 public Response redirectError(ClientModel client, String error, String state, String redirect) {
   UriBuilder redirectUri = UriBuilder.fromUri(redirect).queryParam(OAuth2Constants.ERROR, error);
   if (state != null) {
     redirectUri.queryParam(OAuth2Constants.STATE, state);
   }
   return Response.status(302).location(redirectUri.build()).build();
 }
Example #8
0
 protected static URI getRedirectUri(final UriInfo m_uriInfo, final Object... pathComponents) {
   if (pathComponents != null && pathComponents.length == 0) {
     final URI requestUri = m_uriInfo.getRequestUri();
     try {
       return new URI(
           requestUri.getScheme(),
           requestUri.getUserInfo(),
           requestUri.getHost(),
           requestUri.getPort(),
           requestUri.getPath().replaceAll("/$", ""),
           null,
           null);
     } catch (final URISyntaxException e) {
       return requestUri;
     }
   } else {
     UriBuilder builder = m_uriInfo.getRequestUriBuilder();
     for (final Object component : pathComponents) {
       if (component != null) {
         builder = builder.path(component.toString());
       }
     }
     return builder.build();
   }
 }
 public TreatmentRepresentation(TreatmentDto treatmentDTO, UriInfo context) {
   this.diagnosis = treatmentDTO.getDiagnosis();
   this.patient.setRelation(Representation.RELATION_PATIENT);
   this.patient.setMediaType(Representation.MEDTA_TYPE);
   UriBuilder ub1 = context.getBaseUriBuilder();
   this.patient.setUrl(
       ub1.path("patient").path("{id}").build(treatmentDTO.getPatientId()).toString());
   this.provider.setRelation(Representation.RELATION_PROVIDER);
   this.provider.setMediaType(Representation.MEDTA_TYPE);
   UriBuilder ub2 = context.getBaseUriBuilder();
   this.provider.setUrl(
       ub2.path("provider").path("{id}").build(treatmentDTO.getPatientId()).toString());
   if (treatmentDTO.TreatmentType instanceof DrugTreatmentType) {
     DrugTreatmentType dt = (DrugTreatmentType) treatmentDTO.TreatmentType;
     this.drugTreatment.setDosage(dt.getDosage());
     this.drugTreatment.setName(dt.getName());
   } else if (treatmentDTO.TreatmentType instanceof SurgeryType) {
     this.surgery.setDate(((SurgeryType) treatmentDTO.TreatmentType).getDate());
   } else if (treatmentDTO.TreatmentType instanceof RadiologyType) {
     List<Date> dates = ((RadiologyType) treatmentDTO.TreatmentType).getDate();
     List<Date> treatmentDates = this.radiology.getDate();
     for (Date i : dates) {
       treatmentDates.add(i);
     }
   }
 }
Example #10
0
  /*
   * curl --data "name=Test&lastname=Tester&[email protected]&password=test" http://localhost:8080/prostalytics/rest/auth/register
   *
   */
  @Path("/register")
  @POST
  @Consumes(MediaType.APPLICATION_FORM_URLENCODED)
  @Produces(MediaType.TEXT_HTML)
  public Response register(
      @FormParam("email") String email,
      @FormParam("name") String name,
      @FormParam("lastname") String lastName,
      @FormParam("password") String password)
      throws URISyntaxException {

    try {
      User user = new User();
      user.setName(name);
      user.setLastname(lastName);
      user.setEmail(email);
      user.setPassword(hashPassword(password));
      validate(user);

      userDao.saveUser(user);

      URI uri =
          UriBuilder.fromUri(
                  uriInfo.getBaseUri().resolve(Navigation.fromAuthRegister(Navigation.OK)))
              .build();
      return Response.seeOther(uri).build();
    } catch (Throwable e) {
      e.printStackTrace(); // TODO :)
      URI uri =
          UriBuilder.fromUri(
                  uriInfo.getBaseUri().resolve(Navigation.fromAuthRegister(Navigation.ERROR, e)))
              .build();
      return Response.seeOther(uri).build();
    }
  }
Example #11
0
  /**
   * Creates factory links and links for retrieving factory images.
   *
   * @param images a set of factory images
   * @param serviceContext the context to retrieve factory service base URI
   * @return list of factory and factory images links
   */
  public static List<Link> createLinks(
      FactoryDto factory,
      Set<FactoryImage> images,
      ServiceContext serviceContext,
      String userName) {
    final List<Link> links = new LinkedList<>(createLinks(factory, serviceContext, userName));
    final UriBuilder uriBuilder = serviceContext.getServiceUriBuilder();
    final String factoryId = factory.getId();

    // creation of links to retrieve images
    links.addAll(
        images
            .stream()
            .map(
                image ->
                    createLink(
                        HttpMethod.GET,
                        uriBuilder
                            .clone()
                            .path(FactoryService.class, "getImage")
                            .queryParam("imgId", image.getName())
                            .build(factoryId)
                            .toString(),
                        null,
                        image.getMediaType(),
                        IMAGE_REL_ATT))
            .collect(toList()));
    return links;
  }
  private UriInfo setUpCmdExpectations(
      String[] commands, String[] returns, String collectionType, String newId, boolean build)
      throws Exception {
    mockStatic(PowerShellCmd.class);
    for (int i = 0; i < Math.min(commands.length, returns.length); i++) {
      if (commands[i] != null) {
        expect(PowerShellCmd.runCommand(setUpPoolExpectations(), commands[i]))
            .andReturn(returns[i]);
      }
    }

    UriInfo uriInfo = null;
    if (collectionType != null && newId != null) {
      uriInfo = setUpBasicUriExpectations();
      if (build) {
        UriBuilder uriBuilder = createMock(UriBuilder.class);
        expect(uriInfo.getAbsolutePathBuilder()).andReturn(uriBuilder);
        expect(uriBuilder.path(newId)).andReturn(uriBuilder);
        expect(uriBuilder.build())
            .andReturn(new URI("vms/" + VM_ID + "/" + collectionType + "/" + newId))
            .anyTimes();
      }
    }

    replayAll();

    return uriInfo;
  }
  @Test
  public void testLinks() throws Exception {
    JAXBContext context = JAXBContext.newInstance(LinksList.class);
    LinksList list = new LinksList();
    UriBuilder builder = UriBuilder.fromUri("/blah").queryParam("start", "{start}");
    URI uri = builder.build(1);
    System.out.println("uri: " + uri.toString());
    builder.queryParam("start", "{start}");
    builder.queryParam("size", "{size}");
    list.getLinks().add(Link.fromUri(uri).rel("self").build());
    list.getLinks().add(Link.fromUri("/b").rel("father").build());
    list.setOther(Link.fromUri(uri).rel("other").build());

    StringWriter writer = new StringWriter();
    context.createMarshaller().marshal(list, writer);
    String xml = writer.getBuffer().toString();
    System.out.println(xml);

    System.out.println("----");
    list =
        (LinksList)
            context.createUnmarshaller().unmarshal(new ByteArrayInputStream(xml.getBytes()));
    uri = list.getOther().getUri();
    System.out.println(uri.toString());
    context.createMarshaller().marshal(list, System.out);
  }
Example #14
0
 /*
  * Notify node that we (think we) are its predecessor.
  */
 public TableRep notify(NodeInfo node, TableRep predDb) throws DHTBase.Failed {
   /*
    * The protocol here is more complex than for other operations. We
    * notify a new successor that we are its predecessor, and expect its
    * bindings as a result. But if it fails to accept us as its predecessor
    * (someone else has become intermediate predecessor since we found out
    * this node is our successor i.e. race condition that we don't try to
    * avoid because to do so is infeasible), it notifies us by returning
    * null. This is represented in HTTP by RC=304 (Not Modified).
    */
   NodeInfo thisNode = predDb.getInfo();
   UriBuilder ub = UriBuilder.fromUri(node.addr).path("notify");
   URI notifyPath = ub.queryParam("id", thisNode.id).build();
   info("client notify(" + notifyPath + ")");
   Response response = putRequest(notifyPath, Entity.xml(predDb));
   if (response != null && response.getStatusInfo() == Response.Status.NOT_MODIFIED) {
     /*
      * Do nothing, the successor did not accept us as its predecessor.
      */
     return null;
   } else if (response == null || response.getStatus() >= 300) {
     throw new DHTBase.Failed("PUT /notify?id=ID");
   } else {
     TableRep bindings = response.readEntity(TableRep.class);
     return bindings;
   }
 }
Example #15
0
  @Path("sessions-logout")
  @GET
  public Response processSessionsLogout(@QueryParam("stateChecker") String stateChecker) {
    if (auth == null) {
      return login("sessions");
    }

    require(AccountRoles.MANAGE_ACCOUNT);
    csrfCheck(stateChecker);

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

    UriBuilder builder =
        Urls.accountBase(uriInfo.getBaseUri()).path(AccountService.class, "sessionsPage");
    String referrer = uriInfo.getQueryParameters().getFirst("referrer");
    if (referrer != null) {
      builder.queryParam("referrer", referrer);
    }
    URI location = builder.build(realm.getName());
    return Response.seeOther(location).build();
  }
Example #16
0
 @POST
 public Response create(
     @Context HttpHeaders headers,
     @QueryParam("durable") Boolean durable,
     @QueryParam("expiration") Long expiration,
     @QueryParam("priority") Integer priority,
     @Context UriInfo uriInfo,
     byte[] body) {
   try {
     boolean isDurable = defaultDurable;
     if (durable != null) {
       isDurable = durable.booleanValue();
     }
     publish(headers, body, isDurable, expiration, priority);
   } catch (Exception e) {
     Response error =
         Response.serverError()
             .entity("Problem posting message: " + e.getMessage())
             .type("text/plain")
             .build();
     throw new WebApplicationException(e, error);
   }
   Response.ResponseBuilder builder = Response.status(201);
   UriBuilder nextBuilder = uriInfo.getAbsolutePathBuilder();
   URI next = nextBuilder.build();
   serviceManager
       .getLinkStrategy()
       .setLinkHeader(builder, "create-next", "create-next", next.toString(), "*/*");
   return builder.build();
 }
  @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;
  }
Example #18
0
  /**
   * Adds a trust bundle to the system.
   *
   * @param uriInfo Injected URI context used for building the location URI.
   * @param bundle The bundle to add to the system.
   * @return Status of 201 if the bundle was added or a status of 409 if a bundle with the same name
   *     already exists.
   */
  @PUT
  @Consumes(MediaType.APPLICATION_JSON)
  public Response addTrustBundle(@Context UriInfo uriInfo, TrustBundle bundle) {
    // make sure it doesn't exist
    try {
      if (bundleDao.getTrustBundleByName(bundle.getBundleName()) != null)
        return Response.status(Status.CONFLICT).cacheControl(noCache).build();
    } catch (Exception e) {
      log.error("Error looking up bundle.", e);
      return Response.serverError().cacheControl(noCache).build();
    }

    try {
      final org.nhindirect.config.store.TrustBundle entityBundle =
          EntityModelConversion.toEntityTrustBundle(bundle);

      bundleDao.addTrustBundle(entityBundle);

      final UriBuilder newLocBuilder = uriInfo.getBaseUriBuilder();
      final URI newLoc = newLocBuilder.path("trustbundle/" + bundle.getBundleName()).build();

      // the trust bundle does not contain any of the anchors
      // they must be fetched from the URL... use the
      // refresh route to force downloading the anchors
      template.sendBody(entityBundle);

      return Response.created(newLoc).cacheControl(noCache).build();
    } catch (Exception e) {
      log.error("Error adding trust bundle.", e);
      return Response.serverError().cacheControl(noCache).build();
    }
  }
Example #19
0
  @Test
  public void testAppendPath() {
    URI uri = UriBuilder.fromUri("http://localhost:8080").path("a/b/c").build();
    Assert.assertEquals(URI.create("http://localhost:8080/a/b/c"), uri);

    uri = UriBuilder.fromUri("http://localhost:8080/").path("a/b/c").build();
    Assert.assertEquals(URI.create("http://localhost:8080/a/b/c"), uri);

    uri = UriBuilder.fromUri("http://localhost:8080").path("/a/b/c").build();
    Assert.assertEquals(URI.create("http://localhost:8080/a/b/c"), uri);

    uri = UriBuilder.fromUri("http://localhost:8080/a/b/c/").path("/").build();
    Assert.assertEquals(URI.create("http://localhost:8080/a/b/c/"), uri);

    uri = UriBuilder.fromUri("http://localhost:8080/a/b/c/").path("/x/y/z").build();
    Assert.assertEquals(URI.create("http://localhost:8080/a/b/c/x/y/z"), uri);

    uri = UriBuilder.fromUri("http://localhost:8080/a/b/c").path("/x/y/z").build();
    Assert.assertEquals(URI.create("http://localhost:8080/a/b/c/x/y/z"), uri);

    uri = UriBuilder.fromUri("http://localhost:8080/a/b/c").path("x/y/z").build();
    Assert.assertEquals(URI.create("http://localhost:8080/a/b/c/x/y/z"), uri);

    uri = UriBuilder.fromUri("http://localhost:8080/a/b/c").path("/").build();
    Assert.assertEquals(URI.create("http://localhost:8080/a/b/c/"), uri);

    uri = UriBuilder.fromUri("http://localhost:8080/a/b/c").path("").build();
    Assert.assertEquals(URI.create("http://localhost:8080/a/b/c"), uri);

    uri = UriBuilder.fromUri("http://localhost:8080/a%20/b%20/c%20").path("/x /y /z ").build();
    Assert.assertEquals(URI.create("http://localhost:8080/a%20/b%20/c%20/x%20/y%20/z%20"), uri);
  }
Example #20
0
 // regression test for JERSEY-1114
 @Test
 public void testBuildFromMapNoSlashInUri() {
   UriBuilder builder = new UriBuilderImpl().uri(URI.create("http://localhost:8080")).path("test");
   assertEquals(
       "http://localhost:8080/test",
       builder.buildFromMap(new HashMap<String, Object>()).toString());
 }
Example #21
0
  @Test
  public void testIllegalArgumentException() {
    boolean caught = false;
    try {
      UriBuilder.fromPath(null);
    } catch (IllegalArgumentException e) {
      caught = true;
    }
    Assert.assertTrue(caught);

    caught = false;
    try {
      UriBuilder.fromUri((URI) null);
    } catch (IllegalArgumentException e) {
      caught = true;
    }
    Assert.assertTrue(caught);

    caught = false;
    try {
      UriBuilder.fromUri((String) null);
    } catch (IllegalArgumentException e) {
      caught = true;
    }
    Assert.assertTrue(caught);
  }
Example #22
0
  /*
   * Creates the URL based on the configured host, port, and services context root path.
   */
  private UriBuilder generateEndpointUrl(String path, UriBuilder uriBuilder)
      throws UnknownHostException {
    UriBuilder builder = uriBuilder;
    if (host != null && port != null && servicesContextRoot != null) {
      builder = builder.host(host);

      try {
        int portInt = Integer.parseInt(port);
        builder = builder.port(portInt);
      } catch (NumberFormatException nfe) {
        LOGGER.debug(
            "Cannot convert the current DDF port: {} to an integer."
                + " Defaulting to port in invocation.",
            port);
        throw new UnknownHostException("Unable to determine port DDF is using.");
      }

      builder = builder.replacePath(path);
    } else {
      LOGGER.debug("DDF Port is null, unable to determine host DDF is running on.");
      throw new UnknownHostException("Unable to determine port DDF is using.");
    }

    return builder;
  }
Example #23
0
  public static ResteasyUriInfo extractUriInfo(HttpExchange exchange) {
    String host = exchange.getLocalAddress().getHostName();
    if (exchange.getLocalAddress().getPort() != 80 && exchange.getLocalAddress().getPort() != 443) {
      host += ":" + exchange.getLocalAddress().getPort();
    }
    String uri = exchange.getRequestURI().toString();

    String protocol =
        exchange.getHttpContext().getServer() instanceof HttpsServer ? "https" : "http";

    URI absoluteURI = URI.create(protocol + "://" + host + uri);

    String contextPath = exchange.getHttpContext().getPath();
    String path = PathHelper.getEncodedPathInfo(absoluteURI.getRawPath(), contextPath);
    if (!path.startsWith("/")) {
      path = "/" + path;
    }

    URI baseURI = absoluteURI;
    if (!path.trim().equals("")) {
      String tmpContextPath = contextPath;
      if (!tmpContextPath.endsWith("/")) tmpContextPath += "/";
      baseURI =
          UriBuilder.fromUri(absoluteURI).replacePath(tmpContextPath).replaceQuery(null).build();
    } else {
      baseURI = UriBuilder.fromUri(absoluteURI).replaceQuery(null).build();
    }
    URI relativeURI = UriBuilder.fromUri(path).replaceQuery(absoluteURI.getRawQuery()).build();
    // System.out.println("path: " + path);
    // System.out.println("query string: " + request.getQueryString());
    ResteasyUriInfo uriInfo = new ResteasyUriInfo(baseURI, relativeURI);
    return uriInfo;
  }
  /**
   * 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;
  }
  @Test
  public void testBuildBaseUrlWithNoConfigProperty() {
    when(config.containsKey(eq(ConfigProperties.PREFIX_APIURL))).thenReturn(false);
    when(request.getRequestURL()).thenReturn(new StringBuffer("https://example.com/candlepin"));

    UriBuilder builder = interceptor.buildBaseUrl(request);
    assertEquals("https://example.com/candlepin", builder.build().toString());
  }
Example #26
0
 private URI getQueryStringSeqCluster40OfChain(String pdbid, String chain) {
   UriBuilder builder =
       UriBuilder.fromPath(restHost)
           .queryParam("cluster", 40)
           .queryParam("structureId", pdbid + "." + chain);
   URI uri = builder.build();
   return uri;
 }
Example #27
0
  @Test
  public void testReplacePort() {
    URI uri = UriBuilder.fromUri("http://localhost:8080/a/b/c").port(9090).build();
    Assert.assertEquals(URI.create("http://localhost:9090/a/b/c"), uri);

    uri = UriBuilder.fromUri("http://localhost:8080/a/b/c").port(-1).build();
    Assert.assertEquals(URI.create("http://localhost/a/b/c"), uri);
  }
 public BackupInfo getBackupInfo(String name, boolean isLocal) {
   UriBuilder builder = client.uriBuilder(BACKUP_INFO_URL);
   addQueryParam(builder, "backupname", name);
   if (isLocal) {
     addQueryParam(builder, "isLocal", isLocal);
   }
   return client.getURI(BackupInfo.class, builder.build());
 }
Example #29
0
  /**
   * Get the URL for an asset on this server
   *
   * @return the asset URL
   */
  protected static URL getAssetURL(UriBuilder builder, String moduleName, String assetPath)
      throws MalformedURLException {
    // Should we fetch the context prefix from a property? XXX -jslott
    String assetPrefix = "webdav/content/modules/installed/";
    builder.replacePath(assetPrefix + moduleName + "/" + assetPath);

    return builder.build().toURL();
  }
Example #30
0
 @Override
 protected URI getBaseUri() {
   final UriBuilder baseUriBuilder =
       UriBuilder.fromUri(super.getBaseUri()).path("sse-item-store-webapp");
   final boolean externalFactoryInUse =
       getTestContainerFactory() instanceof ExternalTestContainerFactory;
   return externalFactoryInUse ? baseUriBuilder.path("resources").build() : baseUriBuilder.build();
 }