Google

Sep 30, 2013

Hibernate dependencies jars and plugins

Here is a sample maven pom.xml snippets containing the dependency jars. 


....
<hibernate.version>4.1.3.Final</hibernate.version>
<hibernate-jpa-2.0-api.version>1.0.1.Final</hibernate-jpa-2.0-api.version>
<hibernate-validator-annotation-processor>4.2.0.Final</hibernate-validator-annotation-processor>
<hibernate-validator.version>4.3.0.Final</hibernate-validator.version>



The above snippet defines the version numbers.


The snippet below defines the dependencies.

...
<dependency>
 <groupId>org.hibernate</groupId>
 <artifactId>hibernate-core</artifactId>
</dependency>
<dependency>
 <groupId>org.hibernate</groupId>
 <artifactId>hibernate-entitymanager</artifactId>
</dependency>
<dependency>
 <groupId>org.hibernate.javax.persistence</groupId>
 <artifactId>hibernate-jpa-2.0-api</artifactId>
</dependency>

<dependency>
 <groupId>javax.validation</groupId>
 <artifactId>validation-api</artifactId>
</dependency>

<dependency>
 <groupId>org.hibernate</groupId>
 <artifactId>hibernate-validator</artifactId>
</dependency>
   
<dependency>
 <groupId>org.hibernate.javax.persistence</groupId>
 <artifactId>hibernate-jpa-2.0-api</artifactId>
 <version>${hibernate-jpa-2.0-api.version}</version>
</dependency>

<dependency>
 <groupId>org.hibernate</groupId>
 <artifactId>hibernate-validator-annotation-processor</artifactId>
 <version>${hibernate-validator-annotation-processor}</version>
</dependency>


<!-- bean validation -->
<dependency>
 <groupId>javax.validation</groupId>
 <artifactId>validation-api</artifactId>
 <version>1.0.0.GA</version>
</dependency>

<dependency>
 <groupId>org.hibernate</groupId>
 <artifactId>hibernate-validator</artifactId>
 <version>${hibernate-validator.version}</version>
</dependency>




