How to deal with xml and json as request in Java 17 [closed] - spring-boot

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 3 days ago.
Improve this question
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlRootElement;
import com.fasterxml.jackson.annotation.JsonTypeInfo;
import com.fasterxml.jackson.annotation.JsonTypeName;
#XmlRootElement(name="addressRequest")
#XmlAccessorType(XmlAccessType.FIELD)
#JsonTypeName("addressRequest")
#JsonTypeInfo(include = JsonTypeInfo.As.WRAPPER_OBJECT ,use = JsonTypeInfo.Id.NAME)
public class ValidateAddressRequest {
private boolean checkInLocalDb = false;
private boolean saveInLocalDb = true;
private String vendor;
private String consigneeName;
private String buildingName;
}
public class AddressRestController {
#PostMapping (path = "/validateAddress", consumes = {MediaType.APPLICATION_XML_VALUE,MediaType.APPLICATION_JSON_VALUE}, produces = {MediaType.APPLICATION_XML_VALUE,MediaType.APPLICATION_JSON_VALUE})
#ResponseStatus(HttpStatus.OK)
#ResponseBody
public ValidateResponse validateAddress(#RequestBody #Valid ValidateRequest validateRequest){
//some code
}
}
So the above code is working in Java 1.8
But when I migrated the code to Java 17 and Spring boot 3.0.2 json the request is also working but when I post a XML request it is giving JSON parse error: Could not resolve subtype.
After many efforts i think #JsonTypeInfo is the issue , but don't have any idea how to change that so that both(xml & json) can work.

Related

Spring boot webflux returning HTML content [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
Trying to build a hosted page like Payment application where the payment URL will be embedded on our website inside IFrame which will display the payment HTML.
Is it possible to do the same using Spring boot webeflux? Not sure how to return HTML from Spring boot webflux.
Basically, There will be frontend in which user will upload the HTML and the same will be stored in DB and each upload will have a unique ID. User can just embed this unique id with the URL in their website and thecorresponding HTML from DB should be loaded in the embedded area.
As an option (I don't tell that it's the best option, it depends on your use case)
#RestController
public class HtmlViewController {
#GetMapping(path = "/{pageId}", produces = TEXT_HTML_VALUE)
public Mono<String> get(#PathVariable String pageId,
#RequestParam(required = false) Map<String, String> requestParams) {
return getPage(pageId, requestParams);
}
private Mono<String> getPage(String pageId, Map<String, String> requestParams) {
// `getTemplate` - fetch html template from your storage in a reactive way, should return `Mono<String>`
return getTemplate(pageId)
.flatMap(htmlTemplate -> {
// apply request parameters to your html page, like replacing placeholders with links, user name etc.
});
}
For that you need to add the following dependencies: spring-boot-starter-webflux and springdoc-openapi-webflux-ui (it's optional, but with that you will be able to test your response using swagger).
Returning HTML directly would be odd / ill-advised (possible, but not recommended.)
The better thing to do would be to use Thymeleaf or similar to create your presentation layer, then on your spring controller, set reactive properties on the model, eg:
#RequestMapping("/")
public String index(final Model model) {
model.addAttribute("elements", new ReactiveDataDriverContextVariable(repository.findAll()));
model.addAttribute("anotherattribute", Mono.just(6));
//...and so on
return "index";
}
This will then reactively populate your model with the correct context before displaying the desired HTML.

Load data from the database to mat-table when click Next page [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 3 years ago.
Improve this question
I am using angular 7 with spring boot, and i am use mat-table, i don't want load for example all the data from database in one load, i want to load data just when click on next page in mat-table.
and This image for my mat-table.
how i can do that in angular 7 and spring boot together, if anybody have solution please give me it, thanks.
In JpaRepository of Spring-data-jpathere is a Pageable concept, in your repo implement JpaRepository instead of CrudRepository (It internally extends PagingAndSortingRepository)
You could do something like this,
Repo
public class FooRepository extends JpaRepository<FooClass, Long> {
}
Service
#Service
public class FooService {
#Autowired
private FooRepository fooRepo;
public Page<FooClass> fetchPagedFoo(Integer page, Integer size) {
return fooRepo.findAll(PageRequest.of(page, size));
}
}
Controller
#RestController
public class FooController {
#Autowired
private FooService fooService;
#GetMapping("/foo")
public ResponseEntity getPagedFoo(
#RequestParam(value = "pageIndex", defaultValue ="0") Integer page,
#RequestParam(value = "size", defaultValue = "10") Integer size) {
return ResponseEntity.ok(fooService.fetchPagedFoo(page, size));
}
}
In above if you pass 0, 10 then first page 10 rows will be returned, Page will return total number of data as well with this you could do Pagination.

Where does the filter for Ehcache 3 simple web page caching call the cache?

I am trying to cache a simple web page in Ehcache. Thanks to some help from another SO post I discovered that I need to implement my own filter based on Ehcache 2 code. When I look at the filter I don't understand it. Where does it ever call the cache to return a value? Here is my implementation (quite possibly wrong):
package com.sentiment360.pulse.cache;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.xml.bind.Element;
import org.ehcache.Cache;
import org.ehcache.CacheManager;
import org.ehcache.config.Configuration;
import static org.ehcache.config.builders.CacheManagerBuilder.newCacheManager;
import org.ehcache.core.Ehcache;
import org.ehcache.event.CacheEvent;
import org.ehcache.event.CacheEventListener;
import org.ehcache.xml.XmlConfiguration;
import javax.servlet.http.HttpServletRequest;
public class SimplePageCachingFilter implements CachingFilter {
public static final String DEFAULT_CACHE_NAME = "SimplePageCachingFilter";
private Logger LOG = Logger.getLogger(this.getClass().getName());
private String cacheName="basicCache";
protected String getCacheName() {
if (cacheName != null && cacheName.length() > 0) {
LOG.log(Level.INFO,"Using configured cacheName of {}.", cacheName);
return cacheName;
} else {
LOG.log(Level.INFO,"No cacheName configured. Using default of {}.", DEFAULT_CACHE_NAME);
return DEFAULT_CACHE_NAME;
}
}
protected CacheManager getCacheManager() {
return CacheManager.getInstance();
}
protected String calculateKey(HttpServletRequest httpRequest) {
StringBuffer stringBuffer = new StringBuffer();
stringBuffer.append(httpRequest.getMethod()).append(httpRequest.getRequestURI()).append(httpRequest.getQueryString());
String key = stringBuffer.toString();
return key;
}
}
See in the super class.
But you do implements CachingFilter ?! Where is that interface? It does look like you were trying to "copy" the previous Ehcache's SimplePageCachingFilter, right? You would also need to port that abstract super class (and maybe read a little about javax.servlet.Filter, in case these aren't entirely clear...)
Now, you may also want to ping the dev team on the Ehcache Dev Google group about this. They should be able to provide pointers and then help with the implementation. Looks like a good idea for a future pull request! :)

Spring Data Rest - Add link to search endpoint

In our Spring-Data-Rest Project we have a custom (fuzzy) search on a /buergers/search/findBuergerFuzzy?searchString="..." endpoint.
Is it possible to add a link for it on the /buergers/search endpoint (Without overriding the automatically exposed Repository findBy Methods)?
The Controller exposing the search:
#BasePathAwareController
#RequestMapping("/buergers/search/")
public class BuergerSearchController {
#Autowired
QueryService service;
#RequestMapping(value = "/findBuergerFuzzy", method = RequestMethod.GET)
public
#ResponseBody
ResponseEntity<?> findBuergerFuzzy(PersistentEntityResourceAssembler assembler, #Param("searchString") String searchString) {
if (searchString.length() < 3)
throw new IllegalArgumentException("Search String must be at least 3 chars long.");
List<Buerger> list = service.query(searchString, Buerger.class, new String[]{"vorname", "nachname", "geburtsdatum", "augenfarbe"});
final List<PersistentEntityResource> collect = list.stream().map(assembler::toResource).collect(Collectors.toList());
return new ResponseEntity<Object>(new Resources<>(collect), HttpStatus.OK);
}
}
UPDATE: This is an outdated workaround answer. Upgrade to Spring HATEOAS 1.0.
Old Workaround:
Digging the spring-data-rest source i found the RepositorySearchesResource which seems to solve the problem.
#Component
public class SearchResourcesProcessor implements ResourceProcessor<RepositorySearchesResource> {
#Override
public RepositorySearchesResource process(RepositorySearchesResource repositorySearchesResource) {
final String search = repositorySearchesResource.getId().getHref();
final Link findFullTextFuzzy = new Link(search + "/findFullTextFuzzy{?q}").withRel("findFullTextFuzzy");
repositorySearchesResource.add(findFullTextFuzzy);
return repositorySearchesResource;
}
}
Because we generate this code by templates, this is sufficient and fullfills our needs. Make sure to check the comments for the right and safe way.
Version
migrate-to-1.0.changes
ResourceSupport is now RepresentationModel
Resource is now EntityModel
Resources is now CollectionModel
PagedResources is now PagedModel
Code
The code for new version:
import org.springframework.data.rest.webmvc.RepositorySearchesResource;
import org.springframework.hateoas.Link;
import org.springframework.hateoas.server.RepresentationModelProcessor;
import org.springframework.stereotype.Component;
#Component
public class RepositorySearchesProcessor implements RepresentationModelProcessor<RepositorySearchesResource> {
#Override
public RepositorySearchesResource process(RepositorySearchesResource model) {
System.out.println(model.getDomainType());
model.add(Link.of(model.getRequiredLink("self").getHref() + "/findFullTextFuzzy{?q}").withRel("findFullTextFuzzy"));
return model;
}
}
How
About how to find what resource or model you use, after setting breakpoints in each method of RepresentationModel, you maybe find something useful :

Regarding Dependency Injection [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
interface Car {
public void tyres();
}
class BMW implements Car {
public void tyres() {
System.out.println("BMW");
}
}
class HMW implements Car {
public void tyres() {
System.out.println("HMW");
}
}
public class DependencyInjection {
private Car car;
public void draw() {
this.car.tyres();
}
public void setCar(Car car) {
this.car = car;
}
public static void tyres1(Car c) {
c.tyres();
}
public static void main(String[] args) {
Car car = new BMW();
tyres1(car);//point 1
DependencyInjection dep=new DependencyInjection();
dep.setCar(car);//point2
dep.draw();
}
}
I want some clarification what is advantage we have creating dependency injection at point 1 and point2.Please explain me in detail as i am new to spring???
This is not a Spring specific design principle, and it's hard to grasp in the snippet you've provided which does not have notable separated pieces, but becomes more helpful as systems grow.
By removing the reference to a concrete class you eliminate "type coupling" which means that the internal class can remain "closed": it won't have to change if the implementation changes of the involved class and the client code can use different ways to adapt as needed without the inner class needing to change or be aware of the implementation. This also helps ensure that the method body within the class is focusing on its role and its specific job rather than being getting tangled in with any other implementation (which helps in clearly defining what should be considered part of an API).
You should also read about the concept of SOLID classes:
http://en.wikipedia.org/wiki/SOLID_(object-oriented_design)
The most immediate benefit in my experience is that it also allows for far more complete, isolated unit tests which is very important if that is part of your development process (which is recommended also as systems grow).
Actually what Dependency Injection does that part is done by your code:
Car car = new BMW();
Dependency Injection feature helps you to mentioned dependency as configuration and Framework actually does the rest Injection of Object to references.

Resources