@Test public void testGetEvent() throws URISyntaxException { UriInfo ui = mock(UriInfo.class); when(ui.getBaseUriBuilder()).then(new UriBuilderFactory(URI.create("http://mock"))); Request request = mock(Request.class); when(archivist.getEvent("5479-123456","eventSID")) .thenReturn(new Event(new URI("accounts/5479-1234567/transactions/txSID"))); Response response = service.getSingle(ui, request, "application/hal+json", "5479-123456", "eventSID"); EventRepresentation er = (EventRepresentation) response.getEntity(); assertEquals("http://mock/accounts/5479-1234567/transactions/txSID", er.getOrigin().getHref()); assertEquals("default", er.getCategory()); assertEquals("http://mock/account-events/default/" + er.getId(), er.getSelf().getHref()); response = service.getSingle(ui, request, "application/hal+json;no-real-type", "5479-123456", "eventSID"); assertEquals(415,response.getStatus()); }
private Response cacheAwareResponse( Request request, String entity, EntityTag etag, Date lastModified, int maxAge ) { final Response.ResponseBuilder builderLastMod = request.evaluatePreconditions(lastModified); if (builderLastMod != null) { return builderLastMod.build(); } final Response.ResponseBuilder builderEtag = request.evaluatePreconditions(etag); if (builderEtag != null) { return builderEtag.build(); } final CacheControl cc = new CacheControl(); cc.setMaxAge(maxAge); return Response.ok(entity) .tag(etag) .lastModified(lastModified) .cacheControl(cc) .build(); }
@GET public Response get(@PathParam("id") String id, @Context Request request, @HeaderParam("Range") Optional<String> range, @HeaderParam("If-Range") Optional<String> ifRange) { Optional<File> video = videosRepository.findById(id); if (!video.isPresent()) return Response.status(NOT_FOUND).build(); Optional<Response> notModifiedResponse = evaluateRequestPreconditions(video.get(), request); if (notModifiedResponse.isPresent()) return notModifiedResponse.get(); if (range.isPresent() && (!ifRange.isPresent() || ifRangePreconditionMatches(video.get(), ifRange.get()))) return videoPartResponse(video.get(), range.get()); return fullVideoResponse(video.get()); }
/** * Query via GET. * * @see <a href="http://www.w3.org/TR/sparql11-protocol/#query-operation"> * SPARQL 1.1 Protocol * </a> * @param req JAX-RS {@link Request} object * @param uriInfo JAX-RS {@link UriInfo} object * @param queryString the "query" query parameter * @param defgraphs the "default-graph-uri" query parameter * @param namedgraphs the "named-graph-uri" query parameter * @param inference the "inference" query parameter * @return the result of the SPARQL query */ @GET @Produces({ RDFMediaType.SPARQL_RESULTS_JSON, RDFMediaType.SPARQL_RESULTS_XML, RDFMediaType.SPARQL_RESULTS_CSV, RDFMediaType.SPARQL_RESULTS_TSV, RDFMediaType.RDF_TURTLE, RDFMediaType.RDF_YARS, RDFMediaType.RDF_NTRIPLES, RDFMediaType.RDF_XML, RDFMediaType.RDF_JSON }) public Response query( @Context Request req, @Context UriInfo uriInfo, @QueryParam("query") String queryString, @QueryParam("default-graph-uri") List<String> defgraphs, @QueryParam("named-graph-uri") List<String> namedgraphs, @QueryParam("inference") String inference) { return handleQuery( req, uriInfo, queryString, defgraphs, namedgraphs, inference); }
@GET @Produces({"application/hal+json", "application/hal+json;concept=location;v=1"}) @ApiOperation(value = "lists locations", response = LocationsRepresentation.class, authorizations = { @Authorization(value = "oauth2", scopes = {}), @Authorization(value = "oauth2-cc", scopes = {}), @Authorization(value = "oauth2-ac", scopes = {}), @Authorization(value = "oauth2-rop", scopes = {}), @Authorization(value = "Bearer") }, extensions = {@Extension(name = "roles", properties = { @ExtensionProperty(name = "advisor", value = "advisors are allowed getting every location"), @ExtensionProperty(name = "customer", value = "customer only allowed getting own locations")} )}, produces = "application/hal+json, application/hal+json;concept=locations;v=1", notes = "List all locations in a default projection, which is Location version 1" + "Supported projections and versions are: " + "Locations in version 1 " + "The Accept header for the default version is application/hal+json;concept=location;v=1.0.0.... " + "The format for the default version is {....}", nickname = "listLocations") @ApiResponses(value = { @ApiResponse(code = 415, message = "Content type not supported.") }) public Response list(@Context UriInfo uriInfo, @Context Request request, @HeaderParam("Accept") String accept) { return locationsProducers.getOrDefault(accept, this::handleUnsupportedContentType).getResponse(uriInfo, request); }
@Test public void testList() { Request request = mock(Request.class); UriInfo ui = mock(UriInfo.class); when(ui.getBaseUriBuilder()).then(new UriBuilderFactory(URI.create("http://mock"))); when(archivist.listAccounts("0")) .thenReturn(Arrays.asList(new Account("5479", "1", "Checking account", "cust-1"), new Account("5479", "2", "Savings account", "cust-1"))); Response response = service.list(ui, request, "0", "application/hal+json"); AccountsRepresentation accounts = (AccountsRepresentation) response.getEntity(); assertEquals(2, accounts.getAccounts().size()); assertEquals("http://mock/accounts", accounts.getSelf().getHref()); response = service.list(ui, request, "0", "application/hal+json;concept=non.existing;type"); assertEquals(415,response.getStatus()); }
@LogDuration(limit = 50) Response getServiceGeneration1Version1(UriInfo uriInfo, Request request, String accountNo) { Long no; try { no = Long.parseLong(accountNo); } catch (NumberFormatException e) { throw new WebApplicationException(Response.Status.BAD_REQUEST); } VirtualAccount virtualaccount = archivist.getAccount(no); LOGGER.info("Usage - application/hal+json;concept=virtualaccount;v=1"); return new EntityResponseBuilder<>(virtualaccount, ac -> new VirtualAccountRepresentation(ac, uriInfo)) .name("virtualaccount") .version("1") .maxAge(120) .build(request); }
@Test public void testCreate() throws Exception { Request request = mock(Request.class); UriInfo ui = mock(UriInfo.class); when(ui.getBaseUriBuilder()).then(new UriBuilderFactory(URI.create("http://mock"))); when(ui.getPath()).thenReturn("http://mock"); VirtualAccountUpdateRepresentation account = mock(VirtualAccountUpdateRepresentation.class); when(account.getVaNumber()).thenReturn("34"); when(account.getTotalBalance()).thenReturn("9890"); when(account.getCommittedBalance()).thenReturn("5123"); when(account.getUnCommittedBalance()).thenReturn("4767"); when(archivist.findAccountByAccountNumber(34L)).thenReturn(Optional.empty()); VirtualAccountRepresentation resp = (VirtualAccountRepresentation) service.createOrUpdate(ui, request, "34", account).getEntity(); assertEquals("34", resp.getVaNumber()); assertEquals("9890", account.getTotalBalance()); assertEquals("5123", account.getCommittedBalance()); assertEquals("4767", account.getUnCommittedBalance()); assertEquals("http://mock/virtualaccounts/" + resp.getVaNumber(), resp.getSelf().getHref()); }
@Test public void testUpdate() throws Exception { Request request = mock(Request.class); UriInfo ui = mock(UriInfo.class); when(ui.getBaseUriBuilder()).then(new UriBuilderFactory(URI.create("http://mock"))); when(ui.getPath()).thenReturn("http://mock"); VirtualAccount account = new VirtualAccount(1L, new BigDecimal(10), new BigDecimal(20), new BigDecimal(30)); VirtualAccountUpdateRepresentation accountlocationUpdate = mock(VirtualAccountUpdateRepresentation.class); when(accountlocationUpdate.getVaNumber()).thenReturn("55"); when(accountlocationUpdate.getUnCommittedBalance()).thenReturn("5555"); when(archivist.findAccountByAccountNumber(55L)).thenReturn(Optional.of(account)); VirtualAccountRepresentation resp = ( VirtualAccountRepresentation) service.createOrUpdate(ui, request, "55", accountlocationUpdate).getEntity(); assertEquals(account.getVaNumber().toString(), resp.getVaNumber()); assertEquals(account.getTotalBalance().toString(), resp.getTotalBalance()); assertEquals(account.getComittedBalance().toString(), resp.getCommittedBalance()); assertEquals(account.getUnCommittedBalance().toString(), resp.getUncommittedBalance()); assertEquals("http://mock/virtualaccounts/" + resp.getVaNumber(), resp.getSelf().getHref()); }
@GET @Produces({"application/hal+json", "application/hal+json;concept=customers;v=1"}) @ApiOperation(value = "lists customers", response = CustomersRepresentation.class, authorizations = { @Authorization(value = "oauth2", scopes = {}), @Authorization(value = "oauth2-cc", scopes = {}), @Authorization(value = "oauth2-ac", scopes = {}), @Authorization(value = "oauth2-rop", scopes = {}), @Authorization(value = "Bearer") }, extensions = {@Extension(name = "roles", properties = { @ExtensionProperty(name = "advisor", value = "advisors are allowed getting every customer"), @ExtensionProperty(name = "customer", value = "customer only allowed getting own information")} )}, produces = "application/hal+json, application/hal+json;concept=customers;v=1", notes = "List all customers in a default projection, which is Customers version 1" + "Supported projections and versions are: " + "Customers in version 1 " + "The Accept header for the default version is application/hal+json;concept=customers;v=1.0.0.... " + "The format for the default version is {....}", nickname = "listCustomers") @ApiResponses(value = { @ApiResponse(code = 415, message = "Content type not supported.") }) public Response list(@Context UriInfo uriInfo, @Context Request request, @HeaderParam("Accept") String accept) { return customersProducers.getOrDefault(accept, this::handleUnsupportedContentType).getResponse(uriInfo, request); }
@Test public void testListEventsByCategory() throws URISyntaxException { UriInfo ui = mock(UriInfo.class); when(ui.getBaseUriBuilder()).then(new UriBuilderFactory(URI.create("http://mock"))); Request request = mock(Request.class); when(archivist.getEventsForCategory(Event.getCategory("5479", "123456"), Optional.empty())) .thenReturn(Collections.singletonList(new Event(new URI("account-events/5479-1234567/eventSID"), "5479-123456", CurrentTime.now()))); Response response = service.getByCategory(ui, request, "application/hal+json", "5479-123456", ""); EventsRepresentation events = (EventsRepresentation) response.getEntity(); assertEquals(1, events.getEvents().size()); assertEquals("http://mock/account-events", events.getSelf().getHref()); response = service.getByCategory(ui, request, "application/hal+json;no-real-type", "5479-123456", ""); assertEquals(415,response.getStatus()); }
@Test public void testListEventsByCategory() throws URISyntaxException { UriInfo ui = mock(UriInfo.class); when(ui.getBaseUriBuilder()).then(new UriBuilderFactory(URI.create("http://mock"))); Request request = mock(Request.class); when(archivist.getEventsForCategory(Event.getCategory("some", "category"), Optional.empty())) .thenReturn(Collections.singletonList(new Event(new URI("customer-events/some-category/eventSID"), "some-category", CurrentTime.now()))); Response response = service.getByCategory(ui, request, "application/hal+json", "some-category", ""); EventsRepresentation events = (EventsRepresentation) response.getEntity(); assertEquals(1, events.getEvents().size()); assertEquals("http://mock/customer-events", events.getSelf().getHref()); response = service.getByCategory(ui, request, "application/hal+json;no-real-type", "some-category", ""); assertEquals(415,response.getStatus()); }
@Test public void testUpdate() throws Exception { Request request = mock(Request.class); UriInfo ui = mock(UriInfo.class); when(ui.getBaseUriBuilder()).then(new UriBuilderFactory(URI.create("http://mock"))); when(ui.getPath()).thenReturn("http://mock"); Account existingAcc = new Account("5479", "12345678", "Savings account", "cust-1"); when(archivist.findAccount("5479", "12345678")).thenReturn(Optional.of(existingAcc)); AccountUpdateRepresentation accountUpdate = mock(AccountUpdateRepresentation.class); when(accountUpdate.getName()).thenReturn("new name"); when(accountUpdate.getRegNo()).thenReturn("5479"); when(accountUpdate.getAccountNo()).thenReturn("12345678"); AccountRepresentation resp = (AccountRepresentation) service.createOrUpdate(ui, request, "5479", "12345678", accountUpdate).getEntity(); //name of the existing account should be updated assertEquals("new name", existingAcc.getName()); assertEquals("new name", resp.getName()); assertEquals("5479", resp.getRegNo()); assertEquals("12345678", resp.getAccountNo()); assertEquals("0", existingAcc.getBalance().toString()); assertEquals("0", resp.getBalance().toString()); assertEquals("http://mock/accounts/5479-12345678", resp.getSelf().getHref()); }
@GET @Produces({"application/hal+json", "application/hal+json;concept=metadata;v=1"}) @ApiOperation( value = "metadata for the events endpoint", response = EventsMetadataRepresentation.class, authorizations = { @Authorization(value = "oauth2", scopes = {}), @Authorization(value = "oauth2-cc", scopes = {}), @Authorization(value = "oauth2-ac", scopes = {}), @Authorization(value = "oauth2-rop", scopes = {}), @Authorization(value = "Bearer") }, notes = " the events are signalled by this resource as this this is the authoritative resource for all events that " + "subscribers to the customer service should be able to listen for and react to. In other words this is the authoritative" + "feed for the customer service", tags = {"events"}, produces = "application/hal+json, application/hal+json;concept=metadata;v=1", nickname = "getCustomerMetadata" ) @ApiResponses(value = { @ApiResponse(code = 415, message = "Content type not supported.") }) public Response getCustomerServiceMetadata(@Context UriInfo uriInfo, @Context Request request, @HeaderParam("Accept") String accept) { return eventMetadataProducers.getOrDefault(accept, this::handleUnsupportedContentType).getResponse(uriInfo, request); }
@Test public void testGet() { UriInfo ui = mock(UriInfo.class); when(ui.getBaseUriBuilder()).then(new UriBuilderFactory(URI.create("http://mock"))); Request request = mock(Request.class); Account account = mock(Account.class); when(account.getRegNo()).thenReturn("5479"); when(account.getAccountNo()).thenReturn("123456"); Transaction dbTransaction = new Transaction(account, new BigDecimal("1234.42"), "description"); when(archivist.getTransaction("5479", "123456", "xxx-yyy")).thenReturn(dbTransaction); Response response = service.get(ui, request, "application/hal+json","5479", "123456", "xxx-yyy"); TransactionRepresentation transaction = (TransactionRepresentation) response.getEntity(); assertEquals("1234.42", transaction.getAmount()); assertEquals("http://mock/accounts/5479-123456/transactions/" + dbTransaction.getId(), transaction.getSelf().getHref()); response = service.get(ui, request, "application/hal+json;concept=non.existing;type", "5479", "123456", "xxx-yyy"); assertEquals(415,response.getStatus()); }
@Test public void testList() { Request request = mock(Request.class); UriInfo ui = mock(UriInfo.class); when(ui.getBaseUriBuilder()).then(new UriBuilderFactory(URI.create("http://mock"))); when(archivist.listCustomers()) .thenReturn(Arrays.asList(new Customer("Hans", "Peter", "Hansen"), new Customer("Anders", "P", "Dinesen"))); Response response = service.list(ui, request, "application/hal+json"); CustomersRepresentation customers = (CustomersRepresentation) response.getEntity(); assertEquals(2, customers.getCustomers().size()); assertEquals("http://mock/customers", customers.getSelf().getHref()); response = service.list(ui, request, "application/hal+json;concept=non.existing;type"); assertEquals(415,response.getStatus()); }
@Test public void testCreate() throws Exception { Request request = mock(Request.class); UriInfo ui = mock(UriInfo.class); when(ui.getBaseUriBuilder()).then(new UriBuilderFactory(URI.create("http://mock"))); when(ui.getPath()).thenReturn("http://mock"); CustomerUpdateRepresentation customerUpdate = mock(CustomerUpdateRepresentation.class); when(customerUpdate.getFirstName()).thenReturn("Walther"); when(customerUpdate.getMiddleName()).thenReturn("Gunnar"); when(customerUpdate.getSirname()).thenReturn("Olesen"); when(customerUpdate.getNumber()).thenReturn("1234567890"); when(archivist.findCustomer("1234567890")).thenReturn(Optional.empty()); CustomerRepresentation resp = (CustomerRepresentation) service.createOrUpdate(ui, request, "1234567890", customerUpdate).getEntity(); assertEquals("Olesen", resp.getSirname()); assertEquals("Walther", resp.getFirstName()); assertEquals("Gunnar", resp.getMiddleName()); assertEquals("http://mock/customers/" + resp.getNumber(), resp.getSelf().getHref()); }
@GET @Produces({"application/hal+json", "application/hal+json;concept=metadata;v=1"}) @ApiOperation( value = "metadata for the events endpoint", response = EventsMetadataRepresentation.class, authorizations = { @Authorization(value = "oauth2", scopes = {}), @Authorization(value = "oauth2-cc", scopes = {}), @Authorization(value = "oauth2-ac", scopes = {}), @Authorization(value = "oauth2-rop", scopes = {}), @Authorization(value = "Bearer") }, notes = " the events are signalled by this resource as this this is the authoritative resource for all events that " + "subscribers to the account service should be able to listen for and react to. In other words this is the authoritative" + "feed for the account service", tags = {"events"}, produces = "application/hal+json, application/hal+json;concept=metadata;v=1", nickname = "getAccountMetadata" ) @ApiResponses(value = { @ApiResponse(code = 415, message = "Content type not supported.") }) public Response getMetadata(@Context UriInfo uriInfo, @Context Request request, @HeaderParam("Accept") String accept) { return eventMetadataProducers.getOrDefault(accept, this::handleUnsupportedContentType).getResponse(uriInfo, request); }
@Test public void testGet() { UriInfo ui = mock(UriInfo.class); when(ui.getBaseUriBuilder()).then(new UriBuilderFactory(URI.create("http://mock"))); Request request = mock(Request.class); Account account = mock(Account.class); when(account.getRegNo()).thenReturn("5479"); when(account.getAccountNo()).thenReturn("123456"); Transaction tx = new Transaction(account,new BigDecimal("123.45"), "not much"); ReconciledTransaction rtx = new ReconciledTransaction(true, "mocked decorated transaction", tx); when(archivist.getReconciledTransaction("5479", "123456", "xxx-yyy")).thenReturn(rtx); Response response = service.get( ui, request, "application/hal+json","5479", "123456", "xxx-yyy"); ReconciledTransactionRepresentation reconciledTx = (ReconciledTransactionRepresentation) response.getEntity(); assertEquals("mocked decorated transaction", reconciledTx.getNote()); assertEquals(true, reconciledTx.getReconciled()); assertEquals("http://mock/accounts/5479-123456/reconciled-transactions/" + tx.getId(), reconciledTx.getSelf().getHref()); assertEquals("http://mock/accounts/5479-123456/transactions/" + tx.getId(), reconciledTx.getTransaction().getHref()); response = service.get( ui, request, "application/hal+json;concept=non.existing;type","5479", "123456", "xxx-yyy"); assertEquals(415,response.getStatus()); }
@GET @Produces({"application/hal+json", "application/hal+json;concept=events;v=1"}) @ApiOperation( value = "obtain all events emitted by the customer-event service", response = EventsRepresentation.class, notes = " the events are signalled by this resource as this this is the authoritative resource for all events that " + "subscribers to the customers service should be able to listen for and react to. In other words this is the authoritative" + "feed for the customers service", authorizations = { @Authorization(value = "oauth2", scopes = {}), @Authorization(value = "oauth2-cc", scopes = {}), @Authorization(value = "oauth2-ac", scopes = {}), @Authorization(value = "oauth2-rop", scopes = {}), @Authorization(value = "Bearer") }, tags = {"interval", "events"}, produces = "application/hal+json, application/hal+json;concept=events;v=1", nickname = "listLocationAllEvents" ) @ApiResponses(value = { @ApiResponse(code = 415, message = "Content type not supported.") }) public Response listAll(@Context UriInfo uriInfo, @Context Request request, @HeaderParam("Accept") String accept, @QueryParam("interval") String interval) { return eventsProducers.getOrDefault(accept, this::handleUnsupportedContentType) .getResponse(uriInfo, request, interval); }
@Test public void testGet() { Request request = mock(Request.class); UriInfo ui = mock(UriInfo.class); when(ui.getBaseUriBuilder()).then(new UriBuilderFactory(URI.create("http://mock"))); when(archivist.getLocation("57.0214422", "9.8906541,16")).thenReturn(new Location("57.0214422", "9.8906541,16", "2")); LocationRepresentation location = (LocationRepresentation) service.get(ui, request, "57.0214422", "9.8906541,16", "application/hal+json" ).getEntity(); assertEquals("57.0214422", location.getLatitude()); assertEquals("9.8906541,16", location.getLongitude()); assertEquals("2", location.getAmplitude()); assertEquals("1", location.getNumber()); assertEquals("http://mock/locations/" + location.getLatitude() + "-" + location.getLongitude(), location.getSelf().getHref()); Response response = service.get(ui, request, "57.0214422", "9.8906541,16", "application/hal+json;concept=location;v=0"); assertEquals(415,response.getStatus()); }
@GET @Produces({"application/hal+json", "application/hal+json;concept=accountoverview;v=1"}) @ApiOperation(value = "lists accounts", response = AccountsRepresentation.class, authorizations = { @Authorization(value = "oauth2", scopes = {}), @Authorization(value = "oauth2-cc", scopes = {}), @Authorization(value = "oauth2-ac", scopes = {}), @Authorization(value = "oauth2-rop", scopes = {}), @Authorization(value = "Bearer") }, extensions = {@Extension(name = "roles", properties = { @ExtensionProperty(name = "advisor", value = "advisors are allowed getting every account"), @ExtensionProperty(name = "customer", value = "customer only allowed getting own accounts")} )}, produces = "application/hal+json, application/hal+json;concept=accountoverview;v=1", notes = "List all accounts in a default projection, which is AccountOverview version 1" + "Supported projections and versions are: " + "AccountOverview in version 1 " + "The Accept header for the default version is application/hal+json;concept=AccountOverview;v=1.0.0.... " + "The format for the default version is {....}", nickname = "listAccounts") @ApiResponses(value = { @ApiResponse(code = 415, message = "Content type not supported.") }) public Response list(@Context UriInfo uriInfo, @Context Request request, @QueryParam("customer") @DefaultValue("0") String customer, @HeaderParam("Accept") String accept) { return accountsProducers.getOrDefault(accept, this::handleUnsupportedContentType).getResponse(uriInfo, request, customer); }
@Test public void testVersionedMetadata(){ UriInfo ui = mock(UriInfo.class); when(ui.getBaseUriBuilder()).then(new UriBuilderFactory(URI.create("http://mock"))); Request request = mock(Request.class); Response response = service.getMetadata(ui, request, "application/hal+json;concept=metadata;v=1"); EventsMetadataRepresentation info = (EventsMetadataRepresentation) response.getEntity(); assertNotNull(info); assertTrue(info.getMetadata().contains("purpose")); assertEquals("http://mock/customer-events-metadata", info.getSelf().getHref()); }
@GET public Response get(@Context Request request) { ClimateDto currentClimate = stockholmClimateRepository.get(); EntityTag currentETag = eTagGenerator.eTagFor(currentClimate); Optional<Response> notModifiedResponse = evaluateETagPrecondition(request, currentETag); if (notModifiedResponse.isPresent()) return notModifiedResponse.get(); return Response.ok(currentClimate).tag(currentETag).build(); }
@GET @Path("{category}") @Produces({ "application/hal+json", "application/hal+json;concept=eventcategory;v=1"}) @ApiOperation(value = "obtain all events scoped to a certain category", response = EventsRepresentation.class, notes = " the events are signalled by this resource as this this is the authoritative resource for all events that " + "subscribers to the customer service should be able to listen for and react to. In other words this is the authoritative" + "feed for the customer service, allowing for subscribers to have these grouped into categories", authorizations = { @Authorization(value = "oauth2", scopes = {}), @Authorization(value = "oauth2-cc", scopes = {}), @Authorization(value = "oauth2-ac", scopes = {}), @Authorization(value = "oauth2-rop", scopes = {}), @Authorization(value = "Bearer") }, tags = {"interval", "events"}, produces = "application/hal+json, application/hal+json;concept=eventcategory;v=1", nickname = "getlocationEventsByCategory" ) @ApiResponses(value = { @ApiResponse(code = 415, message = "Content type not supported.") }) public Response getByCategory(@Context UriInfo uriInfo, @Context Request request, @HeaderParam("Accept") String accept, @PathParam("category") String category, @QueryParam("interval") String interval) { return eventCategoryProducers.getOrDefault(accept, this::handleUnsupportedContentType) .getResponse(uriInfo, request, category, interval); }
/** * Construct and {@link HttpRequest} using JAX-RS context informations * @param request Request * @param uriInfo URI informations * @param headers Headers informations */ public DefaultJaxrsHttpRequest(Request request, UriInfo uriInfo, HttpHeaders headers) { super(); ObjectUtils.argumentNotNull(uriInfo, "UriInfo must be not null"); ObjectUtils.argumentNotNull(headers, "HttpHeaders must be not null"); this.method = (request != null) ? request.getMethod() : null; this.uriInfo = uriInfo; this.headers = headers; this.queryParameters = uriInfo.getQueryParameters(); }
@LogDuration(limit = 50) public Response getMetaDataSG1V1(UriInfo uriInfo, Request request) { EventsMetadataRepresentation em = new EventsMetadataRepresentation("", uriInfo); CacheControl cc = new CacheControl(); int maxAge = 4 * 7 * 24 * 60 * 60; cc.setMaxAge(maxAge); return Response.ok() .entity(em) .cacheControl(cc).expires(Date.from(CurrentTime.now().plusSeconds(maxAge))) .type("application/hal+json;concept=metadata;v=1") .build(); }
@Test(expected = WebApplicationException.class) public void testCreateInvalidRequest() throws Exception { Request request = mock(Request.class); UriInfo ui = mock(UriInfo.class); AccountUpdateRepresentation accountUpdate = mock(AccountUpdateRepresentation.class); when(accountUpdate.getRegNo()).thenReturn("5479"); when(accountUpdate.getAccountNo()).thenReturn("12345678"); service.createOrUpdate(ui, request, "5479", "87654321", accountUpdate); fail("Should have thrown exception before this step"); }
/** * Returns RDF data from a graph in the repository. * * @see RDFStreamingOutput * @param req JAX-RS {@link Request} object * @param def the "default" query parameter * @param graphString the "graph" query parameter * @return RDF data as HTTP response */ private Response handleGet( Request req, String def, String graphString) { // select matching MIME-Type for response based on HTTP headers final Variant variant = req.selectVariant(rdfResultVariants); final MediaType mt = variant.getMediaType(); final String mtstr = mt.getType() + "/" + mt.getSubtype(); final RDFFormat format = getRDFFormat(mtstr); StreamingOutput stream; RepositoryConnection conn = null; try { // return data as RDF stream conn = getConnection(); if (graphString != null) { Resource ctx = vf.createURI(graphString); if (conn.size(ctx) == 0) { return Response.status(Response.Status.NOT_FOUND).build(); } stream = new RDFStreamingOutput(conn, format, ctx); } else { stream = new RDFStreamingOutput(conn, format); } } catch (RepositoryException ex) { // server error close(conn, ex); throw new WebApplicationException(ex); } return Response.ok(stream).build(); }
/** * デフォルトボックスへのアクセス. * @param request HTPPサーブレットリクエスト * @param jaxRsRequest JAX-RS用HTTPリクエスト * @return BoxResource BoxResource Object */ @Path("__") public BoxResource box(@Context final HttpServletRequest request, @Context final Request jaxRsRequest) { return new BoxResource(this.cell, Box.DEFAULT_BOX_NAME, this.accessContext, this.cellRsCmp, request, jaxRsRequest); }
@LogDuration(limit = 50) Response getServiceGeneration1Version2(UriInfo uriInfo, Request request, String regNo, String accountNo) { Account account = archivist.getAccount(regNo, accountNo); LOGGER.info("Usage - application/hal+json;concept=account;v=2"); return new EntityResponseBuilder<>(account, acc -> new AccountRepresentation(acc, acc.getTransactions(), uriInfo)) .name("account") .version("2") .maxAge(60) .build(request); }
@PUT public Response put(@Context Request request, @NotNull ClimateDto climate) { synchronized (transactionLock) { ClimateDto currentClimate = stockholmClimateRepository.get(); EntityTag currentETag = eTagGenerator.eTagFor(currentClimate); Optional<Response> preconditionFailedResponse = evaluateETagPrecondition(request, currentETag); if (preconditionFailedResponse.isPresent()) return preconditionFailedResponse.get(); stockholmClimateRepository.save(climate); } EntityTag eTag = eTagGenerator.eTagFor(climate); return Response.noContent().tag(eTag).build(); }
@LogDuration(limit = 50) Response getServiceGeneration1Version1(UriInfo uriInfo, Request request, String latitude, String longitude) { Location location = archivist.getLocation(latitude, longitude); LOGGER.info("Usage - application/hal+json;concept=location;v=1"); return new EntityResponseBuilder<>(location, cust -> new LocationRepresentation(cust, uriInfo)) .name("location") .version("1") .maxAge(120) .build(request); }
@Test public void testList() { UriInfo ui = mock(UriInfo.class); when(ui.getBaseUriBuilder()).then(new UriBuilderFactory(URI.create("http://mock"))); Request request = mock(Request.class); Account account = mock(Account.class); when(account.getRegNo()).thenReturn("5479"); when(account.getAccountNo()).thenReturn("123456"); Transaction tx= new Transaction("human-readable-sid", account, new BigDecimal("1234.42"), "description"); ReconciledTransaction rtx = new ReconciledTransaction(true,"This is a note", tx); when(account.getReconciledTransactions()) .thenReturn(new HashSet<>(Collections.singletonList(rtx))); when(archivist.getAccount("5479", "123456")).thenReturn(account); Response response = service.list( ui, request, "application/hal+json","5479", "123456"); ReconciledTransactionsRepresentation reconciledTxs = (ReconciledTransactionsRepresentation) response.getEntity(); assertEquals(1, reconciledTxs.getReconciledTransactions().size()); assertEquals("http://mock/accounts/5479-123456/reconciled-transactions", reconciledTxs.getSelf().getHref()); response = service.list( ui, request, "application/hal+json;concept=non.existing;type","5479", "123456"); assertEquals(415,response.getStatus()); }
@Test(expected = WebApplicationException.class) public void testCreateInvalidRequest() throws Exception { Request request = mock(Request.class); UriInfo ui = mock(UriInfo.class); VirtualAccountUpdateRepresentation account = mock(VirtualAccountUpdateRepresentation.class); when(account.getVaNumber()).thenReturn("1"); service.createOrUpdate(ui, request, "2", account); fail("Should have thrown exception before this step"); }
Response listServiceGeneration1Version1(UriInfo uriInfo, Request request) { List<Customer> customers = archivist.listCustomers(); return new EntityResponseBuilder<>(customers, list -> new CustomersRepresentation(list, uriInfo)) .name("customers") .version("1") .maxAge(10) .build(request); }
@LogDuration(limit = 50) Response getServiceGeneration1Version1(UriInfo uriInfo, Request request, String customerNo) { Customer customer = archivist.getCustomer(customerNo); LOGGER.info("Usage - application/hal+json;concept=customer;v=1"); return new EntityResponseBuilder<>(customer, cust -> new CustomerRepresentation(cust, uriInfo)) .name("customer") .version("1") .maxAge(120) .build(request); }
@Test public void testVersionedMetadata(){ UriInfo ui = mock(UriInfo.class); when(ui.getBaseUriBuilder()).then(new UriBuilderFactory(URI.create("http://mock"))); Request request = mock(Request.class); Response response = service.getMetadata(ui, request,"application/hal+json;concept=metadata;v=1"); EventsMetadataRepresentation info = (EventsMetadataRepresentation) response.getEntity(); assertNotNull(info); assertTrue(info.getMetadata().contains("purpose")); assertEquals("http://mock/account-events-metadata", info.getSelf().getHref()); }
@Test public void testList() { UriInfo ui = mock(UriInfo.class); when(ui.getBaseUriBuilder()).then(new UriBuilderFactory(URI.create("http://mock"))); Request request = mock(Request.class); Account account = mock(Account.class); when(account.getRegNo()).thenReturn("5479"); when(account.getAccountNo()).thenReturn("123456"); List<Sort> sort = Collections.emptyList(); when(archivist.getTransactions("5479", "123456", Optional.empty(), Optional.empty(), sort)).thenReturn( Arrays.asList( new Transaction(account, "id-1", new BigDecimal("1234.42"), "description 1", Instant.ofEpochMilli(1)), new Transaction(account, "id-2", new BigDecimal("2345.42"), "description 2", Instant.ofEpochMilli(2)) )); Response response = service.list(ui, request, "application/hal+json","5479", "123456", "", "", ""); TransactionsRepresentation transactions = (TransactionsRepresentation) response.getEntity(); assertEquals(2, transactions.getTransactions().size()); assertEquals("http://mock/accounts/5479-123456/transactions", transactions.getSelf().getHref()); response = service.list(ui, request, "application/hal+json;concept=non.existing;type","5479", "123456", "", "", ""); assertEquals(415,response.getStatus()); }