here you can see how to send a message from client.
I have a client HelloServer.java, when i click on the button I want to send message to a server.
package gwt.user.client;
import org.jboss.errai.bus.client.ErraiBus;
import org.jboss.errai.bus.client.api.base.CommandMessage;
import org.jboss.errai.bus.client.api.base.MessageBuilder;
import org.jboss.errai.bus.client.api.messaging.Message;
import org.jboss.errai.bus.client.api.messaging.MessageBus;
import org.jboss.errai.bus.client.api.messaging.MessageCallback;
import org.jboss.errai.bus.client.api.messaging.RequestDispatcher;
import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.user.client.rpc.ServiceDefTarget;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.DialogBox;
import com.google.gwt.user.client.ui.RootPanel;
import com.google.gwt.user.client.ui.VerticalPanel;
public class HelloServer implements EntryPoint{
private MyTable table;
private MessageBus bus = ErraiBus.get();
private RequestDispatcher dispatcher = ErraiBus.getDispatcher();
UserService usrSer;
private RequestDispatcher getDispatcher(){
return this.dispatcher;
}
public void onModuleLoad() {
table = new MyTable(null);
Button button = new Button("Click me");
// We can add style names
button.addStyleName("pc-template-btn");
// or we can set an id on a specific element for styling
VerticalPanel vPanel = new VerticalPanel();
vPanel.setWidth("100%");
vPanel.setHorizontalAlignment(VerticalPanel.ALIGN_CENTER);
vPanel.add(button);
vPanel.add(table);
// add table and button to the RootPanel
RootPanel.get().add(vPanel);
// create the dialog box
final DialogBox dialogBox = new DialogBox();
dialogBox.setText("Welcome to GWT Server Communication!");
dialogBox.setAnimationEnabled(true);
Button closeButton = new Button("close");
VerticalPanel dialogVPanel = new VerticalPanel();
dialogVPanel.setWidth("100%");
dialogVPanel.setHorizontalAlignment(VerticalPanel.ALIGN_CENTER);
dialogVPanel.add(closeButton);
closeButton.addClickHandler(new ClickHandler() {
#Override
public void onClick(ClickEvent event) {
dialogBox.hide();
}
});
// Set the contents of the Widget
dialogBox.setWidget(dialogVPanel);
button.addClickHandler(new ClickHandler() {
#Override
public void onClick(ClickEvent event) {
UserServiceAsync service = (UserServiceAsync) GWT.create(UserService.class);
ServiceDefTarget serviceDef = (ServiceDefTarget) service;
serviceDef.setServiceEntryPoint(GWT.getModuleBaseURL() + "userService");
UserCallback myUserCallback = new UserCallback(table);
MessageBuilder.createMessage()
.toSubject("UserServiceImpl") // (1)
.signalling() // (2)
.noErrorHandling() // (3)
.sendNowWith(getDispatcher()); // (4)
service.getUserList(myUserCallback);
}
});
}
}
UserServiceImpl.java is the server where I want to receive the message in callback method.
package gwt.user.server;
import gwt.user.client.User;
import gwt.user.client.UserService;
import java.util.ArrayList;
import java.util.List;
import org.jboss.errai.bus.client.api.base.CommandMessage;
import org.jboss.errai.bus.client.api.messaging.Message;
import org.jboss.errai.bus.client.api.messaging.MessageCallback;
import org.jboss.errai.bus.server.annotations.Service;
import com.google.gwt.user.server.rpc.RemoteServiceServlet;
#Service
public class UserServiceImpl extends RemoteServiceServlet implements UserService, MessageCallback {
private static final long serialVersionUID = 1L;
private List<User> userList = new ArrayList<User>();
public UserServiceImpl() {
User user = new User();
user.setId("1");
user.setUsername("Peter");
user.setNumberOfHits("15");
userList.add(user);
user = new User();
user.setId("2");
user.setUsername("Hanz");
user.setNumberOfHits("25");
userList.add(user);
}
public User getUser(String id) {
for (Object object : userList) {
if (((User) object).getId().equals(id))
return ((User) object);
}
return null;
}
public List<User> getUserList() {
return userList;
}
#Override
public void callback(Message message) {
System.out.print("Message received");
}
public void callback(CommandMessage message) {
System.out.print("Message received");
}
}
When I click the button I get no subscribers to deliver error message:
org.jboss.errai.bus.client.api.base.NoSubscribersToDeliverTo: no subscribers to deliver to for subject: UserServiceImpl
org.jboss.errai.bus.client.framework.ClientMessageBusImpl.send(ClientMessageBusImpl.java:812)
org.jboss.errai.bus.client.ErraiBus$3.dispatch(ErraiBus.java:171)
org.jboss.errai.bus.client.api.base.CommandMessage.sendNowWith(CommandMessage.java:349)
org.jboss.errai.bus.client.api.base.DefaultMessageBuilder$1.sendNowWith(DefaultMessageBuilder.java:95)
gwt.user.client.HelloServer$2.onClick(HelloServer.java:84)
If I annotate UserServiceImpl.java class with #Service("UserServiceImpl"), it doesn't help and I get the same error.
When I add
bus.subscribe("UserServiceImpl", new UserServiceImpl());
before MessageBuilder.createMessage() in HelloServer.java
I get error message
[ERROR] No source code is available for type gwt.user.server.UserServiceImpl; did you forget to inherit a required module?
Does anybody know how to use messaging between Client and Server in GWT applications or show me a basic example?
Answer is in this thread. I forgot to add ErraiApp.properties file.
Related
I am trying to create a sample CRM for a student project. Currently, I am utilising springboot and vaadin in the STS4. I am using components from their cookbook and the vaading crm tutorial and the their bookstore sample projects from github as templates (i am kind of mixing up the elements of the two, perhaps my lack of understanding is what causes me this trouble). In the form for submission, the following errors are raised in lines 67 and 49: "Syntax error on token ";", { expected after this token" and "Syntax error, insert "}" to complete Block". I am adding my complete form for your inspection, hopefully, someone can explain to me, what is causing the error. Here is "my" code:
package com.vaadin.tutorial.crm.UI.views.list;
import com.vaadin.flow.component.Component;
import com.vaadin.flow.component.ComponentEvent;
import com.vaadin.flow.component.ComponentEventListener;
import com.vaadin.flow.component.HasValue;
import com.vaadin.flow.component.Key;
import com.vaadin.flow.component.button.Button;
import com.vaadin.flow.component.button.ButtonVariant;
import com.vaadin.flow.component.checkbox.CheckboxGroup;
import com.vaadin.flow.component.checkbox.CheckboxGroupVariant;
import com.vaadin.flow.component.combobox.ComboBox;
import com.vaadin.flow.component.formlayout.FormLayout;
import com.vaadin.flow.component.select.Select;
import com.vaadin.flow.component.listbox.ListBox;
import com.vaadin.flow.component.notification.Notification;
import com.vaadin.flow.component.KeyModifier;
import com.vaadin.flow.component.html.Div;
import com.vaadin.flow.component.html.Span;
import com.vaadin.flow.component.orderedlayout.HorizontalLayout;
import com.vaadin.flow.component.orderedlayout.VerticalLayout;
import com.vaadin.flow.component.textfield.EmailField;
import com.vaadin.flow.component.textfield.NumberField;
import com.vaadin.flow.component.textfield.TextField;
import com.vaadin.flow.data.binder.BeanValidationBinder;
import com.vaadin.flow.data.binder.Binder;
import com.vaadin.flow.data.binder.Result;
import com.vaadin.flow.data.binder.ValidationException;
import com.vaadin.flow.data.binder.ValueContext;
import com.vaadin.flow.shared.Registration;
import com.vaadin.tutorial.crm.backend.entity.Disponibilite;
import com.vaadin.tutorial.crm.backend.entity.Livre;
import com.vaadin.tutorial.crm.backend.entity.Livre.Categorie;
import com.vaadin.tutorial.crm.backend.entity.Stock;
import com.vaadin.flow.data.converter.Converter;
import com.vaadin.flow.data.converter.StringToIntegerConverter;
import java.util.List;
import java.util.Set;
public class LivreForm extends FormLayout{
private Livre livre;
private final Select<Disponibilite> disponibilite;
private final TextField stockCount;
TextField titreLivre = new TextField("titreLivre");
TextField description = new TextField("description");
TextField auteur = new TextField("auteur");
TextField refeni = new TextField("refeni");
TextField isbn = new TextField("isbn");
stockCount = new TextField("In stock");
stockCount.addThemeVariants(TextFieldVariant.LUMO_ALIGN_RIGHT);
stockCount.setValueChangeMode(ValueChangeMode.EAGER);
disponibilite = new Select<>();
disponibilite.setLabel("Disponibilite");
disponibilite.setWidth("100%");
disponibilite.setItems(Disponibilite.values());
content.add(disponibilite);
ComboBox<Livre.Categorie> categorie = new ComboBox<>("Categorie");
ListBox<Stock> stock = new ListBox<Stock>();
ComboBox<Livre.Campus> campus = new ComboBox<>("Campus");
Button save = new Button("Save");
Button delete = new Button("Delete");
Button close = new Button("Cancel");
Binder<Livre> binder = new BeanValidationBinder<>(Livre.class);
public LivreForm(List<Stock> stocks) {
addClassName("livre-form");
binder.bindInstanceFields(this);
stock.setItems(stocks);
disponibilite.setItems(Disponibilite.values());
categorie.setItems(Livre.Categorie.values());
campus.setItems(Livre.Campus.values());;
add(titreLivre,
description,
auteur,
refeni,
isbn,
disponibilite,
categorie,
campus,
stock,
createButtonsLayout());
}
public void setLivre(Livre livre) {
this.livre = livre;
binder.readBean(livre);
}
private Component createButtonsLayout() {
save.addThemeVariants(ButtonVariant.LUMO_PRIMARY);
delete.addThemeVariants(ButtonVariant.LUMO_ERROR);
close.addThemeVariants(ButtonVariant.LUMO_TERTIARY);
save.addClickShortcut(Key.ENTER);
close.addClickShortcut(Key.ESCAPE);
save.addClickListener(event -> validateAndSave());
delete.addClickListener(event -> fireEvent(new DeleteEvent(this, livre)));
close.addClickListener(event -> fireEvent(new CloseEvent(this)));
binder.addStatusChangeListener(e -> save.setEnabled(binder.isValid()));
return new HorizontalLayout(save, delete, close);
}
private void validateAndSave() {
try {
binder.writeBean(livre);
fireEvent(new SaveEvent(this, livre));
} catch (ValidationException e) {
e.printStackTrace();
}
}
public static abstract class LivreFormEvent extends ComponentEvent<LivreForm> {
/**
*
*/
private static final long serialVersionUID = -7236023661050023675L;
private Livre livre;
protected LivreFormEvent(LivreForm source,Livre livre) {
super(source, false);
this.livre = livre;
}
public Livre getLivre() {
return livre;
}
}
public static class SaveEvent extends LivreFormEvent {
SaveEvent(LivreForm source, Livre livre) {
super(source, livre);
}
}
public static class DeleteEvent extends LivreFormEvent {
DeleteEvent(LivreForm source, Livre livre) {
super(source, livre);
}
}
public static class CloseEvent extends LivreFormEvent {
CloseEvent(LivreForm source) {
super(source, null);
}
}
public <T extends ComponentEvent<?>> Registration addListener(Class<T> eventType,
ComponentEventListener<T> listener) {
return getEventBus().addListener(eventType, listener);
}
#SuppressWarnings("serial")
private static class StockCountConverter extends StringToIntegerConverter {
public StockCountConverter() {
super(0, "Could not convert value to " + Integer.class.getName()
+ ".");
}
}
}
And this is a screenshot of the errors:
the lines that cause unexplainable errors
= new BeanValidationBinder<>(Livre.class)
Use new Binder<> instead of beanvalidation binder
So I am new to java RMI and making a GUI, but I got the RMI working. Now I have an Interface class called MessageService, a Server class called MessageServer and a Client class called MessageClient. I'd like to make a GUI with a field, where I can write a message, that will then be displayed on the server side. How is this achieved?
EDIT:
I have now done some kind of GUI. I also added a function to the Server. I also edited the Client code, so that when I run it, then it would launch my GUI class.
How would I implement it so I could write text into the input field and when sent, it would be seen on the server?
Here is the code for GUI:
import javafx.application.Application;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.TextField;
import javafx.scene.layout.*;
import javafx.stage.Stage;
import java.rmi.NotBoundException;
import java.rmi.RemoteException;
public class TheGUI extends Application{
Button sendButton;
TextField input;
public static void main(String[] args) throws RemoteException, NotBoundException {
launch(args);
}
#Override
public void start(Stage primaryStage) throws Exception {
primaryStage.setTitle("GUI");
input = new TextField();
sendButton = new Button();
sendButton.setText("send");
AnchorPane layout = new AnchorPane();
HBox hbox = new HBox(5, input, sendButton);
layout.getChildren().addAll(hbox);
AnchorPane.setTopAnchor(hbox, 10d);
EventHandler<ActionEvent> event = new EventHandler<ActionEvent>() {
public void handle(ActionEvent e)
{
String message = input.getText();
input.setText("");
}
};
input.setOnAction(event);
sendButton.setOnAction(event);
Scene scene = new Scene(layout, 300, 250);
primaryStage.setScene(scene);
primaryStage.show();
}
}
This is my Edited Interface:
import java.rmi.Remote;
import java.rmi.RemoteException;
public interface MessageService extends Remote {
public void newMessage (String clientID, String message) throws RemoteException;
}
This is my edited server class:
import java.rmi.RemoteException;
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;
import java.rmi.server.UnicastRemoteObject;
public class MessageServer extends UnicastRemoteObject implements MessageService {
protected MessageServer() throws RemoteException {
super();
}
#Override
public void newMessage(String clientID, String message) throws RemoteException {
System.out.println(clientID + " " + message);
}
public static void main (String[] argv)
{
try
{
Registry registry = LocateRegistry.getRegistry(1099);
MessageServer messageServer = new MessageServer();
registry.rebind("MessageService", messageServer); //register with naming service(bind with registry)
System.out.println("Server is Ready");
}
catch (RemoteException e)
{
System.out.println("ERROR: Could not create registry");
e.printStackTrace();
}
}
}
This is my Edited Client class:
import javafx.application.Application;
import java.rmi.NotBoundException;
import java.rmi.RemoteException;
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;
public class MessageClient
{
public static void main (String[] argv) throws RemoteException, NotBoundException {
try
{
Registry registry = LocateRegistry.getRegistry("127.0.0.1");
MessageService messageService= (MessageService) registry.lookup("MessageService");
Application.launch(TheGUI.class);
}
catch (Exception e)
{
System.out.println ("MessageClient exception: " + e);
}
}
}
You are very close. Your code is almost complete.
RMI means communication between two, separate JVMs. The first JVM is your server process - which you have completed the coding for, hence I will not repeat it here. The second JVM is your client process. You can combine the GUI code with the RMI client code. And the GUI code you posted can be simplified.
Here is my version of your desired GUI to act as your RMI client.
import java.rmi.RemoteException;
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;
import javafx.application.Application;
import javafx.event.ActionEvent;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.TextField;
import javafx.scene.control.Tooltip;
import javafx.scene.layout.HBox;
import javafx.stage.Stage;
public class MessageClientGui extends Application {
private static final String CLIENT_ID = "George";
private static MessageService msgService;
private TextField message;
#Override
public void start(Stage primaryStage) throws Exception {
Label prompt = new Label("Message");
message = new TextField();
Button send = new Button("_Send");
send.setOnAction(this::sendMessage);
send.setTooltip(new Tooltip("Sends message to [RMI] server."));
HBox root = new HBox(5.0D, prompt, message, send);
Scene scene = new Scene(root);
primaryStage.setScene(scene);
primaryStage.show();
}
private void sendMessage(ActionEvent actnEvnt) {
try {
msgService.newMessage(CLIENT_ID, message.getText());
}
catch (RemoteException x) {
x.printStackTrace();
}
}
public static void main(String[] args) {
try {
Registry registry = LocateRegistry.getRegistry("127.0.0.1");
msgService = (MessageService) registry.lookup("MessageService");
launch(args);
}
catch (Exception x) {
x.printStackTrace();
}
}
}
Here is an image of the running client.
In method main(), I initialize the MessageService client and save it in a static class member variable. When the user clicks on the Send button, method sendMessage() is called. In this method the remote method newMessage() is called with the contents of the TextField and some arbitrary client ID, namely George. As a result, in the console (i.e. standard output) of the server JVM, a string is printed that starts with: George
Asterisk 11.4.0
Asterisk-java: 1.0.0.CI-SNAPSHOT
I've try to run this code:
import org.asteriskjava.live.AsteriskChannel;
import org.asteriskjava.live.AsteriskQueue;
import org.asteriskjava.live.AsteriskQueueEntry;
import org.asteriskjava.live.internal.AsteriskAgentImpl;
import org.asteriskjava.live.AsteriskServer;
import org.asteriskjava.live.AsteriskServerListener;
import org.asteriskjava.live.DefaultAsteriskServer;
import org.asteriskjava.live.ManagerCommunicationException;
import org.asteriskjava.live.MeetMeRoom;
import org.asteriskjava.live.MeetMeUser;
import java.beans.PropertyChangeListener;
import java.beans.PropertyChangeEvent;
public class HelloLiveEverything implements AsteriskServerListener, PropertyChangeListener
{
private AsteriskServer asteriskServer;
public HelloLiveEverything()
{
asteriskServer = new DefaultAsteriskServer("localhost", "manager", "password");
}
public void run() throws ManagerCommunicationException
{
// listen for new events
asteriskServer.addAsteriskServerListener(this);
// add property change listeners to existing objects
for (AsteriskChannel asteriskChannel : asteriskServer.getChannels())
{
System.out.println(asteriskChannel);
asteriskChannel.addPropertyChangeListener(this);
}
}
public void onNewAsteriskChannel(AsteriskChannel channel)
{
System.out.println(channel);
channel.addPropertyChangeListener(this);
}
public void onNewMeetMeUser(MeetMeUser user)
{
System.out.println(user);
user.addPropertyChangeListener(this);
}
public void onNewQueueEntry(AsteriskQueueEntry user)
{
System.out.println(user);
user.addPropertyChangeListener(this);
}
public void onNewAgent(AsteriskAgentImpl user)
{
System.out.println(user);
user.addPropertyChangeListener(this);
}
public void propertyChange(PropertyChangeEvent propertyChangeEvent)
{
System.out.println(propertyChangeEvent);
}
public static void main(String[] args) throws Exception
{
HelloLiveEverything helloLiveEverything = new HelloLiveEverything();
helloLiveEverything.run();
while (true) {
}
}
}
When executed, connectios is OK. This code show me current channels but never show me new channels when callers make a calls.
I need to catch the events when new asterisk channels are opening.
What I made wrong?
Thank you
Try This:
Your Class HelloLiveEverything should implement ManagerEventListener
then override the onManagerEvent method
#Override
public void onManagerEvent(ManagerEvent event) {
String event_name = event.getClass().getSimpleName();
if (event_name.equals("DialEvent")) {
DialEvent e = (DialEvent) event;
System.out.println(e.getCallerIdNum());//caller number
System.out.println(e.getDestination());//Called number
//do something here
}
}
edit asterisk manager.conf :
[manager]
secret = password
deny=0.0.0.0/0.0.0.0
permit=209.16.236.73/255.255.255.0; change this ip with one your java app is using permit=127.0.0.1/255.255.255.0
read = system,call,log,verbose,command,agent,user,originate; add full permission
write = system,call,log,verbose,command,agent,user,originate; add full permission
I have built my first GWT app. giving no compilation errors neither run-time errors. However, when the application is loaded into the browser (using Interner Explorer) and I enter username and password field to validate the user, it throws exceptions. Using GWT-RPC method, entire code and interfaces are provided.
I'm using HSQL for database connection(back end).
------------------CODE (CLIENT)
package com.vin.client;
import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.PasswordTextBox;
import com.google.gwt.user.client.ui.RootPanel;
import com.google.gwt.user.client.ui.TextBox;
public class HelloWorld implements EntryPoint{
private UserServiceAsync UserService = (UserServiceAsync) GWT.create(UserService.class);
public void onModuleLoad() {
Button click=new Button("Click Here");
Label name=new Label("Enter Name");
Label passwrd=new Label("Enter Password");
final TextBox t_name=new TextBox();
final PasswordTextBox t_passwrd=new PasswordTextBox();
click.addClickHandler(new ClickHandler() {
public void onClick(ClickEvent ev) {
String temp_user=t_name.getText();
String temp_pass=t_passwrd.getText();
UserService.loginuser(temp_user, temp_pass, new AsyncCallback<String>() {
public void onFailure(Throwable caught) {
Window.alert("Please enter valid details");
}
public void onSuccess(String result) {
Window.alert("Welcome");
// Window.open("http://127.0.0.1:8888/ExWid.html?gwt.codesvr=127.0.0.1:9997", "Dem", null);
}
});
}
});
RootPanel.get().add(name);
RootPanel.get().add(t_name);
RootPanel.get().add(passwrd);
RootPanel.get().add(t_passwrd);
RootPanel.get().add(click);
}
}
-----------------------------CLIENT INTERFACE (1)
package com.vin.client;
import com.google.gwt.user.client.rpc.RemoteService;
public interface UserService extends RemoteService {
public String loginuser(String username, String password);
}
----------------------------CLIENT ASYNC INTERFACE
package com.vin.client;
import com.google.gwt.user.client.rpc.AsyncCallback;
public interface UserServiceAsync {
public void loginuser(String username, String password, AsyncCallback<String> callback);
}
--------------------------IMPLEMENTATION OF CLIENT USERSERVICE (SERVER)...DATABASE CONNECTION
package com.vin.server;
import java.sql.DriverManager;
import java.sql.ResultSet;
import com.google.gwt.dev.generator.ast.Statement;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.server.rpc.RemoteServiceServlet;
import com.vin.client.UserService;
public class UserServiceImpl extends RemoteServiceServlet implements UserService{
private static final long serialVersionUID = 1L;
public String loginuser(String username,String password) {
try {
java.sql.Connection con = null;
Class.forName("org.hsqldb.jdbcDriver");
con = DriverManager.getConnection("jdbc:hsqldb:hsql://localhost/", "SA", "");
Statement st=(Statement) con.createStatement();
ResultSet rs=((java.sql.Statement) st).executeQuery("select username,password from lgfrm");
String user=rs.getString(1);
String pass=rs.getString(2);
if(username.equals(user) && password.equals(pass)) {
Window.alert("success");
}
}
catch (Exception ae) {}
return "success";
}
}
------------------THE EXCEPTION LIST WHILE I'M TRYING TO VALIDATE A USER
15:22:54.583 [ERROR] [helloworld] Uncaught exception escaped
com.google.gwt.event.shared.UmbrellaException: One or more exceptions
caught, see full set in UmbrellaException#getCauses
at com.google.gwt.event.shared.HandlerManager.fireEvent(HandlerManager.java:129)
at com.google.gwt.user.client.ui.Widget.fireEvent(Widget.java:129)
at com.google.gwt.event.dom.client.DomEvent.fireNativeEvent(DomEvent.java:116)
at com.google.gwt.user.client.ui.Widget.onBrowserEvent(Widget.java:177)
at com.google.gwt.user.client.DOM.dispatchEventImpl(DOM.java:1351)
And many more like these.
com.google.gwt.user.client.Window class provides access to the browser window's methods, properties, and events. So you can't use it in Serverside. Better you return String "success" when requirement meets, else return Exception, so that it is caught by onFailure on clientside.
I think you can't use Window.alert on server side (in UserServiceImpl class). There can be many clients and server can't know about what client it directed for.
But i'm not sure that it causes this error.
I'm creating a login application on Eclipse using Google Web Toolkit(GWT). The code checks for the username and password and if its correct, it shows the o/p as welcome. Still after compiling it is giving me errors.I'm sharing both code and the error message. Please help me out.
package com.vin.client;
import java.sql.DriverManager;
import java.sql.ResultSet;
import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.dev.generator.ast.Statement;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.ui.*;
public class HelloWorld implements EntryPoint{
public void onModuleLoad() {
Button click=new Button("Click Here");
Label name=new Label("Enter Name");
Label passwrd=new Label("Enter Password");
final TextBox t_name=new TextBox();
final TextBox t_passwrd=new TextBox();
click.addClickHandler(new ClickHandler() {
public void onClick(ClickEvent ev) {
try {
String temp_user=t_name.getText();
String temp_pass=t_passwrd.getText();
java.sql.Connection con = null;
Class.forName("org.hsqldb.jdbcDriver");
con = DriverManager.getConnection("jdbc:hsqldb:hsql://localhost/", "SA", "");
Statement st=(Statement) con.createStatement();
ResultSet rs=((java.sql.Statement) st).executeQuery("select username,password from lgfrm");
String user=rs.getString(1);
String pass=rs.getString(2);
if(temp_user.equals(user) && temp_pass.equals(pass)) {
Window.alert("Welcome");
}
else {
Window.alert("Please enter valid details");
}
}
catch (Exception ae) {}
}
});
RootPanel.get().add(name);
RootPanel.get().add(t_name);
RootPanel.get().add(passwrd);
RootPanel.get().add(t_passwrd);
RootPanel.get().add(click);
}
}
Error Message is----------
Compiling module com.vin.HelloWorld Exception in thread
"UnitCacheLoader" java.lang.RuntimeException: Unable to read from byte
cache at
com.google.gwt.dev.util.DiskCache.transferFromStream(DiskCache.java:166)
at
com.google.gwt.dev.util.DiskCacheToken.readObject(DiskCacheToken.java:87)
at sun.reflect.GeneratedMethodAccessor19.invoke(Unknown Source)
..............and many more like this....Please help me out
Try something like following for Server side :
UserService.java
#RemoteServiceRelativePath("userService")
public interface UserService extends RemoteService {
String loginUser(String username,String password);
}
UserServiceAsync.java
public interface UserServiceAsync {
void loginUser(String username, String password, AsyncCallback<String> callback);
}
UserServiceImpl.java
public class UserServiceImpl extends RemoteServiceServlet implements UserService {
public String loginUser(String username, String password){
//database interaction
return "result"; //return success or failure depending upon logic
}
}
Follow Communicate with a Server in GWT and the Anatomy of service
For Client Side :
public class HelloWorld implements EntryPoint{
//(1) Create the client proxy.
private UserServiceAsync userService = (UserServiceAsync) GWT.create(UserService.class);
public void onModuleLoad() {
Button click=new Button("Click Here");
Label name=new Label("Enter Name");
Label passwrd=new Label("Enter Password");
final TextBox t_name=new TextBox();
final TextBox t_passwrd=new TextBox();
click.addClickHandler(new ClickHandler() {
public void onClick(ClickEvent ev) {
String temp_user=t_name.getText();
String temp_pass=t_passwrd.getText();
/// (2) Create an asynchronous callback and Make the call
userService.loginUser(temp_user, temp_pass, new AsyncCallback<String>() {
public void onFailure(Throwable caught) {
Window.alert("Please enter valid details");
}
public void onSuccess(String result) {
Window.alert("Welcome");
}
});//end of service call
});//end of clickhandler
RootPanel.get().add(name);
RootPanel.get().add(t_name);
RootPanel.get().add(passwrd);
RootPanel.get().add(t_passwrd);
RootPanel.get().add(click);
}
}
You can not put DB related code in Entry point class, you need to call GWT-RPC on click method.
Actually this EntryPoint class would be compiled by GWT processor and it will create javascript in output which going to run in browser. So there is no justification you can call db in javascript.
GWT-RPC is asynchronous call which code reside in server. Here you can write all business logic, db interactivity etc.
LINK