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);
     }
   }
 }
Ejemplo n.º 2
0
  public static Package toPackage(ModuleItem p, UriInfo uriInfo) {
    PackageMetadata metadata = new PackageMetadata();
    metadata.setUuid(p.getUUID());
    metadata.setCreated(p.getCreatedDate().getTime());
    metadata.setState((p.getState() != null) ? p.getState().getName() : "");
    metadata.setArchived(p.isArchived());
    metadata.setVersionNumber(p.getVersionNumber());
    metadata.setCheckinComment(p.getCheckinComment());

    Package ret = new Package();
    ret.setMetadata(metadata);
    ret.setTitle(p.getTitle());
    ret.setAuthor(p.getLastContributor());
    ret.setPublished(p.getLastModified().getTime());
    ret.setDescription(p.getDescription());

    ret.setBinaryLink(
        uriInfo.getBaseUriBuilder().path("/packages/{packageName}/binary").build(p.getName()));
    ret.setSourceLink(
        uriInfo.getBaseUriBuilder().path("/packages/{packageName}/source").build(p.getName()));
    // ret.setSnapshot(p.getSnapshotName());

    Iterator<AssetItem> iter = p.getAssets();
    Set<URI> assets = new HashSet<URI>();
    while (iter.hasNext()) {
      AssetItem a = iter.next();
      Asset asset = toAsset(a, uriInfo);
      assets.add(asset.getRefLink());
    }

    ret.setAssets(assets);
    return ret;
  }
Ejemplo n.º 3
0
  @GET
  @Path("/{id}")
  @Produces({
    "application/vnd.bytesparadise.order+xml",
    MediaType.APPLICATION_XML,
    "application/json"
  })
  public PurchaseOrderDTO getOrder(@PathParam("id") Integer id, @Context UriInfo uriInfo) {
    PurchaseOrder order = entityManager.find(PurchaseOrder.class, id);
    if (order == null) {
      throw new EntityNotFoundException("Order with id " + id + " not found");
    }

    UriBuilder customerUriBuilder =
        uriInfo.getBaseUriBuilder().clone().path(CustomerResource.class).path("{id}");
    String customerUri = customerUriBuilder.build(order.getCustomer().getId()).toString();

    PurchaseOrderDTO purchaseOrderDTO = new PurchaseOrderDTO(order);
    CustomerDTO customerDTO = new CustomerDTO(order.getCustomer());
    customerDTO.addSelfLink(new Link("self", customerUri));
    purchaseOrderDTO.setCustomer(customerDTO);

    UriBuilder gameUriBuilder =
        uriInfo
            .getBaseUriBuilder()
            .clone()
            .path(ProductResourceLocator.class)
            .path("games")
            .path("{id}");
    UriBuilder bookUriBuilder =
        uriInfo
            .getBaseUriBuilder()
            .clone()
            .path(ProductResourceLocator.class)
            .path("books")
            .path("{id}");
    for (Product product : order.getProducts()) {
      ProductDTO productDTO = null;
      if (product instanceof Book) {
        productDTO = new BookDTO((Book) product);
        productDTO.addSelfLink(new Link("self", bookUriBuilder.build(product.getId()).toString()));
      }
      if (product instanceof Game) {
        productDTO = new GameDTO((Game) product);
        productDTO.addSelfLink(new Link("self", gameUriBuilder.build(product.getId()).toString()));
      }
      purchaseOrderDTO.addProduct(productDTO);
    }
    String orderUri = uriInfo.getAbsolutePath().toString();
    purchaseOrderDTO.addSelfLink(new Link("self", orderUri));

    return purchaseOrderDTO;
  }
