Oct 8, 2011

extjs working with servlet



Following are the steps to delegate ExtJS Ajax or any synchronous calls to servlet.

1). Create a servlet class, with minimum having its doPost and doGet method. I have annotated the servlet with spring’s Controller annotation, which helps me later in doPost processing, but doesn’t impact much for processing at servlet level. You may opt for not to annotate with @Controller and use a simple HttpServlet. Below is full servlet code   

    import java.io.PrintWriter;
     import java.util.Enumeration;
     import java.util.List;
     import javax.servlet.http.HttpServlet;
     import javax.servlet.http.HttpServletRequest;
     import javax.servlet.http.HttpServletResponse;
     import org.springframework.stereotype.Controller;
     import net.sf.json.JSONArray;
     import com.ecms.model.Mainjob;
     import com.ecms.service.MainjobService;
@Controller
public class TestServlet extends HttpServlet {
     private MainjobService mainjobService;
     List<Mainjob> mainjobs = null;
     @Override
     public void doPost(HttpServletRequest req, HttpServletResponse res){
           try{
           System.out.println("inside doPost");
           System.out.println("going to get req params doPost");
           Enumeration<String> param = req.getParameterNames();
           String temp;
           while (param.hasMoreElements()){
                temp = param.nextElement();
           System.out.println("req-->>"+temp+"--value-"+req.getParameter(temp));
           }
           System.out.println("got params ererere");
           // Json object form of data
           String data = "{total:     4," +
                     "data: "+"[ {jobno: \"1\", eta: \"2\", portloading: \"Sin\", flightno: \"1243\"}," +   "          {jobno: \"2\", eta: \"2\", portloading: \"Sin\", flightno: \"14334\"}," +
        "          {jobno: \"3\", eta: \"2\", portloading: \"Sin\", flightno: \"233\"}," +
                     "          {jobno: \"4\", eta: \"2\", portloading: \"Sin\", flightno: \"1233\"}" +"]}";
           PrintWriter out = res.getWriter();
           out.print(data);
           JSONArray jsonArray = JSONArray.fromObject(mainjobs);
           System.out.println("jsonArray"+jsonArray);
           System.out.println("mainjob size-->>"+mainjobs.size());
           System.out.println("data--"+data);
           }
           catch(Exception ex){
                ex.printStackTrace();
           }
     }
     @Override
     public void doGet(HttpServletRequest req, HttpServletResponse res){
           System.out.println("inside doGet");
     }
}





2) Declare this servlet class in application’s web.xml. Following is how I modify my web.xml.

 <servlet>
           <servlet-name>test-servlet</servlet-name>
           <servlet-class>com.ecms.dao.test.TestServlet</servlet-class>
           <load-on-startup>1</load-on-startup>
     </servlet>
     <servlet-mapping>
           <servlet-name>test-servlet</servlet-name>
           <url-pattern>*.test</url-pattern>
     </servlet-mapping>


3) Now update the JS file to point the call to the particular URL mentioned in the web.xml, if you use proxy within the JS file, than proxy’s api must now use any url that has suffix as “.test” as we have mapped test servlet to “/*.test” URL in application’s web.xml file (step2). Following is the code segment, where I integrate the call which forward to servlet.

var proxy = new Ext.data.HttpProxy({
        api: {
            read : 'mainjob/viewMainjob.test',
            create : 'mainjob/createMainjob.action',
           }
    });

Note the difference between read and create, both URL has different suffix.

Above shows that the read operation would delegate task to test servlet, and create operation would look for “.action” mapping in web.xml, which can be mapped to another servlet.

Hope its useful for you, drop me your queries if any.

Thanks

Oct 4, 2011

JPA composite primary key example

JPA composite primary key requires careful implementation of Entity’s ID class,

There are two ways of it mentioned in JPA documentations

1)      Using Embeddable Composite Primary Key Class (uses @ Embeddable annotation)
2)      Using Non-Embedded Composite Primary Key Class (uses IDClass annotation from JPA)

Both above mentioned approaches are easy to implement, I anyhow selected second approach to work with in my project.

Following are the steps to implement


1) Created an Entity Class say Customer, which I annotated with @Entity annotation from JPA.

My Customer class looks like as given below:






@Entity
@Table(name="customer")
public class Customer implements Serializable {
     private static final long serialVersionUID = 1L;
    
     @Id
     @Column(name ="name")
     private Integer customerName;
     @Id
     @Column(name = "customer_id")
     private Integer customerId;
   
     /**
      * @return the customerId
      */
     public Integer getCustomerId() {
           return customerId;
     }
     /**
      * @param customerId the customerId to set
      */

     public void setCustomerId(Integer customerId) {
           this.customerId = customerId;
     }

     /**
      * @return the customerName
      */

     public Integer getCustomerName() {
          return customerName;
     }
     /**
      * @param customerName the customerName to set
      */
     public void setCustomerName(Integer customerName) {
           this.customerName = customerName;
     }
}




