cannot find symbol on getApplication() on AsyncTask - android-asynctask

I am using AsyncTask and want to use getApplication() to work with class Application.
But gets error on getApplication() cannot find symbol.
my code:
public class splash extends AsyncTask {
protected config app;
public splash(Context context) {
super();
app = ((config) getApplication());
this.context=context;
}
and the class that I want to use:
public class config extends Application
{
public Boolean con=true;
public int status=-1;
public String actNum;
public void onCreate()
{
super.onCreate();
}
}

If you want to get the Application instance, you can initialize a member in onCreate() with it and have it returned by a class method:
public class ApplicationConfig extends Application {
private static ApplicationConfig instance;
public void onCreate() {
super.onCreate();
instance = this;
}
public static ApplicationConfig getConfig() {
return instance;
}
}
Then you can retrieve this instance everywhere via:
ApplicationConfig conf = ApplicationConfig.getConfig();

Related

How to add Global Exception Handling on RouteTemplate

I am looking for a way to add global exception handling on all routes generated by multiple RouteTemplates. I have tried the following way but the onException block is not getting added to the routes.
Can you help me understand what I am doing wrong?
Thanks
public abstract class BaseRouteBuilder extends RouteBuilder {
#Override
public void configure(){
this.onException(IllegalStateException.class)
.log("global onException")
.maximumRedeliveries(2)
.redeliveryDelay(100)
.logStackTrace(true)
.to("direct:retryChannel");
}
}
public static class SampleRouteTemplate extends BaseRouteBuilder {
#Override
public void configure() {
super.configure();
this.routeTemplate("myTemplate")
.templateParameter("parameter1")
.from("direct:start")
.setHeader("parameter1", constant("value1"))
.log("RouteCompleted");
}
}
Try to extract a separate method for route, e.g. configureRoute() and call it in parent class in configure() method. Also make a child class non-static.
public abstract class BaseRouteBuilder extends RouteBuilder {
#Override
public final void configure(){
onException(IllegalStateException.class)
.log("global onException")
.maximumRedeliveries(2)
.redeliveryDelay(100)
.logStackTrace(true)
.to("direct:retryChannel");
configureRoute();
}
public abstract void configureRoute();
}
public class SampleRouteTemplate extends BaseRouteBuilder {
#Override
public void configureRoute() {
this.routeTemplate("myTemplate")
.templateParameter("parameter1")
.from("direct:start")
.setHeader("parameter1", constant("value1"))
.log("RouteCompleted");
}
}
}

Spring Bean Factory Configuration passing input parameter

I'm trying to create a BeanFactory called TaskBeanFactory that I can Autowire into another prototype class that's running on a thread. I want a different instance of a bean returned by the Factory based on a taskName that i want to pass into it but when i start the application i get a null pointer exception because the taskName is null. I had a look at this article but i'm confused about how I should configure the Factory and then pass in the taskName.
The Factory:
import org.springframework.beans.factory.config.AbstractFactoryBean;
import org.springframework.stereotype.Component;
#Data
#Component
#NoArgsConstructor
public class TaskBeanFactory extends AbstractFactoryBean<GenericTask>{
private TaskNameEnum taskName;
public TaskBeanFactory(TaskNameEnum taskName) {
setSingleton(false);
}
#Override
public Class<?> getObjectType() {
return GenericTask.class;
}
#Override
protected GenericTask createInstance() throws Exception {
switch (taskName) {
case FILE_OPERATION:
return new FileTask();
case DATA_OPERATION:
return new DataTask();
default:
return new GenericTask();
}
}
}
The classes used by the Factory:
#Data
public class GenericTask {
private String idTask;
public void executeTask(Work work) {};
}
#Component
#Scope(value="prototype")
public class FileTask extends GenericTask {
#Override
public void executeTask(Work work) {
//some processing
}
}
#Component
#Scope(value="prototype")
public class DataTask extends GenericTask {
#Override
public void executeTask(Work work) {
//some processing
}
}
and the thread that's calling the Factory:
#Slf4j
#Data
#Scope("prototype")
#Component
public class WorkerThread implements Runnable {
#Autowired
private TaskBeanFactory taskBeanFactory;
#Autowired
private DataService dataService;
#Override
public void run() {
//iterate a Map of taskIds from the dataService
taskBeanFactory.setTaskName(TaskNameEnum.valueOf(taskEntry.getKey()));
GenericTask genericTask = taskBeanFactory.getObject();
//expecting genericTask to be of Type FileTask if called with one Key
//or of Type DataTask if called with another
}
}
}

