Add data to the RoutingContext of Vert.x middleware - vert.x

Say I have this middleware class:
public class Middleware implements Handler<RoutingContext> {
public void handle(RoutingContext ctx) {
ctx.set("foo", "bar"); // ctx.set is an imaginary method
ctx.next();
}
}
the ctx.set() method is made-up - it doesn't exist on version 3.6.2.
So how can we set arbitrary info on the context of the request?

There is a put method for that:
public class Middleware implements Handler<RoutingContext> {
public void handle(RoutingContext ctx) {
ctx.put("foo", "bar");
ctx.next();
}
}

Related

#Inject constructor with parameters

I saw a method of using #inject annotation with parameter constructor. I found no use in #module in all parts of the project. I don't understand how this code injects or provides parameters in the constructor.
Can you help me analyze it?
Where is the datamanager provided?
In the whole project, #module + #provide is not used to provide datamanager. I only know that #inject can only annotate the parameterless constructor. I don't know where to instantiate the parameterless datamanager object. Thank you for your help
application:
public class Scallop extends Application {
private ApplicationComponent applicationComponent;
#Override
public void onCreate() {
super.onCreate();
applicationComponent = DaggerApplicationComponent.builder()
.applicationModule(new ApplicationModule(this))
.build();
}
public ApplicationComponent getApplicationComponent() {
return applicationComponent;
}
}
application module:
#Module
public class ApplicationModule {
private Scallop application;
public ApplicationModule(Scallop application) { // 提供类的构造器,传入Applicaton
this.application = application;
}
#Provides
#Singleton
Application provideApplication() {
return application;
}
#Provides
#ApplicationContext
Context provideContext() {
return application;
}
#Provides
#Singleton
Retrofit provideRetrofit() {
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(Constants.BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
.build();
return retrofit;
}
#Provides
#Singleton
GankIOService provideGankIOService(Retrofit retrofit) {
return retrofit.create(GankIOService.class);
}
}
#Singleton
#Component(modules = ApplicationModule.class)
public interface ApplicationComponent {
Application getApplication();
DataManager getDataManager();
}
```
one class:
#Singleton
public class DataManager {
private GankIOService gankIOService;
private PreferencesHelper preferencesHelper;
#Inject
public DataManager(GankIOService gankIOService, PreferencesHelper preferencesHelper) {
this.gankIOService = gankIOService;
this.preferencesHelper = preferencesHelper;
}
}
fragment module:
#FragmentScope
#Component(modules = FragmentModule.class, dependencies = ApplicationComponent.class)
public interface FragmentComponent {
void inject(HomeFragment homeFragment);
void inject(GanHuoPageFragment pageFragment);
void inject(XianDuFragment xianDuFragment);
void inject(XianDuPageFragment xianDuPageFragment);
void inject(PicturesFragment picturesFragment);
void inject(MoreFragment moreFragment);
}
#FragmentScope
#Documented
#Scope
#Retention(value = RetentionPolicy.RUNTIME)
public #interface FragmentScope {
}
```
here Can't understand constructor with parameter is #inject
public class GanHuoPagePresenter extends BasePresenter<GanHuoPageContract.View>
implements GanHuoPageContract.Presenter {
private DataManager dataManager;
private Disposable disposable;
#Inject
public GanHuoPagePresenter(DataManager dataManager) { // here here
this.dataManager = dataManager;
}
#Override
public void detachView() {
super.detachView();
if (disposable != null) {
disposable.dispose();
}
}
#Override
public void getGanHuo(String category, final int page) {
final List<GanHuo> ganHuoList = new ArrayList<>();
Observable<BaseResponse<GanHuo>> observable = dataManager.getGanHuo(category, page);
disposable = observable.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.concatMap(new Function<BaseResponse<GanHuo>, ObservableSource<GanHuo>>() {
#Override
public ObservableSource<GanHuo> apply(#NonNull BaseResponse<GanHuo> ganHuoBaseResponse)
throws Exception {
return Observable.fromIterable(ganHuoBaseResponse.getResults());
}
}).filter(new Predicate<GanHuo>() {
#Override
public boolean test(#NonNull GanHuo ganHuo) throws Exception {
return !ganHuo.getType().equals("福利");
}
}).subscribe(new Consumer<GanHuo>() {
#Override
public void accept(GanHuo ganHuo) throws Exception {
ganHuoList.add(ganHuo);
}
}, new Consumer<Throwable>() {
#Override
public void accept(Throwable throwable) throws Exception {
getView().showError(throwable.getMessage());
}
}, new Action() {
#Override`enter code here`
public void run() throws Exception {
getView().showList(ganHuoList, page);
}
});
}
}
This is how it is used in V in MVP mode:
#Inject GanHuoPagePresenter presenter
That's constructor injection. By marking a constructor with #Inject Dagger knows about the object and can create it when needed. There's no need for modules, e.g. the following is a valid Dagger setup to create some Foo.
public class Foo {
#Inject
public Foo() {}
}
#Component
interface MyComponent {
Foo getFoo();
}
That's not true that #Inject can only annotate the parameterless constructor. From documentation
Injectable constructors are annotated with #Inject and accept zero or more dependencies as arguments.
I found "your" project on Github so let's see where dependencies for GanHuoPagePresenter come from.
#Inject
public GanHuoPagePresenter(DataManager dataManager) {
this.dataManager = dataManager;
}
#Inject
public DataManager(GankIOService gankIOService,PreferencesHelper preferencesHelper){
// gankIOService is provided by ApplicationModule and preferencesHelper uses constructor injection
this.gankIOService = gankIOService;
this.preferencesHelper = preferencesHelper;
}
#Inject
public PreferencesHelper(#ApplicationContext Context context){
// context is provided again by ApplicationModule
sharedPreferences = PreferenceManager.getDefaultSharedPreferences(context);
}

How to change base url endpoint for errai jaxrs proxy?

I' need to call different endpoint located on different server, i try to change value of base url of my rest services.
but i found only this method
RestClient.create(MyService.class, otherServiceBaseUrl,
myCallback,
200).doStaf() ;
Any suggestion to more elegant way for setup the base url for all services in my MyService class ?
I found this solution.
I create a abstract class DinamicCaller.
public abstract class DinamicCaller<T> {
public T call() {
T call = getCaller().call();
((AbstractJaxrsProxy) call).setBaseUrl(getBaseUrl());
return call;
}
public T call(RemoteCallback<?> callback) {
T call = getCaller().call(callback);
((AbstractJaxrsProxy) call).setBaseUrl(getBaseUrl());
return call;
}
public T call(RemoteCallback<?> callback, ErrorCallback<?> errorCallback) {
T call = getCaller().call(callback, errorCallback);
((AbstractJaxrsProxy) call).setBaseUrl(getBaseUrl());
return call;
}
protected abstract Caller<T> getCaller();
protected abstract String getBaseUrl();
}
I create a Concrete Class
public class CallerCORSNegoziService extends DinamicCaller<CORSNegoziService> {
#Inject
NegozioManager negozioManager;
#Inject
Caller<CORSNegoziService> caller;
#Override
protected Caller<CORSNegoziService> getCaller() {
return caller;
}
#Override
protected String getBaseUrl() {
return negozioManager.getNegozio().getUrl();
}
}
On my class I inject the concrete class
#Inject
CallerCORSNegoziService service;
And I use it
#UiHandler("testButton")
public void testButtonClick(ClickEvent event) {
service.call(testCallback, testCallback).findAllNegozi();
}
Is ugly but work.

How to use provider in Errai IOC?

I have a problem with #IocProvider (), annotation does not work.
The code is very similar to https://docs.jboss.org/author/display/ERRAI/Container+Wiring
public interface Test {
String getGreeting();
}
#ApplicationScoped
public class TestImpl implements Test {
public String getGreeting() {
return "Hello:)";
}
}
#IOCProvider
#Singleton
public class TestProvider implements Provider<Test> {
#Override
public Test get() {
return new TestImpl();
}
}
Then I want use DI in my broadcast service (errai-bus).
#Service
public class BroadcastService implements MessageCallback {
#Inject
Test test;
#Inject
MessageBus bus;
#Inject
public BroadcastService(MessageBus bus) {
this.bus = bus;
}
public void callback(Message message) {
MessageBuilder.createMessage()
.toSubject("BroadcastReceiver")
.with("BroadcastText", test.getGreeting()).errorsHandledBy(new ErrorCallback() {
#Override
public boolean error(Message message, Throwable throwable) {
return true;
}
}).sendNowWith(bus);
}
}
I get a error:
1) No implementation for com.gwtplatform.samples.basic.server.Test was bound.
while locating com.gwtplatform.samples.basic.server.Test
for field at com.gwtplatform.samples.basic.server.BroadcastService.test(BroadcastService.java:32)
at org.jboss.errai.bus.server.service.ServiceProcessor$1.configure(ServiceProcessor.java:118)
If I change the code to
#Inject
TestImpl test;
It works, but I need the provider. Do you have some idea?
Because you're trying to use #IOCProvider in server-side code. Errai IOC is completely client-side.

Inject into anonymous inner class (GIN)

I have something like this:
request.findAllProjects().fire(new ExtReceiver<List<ProjectProxy>>() {
#Override
public void onSuccess(List<ProjectProxy> response) {
view.setProjects(response);
}
});
It is anonymous inner class of the abstract class ExtReceiver. The ExtReceiver is for handling the errors with an errorHandler which i want to provide.
public abstract class ExtReceiver<T> extends Receiver<T> {
private ErrorHandler errorHandler;
public ExtReceiver() {
}
#Inject
public void setErrorHandler(ErrorHandler errorHandler)
{
this.errorHandler = errorHandler;
}
#Override
public abstract void onSuccess(T response);
#Override
public void onFailure(ServerFailure error) {
errorHandler.exception(error);
}
#Override
public void onViolation(Set<Violation> errors) {
ValidationUtils.processViolation(errors);
}
}
I understand why this can't work, because i use the new Operator. But how could i do something like this. I want to have that anonymous class and not put it in an own file or something.
How could I inject that errorHandler? Thought about staticInjections, but it looked like this does not work too (Maybe because of the inheritance i create with doing an anonymous class)
In the opposite to normal Guice i don't know an injector.getInstance() call.
For information: That is a requestFactory call
Why don't you put the errorHandler parameter into the constructor of your abstract class instead creating a separate setErrorHandler setter, something like this:
public abstract class ExtReceiver<T> extends Receiver<T> {
private ErrorHandler errorHandler;
#Inject
public ExtReceiver(ErrorHandler errorHandler) {
this.errorHandler = errorHandler;
}
}
Declare the bindings:
public class MyClientModule extends AbstractGinModule {
protected void configure() {
bind(ErrorHandler.class).in(Singleton.class);
}
}
Declare a Ginjector for your ErrorHandler class annotating it with the Module:
#GinModules(MyClientModule.class)
public interface MyErrorHandlerInjector extends Ginjector {
ErrorHandler getErrorHandler();
}
and then use it like this:
MyErrorHandlerGinjector injector = GWT.create(MyErrorHandlerGinjector.class);
ErrorHandler errorHandler = injector.getErrorHandler();
request.findAllProjects().fire(new ExtReceiver<List<ProjectProxy>>(errorHandler) {
#Override
public void onSuccess(List<ProjectProxy> response) {
view.setProjects(response);
}
});
I think this should work.

Add methods to generated WCF client proxy code

I'd like to add one additional method for each service operation in my WCF client proxy code (i.e. the generated class that derives from ClientBase). I have written a Visual Studio extension that has an IOperationContractGenerationExtension implementation, but this interface only seems to expose the ability to modify the service interface, not the ClientBase-derived class.
Is there any way to generate new methods in the proxy client class?
As far as I know, those classes are always partial classes:
public partial class MyWCFServiceClient : ClientBase<IMyWCFService>, IMyWCFService
{
...
}
so you can easily extend them with your own, second file that adds method to the same partial class:
YourOwnFile.cs
public partial class MyWCFServiceClient
{
public void NewMethod1()
{
}
public void NewMethod2()
{
}
}
I got around this by generating a wrapper class for the ClientBase-derived class during the import process. I actually first tried generating an additional partial class with the same name as the client class, but that caused the rest of the code generation to stop working properly.
So my final generated code looks something like:
(generated by the built-in WCF proxy generator):
public interface ServiceReference1
{
IAsyncResult BeginWebMethod1(AsyncCallback callback, object asyncState);
void EndWebMethod1(IAsyncResult result);
IAsyncResult BeginWebMethod2(AsyncCallback callback, object asyncState);
void EndWebMethod2(IAsyncResult result);
// ...
}
public class ServiceReference1Client
{
public event EventHandler<AsyncCompletedEventArgs> WebMethod1Completed;
public event EventHandler<AsyncCompletedEventArgs> WebMethod2Completed;
public void WebMethod1Async() { /* ... */ }
public void WebMethod2Async() { /* ... */ }
// ...
}
(generated by my custom IOperationContractGenerationExtension):
public class ServiceReference1Wrapper
{
private ServiceReference1Client _client;
public ServiceReference1Wrapper(ServiceReference1Client client)
{
_client = client;
}
public IObservable<AsyncCompletedEventArgs> WebMethod1()
{
_client.WebMethod1Async();
// ...
}
public IObservable<AsyncCompletedEventArgs> WebMethod2()
{
_client.WebMethod2Async();
// ...
}
// ...
}
Note: I'm using Silverlight, so that's why everything is async.