Ejemplo n.º 4
0
  @GET
  @Path("/{sitemapname: [a-zA-Z_0-9]*}/{pageid: [a-zA-Z_0-9]*}")
  @Produces(MediaType.APPLICATION_JSON)
  @ApiOperation(value = "Polls the data for a sitemap.", response = PageDTO.class)
  @ApiResponses(
      value = {
        @ApiResponse(code = 200, message = "OK"),
        @ApiResponse(
            code = 404,
            message =
                "Sitemap with requested name does not exist or page does not exist, or page refers to a non-linkable widget")
      })
  public Response getPageData(
      @Context HttpHeaders headers,
      @HeaderParam(HttpHeaders.ACCEPT_LANGUAGE) @ApiParam(value = "language") String language,
      @PathParam("sitemapname") @ApiParam(value = "sitemap name") String sitemapname,
      @PathParam("pageid") @ApiParam(value = "page id") String pageId) {
    final Locale locale = LocaleUtil.getLocale(language);
    logger.debug("Received HTTP GET request at '{}'", uriInfo.getPath());

    if (headers.getRequestHeader("X-Atmosphere-Transport") != null) {
      // Make the REST-API pseudo-compatible with openHAB 1.x
      // The client asks Atmosphere for server push functionality,
      // so we do a simply listening for changes on the appropriate items
      blockUnlessChangeOccurs(sitemapname, pageId);
    }
    Object responseObject =
        getPageBean(sitemapname, pageId, uriInfo.getBaseUriBuilder().build(), locale);
    return Response.ok(responseObject).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);
    }
  }
Ejemplo n.º 6
0
 @GET
 @Path("/link")
 public Response getBookLink() {
   URI selfUri = ui.getBaseUriBuilder().path(BookStoreSpring.class).build();
   Link link = Link.fromUri(selfUri).rel("self").build();
   return Response.ok().links(link).build();
 }
Ejemplo n.º 7
0
 @POST
 @ApiOperation(
     value = "Create a new tenant.",
     notes =
         "Clients are not required to create explicitly create a "
             + "tenant before starting to store metric data. It is recommended to do so however to ensure that there "
             + "are no tenant id naming collisions and to provide default data retention settings.")
 @ApiResponses(
     value = {
       @ApiResponse(code = 201, message = "Tenant has been succesfully created."),
       @ApiResponse(
           code = 400,
           message = "Missing or invalid retention properties. ",
           response = ApiError.class),
       @ApiResponse(
           code = 409,
           message = "Given tenant id has already been created.",
           response = ApiError.class),
       @ApiResponse(
           code = 500,
           message = "An unexpected error occured while trying to create a tenant.",
           response = ApiError.class)
     })
 public void createTenant(
     @Suspended AsyncResponse asyncResponse,
     @ApiParam(required = true) TenantDefinition tenantDefinition,
     @Context UriInfo uriInfo) {
   URI location = uriInfo.getBaseUriBuilder().path("/tenants").build();
   metricsService
       .createTenant(tenantDefinition.toTenant())
       .subscribe(new TenantCreatedObserver(asyncResponse, location));
 }
Ejemplo n.º 8
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();
    }
  }
Ejemplo n.º 9
0
  @GET
  @Path("/")
  @Produces(MediaType.APPLICATION_JSON)
  public Response getStatisticsIndex(@Context final UriInfo uriInfo)
      throws IllegalArgumentException, UriBuilderException, JSONException {

    final JSONObject result = new JSONObject();
    result.put(
        MAX_RESULTS_PATH,
        uriInfo.getBaseUriBuilder().path(Settings.class).path(MAX_RESULTS_PATH).build());
    result.put(
        PAGE_REFRESH_PATH,
        uriInfo.getBaseUriBuilder().path(Settings.class).path(PAGE_REFRESH_PATH).build());

    return Response.ok(result.toString()).build();
  }
Ejemplo n.º 10
0
 @POST
 @Consumes(APPLICATION_JSON)
 public Response saveTimeregDTO(TimeregDTO dto) {
   Integer id = timeregDAO.save(dto);
   URI uri = uriInfo.getBaseUriBuilder().path(TimeregisteringResource.class).build(id);
   return Response.created(uri).build();
 }
Ejemplo n.º 11
0
 @POST
 @Consumes(value = MediaType.APPLICATION_JSON)
 public Response save(@Valid UserForm user) {
   UserDetail saved = service.createUser(user);
   return Response.created(uriInfo.getBaseUriBuilder().path("users/{id}").build(saved.getId()))
       .build();
 }
Ejemplo n.º 12
0
  private ResourceUri(Class<R> resourceClass, UriInfo uriInfo) {
    Objects.requireNonNull(resourceClass, "Resource class must not be null");
    Objects.requireNonNull(uriInfo, "URI info must not be null");

    Resource resource = new Resource(resourceClass);
    resourceUri = resource.uriFromBase(uriInfo.getBaseUriBuilder());
    invocationCaptor = InvocationCaptor.forClass(resourceClass);
  }
Ejemplo n.º 13
0
 public static UriBuilder accountServiceBaseUrl(UriInfo uriInfo) {
   UriBuilder base =
       uriInfo
           .getBaseUriBuilder()
           .path(RealmsResource.class)
           .path(RealmsResource.class, "getAccountService");
   return base;
 }
Ejemplo n.º 14
0
 public URI getUriArtikel(Artikel artikel, UriInfo uriInfo) {
   final UriBuilder ub =
       uriInfo
           .getBaseUriBuilder()
           .path(ArtikelResource.class)
           .path(ArtikelResource.class, "findArtikelById");
   final URI uri = ub.build(artikel.getId());
   return uri;
 }
Ejemplo n.º 15
0
  /**
   * Generate a resource uri based off of the specified parameters.
   *
   * @param path path
   * @return resource uri
   */
  protected String generateResourceUri(final String... path) {
    final UriBuilder uriBuilder = uriInfo.getBaseUriBuilder();
    uriBuilder.segment(path);
    URI uri = uriBuilder.build();
    try {

      // check for proxy settings
      final String scheme = httpServletRequest.getHeader(PROXY_SCHEME_HTTP_HEADER);
      final String host = httpServletRequest.getHeader(PROXY_HOST_HTTP_HEADER);
      final String port = httpServletRequest.getHeader(PROXY_PORT_HTTP_HEADER);
      String baseContextPath = httpServletRequest.getHeader(PROXY_CONTEXT_PATH_HTTP_HEADER);

      // if necessary, prepend the context path
      String resourcePath = uri.getPath();
      if (baseContextPath != null) {
        // normalize context path
        if (!baseContextPath.startsWith("/")) {
          baseContextPath = "/" + baseContextPath;
        }

        // determine the complete resource path
        resourcePath = baseContextPath + resourcePath;
      }

      // determine the port uri
      int uriPort = uri.getPort();
      if (port != null) {
        if (StringUtils.isWhitespace(port)) {
          uriPort = -1;
        } else {
          try {
            uriPort = Integer.parseInt(port);
          } catch (final NumberFormatException nfe) {
            logger.warn(
                String.format(
                    "Unable to parse proxy port HTTP header '%s'. Using port from request URI '%s'.",
                    port, uriPort));
          }
        }
      }

      // construct the URI
      uri =
          new URI(
              (StringUtils.isBlank(scheme)) ? uri.getScheme() : scheme,
              uri.getUserInfo(),
              (StringUtils.isBlank(host)) ? uri.getHost() : host,
              uriPort,
              resourcePath,
              uri.getQuery(),
              uri.getFragment());

    } catch (final URISyntaxException use) {
      throw new UriBuilderException(use);
    }
    return uri.toString();
  }