If you want to auto-generate your hibernate entities from DDL then.

   <build>
  <resources>
   <resource>
    <directory>${basedir}/src/main/resources</directory>
    <includes>
     <include>**/*</include>
    </includes>
   </resource>
  </resources>

  <plugins>
   <plugin>
    <groupId>org.codehaus.mojo</groupId>
    <artifactId>hibernate3-maven-plugin</artifactId>
    <configuration>
     <components>
      <component>
       <name>hbm2ddl</name>
       <implementation>jpaconfiguration</implementation>
      </component>
      <component>
       <name>hbmdoc</name>
      </component>
     </components>
     <componentProperties>
      <persistenceunit>my-data</persistenceunit>
      <outputfilename>schema.ddl</outputfilename>
      <drop>true</drop>
      <create>true</create>
      <export>false</export>
      <format>true</format>
     </componentProperties>
    </configuration>
   </plugin>
  </plugins>
 </build>


Finally, the plugin that is required for auto generation.

 <pluginManagement>
 <plugins>
  <plugin>
   <groupId>org.codehaus.mojo</groupId>
   <artifactId>hibernate3-maven-plugin</artifactId>
   <version>2.2</version>
  </plugin>
     </plugins>
  </pluginManagement> 

Labels:

Sep 25, 2013

Spring CrudRepository with JPA example

Step 1: Add the jar dependency to your maven pom.xml file.


..
<spring.data.version>1.2.0.RELEASE</spring.data.version>
...
<dependency>
 <groupId>org.springframework.data</groupId>
 <artifactId>spring-data-jpa</artifactId>
 <version>${spring.data.version}</version>


Step 2: Define the JPA entity -- that is your model class that maps to the table in the database.




package com.mydomain.model;

import java.util.ArrayList;
import java.util.List;

import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.OneToMany;
import javax.persistence.OneToOne;
import javax.persistence.PrimaryKeyJoinColumn;
import javax.persistence.Table;
import javax.persistence.Transient;

import org.apache.commons.lang.builder.EqualsBuilder;
import org.apache.commons.lang.builder.HashCodeBuilder;
import org.apache.commons.lang.builder.ToStringBuilder;
import org.apache.commons.lang.builder.ToStringStyle;
import org.hibernate.annotations.Type;
import org.springframework.data.jpa.domain.AbstractPersistable;

@Entity
@Table(name = "ReportStructure")
public class Node extends AbstractPersistable<Long>
{
    
    private static final long serialVersionUID = 1L;
    
    @ManyToOne
    @JoinColumn(name = "ParentId", insertable = false, updatable = false)
    private Node parent;
    
    @OneToMany(cascade = CascadeType.ALL)
    @JoinColumn(name = "ParentId", nullable = false)
    private List<Node> children = new ArrayList<Node>();
    
    @OneToOne(cascade = CascadeType.ALL)
    @PrimaryKeyJoinColumn
    private NodeAttributes attributes;
    
    @ManyToOne(cascade = CascadeType.ALL, optional = false)
    @JoinColumn(name = "KeyId")
    private NodeKey key;
    
    @Column(name = "InactiveFlag", nullable = false, length = 1)
    @Type(type = "yes_no")
    private boolean isSoftDeleted;
    
   
    public Node()
    {
        this(null);
    }
    
    public Node(Long id)
    {
        this.setId(id);
    }
    
    public List<Node> getChildren()
    {
        return children;
    }
    
    public Node getParent()
    {
        return parent;
    }
    
    public void setParent(Node parent)
    {
        this.parent = parent;
        if (parent != null)
        {
            parent.addChild(this);
        }
    }
    
    public void setChildren(List<Node> children)
    {
        this.children = children;
    }
    
    public void addChild(Node child)
    {
        if (child == null)
        {
            return;
        }
        if (!children.contains(child))
        {
            children.add(child);
            synchronized (this)
            {
                if (child.parent == null)
                {
                    child.setParent(this);
                }
            }
        }
    }
    
    public NodeKey getKey()
    {
        return key;
    }
    
    public void setKey(NodeKey key)
    {
        this.key = key;
    }
    
    public NodeAttributes getAttributes()
    {
        return attributes;
    }
    
    public void setAttributes(NodeAttributes attributes)
    {
        this.attributes = attributes;
        this.attributes.setNode(this);
    }
    
    public boolean isSoftDeleted()
    {
        return isSoftDeleted;
    }
    
    public void setSoftDeleted(boolean isSoftDeleted)
    {
        this.isSoftDeleted = isSoftDeleted;
    }
    
        
    @Override
    public int hashCode()
    {
        return new HashCodeBuilder().append(key).append(parent).append(attributes).toHashCode();
    }
    
    @Override
    public boolean equals(final Object obj)
    {
        if (obj instanceof Node)
        {
            final Node other = (Node) obj;
            return new EqualsBuilder().append(key, other.getKey()).append(parent, other.getParent())
                    .append(attributes, other.getAttributes()).isEquals();
        }
        return false;
    }
    
    @Override
    public String toString()
    {
        return ToStringBuilder.reflectionToString(this, ToStringStyle.SHORT_PREFIX_STYLE);
    }
}


Step 3: Define the CRUD reposotory by extending Spring's  CrudRepository class. The CrudRepository gives you out of the box access to the following standard methods


  • delete(T entity) which deletes the entity given as a parameter.
  • findAll() which returns a list of entities.
  • findOne(ID id) which returns the entity using the id given a parameter as a search criteria.
  • save(T entity) which saves the entity given as a parameter.


You can provide additional custom methods as shown below,


package com.mydomain.model.impl

import com.mydomain.model.Node;
import com.mydomain.model.NodeKey;

import java.util.Date;
import java.util.List;

import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.CrudRepository;
import org.springframework.data.repository.query.Param;


public interface NodeRepository extends CrudRepository<Node, Long>
{
    @Query("SELECT n from Node n JOIN n.key k WITH k.clientId = ?1 and k.evalDate = ?2 "
            + "WHERE n.parent is null and n.isSoftDeleted = false ")
    List<Node> find(String clientId, Date evalDate);
    
    @Query("SELECT n from Node n JOIN n.key k WITH k.clientId = :clientId and k.evalDate = :evalDate "
            + "WHERE n.attributes.code = :code and n.isSoftDeleted = false ")
    List<Node> find(@Param("clientId") String clientId, @Param("evalDate") Date evalDate,
            @Param("code") String code);
    
    @Query("SELECT key from NodeKey key where key.isSoftDeleted = false")
    List<NodeKey> findNodeKey();
    
    @Query("SELECT key from NodeKey key WHERE key.clientId = ?1 and key.isSoftDeleted = false")
    List<NodeKey> fetch(String clientId);  
}


Step 4: The Spring config file to wire up JPA. This example uses HSQL.

<!-- Directory to scan for repository classes -->
<jpa:repositories
   base-package="com.mydomain.model" />
 
<bean class="org.springframework.orm.jpa.JpaTransactionManager"
  id="transactionManager">
  <property name="entityManagerFactory"
      ref="entityManagerFactory" />
  <property name="jpaDialect">
    <bean class="org.springframework.orm.jpa.vendor.HibernateJpaDialect" />
  </property>
</bean>
 
<bean id="entityManagerFactory"
  class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
  <property name="dataSource" ref="dataSource" />
  <property name="jpaVendorAdapter">
    <bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
      <property name="generateDdl" value="true" />
      <property name="database" value="HSQL" />
    </bean>
  </property>
</bean>

Step 5: Use the NodeRepository for CRUD operations in the service layer.

public class ReportServiceImpl extends ReportService {
 
   @Autowired
   NodeRepository nodeRepository;
 
  ...
}

Labels: ,

Sep 19, 2013

30+ Core Java multithreading interview questions and answers

Java Multi-threading Interview Questions and Answers

Beginner Q&A More beginner Q&A Beginner locks Beginner thread communication Beginner thread sequencing Intermediate Q&A Volatile variable
Advanced Q&A Printing odd and even numbers Thread pools ExecutorService Atomic operations CountDownLatch and CyclicBarrier Semaphores and mutexes

Q. Why do interviewers like multi-threading interview questions?
A. Because it is not easy, but very essential to write scalable and high throughput systems.

If you are going for Java interviews to work on large scale systems,  expect multi-threading interview questions. These are more beginner or fresher level questions and if you are already good with the basics, try more intermediate to advanced level coding questions and answers on Java multi-threading at Java multi-threading-1  |   Java multi-threading-2

Q. What is the difference between processes and threads?
A. A process is an execution of a program but a thread is a single execution sequence within the process. A process can contain multiple threads. A thread is sometimes called a lightweight process.


A JVM runs in a single process and threads in a JVM share the heap belonging to that process. That is why several threads may access the same object. Threads share the heap and have their own stack space. This is how one thread’s invocation of a method and its local variables are kept thread safe from other threads. But the heap is not thread-safe and must be synchronized for thread safety.

Q. Explain different ways of creating a thread?
A. Threads can be used by either
  • Extending the Thread class.
  • Implementing the Runnable interface.
  • Using the Executor framework (this creates a thread pool) 



class Counter extends Thread {
   
    //method where the thread execution will start 
    public void run(){
        //logic to execute in a thread    
    }

    //let’s see how to start the threads
    public static void main(String[] args){
       Thread t1 = new Counter();
       Thread t2 = new Counter();
       t1.start();  //start the first thread. This calls the run() method.
       t2.start(); //this starts the 2nd thread. This calls the run() method.  
    }
} 



class Counter extends Base implements Runnable{
  
    //method where the thread execution will start 
    public void run(){
        //logic to execute in a thread    
    }

    //let us see how to start the threads
    public static void main(String[] args){
         Thread t1 = new Thread(new Counter());
         Thread t2 = new Thread(new Counter());
         t1.start();  //start the first thread. This calls the run() method.
         t2.start();  //this starts the 2nd thread. This calls the run() method.  
    }
} 

The thread pool is more efficient and  learn why and how to create pool of  threads using the executor framework.

Q. Which one would you prefer and why?
A. The Runnable interface is preferred, as it does not require your object to inherit a thread because when you need multiple inheritance, only interfaces can help you. In the above example we had to extend the Base class so implementing Runnable interface is an obvious choice. Also note how the threads are started in each of the different cases as shown in the code sample. In an OO approach you should only extend a class when you want to make it different from it’s superclass, and change it’s behavior. By implementing a Runnable interface instead of extending the Thread class, you are telling to the user that the class Counter is an object of type Base and will run as a thread.


Q. Briefly explain high-level thread states?
A. The state chart diagram below describes the thread states.

  • Runnable — A thread becomes runnable when you call the start( ), but does  not necessarily start running immediately.  It will be pooled waiting for its turn to be picked for execution by the thread scheduler based on thread priorities.

    MyThread aThread = new MyThread();
    aThread.start();                   //becomes runnable
    
  • Running: The processor is actively executing the thread code. It runs until it becomes blocked, or voluntarily gives up its turn with this static method Thread.yield( ). Because of context switching overhead, yield( ) should not be used very frequently
  • Waiting: A thread is in a blocked state while it waits for some external processing such as file I/O to finish.A call to currObject.wait( ) method causes the current thread to wait until some other thread invokes currObject.notify( ) or the currObject.notifyAll( ) is executed.
  • Sleeping: Java threads are forcibly put to sleep (suspended) with this overloaded method: Thread.sleep(milliseconds), Thread.sleep(milliseconds, nanoseconds);
  • Blocked on I/O: Will move to runnable after I/O condition like reading bytes of data etc changes.
  • Blocked on synchronization: will move to running when a lock is acquired. 
  • Dead: The thread is finished working.
Thread.State enumeration contains the possible states of a Java thread in the underlying JVM. These thread states are possible due to Java's following thread concepts:
  • The objects can be shared and modified (i.e. if mutable) by any threads.
  • The preemptive nature of the thread scheduler can swap threads on and off cores in a multi-core CPU machine at any time.
  • This means the methods can be swapped out while they are running. Otherwise a method in an infinite loop will clog the CPU forever leaving the other methods on different threads to starve. 
  • To prevent thread safety issues, the methods and block of code that has vulnerable data can be locked
  • This enables the threads to be in locked or waiting to acquire a lock states. 
  • The threads also get into the waiting state for I/O resources like sockets, file handles, and database connections. 
  • The threads that are performing I/O read/write operations can not be swapped. Hence, they need to either complete to the finished state with success/failure or another thread must close the socket for it to get to the state of dead or finished. This is why proper service timeout values are necessary to prevent the thread to get blocked for ever in an I/O operation, causing performance issues. 
  • The threads can be put to sleep to give other threads in waiting state an opportunity to execute.


Q. What is the difference between yield and sleeping? What is the difference between the methods sleep( ) and wait( )?
A. When a task invokes yield( ), it changes from running state to runnable state. When a task invokes sleep ( ), it changes from running state to waiting/sleeping state.

The method wait(1000) causes the current thread to wait up to one second a signal from other threads. A thread could wait less than 1 second if it receives the notify( ) or notifyAll( ) method call. The call to sleep(1000) causes the current thread to sleep for t least 1 second.

Q. Why is locking of a method or block of code for thread safety is called "synchronized" and not "lock" or "locked"?
A. When a method or block of code is locked with the reserved "synchronized" key word in Java, the memory (i.e. heap) where the shared data is kept is synchronized. This means,

  • When a synchronized block or method is entered after the lock has been acquired by a thread, it first reads any changes to the locked object from the main heap memory to ensure that the thread that has the lock has the current info before start executing.
  • After the synchronized  block has completed and the thread is ready to relinquish the lock, all the changes that were made to the object that was locked is written or flushed back to the main heap memory so that the other threads that acquire the lock next has the current info.

This is why it is called "synchronized" and not "locked". This is also the reason why the immutable objects are inherently thread-safe and does not require any synchronization. Once created, the immutable objects cannot be modified.

Q. How does thread synchronization occurs inside a monitor? What levels of synchronization can you apply? What is the difference between synchronized method and synchronized block?
A. In Java programming, each object has a lock. A thread can acquire the lock for an object by using the synchronized keyword. The synchronized keyword can be applied in method level (coarse grained lock – can affect performance adversely) or block level of code (fine grained lock). Often using a lock on a method level is too coarse. Why lock up a piece of code that does not access any shared resources by locking up an entire method. Since each object has a lock, dummy objects can be created to implement block level synchronization. The block level is more efficient because it does not lock the whole method.



The JVM uses locks in conjunction with monitors. A monitor is basically a guardian who watches over a sequence of synchronized code and making sure only one thread at a time executes a synchronized piece of code. Each monitor is associated with an object reference. When a thread arrives at the first instruction in a block of code it must obtain a lock on the referenced object. The thread is not allowed to execute the code until it obtains the lock. Once it has obtained the lock, the thread enters the block of protected code. When the thread leaves the block, no matter how it leaves the block, it releases the lock on the associated object. For static methods, you acquire a class level lock.

More Interview Q&A on Java multithreading:

Beginner:
Intermediate to Advanced

Articles on Java 5 concurrent package


Labels:

When to use a builder design pattern? real life tips

Interview questions relating to design patterns are very popular in job interviews. Even if  this topic is not covered in rare occassions, you can bring it up yourself to open-ended questions to impress your  interviewers.

Q. What are the key difference(s) between a factory and a builder design patterns?
A. The builder design pattern builds an object over several steps. It holds the needed state for the target item at each intermediate step. The  StringBuilder is a good example that goes through to produce a final string. Here is a real world example that shows how builders are used instead of constructors to create Immutable objects. Creating immutable objects where applicable is a development best practice.


The factory design pattern describes an object that knows how to create several different but related kinds of object in one step, where the specific type is chosen based on given parameters. 
Q. When would you use a builder design pattern?
A
  • To construct a complex object. For example, to construct XML DOM objects and any other hierachichal objects. You have to create plenty of nodes and attributes to get your final object.
  •  Builder pattern makes your code more readable as explained in the article  "Using Builders instead of Constructors to create Immutable objects". The article explains how you can create immutable objects in Java by using the builder design pattern as opposed to using multiple constructors, which is known as the "telescoping constructor anti pattern".Firstly, let's see what is not so elegant about using a constructor as shown below with a CashBalance object that takes 3 BigDecimal arguments. Then we will see how a builder class will make your code more intuitive. 

Q. Can you give some examples from your experience?
A.

Example 1: Custom class.





package com.myapp.data;

import java.math.BigDecimal;

import org.apache.commons.lang.builder.ToStringBuilder;
import org.apache.commons.lang.builder.ToStringStyle;
import org.springframework.util.Assert;


public class NetAsset
{
    
    public static NetAsset EMPTY = new Builder().setGrossAssetValueBeforeTax(BigDecimal.ZERO)
            .setGrossAssetValueAfterTax(BigDecimal.ZERO).setTotalAssets(BigDecimal.ZERO)
            .setTotalInvestments(BigDecimal.ZERO)
            .setTotalLiabilities(BigDecimal.ZERO)
            .setTotalReceivables(BigDecimal.ZERO)
            .build();
    
    private final BigDecimal grossAssetValueAfterTax;
    private final BigDecimal grossAssetValueBeforeTax;
    private final BigDecimal totalReceivables;
    private final BigDecimal totalInvestments;
    private final BigDecimal totalAssets;
    private final BigDecimal totalLiabilities;
    
    // add more
    
    private NetAsset(Builder builder)
    {
        Assert.notNull(builder.grossAssetValueAfterTax);
        Assert.notNull(builder.grossAssetValueBeforeTax);
        Assert.notNull(builder.totalReceivables);
        Assert.notNull(builder.totalInvestments);
        Assert.notNull(builder.totalAssets);
        Assert.notNull(builder.totalLiabilities);
        
        this.grossAssetValueAfterTax = builder.grossAssetValueAfterTax;
        this.grossAssetValueBeforeTax = builder.grossAssetValueBeforeTax;
        this.totalReceivables = builder.totalReceivables;
        this.totalInvestments = builder.totalInvestments;
        this.totalAssets = builder.totalAssets;
        this.totalLiabilities = builder.totalLiabilities;
    }
    
    public BigDecimal getGrossAssetValueAfterTax()
    {
        return grossAssetValueAfterTax;
    }
    
    public BigDecimal getGrossAssetValueBeforeTax()
    {
        return grossAssetValueBeforeTax;
    }
    
    public BigDecimal getTotalReceivables()
    {
        return totalReceivables;
    }
    
    public BigDecimal getTotalInvestments()
    {
        return totalInvestments;
    }
    
    public BigDecimal getTotalAssets()
    {
        return totalAssets;
    }
    
    public BigDecimal getTotalLiabilities()
    {
        return totalLiabilities;
    }
    
    @Override
    public String toString()
    {
        return ToStringBuilder.reflectionToString(this, ToStringStyle.SHORT_PREFIX_STYLE);
    }
    
 
 //inner builder class
    public static class Builder
    {
        private BigDecimal grossAssetValueAfterTax;
        private BigDecimal grossAssetValueBeforeTax;
        private BigDecimal totalReceivables;
        private BigDecimal totalInvestments;
        private BigDecimal totalAssets;
        private BigDecimal totalLiabilities;
        
        // add more
        
        public Builder setGrossAssetValueAfterTax(BigDecimal grossAssetValueAfterTax)
        {
            this.grossAssetValueAfterTax = grossAssetValueAfterTax;
            return this;
        }
        
        public Builder setGrossAssetValueBeforeTax(BigDecimal grossAssetValueBeforeTax)
        {
            this.grossAssetValueBeforeTax = grossAssetValueBeforeTax;
            return this;
        }
        
        public Builder setTotalReceivables(BigDecimal totalReceivables)
        {
            this.totalReceivables = totalReceivables;
            return this;
        }
        
        public Builder setTotalInvestments(BigDecimal totalInvestments)
        {
            this.totalInvestments = totalInvestments;
            return this;
        }
        
        public Builder setTotalAssets(BigDecimal totalAssets)
        {
            this.totalAssets = totalAssets;
            return this;
        }
        
        public Builder setTotalLiabilities(BigDecimal totalLiabilities)
        {
            this.totalLiabilities = totalLiabilities;
            return this;
        }
        
        public NetAsset build()
        {
            return new NetAsset(this);
        }
    }
    
}


To use this class

  NetAsset.Builder builder = new NetAsset.Builder();
  builder.setGrossAssetValueBeforeTax(BigDecimal.valueOf("3500.00"))
         .setGrossAssetValueAfterTax(BigDecimal.valueOf("500.00"))
   .setTotalAssets(BigDecimal.valueOf("3500.00"))
         .setTotalReceivables(BigDecimal.valueOf("2500.00"));     


or

return NetAsset.EMPTY;


Example 2: The Mock objects library classes.

m.expects(once())
    .method("method1")
    .with(eq(1), eq(2))
    .returns("someResponse");


Example 3: The StringBuilder class.

  return new StringBuilder("initial text")
            .append("more text")
   .append("some more text").toString();



Example 4: Apache Camel route builders.

   private void configureJobSweeperRoute()
   {
         from(TIMER_START_UP)
              .routeId("JobRecovery")
              .delay(RECOVERY_JOB_KICKIN_DELAY)
              .log(INFO, "Start checking incompleted jobs on start up")
              .bean(recoveryService, "startUpJobRecovery")
              .end();

    }


So, it is very widely used.

Other design patterns - real life examples

Labels:

Sep 18, 2013

AngularJS communicating between controllers



The previous posts covered  AngularJS big picture : Overview and  Working with Angular JS and jQuery UI : writing a custome directive. Let's look at inter controller communication in this blog post.

Q. How do you communicate between controllers in AngularJS?
A. There are scenarios where you want to communicate between controllers. For example, when the submit button is clicked on the parent controller, some values need to be passed to the child controller to show or hide a button in the child form. In AngularJS you can do this with $watch and $broadcast on the parent controller and $on on the child controller.


$watch(watchExpression, listener, objectEquality) : Registers a listener callback to be executed whenever the watchExpression changes.

$broadcast(name, args) : Dispatches an event name downwards to all child scopes (and their children) notifying the registered ng.$rootScope.Scope#$on listeners.

Here is the sample code:


   $scope.buttonClicked = 'N';

   //invoked when $scope.buttonClicked value changes
   $scope.$watch('buttonClicked', function(message) {
  //pass val = 'Y'
  if (message != null) {
   $scope.$broadcast('buttonClicked', {
     "val" : message
   });
   $scope.buttonClicked = 'N';
  }
 });
 
 //when submit button is clicked
 $scope.onParentSubmitButtonClick = function() {
  $scope.buttonClicked = 'Y';
  if ($scope.clientId && $scope.valuationDate) {
   $scope.httpError = null;
    $scope.getCalcStatuses();
   } else {
    $scope.httpError = "Client id or valuation date can not be empty !!";
   }

 };
    


Now, in the child controller, you want to pass the value "val" to indicate that "submit" button has been clicked. "$scope.$broadcast" invokes $scope.$on on the child controllers.

  $scope.$on('buttonClicked', function(event, args) {
  if (args.val == 'Y') {
   $scope.filterText = null;
  }
   
  $timeout(function() {
   $scope.isReleasable(); 
   $scope.isSavable();
          console.log('update with timeout fired');
     }, 2000);
     
  $scope.isReleasable = function() {
   if ($scope.calcViewStatuses != null) { 
    if ($scope.calcViewStatuses.ragStatus == 'GREEN' && $scope.calcViewStatuses.releaseStatus != 'RELEASED') {
     $scope.showReleaseButton = true;
     } else {
     $scope.showReleaseButton = false;
    }
   }
  };
    
    
  $scope.isSavable = function() {
   if ($scope.calcViewStatuses != null) { 
    if ($scope.calcViewStatuses.releaseStatus == 'RELEASED') {
     $scope.showSaveButton = false;
    } else {
     $scope.showSaveButton = true;
    }
   }
  };
   
 });
    


If you want to do the reverse, i.e. communicate from child to parent, you use the $scope.$emit.

$emit(name, args): Dispatches an event name upwards through the scope hierarchy notifying the registered ng.$rootScope.Scope#$on listeners.


Labels: ,

Sep 17, 2013

Google Guava library handy methods to write your Comparators for sorting

Sorting objects in a collection key in presenting those objects in GUI or report like PDF, etc. In Java you use a Comparator interface or the Comparable interface to define the custom sorting logic. I hava covered this in a number of following blog posts.
 Recently, I had the opportunity to work with a number of Google Guava libraries and its comparator  came handy to write a more concise code to get the same thing done. Working with Java Collection using Gauva was covered with examples.

Step 1: The Guava library dependency in pom.xml file.

<!--  Google GUAVA -->
<dependency>
 <groupId>com.google.guava</groupId>
 <artifactId>guava</artifactId>
  <version>13.0.1</version>
</dependency>


Step 2: Here is a sample ReportKey value object class that uses Apache common librarie's utility methods for equals( ), hashCode( ), toString( ), and compareTo( ) methods. Implementing the Comparable interface and providing the compareTo method provides natural ordering for the ReportKey class. It is also a best pracrice to define your key class as an immutable object. Defensive copying is used to make it immutable.

package com.myapp.reporting;

import java.util.Date;

import org.apache.commons.lang.builder.CompareToBuilder;
import org.apache.commons.lang.builder.EqualsBuilder;
import org.apache.commons.lang.builder.HashCodeBuilder;
import org.apache.commons.lang.builder.ToStringBuilder;
import org.apache.commons.lang.builder.ToStringStyle;
import org.springframework.util.Assert;

public class ReportKey implements Comparable<ReportKey>
{    
    private String clientId;
    private Date valuationDate;
    
    public ReportKey()
    {
    }
    
    private ReportKey(String clientId, Date valuationDate)
    {
        this.clientId = clientId;
        this.valuationDate = new Date(valuationDate.getTime()); // defensive
                                                                // copy
    }
    
    public static ReportKey newInstance(String clientId, Date valuationDate)
    {
        Assert.notNull(clientId);
        Assert.notNull(valuationDate);
        return new ReportKey(clientId, valuationDate);
    }
    
    public String getClientId()
    {
        return clientId;
    }
    
    public Date getValuationDate()
    {
        return new Date(valuationDate.getTime()); // defensive copy
    }
    
    @Override
    public int hashCode()
    {
        return new HashCodeBuilder().append(clientId).append(valuationDate).toHashCode();
    }
    
    @Override
    public boolean equals(final Object obj)
    {
        if (obj instanceof ReportKey)
        {
            final ReportKey other = (ReportKey) obj;
            return new EqualsBuilder().append(clientId, other.clientId).append(valuationDate, other.valuationDate)
                    .isEquals();
        }
        return false;
    }
    
    @Override
    public String toString()
    {
        return ToStringBuilder.reflectionToString(this, ToStringStyle.SHORT_PREFIX_STYLE);
    }
    
    @Override
    public int compareTo(ReportKey reportKey)
    {
        return new CompareToBuilder().append(this.clientId, reportKey.clientId)
                .append(this.valuationDate, reportKey.valuationDate).toComparison();
    }
}



Step 3: The above natual ordering sorts by clientId and valuationDate in ascending order. What if you ant to sort it by clientId in ascending order and by valuationDate in descending order? Here is sample anonymous class using Google's Gauva library.

List<ReportKey> reportKeys = (List<ReportKey>) reportService.find();
Collections.sort(reportKeys, new Comparator<ReportKey>()
{
    @Override
    public int compare(ReportKey o1, ReportKey o2)
    {
        return ComparisonChain.start()
                .compare(o1.getClientId(), o2.getClientId())
                .compare(o1.getValuationDate(), o2.getValuationDate(), Ordering.natural().reverse())
                .result();
    }
});


Labels:

Sep 16, 2013

AngularJS big picture : Overview

This is for the AngularJS starters. You will see handy diagrams and third-party links to get started with Angular JS, which is getting so much attention.

Q. Can you give a big picture of AngularJS highlighting its key components?
A. A good diagram is worth 1000 words.



A good link to get an overview of AngularJS. Once you get a high level understanding, go to YouTube and search for excellent AngularJS video tutorials to get started.


Q. What is a scope in AngularJS?
A. scope is an object that refers to the application model. It is the glue between application controller and the view. Both the controllers and directives have reference to the scope, but not with each other. It is an execution context for expressions and arranged in hierarchical structure. Scopes can watch expressions and propagate events.

Q. Can you explain the concept of scope hierachy? How many scopes can an application have?
A. Each Angular application has exactly one root scope, but may have several child scopes. The application can have multiple scopes, because child controllers and some directives create new child scopes. When new scopes are created, they are added as children of their parent scope. This creates a hierarchical structure similar to the DOM where they're attached.

When Angular evaluates a bound variable like say {{firstName}}, it first looks at the scope associated with the given element for the firstName property. If no such property is found, it searches the parent scope and so on until the root scope is reached. In JavaScript this behaviour is known as prototypical inheritance, and child scopes prototypically inherit from their parents. The reverse is not true. I.e. the parent can't see it's children's bound properties.

AnagularJS Interview Questions and Answers



If you are just starting with angularjs

Q. What do you understand by the term two way data binding in AngularJS?
A. The AngularJS ref and Overview

Q. Why is AngularJS popular?
A. Why does AngularJS rock?

The above references should get you started and prepare for key interview questions on AngularJS. Stay tuned for more AngularJS blog posts. Ther are other MVW frameworks like Backbone. Ember, etc.

Labels:

Sep 13, 2013

Defining Hibernate entities with auditable fields, soft delete field, optimistic locking field, etc

There are certain generic columns that database tables have like
  1. Auto generated identity columns.
  2. Auditing columns like creadedDtTm, createdBy, modifiedDtTm, and modifiedBy.
  3. Soft delete or logical delete flags like inactive 'Y' or 'N'.
  4. Optimistic locking detection based on columns like Timestamp or version number.
These logic can be mapped in a generic way using hibernate so that all the other entities can reuse. Let's look at some sample code using Hibernate annotations.

1. Identity columns.

package com.myapp.common;

import static javax.persistence.GenerationType.IDENTITY;

import javax.persistence.Column;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.MappedSuperclass;

@SuppressWarnings("serial")
@MappedSuperclass
public class StandardIdLongBaseEntity  extends AuditableBaseEntity<long>
{
    @Id
    @GeneratedValue(strategy = IDENTITY)
    @Column(name = "ID", unique = true, nullable = false, precision = 18, scale = 0) // name is almost always overridden
    @Override
    public Long getId() {
        return super.getId();
    }
}


2. Audit fields and optimistic locking detection using timestamp. Firstly the "MappedSuperclass"

package com.myapp.common;

import javax.persistence.Column;
import javax.persistence.Embedded;
import javax.persistence.MappedSuperclass;
import javax.persistence.Version;

import org.apache.commons.lang.builder.ToStringBuilder;
import org.apache.commons.lang.builder.ToStringStyle;
import org.hibernate.annotations.Generated;
import org.hibernate.annotations.GenerationTime;
import org.hibernate.annotations.TypeDef;
import org.hibernate.annotations.TypeDefs;

@SuppressWarnings("serial")
@MappedSuperclass
public abstract class AuditableBaseEntity<pk> extends BaseEntity<pk>
{
    private byte[] timestamp;
 private StandardAuditFields auditFields = new StandardAuditFields();

    @Version    
    @Column(name = "Timestamp", insertable = false, updatable = false, unique = true, nullable = false)
    @Generated(GenerationTime.ALWAYS)
 public byte[] getTimestamp() {
  return timestamp;
 }


 public void setTimestamp(byte[] timestamp) {
  this.timestamp = timestamp;
 }
 
 @Embedded
 public StandardAuditFields getAuditFields() {
     if (auditFields == null)
     {
         // TODO: Not thread safe. 
         auditFields = new StandardAuditFields();
     }
  return auditFields;
 }

 public void setAuditFields(StandardAuditFields auditFields) {
  this.auditFields = auditFields;
 }

    @Override
    public String toString()
    {
        return ToStringBuilder.reflectionToString(this, ToStringStyle.SHORT_PREFIX_STYLE, true);
    }
}


Next, the "Embeddable" class with fields for auditing.


package com.myapp.common;

import java.util.Date;

import javax.persistence.Column;
import javax.persistence.Embeddable;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import javax.persistence.Transient;

import org.apache.commons.lang.builder.ToStringBuilder;
import org.apache.commons.lang.builder.ToStringStyle;
import org.hibernate.annotations.Generated;
import org.hibernate.annotations.GenerationTime;

@Embeddable
public class StandardAuditFields {
 private String createdBy;
 private Date createdDtTm;
    private Date modifiedDtTm;
    private String modifiedBy;

   
 @Temporal(TemporalType.TIMESTAMP)
 @Generated(GenerationTime.INSERT)
    @Column(name="CreatedDtTm", length=23, insertable=true, updatable=false)
 public Date getCreatedDtTm() {
  return createdDtTm;
 }

 public void setCreatedDtTm(Date createdDtTm) {
  this.createdDtTm = createdDtTm;
 }

 @Temporal(TemporalType.TIMESTAMP)
 @Generated(GenerationTime.ALWAYS)
    @Column(name="ModifiedDtTm", length=23, insertable=false, updatable=false)
 public Date getModifiedDtTm() {
  return modifiedDtTm;
 }

 public void setModifiedDtTm(Date modifiedDtTm) {
  this.modifiedDtTm = modifiedDtTm;
 }

 @Column(name="ModifiedBy", length=30, insertable=false, updatable=false)
 public String getModifiedBy() {
  return modifiedBy;
 }

 public void setModifiedBy(String modifiedBy) {
  this.modifiedBy = modifiedBy;
 }

 @Override
 public String toString()
 {
     return ToStringBuilder.reflectionToString(this, ToStringStyle.SHORT_PREFIX_STYLE);
 }
}

3. Mapping soft delete.

package com.myapp.common;

import javax.persistence.Column;
import javax.persistence.MappedSuperclass;

import org.hibernate.annotations.Type;
import org.hibernate.annotations.Where;

@SuppressWarnings("serial")
@MappedSuperclass
@Where(clause = "inactiveFlag = 'N'")
public class BaseSoftDeleteableLongEntity extends StandardIdLongBaseEntity
{
    private boolean isSoftDeleted;
    
    @Column(name = "InactiveFlag", nullable = false, length = 1)
    @Type(type = "yes_no")
    public boolean isSoftDeleted()
    {
        return isSoftDeleted;
    }
    
    public void setSoftDeleted(boolean isSoftDeleted)
    {
        this.isSoftDeleted = isSoftDeleted;
    }
   
}

4 Finally, defining your entity.

package com.myapp.batch;

import com.google.common.base.Objects;
import java.util.Date;

import javax.persistence.AttributeOverride;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.EnumType;
import javax.persistence.Enumerated;
import javax.persistence.Table;
import javax.persistence.Transient;

import org.apache.commons.lang.StringUtils;
import org.codehaus.jackson.annotate.JsonIgnoreProperties;
import org.hibernate.annotations.SQLDelete;
import org.hibernate.annotations.Type;
import org.hibernate.annotations.TypeDef;
import org.hibernate.annotations.TypeDefs;
import org.hibernate.annotations.Where;

@Entity
@Table(name = "Tbl_Batch_Run", schema = "dbo", catalog = "sne_kath")
@AttributeOverride(name = "id", column = @Column(name = "Tbl_Batch_RunId"))
@Where(clause = "inactiveFlag = 'N'")
@SQLDelete(sql = "UPDATE Tbl_Batch_Run set inactiveFlag = 'Y' WHERE Tbl_Batch_RunId = ? and timestamp = ?") // optimistic locking
@JsonIgnoreProperties(
{
    "auditFields", "id", "softDeleted"})
@TypeDefs(
{@TypeDef(name = "BatchTypeCd", typeClass = BatchTypeCdType.class)}) // user defined types
public class BatchRun extends BaseSoftDeleteableLongEntity
{
    
    private String entity;
    private long batchId;
    private BatchTypeCd batchTypeCd;
    private Status status;
    
  
    /**
     * Required constructor for JSON Marshal
     */
    public BatchRun()
    {
    }
    
    public BatchRun(BatchRun aBatchRun)
    {
        this(aBatchRun.getEntity(), aBatchRun.getBatchId(), aBatchRun.getBatchTypeCd(), aBatchRun.getStatus());
    }
    

    public BatchRun(String entity, long batchId, BatchTypeCd batchTypeCd, Status status,)
    {
        this.entity = entity;
        this.batchId = batchId;
        this.batchTypeCd = batchTypeCd;
        this.status = status;
    }
    
    @Column(name = "Entity", nullable = false)
    public String getEntity()
    {
        return this.entity;
    }
    
    public void setEntity(String entity)
    {
        this.entity = entity;
    }
    
    @Column(name = "BatchId", nullable = false)
    public long getBatchId()
    {
        return this.batchId;
    }
    
    public void setBatchId(long batchId)
    {
        this.batchId = batchId;
    }
    
    @Enumerated(EnumType.STRING)
    @Column(name = "Status", nullable = false, length = 30)
    public Status getStatus()
    {
        return status;
    }
    
    public void setStatus(Status status)
    {
        this.status = status;
    }
    
    
    @Type(type = "BatchTypeCd")
    @Column(name = "BatchType", nullable = false, length = 30)
    public BatchTypeCd getBatchTypeCd()
    {
        return batchTypeCd;
    }
    
    public void setBatchTypeCd(BatchTypeCd batchTypeCd)
    {
        this.batchTypeCd = batchTypeCd;
    }
    
    /**
     * Business key for this object is the batchid, entity, valuationDate and batchTypeCd
     * @see java.lang.Object#equals(java.lang.Object)
     */
    @Override
    public boolean equals(Object obj)
    {
        if (obj == null)
        {
            return false;
        }
        if (getClass() != obj.getClass())
        {
            return false;
        }
        
        final BatchRun other = (BatchRun) obj;
        
        return Objects.equal(batchId, other.batchId) 
                && Objects.equal(entity, other.entity)
                && Objects.equal(batchTypeCd, other.batchTypeCd);
    }
    
    @Override
    public int hashCode()
    {
        return Objects.hashCode(batchId, entity, valuationDate, batchTypeCd);
    }
    
    @Override
    public String toString()
    {
        return Objects.toStringHelper(this)
                .addValue(batchId)
                .addValue(entity)
                .addValue(batchTypeCd)
                .toString();
    }
}

Labels:

Sep 12, 2013

Working with Angular JS and jQuery UI : resizable TextArea to overcome IE limitation

AngularJS is a popular MVW (Model View Whatever) framework. Recently had an opportunity to test drive Angular JS for GUI development retrieving data via RESTful web service calls. The JavaScript based GUI frameworks like Angular JS, Backbone, etc will becom more poular and replace JSF. So, it really pays off to lean AngularJS if you like developing GUIs. If you go to YouTube, you will find a number of good beginner's tutorials to get started.


Q. What is a directive in AngularJS?
A. Directives extends HTML. During DOM compilation directives are matched against the HTML and executed. This allows directives to register behaviour, or transform the DOM. ng-app, ng-controller, ng-model, etc are directives. The directives can be placed in element names, attributes, class names, as well as comments. Directives are defined with camel cased names such as ngApp and invoked by translating the camel case name into snake case with these special characters :, -, or _. For example ng-ap p as in <html ng-app>




Q. When do you need to create your own directives?  How will you go about creating a custom directive in AngularJS?
A. There are instances where you want to use jQuery UI plugins. Reecently, I had to use the the jQuery Resizable plugin with angular to resize my TextArea in IE 8 as it is the standard browser used by our business and operational staff. Here are some code samples to get AngularJS and jQuery to work together.  By default, the Angular JS is shipped with a lite version of jQuery, but not with the UI plugins.



