Excel File Upload using GWT - gwt

I am not able to upload excel file and parse using GWT 2.7.0. Referred many links Link1 Link2
using above technique and RequestBuilder I couldn't send parsed excel data back to client. Finally implemented GWT RPC technique but having problem load Excel file as GWT cannot implement File.io api on client(Javascript or browser cannot read)
Code:
Client side FileUploading
public class MyFileUpload extends Composite implements Constants{
private ExcelClientServiceImpl excelServiceClient;
private VerticalPanel vPanel;
public MyFileUpload(ExcelClientServiceImpl excelServiceClient){
this.excelServiceClient = excelServiceClient;
this.vPanel = new VerticalPanel();
initWidget(this.vPanel);
}
public void initiateUpload() {
// Create a FormPanel and point it at a service.
final FormPanel form = new FormPanel();
form.setAction("/excelParser");
// Because we're going to add a FileUpload widget, we'll need to set the
// form to use the POST method, and multipart MIME encoding.
form.setEncoding(FormPanel.ENCODING_MULTIPART);
form.setMethod(FormPanel.METHOD_POST);
// Create a panel to hold all of the form widgets.
vPanel = new VerticalPanel();
form.setWidget(vPanel);
// Create a FileUpload widget.
final FileUpload upload = new FileUpload();
//upload.setName("uploadFormElement");
vPanel.add(upload);
System.out.println("File name is : "+upload.getFilename());
// Add a 'submit' button.
vPanel.add(new Button("Submit", new ClickHandler() {
public void onClick(ClickEvent event) {
Window.alert("In Button >>>>>> "+event);
form.submit();
}
}));
// Add an event handler to the form.
form.addSubmitHandler(new FormPanel.SubmitHandler() {
public void onSubmit(SubmitEvent event) {
Window.alert("In Handler >>>>>> "+event);
}
});
form.addSubmitCompleteHandler(new FormPanel.SubmitCompleteHandler() {
public void onSubmitComplete(SubmitCompleteEvent event) {
// When the form submission is successfully completed, this event is
// fired. Assuming the service returned a response of type text/html,
// we can get the result text here (see the FormPanel documentation for
// further explanation).
Window.alert("In complete >>>>>> "+event.getResults());
}
});
RootPanel.get().add(form);
}
}
Client Interface
public interface ExcelClientServiceInt {
void parse(String fileName, String[] lines, StringBuilder integerNumber, StringBuilder floatNumber,
String separator);
void readingExcel();
}
Client Implementation
public class ExcelClientServiceImpl implements ExcelClientServiceInt{
private ExcelServiceIntAsync service;
private MyFileUpload excelUpload;
public ExcelClientServiceImpl(String url){
this.service = GWT.create(ExcelParserService.class);
ServiceDefTarget endpoint = (ServiceDefTarget) this.service;
endpoint.setServiceEntryPoint(url);
this.excelUpload = new MyFileUpload(this);
}
#Override
public void parse(String fileName, String[] lines, StringBuilder integerNumber, StringBuilder floatNumber,
String separator) {
this.service.parse(fileName, lines, integerNumber, floatNumber, separator, new DefaultCallback());
}
#Override
public void readingExcel() {
this.service.readingExcel(null, new DefaultCallback());
}
private class DefaultCallback implements AsyncCallback{
#Override
public void onFailure(Throwable caught) {
System.out.println("Output failed");
}
#Override
public void onSuccess(Object result) {
System.out.println("Output reieved successfully "+result);
}
}
}
Service Interface
#RemoteServiceRelativePath("excelParser")
public interface ExcelServiceInt extends RemoteService{
void parse(String fileName, String[] lines, StringBuilder integerNumber, StringBuilder floatNumber, String separator);
public List readingExcel(String fileName);
}
Async Call Back
public interface ExcelServiceIntAsync{
void parse(String fileName, String[] lines, StringBuilder integerNumber, StringBuilder floatNumber,
String separator, AsyncCallback<Void> callBack);
void readingExcel(String fileName, AsyncCallback<List<String>> callBack);
}
Server side Service
public class ExcelParserService extends RemoteServiceServlet implements ExcelServiceInt{
public void parse(String fileName, String[] lines, StringBuilder integerNumber, StringBuilder floatNumber,
String separator) {
ExcelParser.parse(fileName, lines, integerNumber, floatNumber, separator);
}
public List<String> readingExcel(String fileName) {
return ExcelParser.readingExcel(fileName);
}
}

Related

How can i return hash map from server to client

I have the following method on sever.
public HashMap<String,Set> select()
{
HashMap <String,Set> mp = new HashMap();
//some code
return mp;
}
whenver I am trying to return
<String , Set>
it is going onFailur
but I did this
<String , String >
then its success why this happning
i am using gwt RPC and my client code is
greetingService.select(usertextbox.getText(),new AsyncCallback<HashMap<String,Set>>()
{
public void onFailure(Throwable caught) {
Window.alert("not done");
}
#Override
public void onSuccess(HashMap hm) {
Window.alert("done");
}
Service code is
HashMap<String, Set> select(String user);
service implmentation is
public HashMap<String,Set> select(String user)
{
try {
Session studentDbSession = new Session("localhost",5984);
Database db = studentDbSession.getDatabase("hello");
Document d = db.getDocument("xyz");
JSONArray key = d.names().discard(0).discard(0);
for(int i=0;i<key.size();i++)
{
if(d.containsKey(key.get(i)))
{
k=key.getString(i);
Set aaa=d.getJSONObject(key.getString(i)).entrySet();
System.out.println("----------------");
mp.put(k,aaa);
return mp;
}
Always try to avoid Raw type. Let me share you a sample code. Try it at you end with this sample first or validate all the classes of your code.
Sample code:
RemoteService interface
#RemoteServiceRelativePath("greet")
public interface GreetingService extends RemoteService {
public HashMap<String, Set<String>> select(String input) throws IllegalArgumentException;
}
GreetingServiceAsync interface
public interface GreetingServiceAsync {
void select(String input, AsyncCallback<HashMap<String, Set<String>>> callback);
}
GreetingServiceImpl class
public class GreetingServiceImpl extends RemoteServiceServlet implements GreetingService {
#Override
public HashMap<String, Set<String>> select(String input) throws IllegalArgumentException {
HashMap<String, Set<String>> output = new HashMap<String, Set<String>>();
Set<String> set = new HashSet<String>();
set.add("Hello " + input);
output.put("greeting", set);
return output;
}
}
Entry Point class
public void greetService() {
GreetingServiceAsync greetingService = GWT.create(GreetingService.class);
greetingService.select("Mark", new AsyncCallback<HashMap<String, Set<String>>>() {
#Override
public void onSuccess(HashMap<String, Set<String>> result) {
Window.alert(result.get("greeting").iterator().next());
}
#Override
public void onFailure(Throwable caught) {
Window.alert("fail");
}
});
}
web.xml:
<servlet>
<servlet-name>gwtService</servlet-name>
<servlet-class>com.x.y.z.server.GWTServiceImpl</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>gwtService</servlet-name>
<url-pattern>/moduleName/gwtService</url-pattern>
</servlet-mapping>
output:
What your GWT RPC call HashMap<String, Set> select(String user); does is following:
client-side: serialize String user in order to send it to server
server-side: deserialize RPC call, find implementation of select(String user) and execute it
server-side: serialize return value HashMap<String, Set> in order to return it to client
client-side: deserialize return value and call AsyncCallback
The problem lies in step 3), the serializing of HashMap<String, Set>. The HashMap itself is not the issue; it is the Set which causes the error. When serializing a raw class, GWT usually assumes that the generic type is <Object>. And since Object is not serializable in GWT, an exception is thrown.
Fix: As Braj already mentioned -- give your Set a serializible generic type, e. g. Set<String>, or define your own interface in a package which is accessable from both client- and server-side
public interface UserProperty extends IsSerializable{
}
and change the RPC method like this:
HashMap<String, Set<UserProperty> select(String user);
Have a look at Braj's answer for where to find all the places you need to change after changing your RPC method!

How to use same servlet for RPC and upload File in GWT.

i created a web application where i have to use fileUpload.
i have to send the file and their properties to server . For sending a file i used FormPanel and for properties i used RPC .
public void onModuleLoad() {
final FileServiceEndPoint serviceEndPoint = new FileServiceEndPoint();
new AddDocument();
Button b = new Button("addDocument");
b.addClickHandler(new ClickHandler() {
private Map<String, String> docProperty;
public void onClick(ClickEvent event) {
docProperty =getProperties();
AsyncCallback<String> callback = new AsyncCallback<String>() {
public void onSuccess(String result) {
System.out.println("he ha" +result);
}
public void onFailure(Throwable caught) {
}
};
serviceEndPoint.uploadAttachement(docProperty, callback);
}
});
RootPanel.get().add(b);
}
this new AddDocument(); contains code for uploading a file (formPanel code)
private FormPanel getFormPanel() {
if (uploadForm == null) {
uploadForm = new FormPanel();
uploadForm.setAction(GWT.getHostPageBaseURL() +"TestUploadFileServlet");
uploadForm.setEncoding(FormPanel.ENCODING_MULTIPART);
uploadForm.setMethod(FormPanel.METHOD_POST);
uploadForm.setWidget(getFileUpload());
System.out.println(GWT.getHostPageBaseURL() +"TestUploadFileServlet");
uploadForm.addFormHandler(new FormHandler() {
public void onSubmitComplete(FormSubmitCompleteEvent event) {
AddDocument.this.hide(true);
}
public void onSubmit(FormSubmitEvent event) {
}
});
}
return uploadForm;
}
private Button getAddButton() {
if (addButton == null) {
addButton = new Button("ADD");
addButton.addClickHandler(new ClickHandler() {
public void onClick(ClickEvent event) {
uploadForm.submit();
}
});
addButton.setText("Add");
}
Interface is created for Sending property.
EndPoints:
public class FileServiceEndPoint implements FileServiceAsync{
FileServiceAsync service = (FileServiceAsync)GWT.create(FileService.class);
ServiceDefTarget endpoint = (ServiceDefTarget) service;
public FileServiceEndPoint() {
endpoint.setServiceEntryPoint(GWT.getHostPageBaseURL() + “TestUploadFileServlet”);
}
public void uploadAttachement(Map docProperty,
AsyncCallback callback) {
service.uploadAttachement(docProperty, callback);
}
}
On Server:
public class FileUploadImpl extends RemoteServiceServlet implements FileService {
private static final long serialVersionUID = 1L;
private static final Logger log = Logger.getLogger(FileUploadImpl.class
.getName());
String a;
protected void service(final HttpServletRequest request,HttpServletResponse response)
throws ServletException,IOException {
a=”5″;
System.out.println(“ServletWorking Fine “);
}
public String uploadAttachement(Map docProperty) {
// TODO Auto-generated method stub
return “Checked”;
}
}
When I debug formPanel.submit : the debugger goes in Server and print ServletWorking Fine(this is perfect)
and when i debug the addProperties button it goes to server and print ServletWorking Fine. but It should not go in service method.
the debugger should go in UploadAttachement.
Plz tell how to pass hashMap using same servlet.

GWT - celltable

I'm having problem with a column in my cell table not being populated with anything. Following is my code:
public class CellTableExample implements EntryPoint {
private static class Contact
{
private String address;
private String name;
private String phone="";
public Contact(String name, String address, String phone) {
super();
this.address = address;
this.name = name;
this.phone=getPhoneNumber(name);
}
}
public String getPhoneNumber(String name)
{
String pNum="";
SQLRunnerAsync service = (SQLRunnerAsync) GWT.create(SQLRunner.class);
AsyncCallback<String> callback = new AsyncCallback<String>()
{
#Override
public void onFailure(Throwable caught)
{
}
#Override
public void onSuccess(ArrayList<String[]> result)
{
pNum=reuslt;
}
};
service.findPhoneNum(name,callback);
return pNum;
}
// The list of data to display.
private static List<Contact> CONTACTS = Arrays.asList(
new Contact("John", "123 Fourth Road asdf asdf asdfasdf"),
new Contact("Mary", "222 Lancer Lane")
);
#Override
public void onModuleLoad() {
CellTable<Contact> table = new CellTable<Contact>();
SQLRunnerAsync service = (SQLRunnerAsync) GWT.create(SQLRunner.class);
AsyncCallback<ArrayList<String[]>> callback = new AsyncCallback<ArrayList<String[]>>()
{
#Override
public void onFailure(Throwable caught)
{
}
#Override
public void onSuccess(ArrayList<String[]> result)
{
compFlexTable.setPageSize(result.size());
Contact[] contactArr = new Contact[result.size()];
for(int i=0;i<result.size();i++)
{
String [] temp = result.get(i);
String name=temp[0];//name
String address=temp[1];//address
contactArr[i]=new Component1(name,address);
}
COMPONENT=Arrays.asList(compArray);
//address column
TextColumn<Contact> addressColumn = new TextColumn<Contact>(){
#Override
public String getValue(Contact contact) {
return contact.address;
}
};
//name column
TextColumn<Contact> nameColumn = new TextColumn<Contact>(){
#Override
public String getValue(Contact contact) {
return contact.name;
}
};
//name column
TextColumn<Contact> phoneColumn = new TextColumn<Contact>(){
#Override
public String getValue(Contact contact) {
return contact.phone;
}
};
service.getContactInfo(callback);
// Add the columns.
table.addColumn(nameColumn, "Name");
table.addColumn(addressColumn, "Address");
table.setRowCount(CONTACTS.size(), true);
table.setRowData(0, CONTACTS);
RootPanel.get().add(table);
}
}
So when I'm creating a contact object, another async method is being called to get the phone number for the contact. The table displays fine but the column for the phone number is empty. How do I resolve this? Any ideas/suggestions will be appreciated.. Thanks so much in advance.
You are misunderstanding the order of execution of your program. In getPhoneNumber, you set pNum to "", start an asynchronous request, and then return pNum. pNum is still "" at the end of this process. Later, when your asynchronous request returns, pNum is set to result, but at that point it's too late - your celltable has already been rendered.
Basically, you can't expect any asynchronous calls to complete in time to render your table accurately, once render has been called. All of the data you need must be immediately available before you render, or it won't show up. You can subclass a DataProvider to do these extra retrievals before asking the CellTable to render itself.
use asynchronous data provider as #Riley said
for more reference use the below link ..
http://www.mytechtip.com/2010/11/gwt-celltable-example-using_8168.html

GWT 2.1 Places example without Activities

does anyone have any examples of how to using Places without using activities for history management. I knocked something up quickly and can see the url changing with browser-back and browser-forward clicks but the display doesn't go anywhere.
I'm using a DecoratedTabPanel and have a SelectionHandler that fires off getPlaceController().goTo(place).
Any ideas would be useful.
Here is a simple piece of code that I've made to demonstrate what you expected. It's based on the GWT and MVP Development document (GWT and MVP)
In this example you navigate between two tabs. On selection, a new history item is created (without any activity). As long as you use browser buttons to go back/forward the page will be updated correctly.
I have defined one place, one activity and its view. I've adjusted AppActivityMapper, AppActivityManager and ClientFactory to my needs. The code is lightweight and doesn't need comments to be understood. I've only put some explanations when it was needed, but if it's not clear do not hesitate to ask.
ExampleView.java
public interface ExampleView extends IsWidget {
void selectTab(int index);
}
ExampleViewImpl.java
public class ExampleViewImpl extends Composite implements ExampleView, SelectionHandler<Integer> {
private DecoratedTabPanel panel;
public ExampleViewImpl() {
panel = new DecoratedTabPanel();
initComposite();
initWidget(panel);
}
private void initComposite() {
panel.add(new HTML("Content 1"), "Tab 1");
panel.add(new HTML("Content 2"), "Tab 2");
panel.selectTab(0);
panel.addSelectionHandler(this);
}
#Override
public void selectTab(int index) {
if (index >=0 && index < panel.getWidgetCount()) {
if (index != panel.getTabBar().getSelectedTab()) {
panel.selectTab(index);
}
}
}
#Override
public void onSelection(SelectionEvent<Integer> event) {
// Fire an history event corresponding to the tab selected
switch (event.getSelectedItem()) {
case 0:
History.newItem("thetabplace:1");
break;
case 1:
History.newItem("thetabplace:2");
break;
}
}
}
ClientFactory.java
public class ClientFactory {
private final EventBus eventBus = new SimpleEventBus();
private final PlaceController placeController = new PlaceController(eventBus);
private final ExampleViewImpl example = new ExampleViewImpl();
public EventBus getEventBus() {
return this.eventBus;
}
public PlaceController getPlaceController() {
return this.placeController;
}
public ExampleViewImpl getExampleView() {
return example;
}
}
ExampleActivity.java
public class ExampleActivity extends AbstractActivity {
private ExampleView view;
private ClientFactory factory;
public ExampleActivity(ExamplePlace place, ClientFactory factory) {
// Get the factory reference
this.factory = factory;
// Get the reference to the view
view = this.factory.getExampleView();
// Select the tab corresponding to the token value
if (place.getToken() != null) {
// By default the first tab is selected
if (place.getToken().equals("") || place.getToken().equals("1")) {
view.selectTab(0);
} else if (place.getToken().equals("2")) {
view.selectTab(1);
}
}
}
#Override
public void start(AcceptsOneWidget panel, EventBus eventBus) {
// Attach this view to the application container
panel.setWidget(view);
}
}
ExamplePlace.java
/**
* Just an very basic place
*/
public class ExamplePlace extends Place {
// The token corresponding to an action
private String token;
// This place should use a token to identify a view behavior
public ExamplePlace(String token) {
this.token = token;
}
// Return the current token
public String getToken() {
return token;
}
// Custom prefix to break the default name : ExamplePlace
// So that the history token will be thetabplace:token
// and not any more : ExamplePlace:token
#Prefix(value="thetabplace")
public static class Tokenizer implements PlaceTokenizer<ExamplePlace> {
#Override
public String getToken(ExamplePlace place) {
return place.getToken();
}
#Override
public ExamplePlace getPlace(String token) {
return new ExamplePlace(token);
}
}
}
AppActivityMapper.java
public class AppActivityMapper implements ActivityMapper {
private ClientFactory clientFactory;
public AppActivityMapper(ClientFactory clientFactory) {
super();
this.clientFactory = clientFactory;
}
#Override
public Activity getActivity(Place place) {
if (place instanceof ExamplePlace) {
return new ExampleActivity((ExamplePlace) place, clientFactory);
}
return null;
}
}
AppPlaceHistoryMapper.java
#WithTokenizers({ExamplePlace.Tokenizer.class})
public interface AppPlaceHistoryMapper extends PlaceHistoryMapper
{
}
All together
private Place defaultPlace = new ExamplePlace("1");
private SimplePanel appWidget = new SimplePanel();
public void onModuleLoad() {
ClientFactory clientFactory = new ClientFactory();
EventBus eventBus = clientFactory.getEventBus();
PlaceController placeController = clientFactory.getPlaceController();
// Start ActivityManager for the main widget with our ActivityMapper
ActivityMapper activityMapper = new AppActivityMapper(clientFactory);
ActivityManager activityManager = new ActivityManager(activityMapper, eventBus);
activityManager.setDisplay(appWidget);
// Start PlaceHistoryHandler with our PlaceHistoryMapper
AppPlaceHistoryMapper historyMapper= GWT.create(AppPlaceHistoryMapper.class);
PlaceHistoryHandler historyHandler = new PlaceHistoryHandler(historyMapper);
historyHandler.register(placeController, eventBus, defaultPlace);
RootPanel.get().add(appWidget);
// Goes to the place represented on URL else default place
historyHandler.handleCurrentHistory();
}

GWT confirmation dialog box

I'm trying to create a modal confirmation dialog box. I'd like it to work like Window.confirm(""), where I can just call it, and get a boolean response.
My trouble is I'm not sure how to do it. I'm trying to use MVP in my application. Here is the code I have so far:
public class DialogBoxPresenter implements Presenter {
public interface Display {
Label getDialogText();
Button getAffirmativeButton();
Button getCancelButton();
Widget asWidget();
public void center();
public void hide();
public void setHeader(String text);
}
private Display display;
private String header;
private String dialogText;
private String cancelButtonText;
private String affirmativeButtonText;
protected DialogBoxPresenter() {
}
public DialogBoxPresenter(Display display, String header, String dialogText, String cancelButtonText, String affirmativeButtonText) {
this.display = display;
this.header = header;
this.dialogText = dialogText;
this.cancelButtonText = cancelButtonText;
this.affirmativeButtonText = affirmativeButtonText;
bind();
}
public DialogBoxPresenter(Display display, String header, String dialogText) {
this.display = display;
this.header = header;
this.dialogText = dialogText;
this.cancelButtonText = "Cancel";
this.affirmativeButtonText = "OK";
bind();
}
private void bind() {
this.display.getDialogText().setText(dialogText);
this.display.getAffirmativeButton().setText(affirmativeButtonText);
this.display.getCancelButton().setText(cancelButtonText);
this.display.setHeader(header);
addClickHandlers();
}
private void addClickHandlers() {
this.display.getAffirmativeButton().addClickHandler(new ClickHandler() {
#Override
public void onClick(ClickEvent event) {
doAffirmative();
}
});
this.display.getCancelButton().addClickHandler(new ClickHandler() {
#Override
public void onClick(ClickEvent event) {
doCancel();
}
});
}
private void doAffirmative() {
//do something
display.hide();
}
private void doCancel() {
//do something
display.hide();
}
public void init() {
display.center();
}
#Override
public void go(HasWidgets container) {
container.clear();
container.add(display.asWidget());
}
}
and my view:
public class DialogBoxView extends DialogBox implements DialogBoxPresenter.Display {
private Label dialogText;
private Button affirmativeButton;
private Button cancelButton;
private VerticalPanel container;
public DialogBoxView() {
//init items
dialogText = new Label();
affirmativeButton = new Button();
cancelButton = new Button();
container = new VerticalPanel();
setGlassEnabled(true);
setAnimationEnabled(true);
setModal(false);
init();
}
private void init() {
//add items
container.add(dialogText);
HorizontalPanel hp = new HorizontalPanel();
hp.add(affirmativeButton);
hp.add(cancelButton);
container.add(hp);
this.add(container);
}
#Override
public Widget asWidget() {
return this;
}
#Override
public Label getDialogText() {
return dialogText;
}
#Override
public Button getAffirmativeButton() {
return affirmativeButton;
}
#Override
public Button getCancelButton() {
return cancelButton;
}
#Override
public void setHeader(String text) {
this.setText(text);
}
}
You're not going to be able to have it work in exactly the same way as Window.confirm(). The problem is that all of the javascript in a web page runs in a single thread. You'll notice that as long as a standard confirm dialog is open, the rest of the page goes dead. That's because the one javascript thread is blocked, waiting for confirm() to return. If you were to create a similar method for your dialog, as long as it was waiting for that method to return no user generated events would be processed and so your dialog wouldn't work. I hope that makes sense.
The best you will be able to do is similar to what the GWT library does for RPC calls -- the AsyncCallback interface. You could even reuse that interface yourself, or you might prefer to roll your own:
public interface DialogCallback {
void onOk();
void onCancel();
}
Instead of Window.confirm(String), your method signature will be more like Dialog.confirm(String,DialogCallback). Then your dialog just keeps a reference to the callback that's passed in, and where you have // do something in your code you make calls to onOk and onCancel.
Here is the code I have working if anyone is curious.
public class DialogBoxPresenter implements Presenter {
public interface Display {
Label getDialogText();
Button getAffirmativeButton();
Button getCancelButton();
Widget asWidget();
public void center();
public void hide();
public void setHeader(String text);
}
private Display display;
private String header;
private String dialogText;
private String cancelButtonText;
private String affirmativeButtonText;
private ConfirmDialogCallback confirmCallback;
private AlertDialogCallback alertCallback;
protected DialogBoxPresenter() {
}
public DialogBoxPresenter(Display display, String header, String dialogText, String cancelButtonText, String affirmativeButtonText, ConfirmDialogCallback callback) {
this.display = display;
this.header = header;
this.dialogText = dialogText;
this.cancelButtonText = cancelButtonText;
this.affirmativeButtonText = affirmativeButtonText;
this.confirmCallback = callback;
bind();
}
public DialogBoxPresenter(Display display, String header, String dialogText, String affirmativeButtonText, AlertDialogCallback callback) {
this.display = display;
this.header = header;
this.dialogText = dialogText;
this.affirmativeButtonText = affirmativeButtonText;
this.alertCallback = callback;
this.display.getCancelButton().setVisible(false);
bind();
}
private void bind() {
this.display.getDialogText().setText(dialogText);
this.display.getAffirmativeButton().setText(affirmativeButtonText);
this.display.getCancelButton().setText(cancelButtonText);
this.display.setHeader(header);
addClickHandlers();
}
private void addClickHandlers() {
this.display.getAffirmativeButton().addClickHandler(new ClickHandler() {
#Override
public void onClick(ClickEvent event) {
doAffirmative();
}
});
this.display.getCancelButton().addClickHandler(new ClickHandler() {
#Override
public void onClick(ClickEvent event) {
doCancel();
}
});
}
private void doAffirmative() {
if (confirmCallback != null) {
confirmCallback.onAffirmative();
} else {
alertCallback.onAffirmative();
}
display.hide();
}
private void doCancel() {
confirmCallback.onCancel();
display.hide();
}
public void init() {
display.center();
}
#Override
public void go(HasWidgets container) {
container.clear();
container.add(display.asWidget());
}
}
public class DialogBoxView extends DialogBox implements DialogBoxPresenter.Display {
private Label dialogText;
private Button affirmativeButton;
private Button cancelButton;
private VerticalPanel container;
public DialogBoxView() {
//init items
dialogText = new Label();
affirmativeButton = new Button();
cancelButton = new Button();
container = new VerticalPanel();
setGlassEnabled(true);
setAnimationEnabled(true);
setModal(false);
init();
}
private void init() {
//add items
container.add(dialogText);
HorizontalPanel hp = new HorizontalPanel();
hp.add(affirmativeButton);
hp.add(cancelButton);
container.add(hp);
this.add(container);
}
#Override
public Widget asWidget() {
return this;
}
#Override
public Label getDialogText() {
return dialogText;
}
#Override
public Button getAffirmativeButton() {
return affirmativeButton;
}
#Override
public Button getCancelButton() {
return cancelButton;
}
#Override
public void setHeader(String text) {
this.setText(text);
}
}
public class DialogBoxWidget implements LensooConstant {
private static DialogBoxView view = null;
private static DialogBoxPresenter presenter = null;
public static DialogBoxPresenter confirm(String header, String dialogText, String cancelButtonText, String affirmativeButtonText, ConfirmDialogCallback callback) {
view = new DialogBoxView();
presenter = new DialogBoxPresenter(view, header, dialogText, cancelButtonText, affirmativeButtonText, callback);
presenter.init();
return presenter;
}
public static DialogBoxPresenter confirm(String header, String dialogText, ConfirmDialogCallback callback) {
return DialogBoxWidget.confirm(header, dialogText, constants.cancelButton(), constants.okButton(), callback);
}
public static DialogBoxPresenter alert(String header, String dialogText, String affirmativeButtonText, AlertDialogCallback callback) {
view = new DialogBoxView();
presenter = new DialogBoxPresenter(view, header, dialogText, affirmativeButtonText, callback);
presenter.init();
return presenter;
}
public static DialogBoxPresenter alert(String header, String dialogText, AlertDialogCallback callback) {
return DialogBoxWidget.alert(header, dialogText, constants.okButton(), callback);
}
protected DialogBoxWidget() {
}
}
public interface AlertDialogCallback {
void onAffirmative();
}
public interface ConfirmDialogCallback {
void onAffirmative();
void onCancel();
}