Jersy2 inject slf4j Logger - dependency-injection

I'm trying to understand Jersey 2 development and context-dependency injection.
I don't understand how to inject into a resource an object that needs initialization parameters in the constructor.
For example: I'd like to #Inject slf4j Logger, built using LoggerFactory.
My resource class is:
#Path("/myresource")
public class MyResource {
#Inject
private Logger log;
#GET
#Produces(MediaType.APPLICATION_JSON)
public Answer status() {
log.info("STATUS");
return new Answer(200, "Server up and running # "+ ZonedDateTime.now());
}
}
My Resource config is:
public class MyAppextends ResourceConfig {
public MyApp() {
register(new MyBinder());
packages(true, "my.packages");
}
}
public class MyBinder extends AbstractBinder {
#Override
protected void configure() {
bindFactory(MyLoggerFactory.class).to(org.slf4j.Logger.class);
}
}
Finally, the Factory is:
public class MyLoggerFactory implements Factory<Logger> {
#Override
public Logger provide() {
return LoggerFactory.getLogger(TYPE_FOR_LOGGING.class);
}
#Override
public void dispose(Logger logger) {
}
}
How can I specify TYPE_FOR_LOGGING as argument, in order to Inject the correctly initialized Logger in every resource I want?
Thanks

What you are looking for is called the InstantiationService. You can inject it into Factories to find out who is calling the factory inside of the provide method.
Below find a code sample from the hk2 tests that illustrate the use of the InstantiationService.
#Singleton
public class CorrelationFactory implements Factory<PerLookupServiceWithName> {
private final static PerLookupServiceWithName NULL_SERVICE = new PerLookupServiceWithName() {
#Override
public String getName() {
return null;
}
};
#Inject
private InstantiationService instantiationService;
/* (non-Javadoc)
* #see org.glassfish.hk2.api.Factory#provide()
*/
#Override #PerLookup
public PerLookupServiceWithName provide() {
InstantiationData data = instantiationService.getInstantiationData();
if (data == null) {
return NULL_SERVICE;
}
Injectee parent = data.getParentInjectee();
if (parent == null) {
return NULL_SERVICE;
}
Class<?> parentClass = parent.getInjecteeClass();
if (parentClass == null) {
return NULL_SERVICE;
}
Correlator correlator = parentClass.getAnnotation(Correlator.class);
if (correlator == null) {
return NULL_SERVICE;
}
final String fName = correlator.value();
return new PerLookupServiceWithName() {
#Override
public String getName() {
return fName;
}
};
}
/* (non-Javadoc)
* #see org.glassfish.hk2.api.Factory#dispose(java.lang.Object)
*/
#Override
public void dispose(PerLookupServiceWithName instance) {
// DO nothing
}
}

Related

How can I inject Optional<T> with hk2?

I have a Factory that looks at some property to determine if the value T should be provided. How can I use this with HK2 in an abstract binder?
public interface Printer {
void print(String str);
}
public ConsolePrinter implements Printer {
public void print(String str) {
System.out.println(str);
}
}
public PrinterFactory implements Factory<Optional<Printer>> {
boolean isPrinterAvailable;
public PrinterFactory(boolean isPrinterAvailable) {
this.isPrinterAvailable = isPrinterAvailable;
}
public Optional<Printer> provide() {
if (this.isPrinterAvailable) {
return new ConsolePrinter();
}
return Optional.empty();
}
}
public class Binder extends AbstractBinder {
protected void configure() {
// ?????
bindFactory(PrinterFactory.class).to(Printer.class);
}
}
Any help/documentation/examples is much appreciated!

Google Guice binding using Annotation and Key class