Step 1: You need to define directives.  Directives are a way to teach HTML new tricks. During DOM compilation directives are matched against the HTML and executed. I am using RequireJS to manage dependencies. here is myTextAreaWithModel.js file


'use strict';

define([ 'jqueryui' ], function() {

 
 function myTextAreaWithModel() {
  return {
   require: 'ngModel',
   // Restrict it to be an attribute in this case
   restrict : 'A',
   // responsible for registering DOM listeners as well as updating the
   // DOM
   link : function($scope, $element, $attrs) {
    jQuery(function() {
     jQuery("textarea.resizableAreaWithModel").resizable();
    });
   }
  };
 }

 return myTextAreaWithModel;
});


Step 2:  A sample bootstrapping JS file that uses require js to manage dependencies. The key here is to see how jquery-ui is loaded. You can choose to ignore the rest.

'use strict';

/**
 * Configure JS file paths and dependencies
 */
var requireConf = {
    baseUrl: '.',   // This will be the path to portal.html
    shim: {
        'angular'             : { deps: ['jquery'] },
        'jqueryui'            : { deps: ['jquery']},
        'bootstrap'           : { deps: ['jquery'] },
        'portal/portalCtrl'   : { deps: ['angular'] }
    },
    paths: {
        jquery    : 'lib/jquery/jquery',
        jqueryui  : 'lib/jquery/jquery-ui',
        angular   : 'lib/angular/angular-module',
        bootstrap : 'lib/bootstrap/js/bootstrap',
        text      : 'lib/require/plugins/text'
    },
    waitSeconds: 0,                 // Disable the RequireJS timeout
    urlArgs: ((myapp.debug) ? '' : 'v=' + (((new Date()).getTime() + '').substr(2,8)))   // URL cache breaker changes every second - TODO: use a version number instead : '';
};

