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!
Related
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);
}
}
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
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
}
}
What is the correct way to configure an object in structuremap that implements two interface but is a singleton.
For example class Main implements both iMainFrmService and iActiveJobService.
Here is what I've tried, but I'm not sure if it's correct.
ObjectFactory.Initialize(pExpression=>
{
pExpression.ForSingletonOf<iMainFrmService>().Use<Main>();
pExpression.ForSingletonOf<iActiveJobService>().Use<Main>();
});
As mentioned in the answer linked to from the comment above, x.Forward< , >() does give the singleton for both the interfaces.
Please check out this dotnetfiddle for a working sample. Here is snippet that is posted there:
using System;
using StructureMap;
namespace StructureMapSingleton {
public class Program {
public static void Main(string [] args) {
Bootstrapper.Initialize();
var mainService = Bootstrapper.GetInstance<IMainService>();
mainService.MainMethod();
var secondaryService = Bootstrapper.GetInstance<ISecondaryService>();
secondaryService.SecondMethod();
Console.ReadLine();
}
}
public interface IMainService {
void MainMethod();
}
public interface ISecondaryService {
void SecondMethod();
}
public class MainService : IMainService, ISecondaryService {
private int _invokeCount;
public void MainMethod() {
this._invokeCount++;
Console.WriteLine("In MainService: MainMethod ({0})", this._invokeCount);
}
public void SecondMethod() {
this._invokeCount++;
Console.WriteLine("In MainService: SecondMethod ({0})", this._invokeCount);
}
}
public class Bootstrapper {
private static Container _container;
public static void Initialize() {
_container = new Container(x => {
x.For<IMainService>().Singleton().Use<MainService>();
//x.For<ISecondaryService>().Singleton().Use<MainService>();
x.Forward<IMainService, ISecondaryService>();
});
}
public static T GetInstance<T>() {
return _container.GetInstance<T>();
}
}
}
I have developed the demo application of blackberry analytic service but report is not updated in my account my program is..
public class MyApp extends WebtrendsUiApplication {
public static void main(String[] args) {
MyApp theApp = new MyApp();
theApp.enterEventDispatcher();
}
public MyApp() {
WebtrendsConfigurator.LoadConfigFile(new AnalyticsConfig());
WebtrendsDataCollector wtDC = WebtrendsDataCollector.getInstance();
wtDC.Initialize();
pushScreen(new MyScreen());
}
private class AnalyticsConfig extends WebtrendsConfig {
public String wt_dc_app_name() {
return "sample";
}
public String wt_dc_app_version() {
return "1.0.1";
}
public String wt_dc_dcsid() {
return "dcswcrmlj9dv0hgctfq9y6lw8_3w4g"; // Analytics Demo
}
public String wt_dc_debug() {
return "true";
}
public String wt_dc_timezone() {
return "+5";
}
public String wt_dc_url() {
return "http://dc.webtrends.com/v1";
}
public String wt_dc_app_category() {
return "Utilities";
}
public String wt_dc_app_publisher() {
return "abc";
}
}
}
public final class MyScreen extends MainScreen implements FieldChangeListener{
ButtonField b;
public MyScreen() {
b=new ButtonField();
b.setChangeListener(this);
add(b);
}
public boolean onClose() {
try {
WebtrendsDataCollector.getInstance().onApplicationTerminate("Application Terminate", null);
} catch (IllegalWebtrendsParameterValueException err) {
WebtrendsDataCollector.getLog().e(err.getMessage());
}
System.exit(0);
return true;
}
public void fieldChanged(Field field, int context) {
if(field==b){
try {
WebtrendsDataCollector.getInstance().onAdClickEvent("/mainscreen", "Main Screen", "menu", null, "Demo Ad");
} catch (IllegalWebtrendsParameterValueException e1) {
System.out.println(e1.toString());
e1.printStackTrace();
}
}
}
}
please find where is the problem. I have changed only the dcsid in the application .
I know this question is quite old..but I wrote like a group of class u can use.. https://bitbucket.org/folorunsho1/googleanalyticsforblackberry