Lets say we have A.java interface implemented by AImpl.java and B.java implemented by Bimpl.java
Above classes are binded in two modules as below
Module1 {
bind(A.class).to(AImpl.class);
bind(B.class).to(BImpl.class);
}
Module2 {
Key<A> aKey = Key.get(A.class, AnAnnot.class);
bind(aKey).to(AImpl.class);
Key<B> bKey = Key.get(B.class, AnAnnot.class);
bind(bKey).to(BImpl.class);
}
Class AImpl implements A {
}
Class BImpl implements B {
#Inject
BImpl(A aImpl) {
//??
}
}
BImpl refers to A
For BImpl binded using Annotation, I want corresponding aImpl, binded using Annotation but here I'm getting aImpl which is not binded using Annotation
Please suggest
I'm able to achieve using below pattern. May be there is a more easier way. Happy to know more
A.java
public interface A {
String aMethod();
}
AImpl.java
public class AImpl implements A {
private String moduleName;
public AImpl(String moduleName) {
this.moduleName = moduleName;
}
#Override
public String aMethod() {
return moduleName;
}
}
B.java
public interface B {
String bMethod();
}
Bimpl.java
public class BImpl implements B {
private final A a;
BImpl(A a) {
this.a = a;
}
#Override
public String bMethod() {
return a.aMethod();
}
}
AnAnnot.java
#Target(PARAMETER)
#Retention(RUNTIME)
#BindingAnnotation
public #interface AnAnnot {
}
BProvider.java
public class BProvider implements Provider<B> {
private final A a;
#Inject
BProvider(A a) {
this.a = a;
}
#Override
public B get() {
return new BImpl(a);
}
}
BHavingAnnotatedA.java
public class BHavingAnnotatedA implements Provider<B> {
private final A a;
#Inject
BHavingAnnotatedA(#AnAnnot A a) {
this.a = a;
}
#Override
public B get() {
return new BImpl(a);
}
}
ABModule1.java
public class ABModule1 extends AbstractModule {
#Override
protected void configure() {
bind(A.class).to(AImpl.class);
bind(B.class).toProvider(BProvider.class);
}
}
ABModule2.java
public class ABModule2 extends AbstractModule {
#Override
protected void configure() {
Key<A> aKey = Key.get(A.class, AnAnnot.class);
bind(aKey).to(AImpl.class);
Key<B> bKey = Key.get(B.class, AnAnnot.class);
bind(bKey).toProvider(BHavingAnnotatedA.class);
}
}

Dagger generated code compilation failed when using #Singleton annotation

I am using Dagger - 2.6 and i have the following classes.
public class Trigger {
public static JSONObject triggerLambda(JSONObject jsonObject) {
DataTransformerComponent daggerDataTransformerComponent = DaggerDataTransformerComponent.create();
return daggerDataTransformerComponent.getHandler().handle(jsonObject);
}
}
Data Handler class:
public class DataHandler {
private static final Logger LOGGER = Logger.getLogger(DataHandler.class.getName());
private A a;
#Inject
public DataHandler(A a) {
this.a = a;
}
public JSONObject handle(JSONObject input) {
LOGGER.info("Json input received - " + input.toString());
return a.executeTransformation(input);
}
}
And a dependency:
public class A {
#Inject
public A() {
}
public JSONObject executeTransformation(JSONObject jsonObject) {
System.out.println("a");
return null;
}
}
My component class looks like:
#Component
public interface DataTransformerComponent {
DataHandler getHandler();
}
When i compile the above code it runs absolutely fine.
Now i want to make my A dependency #Singleton.
So i change my dependency class and component class as follows:
#Singleton
#Component
public interface DataTransformerComponent {
DataHandler getHandler();
}
Dependency class:
#Singleton
public class A {
#Inject
public A() {
}
public JSONObject executeTransformation(JSONObject jsonObject) {
System.out.println("a");
return null;
}
}
But now the generated component shows compilation errors saying:
A_Factory not found and it fails in the initialize() method.
DaggerDataTransformerComponent :
#Generated(
value = "dagger.internal.codegen.ComponentProcessor",
comments = "https://google.github.io/dagger"
)
public final class DaggerDataTransformerComponent implements DataTransformerComponent {
private Provider<A> aProvider;
private Provider<DataHandler> dataHandlerProvider;
private DaggerDataTransformerComponent(Builder builder) {
assert builder != null;
initialize(builder);
}
public static Builder builder() {
return new Builder();
}
public static DataTransformerComponent create() {
return builder().build();
}
#SuppressWarnings("unchecked")
private void initialize(final Builder builder) {
this.aProvider = DoubleCheck.provider(A_Factory.create());
this.dataHandlerProvider = DataHandler_Factory.create(aProvider);
}
#Override
public DataHandler getHandler() {
return dataHandlerProvider.get();
}
public static final class Builder {
private Builder() {}
public DataTransformerComponent build() {
return new DaggerDataTransformerComponent(this);
}
}
}
I am unable to figure out why it does not create _factory class when i use #Singleton annotation.?.
Just use regular JavaScript + node.js, its a lot simpler

