Tuesday, July 06, 2010

Integration of Portal with SQL

TestPortalWithSQL : This example show CRUD Operation using Portal on My-SQL Database. Here in example we had used is JBOSS Portal along with JBOSS Application Server. Portal frame work is more verbose and has very good look and feel aspect for the project. It addition to Look and feel it also helps the user to maintain his/her portal via screen i.e. through GUI rather then hard coding.

TestPortalWithSQL:

package testPortalWithSQL;

import java.io.IOException;

import java.io.PrintWriter;

import java.sql.Connection;

import java.sql.DriverManager;

import java.sql.Statement;

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

import javax.portlet.WindowState;

public class TestPortalWithSQL extends GenericPortlet {

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

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

/* (non-Javadoc)

* @see javax.portlet.GenericPortlet#doView(javax.portlet.RenderRequest, javax.portlet.RenderResponse)

*/

@Override

protected void doView(RenderRequest request, RenderResponse response)

throws PortletException, IOException, UnavailableException {

/*response.setContentType("text/html");

PrintWriter writer = response.getWriter();

writer.write("Hello World!");

writer.close();*/

PortletPreferences pref = request.getPreferences();

String id = pref.getValue("id","");

String name = pref.getValue("name","");

response.setContentType(request.getResponseContentType());

PrintWriter writer = response.getWriter();

writer.write(" value id :" + id +" and name:" + name);

}

/* (non-Javadoc)

* @see javax.portlet.GenericPortlet#doEdit(javax.portlet.RenderRequest, javax.portlet.RenderResponse)

*/

@Override

protected void doEdit(RenderRequest request, RenderResponse response)

throws PortletException, PortletSecurityException, IOException {

// TODO Auto-generated method stub

//super.doEdit(request, response);

PortletURL actionURL = response.createActionURL();

response.setContentType(request.getResponseContentType());

PrintWriter writer = response.getWriter();

//Code to show text field for ID and NAME and three button Insert, Update and Delete.

}

/* (non-Javadoc)

* @see javax.portlet.GenericPortlet#doHelp(javax.portlet.RenderRequest, javax.portlet.RenderResponse)

*/

@Override

protected void doHelp(RenderRequest request, RenderResponse response)

throws PortletException, PortletSecurityException, IOException {

// TODO Auto-generated method stub

//super.doHelp(request, response);

response.setContentType(request.getResponseContentType());

try {

response.setContentType(request.getResponseContentType());

PrintWriter writer = response.getWriter();

writer.write("Pref Portlet Help

");

} catch (IOException e) {

throw new PortletException("PrefPortlet.doHelp exception", e);

}

}

/* (non-Javadoc)

* @see javax.portlet.Portlet#processAction(javax.portlet.ActionRequest, javax.portlet.ActionResponse)

*/

@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 id = request.getParameter("ID");

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

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();

}

}

public void UpdatebuttonPress(ActionRequest request, ActionResponse response)

{

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

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

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();

}

}

public void DeletebuttonPress(ActionRequest request, ActionResponse response)

{

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

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

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();

}

}

}

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>TestPortalWithSQLWindowwindow-name>

<instance-ref>TestPortalWithSQLInstanceinstance-ref>

<region>centerregion>

<height>1height>

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

window>

deployment>

deployments>

portlet.xml:

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

<portlet-app

xmlns="http://java.sun.com/xml/ns/portlet/portlet-app_2_0.xsd"

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

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

version="2.0">

<portlet>

<portlet-name>TestPortalWithSQLportlet-name>

<display-name>TestPortalWithSQLdisplay-name>

<portlet-class>

testPortalWithSQL.TestPortalWithSQL

portlet-class>

<supports>

<mime-type>text/htmlmime-type>

<portlet-mode>VIEWportlet-mode>

<portlet-mode>EDITportlet-mode>

<portlet-mode>HELPportlet-mode>

supports>

<portlet-info>