I have annotated both customerName and customerId with @Id, and Customer class with @Entity annotation.

3)   As we have a composite primary key for Customer Entity, so it requires for us to have an IDClass which mentions both the keys as parameters.
4)      I constructed the required ID class as given below




public class CustomerCompositeKey {
     private Integer customerName;
     private Integer customerId;
}




While testing above composite key, we will surely get some exception it doest not look complete and compliance with JPA documentation,  anyhow I run the test to retrieve data from database and got the following exception

Exception in thread "main" java.lang.IllegalArgumentException: to.CustomerCompositeKey cannot be cast to java.io.Serializable
       at org.hibernate.ejb.AbstractEntityManagerImpl.find(AbstractEntityManagerImpl.java:191)
       at mgr.CustomerMgr.getCustomer(CustomerMgr.java:24)
   at Test.main(Test.java:51)


Above exception caused by the not having Serialization interface implementation with my Composite key

So I changed my class further

public class CustomerCompositeKey implements Serializable{
    
     private static final long serialVersionUID = 1L;

If you follow the JPA document, they mention following rules for Composite key class link

·  Must be a POJO class, with public access and with a public constructor.
· properties of composite primary key class must be public or protected.
·  Serializable; and having implementation of  equals and hashCode methods.

Upon applying following changes my composite key evolved further as given below

/**

 *
@author varun

 *

 */

public class CustomerCompositeKey implements Serializable{
     private static final long serialVersionUID = 1L;
     public  String customerName;
     public  Integer customerId;
     public CustomerCompositeKey(){
     }
     public CustomerCompositeKey(String name, Integer id){
           this.setCustomerId(id);
           this.setCustomerName(name);
     }
     /**
      * @return the customerName
      */
     public String getCustomerName() {
           return customerName;
     }
     /**
      * @param customerName the customerName to set
      */
     public void setCustomerName(String customerName) {
           this.customerName = customerName;
     }
     /**
      * @return the customerId
      */
     public Integer getCustomerId() {
           return customerId;
     }
     /**
      * @param customerId the customerId to set
      */
     public void setCustomerId(Integer customerId) {
          this.customerId = customerId;
     }
     public int hashCode() {
        return (int) customerId.hashCode();
    }
   public boolean equals(Object obj) {
        if (obj == this) return true;
        if (!(obj instanceof ConfigNodeTypeId)) return false;
        if (obj == null) return false;
        CustomerCompositeKey pk = (CustomerCompositeKey) obj;
        return pk.customerId.equals(customerId);
    }
}



Upon testing, it throws another exception, which says

Exception in thread "main" java.lang.IllegalArgumentException: Provided id of the wrong type. Expected: class java.lang.String, got class to.CustomerCompositeKey
       at org.hibernate.ejb.AbstractEntityManagerImpl.find(AbstractEntityManagerImpl.java:188)
       at mgr.CustomerMgr.getCustomer(CustomerMgr.java:24)
   at Test.main(Test.java:51)

This is actually taking the default type of parameter for Customer entity instead of a composite key to match and find the record, this is because we have forgotten the very important step of including @IDClass annotation to bind the Entity to ID Class or composite key.

We further modify our Customer Entity class as

@Entity
@IdClass(CustomerCompositeKey.class)
@Table(name="customer")
public class Customer implements Serializable {
..
..

Upon testing further following Exception printed


