Showing posts with label app engine. Show all posts
Showing posts with label app engine. Show all posts

Monday, July 27, 2009

Authenticate user using the google accounts

It's very easy to use the google accounts login system in your website.
First let's create a class to represent the User state in the view.
public class LoginInfo implements Serializable {    private boolean loggedIn = false;   private String loginUrl;   private String logoutUrl;   private String emailAddress;   private String nickname;
(we hided the getters and setters)

Now we must create the service interface that will fill this object:
import com.google.gwt.user.client.rpc.RemoteService; import com.google.gwt.user.client.rpc.RemoteServiceRelativePath;  @RemoteServiceRelativePath("login") public interface LoginService extends RemoteService {   public LoginInfo login(String requestUri); }
the service Async interface:
import com.google.gwt.user.client.rpc.AsyncCallback;  public interface LoginServiceAsync {   public void login(String requestUri, AsyncCallback async); }
and the service implementation:
import com.google.appengine.api.users.User; import com.google.appengine.api.users.UserService; import com.google.appengine.api.users.UserServiceFactory; import com.google.gwt.sample.stockwatcher.client.LoginInfo; import com.google.gwt.sample.stockwatcher.client.LoginService; import com.google.gwt.user.server.rpc.RemoteServiceServlet;  public class LoginServiceImpl extends RemoteServiceServlet implements     LoginService {    public LoginInfo login(String requestUri) {     UserService userService = UserServiceFactory.getUserService();     User user = userService.getCurrentUser();     LoginInfo loginInfo = new LoginInfo();      if (user != null) {       loginInfo.setLoggedIn(true);       loginInfo.setEmailAddress(user.getEmail());       loginInfo.setNickname(user.getNickname());       loginInfo.setLogoutUrl(userService.createLogoutURL(requestUri));     } else {       loginInfo.setLoggedIn(false);       loginInfo.setLoginUrl(userService.createLoginURL(requestUri));     }     return loginInfo;   }  }
Note that to use the UserService of google accounts you need to instantiate a user Object. If the user is already logged in, the call of userService.getCurrentUser(); will return this user. Else it will return null and we will need to redirect the user to login. We create the login URL using the:userService.createLoginURL(requestUri) . It will return the login url for your application. Also to get the logout url you just need to call:userService.createLogoutURL(requestUri) .
Don't forget to configure the LoginServiceImpl in the web.xml file (you can see an example of how to do this here).

To call this service in the view use:
LoginServiceAsync loginService = GWT.create(LoginService.class);     loginService.login(GWT.getHostPageBaseURL(), new AsyncCallback() {       public void onFailure(Throwable error) {       }        public void onSuccess(LoginInfo result) {         loginInfo = result;         if(loginInfo.isLoggedIn()) {           loadUserData();         } else {           loadLogin();         }       }     });
That's it.
You may also save this LoginInfo object to the database, because it does not contain any password or anything like that.

To learn more you may visit the google code tutorial. All the source code of this post was taken from this tutorial.


Thursday, July 16, 2009

How to upload the chat application to google AppEngine

In the last post we finished the chat application. Now we will learn how to upload it to google appengine.

First log in to the appEngine site with your google account.
If this is the first time you log in into appengine it will ask to validate your mobile number. (Please, don't forget to put also the country code and the area code. )
After you validate you will be able to create your first application.
Choose an application ID avaliable and the application title hit the save button.

After all you need to do is open your eclipse project. Select the project properties -> Google -> AppEngine and set the id of the application. You may also set the version of the application(the AppEngine keeps track of the versions, and you can make any version the one default). After just click on the appengine icon (its close to the button you hit to create a google project and the button to compile the gwt). Fillin your email and password, and you're done.
That's all you need to create a chat application and publish it to the internet.

Wednesday, July 15, 2009

How to create a simple chat using GWT and AppEngine - Second Part

Now comes the second part of the tutorial to create a basic chat.

In the last part we created the base of the interface and the base of the server.
Now we will create the Persistence Manager.

Create a new package under the server package named persist.

Now create a Class named PMF. Here is the code:

public final class PMF {


private static final PersistenceManagerFactory pmfInstance = JDOHelper.getPersistenceManagerFactory("transactions-optional");


private PMF(){ }

public static final PersistenceManagerFactory getFactory(){

return pmfInstance;

}

public static final PersistenceManager getManager(){

return getFactory().getPersistenceManager();

}

public static final void saveObject(Object obj){

getManager().makePersistent(obj);

}

}

This class uses the PersistenceManagerFactory to get a PersistenceManager. This manager is responsable for saving, updating and deleting the objects. (Notice that this class is very simple just to explain this example).
Now open the Shout class. We need to set the time that the message was sent.
Add the Date field sentAt to it.

@Persistent

private Date sentAt;

also great the get and set for this field.
Now change the shoutToServer method of the ShoutServiceImpl class. This is the code:

public String shoutToServer(Shout s){

s.setSentAt(new Date());

PMF.saveObject(s);

return s.getMessage();

}

we just set the date to today and save the message.
Now all of our messages been saved. We need now to display them on the browser.
Create a method getAllShouts in the ShoutServiceImpl class. This is the code:

public List getAllShouts() {

Query query = PMF.getManager().newQuery(Shout.class);

query.setOrdering("sentAt ascending");

List resultset = (List)query.execute();

return resultset;

}

Here we get the PersistenceManager and create a new query based on the Shout class.
next we order the results acording to the sentAt field.
This will return all the messages in the server.
Next we need to create a method that will return only messages newer than a date we will pass.
Create a method called get getNewerThan that will receive a Date parameter. This is the code:

public List getNewerThan(Date now) {

PersistenceManager manager = PMF.getManager();

Query q = manager.newQuery(Shout.class);

ArrayList result = new ArrayList();

List resultset = (List)q.execute();

for (Shout a: resultset){

if (a.getSentAt().after(now)){

result.add(a);

}

}

return result;

}

Here we filter the messages to the ones that were sent only after some specific date. We will need this to update the browser with new messages.
Now we need to update the ShoutService and ShoutServiceAsync with this methods too. Here are the codes:
ShoutService:

public List getAllShouts();

public List getNewerThan(Date now);

ShoutServiceAsycn:

void getAllShouts(AsyncCallback> callback);

void getNewerThan(Date now, AsyncCallback> callback);

Now that your interfaces are updated let's change the EntryPoint (The .java).

First create a Date attribute called lastUpdatedAt and a Timer attribute caled t.
Here is the code:

final VerticalPanel messagesPanel = new VerticalPanel();

private Date lastUpdatedAt;

Timer t;

private void checkMessages(){

t.schedule(1000);

}

private void configureTimers(){

t = new Timer(){

@Override

public void run() {

shoutService.getNewerThan(lastUpdatedAt, new AsyncCallback>(){

public void onFailure(Throwable caught) {

checkMessages();

}

public void onSuccess(List result) {

if (result.size() > 0){

for (Shout i: result){

messagesPanel.add(new HTML(i.getMessage()));

}

lastUpdatedAt = result.get(result.size()-1).getSentAt();

}

checkMessages();

};

});

}

};

}

Here we created the Timer and the Date attributes and also changed the scope of the messagesPanel, making it accessible to all methods in the class.
In the checkMessages() method we just start the Timer, and the timer will get all the messages that were sent after the last message received.
Don't forget to remove the messagesPanel from inside the onModuleLoad method.

Finally add this to the end of the onModuleLoad method:

configureTimers();

shoutService.getAllShouts(new AsyncCallback>(){

public void onFailure(Throwable caught) {

checkMessages();

}

public void onSuccess(List result) {

for (Shout i: result){

messagesPanel.add(new HTML(i.getMessage()));

if (i.getSentAt().after(lastUpdatedAt)){

lastUpdatedAt = i.getSentAt();

}

}

checkMessages();

}

});

this will configure the timer object and also get all the messages that were sent before opening the page.
This will also start the Timer, that will loop now forever.

Here we got our chat. Later you may add a name's field to identify who is sending the message if you want.

That's all folks!
Next i will teach how to send this project online to Google AppEngine.

Until there!

Monday, July 13, 2009

Google App Engine

Pessoal,

Neste post eu vou falar rapidamente sobre o google app engine, que já vem configurado para uso junto com o plugin do google para o eclipse.

Bom, primeiramente (e antes mesmo ate de falar sobre real praticidade de usar o app engine como servidor) vem o fato de um usuário google ter direito a até 8 aplicativos dentro do appengine.

Para criar um aplicativo que utiliza o app engine, primeiro é preciso acessar http://appengine.google.com e criar fazer o login pela primeira vez. Logo após já é possível criar a primeira aplicação no site mesmo.

Cada aplicação do app engine tem um ID próprio, que deve ser escolhido durante a criação da aplicação e vai ser a url de acesso para ela (id-da-aplicacao.appspot.com).

Com esse ID, abra o eclipse, clique com o botão direito sobre o projeto, selecione propriedades->Google->App engine.
Coloque o ID de sua aplicação e pronto.
Para publicá-la, clique no logo do app engine (aquela turbina com asas) que fica no topo esquerdo da tela (ao lado do desenho do google e do gwt), que o site sera enviado para o appengine.
Alem disso, é possível especificar (na tela onde coloca o id da aplicação) qual a versão atual da mesma, e assim, manter um histórico no servidor de versões.

Caso você opte por definir uma nova versão para a aplicação, quando você publica-la ela não vai atualizar para a nova versão automaticamente. Será preciso acessar o site appengine.google.com, selecionar a sua aplicação, selecionar a aba lateral "Versions" escolher qual versão do site deixar disponivel e selecionar a opção make default.

Agora que já sabemos como enviar uma aplicação para a nuvem, vamos falar das vantagens e usos do app engine.
  • Uso para hospedar sites estaticos (apenas html). Como possui um limite de 500mb de armazenamento, o app engine é uma opção rápida e barata para colocar no ar um hotsite, site institucional e afins
  • Computação nas nuvens. Uma aplicação no app engine tem acesso a toda a infraestrutura do google de servidores, o que permite uma resposta mais rápida e escalonável da aplicação ao usuário final. Outro ponto interessante é que não precisamos nos preocupar com a infraestrutura por tras do site.
  • BigTables. Acesso a mesma estrutura de armazenamento de dados que o google usa. Isso se traduz num banco de dados rápido e simples de ser utilizado.
Nem tudo são flores porém.
O App Engine é um serviço semi-free. Ele possui uma cota diária de utilização:
  • Tempo de processamento
  • Requests
  • Entrada e saída de dados
  • Pedidos de segurança
  • entre outras...
Porém essas cotas são mais que suficientes para sites médios, e mesmo para sites com muitos acessos, é possível habilitar a opção de pagamento. Onde você paga se exceder uma das cotas. Os valores são relativamente baixos... algo como R$0,20 por hora adicional de processamento e por ai vai...

Realmente vale mais a pena, pois em um dia que o trafego não exceda a cota você nao paga a mais.

Bom, esses são os motivos pelos quais o The Way better está sendo implementado utilizando o App Engine.

Friday, July 10, 2009

Criando um projeto GWT

Agora que sabemos um pouco mais sobre o GWT vamos começar a por a mão na massa.
A maneira mais rápida e fácil de começar a desenvolver com GWT é através do plugin do eclipse do Google. Esse plugin facilita bastante a criação de um projeto que utilize o GWT.
Esse plugin atualmente suporta as versões 3.3 e 3.4 do eclipse. Para instalá-lo siga os procedimentos no site do projeto.

Com o plugin instalado, vá em Arquivo -> Novo -> Other e procure por Web Application Project.

Defina o nome do projeto, o pacote padrão e se você quer usar o GWT e o App Engine.

Ao criar o projeto você ja terá um módulo criado de exemplo. Para ve-lo clique com o botão direito sobre o projeto e depois em Run as -> Web Application

Pronto com isso temos a nossa primeira aplicação com GWT!

No próximo post vamos alterar esse exemplo e criar uma estrutura de pastas e pacotes para melhor organizar o projeto.