<title>TestPortalWithSQLtitle>

portlet-info>

portlet>

portlet-app>

portlet-instances.xml:

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

DOCTYPE deployments PUBLIC

"-//JBoss Portal//DTD Portlet Instances 2.6//EN"

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

<deployments>

<deployment>

<instance>

<instance-id>TestPortalWithSQLInstanceinstance-id>

<portlet-ref>TestPortalWithSQLportlet-ref>

instance>

deployment>

deployments>

web.xml:

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

<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">

<display-name>TestPortalWithSQLdisplay-name>

<welcome-file-list>

<welcome-file>index.htmlwelcome-file>

<welcome-file>index.htmwelcome-file>

<welcome-file>index.jspwelcome-file>

<welcome-file>default.htmlwelcome-file>

<welcome-file>default.htmwelcome-file>

<welcome-file>default.jspwelcome-file>

welcome-file-list>

web-app>
Google Assist: Portal with SQL, Simple Portal Example with MySQL, Portal with CRUD Operation,Portal-MySQL,Portal with SQL.

Integration of Portal with SQL using Spring Frame Work




TestPortalSpringMySQL : Shows integration of Portal with Spring Frame Work in addition of performing CRUD operation on My-SQL Db.

LoginFormController:

package Controller;

import javax.portlet.ActionRequest;

import javax.portlet.ActionResponse;

import org.springframework.jdbc.core.JdbcTemplate;

import org.springframework.jdbc.datasource.DriverManagerDataSource;

import org.springframework.validation.BindException;

import org.springframework.web.portlet.mvc.SimpleFormController;

public class LoginFormController extends SimpleFormController {

@Override

public void onSubmitAction(ActionRequest request, ActionResponse response, Object command, BindException errors) throws Exception {

LoginFormData formData = (LoginFormData)command;

//request.getSession().setAttribute("FORM_DATA", formData);

//ModelAndView modelAndView = new ModelAndView(new RedirectView(getSuccessView()));

if (request.getParameter("Insert") != null) {

// delete object

Insert(command, errors);

} else if (request.getParameter("Update") != null) {

// Update object

Update(command, errors);

} else if (request.getParameter("Delete") != null) {

// Delete object

Delete(command, errors);

}

/*

else {

// save object

return new ModelAndView("EnterData");

}*/

}

/*

@Override

public ModelAndView onSubmit(HttpServletRequest request, HttpServletResponse response, Object command, BindException errors) throws Exception {

LoginFormData formData = (LoginFormData)command;

request.getSession().setAttribute("FORM_DATA", formData);

ModelAndView modelAndView = new ModelAndView(new RedirectView(getSuccessView()));

if (request.getParameter("Insert") != null) {

// delete object

return Insert(request, response, command, errors);

} else if (request.getParameter("Update") != null) {

// Update object

return Update(request, response, command, errors);

} else if (request.getParameter("Delete") != null) {

// Delete object

return Delete(request, response, command, errors);

}

else {

// save object

return new ModelAndView("EnterData");

}

}

*/

public void Insert(Object command, BindException errors) throws Exception {

LoginFormData formData = (LoginFormData)command;

//request.getSession().setAttribute("FORM_DATA", formData);

DriverManagerDataSource dataSource = new DriverManagerDataSource();

dataSource.setDriverClassName("com.mysql.jdbc.Driver");

dataSource.setUrl("jdbc:mysql://localhost/siddhutest_db");

dataSource.setUsername("root");

dataSource.setPassword("");

JdbcTemplate template = new JdbcTemplate(dataSource);

template.update("insert into test_table (id, name) values (?, ?)", new Object[] {formData.getId(), formData.getName()});

//ModelAndView modelAndView = new ModelAndView(new RedirectView(getSuccessView()));

//return modelAndView;

}

public void Update(Object command, BindException errors) throws Exception {

LoginFormData formData = (LoginFormData)command;

//request.getSession().setAttribute("FORM_DATA", formData);

DriverManagerDataSource dataSource = new DriverManagerDataSource();

dataSource.setDriverClassName("com.mysql.jdbc.Driver");

dataSource.setUrl("jdbc:mysql://localhost/siddhutest_db");

dataSource.setUsername("root");

dataSource.setPassword("");

JdbcTemplate template = new JdbcTemplate(dataSource);

template.update("update test_table set name = ? where id = ?", new Object[] {formData.getName(),formData.getId()});

//ModelAndView modelAndView = new ModelAndView(new RedirectView(getSuccessView()));

//return modelAndView;

}

public void Delete(Object command, BindException errors) throws Exception {

LoginFormData formData = (LoginFormData)command;

//request.getSession().setAttribute("FORM_DATA", formData);

DriverManagerDataSource dataSource = new DriverManagerDataSource();

dataSource.setDriverClassName("com.mysql.jdbc.Driver");

dataSource.setUrl("jdbc:mysql://localhost/siddhutest_db");

dataSource.setUsername("root");

dataSource.setPassword("");

JdbcTemplate template = new JdbcTemplate(dataSource);

template.update("delete from test_table where id = ?", new Object[] {formData.getId()});

//ModelAndView modelAndView = new ModelAndView(new RedirectView(getSuccessView()));

//return modelAndView;

}

}