 [ WARN][org.hibernate.util.JDBCExceptionReporter:71]SQL Error: 1054, SQLState: 42S22
[ERROR][org.hibernate.util.JDBCExceptionReporter:72]Unknown column 'customer0_.customerName' in 'field list'
Exception in thread "main" javax.persistence.PersistenceException: org.hibernate.exception.SQLGrammarException: could not load an entity: [to.Customer#component[customerName,customerId]{customerName=null, customerId=null}]
       at org.hibernate.ejb.AbstractEntityManagerImpl.throwPersistenceException(AbstractEntityManagerImpl.java:647)
       at org.hibernate.ejb.AbstractEntityManagerImpl.find(AbstractEntityManagerImpl.java:194)
       at mgr.CustomerMgr.getCustomer(CustomerMgr.java:24)
   at Test.main(Test.java:51)


This is found to be strange, even after following all the steps mentioned by JPA documentation, still there is trap.

Actually it says the particular column are not in the table, or your key’s entity names are not matching with your column, any way change the names to  matching your table column than you also have to change the names in the Entity class. But simpler solution is to annotate your IDClass or composite key attributes with @Column and in the name, write your database column name which are also mentioned in the Entity class.


Here is the updated code for CustomerCompositKey.class






public class CustomerCompositeKey implements Serializable{
     private static final long serialVersionUID = 1L;
     @Column(name ="name")
     private String customerName;
     @Column(name = "customer_id")
     private Integer customerId;
     .. .. ..
     .. .. ..


This would make it finally run and achieve the desired results.

Hope above explanation clears all doubts of composite key in JPA, queries are welcomed.

Thanks

Sep 23, 2011

spring security


Spring Security

Security is a concern for an application to provide its services consistently. There can be many security aspects, to protect your application from threats or potential attacks. To deal with the security issues its recommended that we must understand or make aware about the potential vulnerabilities such as session-hijacking, cross site scripting and request forgery which we need to taking into account right from the start of application development.

owasp.org particular website keeps details of top ten list of application vulnerabilities also some useful stuff to refer.

Following two types of approaches we can go with in case of Spring
1)      Name space based application security
2)      Spring bean approach where we wire up all implementation classes.

We will be doing the name space based security arrangements as it’s the latest and less work to do instead the Spring bean security.

 Security Requirements:

J2EE traditional security approaches for EJB or Servlet based applications is not so comprehensive and transferable to different platform, most of the case you will end-up deploying security setting for the same code or package in different environments or physical sites, which makes security an overhead and repeated process for multiple deployment of the same package.

However, spring security found to be comprehensive and tightly coupled with your package to give more flexibility when you move your configurations.

Following are the two most important sectors in the Security of a web application:

1)                  Authentication
2)                  Authorization

In Spring, authentication process is assigning or allocating a principle who can perform actions of application feature, who can be any thing such as a user, another system, module and device.

Authorization, is a process of deciding whether a principle is allowed to perform any action within our application.

Authorization usually to be provided to user with a UI component or screen, however authentication is something like assigning a role to the principle’s id.

At authentication level,  Spring security supports a wide range of authentication models, which are usually provided by third party components or may be developed. However, spring provides its own authentication features.

Authentication:

Spring currently supports authentication integration with many technologies however following is a some important one and mostly used technologies:
1)      Http Basic
2)      Http Digest
3)      LDAP
4)      Form based authentication
5)      OpenID
6)      AndroMDA
7)      Tapestery

Apart from theses, we can have our own security system depends on the requirement.

Authorization:

Irrespective of above mentioned authentication mechanism, spring provides a set of authorization capabilities:

1)                  Authorizing a web request.
2)                  Authorizing a method access.
3)                  Authorizing a domain object instance.
I will take some examples in my next post to show how actually it works in spring.

Sep 14, 2011

Aloha html5 editor

After doing my research on available html editors, found this html5 editor, recently released and quite cool to have as editor for web site contents online.

Beauty of the aloha html editor is, it does not need a textarea, it allow you to mark particular page content, which you like to edit and provides a boundary to the that area, which means its dynamically create a textarea on active text, and let you have a feeling of WYSIWYG feature.

Another, cool thing about this editor is, its floating menu style, I like it so much. Html5 editor is still in under experiment, which we need to wait and see, how does it progress in future.

I will take you through an implementaion of such a cool gadget style html editor.

  1. To start, download aloha library package from this link aloha-0.9.3.zip 
  2.  Extract the zip; below shows aloha's directory structure
aloha html editor directory structure
  1. write an html file as follows 
    1. wirte doctype as  <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> 
Add following plugins java scripts and
<script type="text/javascript" src="aloha/aloha.js"></script>
<script type="text/javascript" src="aloha/plugins/com.gentics.aloha.plugins.Format/plugin.js"></script>
<script type="text/javascript" src="aloha/plugins/com.gentics.aloha.plugins.Table/plugin.js"></script>
<script type="text/javascript" src="aloha/plugins/com.gentics.aloha.plugins.List/plugin.js"></script>
<script type="text/javascript" src="aloha/plugins/com.gentics.aloha.plugins.Link/plugin.js"></script>

