Tuesday, July 06, 2010

Integration of GWT with Portal and My SQL as Database- GWT with Portal performing CRUD Operation on My-SQL DataBase.



MyGWTPortalSQL:

package myGWTPortalSQL;

import java.io.IOException;

import java.io.PrintWriter;

import javax.portlet.ActionRequest;

import javax.portlet.ActionResponse;

import javax.portlet.GenericPortlet;

import javax.portlet.PortletException;

import javax.portlet.PortletMode;

import javax.portlet.PortletPreferences;

import javax.portlet.PortletSecurityException;

import javax.portlet.PortletURL;

import javax.portlet.RenderRequest;

import javax.portlet.RenderResponse;

import javax.portlet.WindowState;

import myGWTPortalSQL.server.GreetingServiceImpl;

/*

*Refer this site for reference http://xantorohara.blogspot.com/2007/07/portlets-and-gwt.html

*/

public class MyGWTPortalSQL extends GenericPortlet

{

private static final String SERVER_ERROR = "An error occurred while "

+ "attempting to contact the server. Please check your network "

+ "connection and try again.";

//private final GreetingServiceAsync greetingService = GWT.create(GreetingService.class);

protected void doView(RenderRequest renderRequest, RenderResponse renderResponse) throws PortletException, PortletSecurityException, IOException

{

renderResponse.setContentType("text/html");

PrintWriter writer = renderResponse.getWriter();

//System.out.println("value of renderRequest.getContextPath()>>>>>"+renderRequest.getContextPath());

writer.println("");

writer.println("This is just to show the View:");

writer.println("

");

writer.println("

");

writer.println("

");

writer.println("

");

writer.println("

");

writer.println("

");

writer.println("

");

writer.close();

}

protected void doHelp(RenderRequest renderRequest, RenderResponse renderResponse) throws PortletException, PortletSecurityException, IOException

{

renderResponse.setContentType("text/html");

PrintWriter writer = renderResponse.getWriter();

writer.write("Help");

writer.close();

}

protected void doEdit(RenderRequest renderRequest, RenderResponse renderResponse) throws PortletException, PortletSecurityException, IOException

{

//renderResponse.setContentType("text/html");

PrintWriter writer = renderResponse.getWriter();

writer.println("");

/*

PortletURL actionURL = renderResponse.createActionURL();

renderResponse.setContentType(renderRequest.getResponseContentType());


*/

writer.println("This is in Edit Function of MyGWTPortalSQL:");

writer.println("

");

writer.println("

");

writer.println("

");

writer.println("

");

writer.println("

");

writer.println("

");

writer.println("

");

writer.println("Edit");

writer.close();

}

//Added to have the EvenListener in Portal

/*

@Override

public void processAction(ActionRequest request, ActionResponse response)

throws PortletException, PortletSecurityException, IOException {

// TODO Auto-generated method stub

//super.processAction(request, response);

String id = request.getParameter("ID");

String name = request.getParameter("NAME");

//String buttonPressed;

if(request.getParameter("Insert") !=null && request.getParameter("Insert").equals("Insert1") && !request.getParameter("Insert").equals(""))

{

InsertbuttonPress(request,response);

}

if(request.getParameter("Update") !=null && request.getParameter("Update").equals("Update1")&& !request.getParameter("Update").equals(""))

{

UpdatebuttonPress(request,response);

}

if(request.getParameter("Delete") !=null && request.getParameter("Delete").equals("Delete1")&& !request.getParameter("Delete").equals(""))

{

DeletebuttonPress(request,response);

}

//String InsertbuttonPress = request.getParameter("Insert");

//String DeletebuttonPress = request.getParameter("Delete");

try {

PortletPreferences pref = request.getPreferences();

pref.setValue("id", id);

pref.setValue("name", name);

pref.store();

} catch (Exception e) {

throw new PortletException(e.getMessage());

}

response.setPortletMode(PortletMode.VIEW);

response.setWindowState(WindowState.NORMAL);

}

*/

/*

public void InsertbuttonPress(ActionRequest request, ActionResponse response)

{

String idText = request.getParameter("ID");

String nameText = request.getParameter("NAME");

String methodname = "Insert";

GreetingServiceImpl objGreetingServiceImpl = new GreetingServiceImpl();

objGreetingServiceImpl.greetServer(idText,nameText,methodname);

}

public void UpdatebuttonPress(ActionRequest request, ActionResponse response)

{

String idText = request.getParameter("ID");

String nameText = request.getParameter("NAME");

String methodname = "Update";

GreetingServiceImpl objGreetingServiceImpl = new GreetingServiceImpl();

objGreetingServiceImpl.greetServer(idText,nameText,methodname);

}

public void DeletebuttonPress(ActionRequest request, ActionResponse response)

{

String idText = request.getParameter("ID");

String nameText = request.getParameter("NAME");

String methodname = "Delete";

GreetingServiceImpl objGreetingServiceImpl = new GreetingServiceImpl();

objGreetingServiceImpl.greetServer(idText,nameText,methodname);

}

*/

}

MyGWTClientPortalSQL.gwt.xml:

xml version="1.0" encoding="UTF-8"?>

<module rename-to='mygwtportalsql'>

<inherits name='com.google.gwt.user.User'/>

<inherits name='com.google.gwt.user.theme.standard.Standard'/>

<entry-point class='myGWTPortalSQL.client.MyGWTClientPortalSQL'/>

<source path='client'/>

<source path='shared'/>

module>

GreetingService:

package myGWTPortalSQL.client;

import com.google.gwt.core.client.GWT;

import com.google.gwt.user.client.rpc.RemoteService;

import com.google.gwt.user.client.rpc.RemoteServiceRelativePath;

import com.google.gwt.user.client.rpc.ServiceDefTarget;

/**

* The client side stub for the RPC service.

*/

@RemoteServiceRelativePath("MyGWTPortalSQLService")

public interface GreetingService extends RemoteService {

//String greetServer(String name) throws IllegalArgumentException;

String greetServer(String id,String name,String methodName) throws IllegalArgumentException;

/*

Time getTime();

public static class App {

private static myGWTPortalSQL.client.GreetingServiceAsync ourInstance = null;

public static synchronized myGWTPortalSQL.client.GreetingServiceAsync getInstance() {

if (ourInstance == null) {

ourInstance = (myGWTPortalSQL.client.GreetingServiceAsync) GWT.create(GreetingService.class);

((ServiceDefTarget) ourInstance).setServiceEntryPoint(GWT.getModuleBaseURL() + "GreetingService");

}

return ourInstance;

}

}

*/

}

GreetingServiceAsync:

package myGWTPortalSQL.client;

import com.google.gwt.user.client.rpc.AsyncCallback;

/**

* The async counterpart of GreetingService.

*/

public interface GreetingServiceAsync {

//void greetServer(String input, AsyncCallback callback) throws IllegalArgumentException;

public void greetServer(String input1,String input2,String methodName, AsyncCallback callback)

throws IllegalArgumentException;

//void getTime(AsyncCallback callback);

}

MyGWTClientPortalSQL:

package myGWTPortalSQL.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.Timer;

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.HTML;

import com.google.gwt.user.client.ui.Label;

import com.google.gwt.user.client.ui.RootPanel;

import com.google.gwt.user.client.ui.TextBox;

/**

* Entry point classes define onModuleLoad().

*/

public class MyGWTClientPortalSQL implements EntryPoint {

private static final String SERVER_ERROR = "An error occurred while "

+ "attempting to contact the server. Please check your network "

+ "connection and try again.";

private final GreetingServiceAsync greetingService = GWT

.create(GreetingService.class);

/*

public void onModuleLoad() {greetingService.greetServer("Called",

new AsyncCallback() {

public void onFailure(Throwable caught) {

// Show the RPC error message to the user

RootPanel.get().add(new HTML("RPC call failed. :-("));

}

public void onSuccess(String result) {

System.out.println("Vaule of result is:"+result);

RootPanel.get().add(new HTML("RPC call Success:"));

}

});

}

private Timer timer;

private Label label = new Label("Wait...");

private class CallBack implements AsyncCallback

{

public void onFailure(Throwable caught)

{

timer.cancel();

Window.alert(caught.getMessage());

}

public void onSuccess(Object result)

{

label.setText(((Time) result).getTime());

}

}

private CallBack callBack = new CallBack();

*/

public void onModuleLoad()

{

/*

RootPanel.get("uid").add(label);

timer = new Timer()

{

public void run()

{

GreetingService.App.getInstance().getTime(callBack);

}

};

timer.scheduleRepeating(1000);

*/

final Button insertButton = new Button("Insert");

final Button updateButton = new Button("Update");

final Button deleteButton = new Button("Delete");

final Label idLabel = new Label();

idLabel.setText("ID:");

RootPanel.get("idLabelContainer").add(idLabel);

final TextBox idField = new TextBox();

RootPanel.get("idFieldContainer").add(idField);

final Label nameLabel = new Label();

nameLabel.setText("NAME:");

RootPanel.get("nameLabelContainer").add(nameLabel);

final TextBox nameField = new TextBox();

RootPanel.get("nameFieldContainer").add(nameField);

insertButton.addStyleName("Insert");

updateButton.addStyleName("Update");

deleteButton.addStyleName("Delete");

final Label errorLabel = new Label();

RootPanel.get("insertButtonContainer").add(insertButton);

RootPanel.get("updateButtonContainer").add(updateButton);

RootPanel.get("deleteButtonContainer").add(deleteButton);

//RootPanel.get("errorLabelContainer").add(errorLabel);

// Focus the cursor on the name field when the app loads

idField.setFocus(true);

idField.selectAll();

// Create a handler for the sendButton and nameField

class MyHandler implements ClickHandler {

/**

* Fired when the user clicks on the sendButton.

*/

public void onClick(ClickEvent event) {

if(event.getSource().equals(insertButton))

{

insertToMYSQL();

}

else if(event.getSource().equals(updateButton))

{

updateToMYSQL();

}

else if (event.getSource().equals(deleteButton))

{

deleteToMYSQL();

}

}

/**

* Send the name from the nameField to the server and wait for a response.

*/

private void insertToMYSQL() {

String idText = idField.getText();

String nameText = nameField.getText();

String methodname = "Insert";

greetingService.greetServer(idText,nameText,methodname,

new AsyncCallback() {

public void onFailure(Throwable caught) {

// Show the RPC error message to the user

RootPanel.get().add(new HTML("RPC call failed. :-("));

}

public void onSuccess(String result) {

RootPanel.get().add(new HTML("RPC call Success:"));

}

});

}

private void updateToMYSQL() {

String idText = idField.getText();

String nameText = nameField.getText();

String methodname = "Update";

greetingService.greetServer(idText,nameText,methodname,

new AsyncCallback() {

public void onFailure(Throwable caught) {

// Show the RPC error message to the user

RootPanel.get().add(new HTML("RPC call failed. :-("));

}

public void onSuccess(String result) {

RootPanel.get().add(new HTML("RPC call Success:"));

}

});

}

private void deleteToMYSQL() {

String idText = idField.getText();

String nameText = nameField.getText();

String methodname = "Delete";

greetingService.greetServer(idText,nameText,methodname,

new AsyncCallback() {

public void onFailure(Throwable caught) {

// Show the RPC error message to the user

RootPanel.get().add(new HTML("RPC call failed. :-("));

}

public void onSuccess(String result) {

RootPanel.get().add(new HTML("RPC call Success:"));

}

});

}

}

// Add a handler to send the name to the server

MyHandler handler = new MyHandler();

insertButton.addClickHandler(handler);

updateButton.addClickHandler(handler);

deleteButton.addClickHandler(handler);

//nameField.addKeyUpHandler(handler);

}

}

Time:

package myGWTPortalSQL.client;

import com.google.gwt.user.client.rpc.IsSerializable;

public class Time implements IsSerializable

{

private String time;

public String getTime() { return time; }

public Time(String message) { this.time = message; }

public Time() { }

}

GreetingServiceImpl:

package myGWTPortalSQL.server;

import java.sql.Connection;

import java.sql.Date;

import java.sql.DriverManager;

import java.sql.Statement;

import java.text.DateFormat;

import myGWTPortalSQL.client.Time;

import myGWTPortalSQL.client.GreetingService;

import com.google.gwt.user.server.rpc.RemoteServiceServlet;

/**

* The server side implementation of the RPC service.

*/

@SuppressWarnings("serial")

public class GreetingServiceImpl extends RemoteServiceServlet implements GreetingService {

String dbUrl = "jdbc:mysql://localhost/siddhutest_db";

String dbClass = "com.mysql.jdbc.Driver";

/*

public String greetServer(String input) throws IllegalArgumentException {

// Verify that the input is valid.

if (!FieldVerifier.isValidName(input)) {

// If the input is not valid, throw an IllegalArgumentException back to

// the client.

throw new IllegalArgumentException(

"Name must be at least 4 characters long");

}

String serverInfo = getServletContext().getServerInfo();

String userAgent = getThreadLocalRequest().getHeader("User-Agent");

return "Hello, " + input + "!

I am running " + serverInfo

+ ".

It looks like you are using:
" + userAgent;

}

public Time getTime()

{

String out = DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.FULL).format(new Date());

return new Time(out);

}

*/

public String greetServer(String id,String name,String methodName) throws IllegalArgumentException {

if(methodName.equals("Insert"))

{

try {

Class.forName(dbClass).newInstance();

Connection con = DriverManager.getConnection(dbUrl,"root","");

Statement stmt = con.createStatement();

String query = "insert into test_table (id, name) values ("+id+",'"+name+"')";

int i = stmt.executeUpdate(query);

con.close();

//return "success";

} //end try

catch(Exception e) {

e.printStackTrace();

}

}

else if(methodName.equals("Delete"))

{

try {

Class.forName(dbClass).newInstance();

Connection con = DriverManager.getConnection(dbUrl,"root","");

Statement stmt = con.createStatement();

String query = "delete from test_table where id ="+id;

int i = stmt.executeUpdate(query);

con.close();

//return "success";

} //end try

catch(Exception e) {

e.printStackTrace();

}

}else if (methodName.equals("Update"))

{

try {

Class.forName(dbClass).newInstance();

Connection con = DriverManager.getConnection(dbUrl,"root","");

Statement stmt = con.createStatement();

String query = "update test_table set name = '"+name+"' where id ="+id;

int i = stmt.executeUpdate(query);

con.close();

//return "success";

} //end try

catch(Exception e) {

e.printStackTrace();

}

}

return "success";

}

}

default-object.xml:

xml version="1.0" encoding="UTF-8"?>

DOCTYPE deployments PUBLIC

"-//JBoss Portal//DTD Portal Object 2.6//EN"

"http://www.jboss.org/portal/dtd/portal-object_2_6.dtd">

<deployments>

<deployment>

<parent-ref>default.defaultparent-ref>

<if-exists>overwriteif-exists>

<window>

<window-name>

MyGWTPortalSQLWindow

window-name>

<instance-ref>

MyGWTPortalSQLInstance

instance-ref>

<region>centerregion>

<height>1height>

<initial-window-state>maximizedinitial-window-state>

window>

deployment>

deployments>

MyGWTPortalSQL-object.xml:

xml version="1.0" encoding="UTF-8"?>

<deployments>

<deployment>

<if-exists>overwriteif-exists>

<parent-ref>defaultparent-ref>

<page>

<page-name>XLampage-name>

<window>

<window-name>MyGWTPortalSQLWindowwindow-name>

<instance-ref>MyGWTPortalSQLInstanceinstance-ref>

<region>leftregion>

<height>0height>

window>

page>

deployment>

deployments>

portlet.xml:

xml version="1.0" encoding="UTF-8"?>

<portlet-app xmlns="http://java.sun.com/xml/ns/portlet/portlet-app_1_0.xsd"

xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

xsi:schemaLocation="http://java.sun.com/xml/ns/portlet/portlet-app_1_0.xsd

http://java.sun.com/xml/ns/portlet/portlet-app_1_0.xsd"

version="1.0">

<portlet>

<portlet-name>MyGWTPortalSQLportlet-name>

<portlet-class>myGWTPortalSQL.MyGWTPortalSQLportlet-class>

<supports>

<mime-type>text/htmlmime-type>

<portlet-mode>VIEWportlet-mode>

<portlet-mode>EDITportlet-mode>

<portlet-mode>HELPportlet-mode>

supports>

<portlet-info>

<title>MyGWTPortalSQL Portaltitle>

portlet-info>

portlet>

portlet-app>

portlet-instances.xml:

xml version="1.0" standalone="yes"?>

<deployments>

<deployment>

<instance>

<instance-id>MyGWTPortalSQLInstanceinstance-id>

<portlet-ref>MyGWTPortalSQLportlet-ref>

instance>

deployment>

deployments>

web.xml:

xml version="1.0" encoding="UTF-8"?>

DOCTYPE web-app

PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"

"http://java.sun.com/dtd/web-app_2_3.dtd">

<web-app>

<servlet>

<servlet-name>MyGWTPortalSQLServiceservlet-name>

<servlet-class>

myGWTPortalSQL.server.GreetingServiceImpl

servlet-class>

servlet>

<servlet-mapping>

<servlet-name>MyGWTPortalSQLServiceservlet-name>

<url-pattern>/MyGWTPortalSQLServiceurl-pattern>

servlet-mapping>

<servlet-mapping>

<servlet-name>MyGWTPortalSQLServiceservlet-name>

<url-pattern>/mygwtportalsql/MyGWTPortalSQLServiceurl-pattern>

servlet-mapping>

web-app>

MyGWTPortalSQL.html:

<html>

<head>

<title>MyGWTPortaltitle>

head>

<body>

<script type="text/javascript" language="javascript" src="mygwtportalsql/mygwtportalsql.nocache.js">script>

<div id='idLabelContainer'>div>

<div id='idFieldContainer'>div>

<div id='nameLabelContainer'>div>

<div id='nameFieldContainer'>div>

<div id='insertButtonContainer'>div>

<div id='updateButtonContainer'>div>

<div id='deleteButtonContainer'>div>

body>

html>

No comments: