Getting 404 Error when Trying to Access GraphQL endpoint on Springboot - java

I am new to GraphQL and working on a demo springboot app using GraphQL. I am looking to access the http://localhost:8080/graphql/schema.json endpoint but getting 404 whitelabel error. I am able to access one of the endpoints in the controller. Initially, I used the springboot graphql maven dependency but included another graphql maven dependency in my pom file but still got 404 error. I will greatly appreciate any help in debugging the error. Below is snippet of my code.
The app
#SpringBootApplication
public class DogGraphqlApiApplication {
public static void main(String[] args) {
SpringApplication.run(DogGraphqlApiApplication.class, args);
}
}
application.properties
spring.jpa.defer-datasource-initialization=true
spring.h2.console.enabled=true
spring.h2.console.path=/h2
spring.datasource.url=jdbc:h2:mem:dogdata
graphql.servlet.mapping=/graphql
graphql.servlet.enabled=true
graphql.servlet.corsEnabled=true
graphiql.enabled=true
graphiql.endpoint=/graphql
graphiql.mapping=graphiql
pom.xml
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webflux</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.graphql</groupId>
<artifactId>spring-graphql-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.graphql-java</groupId>
<artifactId>graphql-spring-boot-starter</artifactId>
<version>5.0.2</version>
</dependency>
<dependency>
<groupId>com.graphql-java</groupId>
<artifactId>graphql-java-tools</artifactId>
<version>5.2.4</version>
</dependency>
<dependency>
<groupId>com.graphql-java</groupId>
<artifactId>graphiql-spring-boot-starter</artifactId>
<version>5.0.2</version>
</dependency>
dog.graphqls
type Dog {
id: ID!
name: String!
breed: String!
origin: String!
}
type Query {
findAllDogs: [Dog]!
findDogById(id:ID!): Dog!
}
type Mutation {
deleteDogBreed(breed: String!) : Boolean
updateDogName(newName: String!, id:ID!) : Dog!
}
Controller class
#RestController
public class DogController {
private DogService dogService;
#Autowired
public void setDogService(DogService dogService){
this.dogService = dogService;
}
#GetMapping("/dogs")
public ResponseEntity<List<Dog>> getAllDog(){
List<Dog> list = dogService.retrieveDogs();
return new ResponseEntity<List<Dog>>(list, HttpStatus.OK);
}
}
Query.java
#Component
public class Query implements GraphQLQueryResolver {
private DogRepository dogRepository;
public Query(DogRepository dogRepository){
this.dogRepository = dogRepository;
}
public Iterable<Dog> findAllDogs(){
return dogRepository.findAll();
}
public Dog findDogById(Long id){
Optional<Dog> optionalDog = dogRepository.findById(id);
if(optionalDog.isPresent()){
Dog dog = optionalDog.get();
return dog;
}else{
throw new DogNotFoundException("Dog Not Found", id);
}
}
}
Mutation.java
#Component
public class Mutation implements GraphQLMutationResolver {
private DogRepository dogRepository;
public Mutation(DogRepository dogRepository){
this.dogRepository = dogRepository;
}
public Boolean deleteDogBreed(String breed){
boolean deleted = false;
Iterable <Dog> dogs = dogRepository.findAll();
for(Dog dog: dogs){
if(dog.getBreed().equals( breed) ){
dogRepository.delete(dog);
deleted = true;
}
}
if(!deleted){
throw new BreedNotFoundException("Breed Not Found", breed);
}
return deleted;
}
public Dog updateDogName(String newName, Long id){
Optional<Dog> optionalDog = dogRepository.findById(id);
if(optionalDog.isPresent()){
Dog dog = optionalDog.get();
dog.setName(newName);
dogRepository.save(dog);
return dog;
}else {
throw new DogNotFoundException("Dog Not Found", id);
}
}
}
Error page

Related

Communication between microservices using Feign throws bean could not be found

