Tuesday, October 2, 2012

ExtJs 4 Grid display URL or hyperlink (href)

To display a Web link, basically an URL, all you need to do is write a custom renderer function for the ExtJs Grid column that you want as shown below ...

formatURL: function(value){
        myURL = '';
        if(value !== ''){
            myURL = '<a href="http://' + value + '" target="_blank">' + value +'</a>';
        }
        return myURL;
    }


ExtJs 4 Grid Cell display URL link
ExtJs 4 Grid Cell display URL link
ExtJs 4 Grid Cell display URL link




Web application index.html


<html>
<head>
    <title>ExtJs 4 Grid display Web URL link</title>
 
    <link rel="stylesheet" type="text/css" href="extjs/resources/css/ext-all.css">
 
    <script type="text/javascript" src="extjs/ext-all-debug.js"></script>
    <script type="text/javascript" src="app.js"></script>
 
</head>
<body></body>
</html>

Web application javascript file app.js


Ext.Loader.setConfig({
    enabled: true
    });
 
Ext.application({
    name: 'WEB',
 
    appFolder: 'app',
    
    controllers: [
                  'Websites'
              ],
 
    launch: function() {
        Ext.create('Ext.container.Viewport', {
            layout: 'fit',
            items: [
                {
                    xtype: 'websiteList'
                }
            ]
        });
    }
});

Model javascript file Website.js


Ext.define('WEB.model.Website', {
    extend: 'Ext.data.Model',
    fields: ['name', 'url']
});

Store javascript file Websites.js


Ext.define('WEB.store.Websites', {
    extend: 'Ext.data.Store',
    model: 'WEB.model.Website',
    autoLoad: true,
 
    proxy: {
        type: 'ajax',
        api: {
            read: 'data/sites.json',
        },
        reader: {
            type: 'json',
            root: 'sites',
            successProperty: 'success'
        }
    }
});

View javascript file WebsiteList.js


Ext.define('WEB.view.WebsiteList' ,{
    extend: 'Ext.grid.Panel',
    alias : 'widget.websiteList',
    title : 'My Website Listing',
    store : 'Websites',
    
    initComponent: function() {
        
        this.columns = [
            {header: 'Name',  dataIndex: 'name',  flex: 1},
            {header: 'URL', dataIndex: 'url', flex: 1, renderer: this.formatURL}
        ];
 
        this.callParent(arguments);
    },
 
    formatURL: function(value){
        myURL = '';
        if(value !== ''){
            myURL = '<a href="http://' + value + '" target="_blank">' + value +'</a>';
        }
        return myURL;
    }
});

Controller javascript file Websites.js


Ext.define('WEB.controller.Websites', {
    extend: 'Ext.app.Controller',
    
    stores: ['Websites'],
    models: ['Website'],
    views: ['WebsiteList'],
   
    init: function() {
        this.control({
            'viewport > panel': {
                render: this.onPanelRendered
            }
        });
    },
 
    onPanelRendered: function() {
        console.log('The panel was rendered');
    }
   
});

JSON data file sites.json


{
    success: true,
    sites: [
        {id: 1, name: 'google', url: 'www.google.com'},
        {id: 2, name: 'yahoo',     url: 'www.yahoo.com'}
    ]
}

HTML email using Apache Commons Email API

The Commons Email is built on top of the Java Mail API, which basically simplifies the whole process of sending an email. With the help of HTMLEmail class in commons you can send HTML formatted email. It has all of the capabilities as MultiPartEmail allowing attachments to be easily added and also supports embedded images. In this tutorial we have created a contact US form in JSP so that we can check the capabilities of this very userful API. To send an email we need a SMTP server, from Email address, to Email address and a Subject. If your SMTP server needs authetication then you have to provide the login credentials.

For this example we are using gmail as our SMTP server. To create the HTML content that needs to go in the message body we have taken help of the WYSIWYG editor based on jQuery named jWysiwyg. You can read more about this editor at http://akzhan.github.com/jwysiwyg/. Following jars in your project classpath for this example to work



HTML email using Apache Commons Email API
Source for the JSP - htmlEmail.jsp


























<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
 pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<meta name="robots" content="noindex,nofollow" />
<title>HTML email using Apache Commons API</title>
<link rel="stylesheet" href="/resources/themes/master.css" type="text/css" />
<link rel="stylesheet" href="/resources/themes/jquery.wysiwyg.css" type="text/css" />
<link
 rel="stylesheet" type="text/css" />
<script
 type="text/javascript"></script>
<script
 type="text/javascript"></script>
<script
 type="text/javascript"></script>