LoginFormData:

package Controller;

import java.io.Serializable;

public class LoginFormData implements Serializable{

private String id;

private String name;

public String getId() {

return id;

}

public void setId(String id) {

this.id = id;

}

public String getName() {

return name;

}

public void setName(String name) {

this.name = name;

}

}

TestPortalSpringMySQL:

package testPortalSpringMySQL;

import java.util.HashMap;

import java.util.Map;

import javax.portlet.ActionRequest;

import javax.portlet.ActionResponse;

import javax.portlet.RenderRequest;

import javax.portlet.RenderResponse;

import org.springframework.web.portlet.ModelAndView;

import org.springframework.web.portlet.mvc.Controller;

public class TestPortalSpringMySQL implements Controller {

/* (non-Javadoc)

* @see javax.portlet.GenericPortlet#doView(javax.portlet.RenderRequest, javax.portlet.RenderResponse)

*/

/*

@Override

protected void doView(RenderRequest request, RenderResponse response)

throws PortletException, IOException, UnavailableException {

response.setContentType("text/html");

PrintWriter writer = response.getWriter();

writer.write("Hello World!");

writer.close();

}*/

/**

* action method.

*/

public void handleActionRequest(ActionRequest request,

ActionResponse response) throws Exception {

//-- do nothing the Hello World portlet doesn't receive

//-- action requests.

}

/**

* render method.

*/

public ModelAndView handleRenderRequest(RenderRequest request,

RenderResponse response) throws Exception {

Map model = new HashMap();

model.put("helloWorldMessage", "Hello World HelloWorldController");

return new ModelAndView("helloWorld", model);

}

}

applicationContext.xml:

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

<beans xmlns="http://www.springframework.org/schema/beans"

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

xmlns:context="http://www.springframework.org/schema/context"

xsi:schemaLocation="

http://www.springframework.org/schema/beans

http://www.springframework.org/schema/beans/spring-beans-3.0.xsd

http://www.springframework.org/schema/context

http://www.springframework.org/schema/context/spring-context-3.0.xsd">

beans>

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>TestPortalSpringMySQLWindowwindow-name>

<instance-ref>TestPortalSpringMySQLInstanceinstance-ref>

<region>centerregion>

<height>1height>

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

window>

deployment>

deployments>

EnterData.jsp:

<html>

<head>

<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">

<title>Database Modificationtitle>

head>

<body>

No Action has been done on the Database side please check the DB for more confirmation.

body>

html>

helloWorld.jsp:

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>

