Skip to content

Commit

Permalink
Prefer static import syntax for structured type classes (#270)
Browse files Browse the repository at this point in the history
  • Loading branch information
beckermarc authored Nov 21, 2023
1 parent 8be1a33 commit 17a78d4
Show file tree
Hide file tree
Showing 6 changed files with 30 additions and 30 deletions.
9 changes: 5 additions & 4 deletions srv/src/main/java/my/bookshop/RatingCalculator.java
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
package my.bookshop;

import static cds.gen.my.bookshop.Bookshop_.BOOKS;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.OptionalDouble;
Expand All @@ -13,7 +15,6 @@
import com.sap.cds.services.persistence.PersistenceService;

import cds.gen.my.bookshop.Books;
import cds.gen.my.bookshop.Bookshop_;
import cds.gen.my.bookshop.Reviews;

/**
Expand All @@ -33,7 +34,7 @@ public class RatingCalculator {
* Initializes the ratings for all existing books based on their reviews.
*/
public void initBookRatings() {
Result result = db.run(Select.from(Bookshop_.BOOKS).columns(b -> b.ID()));
Result result = db.run(Select.from(BOOKS).columns(b -> b.ID()));
for (Books book : result.listOf(Books.class)) {
setBookRating(book.getId());
}
Expand All @@ -45,12 +46,12 @@ public void initBookRatings() {
* @param bookId
*/
public void setBookRating(String bookId) {
Result run = db.run(Select.from(Bookshop_.BOOKS, b -> b.filter(b.ID().eq(bookId)).reviews()));
Result run = db.run(Select.from(BOOKS, b -> b.filter(b.ID().eq(bookId)).reviews()));

Stream<Double> ratings = run.streamOf(Reviews.class).map(r -> r.getRating().doubleValue());
BigDecimal rating = getAvgRating(ratings);

db.run(Update.entity(Bookshop_.BOOKS).byId(bookId).data(Books.RATING, rating));
db.run(Update.entity(BOOKS).byId(bookId).data(Books.RATING, rating));
}

static BigDecimal getAvgRating(Stream<Double> ratings) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -296,7 +296,7 @@ public void addBooksViaCsv(CdsUpdateEventContext context, Upload upload) {

// separate transaction per line
context.getCdsRuntime().changeSetContext().run(ctx -> {
db.run(Upsert.into(Bookshop_.BOOKS).entry(book));
db.run(Upsert.into(BOOKS).entry(book));
});
});
} catch (IOException e) {
Expand Down
22 changes: 8 additions & 14 deletions srv/src/main/java/my/bookshop/handlers/CatalogServiceHandler.java
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package my.bookshop.handlers;

import static cds.gen.catalogservice.CatalogService_.BOOKS;
import static cds.gen.catalogservice.CatalogService_.REVIEWS;

import java.util.List;
import java.util.Optional;
Expand Down Expand Up @@ -36,7 +37,6 @@
import cds.gen.catalogservice.Books_;
import cds.gen.catalogservice.CatalogService_;
import cds.gen.catalogservice.Reviews;
import cds.gen.catalogservice.Reviews_;
import cds.gen.catalogservice.SubmitOrderContext;
import cds.gen.reviewservice.ReviewService;
import cds.gen.reviewservice.ReviewService_;
Expand Down Expand Up @@ -84,12 +84,12 @@ public void beforeAddReview(AddReviewContext context) {
String user = context.getUserInfo().getName();
String bookId = (String) analyzer.analyze(context.getCqn()).targetKeys().get(Books.ID);

Result result = db.run(Select.from(CatalogService_.REVIEWS)
Result result = db.run(Select.from(REVIEWS)
.where(review -> review.book_ID().eq(bookId).and(review.createdBy().eq(user))));

if (result.first().isPresent()) {
throw new ServiceException(ErrorStatuses.METHOD_NOT_ALLOWED, MessageKeys.REVIEW_ADD_FORBIDDEN)
.messageTarget(Reviews_.class, r -> r.createdBy());
.messageTarget(REVIEWS, r -> r.createdBy());
}
}

Expand All @@ -100,23 +100,17 @@ public void beforeAddReview(AddReviewContext context) {
*/
@On(entity = Books_.CDS_NAME)
public void onAddReview(AddReviewContext context) {
Integer rating = context.getRating();
String title = context.getTitle();
String text = context.getText();

String bookId = (String) analyzer.analyze(context.getCqn()).targetKeys().get(Books.ID);

cds.gen.reviewservice.Reviews review = cds.gen.reviewservice.Reviews.create();
review.setBookId(bookId);
review.setRating(rating);
review.setTitle(title);
review.setText(text);
review.setRating(context.getRating());
review.setTitle(context.getTitle());
review.setText(context.getText());

Result res = reviewService.run(Insert.into(ReviewService_.REVIEWS).entry(review));
cds.gen.reviewservice.Reviews inserted = res.single(cds.gen.reviewservice.Reviews.class);

messages.success(MessageKeys.REVIEW_ADDED);

context.setResult(Struct.access(inserted).as(Reviews.class));
}

Expand Down Expand Up @@ -148,7 +142,7 @@ public void setIsReviewable(CdsReadEventContext context, List<Books> books) {
return;
}

CqnSelect query = Select.from(CatalogService_.BOOKS, b -> b.filter(b.ID().in(bookIds)).reviews())
CqnSelect query = Select.from(BOOKS, b -> b.filter(b.ID().in(bookIds)).reviews())
.where(r -> r.createdBy().eq(user));

Set<String> reviewedBooks = db.run(query).streamOf(Reviews.class).map(Reviews::getBookId)
Expand All @@ -169,7 +163,7 @@ public void onSubmitOrder(SubmitOrderContext context) {
Optional<Books> book = db.run(Select.from(BOOKS).columns(Books_::stock).byId(bookId)).first(Books.class);

book.orElseThrow(() -> new ServiceException(ErrorStatuses.NOT_FOUND, MessageKeys.BOOK_MISSING)
.messageTarget(Books_.class, b -> b.ID()));
.messageTarget(BOOKS, b -> b.ID()));

int stock = book.map(Books::getStock).get();

Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,8 @@
package my.bookshop.handlers;

import static cds.gen.notesservice.NotesService_.ADDRESSES;
import static cds.gen.notesservice.NotesService_.NOTES;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
Expand Down Expand Up @@ -57,7 +60,7 @@ Result readAddresses(CdsReadEventContext context) {
// via note
if(segments.size() == 2 && segments.get(0).id().equals(Notes_.CDS_NAME)) {
Map<String, Object> noteKeys = analyzer.analyze(context.getCqn()).rootKeys();
Notes note = context.getService().run(Select.from(Notes_.class).columns(n -> n.address_businessPartner(), n -> n.address_ID()).matching(noteKeys)).single(Notes.class);
Notes note = context.getService().run(Select.from(NOTES).columns(n -> n.address_businessPartner(), n -> n.address_ID()).matching(noteKeys)).single(Notes.class);
CqnSelect addressOfNote = CQL.copy(context.getCqn(), new Modifier() {

@Override
Expand Down Expand Up @@ -89,7 +92,7 @@ public List<CqnSelectListItem> items(List<CqnSelectListItem> items) {
// add expanded notes?
CqnExpand notesExpand = notesExpandHolder.get();
if(notesExpand != null) {
Select<?> notesSelect = Select.from(Notes_.class)
Select<?> notesSelect = Select.from(NOTES)
.columns(ensureSelected(notesExpand.items(), Notes.ADDRESS_BUSINESS_PARTNER, Notes.ADDRESS_ID))
.orderBy(notesExpand.orderBy())
.where(n -> CQL.or(addresses.streamOf(Addresses.class)
Expand Down Expand Up @@ -155,7 +158,7 @@ public List<CqnSelectListItem> items(List<CqnSelectListItem> items) {
Result notes = context.getService().run(noAddressExpand);
List<Notes> notesWithAddresses = notes.streamOf(Notes.class).filter(n -> n.getAddressBusinessPartner() != null && n.getAddressId() != null).collect(Collectors.toList());
if (notesWithAddresses.size() > 0) {
Select<?> addressSelect = Select.from(Addresses_.class)
Select<?> addressSelect = Select.from(ADDRESSES)
.columns(ensureSelected(addressExpand.items(), Addresses.BUSINESS_PARTNER, Addresses.ID))
.orderBy(addressExpand.orderBy())
.where(a -> CQL.or(notesWithAddresses.stream()
Expand Down
6 changes: 3 additions & 3 deletions srv/src/test/java/my/bookshop/AdminServiceTest.java
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package my.bookshop;

import static cds.gen.adminservice.AdminService_.AUTHORS;
import static cds.gen.adminservice.AdminService_.ORDERS;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;

Expand All @@ -24,7 +25,6 @@
import cds.gen.adminservice.Authors;
import cds.gen.adminservice.OrderItems;
import cds.gen.adminservice.Orders;
import cds.gen.adminservice.Orders_;

@ExtendWith(SpringExtension.class)
@SpringBootTest
Expand Down Expand Up @@ -74,7 +74,7 @@ void testCreateOrderWithoutBook() {

// Runtime ensures that book is present in the order item, when it is created.
ServiceException exception =
assertThrows(ServiceException.class, () -> adminService.run(Insert.into(Orders_.class).entry(order)));
assertThrows(ServiceException.class, () -> adminService.run(Insert.into(ORDERS).entry(order)));
assertEquals(CdsErrorStatuses.VALUE_REQUIRED.getCodeString(), exception.getErrorStatus().getCodeString());
}

Expand All @@ -92,7 +92,7 @@ void testCreateOrderWithNonExistingBook() {

// Runtime ensures that book exists when order item is created.
ServiceException exception =
assertThrows(ServiceException.class, () -> adminService.run(Insert.into(Orders_.class).entry(order)));
assertThrows(ServiceException.class, () -> adminService.run(Insert.into(ORDERS).entry(order)));
assertEquals(CdsErrorStatuses.TARGET_ENTITY_MISSING.getCodeString(), exception.getErrorStatus().getCodeString());
}

Expand Down
12 changes: 7 additions & 5 deletions srv/src/test/java/my/bookshop/CatalogServiceTest.java
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
package my.bookshop;

import static cds.gen.catalogservice.CatalogService_.BOOKS;
import static cds.gen.catalogservice.CatalogService_.REVIEWS;
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
import static org.junit.jupiter.api.Assertions.assertEquals;
Expand Down Expand Up @@ -47,7 +48,8 @@ public void testCreateReviewHandler() {
createReview("aebdfc8a-0dfa-4468-bd36-48aabd65e663", 5, "great read", "just amazing..."));

bookReviews.forEach(bookReview -> {
Books_ ref = CQL.entity(Books_.class).filter(b -> b.ID().eq(bookReview.getBookId()));

Books_ ref = CQL.entity(BOOKS).filter(b -> b.ID().eq(bookReview.getBookId()));
Reviews result = catalogService.addReview(ref, bookReview.getRating(), bookReview.getTitle(), bookReview.getText());

assertEquals(bookReview.getBookId(), result.getBookId());
Expand All @@ -69,7 +71,7 @@ public void testAddReviewWithInvalidRating() {
String message = "Valid rating range needs to be within 1 and 5";

bookReviews.forEach(bookReview -> {
Books_ ref = CQL.entity(Books_.class).filter(b -> b.ID().eq(bookReview.getBookId()));
Books_ ref = CQL.entity(BOOKS).filter(b -> b.ID().eq(bookReview.getBookId()));
assertThrows(ServiceException.class, () -> catalogService.addReview(ref, bookReview.getRating(),
bookReview.getTitle(), bookReview.getText()), message);
});
Expand All @@ -91,7 +93,7 @@ public void testAddReviewForNonExistingBook() {
exMessage2));

testCases.forEach(testCase -> {
Books_ ref = CQL.entity(Books_.class).filter(b -> b.ID().eq(testCase.review.getBookId()));
Books_ ref = CQL.entity(BOOKS).filter(b -> b.ID().eq(testCase.review.getBookId()));
assertThrows(ServiceException.class, () -> catalogService.addReview(ref, testCase.review.getRating(),
testCase.review.getTitle(), testCase.review.getText()), testCase.exceptionMessage);
});
Expand All @@ -102,14 +104,14 @@ public void testAddReviewForNonExistingBook() {
public void testAddReviewSameBookMoreThanOnceBySameUser() {

String bookId = "4a519e61-3c3a-4bd9-ab12-d7e0c5329933";
Books_ ref = CQL.entity(Books_.class).filter(b -> b.ID().eq(bookId));
Books_ ref = CQL.entity(BOOKS).filter(b -> b.ID().eq(bookId));

assertDoesNotThrow(() -> catalogService.addReview(ref, 1, "quite bad", "disappointing..."));
assertThrows(ServiceException.class, () -> catalogService.addReview(ref, 5, "great read", "just amazing..."),
"User not allowed to add more than one review for a given book");

String anotherBookId = "9b084139-0b1e-43b6-b12a-7b3669d75f02";
Books_ anotherRef = CQL.entity(Books_.class).filter(b -> b.ID().eq(anotherBookId));
Books_ anotherRef = CQL.entity(BOOKS).filter(b -> b.ID().eq(anotherBookId));

assertDoesNotThrow(() -> catalogService.addReview(anotherRef, 4, "very good", "entertaining..."));
}
Expand Down

0 comments on commit 17a78d4

Please sign in to comment.