Ejemplo n.º 16
0
    @Override
    public Response run(JerseyResourceDelegateContext context) {
      JerseyResourceDelegateContextKey<String> sessionIdKey =
          JerseyResourceDelegateContextKey.valueOf(sessionIdKeyName, String.class);
      String sessionId = context.get(sessionIdKey);
      JerseyResourceDelegateContextKey<SubmitQueryRequest> submitQueryRequestKey =
          JerseyResourceDelegateContextKey.valueOf(
              submitQueryRequestKeyName, SubmitQueryRequest.class);
      SubmitQueryRequest request = context.get(submitQueryRequestKey);
      JerseyResourceDelegateContextKey<MasterContext> masterContextKey =
          JerseyResourceDelegateContextKey.valueOf(
              JerseyResourceDelegateUtil.MasterContextKey, MasterContext.class);
      MasterContext masterContext = context.get(masterContextKey);

      if (sessionId == null || sessionId.isEmpty()) {
        return ResourcesUtil.createBadRequestResponse(LOG, "Session Id is null or empty string.");
      }
      if (request == null || request.getQuery() == null || request.getQuery().isEmpty()) {
        return ResourcesUtil.createBadRequestResponse(LOG, "query is null or emptry string.");
      }

      Session session;
      try {
        session = masterContext.getSessionManager().getSession(sessionId);
      } catch (InvalidSessionException e) {
        return ResourcesUtil.createBadRequestResponse(
            LOG, "Provided session id (" + sessionId + ") is invalid.");
      }

      SubmitQueryResponse response =
          masterContext.getGlobalEngine().executeQuery(session, request.getQuery(), false);
      if (ReturnStateUtil.isError(response.getState())) {
        return ResourcesUtil.createExceptionResponse(LOG, response.getState().getMessage());
      } else {
        JerseyResourceDelegateContextKey<UriInfo> uriInfoKey =
            JerseyResourceDelegateContextKey.valueOf(
                JerseyResourceDelegateUtil.UriInfoKey, UriInfo.class);
        UriInfo uriInfo = context.get(uriInfoKey);

        QueryId queryId = new QueryId(response.getQueryId());
        URI queryURI =
            uriInfo
                .getBaseUriBuilder()
                .path(QueryResource.class)
                .path(QueryResource.class, "getQuery")
                .build(queryId.toString());

        GetSubmitQueryResponse queryResponse = new GetSubmitQueryResponse();
        if (queryId.isNull() == false) {
          queryResponse.setUri(queryURI);
        }

        queryResponse.setResultCode(response.getState().getReturnCode());
        queryResponse.setQuery(request.getQuery());
        return Response.status(Status.OK).entity(queryResponse).build();
      }
    }
  public static final Link buildURILibro(UriInfo uriInfo, Libro libro) {
    URI stingURI = uriInfo.getBaseUriBuilder().path(LibroResource.class).build();
    Link link = new Link();
    link.setUri(stingURI.toString());
    link.setRel("self");
    link.setTitle("Sting " + libro.getIdlibro());
    link.setType(MediaType.LIBROS_API_LIBRO);

    return link;
  }
Ejemplo n.º 18
0
 private String getProfileUri(UriInfo uriInfo, Message message) {
   String uri =
       uriInfo
           .getBaseUriBuilder()
           .path(ProfileResource.class)
           .path(message.getAuthor())
           .build()
           .toString();
   return uri;
 }
Ejemplo n.º 19
0
 private URI getAbsoluteRedirectUri(UriInfo ui) {
   if (redirectUri != null) {
     return URI.create(redirectUri);
   } else if (completeUri != null) {
     return completeUri.startsWith("http")
         ? URI.create(completeUri)
         : ui.getBaseUriBuilder().path(completeUri).build();
   } else {
     return ui.getAbsolutePath();
   }
 }
  public static final Link buildURIRootAPI(UriInfo uriInfo) {

    URI uriRoot = uriInfo.getBaseUriBuilder().path(LibrosRootAPIResource.class).build();
    Link link = new Link();
    link.setUri(uriRoot.toString());
    link.setRel("self bookmark");
    link.setTitle("Libros API");
    link.setType(MediaType.LIBROS_API_LINK_COLLECTION);

    return link;
  }
  public static LinkType getRadiologyLink(String diag, UriInfo uriInfo) {
    UriBuilder ub = uriInfo.getBaseUriBuilder();
    ub.path("radiologytreatment").path("{diagnosys}");
    String radiologyURI = ub.build(diag).toString();

    LinkType link = new LinkType();
    link.setUrl(radiologyURI);
    link.setRelation(Representation.RELATION_TREATMENT);
    link.setMediaType(Representation.MEDIA_TYPE);
    return link;
  }
Ejemplo n.º 22
0
  URI getLocation(UriInfo info, String id) {
    List<PathSegment> segments = info.getPathSegments();
    List<PathSegment> patate = segments.subList(0, segments.size() - 1);
    StringBuilder root = new StringBuilder();
    for (PathSegment s : patate) {
      root.append('/').append(s.getPath());
    }
    root.append("/session");

    return info.getBaseUriBuilder().path(root.toString()).path(id).build();
  }