require.config(requireConf);

/**
 * Load JS resources for the portal (but not for apps), then bootstrap Angular.
 */
require([
    'jquery',
    'angular',
    'portal/portalCtrl',
 
], function (jq, angular, portalCtrl) {

    angular.element(document).ready(function() {

        // Load the root controller for the page
        angular.module('portalModule.controller', [])
            .controller('portalCtrl', portalCtrl);

        // Load all angular style resources
        angular.module('portalModule', [
            'portalModule.controller',
            'portalModule.directives',
            'portalModule.services',
            'portalModule.filter'
        ]);

        // Bootstrap angular, this needs to be after the html page and the various JS resources defined above have loaded.
        angular.bootstrap(document, ['portalModule']);
    });
});


Step 3: Bootstrapping the "myTextAreaWithModel" using require js framework.

'use strict';

define([
    'angular',
    'utils/directives/myTextAreaWithModel'
], function (angular, myTextAreaWithModel) {

    angular.module('portalModule.directives', [])
         .directive('myTextAreaWithModel', myTextAreaWithModel);
});


Step 4: Finally the HTML code.

    ....
 <td width="30%">
  <textarea class="resizableAreaWithModel comments" 
     name="comments" ng-model="myAppStatus.comment" 
     jp-text-area-with-model 
  />
  </td>
  ....


