Inject EJB annotation - java

When I use annotation #EJB in my code all work fine
public class CatalogueDetailsPage extends AbstractBasePage {
#EJB(lookup = "java:global/mobile.bank.services-1.0.5/api.ejb-1.1/CatalogueFacadeBean!by.softclub.common.api.ICatalogueService")
private ICatalogueService iCatalogueService;
}
But when I want use #Inject & #Produces I have error null pointer
public class CatalogueDetailsPage extends AbstractBasePage {
#Inject
#EJBBean
private ICatalogueService iCatalogueService;
}
#Stateless
public class EJBFactory {
#EJB(lookup = "java:global/mobile.bank.services-1.0.5/api.ejb-
protected ICatalogueService iCatalogueService;
#Produces
#EJBBean
public ICatalogueService getiCatalogueService() {
return iCatalogueService;
}
}
#Qualifier
#Retention(RetentionPolicy.RUNTIME)
#Target({ ElementType.TYPE, ElementType.METHOD, ElementType.FIELD, ElementType.PARAMETER })
public #interface EJBBean {
}
}
Why is this happening?

Related

#Inject interface with two implementation

I am using Microprofile and I have a question. I have an interface with a method inside:
public interface CheckData extends Serializable{
MyObject retrieveData(String name);
}
This interface is implemented by 2 different classes( Class A and Class B).
In the service class I need to use class A or class B based on a condition.
I did the #Inject of my interface:
#ApplicationScoped
public class MyService{
#Inject
private CheckData checkData;
public Response manageData{
...
if(condition)
checkData.retrieveData(name) // i needed Class A implementation
if(condition)
checkData.retrieveData(name) // i needed Class B implementation
}
}
how do you specify which implementation to use?
I solved it this way.
I have created a class with two qualifiers:
public class MyQualifier {
#Qualifier
#Retention(RetentionPolicy.RUNTIME)
#Target({ElementType.FIELD, ElementType.TYPE, ElementType.METHOD})
public #interface ClassifierOne {
}
#Qualifier
#Retention(RetentionPolicy.RUNTIME)
#Target({ElementType.FIELD, ElementType.TYPE,ElementType. METHOD})
public #interface ClassifierTwo {
}
}
later I added the qualifiers to the classes that implement the interface:
#ClassifierOne
public class A implements CheckData{
...
}
#ClassifierTwo
public class B implements CheckData{
...
}
Finally I injected the interface specifying the qualifier:
#Inject
#ClassifierOne
private CheckData myClassA;
#Inject
#ClassifierTwo
private CheckData myClassB;
I hope it is correct and can help others.
Thanks to #Turo and #Asif Bhuyan for the support

Spring Async Annotation: Executor Id by Enum

I have a custom #Async annotation with the specified Executor ID.
#Retention(RetentionPolicy.RUNTIME)
#Target({ElementType.TYPE, ElementType.METHOD})
#Async("fixedThreadPool")
public #interface AsyncFixedPool {
}
I wonder is it possible to specify executor id by enum? For example, something like that.
public enum ExecutorType {
EXECUTOR_1, EXECUTOR_2
}
...
#Retention(RetentionPolicy.RUNTIME)
#Target({ElementType.TYPE, ElementType.METHOD})
#Async
public #interface AsyncFixedPool {
// value converts as Enum.name()
#AliasFor(annotation = Async.class, attribute = "value")
ExecutorType value();
}
...
#AsyncFixedPool(EXECUTOR_1)
public void myAsyncMethod() {...}

Validating member List variables for null values

The structure that I have is something like below:
Class A{
String str;
int i;
List<B> bs;
C c;
#NotNull
List<D> ds;
}
Class B{
#NotNull
List<E> es;
}
Class C{
List<String> s;
}
Class E{
#NotNull
List<String> s;
}
For the list variables that are annotated with #NotNull I need to throw validation error if any of them variables has one or more null objects. While for the other list variables I just need to remove the nulls;
What would be the best way to achieve this?
If you are using validation 2.0+ you can put annotation inside: List<#NotNull String> s;
You should define custom annotation for validating.
so define custom annotation like bellow.
#Target({ElementType.FIELD, ElementType.PARAMETER,ElementType.ANNOTATION_TYPE})
#Retention(RUNTIME)
#Constraint(validatedBy = ValidateListValidator.class)
#Documented
public #interface ValidateList {
}
and implement ValidateListValidator like this:
public class ValidateListValidator implements ConstraintValidator<ValidateList, List<Object>> {
private ValidateList validateList;
#Override
public void initialize(ValidateList validateList) {
this.validateList = validateList;
}
#Override
public boolean isValid( List<Object> list, ConstraintValidatorContext constraintValidatorContext) {
return list.stream().noneMatch(Objects::isNull);
}
}
and for test it
#Test
public void test() {
boolean valid = validator.isValid(Arrays.asList("test","this",null),context);
assertThat(valid, is(false));
}
This is the final code that I wrote, just a few tweaks to the code that Hadi posted. I hope it helps:
Annotation:
import java.lang.annotation.Target;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import javax.validation.Constraint;
import javax.validation.Payload;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
#Target({ElementType.ANNOTATION_TYPE, ElementType.FIELD, ElementType.TYPE})
#Retention(RetentionPolicy.RUNTIME)
#Constraint(validatedBy = ListValidator.class)
#Documented
public #interface ValidList {
String message() default "Null values are not allowed in array fields.";
Class<?>[] groups() default {};
Class<? extends Payload>[] payload() default {};
}
Validator Class:
import java.util.List;
import java.util.Objects;
import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
public class ListValidator implements ConstraintValidator<ValidList, List<? extends Object>> {
#Override
public boolean isValid(List<? extends Object> list, ConstraintValidatorContext context) {
return list.stream().noneMatch(Objects::isNull);
}
#Override
public void initialize(ValidList constraintAnnotation) {}
}

CDI method injection and bean inheritance in Java

What I want to do - I have a child and parent class. Child has SimpleFoo, Parent needs Advaced foo. So,
#Dependent
public class SimpleFoo {
}
#Dependent
public class AdvancedFoo extends SimpleFoo {
}
#Dependent
public class Child {
private SimpleFoo foo;
#Inject
protected void setFoo(SimpleFoo foo) {
this.foo = foo;
}
}
#Dependent
public class Parent extends Child {
#Inject
#Override
protected void setFoo(SimpleFoo foo) { //How to inject here AdvancedFoo
super.setFoo(foo);
}
}
I know that I can do it via constructor injection but I need method injection. How to do it? Can it be done without using names (like MyBean1) but only using classes (AdvancedFoo)?
Use qualifiers - you now have two beans which both fulfill your requirements on type; you need to limit that and qualifiers are made for such cases.
Here is how to do it, first the qualifier:
#Qualifier
#Retention(RetentionPolicy.RUNTIME)
#Target({ ElementType.TYPE, ElementType.PARAMETER, ElementType.FIELD, ElementType.METHOD })
public #interface MyQualifier {
}
Now, make your AdvancedFoo bean use that qualifier:
#Dependent
#MyQualifier
public class AdvancedFoo extends SimpleFoo {
...
}
And finally, in the init method, inject a bean of type SimpleFoo and with qualifier #MyQualifier:
#MyQualifier
public class Parent extends Child {
#Inject
protected void setFoo(#MyQualifier SimpleFoo foo) {
this.foo = foo;
}
}

bean validation spring + hibernate annotion does not work

What am I doing wrong? The test does not work.
This is my Interface class:
#Validated
public interface ICustomerService
{
public List<Customer> findbyStr(
#NotEmpty(message = "{column.notvalid}")
#NotNull(message = "{column.notvalid}")
String column,
#NotEmpty(message = "{column.notvalid}")
#NotNull(message = "{value.notvalid}")
String value);
}
This is my Implementation class:
#Service("customerService")
#Scope(value = "singleton", proxyMode = ScopedProxyMode.TARGET_CLASS)
public class CustomerService implements ICustomerService {
#Autowired
private IStorageDao<Customer> dao;
#Override
public List<Customer> findbyStr(String column, String value) {
return dao.findByString(Customer.class, column, value);
}
}
This is my unit-Test class:
JUNIT Test does not work.
#RunWith(SpringJUnit4ClassRunner.class)
public class CustomerTest extends BaseIntegrationTest {
#Autowired
private ICustomerService service;
#Autowired
public static Validator validator;
#Test
public void test_A6_CustomerFindByStrNull() {
List<Customer> result = service.findbyStr(null, null);
Set<ConstraintViolation<ICustomerService>> constraintViolations = validator
.validate(service);
assertEquals(0, constraintViolations.size());
assertEquals("Die angegebene E-Mail-Adresse ist fehlerhaft.",
constraintViolations.iterator().next().getMessage());
assertNotNull(result);
assertNotNull(result.get(1));
}
}
I'm pretty sure you cannot test ConstraintViolations when the annotations are on a method of an object since it should throw a MethodConstraintViolationException. You should try something like this :
#RunWith(SpringJUnit4ClassRunner.class)
public class CustomerTest extends BaseIntegrationTest {
#Autowired
private ICustomerService service;
#Test
public void test_A6_CustomerFindByStrNull() {
try {
List<Customer> result = service.findbyStr(null, null);
} catch (MethodConstraintViolationException ex) {
assertEquals("Die angegebene E-Mail-Adresse ist fehlerhaft.", ex.getConstraintViolations().iterator().next().getMessage());
}
fail("Exception expected");
}
}
You need to have the following Bean in your application-context.xml file :
<bean class="org.springframework.validation.beanvalidation.MethodValidationPostProcessor"/>

Categories