@GET
  @Path("/{id}")
  public Response get(@PathParam("id") int id, @Context Request request) {
    // Create cache control header
    CacheControl cc = new CacheControl();
    // Set max age to one day
    cc.setMaxAge(86400);

    Response.ResponseBuilder rb = null;

    // Calculate the ETag on last modified date of user resource
    EntityTag etag = new EntityTag(UserDao.getLastModifiedById(id).hashCode() + "");

    // Verify if it matched with etag available in http request
    rb = request.evaluatePreconditions(etag);

    // If ETag matches the rb will be non-null;
    // Use the rb to return the response without any further processing
    if (rb != null) {
      return rb.cacheControl(cc).tag(etag).build();
    }

    // If rb is null then either it is first time request; or resource is modified
    // Get the updated representation and return with Etag attached to it
    rb = Response.ok(UserDao.get(id).get()).cacheControl(cc).tag(etag);
    return rb.build();
  }
 @Test
 public void testPreconditionsNoneMatch() {
   MutableRequest mr = new MutableRequest("", "http://example.org/app/resource", "GET");
   mr.header(HttpHeaders.IF_NONE_MATCH, "\"686897696a7c876b7e\"");
   Request r = mr.toJaxrsRequest();
   assertEquals(
       r.evaluatePreconditions(new EntityTag("686897696a7c876b7e")).build().getStatus(),
       Status.NOT_MODIFIED.getStatusCode());
   assertNull(r.evaluatePreconditions(new EntityTag("000000000000000000")));
 }
 @Test
 public void testPreconditionsModified() throws ParseException {
   MutableRequest mr = new MutableRequest("", "http://example.org/app/resource", "GET");
   mr.header(HttpHeaders.IF_MODIFIED_SINCE, "Sat, 29 Oct 2011 19:43:31 GMT");
   Request r = mr.toJaxrsRequest();
   SimpleDateFormat f = new SimpleDateFormat("E, dd MMM yyyy HH:mm:ss Z", Locale.ENGLISH);
   Date date = f.parse("Sat, 29 Oct 2011 19:43:31 GMT");
   assertEquals(
       r.evaluatePreconditions(date).build().getStatus(), Status.NOT_MODIFIED.getStatusCode());
   date = f.parse("Sat, 30 Oct 2011 19:43:31 GMT");
   assertNull(r.evaluatePreconditions(date));
 }
 @Test
 public void testSelectVariant() {
   MutableRequest mr = new MutableRequest("", "http://example.org/app/resource", "GET");
   mr.header(HttpHeaders.ACCEPT, MediaType.APPLICATION_JSON);
   mr.header(HttpHeaders.ACCEPT_LANGUAGE, "en");
   Request r = mr.toJaxrsRequest();
   List<Variant> lv =
       Variant.mediaTypes(MediaType.APPLICATION_XML_TYPE, MediaType.APPLICATION_JSON_TYPE)
           .languages(Locale.ENGLISH, Locale.FRENCH)
           .add()
           .build();
   assertEquals(r.selectVariant(lv).getMediaType(), MediaType.APPLICATION_JSON_TYPE);
   assertEquals(r.selectVariant(lv).getLanguage(), Locale.ENGLISH);
 }
示例#5
0
 public UsageMessage getUsageMessage(Application application, UriInfo uriInfo, Request request)
     throws ClassNotFoundException, IOException {
   UsageMessage usage = new UsageMessage();
   usage.setMessage(RESPONSE);
   usage.setDetailedLink(findUsage(getRSDL(application), uriInfo, request.getMethod()));
   return usage;
 }
