Pages

Saturday, November 15, 2014

Extjs best practises

 

 

 

 

                                                            1.use MVC

2.use xtype

3.define custom xtypes

4.use compressor - give minified files to client

5.use SenchaArchitect or cmd

6.travese dom using up/down etc - dont give ID and dont get by ID to elements

7.use icons instead of "text+icons"

8.inject images using css

9.use theming

10.avoid using deprecated commands and use new commands like using Ext.launch method

instead of Ext.onReady

11.dont declare deep tree... use layouts precisely... try to keep things with in 2 or 3

levels

12.Reuse the components

13. Try to do population and manipulation in afterRenderer than in beforeRenederer

14.Always handle exceptions, especially failure cases of a Ajax call

 

Wednesday, November 12, 2014

While trying samples with Ext.tab.Panel, as usual I though about the next step of using nested panels and load an external html file into a panel.
And I tried a few simple straight forward stuffs and for some reason it kept failing. Eventually I came up with an answer as usual. Guess I dont want to be stuck with this silly issue every again. And hence this post. Following is a part of my practise project which is necessary for the nested tab implementation

I have the following in code in the head section of my "index.html" file

 <!-- STYLES -->
    <link rel="stylesheet" type="text/css" href="\ext-4.2.1.883/resources/css/ext-all.css">
    <!-- LIBS -->
    <script type="text/javascript" src="\ext-4.2.1.883/ext-all-debug.js"></script>
    <!-- APP -->
    <script type="text/javascript" src="./app.js"></script>

The contents of my "external.html" file are as follows
<div id='karthick'>
My Custom text from an external HTMl
</div>

And the following in my "app.js" file

 Ext.require('Ext.tab.*'); Ext.application({ name: "Tab Panel example", launch : function() { var tabs = Ext.create('Ext.tab.Panel', { width : 450, height: 400, renderTo: document.body, activeTab : 0, id:'parentTab', items : [{ title:'Home', itemId : 'tab1', xtype: 'container', loader: { url: 'external.htm', autoLoad: true }, closable : true }, { title:'Away', itemId : 'tab2', closable : true, items:[{ xtype:'tabpanel', items : [{ title: 'Nested Tab 1', itemId : 'nested tab1', closable : true, html:'nested tab1' },{ title: 'Nested Tab 2', itemId : 'nested tab2', closable : true, html:'nested tab2', disabled:true }] }] }] }); } });

So the end result is as follows
The highlights in this example are
1. You are using a nested tabbed table created through Ext-js 4.2
2. It implements some inbuilt properties like
- closable:true
- and disable:true
3. You have included an external html file's content into your page


Note: this example wont work if you are trying this example in a local stand alone machine. Use a server like tomcat or IIS, because, the inclusion of content from an other html file includes AJAX requests in the back end by Ext-JS which would definitely fail in local or conclusively it requires a server to operate

Nested Tab example in Ext-Js

While trying samples with Ext.tab.Panel, as usual I though about the next step of using nested panels.
And I tried a few simple straight forward stuffs and for some reason it kept failing. Eventually I came up with an answer as usual. Guess I dont want to be stuck with this silly issue every again. And hence this post. Following is a part of my practise project which is necessary for the nested tab implementation

You can safely omit external.htm file for now

I have the following in code in the head section of my "index.html" file

 <!-- STYLES -->
    <link rel="stylesheet" type="text/css" href="\ext-4.2.1.883/resources/css/ext-all.css">
 
    <!-- LIBS -->
    <script type="text/javascript" src="\ext-4.2.1.883/ext-all-debug.js"></script>
 
    <!-- APP -->
    <script type="text/javascript" src="./app.js"></script>

And the following in my "app.js" file

Ext.require('Ext.tab.*');

Ext.application({
name: "Tab Panel example",
launch : function() {
var tabs = Ext.create('Ext.tab.Panel', {
width : 450,
height: 400,
renderTo: document.body,
activeTab : 1,
id:'parentTab',
items : [{
title:'Home',
itemId : 'tab1',
html: 'First tab content',
closable : true
}, {
title:'Away',
itemId : 'tab2',
closable : true,
items:[{
xtype:'tabpanel',
items : [{
title: 'Nested Tab 1',
itemId : 'nested tab1',
closable : true,
html:'nested tab1'
},{
title: 'Nested Tab 2',
itemId : 'nested tab2',
closable : true,
html:'nested tab2',
disabled:true
}]
}]
}]
});

}
});

The end result that I obtained is as follows. 


:)

Wednesday, November 5, 2014

File Upload using Servlets


Create a simple Dynamic Web project in the eclipse IDE. I have installed Apache Tomcat 7.0.10 and following is my folder stucture. You can safely skip the HelloWorld.java and LogFilter.java files from this folder structure as they don't have any thing to do with this post.

My motive is to give a simple explanation/illustration on how a file upload control can be implemented in java programs using servlets.

Step 1. create a FileUploadTest.html file in your WebContent folder. I tried putting the same under a sub folder of the WebContent folder. But it never worked. It was not able to communicate with the corresponding servlet.
The code contents of this HTML file are as follows
test




Step 2: Create a servlet class with the following contents in it

package com.practise.karthik.servlet;

// Import required java libraries
import java.io.*;
import java.util.*;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.io.output.*;

public class UploadServlet extends HttpServlet {
 
   private boolean isMultipart;
   private String filePath;
   private int maxFileSize = 50 * 1024;
   private int maxMemSize = 4 * 1024;
   private File file ;

   public void init( ){
      // Get the file location where it would be stored.
      filePath =
             getServletContext().getInitParameter("file-upload");
   }
   public void doPost(HttpServletRequest request,
               HttpServletResponse response)
              throws ServletException, java.io.IOException {
      // Check that we have a file upload request
      isMultipart = ServletFileUpload.isMultipartContent(request);
      response.setContentType("text/html");
      java.io.PrintWriter out = response.getWriter( );
      if( !isMultipart ){
         out.println("<html>");
         out.println("<head>");
         out.println("<title>Servlet upload</title>");
         out.println("</head>");
         out.println("<body>");
         out.println("<p>No file uploaded</p>");
         out.println("</body>");
         out.println("</html>");
         return;
      }
      DiskFileItemFactory factory = new DiskFileItemFactory();
      // maximum size that will be stored in memory
      factory.setSizeThreshold(maxMemSize);
      // Location to save data that is larger than maxMemSize.
      factory.setRepository(new File("c:\\temp"));

      // Create a new file upload handler
      ServletFileUpload upload = new ServletFileUpload(factory);
      // maximum file size to be uploaded.
      upload.setSizeMax( maxFileSize );

      try{
      // Parse the request to get file items.
      List fileItems = upload.parseRequest(request);
      // Process the uploaded file items
      Iterator i = fileItems.iterator();

      out.println("<html>");
      out.println("<head>");
      out.println("<title>Servlet upload</title>");
      out.println("</head>");
      out.println("<body>");
      while ( i.hasNext () )
      {
         FileItem fi = (FileItem)i.next();
         if ( !fi.isFormField () )
         {
            // Get the uploaded file parameters
            String fieldName = fi.getFieldName();
            String fileName = fi.getName();
            String contentType = fi.getContentType();
            boolean isInMemory = fi.isInMemory();
            long sizeInBytes = fi.getSize();
            // Write the file
            if( fileName.lastIndexOf("\\") >= 0 ){
               file = new File( filePath +
               fileName.substring( fileName.lastIndexOf("\\"))) ;
            }else{
               file = new File( filePath +
               fileName.substring(fileName.lastIndexOf("\\")+1)) ;
            }
            fi.write( file ) ;
            out.println("Uploaded Filename: " + fileName + "<br>");
         }
      }
      out.println("</body>");
      out.println("</html>");
   }catch(Exception ex) {
       System.out.println(ex);
   }
   }
   public void doGet(HttpServletRequest request,
                       HttpServletResponse response)
        throws ServletException, java.io.IOException {
     
        throw new ServletException("GET method used with " +
                getClass( ).getName( )+": POST method required.");
   }
}

Step 3: Add the following to your web.xml
 <servlet>
<servlet-name>UploadServlet</servlet-name>
<servlet-class>com.practise.karthik.servlet.UploadServlet</servlet-class>
</servlet>

<servlet-mapping>
<servlet-name>UploadServlet</servlet-name>
<url-pattern>/UploadServlet</url-pattern>
</servlet-mapping>


Set 4 : Now you would need a couple of jar files that would help you with the file upload functionality

commons-fileupload.x.x.jar file - You can download it fromhttp://commons.apache.org/fileupload/.
commons-io-x.x.jar file - You can download it from http://commons.apache.org/io/.

Step 5: Download these files and add them to the lib folder under the WEB-INF folder and add it to the project's build path


Step 6: Now stop your Apache Tomcat Server if its already running. 
 - Right click on the html file mentioned in step 1, 
 - click on "Run as" and 
 - click on "Run on server" option
 - choose your installed Tomcat server ( hope you had already added the server to your Servers view in the eclipse) and
 - finish

This helped me get to the following screen



Choose your file and click on the "Upload File" button. You should receive a confirmation screen with the name of the file that you just uploaded as follows


This helped me upload my file to my server space configured in the web.xml and I am able to find the uploaded file as follows