Saturday, July 31, 2010

Creating Message Driven Bean with NetBeans/GlassFish

This is an example for Simple message driven bean with GlassFish server and NetBeans. We can use message driven bean to asynchronously process messages. Although you can use session bean to synchronously process messages but it is bit expensive to block message processing with synchronization since it is eating server resources. Following are the summery of steps for this example.

· Creating web application with NetBeans

· Creative required JMS connection factory and queue in the GlassFish server.

· Creating Servlet (MessageProducerServlet) to put messages into the JMS queue.

· Creating message driven bean (SimpleMessageBean) to process messages from JMS queue

The architecture of the example

With the MessageProducerServlet we are producing messages and put them into the JMS queue. The SimpleMessageBean is listing to the JMS queue and ones the message arrived the onMassage() on SimpleMessageBean is invoked.

Creating web application with NetBeans

Open NetBeans IDE and File à New Project à Java Web à Web Application

Creative required JMS connection factory and queue in the GlassFish server.

Open the browser for url http://localhost:4848/ and you will directed to the GlassFish administrator UI. First we need to create JMS ConnectionFactory in the server. Go to resources à JMS resources à Connection Factories à New, give name as jms/MyConnectionFactory and select resource type as ‘javax.jms.ConnectionFactory’.

Then we need to create JMS queue and go to resources à JMS resources à Destination Resources à New, give name as jms/MyQueue and select resource type as ‘javax.jms.Queue’ and Destination name as ‘PhysicalQueue’.

We need to create the ConnectionFactory and queue on the GlassFish server. Since server to server default ConnectionFactory and queue is changing I am not using the defaults.

Creating Servlet (MessageProducerServlet) to put messages into the JMS queue.

I choose servlet to put messages into the JMS queue because it is very easy when reffering ConnectionFactory and Queue. We are referring ConnectionFactory and Queue with resource annotation (dependency injection) so we need to run this on the GlassFish server. If we are using outside GlassFish server we should do JNDI lookup.

To create Servlet for the project right click the project and create Servlet and add following code into it. When creating the servlet remember to add servlet information to the web.xml.



package org.sun.exam.message.producer;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.annotation.Resource;
import javax.jms.Connection;
import javax.jms.ConnectionFactory;
import javax.jms.MessageProducer;
import javax.jms.Queue;
import javax.jms.Session;
import javax.jms.TextMessage;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class MessageProducerServlet extends HttpServlet {
@Resource(mappedName = "jms/MyConnectionFactory")
private ConnectionFactory connectionFactory;
@Resource(mappedName = "jms/MyQueue")
private Queue queue;

protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
try {
sendMessages();
} catch (Exception ex) {
Logger.getLogger(MessageProducerServlet.class.getName()).log(Level.SEVERE, null, ex);
}
}

private int NUM_MSGS = 3;

public void sendMessages() throws Exception {
Connection connection = connectionFactory.createConnection();
Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
MessageProducer messageProducer = session.createProducer(queue);
TextMessage message = session.createTextMessage();

for (int i = 0; i < NUM_MSGS; i++) {
message.setText("This is message " + (i + 1));
System.out.println("Sending message: " + message.getText());
messageProducer.send(message);
}
}



Creating message driven bean (SimpleMessageBean) to process messages from JMS queue

Our message driven bean does not directly communicate with Servlet, it is using JMS queue to listen to messages. To create message driven bean for the project right click the project and create new message driven bean and add following code into it.


package org.sun.exam.message.bean;

import javax.annotation.Resource;
import javax.ejb.ActivationConfigProperty;
import javax.ejb.MessageDriven;
import javax.ejb.MessageDrivenContext;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageListener;
import javax.jms.TextMessage;

@MessageDriven(mappedName = "jms/MyQueue", activationConfig = {
@ActivationConfigProperty(propertyName = "acknowledgeMode", propertyValue = "Auto-acknowledge"),
@ActivationConfigProperty(propertyName = "destinationType", propertyValue = "javax.jms.Queue")
})
public class SimpleMessageBean implements MessageListener {

@Resource
private MessageDrivenContext mdc;

public SimpleMessageBean() {
}

public void onMessage(Message inMessage) {
TextMessage msg = null;
try {
if (inMessage instanceof TextMessage) {
msg = (TextMessage) inMessage;
System.out.println("MESSAGE BEAN: Message received: " + msg.getText());
//logger.info("MESSAGE BEAN: Message received: " + msg.getText());
} else {
System.out.println("Message of wrong type: " + inMessage.getClass().getName());
//logger.warning("Message of wrong type: " + inMessage.getClass().getName());
}
} catch (JMSException e) {
e.printStackTrace();
mdc.setRollbackOnly();
} catch (Throwable te) {
te.printStackTrace();
}
}
}