示例#6
0
 @Path("")
 @DELETE
 public Response resetBank() {
   log.debug("{} {}", request.getMethod(), uriInfo.getRequestUri());
   service.resetBank();
   return Response.noContent().build();
 }
  private static void evaluateRequestPreconditions(
      final Request request,
      final HttpServletResponse servletResponse,
      final FedoraResource resource,
      final Session session,
      final boolean cacheControl) {

    final String txId = TransactionServiceImpl.getCurrentTransactionId(session);
    if (txId != null) {
      // Force cache revalidation if in a transaction
      servletResponse.addHeader(CACHE_CONTROL, "must-revalidate");
      servletResponse.addHeader(CACHE_CONTROL, "max-age=0");
      return;
    }

    final EntityTag etag = new EntityTag(resource.getEtagValue());
    final Date date = resource.getLastModifiedDate();
    final Date roundedDate = new Date();

    if (date != null) {
      roundedDate.setTime(date.getTime() - date.getTime() % 1000);
    }

    Response.ResponseBuilder builder = request.evaluatePreconditions(etag);
    if (builder != null) {
      builder = builder.entity("ETag mismatch");
    } else {
      builder = request.evaluatePreconditions(roundedDate);
      if (builder != null) {
        builder = builder.entity("Date mismatch");
      }
    }

    if (builder != null && cacheControl) {
      final CacheControl cc = new CacheControl();
      cc.setMaxAge(0);
      cc.setMustRevalidate(true);
      // here we are implicitly emitting a 304
      // the exception is not an error, it's genuinely
      // an exceptional condition
      builder = builder.cacheControl(cc).lastModified(date).tag(etag);
    }
    if (builder != null) {
      throw new WebApplicationException(builder.build());
    }
  }
 @Test
 public void testGetVersionList() {
   when(mockRequest.selectVariant(POSSIBLE_RDF_VARIANTS)).thenReturn(mockVariant);
   when(mockNodes.find(any(Session.class), anyString())).thenReturn(mockResource);
   when(mockResource.getTriples(any(IdentifierConverter.class), eq(VersionsRdfContext.class)))
       .thenReturn(mockRdfStream);
   when(mockResource.isVersioned()).thenReturn(true);
   when(mockVariant.getMediaType()).thenReturn(new MediaType("text", "turtle"));
   final RdfStream response = testObj.getVersionList();
   assertEquals("Got wrong RdfStream!", mockRdfStream, response);
 }
示例#9
0
  protected ResourceState getCurrentState(ResourceState serviceDocument, String resourcePath) {
    ResourceState state = null;
    if (resourcePath != null) {
      /*
       * add a leading '/' if it needs it (when defining resources we must use a
       * full path, but requests can be relative, i.e. without a '/'
       */
      if (!resourcePath.startsWith("/")) {
        resourcePath = "/" + resourcePath;
      }
      // add service document path to resource path
      String serviceDocumentPath = serviceDocument.getPath();
      if (serviceDocumentPath.endsWith("/")) {
        serviceDocumentPath =
            serviceDocumentPath.substring(0, serviceDocumentPath.lastIndexOf("/"));
      }
      resourcePath = serviceDocumentPath + resourcePath;
      // turn the uri back into a template uri
      MultivaluedMap<String, String> pathParameters = uriInfo.getPathParameters();
      if (pathParameters != null) {
        for (String key : pathParameters.keySet()) {
          List<String> values = pathParameters.get(key);
          for (String value : values) {
            resourcePath = resourcePath.replace(value, "{" + key + "}");
          }
        }
      }
      String httpMethod = requestContext.getMethod();
      Event event = new Event(httpMethod, httpMethod);
      state = resourceStateProvider.determineState(event, resourcePath);

      if (state == null) {
        logger.warn("No state found, dropping back to path matching " + resourcePath);
        // escape the braces in the regex
        resourcePath = Pattern.quote(resourcePath);
        Map<String, Set<String>> pathToResourceStates =
            resourceStateProvider.getResourceStatesByPath();
        for (String path : pathToResourceStates.keySet()) {
          for (String name : pathToResourceStates.get(path)) {
            ResourceState s = resourceStateProvider.getResourceState(name);
            String pattern = null;
            if (s instanceof CollectionResourceState) {
              pattern = resourcePath + "(|\\(\\))";
              Matcher matcher = Pattern.compile(pattern).matcher(path);
              if (matcher.matches()) {
                state = s;
              }
            }
          }
        }
      }
    }
    return state;
  }
示例#10
0
 @Test
 public void testGetVersionList() throws RepositoryException {
   final String pid = "FedoraVersioningTest";
   when(mockRequest.selectVariant(POSSIBLE_RDF_VARIANTS)).thenReturn(mockVariant);
   when(mockNodes.getObject(any(Session.class), anyString())).thenReturn(mockResource);
   when(mockResource.getVersionTriples(any(HttpIdentifierTranslator.class)))
       .thenReturn(mockRdfStream);
   when(mockVariant.getMediaType()).thenReturn(new MediaType("text", "turtle"));
   final RdfStream response =
       testObj.getVersionList(createPathList(pid), mockRequest, getUriInfoImpl());
   assertEquals("Got wrong RdfStream!", mockRdfStream, response);
 }
示例#11
0
 @GET
 @Produces(MediaType.APPLICATION_JSON)
 public Response getJSON(@Context Request request) {
   EntityTag etag = new EntityTag(data().getVersioned().getUniqueId().toString());
   ResponseBuilder builder = request.evaluatePreconditions(etag);
   if (builder != null) {
     return builder.build();
   }
   FlexiBean out = createRootData();
   String json = getFreemarker().build("holidays/jsonholiday.ftl", out);
   return Response.ok(json).tag(etag).build();
 }
 public Object getTasks(
     Request request, UriInfo uriInfo, Integer firstResult, Integer maxResults) {
   Variant variant = request.selectVariant(VARIANTS);
   if (variant != null) {
     if (MediaType.APPLICATION_JSON_TYPE.equals(variant.getMediaType())) {
       return getJsonTasks(uriInfo, firstResult, maxResults);
     } else if (Hal.APPLICATION_HAL_JSON_TYPE.equals(variant.getMediaType())) {
       return getHalTasks(uriInfo, firstResult, maxResults);
     }
   }
   throw new InvalidRequestException(
       Response.Status.NOT_ACCEPTABLE, "No acceptable content-type found");
 }
示例#13
0
  /**
   * Delete all glossary terms.
   *
   * @return The following response status codes will be returned from this operation:<br>
   *     OK(200) - If the glossary entries were successfully deleted. UNAUTHORIZED(401) - If the
   *     user does not have the proper permissions to perform this operation.<br>
   *     INTERNAL SERVER ERROR(500) - If there is an unexpected error in the server while performing
   *     this operation.
   */
  @Override
  @DELETE
  @Restrict("#{s:hasPermission('', 'glossary-delete')}")
  public Response deleteGlossaries() {
    ResponseBuilder response = request.evaluatePreconditions();
    if (response != null) {
      return response.build();
    }
    int rowCount = glossaryDAO.deleteAllEntries();
    log.info("Glossary delete all: " + rowCount);

    return Response.ok().build();
  }
 public static boolean isPaged(HttpServletRequest httpRequest, Request request) {
   String accept = httpRequest.getHeader("Accept");
   if (StringHelper.containsNonWhitespace(accept)) {
     MediaType requestMediaType = MediaType.valueOf(accept);
     if (APPLICATION_JSON_PAGED.equals(requestMediaType)
         || APPLICATION_XML_PAGED.equals(requestMediaType)) {
       return true;
     }
   }
   Variant variant = request.selectVariant(variants);
   return (variant != null
       && (variant.equals(APPLICATION_JSON_PAGED) || variant.equals(APPLICATION_XML_PAGED)));
 }
示例#15
0
 @Path("")
 @GET
 @Produces(MediaType.APPLICATION_XML)
 @Formatted
 public Response getBank() {
   log.debug("{} {}", request.getMethod(), uriInfo.getRequestUri());
   Bank bank = service.getBank();
   URI self = new BankRefs(uriInfo).setHRefs(bank);
   log.debug("returning bank:\n{}", bank.toXML());
   return Response.ok(bank, MediaType.APPLICATION_XML)
       .contentLocation(self)
       .lastModified(bank.getUpdated())
       .build();
 }
示例#16
0
  private Response buildResponse(
      final Request request, final HttpHeaders headers, final Object entity) {

    final EntityTag tag = makeTag(entity, headers);

    Response.ResponseBuilder builder = request.evaluatePreconditions(tag);
    if (builder == null) {
      // preconditions are not met and the cache is invalid
      // need to send new value with reponse code 200 (OK)
      builder = Response.ok(entity);
      builder.tag(tag);
    }
    return builder.build();
  }
示例#17
0
  @GET
  public Response getItem() {
    System.out.println("GET ITEM " + container + " " + item);

    Item i = MemoryStore.MS.getItem(container, item);
    if (i == null) throw new NotFoundException("Item not found");
    Date lastModified = i.getLastModified().getTime();
    EntityTag et = new EntityTag(i.getDigest());
    ResponseBuilder rb = request.evaluatePreconditions(lastModified, et);
    if (rb != null) return rb.build();

    byte[] b = MemoryStore.MS.getItemData(container, item);
    return Response.ok(b, i.getMimeType()).lastModified(lastModified).tag(et).build();
  }