RequestMapping in Sprint-boot VAADIN application

I have a Spring-boot VAADIN application with main classes as follows
Application Class
#SpringBootApplication
public class MySpringBootApplication {
public static void main(String[] args) {
SpringApplication.run(MySpringBootApplication.class, args);
}
}
VAADIN-UI Class
#Theme("valo")
#SpringUI
public class MyAppUI extends UI {
#Autowired
private SpringViewProvider viewProvider;
#Override
protected void init(VaadinRequest vaadinRequest) {
final VerticalLayout mainLayout = new VerticalLayout();
setContent(mainLayout);
Navigator navigator = new Navigator(this, mainLayout);
navigator.addProvider(viewProvider);
}
}
VAADIN-View Class
#SpringView(name = "")
public class MyAppView extends VerticalLayout implements View {
#PostConstruct
void init() {
// Some logic here
}
#Override
public void enter(ViewChangeListener.ViewChangeEvent event) {
// Some logic here
}
}
Currently, the application handles the request in root URL i.e. say http://localhost:8080/. But I want the application to handle requests when a parameter is supplied by http://localhost:8080/<parameter_value>. How can I achieve this?
The logic I have to execute is the same in both cases i.e. I want MyAppView to process both root URL request and the one with a parameter value.
VAADIN's getUI().getPage().getLocation().getPath() method can be used to get the parameter value from the URL. This will give everything from '/' in the URL. Sample code is given below:
VAADIN-View Class
#SpringView(name = "")
public class MyAppView extends VerticalLayout implements View {
#PostConstruct
void init() {
// Some logic here
}
#Override
public void enter(ViewChangeListener.ViewChangeEvent event) {
// Remove spaces and also initial '/' in the path
String uriParamValue = getUI().getPage().getLocation().getPath().trim().substring(1);
// Do processing with uriParamValue
}
}

GWT, how to fire event from widget or composite using EventBus from HandlerManager

I have widget. I would like to fire an event as follow:
fireEvent(new IndicatorStartEvent("Message"));
But it dosn't work.
Normally I use Presenter for this (GWTP), but now I just would like to have regular widget:
public class FileUploadWidget extends Composite {
MaterialFileUploader uploader = new MaterialFileUploader();
#Inject
public FileUploadWidget(String triggerId, EventBus eventBus) {
super();
initWidget(uploader);
Window.alert("TEST Start");
fireEvent(new IndicatorStartEvent("Message"));
}
}
Here is event code:
public class IndicatorStartEvent extends GwtEvent<IndicatorStartEvent.IndicatorHandler> {
public static Type<IndicatorHandler> TYPE = new Type<IndicatorHandler>();
public interface IndicatorHandler extends EventHandler {
void onIndicatorProgressStart(IndicatorStartEvent event);
}
public interface IndicatorHandlers extends HasHandlers {
HandlerRegistration addStartIndicatorHandler(IndicatorHandler handler);
}
private final String message;
public IndicatorStartEvent(final String message) {
this.message = message;
}
public static Type<IndicatorHandler> getType() {
return TYPE;
}
#Override
protected void dispatch(final IndicatorHandler handler) {
handler.onIndicatorProgressStart(this);
}
#Override
public Type<IndicatorHandler> getAssociatedType() {
return TYPE;
}
public String getMessage() {
return this.message;
}
}
This is my app presenter that handle the event:
public class AppPresenter extends TabContainerPresenter<AppPresenter.MyView, AppPresenter.MyProxy> implements AppUiHandlers
, IndicatorStartEvent.IndicatorHandler {
#ProxyStandard
public interface MyProxy extends Proxy<AppPresenter> {}
public interface MyView extends TabView, HasUiHandlers<AppUiHandlers> {}
#Override
protected void onBind() {
super.onBind();
addRegisteredHandler(IndicatorStartEvent.getType(), this);
}
public void onAsyncCallFail(AsyncCallFailEvent event) {
// fireEvent is executed from: com.gwtplatform.mvp.client;PresenterWidget
fireEvent(new IndicatorStartEvent("Firing message"));
}
#Override
public void onIndicatorProgressStart(IndicatorStartEvent event) {
MaterialToast.fireToast("Indicator start: " + event.getMessage());
}
}
If I fire this event from f.e.: AppPresenter (code above), or GwtRESTY filter/callback ass follow:
class ProgressIndicatorFilter implements DispatcherFilter {
private AssistedInjectionFactory factory;
private EventBus eventBus;
#Inject
public ProgressIndicatorFilter(AssistedInjectionFactory factory, EventBus eventBus) {
this.factory = factory;
this.eventBus = eventBus;
}
#Override
public boolean filter(Method method, RequestBuilder builder) {
builder.setCallback(factory.createProgressIndicatorCallback(method));
eventBus.fireEvent(new IndicatorStartEvent("Rest-Gwt Comunication started"));
return true;
}
}
It work as expected. But in those working examples it use com.google.web.bindery.event.shared;EventBus
The firing event doesnt work from widget, where is used:
com.google.gwt.event.shared;HandlerManager;Bus class. This class Bus extends com.google.web.bindery.event.shared.SimpleEventBus which extends the proper EventBus class from com.google.web.bindery.event.shared;EventBus.
So the widget's method fireEvent() use other EventBus.
Can anyone help me with this?
I've red official and this instruction:
http://blog.arcbees.com/2015/04/01/gwt-platform-event-best-practices-revisited/ but no luck so far. Please help.
It does not work because your FileUploadWidget uses it's own EventBus and not GWTP one that is also used in all of your Presenters.
There are two solutions:
Don't use fireEvent(new IndicatorStartEvent("Message")) but use eventBus.fireEvent(new IndicatorStartEvent("Message")) on the injected EventBus inside of your Widget.
Add the IndicatorStartEvent handler to your FileUploadWidget directly instead of using addRegisteredHandler on your Presenter.
I prefer solution 2:
public class FileUploadWidget extends Composite {
MaterialFileUploader uploader = new MaterialFileUploader();
#Inject
public FileUploadWidget(String triggerId) {
super();
initWidget(uploader);
Window.alert("TEST Start");
fireEvent(new IndicatorStartEvent("Message"));
}
}
In the Presenter or to be precise the View which uses your FileUploadWidget, you add a handler directly to the FileUploadWidget:
public class UploadView extends ViewWithUiHandlers<UploadUiHandlers> implements UploadPresenter.MyView,IndicatorStartEvent.IndicatorHandler {
#UiField
FileUploadWidget uploadWidget;
#Inject
public UploadView(final Binder binder) {
widget = binder.createAndBindUi(this);
uploadWidget.addHandler(new IndicatorStartEvent.Handler(),this);
}
public void onIndicatorProgressStart(IndicatorStartEvent event) {
MaterialToast.fireToast("Indicator start: " + event.getMessage());
}
}

Spring-Boot Access object created in main from RequestMapping

I am using spring-boot for implementing a REST server. Inside a function for request mapping, I have to create an object which is heavyweight, so for every REST call I have do it and it is slowing things down. Is it possible to create the object in main and access from the function?
#SpringBootApplication
public class MyClass{
public static void main(String[] args) {
/* I want to initialize the object here */
SpringApplication.run(MyClass.class, args);
}
}
#RestController
public class MyController {
#RequestMapping("/go/to/user/summary")
public Users[] getUsers(#RequestParam(value="length", defaultValue="10") int length) {
/* I want to use the object here */
}
You can create a bean in MyClass and then consume that bean in MyController. Spring will only create a single instance of the bean so you'll avoid the cost of creating it multiple times. Something like this:
#SpringBootApplication
public class MyClass {
public static void main(String[] args) {
SpringApplication.run(MyClass.class, args);
}
#Bean
public Heavyweight heavyweight() {
// Initialize and return heavyweight object here
}
}
#RestController
public class MyController {
private final Heavyweight heavyweight;
#Autowired
public MyController(Heavyweight heavyweight) {
this.heavyweight = heavyweight;
}
#RequestMapping("/go/to/user/summary")
public Users[] getUsers(#RequestParam(value="length", defaultValue="10") int length) {
// Use heavyweight here
this.heavyweight.foo();
// ...
return users;
}
}
I think You can use #Service for this approach. Service class is Singleton so if You create object inside it on startup application then You can use it requests in Your controllers class.
Example service:
#Service
public class MyService{
private MyLargeObject largeObject;
public MyLargeObject set(MyLargeObject largeObject){
this.largeObject = largeObject;
}
public MyLargeObject get(){
return largeObject;
}
}
Example controller:
#RestController
public class MyController{
#Inject
private MyService myService;
#RequestMapping("/go/to/user/summary")
public Users[] getUsers(#RequestParam(value="length", defaultValue="10") int length) {
MyLargeObject o = myService.get();
}
}
EDIT1:
If You want init Your largeObject directly in service You can use #PostConstruct annotation. For example:
#PostConstruct
public void init() {
// initialization Your object here
}

Resources