<script src="/resources/scripts/mysamplecode.js" type="text/javascript"></script>
<script type="text/javascript" src="/resources/scripts/jquery.wysiwyg.js"></script>
<script type="text/javascript">
$(document).ready(function() {
  
 $("#samplecode").validate({
   rules: {
    mailServer: "required",
    fromName: "required",
    fromEmail: "required",
    toName: "required",
    toEmail: "required",
    subject: "required",
    password: {
     required: function(element) {
         return $.trim($("#userId").val()) != '';
       }
    }
  }
 });
  
 $(function(){
      $('#messageBody').wysiwyg();
      $('#messageBody').wysiwyg('clear');
   });
  
  
});
</script>
</head>
<body>
 <div id="allContent">
 <%@include file="/header.jsp"%>
  <div id="myContent">
   <div>
    <%
     boolean success = false;
     if(request.getAttribute("success") != null){
      success = (Boolean) request.getAttribute("success");
     }
     if (success){
    %>
      <font color="green">
       <b><br/>Thank you! You message has been sent.</b>
       <br/>&nbsp;
      </font>
    <% 
     }
     else {
      if(request.getAttribute("success") != null){
    %>
      
      <font color="red">
       <b><br/>Error! You message was not sent.</b>
       <br/>&nbsp;
      </font>
    <% 
      }
     }
    %>
   </div>
   <form id="samplecode" name="samplecode" method="POST" action="<%= request.getContextPath() %>/SendHTMLEmail">
     <fieldset>
      <legend><b>&nbsp;&nbsp;&nbsp;HTML Email using Apache Commons API&nbsp;&nbsp;&nbsp;</b></legend>
      <table>
      <tr>
       <td>
       <label for="mailServer"> Mail Server Host Name  </label>
       </td>
       <td>
       <input id="mailServer" type="text" name="mailServer" size="50" value="smtp.gmail.com"/>
       </td>
      </tr>
      <tr>
       <td>
       <label for="userId"> Mail Server User Id  </label>
       </td>
       <td>
       <input id="userId" type="text" name="userId" size="30" value=""/>
       <i>(In case your mail server needs Authentication)</i>
       </td>
      </tr>
      <tr>
       <td>
       <label for="password"> Mail Server Password  </label>
       </td>
       <td>
       <input id="password" type="password" name="password" size="30" value=""/>
       <i>(In case your mail server needs Authentication)</i>
       </td>
      </tr>
       
      <tr>
       <td colspan="2">
       &nbsp;
       </td>
      </tr>
      <tr>
       <td>
       <label for="fromName"> Sender's Name  </label>
       </td>
       <td>
       <input id="fromName" type="text" name="fromName" size="30" value=""/>
       </td>
      </tr>
      <tr>
       <td>
       <label for="fromEmail"> Sender's Email Address  </label>
       </td>
       <td>
       <input id="fromEmail" type="text" name="fromEmail" size="50" value=""/>
       </td>
      </tr>
      <tr>
       <td>
       <label for="toName"> Recipient's Name  </label>
       </td>
       <td>
       <input id="toName" type="text" name="toName" size="30" value=""/>
       </td>
      </tr>
      <tr>
       <td>
       <label for="toEmail"> Recipient's Email Address  </label>
       </td>
       <td>
       <input id="toEmail" type="text" name="toEmail" size="50" value=""/>
       </td>
      </tr>
      <tr>
       <td colspan="2">
       &nbsp;
       </td>
      </tr>
      <tr>
       <td>
       <label for="subject"> Subject  </label>
       </td>
       <td>
       <input id="subject" type="text" name="subject" size="50" value=""/>
       </td>
      </tr>
      <tr>
       <td class="formText" >
        <label for="messageBody"> Message </label>
       </td>
       <td>
        <textarea id="messageBody" name="messageBody" rows="10" cols="100" maxlength="1000"></textarea>
       </td>
      </tr>
      <tr>
       <td class="formText" >
        &nbsp;
       </td>
       <td>
        <input id="sendEmail" type="submit" value="Send my Email" />
       </td>
      </tr>
      </table>
     </fieldset>
   </form>
  </div>
 </div>
 <%@include file="/footer.jsp"%>
 <div></div>
</body>
</html>

Source for the Java Servlet - SendHTMLEmail.java


package com.as400samplecode;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.mail.DefaultAuthenticator;
import org.apache.commons.mail.EmailException;
import org.apache.commons.mail.HtmlEmail;
public class SendHTMLEmail extends HttpServlet {
 private static final long serialVersionUID = 1L;
        
    public SendHTMLEmail() {
        super();
    }
 protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
  doPost(request, response);
 }
 protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
  
  String mailServer = request.getParameter("mailServer").trim();
  String userId = request.getParameter("userId").trim();
  String password = request.getParameter("password").trim();
   
  String fromName = request.getParameter("fromName").trim();
  String fromEmail = request.getParameter("fromEmail").trim();
  String toName = request.getParameter("toName").trim();
  String toEmail = request.getParameter("toEmail").trim();
   
  String subject = request.getParameter("subject").trim();
  String messageBody = request.getParameter("messageBody").trim();
   
  StringBuilder sb = new StringBuilder();
  sb.append("<html>");
  sb.append("<body>");
  sb.append("<table>");
   
  sb.append(messageBody);
     
  sb.append("</table>");
  sb.append("</body>");
  sb.append("</html>");
   
  try {
    
   // Sending HTML formatted email
   HtmlEmail htmlEmail = new HtmlEmail();
    
   // set the address of the outgoing SMTP server that will be used to send the email
   htmlEmail.setHostName(mailServer);
   // set to true if you want to debug
   htmlEmail.setDebug(true);
   // if the SMTP server needs authentication
   if(!userId.trim().equalsIgnoreCase("") && !password.trim().equalsIgnoreCase("")){
    htmlEmail.setAuthenticator(new DefaultAuthenticator(userId, password));
    htmlEmail.setTLS(true);
   }
    
   // set the recipient
   htmlEmail.addTo(toEmail, toName);
    
   // set the sender
   htmlEmail.setFrom(fromEmail, fromName);
    
   // set the subject
   htmlEmail.setSubject(subject);
    
   // set the email body
   htmlEmail.setHtmlMsg(sb.toString());
    
   // finally send the email
   htmlEmail.send();
   request.setAttribute("success",true);
    
  } catch (EmailException e) {
   request.setAttribute("success",false);
   e.printStackTrace();
  }
   
  getServletContext().getRequestDispatcher("/pages/htmlEmail.jsp").forward(request, response);
  
 }
}
References