Directives in angularjs are very powerful.


Labels: ,

Sep 10, 2013

Agile development methodology: theme, epic and user story

Agile Development Interview Questions and Answers

Agile Development methodology Q1 - Q6 Agile Development methodology Q7 - Q16 Agile methodology: theme, epic and user story Pros and cons of agile development methodology and principles

This blog post extends and compliments Agile methodology or practices interview questions and answers

Q. What is the difference between agile theme, epic and story?
A. 

  • A theme is an objective that may span projects and products. Themes can be broken down into sub-themes, which are more likely to be product-specific. At its most granular form, a theme can be an epic.
  • An epic is a group of related user stories. An epic needs to be broken down into a user story before it is sized using fibonacci number (eXtra Smal [XS=1 pt] Small [S = 2 pt], Medium [M = 3], Large (L = 5), XtraLarge (XL = 8) , XtraXtraLarge [XXL = 13pts],  XtraXtraXtraLarge [XXXL = 21 pts] ) and introduced into a sprint. The sizing is similar to the T-shirt sizes. These points are also known as the velocity points to monitor progress.
  • A user story is an Independent, Negotiable, Valuable, Estimatable, Small, Testable requirement, which is abbreviated to “INVEST”. Even though stories are independent, they have no direct dependencies with other requirements and user stories may be combined into epics when represented on a product road map. User stories need to be defined prior to sprint planning in ABC (Accelerated Business Case) sessions where the development teams, QA (i.e. testing) teams and product managers can use them to discuss, size and prioritise at sprint-level. User stories will often be broken down into tasks during the sprint planning Process unless the stories are small enough to be consumed on their own. Tools like "MindMap" is used to capture the stories in the form of COS (i.e. Condition Of Staisfaction).  
  • The sized cards are prioritized interms of its value add to achieve the MVP (Minimum Viable Product) defined by the product manager and the business owners.