In this example with the message driven bean we have used asynchronous message consumption. When is comes to JMS there are two types of consumers,
  • Synchronously: A subscriber or a receiver explicitly fetches the message from the destination by calling the receive method. The receive method can block until a message arrives or can time out if a message does not arrive within a specified time limit.

  • Asynchronously: A client can register a message listener with a consumer. A message listener is similar to an event listener. Whenever a message arrives at the destination, the JMS provider delivers the message by calling the listener’s onMessage method, which acts on the contents of the message


  • Note:

    This example based on Java EE6 tutorial and in the reference you can find the link.

    Reference:

    http://download-llnw.oracle.com/javaee/6/tutorial/doc/bnbpk.html

    EJB 3 - Tutorial

    Enterprise Java bean is a server-side component that encapsulates the business logic of an application. EJB can be be used when you need a scalability, data/transaction integrity and if you need to add thin clients for your application.
    EJB container provides system-level services to enterprise beans, the bean developer can concentrate on solving business problems. The EJB container, rather than the bean developer, is responsible for system-level services such as transaction management and security authorization.

    There are two types of EJBs in EJB3
    • Session Bean : Performs a task for a client; optionally may implement a web service
    • Message-Driven Bean : Acts as a listener for a particular messaging type, such as the Java Message Service API
    There three types of Session beans as well,


    • Stateful Session Beans : The instance variables of this kind of bean represent the state of a unique client-bean session. A session bean is not shared; it can have only one client,

    • Stateless Session Beans : When a client invokes the methods of a stateless bean, the bean’s instance variables may contain a state specific to that client, but only for the duration of the invocation. Can be shared across multiple clients.

    • Singleton Session Beans : A singleton session bean is instantiated once per application, and exists for the life cycle of the application
    A message-driven bean is an enterprise bean that allows Java EE applications to process messages asynchronously. It normally acts as a JMS message listener. Messages can be sent by any Java EE component or by a JMS application or system that does not use Java EE technology. Message-driven beans can process JMS messages or other kinds of messages. The most visible difference between message-driven beans and session beans is that clients do not access message-driven beans through interfaces.

    Creating a stateless Enterprise Bean with NetBeans

    We can create and deploy simple EJB with NetBeans and deploy it on glassfish server.


    • First create web application with NetBeans (File --> New Project --> Java Web --> Web Application).

    • Right click the project and add a Session Bean to it (New --> Session bean). This is a slateless session bean and you can add following code into it.
      package com.sun.tutorial.javaee.ejb;
      
      import java.math.BigDecimal;
      import javax.ejb.Stateless;
      
      @Stateless
      public class ConverterBean {
      
      private BigDecimal yenRate = new BigDecimal("115.3100");
      private BigDecimal euroRate = new BigDecimal("0.0071");
      
      public BigDecimal dollarToYen(BigDecimal dollars) {
        BigDecimal result = dollars.multiply(yenRate);
        return result.setScale(2, BigDecimal.ROUND_UP);
      }
      
      public BigDecimal yenToEuro(BigDecimal yen) {
        BigDecimal result = yen.multiply(euroRate);
        return result.setScale(2, BigDecimal.ROUND_UP);
      }
      
      }

    • Add a Servelt to the project (New --> Servlet).We use this servlet to call our EJB and to display result in the web browser. Add following code into the servlet.
      package converter.web;
      
      import com.sun.tutorial.javaee.ejb.ConverterBean;
      import java.io.IOException;
      import java.io.PrintWriter;
      import java.math.BigDecimal;
      import javax.ejb.EJB;
      import javax.servlet.ServletException;
      import javax.servlet.http.HttpServlet;
      import javax.servlet.http.HttpServletRequest;
      import javax.servlet.http.HttpServletResponse;
      
      public class ConverterServlet extends HttpServlet {
      
       @EJB
       ConverterBean converterBean ;
      
       public void doGet(HttpServletRequest request, HttpServletResponse response)
               throws ServletException, IOException {
      
           BigDecimal euroAmount = performOperation(request);
      
           response.setContentType("text/html");
           PrintWriter pw = response.getWriter();
           pw.println(euroAmount);
       }
      
       public BigDecimal performOperation(HttpServletRequest request) {
           try {
               String amount = request.getParameter("amount");
               if (amount != null && amount.length() > 0) {
                   BigDecimal d = new BigDecimal(amount);
                   BigDecimal yenAmount = converterBean.dollarToYen(d);
      
                   // call the ConverterBean.yenToEuro() method to get the amount in Euros
                   BigDecimal euroAmount = converterBean.yenToEuro(yenAmount);
                   return euroAmount;
               }
           } catch (Exception e){
               System.out.println(e.getMessage());
           }
           return new BigDecimal(0);
       }
      }
      
      Here we are referring ConverterBean with @EJB annotation and it uses dependency injection to obtain a reference to ConverterBean .

    • Change the index.jsp to add text box and set form action to the Servlet. Modify Index.jsp as follows.
        <body>
            <form id="form1" action="ConverterServlet">
                < div >
                    <input id="amount" name="amount" type="text" />
                    <input id="Submit1" type="submit" value="submit"/>
                </div>
            </form>
        </body>
    • Changing the web.xml to route appropriate request to servlet. Add following content to web.xml inside web-app tag.

      <servlet>
     <servlet-name>ConverterServlet</servlet-name>
     <servlet-class>
     SimpleServlet
     </servlet-class>
     </servlet>
     <servlet-mapping>
     <servlet-name>ConverterServlet</servlet-name>
     <url-pattern>/converterServlet</url-pattern>
     </servlet-mapping>
    

    • Running the application: Run the application and go to the url 
    http://localhost:8080/<proj_name>/converterServlet

    References:

    Sunday, July 18, 2010

    The builder pattern

    Definition
    Separate the construction of a complex object from its representation so that the same construction process can create different representations.

    The Class diagram





    The implementation

    The computer builder is an abstract class (builder). The client use this abstract class to build the product.

    public abstract class ComputerBuilder
    {
    protected Computer computer;
    public Computer Computer
    {
    get { return computer; }
    }

    public abstract void BuildDisplay();
    public abstract void BuildMotherBoard();
    public abstract void BuildKeybord();
    public abstract void BuildHardDisk();
    public abstract void BuildPowerUnit();
    }

    The LaptopBuilder and DesktopBuilder are concrete builders and they create the real product parts and store them in the part composite structure.

    public class LaptopBuilder : ComputerBuilder
    {
    public LaptopBuilder()
    {
    computer = new Computer("Laptop Computer");
    }

    public override void BuildDisplay()
    {
    computer["display"] = "LCD integrated Display";
    }

    public override void BuildMotherBoard()
    {
    computer["mother_board"] = "Motherbord with centrino processor";
    }

    public override void BuildKeybord()
    {
    computer["keybord"] = "Integrated Keybord";
    }

    public override void BuildHardDisk()
    {
    computer["hard_disk"] = "Integrated Hard Disk";
    }

    public override void BuildPowerUnit()
    {
    computer["power_unit"] = "Integrated power unit";
    }
    }



    public class DesktopBuilder : ComputerBuilder
    {
    public DesktopBuilder()
    {
    computer = new Computer("Desktop Computer");
    }
    public override void BuildDisplay()
    {
    computer["display"] = "LCD separated Display";
    }

    public override void BuildMotherBoard()
    {
    computer["mother_board"] = "Motherbord with processor";
    }

    public override void BuildKeybord()
    {
    computer["keybord"] = "Separate Keybord";
    }

    public override void BuildHardDisk()
    {
    computer["hard_disk"] = "Hard Disk";
    }

    public override void BuildPowerUnit()
    {
    computer["power_unit"] = "Power unit";
    }
    }
    This is the product and concrete builder responsible for building this by building parts.

    public class Computer
    {
    private string _computerType;
    private Dictionary _parts = new Dictionary();
    public string this[string key]
    {
    get { return _parts[key]; }
    set { _parts[key] = value; }
    }
    public Computer(string computerType)
    {
    _computerType = computerType;
    }

    public void Show()
    {
    Console.WriteLine("\n---------------------------");
    Console.WriteLine("Computer Type: {0}", _computerType);
    Console.WriteLine(" Display : {0}", _parts["display"]);
    Console.WriteLine(" Motherbord : {0}", _parts["mother_board"]);
    Console.WriteLine(" Keybord: {0}", _parts["keybord"]);
    Console.WriteLine(" Hard Disk : {0}", _parts["hard_disk"]);
    Console.WriteLine(" Power unit : {0}", _parts["power_unit"]);
    }
    }

    The Shop (Director) construct the object using the builder interface.


    public class Shop
    {
    public void Construct(ComputerBuilder computerBuilder)
    {
    computerBuilder.BuildDisplay();
    computerBuilder.BuildHardDisk();
    computerBuilder.BuildKeybord();
    computerBuilder.BuildMotherBoard();
    computerBuilder.BuildPowerUnit();
    }
    }



    class Program
    {
    static void Main(string[] args)
    {
    ComputerBuilder computerBuilder;
    Shop shop = new Shop();
    computerBuilder = new LaptopBuilder();
    shop.Construct(computerBuilder);
    computerBuilder.Computer.Show();
    Console.ReadLine();
    }
    }


    The pattern can apply:
    • If the algorithm of creating complex objects should separate parts making how they are assembled.
    • If you need control over the construction

    Saturday, July 17, 2010

    Singleton pattern with with C# code example

    Definition
    The singleton patterns ensures a class has only one instance, and provide a global point of access it.

    More information
    To assure there is one and only one instance, first we can disable the object creation by making constructor private. Then secondly we can mark instance variable/method to static to ensure only one instance and to provide access point.

    The Instance() method is the method that return the singleton instance. We can mark this method as lock (syncronized) to make thread safe. But lock (syncronized) is not good for performance. So what are the other available options,
    • No worry about the Instance method if the performance is not important :P
    This is obvious, if the performance is not a critical factor then you can use syncronization.
    • Do the instance creation as eagerly created rather than a lazy created one
    Static constructors in C# are specified to execute only when an instance of the class is created or a static member is referenced, and to execute only once per AppDomain.
    • Use double check locking to reduce the use of syncronized Instance method
    C# you can easily do this but in Java you need to do this with Volatile keyword. Also you need Java 1.5 or higher version. Please see the reference for more details.


    Implementation

    This implementation is a non lazy implementation of the singleton pattern. This is a thread safe version.

    internal class Singleton
    {
    private static Singleton _instance = new Singleton();

    private string _property = "Singleton Property";

    private Singleton()
    {
    }

    public string Property
    {
    get { return _property; }
    set { _property = value; }
    }

    public static Singleton Instance
    {
    get { return _instance; }
    set { _instance = value; }
    }
    }

    This implementation is a lazy implementation of the singleton pattern. This is not a thread safe version.



    internal class SingletonLazy
    {
    private static SingletonLazy _instance;
    private string _property = "Singleton Property";

    private SingletonLazy()
    {
    }

    public string Property
    {
    get { return _property; }
    set { _property = value; }
    }

    public static SingletonLazy Instance()
    {
    if (_instance == null)
    {
    _instance = new SingletonLazy();
    }
    return _instance;
    }
    }

    This is the Main program to work with above classes.


    internal class Program
    {
    private static void Main(string[] args)
    {
    // The non lazy initialization
    Singleton nonLazySingleton1 = Singleton.Instance;
    Singleton nonLazySingleton2 = Singleton.Instance;
    nonLazySingleton1.Property = "The new Property";

    if (nonLazySingleton1.Property.Equals(nonLazySingleton2.Property))
    {
    Console.WriteLine("The non lazy singleton is successful");
    }

    // The lazy initialization
    SingletonLazy singletonLazy1 = SingletonLazy.Instance();
    SingletonLazy singletonLazy2 = SingletonLazy.Instance();
    singletonLazy2.Property = "The new Property";

    if (singletonLazy1.Property.Equals(singletonLazy2.Property))
    {
    Console.WriteLine("The lazy singleton is successful");
    }
    }
    }


    Reference:
    http://www.yoda.arachsys.com/csharp/singleton.html

    Factory Method with C# code example

    Definition
    The factory method pattern defines an interface for creating an object, but let subclasses decides which class to instantiate.



    The Class digram



    The implementation

    • Vehicle Factory :- Abstract Factory


    public abstract class VehicleFactory
    {
    public enum VehicleType
    {
    Car,
    Bicycle
    }

    public abstract Vehicle CreateVehicle(VehicleType vehicleType);

    public Vehicle OrderVehicle(VehicleType vehicleType)
    {
    Console.WriteLine("You are Ordering a " + vehicleType);
    return CreateVehicle(vehicleType);
    }
    }


    • Bicycle, Car Factory :- Concrete Factory



    • public class BicycleFactory : VehicleFactory
      {
      public override Vehicle CreateVehicle(VehicleType vehicleType)
      {
      Console.WriteLine("Creating a " + vehicleType);
      return new MotorBicycle();
      }
      }



      public class CarFactory : VehicleFactory
      {
      public override Vehicle CreateVehicle(VehicleType vehicleType)
      {
      Console.WriteLine("Creating a " + vehicleType);
      return new Car();
      }
      }


    • Vehicle :- Abstract Product


    • public abstract class Vehicle
      {

      private int _engineCapacity;
      private int _noOfWheels;

      public int EngineCapacity
      {
      get
      {
      return _engineCapacity;
      }
      set
      {
      _engineCapacity = value;
      }
      }

      public int NoOfWheels
      {
      get
      {
      return _noOfWheels;
      }
      set
      {
      _noOfWheels = value;
      }
      }

      public abstract void Accelerate();

      public abstract void Break();
      }


    • MotorBicycle, Car :- Concrete Product



    public class MotorBicycle : Vehicle
    {
    public MotorBicycle()
    {
    base.EngineCapacity = 100;
    base.NoOfWheels = 2;
    }

    public override void Accelerate()
    {
    Console.WriteLine("Accelerating with Handle");
    }

    public override void Break()
    {
    Console.WriteLine("Stopping with Handle");
    }
    }



    public class Car : Vehicle
    {
    public Car()
    {
    base.EngineCapacity = 300;
    base.NoOfWheels = 4;
    }

    public override void Accelerate()
    {
    Console.WriteLine("Accelerating with Paddle");
    }

    public override void Break()
    {
    Console.WriteLine("Stopping with Paddle");
    }
    }


    • Prorgam :- Cleint


    class Program
    {
    static void Main(string[] args)
    {
    Console.WriteLine("Creating a Motor Bicycle");
    VehicleFactory bicycleFactory = new BicycleFactory();
    Vehicle motorBicycle = bicycleFactory.CreateVehicle(VehicleFactory.VehicleType.Bicycle);
    Console.WriteLine("Got a " + motorBicycle.GetType() + " with EngineCapacity " + motorBicycle.EngineCapacity + " and " + motorBicycle.NoOfWheels + " wheels.");
    motorBicycle.Accelerate();
    motorBicycle.Break();

    Console.WriteLine("");
    Console.WriteLine("");

    Console.WriteLine("Creating a Car");
    VehicleFactory carFactory = new CarFactory();
    Vehicle car = carFactory.CreateVehicle(VehicleFactory.VehicleType.Car);
    Console.WriteLine("Got a " + car.GetType() + " with EngineCapacity " + car.EngineCapacity + " and " + car.NoOfWheels + " wheels.");
    car.Accelerate();
    car.Break();

    Console.ReadLine();
    }
    }

    Thursday, July 15, 2010

    The Abstract Factory pattern with C# code example


    The Abstract Factory
    The The Abstract Factory is a design pattern which provides an interface for creating families of related or dependent objects without specifying their concrete classes.

    The class diagram








































    The implementation

    • Animal Factory :- Abstract Factory
    This abstract factory defines method/s for producing the product (in our case Animal). All other concrete factories should implement this/these methods.



    interface AnimalFactory
    {
    Animal CreateAnimal();
    }



    • LandFactory, SeaFactory :- Concrete Factories
    These are concrete factories, implements different product families. Client can use one of these to create a product (in our case Animal), so client never need to create product object.


    class LandFactory : AnimalFactory
    {
    public Animal CreateAnimal()
    {
    return new Horse();
    }
    }

    class SeaFactory : AnimalFactory
    {
    public Animal CreateAnimal()
    {
    return new Seahorse();
    }
    }

    • Animal :- Abstract Product



    public interface Animal
    {
    void Move();
    }


    • Horse, SeaHorse :- Concrete Product




    class Horse : Animal
    {
    public void Move() {
    Console.WriteLine("I Can run very fastly!");
    }
    }

    class Seahorse : Animal
    {
    public void Move() {
    Console.WriteLine("I am moving in the water! He he!");
    }
    }


    • AnimalWorld:- Client
    This is the client and it was written against the abstract factory and it will deal actual factory and the product in the run time. The Program class is having the main method as the entry point



    class AnimalWorld
    {
    private Animal animal;

    public AnimalWorld(AnimalFactory animalFactory)
    {
    animal = animalFactory.CreateAnimal();
    }

    public void Move()
    {
    animal.Move();
    Console.ReadLine();
    }
    }



    class Program
    {
    static void Main(string[] args)
    {
    AnimalFactory animalFactory = createAnimalFactory("land");
    AnimalWorld animalWorld = new AnimalWorld(animalFactory);
    animalWorld.Move();
    }

    public static AnimalFactory createAnimalFactory(String type)
    {
    if ("sea".Equals(type))
    return new SeaFactory();
    else if ("land".Equals(type))
    return new LandFactory();
    else
    return null;
    }
    }



    References:
    http://www.dofactory.com/Patterns/PatternAbstract.aspx#_self2
    http://en.wikipedia.org/wiki/Abstract_factory_pattern

    Saturday, January 30, 2010

    භාවනාව

    භාවනා වැඩීමට පෙර ඔබ තුල තිබිය යුතු සුදුසුකම්
    • නිදහස් චින්තනය
    • මනස දියුනු කිරීමේ වටිනාකම ගැන තේරුම් කර ගැනීම
    • ජීවිතය ගෙවීයාමට කලින් ප්‍රයොජනයක් ගත යුතු බවට මතයකට පැමිණ සිටීම
    • සිත දියුනු කිරීමේ සියලු උපදෙස් බුදු දහමේ ඇති බවට පැහැදීම

    සමත භාවනාවත් විදර්ශනා භාවනාවත් යනු ජීවිතාවබෝධයට වැදගත් වන භාවනා දෙකකි. සමත භාවනාව ප්‍රගුණ කිරීමෙන් සිතෙහි දියුනුව වර්ධනයවේ (සිතෙහි දුර්වලකම් නැතිවේ, සිත විසෙරෙන ගතිය නැතිවේ, ශක්තිමත් වේ, යමක් අවබෝධකර ගැනීමට සුදුසු අකාරයට සිත සකස් වේ ). විදර්ශනා භාවනාව දියුනු කිරීමෙන් ප්‍රඤ්ඥාව දියුනුවේ (යම් කිසි දෙයක ඇත්ත ස්වභාවය තේරුම් ගැනීමට හැකිවේ). මෙ භාවනා දෙකම එකිනෙකින් වෙන්කිරීම අපහසුය.

    සමත භාවනාව
    සමත භාවනාව වැඩීමෙන් පංච නීවරන ධරම යටපත් කොට, සිත තැම්පත් කොට, සමාධිය දියුනු කොට සිත දියුනු කිරීමට හැකිවේ.

    පංච නීවරන ධර්ම
    • කාමචන්ධය
    තමන් අසා කරන රූප, ගන්ධ, ශබ්ද, රස හා ස්පර්ශ වලට සිත නිතර නිතර ඇලී යාම.
    • ව්‍යාපද නීවරනය
    ඉහත සදහන් කල සැප විදීම් මෙනෙහි කරමින් ඒතුල ගැටීම
    • තීන මිත්ත
    සිත දියුනු කිරීමට බැරි මට්ටමට තමන් අලස වීම
    • උද්දච්ච කුක්කුච්ච
    තමන්ගෙන් සිදුවුන අත්වැරදි ගැන මෙනෙහි කිරීමෙන් ශොක වෙමින් ධර්ම මර්ගයෙහි නොහැසිරීම
    • විචිකිච්චා
    තමන්ට ධර්ම මාරගයෙහි හැසිරීමට බැරිය යනුවෙන් ඇති වන්නාවූ සැකය (මෙය පසුබැසීමට හෙතුවේ).

    මෙවැනි කරුනු සිතෙන් යටපත් කර සිත සමාදි ගත කිරීමේ හැකියාවක් සමත භාවනවට ඇත. මෙම සමාධි ගත වීම තුලින් පිලිවෙලින් පලමු, දෙවන, තෙවන හා සිවුවෙනි ධ්‍යාන ලබ ගත හැක.

    විදර්ශනා භාවනාව
    විදර්ශනා භාවනවෙන් යමක මූලික ලක්ෂණය හෙවත් අනිත්‍ය භාවය තෙරුම් කර ගැනීමට හැකිවේ. අනිත්‍ය, දුක්‍ය, අනාත්ම යන ලක්ෂණ ප්‍රගුණ කරමින් යමක් විනිවිද දැකීමේ හැකියාව ප්‍රඤ්ඥාව වේ. විදර්ශනාව යනු ප්‍රඤ්ඥාව ලබා ගැනීමට ඉහත හැකියාව දියුනු කිරීමයි.