<script type="text/javascript" src="aloha/plugins/com.gentics.aloha.plugins.HighlightEditables/plugin.js"></script>
<script type="text/javascript" src="aloha/plugins/com.gentics.aloha.plugins.TOC/plugin.js"></script>
<script type="text/javascript" src="aloha/plugins/com.gentics.aloha.plugins.Link/delicious.js"></script>
<script type="text/javascript" src="aloha/plugins/com.gentics.aloha.plugins.Link/LinkList.js"></script>
<script type="text/javascript" src="aloha/plugins/com.gentics.aloha.plugins.Paste/plugin.js"></script>
<script type="text/javascript" src="aloha/plugins/com.gentics.aloha.plugins.Paste/wordpastehandler.js"></script>
<link rel="stylesheet" href="AlohaWorld.css" />
<script type="text/javascript"   src="/ext-3.2.1/ext-all.js"></script>
<link rel="stylesheet" type="text/css"   href="/ext-3.2.1/resources/css/ext-all.css" />  
<script language="javascript" type="text/javascript"> 
    1. Add a div element to the body where the editable content shall be rendered or added by aloha editor as                                                                                                                <div id="content" ><br><br></div>

Add below java script code for aloha to get instantiate its resources

<script type="text/javascript">
GENTICS.Aloha.settings = {
      logLevels: {'error': true, 'warn': true, 'info': true, 'debug': false},
      errorhandling : false,
      ribbon: false,   
      "i18n": {
            // you can either let the system detect the users language (set acceptLanguage on server)
            // In PHP this would would be '<?=$_SERVER['HTTP_ACCEPT_LANGUAGE']?>' resulting in
            // "acceptLanguage": 'de-de,de;q=0.8,it;q=0.6,en-us;q=0.7,en;q=0.2'
            // or set current on server side to be in sync with your backend system
            "current": "en"
      },
      "repositories": {
            "com.gentics.aloha.repositories.LinkList": {
                  data: [
                    { name: 'Aloha Developers Wiki', url:'http://www.aloha-editor.com/wiki', type:'website', weight: 0.50 },
                    { name: 'Aloha Editor - The HTML5 Editor', url:'http://aloha-editor.com', type:'website', weight: 0.90  },
                    { name: 'Aloha Demo', url:'http://www.aloha-editor.com/demos.html', type:'website', weight: 0.75  },
                    { name: 'Aloha Wordpress Demo', url:'http://www.aloha-editor.com/demos/wordpress-demo/index.html', type:'website', weight: 0.75  },
                    { name: 'Aloha Logo', url:'http://www.aloha-editor.com/images/aloha-editor-logo.png', type:'image', weight: 0.10  }
                  ]
            }
      },
      "plugins": {
            "com.gentics.aloha.plugins.Format": {
                  // all elements with no specific configuration get this configuration
                  config : [ 'b', 'i','sub','sup'],
                  editables : {
                        // no formatting allowed for title
                        '#title'    : [ ],
                        // formatting for all editable DIVs
                        'div'       : [ 'b', 'i', 'del', 'sub', 'sup'  ],
                        // content is a DIV and has class .article so it gets both buttons
                        '.article'  : [ 'b', 'i', 'p', 'title', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'pre', 'removeFormat']
                  }
            },
            "com.gentics.aloha.plugins.List": {
                  // all elements with no specific configuration get an UL, just for fun :)
                  config : [ 'ul' ],
                  editables : {
                        // Even if this is configured it is not set because OL and UL are not allowed in H1.
                        '#title'    : [ 'ol' ],
                        // all divs get OL
                        'div'       : [ 'ol' ],
                        // content is a DIV. It would get only OL but with class .article it also gets UL.
                        '.article'  : [ 'ul' ]
                  }
            },
            "com.gentics.aloha.plugins.Link": {
                  // all elements with no specific configuration may insert links
                  config : [ 'a' ],
                  editables : {
                        // No links in the title.
                        '#title'    : [  ]
                  },
                  // all links that match the targetregex will get set the target
                  // e.g. ^(?!.*aloha-editor.com).* matches all href except aloha-editor.com
                  targetregex : '^(?!.*aloha-editor.com).*',
                  // this target is set when either targetregex matches or not set
                // e.g. _blank opens all links in new window
                  target : '_blank',
                  // the same for css class as for target
                  cssclassregex : '^(?!.*aloha-editor.com).*',
                  cssclass : 'aloha',
                  // use all resources of type website for autosuggest
                  objectTypeFilter: ['website'],
                  // handle change of href
                  onHrefChange: function( obj, href, item ) {
                        if ( item ) {
                              jQuery(obj).attr('data-name', item.name);
                        } else {
                              jQuery(obj).removeAttr('data-name');
                        }
                  }
            },
            "com.gentics.aloha.plugins.Table": {
                  // all elements with no specific configuration are not allowed to insert tables
                  config : [ ],
                  editables : {
                        // Allow insert tables only into .article
                        '.article'  : [ 'table' ]
                  }
            }
      }
};

$(document).ready(function() {
      $('#title').aloha();
      $('#teaser').aloha();
      $('#content').aloha(); 
});


</script>


Following code is to play around with the editor using control button on html page,

I like to modify some content on the page and like to publish, when I press the publish button, idea is the button calls below given java script methods

savePage() would save actually publish the content to the same page (just for the simplicity)

Ext.onReady(function(){
  var editor = new Ext.form.HtmlEditor({id:'note'});
  editor.applyTo('note');
})


var contentHtml;

function  savePage (){
      //alert("Hello World!");
      var content;
      // iterate all dom elements which have been made aloha editable
      jQuery.each(GENTICS.Aloha.editables,function (index, editable) {
            // and get their clean and valid html5 content, and remember it to fake saving
            content = content + "Editable ID: " + editable.getId() +"\nHTML code: " + editable.getContents() + "\n\n";
            publishContent(editable.getContents());
            contentHtml = editable.getContents();
            editable.disable();
            this.obj.deactivateEditable();
                  
        // set scope for floating menu
        this.obj.FloatingMenu.setScope('GENTICS.Aloha.empty');
       
        //this.activeEditable = null;
            //alert(contentHtml);
      });
      // this fakes the saving of the content to your backend.
      // TODO implement this to save the edited aloha content into your backend
      //alert("Hello World!123");
      //alert(""+content);
     
};


/// method publishes this content to the url '/TestEditor/saveContent', which directs the request to a servlet to process it ( servlet further can store the content in database and retrieve back for the publishing)

function publishContent(content) {
            //alert('this is publish content-'+content);
                  //alert('checkUserName');
             url  =  '/TestEditor/saveContent';
             if (window.XMLHttpRequest) {
                   // alert('this is window.XMLHttpRequest-'+document.myform.htmlEditor.value);
                // obtain new object
                obj = new XMLHttpRequest();
                // callback function
                obj.onreadystatechange = processChange;
                // this will perform a GET with the url
                obj.open("POST", url, true);
         
                obj.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
                if (content != null){
                   // alert('content available now'+content);
                    obj.send('htmlEditor='+content);
                    
                } else
                  obj.send('htmlEditor='+document.myform.htmlEditor.value);
              // IE/Windows ActiveX object
              } else if (window.ActiveXObject) {
                obj = new ActiveXObject("Microsoft.XMLHTTP");
                if (obj) {
                  obj.onreadystatechange = processChange;
                  obj.open("POST", url, true);
                  // don't send null for ActiveX
                  obj.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
                  obj.send('htmlEditor='+document.myform.htmlEditor.value);
                }
              } else {
                alert("Your browser does not support AJAX");
              }
        
       
      }


// just after it publish, I force editor to deactivate, which it require to press Edit button for user to again start editing

function activateEditable(){
      //alert('activateEditable');
      jQuery.each(GENTICS.Aloha.editables,function (index, editable) {
            //alert('enabling');
            //editable.activate();
            editable.enable();
            });
};


Finally the body part of our html file which will have all the game.

<body>
<div id="content" ><br><br>
</div>
<form name="myform">
<textarea name="htmlEditor" cols="125" rows="20"  ></textarea>
<br />
<input type="button" value="Save" onclick="publishContent(null)" /><br>
<input type="button" value="Publish" onclick="savePage()" />
<input type="button" value="Edit" onclick="activateEditable()" />
</form>
<div id="published">
</div>
</body>


Hope this would help you to get the one of the coolest Html editor and save the edited content and render back on  screen. Drop me your queries or further knowledge on knowledge-pages.

Thanks