NestedSlot presenter with own url- how to setup url for NestedSlot presenters

I have parent presenter: UsersListPresenter that contains nested presenter: UserPresenter in NestedSlot.
public class UsersListPresenter extends ApplicationPresenter<UsersListPresenter.MyView, UsersListPresenter.MyProxy> implements UsersListUiHandlers,
OpenWindowEvent.OpenModaHandler, UserAddedEvent.UserAddedHandler {
#ProxyStandard
#NameToken(ClientRouting.Url.users)
#UseGatekeeper(IsUserLoggedGatekeeper.class)
public interface MyProxy extends TabContentProxyPlace<UsersListPresenter> {}
#TabInfo(container = AppPresenter.class)
static TabData getTabLabel(IsUserLoggedGatekeeper adminGatekeeper) {
return new MenuEntryGatekeeper(ClientRouting.Label.users, 1, adminGatekeeper);
}
public interface MyView extends View, HasUiHandlers<UsersListUiHandlers> {
void setUsers(List<UserDto> users);
void addUser(UserDto user);
}
public static final NestedSlot SLOT_USER_WINDOW = new NestedSlot();
//interface Driver extends SimpleBeanEditorDriver<UserDto, UserEditor> {}
private static final UserService userService = GWT.create(UserService.class);
private AppPresenter appPresenter;
private UserTestPresenter userPresenter;
#Inject
UsersListPresenter(EventBus eventBus, MyView view, MyProxy proxy, AppPresenter appPresenter, UserTestPresenter userPresenter) {
super(eventBus, view, proxy, appPresenter, AppPresenter.SLOT_TAB_CONTENT);
this.appPresenter = appPresenter;
this.userPresenter = userPresenter;
getView().setUiHandlers(this);
}
#Override
protected void onBind() {
super.onBind();
updateList();
setInSlot(SLOT_USER_WINDOW, userPresenter);
addRegisteredHandler(OpenWindowEvent.getType(), this);
}
#Override
protected void onReveal() {
super.onReveal();
initializeApplicationUiComponents(ClientRouting.Label.users);
}
#Override
public void onOpenModal(OpenWindowEvent event) {
openModal(event.getUser());
}
#Override
public void openModal(UserDto user) {
userPresenter.openModal(user);
}
}
public class UsersListView extends ViewWithUiHandlers<UsersListUiHandlers> implements UsersListPresenter.MyView {
interface Binder extends UiBinder<Widget, UsersListView> {}
#UiField
SimplePanel windowSlot;
#Inject
UsersListView(Binder uiBinder) {
initWidget(uiBinder.createAndBindUi(this));
}
#Override
public void setInSlot(Object slot, IsWidget content) {
if (slot == UsersListPresenter.SLOT_USER_WINDOW) {
windowSlot.setWidget(content);
}
};
}
public class UserTestPresenter extends Presenter<UserTestPresenter.MyView, UserTestPresenter.MyProxy> implements UserTestUiHandlers {
public interface MyView extends View, HasUiHandlers<UserTestUiHandlers> {
void openModal(UserDto user);
}
#ProxyStandard
#NameToken("/user/{userid}")
public interface MyProxy extends ProxyPlace<UserTestPresenter> {
}
private PlaceManager placeManager;
#Inject
public UserTestPresenter(EventBus eventBus, MyView view, MyProxy proxy, PlaceManager placeManager) {
super(eventBus, view, proxy, UsersListPresenter.SLOT_USER_WINDOW);
this.placeManager = placeManager;
getView().setUiHandlers(this);
}
#Override
public void prepareFromRequest(PlaceRequest request) {
GWT.log("Prepare from request " + request.getNameToken());
}
#Override
protected void onReveal() {
super.onReveal();
};
public void openModal(UserDto user) {
getView().openModal(user);
}
#Override
public void onSave(UserDto user) {
// TODO Auto-generated method stub
MaterialToast.fireToast("onSaveClick in new presenter for " + user.toString());
}
#Override
public void onClose() {
PlaceRequest placeRequest = new PlaceRequest.Builder().nameToken("/users/{userid}").with("userid", "list").build();
placeManager.revealPlace(placeRequest);
}
public class UserTestView extends ViewWithUiHandlers<UserTestUiHandlers> implements UserTestPresenter.MyView {
interface Binder extends UiBinder<Widget, UserTestView> {}
#UiField
MaterialRow main;
#UiField
MaterialWindow window;
#UiField
MaterialLabel userName, userFullName;
#UiField
MaterialButton saveButton;
private HandlerRegistration saveButtonClickHandler;
#Inject
UserTestView(Binder uiBinder) {
initWidget(uiBinder.createAndBindUi(this));
// adding default click handler
saveButtonClickHandler = saveButton.addClickHandler(new ClickHandler() {
#Override
public void onClick(ClickEvent event) {}
});
}
#Override
public void openModal(final UserDto user) {
userName.setText(user.getEmail());
userFullName.setText(user.getId() + " " + user.getEmail());
saveButtonClickHandler.removeHandler();
saveButtonClickHandler = saveButton.addClickHandler(new ClickHandler() {
#Override
public void onClick(ClickEvent event) {
getUiHandlers().save(user);
}
});
window.openWindow();
}
}
when user from list is clicked the window with clicked users is opened. At this moment url should change from http://localhost:8080/cms/#/users/list to http://localhost:8080/cms/#/user/3
for better understanding below is screencast from that code:
and now some job done, but still not ideal:
here is my gwtp configuration:
public class ClientModule extends AbstractPresenterModule {
#Override
protected void configure() {
bind(RestyGwtConfig.class).asEagerSingleton();
install(new Builder()//
.defaultPlace(ClientRouting.HOME.url)//
.errorPlace(ClientRouting.ERROR.url)//
.unauthorizedPlace(ClientRouting.LOGIN.url)//
.tokenFormatter(RouteTokenFormatter.class).build());
install(new AppModule());
install(new GinFactoryModuleBuilder().build(AssistedInjectionFactory.class));
bind(CurrentUser.class).in(Singleton.class);
bind(IsAdminGatekeeper.class).in(Singleton.class);
bind(IsUserLoggedGatekeeper.class).in(Singleton.class);
bind(ResourceLoader.class).asEagerSingleton();
}
}
As You can see I use tokenFormatter(RouteTokenFormatter.class)
how it can be achieved with gwtp framework?
One way to achieve this is to change the URL of your UserListPresenter to support passing in the user id as an optional parameter:
#NameToken("/users/{userid}")
public interface MyProxy extends ProxyPlace<UserListPresenter> {
}
You need to override the prepareFromRequest method of your UserListPresenter and there you check if the userid is set and open your modal window if it is.
#Override
public void prepareFromRequest(PlaceRequest request) {
String userid = request.getParameter("userid", "list");
if (userid != "list") {
# open modal
}
else {
# close modal
}
}
You also need to change the logic when you click your on a user in your list:
#Override
public void onOpenModal(OpenWindowEvent event) {
PlaceRequest placeRequest = new PlaceRequest.Builder()
.nameToken("/users/{userid}")
.with("userid", event.getUser().getId())
.build();
placeManager.revealPlace(placeRequest);
}
This will change the URL and open the modal.

Stateless EJB not injected in message driven bean (MDB)

I have a message driven bean (MDB) that implements MessageListener and has several EJB attributes but non of them are injected so I have to inject them manually. The MDB also has a resource and a CDI bean that are injected fine.
Why the EJBs are not injected automatically? I use NotificationService EJB at other parts of the application and they are injected. Any clue about how to figure out the problem?
I don't get any error from Weblogic 12.1.3, so I can't figure out what's happening here. My code is (full of traces for debugging purposes). I've removed javadocs and method implementations that are not relevant to the problem:
#MessageDriven(name = "MailMessageConsumer", description = "JMS consumer", mappedName = MailJndiConfiguration.JNDI_QUEUE,
activationConfig = {
#ActivationConfigProperty(propertyName = "acknowledgeMode",
propertyValue = "Auto-acknowledge"),
#ActivationConfigProperty(propertyName = "destinationType",
propertyValue = "javax.jms.Queue")
})
#TransactionAttribute(TransactionAttributeType.REQUIRED)
#MessageReceiver(responsibility = "Consumes JMS messages of type MailMessage")
public class MailMessageConsumer implements MessageListener {
private static final Logger log = LoggerFactory.getLogger(MailMessageConsumer.class);
#Resource
private MessageDrivenContext messageDrivenContext;
#EJB
private NotificationService notificationService;
#EJB
private MailClient mailClient;
#Inject
private ApplicationInformation applicationInformation;
#Override
public void onMessage(Message message) {
if (mailClient == null) {
log.error("mailClient object is null");
try {
log.info("Instantiating MailClient manually...");
mailClient = BeanManagerHelper.getReference(MailClient.class);
} catch (Exception e) {
log.error("Cannot instantiate MailClient manually", e);
}
}
if (notificationService == null) {
log.error("notificationService object is null");
try {
log.info("Instantiating NotificationService manually...");
notificationService = BeanManagerHelper.getReference(NotificationService.class);
} catch (Exception e) {
log.error("Cannot instantiate NotificationService manually", e);
}
}
// This never happens
if (applicationInformation == null) {
log.error("applicationInformation object is null");
}
// This never happens
if (messageDrivenContext == null) {
log.error("messageDrivenContext object is null");
}
deliverMessage(message);
}
private void deliverMessage(Message message) {
// Not important
}
private MailMessage retrieveMessage(Message message) {
// Not important
}
private void sendEmail(MailMessage mailMessage) {
// Not important
}
}
MailClient EJB:
#Stateless
#LocalBean
#TransactionAttribute(TransactionAttributeType.MANDATORY)
#Service
public class MailClient {
private static final Logger logger = LoggerFactory.getLogger(MailClient.class);
#Resource(mappedName = MailJndiConfiguration.JNDI_MAIL_SESSION)
private Session mailSession;
#EJB
private NotificationService notificationService;
#Inject
private ApplicationInformation applicationInformation;
enum ValidationError {
NULL_OBJECT("Mail message is null"),
CONTENT_TYPE_EMPTY("Content type not initialized"),
BODY_EMPTY("Message body content is empty");
private static final String ERROR_MESSAGE_PREFIX = "Invalid mail message: ";
private String message = ERROR_MESSAGE_PREFIX;
ValidationError(String message) {
this.message += message;
}
public String getMessage() {
return message;
}
}
public void sendMail(MailMessage mailMessage) throws MailMessageSendingException {
// Not important
}
}
NotificationService EJB:
#Stateless
#LocalBean
#TransactionAttribute(TransactionAttributeType.MANDATORY)
#Service
public class NotificationService {
private static final Logger logger = LoggerFactory.getLogger(NotificationService.class);
#PersistenceContext(unitName = "myEntityManager")
private EntityManager entityManager;
#EJB
private NotificationPendingMessageValidator notificationPendingMessageValidator;
#EJB
private NotificationFinder notificationFinder;
#Inject
private ApplicationInformation applicationInformation;
public NotificationPendingMessageEntity saveNotificationMessageForDeferredMail(NotificationPendingMessageEntity notificationPendingMessageEntity) throws ValidationException {
// Not important
}
public List<NotificationPendingMessageEntity> findNotificationPendingMessageEntities(TimeSlot timeSlot) {
// Not important
}
#TransactionAttribute(TransactionAttributeType.REQUIRES_NEW)
public NotificationMailEntity createNewMailEntity() {
// Not important
}
#TransactionAttribute(TransactionAttributeType.REQUIRES_NEW)
public void updateMailEntity(NotificationMailEntity mailEntity) {
// Not important
}
public void createNotificationMessageProcessedEntity(NotificationProcessedMessageEntity notificationProcessedMessageEntity) {
// Not important
}
public void removeNotificationMessagePendingEntity(NotificationPendingMessageEntity notificationPendingMessageEntity) {
// Not important
}
public void reportMailFailure(NotificationMailEntity mailEntity, String failureNotice) {
// Not important
}
}
Using #Inject for injecting the EJBs instead of #EJB annotation works fine. So there should be a problem with some Weblogic's patches, because testing it in another Weblogic (same version, different patches) it worked as well

Resources