Ejemplo n.º 23
0
  public static Asset toAsset(AssetItem a, UriInfo uriInfo) {
    AssetMetadata metadata = new AssetMetadata();
    metadata.setUuid(a.getUUID());
    metadata.setCreated(a.getCreatedDate().getTime());
    metadata.setDisabled(a.getDisabled());
    metadata.setFormat(a.getFormat());
    metadata.setNote("<![CDATA[ " + a.getCheckinComment() + " ]]>");
    metadata.setCheckInComment(a.getCheckinComment());
    metadata.setVersionNumber(a.getVersionNumber());
    List<CategoryItem> categories = a.getCategories();
    // TODO: Is this a bug since cat's are never assigned to metadata after this?
    String[] cats = new String[categories.size()];
    int counter = 0;
    for (CategoryItem c : categories) {
      cats[counter++] = c.getName();
    }

    Asset ret = new Asset();
    ret.setTitle(a.getTitle());
    ret.setBinaryContentAttachmentFileName(a.getBinaryContentAttachmentFileName());
    ret.setPublished(a.getLastModified().getTime());
    ret.setAuthor(a.getLastContributor());
    ret.setMetadata(metadata);
    ret.setDescription(a.getDescription());
    ret.setRefLink(
        uriInfo
            .getBaseUriBuilder()
            .path("/packages/{packageName}/assets/{assetName}")
            .build(a.getModule().getName(), a.getName()));
    ret.setBinaryLink(
        uriInfo
            .getBaseUriBuilder()
            .path("/packages/{packageName}/assets/{assetName}/binary")
            .build(a.getModule().getName(), a.getName()));
    ret.setSourceLink(
        uriInfo
            .getBaseUriBuilder()
            .path("/packages/{packageName}/assets/{assetName}/source")
            .build(a.getModule().getName(), a.getName()));
    return ret;
  }
  public static final Link buildTemplatedURILibros(
      UriInfo uriInfo, boolean titulo, boolean autor, String rel) {
    URI uriLibros = null;

    if (titulo == true && autor == false) {
      uriLibros =
          uriInfo
              .getBaseUriBuilder()
              .path(LibroResource.class)
              .path("/search")
              .queryParam("titulo", "{titulo}")
              .build();

    } else if (titulo == false && autor == true) {
      uriLibros =
          uriInfo
              .getBaseUriBuilder()
              .path(LibroResource.class)
              .path("/search")
              .queryParam("autor", "{autor}")
              .build();

    } else if (autor == true && titulo == true) {
      uriLibros =
          uriInfo
              .getBaseUriBuilder()
              .path(LibroResource.class)
              .path("/search")
              .queryParam("titulo", "{titulo}")
              .queryParam("autor", "{autor}")
              .build();
    }

    Link link = new Link();
    link.setUri(URITemplateBuilder.buildTemplatedURI(uriLibros));
    link.setRel(rel);
    link.setTitle("Stings collection resource");
    link.setType(MediaType.LIBROS_API_LIBRO_COLLECTION);

    return link;
  }
  public static final Link buildURILibros(
      UriInfo uriInfo, String titulo, String autor, String rel) {
    URI uriLibros = null;
    if (autor == null && titulo == null)
      uriLibros = uriInfo.getBaseUriBuilder().path(LibroResource.class).build();
    else {
      if (autor == null && titulo != null)
        uriLibros =
            uriInfo
                .getBaseUriBuilder()
                .path(LibroResource.class)
                .path("/search")
                .queryParam("titulo", titulo)
                .build();
      else if (titulo == null && autor != null)
        uriLibros =
            uriInfo
                .getBaseUriBuilder()
                .path(LibroResource.class)
                .path("/search")
                .queryParam("autor", autor)
                .build();
      else if (titulo != null && autor != null)
        uriLibros =
            uriInfo
                .getBaseUriBuilder()
                .path(LibroResource.class)
                .path("/search")
                .queryParam("titulo", titulo)
                .queryParam("autor", autor)
                .build();
    }

    Link self = new Link();
    self.setUri(uriLibros.toString());
    self.setRel("libros");
    self.setTitle("Libros collection");
    self.setType(MediaType.LIBROS_API_LIBRO_COLLECTION);

    return self;
  }
Ejemplo n.º 26
0
 private String getCommntUri(UriInfo uriInfo, Message message) {
   String uri =
       uriInfo
           .getBaseUriBuilder()
           .path(MessageRecource.class)
           .path(MessageRecource.class, "getCommentResource")
           .path(CommentResource.class)
           .resolveTemplate("messageId", message.getId())
           .build()
           .toString();
   return uri;
 }
 @Before
 public void setUp() throws Exception {
   initMocks(this);
   testObj = new FedoraRepositoryNodeTypes();
   setField(testObj, "nodeService", mockNodes);
   setField(testObj, "uriInfo", getUriInfoImpl());
   mockSession = mockSession(testObj);
   setField(testObj, "session", mockSession);
   when(mockUriInfo.getBaseUriBuilder()).thenReturn(mockUriBuilder);
   when(mockUriBuilder.path(any(Class.class))).thenReturn(mockUriBuilder);
   when(mockUriBuilder.build(any(String.class))).thenReturn(URI.create("mock:uri"));
 }
Ejemplo n.º 28
0
 @GET
 @Path("/{sitemapname: [a-zA-Z_0-9]*}/{pageid: [a-zA-Z_0-9]*}")
 @Produces({MediaType.WILDCARD})
 public SuspendResponse<Response> getPageData(
     @Context HttpHeaders headers,
     @PathParam("sitemapname") String sitemapname,
     @PathParam("pageid") String pageId,
     @QueryParam("type") String type,
     @QueryParam("jsoncallback") @DefaultValue("callback") String callback,
     @HeaderParam(HeaderConfig.X_ATMOSPHERE_TRANSPORT) String atmosphereTransport,
     @Context AtmosphereResource resource) {
   logger.debug(
       "Received HTTP GET request at '{}' for media type '{}'.",
       new String[] {uriInfo.getPath(), type});
   if (atmosphereTransport == null || atmosphereTransport.isEmpty()) {
     String responseType =
         MediaTypeHelper.getResponseMediaType(headers.getAcceptableMediaTypes(), type);
     if (responseType != null) {
       Object responseObject =
           responseType.equals(MediaTypeHelper.APPLICATION_X_JAVASCRIPT)
               ? new JSONWithPadding(
                   getPageBean(sitemapname, pageId, uriInfo.getBaseUriBuilder().build()), callback)
               : getPageBean(sitemapname, pageId, uriInfo.getBaseUriBuilder().build());
       throw new WebApplicationException(Response.ok(responseObject, responseType).build());
     } else {
       throw new WebApplicationException(Response.notAcceptable(null).build());
     }
   }
   GeneralBroadcaster sitemapBroadcaster =
       (GeneralBroadcaster)
           BroadcasterFactory.getDefault()
               .lookup(GeneralBroadcaster.class, resource.getRequest().getPathInfo(), true);
   sitemapBroadcaster.addStateChangeListener(new SitemapStateChangeListener());
   return new SuspendResponse.SuspendResponseBuilder<Response>()
       .scope(SCOPE.REQUEST)
       .resumeOnBroadcast(!ResponseTypeHelper.isStreamingTransport(resource.getRequest()))
       .broadcaster(sitemapBroadcaster)
       .outputComments(true)
       .build();
 }
  public static final Link buildURIResenas(UriInfo uriInfo, String rel) {
    URI uriResenas;

    uriResenas = uriInfo.getBaseUriBuilder().path(ResenaResource.class).build();

    Link self = new Link();
    self.setUri(uriResenas.toString());
    self.setRel(rel);
    self.setTitle("Reviews collection");
    self.setType(MediaType.LIBROS_API_RESENA_COLLECTION);

    return self;
  }
  public static final Link buildURIUsers(UriInfo uriInfo, String rel) {
    URI uriUsers;

    uriUsers = uriInfo.getBaseUriBuilder().path(UserResource.class).build();

    Link self = new Link();
    self.setUri(uriUsers.toString());
    self.setRel(rel);
    self.setTitle("Users collection");
    self.setType(MediaType.LIBROS_API_USER_COLLECTION);

    return self;
  }