Spring HATEOAS RepresentationModelAssembler toCollectionModel() - spring

I'm creating Spring Boot HATEOAS REST application. Code below shows how am I adding links, while GET request is send for specific Employee. I'm using RepresentationModelAssembler toModel function. There's also toCollectionModel function to Override, which I would like to use to convert List<Employees> to CollectionModel. -> This will be returned in /Employees/all endpoint.
And I dunno how to do that. So what I need is to pass List<Employees>, then all list elements needs to be processed by toModel functions, and then, like in toModel function I need possibility to add more links to it -> links to entire new collection (not individual items).
Looking forward for your answers!
#Component
public class EmployeeModelAssembler implements RepresentationModelAssembler<Employee, EntityModel<Employee>> {
#Override
public EntityModel<Employee> toModel(Employee employee) {
EntityModel<Employee> employeeEntityModel = EntityModel.of(employee);
Link selfLink = linkTo(methodOn(EmployeeController.class).getEmployeeById(employee.getId())).withSelfRel();
employeeEntityModel.add(selfLink);
return employeeEntityModel;
}
#Override
public CollectionModel<EntityModel<Employee>> toCollectionModel(Iterable<? extends Employee> entities) {
?? ?? ??
}
}

You can use something like this:
#GetMapping(produces = { "application/hal+json" })
public CollectionModel<Customer> getAllCustomers() {
List<Customer> allCustomers = customerService.allCustomers();
for (Customer customer : allCustomers) {
String customerId = customer.getCustomerId();
Link selfLink = linkTo(CustomerController.class).slash(customerId).withSelfRel();
customer.add(selfLink);
if (orderService.getAllOrdersForCustomer(customerId).size() > 0) {
Link ordersLink = linkTo(methodOn(CustomerController.class)
.getOrdersForCustomer(customerId)).withRel("allOrders");
customer.add(ordersLink);
}
}
Link link = linkTo(CustomerController.class).withSelfRel();
CollectionModel<Customer> result = CollectionModel.of(allCustomers, link);
return result;
}
Visit https://www.baeldung.com/spring-hateoas-tutorial#springhateoasinaction for detailed explanation

Related

Spring WebFlux: How to route to a different handler function based on query parameters?

I am writing a person API using Spring WebFlux functional programming, how to route to different handler functions based on the query param names?
#Bean
public RouterFunction<ServerResponse> route(PersonHandler personHandler) {
return RouterFunctions.route(GET("/people/{id}").and(accept(APPLICATION_JSON)), personHandler::get)
.andRoute(GET("/people").and(accept(APPLICATION_JSON)), personHandler::all)
.andRoute(GET("/people/country/{country}").and(accept(APPLICATION_JSON)), personHandler::getByCountry)
// .andRoute(GET("/people?name={name}").and(accept(APPLICATION_JSON)), personHandler::searchByName)
// .andRoute(GET("/people?age={age}").and(accept(APPLICATION_JSON)), personHandler::searchByAge)
// I am expecting to do something like this
;
}
Or do I need to handle it in the handler function?
like
public Mono<ServerResponse> searchPeople(ServerRequest serverRequest) {
final Optional<String> name = serverRequest.queryParam("name");
final Optional<String> age = serverRequest.queryParam("age");
Flux<People> result;
if(name.isPresent()){
result = name.map(peopleRepository::searchByName)
.orElseThrow();
} else if(age.isPresent()){
result = name.map(peopleRepository::searchByage)
.orElseThrow();
}
return ok().contentType(MediaType.APPLICATION_JSON).body(result, People.class);
}
What is the best way to do it?
Thanks
You can create your own RequestPredicate and use the existing infrastructure (by plugging it into a and()):
public static RequestPredicate hasQueryParam(String name) {
return RequestPredicates.queryParam(name, p -> StringUtils.hasText(p));
}

How to make the PUT method work? I want to update my data in Table

This is my POST method and it is successful and run well. My question is how to do the PUT request method so that it can update the data well?
Post method
public void addRecipe(RecipeDTO recipedto)
{
Category categoryTitle = categoryRepository.findByCategoryTitle(recipedto.getCategoryTitle());
Recipe recipe = new Recipe();
/*I map my dto data original model*/
recipe.setRID(recipedto.getrID());
recipe.setRecipeTitle(recipedto.getRecipeTitle());
recipe.setDescription(recipedto.getDescription());
recipe.setCookTime(recipedto.getCookTime());
List categoryList = new ArrayList<>();
categoryList.add(categoryTitle);
recipe.setCategories(categoryList);
Recipe savedRecipe = recipeRepository.save(recipe);
/*I map the data in ingredientDTO and setpDTO to actual model */
List ingredientList = new ArrayList<>();
for(IngredientDTO ingredientdto : recipedto.getIngredients())
{
Ingredient ingredient = new Ingredient();
ingredient.setIID(ingredientdto.getiID());
ingredient.setIngredientName(ingredientdto.getIngredientName());
ingredient.setRecipe(savedRecipe);
ingredientList.add(ingredient);
}
List stepList = new ArrayList<>();
for(StepDTO stepdto : recipedto.getSteps())
{
Step step = new Step();
step.setSID(stepdto.getsID());
step.setStepDescription(stepdto.getStepDescription());
step.setStepNumber(stepdto.getStepNumber());
step.setRecipe(savedRecipe);
stepList.add(step);
}
ingredientRepository.save(ingredientList);
stepRepository.save(stepList);
}
This is my put method and it wont work, how should I do it, because I have no idea. Please teach me to do this method, if it is better.
public void updateRecipe(RecipeDTO recipedto, String id)
{
Recipe recipe = recipeRepository.findByrID(recipedto.getrID());
if(id==recipedto.getrID().toString())
{
recipeRepository.save(recipe);
}
}
When building REST services in Java you usually use an Framework to help you with this.
Like "jax-rs": https://mvnrepository.com/artifact/javax.ws.rs/javax.ws.rs-api/2.0
If using jax-rs then you mark your method as an Http PUT method with the annotation #PUT, ex:
#PUT
#Path("ex/foo")
public Response somePutMethod() {
return Response.ok().entity("Put some Foos!").build();
}
If using Spring as an Framework you mark your PUT method with the #RequestMapping annotation, ex:
#RequestMapping(value = "/ex/foo", method = PUT)
public String putFoos() {
return "Put some Foos";
}
Firstly and very importantly, you DO NOT use String == String for checking equality. Your code:
public void updateRecipe(RecipeDTO recipedto, String id)
{
Recipe recipe = recipeRepository.findByrID(recipedto.getrID());
if(id==recipedto.getrID().toString())
{
recipeRepository.save(recipe);
}
}
It should be:
public void updateRecipe(RecipeDTO recipedto, String id)
{
Recipe recipe = recipeRepository.findByrID(recipedto.getrID());
if(recipedto.getrID().toString().equals(id))
{
recipeRepository.save(recipe);
}
}
Why?
Because equality with == checks if objects have the same memory address. In other words:
new Integer(1) == new Integer(1) //false
1 == 1 //true
new String("hello") == new String("hello") //false
"hello" == "hello" //true because literal strings are stored in a String pool
new String("hello") == "hello" //false
Secondly, you SHOULD ALWAYS use generics with Collection APIs.
Your code:
List categoryList = new ArrayList<>();
Should be:
List<Category> categoryList = new ArrayList<>();
And lastly, like askepan said, you have not defined what framework you are using. In case of Jersey (JAX-RS implementation) you have HTTP Request Methods:
#GET, #POST, #PUT, #DELETE, #HEAD, #OPTIONS.
#PUT
#Produces("text/plain")
#Consumes("text/plain")
public Response putContainer() {
System.out.println("PUT CONTAINER " + container);
URI uri = uriInfo.getAbsolutePath();
Container c = new Container(container, uri.toString());
Response r;
if (!MemoryStore.MS.hasContainer(c)) {
r = Response.created(uri).build();
} else {
r = Response.noContent().build();
}
MemoryStore.MS.createContainer(c);
return r;
}
If you use Spring, there are #RequestMapping(method = ), or short versions:
#GetMapping, #PutMapping, #PostMapping, #DeleteMapping.
#GetMapping("/{id}")
public Person getPerson(#PathVariable Long id) {
// ...
}
#PutMapping
public void add(#RequestBody Person person) {
// ...
}
According to the annotation, the method will be called accordingly.
More information in:
Spring,JAX-RS

Adding custom data for an operation to Application Insights telemetry

I'm trying to add a bunch of custom data fields to every piece of telemetry I can, and this data is consistent across a single operation, but varies from operation to operation.
I have a custom ITelemetryInitializer, and within that I can do something like:
public class MyInitializer : ITelemetryInitializer
{
public void Initialize(Microsoft.ApplicationInsights.Channel.ITelemetry telemetry)
{
telemetry.Context.Properties[ "platform" ] = "PC";
}
}
But I don't understand how I'm suppose to push this data into this initializer.
I've added something like this:
public class MyInitializer : ITelemetryInitializer
{
private string mPlatform = "unknown";
public void Initialize(Microsoft.ApplicationInsights.Channel.ITelemetry telemetry)
{
telemetry.Context.Properties[ "platform" ] = mPlatform;
}
public void SetPlatform(string platform)
{
mPlatform = platform
}
}
And then at the controller level I do something like this:
foreach (var init in TelemetryConfiguration.Active.TelemetryInitializers)
{
var customInit = init as MyInitializer;
if (customInit != null)
{
customInit.SetPlatform(requestPlatform);
}
}
But this is horribly clunky, and prone to error (e.g. if a piece of telemetry gets sent before this function is called), and I'm not really sure if this is thread-safe.
What's the intended way of passing around this kind of data?
I think I've solved this now, the solution is to write to the properties of the TelemetryClient within the controller like this:
[Route( "[controller]" )]
public class MyController : Controller
{
private readonly TelemetryClient mTelemetryClient;
public MyController(
TelemetryClient TelemetryClientArg )
{
mTelemetryClient = TelemetryClientArg;
mTelemetryClient.Context.Properties.Remove("platform");
}
[HttpPost]
[Produces( "application/json" )]
public IActionResult Post( [FromBody] RequestClass RequestData )
{
mTelemetryClient.TrackTrace("Test trace 1"); // doesn't have platform set
mTelemetryClient.Context.Properties["platform"] = RequestData.platform;
mTelemetryClient.TrackTrace("Test trace 2"); // has platform set correctly
}
}
This seems to be safe as the controller constructor appears to be called before each http request is processed and the context within the TelemetryClient is unique per thread. I would like to get confirmation from the team that this is reasonable.

How update/remove an item already cached within a collection of items

I am working with Spring and EhCache
I have the following method
#Override
#Cacheable(value="products", key="#root.target.PRODUCTS")
public Set<Product> findAll() {
return new LinkedHashSet<>(this.productRepository.findAll());
}
I have other methods working with #Cacheable and #CachePut and #CacheEvict.
Now, imagine the database returns 100 products and they are cached through key="#root.target.PRODUCTS", then other method would insert - update - deleted an item into the database. Therefore the products cached through the key="#root.target.PRODUCTS" are not the same anymore such as the database.
I mean, check the two following two methods, they are able to update/delete an item, and that same item is cached in the other key="#root.target.PRODUCTS"
#Override
#CachePut(value="products", key="#product.id")
public Product update(Product product) {
return this.productRepository.save(product);
}
#Override
#CacheEvict(value="products", key="#id")
public void delete(Integer id) {
this.productRepository.delete(id);
}
I want to know if is possible update/delete the item located in the cache through the key="#root.target.PRODUCTS", it would be 100 with the Product updated or 499 if the Product was deleted.
My point is, I want avoid the following:
#Override
#CachePut(value="products", key="#product.id")
#CacheEvict(value="products", key="#root.target.PRODUCTS")
public Product update(Product product) {
return this.productRepository.save(product);
}
#Override
#Caching(evict={
#CacheEvict(value="products", key="#id"),
#CacheEvict(value="products", key="#root.target.PRODUCTS")
})
public void delete(Integer id) {
this.productRepository.delete(id);
}
I don't want call again the 500 or 499 products to be cached into the key="#root.target.PRODUCTS"
Is possible do this? How?
Thanks in advance.
Caching the collection using the caching abstraction is a duplicate of what the underlying caching system is doing. And because this is a duplicate, it turns out that you have to resort to some kind of duplications in your own code in one way or the other (the duplicate key for the set is the obvious representation of that). And because there is duplication, you have to sync state somehow
If you really need to access to the whole set and individual elements, then you should probably use a shortcut for the easiest leg. First, you should make sure your cache contains all elements which is not something that is obvious. Far from it actually. Considering you have that:
//EhCacheCache cache = (EhCacheCache) cacheManager.getCache("products");
#Override
public Set<Product> findAll() {
Ehcache nativeCache = cache.getNativeCache();
Map<Object, Element> elements = nativeCache.getAll(nativeCache.getKeys());
Set<Product> result = new HashSet<Product>();
for (Element element : elements.values()) {
result.add((Product) element.getObjectValue());
}
return Collections.unmodifiableSet(result);
}
The elements result is actually a lazy loaded map so a call to values() may throw an exception. You may want to loop over the keys or something.
You have to remember that the caching abstraction eases the access to the underlying caching infrastructure and in no way it replaces it: if you had to use the API directly, this is probably what you would have to do in some sort.
Now, we can keep the conversion on SPR-12036 if you believe we can improve the caching abstraction in that area. Thanks!
I think something like this schould work... Actually it's only a variation if "Stéphane Nicoll" answer ofcourse, but it may be useful for someone. I write it right here and haven't check it in IDE, but something similar works in my Project.
Override CacheResolver:
#Cacheable(value="products", key="#root.target.PRODUCTS", cacheResolver = "customCacheResolver")
Implement your own cache resolver, which search "inside" you cached items and do the work in there
public class CustomCacheResolver implements CacheResolver{
private static final String CACHE_NAME = "products";
#Autowired(required = true) private CacheManager cacheManager;
#SuppressWarnings("unchecked")
#Override
public Collection<? extends Cache> resolveCaches(CacheOperationInvocationContext<?> cacheOperationInvocationContext) {
// 1. Take key from query and create new simple key
SimpleKey newKey;
if (cacheOperationInvocationContext.getArgs().length != null) { //optional
newKey = new SimpleKey(args); //It's the key of cached object, which your "#Cachable" search for
} else {
//Schould never be... DEFAULT work with cache if something wrong with arguments
return new ArrayList<>(Arrays.asList(cacheManager.getCache(CACHE_NAME)));
}
// 2. Take cache
EhCacheCache ehCache = (EhCacheCache)cacheManager.getCache(CACHE_NAME); //this one we bringing back
Ehcache cache = (Ehcache)ehCache.getNativeCache(); //and with this we working
// 3. Modify existing Cache if we have it
if (cache.getKeys().contains(newKey) && YouWantToModifyIt) {
Element element = cache.get(key);
if (element != null && !((List<Products>)element.getObjectValue()).isEmpty()) {
List<Products> productsList = (List<Products>)element.getObjectValue();
// ---**--- Modify your "productsList" here as you want. You may now Change single element in this list.
ehCache.put(key, anfragenList); //this method NOT adds cache, but OVERWRITE existing
// 4. Maybe "Create" new cache with this key if we don't have it
} else {
ehCache.put(newKey, YOUR_ELEMENTS);
}
return new ArrayList<>(Arrays.asList(ehCache)); //Bring all back - our "new" or "modified" cache is in there now...
}
Read more about CRUD of EhCache: EhCache code samples
Hope it helps. And sorry for my English:(
I think there is a way to read the collection from underlying cache structure of spring. You can retrieve the collection from underlying ConcurrentHashMap as key-value pairs without using EhCache or anything else. Then you can update or remove an entry from that collection and then you can update the cache too. Here is an example that may help:
import com.crud.model.Post;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.Cache;
import org.springframework.cache.CacheManager;
import org.springframework.cache.interceptor.CacheOperationInvocationContext;
import org.springframework.cache.interceptor.CacheResolver;
import org.springframework.cache.interceptor.SimpleKey;
import org.springframework.stereotype.Component;
import java.util.*;
#Component
#Slf4j
public class CustomCacheResolver implements CacheResolver {
private static final String CACHE_NAME = "allPost";
#Autowired
private CacheManager cacheManager;
#SuppressWarnings("unchecked")
#Override
public Collection<? extends Cache> resolveCaches(CacheOperationInvocationContext<?> cacheOperationInvocationContext) {
log.info(Arrays.toString(cacheOperationInvocationContext.getArgs()));
String method = cacheOperationInvocationContext.getMethod().toString();
Post post = null;
Long postId = null;
if(method.contains("update")) {
//get the updated post
Object[] args = cacheOperationInvocationContext.getArgs();
post = (Post) args[0];
}
else if(method.contains("delete")){
//get the post Id to delete
Object[] args = cacheOperationInvocationContext.getArgs();
postId = (Long) args[0];
}
//read the cache
Cache cache = cacheManager.getCache(CACHE_NAME);
//get the concurrent cache map in key-value pair
assert cache != null;
Map<SimpleKey, List<Post>> map = (Map<SimpleKey, List<Post>>) cache.getNativeCache();
//Convert to set to iterate
Set<Map.Entry<SimpleKey, List<Post>>> entrySet = map.entrySet();
Iterator<Map.Entry<SimpleKey, List<Post>>> itr = entrySet.iterator();
//if a iterated entry is a list then it is our desired data list!!! Yayyy
Map.Entry<SimpleKey, List<Post>> entry = null;
while (itr.hasNext()){
entry = itr.next();
if(entry instanceof List) break;
}
//get the list
assert entry != null;
List<Post> postList = entry.getValue();
if(method.contains("update")) {
//update it
for (Post temp : postList) {
assert post != null;
if (temp.getId().equals(post.getId())) {
postList.remove(temp);
break;
}
}
postList.add(post);
}
else if(method.contains("delete")){
//delete it
for (Post temp : postList) {
if (temp.getId().equals(postId)) {
postList.remove(temp);
break;
}
}
}
//update the cache!! :D
cache.put(entry.getKey(),postList);
return new ArrayList<>(Collections.singletonList(cacheManager.getCache(CACHE_NAME)));
}
}
Here are the methods that uses the CustomCacheResolver
#Cacheable(key = "{#pageNo,#pageSize}")
public List<Post> retrieveAllPost(int pageNo,int pageSize){ // return list}
#CachePut(key = "#post.id",cacheResolver = "customCacheResolver")
public Boolean updatePost(Post post, UserDetails userDetails){ //your logic}
#CachePut(key = "#postId",cacheResolver = "customCacheResolver")
public Boolean deletePost(Long postId,UserDetails userDetails){ // your logic}
#CacheEvict(allEntries = true)
public Boolean createPost(String userId, Post post){//your logic}
Hope it helps to manipulate your spring application cache manually!
Though I don't see any easy way, but you can override Ehcache cache functionality by supplying cache decorator. Most probably you'd want to use EhcahceDecoratorAdapter, to enhance functions used by EhCacheCache put and evict methods.
Simple and rude solution is :
#Cacheable(key = "{#pageNo,#pageSize}")
public List<Post> retrieveAllPost(int pageNo,int pageSize){ // return list}
#CacheEvict(allEntries = true)
public Boolean updatePost(Post post, UserDetails userDetails){ //your logic}
#CacheEvict(allEntries = true)
public Boolean deletePost(Long postId,UserDetails userDetails){ // your logic}
#CacheEvict(allEntries = true)
public Boolean createPost(String userId, Post post){//your logic}

customizing odata output from asp.net web api

I'm using the new ASP.NET webapi odata (version 4.0.0 last published 27/2/2013 according to Nuget)
Basically I'm doing it as described here: http://www.asp.net/web-api/overview/odata-support-in-aspnet-web-api
I'm publishing my data transfer objects and the odata atom pub feed is created but I'd like to have some more control over it. Mainly I'd like to be able to do the following:
decide what goes on the title, author and updated elements for the feed
decide whether or not to have the edit links
change what is shown in <category term="X"and in m:type in sub properties that are classes in my application. Currently they expose the c# class names with the full namespace but I don't want to expose this.
Thanks.
The OData media type formatter is more extensible now. Samples follow.
1) decide what goes on the title, author and updated elements for the feed
public class AtomMetadataFeedSerializer : ODataFeedSerializer
{
public AtomMetadataFeedSerializer(IEdmCollectionTypeReference edmType, ODataSerializerProvider serializerProvider)
: base(edmType, serializerProvider)
{
}
public override ODataFeed CreateODataFeed(IEnumerable feedInstance, ODataSerializerContext writeContext)
{
ODataFeed feed = base.CreateODataFeed(feedInstance, writeContext);
feed.Atom().Title = new AtomTextConstruct { Kind = AtomTextConstructKind.Text, Text = "My Awesome Feed" };
return feed;
}
}
public class CustomSerializerProvider : DefaultODataSerializerProvider
{
public override ODataEntrySerializer CreateEdmTypeSerializer(IEdmTypeReference edmType)
{
if (edmType.IsCollection() && edmType.AsCollection().ElementType().IsEntity())
{
// feed serializer
return new AtomMetadataFeedSerializer(edmType.AsCollection(), this);
}
return base.CreateEdmTypeSerializer(edmType);
}
}
And register the custom serializer provider using,
config.Formatters.InsertRange(0, ODataMediaTypeFormatters.Create(new CustomSerializerProvider(), new DefaultODataDeserializerProvider()));
2) customize edit links
public class CustomEntityTypeSerializer : ODataEntityTypeSerializer
{
public CustomEntityTypeSerializer(IEdmEntityTypeReference edmType, ODataSerializerProvider serializerProvider)
: base(edmType, serializerProvider)
{
}
public override ODataEntry CreateEntry(EntityInstanceContext entityInstanceContext, ODataSerializerContext writeContext)
{
ODataEntry entry = base.CreateEntry(entityInstanceContext, writeContext);
if (notProduceEditLinks)
{
entry.EditLink = null;
}
return entry;
}
}
public class CustomSerializerProvider : DefaultODataSerializerProvider
{
public override ODataEntrySerializer CreateEdmTypeSerializer(IEdmTypeReference edmType)
{
if (edmType.IsEntity())
{
// entity type serializer
return new CustomEntityTypeSerializer(edmType.AsEntity(), this);
}
return base.CreateEdmTypeSerializer(edmType);
}
}
and register the custom serializer provider as above.
We still don't support scenario 3 i.e aliasing type names and namespaces.

Resources