Q. How is an agile project monitored for progress?
A. Any one who has worked on an agile project would have come across thes key terms:

  • Colocation
  • Frequent delivery
  • Daily standups
  • Timeboxed tasks

The best evidence that a software project is on track is working software, preferably deployed to production.

Secondly, a burn down chart is used to present the progress to the management. Each sprint is basically 2 weeks and this is plotted on the X axis. The Y axis will have the velocity points. In each Sprint depending on the team size, a number of sized up cards are picked and the individual points are added up. For example say, 40 points. This chart is about how quickly you burn through the stories. These graphs can be plotted manually or via tools like Excel spreadsheet or JIRA.




Velocity is the key to agile project management.

Q. What are different roles in an agile project?
A.


Mandatory roles:

Team lead:  This role, called “Scrum Master” in Scrum or team coach or project lead in other methods
Team member: This role, sometimes referred to as developer or programmer, is responsible for the creation and delivery of a system.  This includes modeling, programming, testing, and release activities, as well as others.
Product owner:  The product owner is responsible for the prioritized work item list
Stakeholder:  is anyone who is a direct user, indirect user, manager of users, senior manager, and operations staff member.


Optional roles that are typically adopted only on very complex projects 

Technical experts: Sometimes the team needs the help of technical experts, such as build masters to set up their build scripts or an agile DBA to help design and test their database.
Domain experts:  Sometimes the product owner will sometimes bring in domain experts to work with the team
Independent tester: to validate functional and non-functional testing. For example, security testing, performance testing, cross browser compatibility testing, etc.