示例#18
0
  /**
   * Delete all glossary terms with the specified locale.
   *
   * @param targetLocale The target locale to delete glossary entries from.
   * @return The following response status codes will be returned from this operation:<br>
   *     OK(200) - If the glossary entries were successfully deleted. UNAUTHORIZED(401) - If the
   *     user does not have the proper permissions to perform this operation.<br>
   *     INTERNAL SERVER ERROR(500) - If there is an unexpected error in the server while performing
   *     this operation.
   */
  @Override
  @DELETE
  @Path("/{locale}")
  @Restrict("#{s:hasPermission('', 'glossary-delete')}")
  public Response deleteGlossary(@PathParam("locale") LocaleId targetLocale) {
    ResponseBuilder response = request.evaluatePreconditions();
    if (response != null) {
      return response.build();
    }

    int rowCount = glossaryDAO.deleteAllEntries(targetLocale);
    log.info("Glossary delete (" + targetLocale + "): " + rowCount);

    return Response.ok().build();
  }
示例#19
0
 @Path("")
 @PUT
 @Consumes(MediaType.APPLICATION_XML)
 public Response updateBank(Bank bank) {
   log.debug("{} {}", request.getMethod(), uriInfo.getRequestUri());
   if (service.updateBank(bank) == 0) {
     log.debug("updated bank:\n{}", bank.toXML());
     return Response.noContent().build();
   } else {
     return Response.status(Status.BAD_REQUEST)
         .entity(String.format("cannot update bank"))
         .type(MediaType.TEXT_PLAIN)
         .build();
   }
 }
示例#20
0
  @GET
  @Path("/{id}")
  public Response getWebLogon(@PathParam("id") Long id) throws Exception {
    String method = request.getMethod();
    System.out.printf("method: %s%n", method);

    WebLogon webLogon = new WebLogon();
    webLogon.setUsername("johndoe");
    webLogon.setEmail("*****@*****.**");
    webLogon.setPassword("password");
    webLogon.setNotes("notes");
    webLogon.setUrl(new URI("http://www.yahoo.com"));

    URI self = uriInfo.getRequestUri();
    webLogon.setSelf(self);
    return Response.ok(webLogon).build();
  }
示例#21
0
 @GET
 @Produces(MediaType.APPLICATION_JSON)
 public Response getJSON(@Context Request request) {
   EntityTag etag = new EntityTag(data().getConfig().getUniqueId().toString());
   ResponseBuilder builder = request.evaluatePreconditions(etag);
   if (builder != null) {
     return builder.build();
   }
   FlexiBean out = createRootData();
   ConfigDocument doc = data().getConfig();
   String jsonConfig = StringUtils.stripToNull(toJSON(doc.getConfig().getValue(), doc.getType()));
   if (jsonConfig != null) {
     out.put("configJSON", jsonConfig);
   } else {
     out.put("configXML", StringEscapeUtils.escapeJavaScript(createXML(doc)));
   }
   out.put("type", doc.getType().getName());
   String json = getFreemarker().build("configs/jsonconfig.ftl", out);
   return Response.ok(json).tag(etag).build();
 }
示例#22
0
  /**
   * Returns all Glossary entries.
   *
   * @return The following response status codes will be returned from this operation:<br>
   *     OK(200) - Response containing all Glossary entries in the system. INTERNAL SERVER
   *     ERROR(500) - If there is an unexpected error in the server while performing this operation.
   */
  @Override
  @GET
  @Produces({
    MediaTypes.APPLICATION_ZANATA_GLOSSARY_XML,
    MediaTypes.APPLICATION_ZANATA_GLOSSARY_JSON,
    MediaType.APPLICATION_XML,
    MediaType.APPLICATION_JSON
  })
  @TypeHint(Glossary.class)
  public Response getEntries() {
    ResponseBuilder response = request.evaluatePreconditions();
    if (response != null) {
      return response.build();
    }

    List<HGlossaryEntry> hGlosssaryEntries = glossaryDAO.getEntries();

    Glossary glossary = new Glossary();
    transferEntriesResource(hGlosssaryEntries, glossary);

    return Response.ok(glossary).build();
  }
示例#23
0
  /**
   * Adds glossary entries.
   *
   * @param glossary The Glossary entries to add.
   * @return The following response status codes will be returned from this operation:<br>
   *     CREATED(201) - If the glossary entries were successfully created. UNAUTHORIZED(401) - If
   *     the user does not have the proper permissions to perform this operation.<br>
   *     INTERNAL SERVER ERROR(500) - If there is an unexpected error in the server while performing
   *     this operation.
   */
  @Override
  @PUT
  @Consumes({
    MediaTypes.APPLICATION_ZANATA_GLOSSARY_XML,
    MediaTypes.APPLICATION_ZANATA_GLOSSARY_JSON,
    MediaType.APPLICATION_XML,
    MediaType.APPLICATION_JSON
  })
  @Restrict("#{s:hasPermission('', 'glossary-insert')}")
  public Response put(Glossary glossary) {
    ResponseBuilder response;

    // must be a create operation
    response = request.evaluatePreconditions();
    if (response != null) {
      return response.build();
    }
    response = Response.created(uri.getAbsolutePath());

    glossaryFileServiceImpl.saveGlossary(glossary);

    return response.build();
  }
示例#24
0
  /**
   * Get the binary content of a datastream
   *
   * @param pathList
   * @return Binary blob
   * @throws RepositoryException
   */
  @GET
  public Response getContent(
      @PathParam("path") List<PathSegment> pathList, @Context final Request request)
      throws RepositoryException {

    String path = toPath(pathList);
    final Datastream ds = datastreamService.getDatastream(path);

    final EntityTag etag = new EntityTag(ds.getContentDigest().toString());
    final Date date = ds.getLastModifiedDate();
    final Date roundedDate = new Date();
    roundedDate.setTime(date.getTime() - date.getTime() % 1000);
    ResponseBuilder builder = request.evaluatePreconditions(roundedDate, etag);

    final CacheControl cc = new CacheControl();
    cc.setMaxAge(0);
    cc.setMustRevalidate(true);

    if (builder == null) {
      builder = Response.ok(ds.getContent(), ds.getMimeType());
    }

    return builder.cacheControl(cc).lastModified(date).tag(etag).build();
  }
示例#25
0
  @POST
  @Path("/studies")
  @Consumes({"multipart/related", "multipart/form-data"})
  public Response storeInstances(InputStream in) throws Exception {
    String str = req.toString();
    LOG.info(str);
    init();
    final StoreSession session = storeService.createStoreSession(storeService);
    session.setSource(new HttpSource(request));
    ApplicationEntity sourceAE = aeCache.findAE(new HttpSource(request));
    session.setRemoteAET(
        sourceAE != null ? sourceAE.getAETitle() : null); // add AE for the web source
    session.setArchiveAEExtension(arcAE);
    storeService.initStorageSystem(session);
    storeService.initSpoolDirectory(session);
    storeService.initMetaDataStorageSystem(session);
    try {
      new MultipartParser(boundary)
          .parse(
              in,
              new MultipartParser.Handler() {

                @Override
                public void bodyPart(int partNumber, MultipartInputStream in) throws IOException {
                  Map<String, List<String>> headerParams = in.readHeaderParams();
                  String transferSyntax = null;
                  LOG.info("storeInstances: Extract Part #{}{}", partNumber, headerParams);
                  String contentType = getHeaderParamValue(headerParams, "content-type");
                  String contentLocation = getHeaderParamValue(headerParams, "content-location");
                  MediaType mediaType;
                  try {
                    mediaType =
                        contentType == null
                            ? MediaType.TEXT_PLAIN_TYPE
                            : MediaType.valueOf(contentType);
                  } catch (IllegalArgumentException e) {
                    LOG.info(
                        "storeInstances: Ignore Part with illegal Content-Type={}", contentType);
                    in.skipAll();
                    return;
                  }
                  // check for metadata transfer syntax

                  if (contentLocation == null) {
                    transferSyntax =
                        contentType.contains("transfer-syntax=")
                            ? contentType.split("transfer-syntax=")[1]
                            : null;
                  }
                  if (!creatorType.readBodyPart(
                      StowRS.this, session, in, mediaType, contentLocation, transferSyntax)) {
                    LOG.info("storeInstances: Ignore Part with Content-Type={}", mediaType);
                    in.skipAll();
                  }
                }
              });
      creatorType.storeMetadataAndBulkdata(this, session);
    } finally {
      storeService.onClose(session);
    }
    return buildResponse();
  }
示例#26
0
 @Test
 public void testUri() throws URISyntaxException {
   MutableRequest r = new MutableRequest("", "http://example.org/app/resource", "GET");
   Request v = r.toJaxrsRequest();
   assertEquals(v.getUri(), URI.create("http://example.org/app/resource"));
 }
示例#27
0
 @Test
 public void testMethod() {
   MutableRequest r = new MutableRequest("", "http://example.org/app/resource", "GET");
   Request v = r.toJaxrsRequest();
   assertEquals(v.getMethod(), "GET");
 }