<%@ page contentType="text/html" isELIgnored="false" %>

<c:out value="${helloWorldMessage}"/>

LogIn.jsp:

<%@page contentType="text/html"%>

<%@page pageEncoding="UTF-8"%>

<%@ taglib prefix="portlet" uri="http://java.sun.com/portlet_2_0" %>

<html>

<body>

<form method="POST" action="<portlet:actionURL/>">

ID:<input type="text" name="id" /><br/>

Name:<input type="text" name="name" /><br/>

<input type="submit" value="Insert1" name="Insert"/>

<input type="submit" value="Update1" name="Update"/>

<input type="submit" value="Delete1" name="Delete"/>

form>

body>

html>

ResultPage.jsp:

<%@page contentType="text/html" pageEncoding="UTF-8"%>

<html>

<body>

<h1>Data Base is updated Successfully!h1>

body>

html>

portlet.xml:

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

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

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

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

version="2.0">

<portlet>

<portlet-name>TestPortalSpringMySQLportlet-name>

<portlet-class>org.springframework.web.portlet.DispatcherPortletportlet-class>

<supports>

<mime-type>text/htmlmime-type>

<portlet-mode>viewportlet-mode>

<portlet-mode>editportlet-mode>

<portlet-mode>helpportlet-mode>

supports>

<portlet-info>

<title>TestPortalSpringMySQLtitle>

portlet-info>

portlet>

portlet-app>

portlet-instances.xml:

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

DOCTYPE deployments PUBLIC

"-//JBoss Portal//DTD Portlet Instances 2.6//EN"

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

<deployments>

<deployment>

<instance>

<instance-id>TestPortalSpringMySQLInstanceinstance-id>

<portlet-ref>TestPortalSpringMySQLportlet-ref>

instance>

deployment>

deployments>

TestPortalSpringMySQL-portlet.xml:

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

<beans xmlns="http://www.springframework.org/schema/beans"

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

xmlns:context="http://www.springframework.org/schema/context"

xsi:schemaLocation="

http://www.springframework.org/schema/beans

http://www.springframework.org/schema/beans/spring-beans-3.0.xsd

http://www.springframework.org/schema/context

http://www.springframework.org/schema/context/spring-context-3.0.xsd">

<bean id="TestPortalSpringMySQL" class="testPortalSpringMySQL.TestPortalSpringMySQL" />

<bean id="loginFormController" class="Controller.LoginFormController">

<property name="formView" value="LogIn" />

<property name="successView" value="ResultPage" />

<property name="commandName" value="loginData" />

<property name="commandClass" value="Controller.LoginFormData" />

bean>

<bean id="portletModeHandlerMapping"

class="org.springframework.web.portlet.handler.PortletModeHandlerMapping">

<property name="portletModeMap">

<map>

<entry key="view">

<ref bean="TestPortalSpringMySQL" />

entry>

<entry key="edit">

<ref bean="loginFormController" />

entry>

map>

property>

bean>

<bean id="viewResolver"

class="org.springframework.web.servlet.view.InternalResourceViewResolver">

<property name="viewClass"

value="org.springframework.web.servlet.view.InternalResourceView" />

<property name="prefix" value="/WEB-INF/jsp/" />

<property name="suffix" value=".jsp" />

bean>

beans>

web.xml:

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

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

xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"

xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"

id="WebApp_ID" version="2.5">

<display-name>TestPortalSpringMySQLdisplay-name>

<listener>

<listener-class>org.springframework.web.context.ContextLoaderListenerlistener-class>

listener>

<servlet>

<servlet-name>view-servletservlet-name>

<servlet-class>org.springframework.web.servlet.ViewRendererServletservlet-class>

<load-on-startup>1load-on-startup>

servlet>

<servlet-mapping>

<servlet-name>view-servletservlet-name>

<url-pattern>/WEB-INF/servlet/viewurl-pattern>

servlet-mapping>

web-app>