I'm trying to get my microservice java spring boot to communicate with another microservice using Feign but I'm getting this message when starting the application:
APPLICATION FAILED TO START
***************************
Description: Parameter 0 of constructor in ProductService required a bean of type ProductClientRepository' that could not be found.
Action: Consider defining a bean of type 'ProductClientRepository' in your configuration.
I don't know what could be wrong, I already checked if all the declared variables are in the project's properties and I already checked the imports, I don't know why it is saying that something is missing in the bean.
pom.xml:
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-oauth2</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
SaleService:
#Service
#RequiredArgsConstructor
public class SaleService {
private final ProductService productService;
#Transactional
public Sale createSale(Sale sale) {
Set<Long> codesFromRequest = sale.getProducts().stream().map(p -> p.getCode())
.collect(Collectors.toSet());
validateProduct(codesFromRequest);
return saleRepository.save(sale);
}
public void validateProduct(Set<Long> codesFromRequest) {
List<SaleProductDTO> products = productService.findProduct(codesFromRequest);
Set<Long> returnedCodes = products.stream().map(p -> p.getCode()).collect(Collectors.toSet());
throwExceptionIf(validateSizeList(codesFromRequest, returnedCodes),
new ProductNotFoundException());
}
public boolean validateSizeList(Collection<?> codesFromRequest, Collection<?> returnedCodes) {
return codesFromRequest.size() != returnedCodes.size();
}
}
ProductService:
#Service
#Slf4j
#AllArgsConstructor
public class ProductService {
private final ProductClientRepository productRepository;
#Retryable(value = { Exception.class }, maxAttempts = 3, backoff = #Backoff(delay = 50))
public List<SaleProductDTO> findProduct(Set<Long> codes) {
Page<SaleProductDTO> resultPage;
try {
var search = SearchProductDTO
.builder()
.codes(codes)
.build();
resultPage = productRepository.getProducts(search);
} catch (FeignException f) {
return Collections.emptyList();
}
return resultPage.getContent();
}
}
ProductClientRepository:
#FeignClient(name = "product-service", url = "${ms-product.url}", configuration = ProductOAuth2FeignConfig.class)
public interface ProductClientRepository {
#GetMapping(value = "/chunk")
Page<SaleProductDTO> getProducts(#RequestBody SearchProductDTO searchDTO);
}
ProductOAuth2FeignConfig:
public class ProductOAuth2FeignConfig {
#Autowired
private ProductConfig productConfig;
#Bean
public RequestInterceptor stockOAuth2RequestInterceptor() {
return new OAuth2FeignRequestInterceptor(new DefaultOAuth2ClientContext(), resource());
}
private OAuth2ProtectedResourceDetails resource() {
ClientCredentialsResourceDetails resource = new ClientCredentialsResourceDetails();
resource.setAccessTokenUri(productConfig.getTokenUri());
resource.setClientId(productConfig.getTokenClientId());
resource.setClientSecret(productConfig.getTokenClientSecret());
resource.setGrantType(productConfig.getTokenGrantType());
resource.setScope(List.of(productConfig.getTokenScope()));
return resource;
}
}
ProductConfig:
#Data
#Configuration
#ConfigurationProperties(prefix = "ms-product")
public class ProductConfig {
private String tokenUri;
private String tokenGrantType;
private String tokenClientId;
private String tokenClientSecret;
private String tokenScope;
}
application.properties:
external.api=https://myadress.com/api
ms-product.url=${external.api}/products
ms-product.token-uri=${external.api}/products/oauth2/token
ms-product.token-grant-type=client_credentials
ms-product.token-client-id=client-id-value
ms-product.token-client-secret=secret-value
ms-product.token-scope=read
feign.client.config.default.connect-timeout=3000
feign.client.config.default.read-timeout=7000
Seems you need to add #EnableFeignClients annotation. Please refer Spring Boot OpenFeign

ClassNotFoundException: No RObject is found to match class type of org.redisson.RedissonMap with codec type of org.redisson.codec.JsonJacksonCodec

Having problems to solve LiveObject raised exception, I try to reproduce problematic behavior based on Redisson test cases.
The minimal code I get to reproduce issue is this test case (mostly inspired from RedissonLiveObjectServiceTest.java):
public class LiveObjectTest {
public static final String TEST_VALUE = "my test value";
public static final Integer TEST_INTEGER = 30;
private RedissonClient redisson;
#BeforeEach
public void beforeEach () {
Config config = new Config();
config.useSingleServer()
.setAddress("http://127.0.0.1:6379");
redisson = Redisson.create(config);
}
#AfterEach
public void afterEach () {
redisson.shutdown();
}
#Test
#DisplayName("Test LiveObject with collection")
public void testLiveObjectMap () {
// Use Live Objects service
RLiveObjectService service = redisson.getLiveObjectService();
service.registerClass(TestREntityWithMap.class);
TestREntityWithMap createdObject = new TestREntityWithMap("testID2");
createdObject = service.persist(createdObject);
RMap<Integer, String> map = redisson.getMap("testMap");
createdObject.setValue(map);
map.put(TEST_INTEGER, TEST_VALUE);
TestREntityWithMap updatedObject = service.get(TestREntityWithMap.class, "testID");
// Fails here to access updatedObject.getValue()
assertEquals(TEST_VALUE, updatedObject.getValue().get(TEST_INTEGER));
}
// Tested class
#REntity
public static class TestREntityWithMap implements Comparable<TestREntityWithMap> {
#RId(generator = UUIDGenerator.class)
private String name;
private Map<Integer, String> value;
public TestREntityWithMap (String name) {
super();
this.name = name;
}
protected TestREntityWithMap () {
super();
}
public String getName () {
return name;
}
public void setName (String name) {
this.name = name;
}
public Map<Integer, String> getValue () {
return value;
}
public void setValue (Map<Integer, String> value) {
this.value = value;
}
#Override
public int compareTo (TestREntityWithMap o) {
return name.compareTo(o.name);
}
}
}
This fails converting back the RedissonMap object to an RObject...
Should not it rather try to convert value property to standard java.util.Map ?
This looks like rather simple usage of the API, am I missing some point here ?
Here is my ObjectMapper setup for JsonJackson:
ObjectMapper mapper = new ObjectMapper();
mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
mapper.configure(MapperFeature.DEFAULT_VIEW_INCLUSION, true);
mapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
mapper.disable(DeserializationFeature.ADJUST_DATES_TO_CONTEXT_TIME_ZONE);
mapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
mapper.configure(MapperFeature.SORT_PROPERTIES_ALPHABETICALLY, true);
mapper.addMixIn(Throwable.class, JsonJacksonCodec.ThrowableMixIn.class);
mapper.findAndRegisterModules();
mapper.registerModule(new JavaTimeModule());
OK....
In case that helps anyone, switching from Redisson 3.8.2 to 3.9.1 solved the bug.
A few minor changes in API (RTopics, connection scheme...) but it is well worth it !
As of now latest redisson
<dependency>
<groupId>org.redisson</groupId>
<artifactId>redisson</artifactId>
<version>3.13.4</version>
</dependency>
Latest Jackson jackson.version property is 2.11.2 for me
<!-- faster JSON -->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>${jackson.version}</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-annotations</artifactId>
<version>${jackson.version}</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>${jackson.version}</version>
</dependency>
Updating Eclipse references
eclipse:eclipse -U

CDI Produces Method InjectionPoint is Null

I am leaning CDI Annotation have a question with respect to Produces Annotation:
I have a Bank
public interface Bank {
public void withdrawal();
public void deposit();
}
Two Implementation flavors
public class BankOfAmerica implements Bank {
public void withdrawal() {
System.out.println("You are withdrawing from Bank Of America");
}
public void deposit() {
System.out.println("You are depositing in Bank Of America");
}
}
public class Chase implements Bank {
public void withdrawal() {
System.out.println("You are withdrawing from Chase");
}
public void deposit() {
System.out.println("You are depositing in Chase");
}
}
A Qualifier
#Qualifier
#Retention(RUNTIME)
#Target({TYPE, METHOD, PARAMETER, FIELD})
public #interface BankProducer {
}
An Enum
public enum BankName {
DCU(DCU.class), Chase(Chase.class), BankOfAmerica(BankOfAmerica.class);
private Class<? extends Bank> bankType;
private BankName(Class<? extends Bank> bankType) {
this.bankType = bankType;
}
public Class<? extends Bank> getBankType() {
return bankType;
}
}
An Annotation to bind the BankName
#Retention(RUNTIME)
#Target({TYPE, METHOD, PARAMETER, FIELD})
public #interface BankType {
#Nonbinding
BankName value();
}
A Factory
public class BankFactory {
#Produces
#BankProducer
public Bank createBank(#Any Instance<Bank> instance, InjectionPoint injectionPoint) {
Annotated annotated = injectionPoint.getAnnotated();
BankType bankTypeAnnotation = annotated.getAnnotation(BankType.class);
Class<? extends Bank> bankType = bankTypeAnnotation.value().getBankType();
return instance.select(bankType).get();
}
}
And a JUnit
#RunWith(Arquillian.class)
public class ProducesTest {
#Inject
#BankProducer
#BankType(BankName.BankOfAmerica)
private Bank bankOfAmerica;
#Deployment
public static JavaArchive createDeployment() {
return ShrinkWrap.create(JavaArchive.class).addPackages(true, "com.tutorial.produces")
.addAsManifestResource(EmptyAsset.INSTANCE, "beans.xml").merge(getDependecies());
}
private static JavaArchive getDependecies() {
JavaArchive[] javaArchives = Maven.configureResolver().loadPomFromFile("pom.xml")
.resolve("org.projectlombok:lombok").withTransitivity().as(JavaArchive.class);
JavaArchive mergedLibraries = ShrinkWrap.create(JavaArchive.class);
for (JavaArchive javaArchive : javaArchives) {
mergedLibraries.merge(javaArchive);
}
return mergedLibraries;
}
#Test
public void create() {
assertEquals(banks.getBankOfAmerica().getClass(), BankOfAmerica.class);
}
}
POM - using tomee
<dependency>
<groupId>org.apache.tomee</groupId>
<artifactId>javaee-api</artifactId>
<version>7.0-1</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.apache.tomee</groupId>
<artifactId>arquillian-tomee-embedded</artifactId>
<version>7.0.3</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.jboss.shrinkwrap.resolver</groupId>
<artifactId>shrinkwrap-resolver-depchain</artifactId>
<version>2.2.2</version>
<scope>test</scope>
<type>pom</type>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.10</version>
<scope>test</scope>
</dependency>
I am getting a NullPointer exception in my factory createBank method. InjectionPoint is Null. What is the issue and how do I resolve it?
Alternate Solution: Tried Weld
<dependency>
<groupId>org.jboss.weld.se</groupId>
<artifactId>weld-se</artifactId>
<version>2.2.8.Final</version>
</dependency>
JUnit
#RunWith(WeldJUnit4Runner.class)
public class ProducesWeldTest {
#Inject
#BankProducer
#BankType(BankName.BankOfAmerica)
private Bank bankOfAmerica;
#Test
public void create() {
assertEquals(bankOfAmerica.getClass(), BankOfAmerica.class);
}
}
WeldContext and WeldJUnit4Runner are from here -
http://memorynotfound.com/java-se-unit-testing-cdi-junit-jboss-weld-se/
As I already mentioned in my comment to the post, the CDI implememtatin seems to work. I think the problem lies in the test. Originally, I just wrote a simple test with a main() method and everything works. Now I moved the same code to the JUnit test and it still works. To test your implementation I just added the following client for your factory and a test class as follows:
public class BankClient {
#Inject
#BankProducer
#BankType(BankName.BankOfAmerica)
private Bank bankOfAmerica;
public void deposit() {
bankOfAmerica.deposit();
}
public void withdrawal() {
bankOfAmerica.withdrawal();
}
}
// JUnit test
public class BankServiceTest {
private static Weld weld = new Weld();
private static BankClient sut;
#BeforeClass
public static void initWeld() {
WeldContainer container = weld.initialize();;
sut = container.instance().select(BankClient.class).get();
}
#Test
public void deposit_should_be_invoked() {
sut.deposit();
}
#Test
public void withdrawal_should_be_called() {
sut.withdrawal();
}
#AfterClass
public static void shutDown() {
weld.shutdown();
}
}
After executing the test, you should see the following output on the console and JUnit green bar:
You are depositing in Bank Of America
You are withdrawing from Bank Of America