Labels:

Sep 9, 2013

Web (i.e. HTTP) security vulnerabilities - HttpOnly attribute

Q. What do you understand by the term "HttpOnly" attribute in HTTP cookies?
A. Here is a sample PEN test report comment:

"During the application test, it was detected that the tested web application set a session cookie without the "HttpOnly" attribute. Since this session cookie does not contain the "HttpOnly" attribute, it might be accessed by a malicous script injected to the site (i.e XSS), and its value can be stolen. Any information stored in session tokens may be stolen and used later for identity theft or user impersonation"

When you tag a cookie with the "HttpOnly" flag, it tells the browser that this particular cookie should only be accessed by the server. Any attempt to access the cookie from client script is strictly forbidden. This will works woth  a modern web browser that supports and actually implements "HttpOnly" functionality correctly. The most modern browsers do support the "HttpOnly" flag. This flag will make more difficult to pull off XSS attacks.


Q. What do you understand by the term "Secure" attribute in HTTP cookies?
A. Here is a sample PEN test report comment:

"During the application test, it was detected that the tested web application set a cookie without the "secure" attribute, during an encrypted session. Since this cookie does not contain the "secure" attribute, it might also be sent to the site during an unencrypted session. Any information such as cookies, session tokens or user credentials that are sent to the server as clear text, may be stolen and used later for identity theft or user impersonation."

Remedy: Basically the only required attribute for the cookie is the "name" field. Common optional attributes are: "comment", "domain", "path", etc. The "secure" and "HttpOnly" attributes must be set accordingly in order to prevent a cookie from being sent unencrypted or modified respectively.

Tip: You can use the Firefox plugin Fire cookie to view these attributes.

Labels: