GWT.setUncaughtExceptionHandler() - gwt

Has anyone successfully used the above statement to catch the exception before it goes to the browser as an alert?.
I registered a custom Exception Handler in the first line of my application entry point. But it does not catch the exception as expected.
public void onModuleLoad(){
GWT.setUncaughtExceptionHandler(new MyExceptionHandler());
...
....
}
EDIT
Here are my two classes:
I expect my system.out will print the details of the exception
and exception will be swallowed and should not be sent to browser.
Or Am I wrong?
package mypackage;
import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.core.client.GWT;
public class MyEntryPoint implements EntryPoint {
public void onModuleLoad() {
GWT.setUncaughtExceptionHandler(new ClientExceptionHandler());
startApplication();
}
private void startApplication() {
Integer.parseInt("I_AM_NOT_NUMBER");
}
}
package mypackage;
import com.google.gwt.core.client.GWT;
public class ClientExceptionHandler implements GWT.UncaughtExceptionHandler {
#Override
public void onUncaughtException(Throwable cause) {
System.out.println(cause.getMessage());
}
}

I believe what's happening here is that the current JS event cycle is using the DefaultUncaughtExceptionHandler because that was the handler set at the start of the cycle. You'll need to defer further initialization to the next event cycle, like this:
public void onModuleLoad() {
GWT.setUncaughtExceptionHandler(new ClientExceptionHandler());
Scheduler.get().scheduleDeferred(new ScheduledCommand() {
#Override
public void execute() {
startApplication();
Window.alert("You won't see this");
}
});
}
private void startApplication() {
Integer.parseInt("I_AM_NOT_A_NUMBER");
// or any exception that results from server call
}
Update: And here's the issue that describes why this works, and why it isn't planned to be fixed.

Setting up a default handler can be a tricky proposition some times. I can tell you exactly what is going on. If you get an exception in the onModuleLoad(), the handler will not be called. It is only after the load method is completed that it will ACTUALLY get put into place.

You should try the following:
public void onModuleLoad(){
GWT.setUncaughtExceptionHandler(new UncaughtExceptionHandler() {
onUncaughtException(Throwable t) {
// Do stuff here
}
});
}
and see if that helps.

Silly solution, but it works fine!
before anything add your EntryPoint in your app.gwt.xml
<entry-point class='myPackage.client.MyEntryPoint' />
then;
import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.core.client.GWT;
import com.google.inject.Inject;
import com.google.web.bindery.event.shared.EventBus;
public class MyEntryPoint implements EntryPoint {
private EventBus eventBus;
#Inject
public MyEntryPoint(final EventBus eventBus){
this.eventBus = eventBus;
}
#Override
public void onModuleLoad() {
CustomUncaughtExceptionHandler customUncaughtExceptionHandler = new CustomUncaughtExceptionHandler();
GWT.setUncaughtExceptionHandler(customUncaughtExceptionHandler);
try {
onModuleLoad2();
} catch (RuntimeException ex) {
eventBus.fireEvent(new BusyEvent(false));
customUncaughtExceptionHandler.onUncaughtException(ex);
}
}
private void onModuleLoad2() {
throw new RuntimeException("test");
}
}
and your CustomUncaughtExceptionHandler would be something like:
import com.google.gwt.core.client.GWT.UncaughtExceptionHandler;
import com.google.gwt.event.shared.UmbrellaException;
import com.google.gwt.user.client.Window;
public class CustomUncaughtExceptionHandler implements UncaughtExceptionHandler {
#Override
public void onUncaughtException(Throwable e) {
Throwable exceptionToDisplay = getExceptionToDisplay( e );
Window.alert( exceptionToDisplay.getCause() .getMessage()+" "+ exceptionToDisplay.getStackTrace());
}
private static Throwable getExceptionToDisplay( Throwable throwable ) {
Throwable result = throwable;
if (throwable instanceof UmbrellaException && ((UmbrellaException) throwable).getCauses().size() >= 1) {
result = ((UmbrellaException) throwable).getCauses().iterator().next();
}
return result;
}
}

Related

Issue retrieving a ExecutionContext from a SkipListener

I am trying to retrieve a spring batch ExecutionContext from a SkipListener.
Here is what I have attempted (I rely on annotations instead of interfaces in order to implement my listeners):
import com.xxxx.domain.UserAccount;
import lombok.extern.slf4j.Slf4j;
import org.springframework.batch.core.StepExecution;
import org.springframework.batch.core.annotation.BeforeStep;
import org.springframework.batch.core.annotation.OnSkipInWrite;
import org.springframework.mail.MailSendException;
import org.springframework.stereotype.Component;
#Slf4j
#Component
public class MailSkipListener {
private StepExecution stepExecution;
#BeforeStep
public void saveStepExecution(StepExecution stepExecution) {
this.stepExecution = stepExecution;
}
#OnSkipInWrite
public void logSkippedEmail(UserAccount userAccount, Throwable t) {
if (t instanceof MailSendException) {
MailSendException e = (MailSendException) t;
log.warn("FailedMessages: " + e.getFailedMessages());
}
}
}
However, the logSkippedEmail method is never executed when a MailSendException is raised. When I remove the saveStepExecution method, the logSkippedEmail is again executed in case of a MailSendException.
I register my MailSkipListener as follows:
#Bean
public Step messagesDigestMailingStep(EntityManagerFactory entityManagerFactory) {
return stepBuilderFactory
.get("messagesDigestMailingStep")
.<UserAccount, UserAccount>chunk(5)
...
.writer(itemWriter)
.listener(mailSkipListener)//Here
.build();
}
What I am trying to achieve here is retrieving an ExecutionContext from my SkipListener. How can this be achieved? It seems there's no way to autowire theExecutionContext.
This is quite an old question, but I just struggled with this too.
I ended up registering the skiplistener twice in order for it to work, once as a StepExecutionListener and another as a SkipListener.
It sucks, but it seems to work:
#Bean
public Step messagesDigestMailingStep(EntityManagerFactory entityManagerFactory) {
return stepBuilderFactory
.get("messagesDigestMailingStep")
.<UserAccount, UserAccount>chunk(5)
...
.writer(itemWriter)
.listener((StepExecutionListener) mailSkipListener) // <--- 1
.listener((SkipListener) mailSkipListener) // <--- 2
.build();
}
I know this is an old Question, but I had to deal with this myself, and have put together the following implementation, wherein I made the SkipListener also implement the StepExecutionListener, and adding the same class as both the SkipListener and StepExecutionListener.
#Component
public class PersonImportListener implements SkipListener<Person, Person>, StepExecutionListener {
private final Logger logger = LoggerFactory.getLogger(this.getClass());
private StepExecution stepExecution;
#Override
public void beforeStep(StepExecution stepExecution) {
this.stepExecution = stepExecution;
}
#Override
public ExitStatus afterStep(StepExecution stepExecution) {
return ExitStatus.COMPLETED;
}
#Override
public void onSkipInRead(Throwable throwable) {
logger.warn("Line skipped on read", throwable);
}
#Override
public void onSkipInWrite(Person person, Throwable throwable) {
logger.warn("Bean skipped on write", throwable);
logger.warn("Execution Context" + stepExecution);
}
#Override
public void onSkipInProcess(Person person, Throwable throwable) {
logger.warn("Bean skipped on process", throwable);
}
}
And use this class as a listener for StepExecutionListener and also SkipListener.
#Bean
public Step step1(JdbcBatchItemWriter<Person> writer) {
PersonImportListener listener = new PersonImportListener();
return stepBuilderFactory.get("step1")
.<Person, Person> chunk(10)
.reader(reader())
.faultTolerant()
.skipLimit(10)
.skip(DataIntegrityViolationException.class)
.listener((StepExecutionListener) listener)
.listener((SkipListener) listener)
.processor(processor())
.writer(writer)
.build();
}
You can implement StepExecutionListener on your MailSkipListener to save the context in your stepExecution during the beforeStep() method :
public class MailSkipListener implements StepExecutionListener {
#Override
public void beforeStep(StepExecution stepExecution) {
this.stepExecution = stepExecution;
}

Launch JavaFX application from another class

I need to start a javafx Application from another "container" class and call functions on the Application, but there doesn't seem to be any way of getting hold of a reference to the Application started using the Application.launch() method. Is this possible?
Thanks
Suppose this is our JavaFX class:
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.stage.Stage;
public class OKButton extends Application {
#Override
public void start(Stage stage) {
Button btn = new Button("OK");
Scene scene = new Scene(btn, 200, 250);
stage.setTitle("OK");
stage.setScene(scene);
stage.show();
}
}
Then we may launch it from another class like this:
import javafx.application.Application;
public class Main {
public static void main(String[] args) {
Application.launch(OKButton.class, args);
}
}
I had the same problem as this and got round it using this hack:
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Label;
import javafx.scene.layout.BorderPane;
import javafx.stage.Stage;
import java.util.concurrent.CountDownLatch;
public class StartUpTest extends Application {
public static final CountDownLatch latch = new CountDownLatch(1);
public static StartUpTest startUpTest = null;
public static StartUpTest waitForStartUpTest() {
try {
latch.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
return startUpTest;
}
public static void setStartUpTest(StartUpTest startUpTest0) {
startUpTest = startUpTest0;
latch.countDown();
}
public StartUpTest() {
setStartUpTest(this);
}
public void printSomething() {
System.out.println("You called a method on the application");
}
#Override
public void start(Stage stage) throws Exception {
BorderPane pane = new BorderPane();
Scene scene = new Scene(pane, 500, 500);
stage.setScene(scene);
Label label = new Label("Hello");
pane.setCenter(label);
stage.show();
}
public static void main(String[] args) {
Application.launch(args);
}
}
and then the class you are launching the application from:
public class StartUpStartUpTest {
public static void main(String[] args) {
new Thread() {
#Override
public void run() {
javafx.application.Application.launch(StartUpTest.class);
}
}.start();
StartUpTest startUpTest = StartUpTest.waitForStartUpTest();
startUpTest.printSomething();
}
}
Hope that helps you.
Launch JavaFX in other Class using Button:
class Main extends Application{
public void start(Stage s)throws Exception{
event();
s.show();
}
public void event(){
btn.setOnAction(new EventHandler<ActionEvent>(){
public void handle(ActionEvent ae){
Stage s = new Stage();
new SubClassName().start(s);
}
});
}
public static void main(String[] args) {
launch(args);
}
}
class SubClassName{
public void start(Stage s){
Pane pane = new Pane();
Scene addFrame = new Scene(pane,280,450);
s.setScene(addFrame);
s.show();
}
}
I'm not sure what you're trying to achieve, but note that you can e.g call from another class Application.launch to start the JavaFX Application thread and Platform.exit to stop it.
The above ways of invoking other javafx class from another sometimes work. Struggling to find an ultimate way to do this brought me to the following walk around:
Suppose this is the javafx class that exteds Application we wish to show from a different class, then we should add the following lines
class ClassToCall extends Application{
//Create a class field of type Shape preferably static...
static Stage classStage = new Stage();
#Override
public void start(Stage primaryStage){
// Assign the class's stage object to
// the method's local Stage object:
classStage = primaryStage ;
// Here comes some more code that creates a nice GUI.....
// ......
}
}
And now from the other place in the project, in order to open the window
that the above class creates do the following:
// Suppose we want to do it with a button clicked:
btn1.setOnAction(new EventHandler<ActionEvent>() {
#Override
public void handle(ActionEvent event) {
//create an object of the class you wish to invoke its
//start() method:
ClassToCall ctc = new ClassToCall();
// Then call its start() method in the following way:
ctc.start(ClassToCall.classStage);
}// End handle(ActionEvent event)
});// End anonymous class

Customized itemreader throwing ReaderNotOpenException

I have a customized item reader as shown below
class MyReader implements ItemReader<MyBean>, ItemStream{
SingleItemPeekableItemReader<MyBean> myBeanPeekableReader;
public SingleItemPeekableItemReader<MyBean> getMyBeanPeekableReader() {
return myBeanPeekableReader;
}
public void setMyBeanPeekableReader(
SingleItemPeekableItemReader<MyBean> myBeanPeekableReader) {
this.myBeanPeekableReader = myBeanPeekableReader;
}
#Resource
public void caller(ItemReader<MyBean> myJdbcReader){
myBeanPeekableReader.setDelegate(myJdbcReader);
}
#Override
public void close() throws ItemStreamException {
myBeanPeekableReader.close();
}
#Override
public void open(ExecutionContext arg0) throws ItemStreamException {
myBeanPeekableReader.open(arg0);
}
#Override
public void update(ExecutionContext arg0) throws ItemStreamException {
// TODO Auto-generated method stub
}
Class extending JdbcCursorItemReader:
import javax.annotation.Resource;
import javax.sql.DataSource;
import org.springframework.batch.item.database.JdbcCursorItemReader;
import org.springframework.jdbc.core.PreparedStatementSetter;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Component;
#Component("myJdbcReader")
public class MyJdbcReader extends JdbcCursorItemReader<MyBean> {
private String sql = "Select * from mytable";
MyJdbcReader(){
super.setSql(sql);
}
#Override
#Resource
public void setDataSource(DataSource dataSource){
super.setDataSource(dataSource);
}
#Override
#Resource
public void setRowMapper(RowMapper myRowMapper){
super.setRowMapper(myRowMapper);
}
#Override
#Resource
public void setPreparedStatementSetter(PreparedStatementSetter myPrepSetter){
super.setPreparedStatementSetter(myPrepSetter);
}
}
Even after implementing ItemStream it is throwing exception ReaderNotFound..can someone suggest where I am getting wrong.

Handling mouse event in javafx: how to add listener?

I have a problem with the event handler, this is the code. There is a compile error. NetBeans says: cannot find symbol, method setOnAction.
This is exactly like the example I found at Oracle Doxs.
And then I have another question: how should i use this listener? by creating an object in main?
public class StartButtonController implements Initializable {
#FXML private Button startButton;
#Override
public void initialize(URL location, ResourceBundle resources) {
try {
Parent root = FXMLLoader.load(getClass().getResource("Sample.fxml"));
} catch (IOException ex) {
Logger.getLogger(StartButtonController.class.getName()).log(Level.SEVERE, null, ex);
}
startButton.setOnAction(new EventHandler<ActionEvent>(){
#Override
public void handle(ActionEvent event) {
startButton.setForeground(Color.BLACK);
startButton.setEnabled(false);
}
});
}
Thanks for your help.
import javafx.scene.control.Button.
and
remove the line import java.awt.Button;

GWT - Manage a boolean method in the RPC configuration

I have make my own method in the RPC schema by using the GWT framework. Now, i need to add another method.
So, i wrote this code for each part of RPC :
package org.sinfonet.client;
import com.google.gwt.user.client.rpc.RemoteService;
import com.google.gwt.user.client.rpc.RemoteServiceRelativePath;
#RemoteServiceRelativePath("gwtservice")
public interface GWTService extends RemoteService {
public String checkLogin(String nickname, String password);
public boolean anotherFunction(String nickname);
}
#########################################################
package org.sinfonet.client;
import com.google.gwt.user.client.rpc.AsyncCallback;
public interface GWTServiceAsync {
public void checkLogin(String nickname, String password, AsyncCallback<String> callback);
public void anotherFunction(String nickname, AsyncCallback<java.lang.Boolean> asyncCallback);
}
#########################################################
package org.sinfonet.server;
import com.google.gwt.user.server.rpc.RemoteServiceServlet;
import java.util.ArrayList;
import org.sinfonet.client.GWTService;
import org.sinfonet.mgmt.Configuration;
import org.sinfonet.mgmt.Database;
public class GWTServiceImpl extends RemoteServiceServlet implements GWTService {
public String checkLogin(String nickname, String password) {
Database mydb=Configuration.getDatabase();
mydb.connetti();
// faccio md5 ed escape
String log_check_user=nickname;
String log_check_pass=password;
// controllo che l'utente esista
ArrayList<String[]> db_result=null;
db_result=mydb.selectQuery("SELECT nickname FROM users WHERE nickname='"+log_check_user+"' AND password='"+log_check_pass+"'");
if(db_result.size()!=0) {
return "YES";
}
// sconnessione al database
mydb.disconnetti();
return "NO";
}
public boolean anotherFunction(String nickname) {
// somethings others
return true;
}
}
#########################################################
final AsyncCallback<java.lang.Boolean> callCheckLogin = new AsyncCallback<java.lang.Boolean>() {
public void onSuccess(boolean result) {
if(result) {
designLogout(menu_login_label1.getText());
} else {
menu_err.setText("Username e password non validi");
}
}
};
// Listen for the button clicks
menu_login_button.addClickHandler(new ClickHandler(){
public void onClick(ClickEvent event) {
// Make remote call. Control flow will continue immediately and later
// 'callback' will be invoked when the RPC completes.
getService().anotherFunction(menu_login_input1.getText(), callCheckLogin);
}
});
as you can see, i added the anotherFunction() method (boolean), but Netbeans says to me that i need to implements all abracts method about allCheckLogin, but i wont do it :) How can I fix this problem?
So Netbeans complains about the missing onFailure method, right? If you don't want to implement that method every time, write yourself an abstract class like:
public abstract class BaseAsyncCallback<T> implements AsyncCallback<T> {
#Override
public void onFailure(Throwable caught) {
// Perform generic failure handling
}
}
Then you can change your code into:
final AsyncCallback<java.lang.Boolean> callCheckLogin =
new BaseAsyncCallback<java.lang.Boolean>() {
public void onSuccess(java.lang.Boolean result) {
...
}
};
Now you don't need to implement onFailure anymore, except if you need to perform additional error handling.