JAX-RS test web service showing a blank web page after adding a new #PATH annotation to a new method

I am implementing a restful service in java using JAX-RS, and when testing the service it works only for one of my methods, when I add a new method with a different #PATH annotation the test web page is just blank without errors
My resource class
#Path("beer")
public class BeerResources {
#Context
private UriInfo context;
/**
* Creates a new instance of BeerResources
*/
public BeerResources() {
}
#GET
#Path("/costliest")
#Produces(MediaType.TEXT_PLAIN)
public String getCostliest() {
//TODO return proper representation object
return new BusinessLayer().getCostliest();
}
#GET
#Path("/cheapest")
#Produces(MediaType.APPLICATION_XML)
public String getCheapest() {
//TODO return proper representation object
return new BusinessLayer().getCheapest();
}
}
Application config class
#javax.ws.rs.ApplicationPath("/webresources")
public class ApplicationConfig extends Application {
#Override
public Set<Class<?>> getClasses() {
Set<Class<?>> resources = new java.util.HashSet<>();
addRestResourceClasses(resources);
return resources;
}
/**
* Do not modify addRestResourceClasses() method.
* It is automatically populated with
* all resources defined in the project.
* If required, comment out calling this method in getClasses().
*/
private void addRestResourceClasses(Set<Class<?>> resources) {
resources.add(beerrestful.BeerResources.class);
}
}
You can try to use Spring Boot + JAX-RS approach or Spring Boot + Spring MVC. Here are both of them on my Github page.
Also there is Spring Boot + JAX-RS source code:
Application.java:
#SpringBootApplication
public class Application extends SpringBootServletInitializer {
#Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
return application.sources(Application.class);
}
public static void main(String[] args) {
SpringApplicationBuilder builder = new SpringApplicationBuilder(Application.class);
new Application().configure(builder).run(args);
}
}
DrinkEndpoint.java:
#Component
#Path("/drinks")
public class DrinkEndpoint {
#Autowired
private DrinkService drinkService;
#GET
#Path("/list")
#Produces(MediaType.APPLICATION_JSON)
public Iterable<Drink> getCostliest() {
return drinkService.getDrinks();
}
#GET
#Path("/{drink}")
#Produces(MediaType.APPLICATION_JSON)
public Response getCheapest(#PathParam("drink") String name) {
Optional<Drink> drink = drinkService.getDrink(name);
if (drink.isPresent()) {
return Response.status(201).entity(drink.get().getName()).build();
} else {
return Response.status(201).entity("NOT_FOUND").build();
}
}
}
DrinkService.java:
public interface DrinkService {
Iterable<Drink> getDrinks();
Optional<Drink> getDrink(String name);
}
DrinkServiceImpl.java:
#Component
public class DrinkServiceImpl implements DrinkService {
private List<Drink> drinks = new ArrayList<Drink>() {{
add(new Drink("Coca Cola", 1886));
add(new Drink("Pepsi", 1903));
}};
public Iterable<Drink> getDrinks() {
return drinks;
}
public Optional<Drink> getDrink(String name) {
for (Drink drink : drinks) {
if (drink.getName().equalsIgnoreCase(name)) {
return Optional.of(drink);
}
}
return Optional.empty();
}
}
ApplicationConfig.java:
#Component
public class ApplicationConfig extends ResourceConfig {
public ApplicationConfig() {
register(DrinkEndpoint.class);
}
}
Drink.java:
public class Drink {
private String name;
private int since;
public Drink(String name, int since) {
this.name = name;
this.since = since;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getSince() {
return since;
}
public void setSince(int since) {
this.since = since;
}
}
pom.xml:
<project>
....
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-dependencies</artifactId>
<version>1.3.0.RELEASE</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jersey</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
<scope>provided</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
To start application run:
mvn spring-boot:run
Then open in browser:
http://localhost:8080/drinks/list
http://localhost:8080/drinks/pepsi
Make sure you are returning proper XML format
Example:
#Produces(MediaType.APPLICATION_XML)
public String getCheapest() {
return "<abc>xyz</abc>";
}
If BusinessLayer().getCheapest() function is returning String and you have used tag #Produces(MediaType.APPLICATION_XML) it will just show you a blank page.
Use appropriate MediaType in #Produces tag according to the value returned from BusinessLayer().getCheapest() function

Weld and Java SE

I'm new to Weld and have been trying to get my head around it's concepts. I have a little experience with Spring and nothing with Guice, so I'm pretty much a novice with the DI frameworks.
Here's a tutorial that introduce CDI, but in the context of web apps. I'm interested to see how this works in Java SE alone. I have created the following classes, but have no idea how to test the ItemProcessor's execute method with the DefaultItemDao class (or any other alternative) in a Java SE app.
Here're the classes:
public class Item {
private int value;
private int limit;
public Item(int v, int l) {
value = v;
limit = l;
}
public int getValue() {
return value;
}
public void setValue(int value) {
this.value = value;
}
public int getLimit() {
return limit;
}
public void setLimit(int limit) {
this.limit = limit;
}
#Override
public String toString() {
return "Item [value=" + value + ", limit=" + limit + "]";
}
}
import java.util.List;
public interface ItemDao {
List<Item> fetchItems();
}
import java.util.ArrayList;
import java.util.List;
public class DefaultItemDao implements ItemDao {
#Override
public List<Item> fetchItems() {
List<Item> results = new ArrayList<Item>(){{
add(new Item(1,2));
add(new Item(2,3));
}};
return results;
}
}
import java.util.List;
import javax.inject.Inject;
public class ItemProcessor {
#Inject
private ItemDao itemDao;
public void execute() {
List<Item> items = itemDao.fetchItems();
for (Item item : items) {
System.out.println("Found item: "+item);
}
}
}
And I have no idea how to write a test client for the ItemProcessor class. Can someone help me understand how to write one with CDI?
Thanks, Kumar
I had same question with injection Validator using JavaSE. Finally I managed to solve it. Hope it helps someone!
Dependencies i used:
<dependency>
<groupId>javax.validation</groupId>
<artifactId>validation-api</artifactId>
<version>2.0.0.Alpha2</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-validator-cdi</artifactId>
<version>6.0.0.Alpha2</version>
</dependency>
<dependency>
<groupId>org.jboss.weld.se</groupId>
<artifactId>weld-se</artifactId>
<version>2.4.3.Final</version>
</dependency>
<dependency>
<groupId>javax.el</groupId>
<artifactId>javax.el-api</artifactId>
<version>3.0.0</version>
</dependency>
<dependency>
<groupId>org.glassfish.web</groupId>
<artifactId>javax.el</artifactId>
<version>2.2.6</version>
</dependency>
Main method:
Weld weld = new Weld().interceptors(Validator.class);
WeldContainer container = weld.initialize();
PurchaseOrderService service =
container.select(ru.code.service.PurchaseOrderService.class).get();
Customer customer = new Customer(.....);
service.createCustomer(customer);
weld.shutdown();
PurchaseOrderService.java
#Inject
private Validator validator;
private Set<ConstraintViolation<Customer>> violations;
public PurchaseOrderService() {
}
public void createCustomer(Customer customer) {
violations = validator.validate(customer);
if (violations.size() > 0) {
throw new ConstraintViolationException(violations);
}
}
And also i created beans.xml in resources/META-INF directory:
<?xml version="1.0" encoding="UTF-8"?>
<beans
xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/beans_1_1.xsd"
bean-discovery-mode="all">
</beans>

Categories