Tuesday, 10 September 2013

Java Bean

A JavaBean is a specially constructed Java class written in the Java and coded according to the JavaBeans API specifications.
Following are the unique characteristics that distinguish a JavaBean from other Java classes:
  • It provides a default, no-argument constructor.
  • It should be serializable and implement the Serializable interface.
  • It may have a number of properties which can be read or written.
  • It may have a number of "getter" and "setter" methods for the properties.

JavaBeans Properties:

A JavaBean property is a named attribute that can be accessed by the user of the object. The attribute can be of any Java data type, including classes that you define.
A JavaBean property may be read, write, read only, or write only. JavaBean properties are accessed through two methods in the JavaBean's implementation class:
MethodDescription
getPropertyName()For example, if property name is firstName, your method name would be getFirstName() to read that property. This method is called accessor.
setPropertyName()For example, if property name is firstName, your method name would be setFirstName() to write that property. This method is called mutator.
A read-only attribute will have only a getPropertyName() method, and a write-only attribute will have only a setPropertyName() method.

JavaBeans Example:

Consider a student class with few properties:
package com.tutorialspoint;

public class StudentsBean implements java.io.Serializable
{
private String firstName = null;
private String lastName = null;
private int age = 0;

public StudentsBean() {
}
public String getFirstName(){
return firstName;
}
public String getLastName(){
return lastName;
}
public int getAge(){
return age;
}
public void setFirstName(String firstName){
this.firstName = firstName;
}
public void setLastName(String lastName){
this.lastName = lastName;
}
public void setAge(Integer age){
this.age = age;
}
}

Accessing JavaBeans:

The useBean action declares a JavaBean for use in a JSP. Once declared, the bean becomes a scripting variable that can be accessed by both scripting elements and other custom tags used in the JSP. The full syntax for the useBean tag is as follows:
<jsp:useBean id="bean's name" scope="bean's scope" typeSpec/>
Here values for the scope attribute could be page, request, session or application based on your requirement. The value of the id attribute may be any value as a long as it is a unique name among other useBean declarations in the same JSP.
Following example shows its simple usage:
<html>
<head>
<title>useBean Example</title>
</head>
<body>

<jsp:useBean id="date" class="java.util.Date" />
<p>The date/time is <%= date %>

</body>
</html>
This would produce following result:
The date/time is Thu Sep 30 11:18:11 GST 2010 

Accessing JavaBeans Properties:

Along with <jsp:useBean...>, you can use <jsp:getProperty/> action to access get methods and <jsp:setProperty/> action to access set methods. Here is the full syntax:
<jsp:useBean id="id" class="bean's class" scope="bean's scope">
<jsp:setProperty name="bean's id" property="property name"
value="value"/>
<jsp:getProperty name="bean's id" property="property name"/>
...........
</jsp:useBean>
The name attribute references the id of a JavaBean previously introduced to the JSP by the useBean action. The property attribute is the name of the get or set methods that should be invoked.
Following is a simple example to access the data using above syntax:
<html>
<head>
<title>get and set properties Example</title>
</head>
<body>

<jsp:useBean id="students"
class="com.tutorialspoint.StudentsBean">
<jsp:setProperty name="students" property="firstName"
value="Zara"/>
<jsp:setProperty name="students" property="lastName"
value="Ali"/>
<jsp:setProperty name="students" property="age"
value="10"/>
</jsp:useBean>

<p>Student First Name:
<jsp:getProperty name="students" property="firstName"/>
</p>
<p>Student Last Name:
<jsp:getProperty name="students" property="lastName"/>
</p>
<p>Student Age:
<jsp:getProperty name="students" property="age"/>
</p>

</body>
</html>
Let us make StudentsBean.class available in CLASSPATH and try to access above JSP. This would produce following result:
Student First Name: Zara 

Student Last Name: Ali

Student Age: 10

Database ACID (Atomicity, Consistency, Isolation, Durability) Properties

There are a set of properties that guarantee that database transactions are processed reliably, referred to as ACID (Atomicity, Consistency, Isolation, Durability).

Atomicity

Atomicity refers to the ability of the database to guarantee that either all of the tasks of a transaction are performed or none of them are. Database modifications must follow an all or nothing rule. Each transaction is said to be atomic if when one part of the transaction fails, the entire transaction fails.

Consistency

The consistency property ensures that the database remains in a consistent state before the start of the transaction and after the transaction is over (whether successful or not). For example, in a storefront there is an inconsistent view of what is truly available for purchase if inventory is allowed to fall below 0, making it impossible to provide more than an intent to complete a transaction at checkout time. An example in a double-entry accounting system illustrates the concept of a true transaction. Every debit requires an associated credit. Both of these happen or neither happen.
A distributed data system is either strongly consistent or has some form of weak consistency. Once again, using the storefront example, a database needs to provide consistency and isolation, so that when one customer is reducing an item in stock and in parallel is increasing the basket by one, this is isolated from another customer who will have to wait while the data store catches up. At the other end of the spectrum is BASE (Basically Available Soft-state Eventual consistency).
Weak consistency is sometimes referred to as eventual consistency, the database eventually reaches a consistent state. Weak consistency systems are usually ones where data is replicated; the latest version is sitting somewhere in the cluster, older versions are still out there. Eventually all nodes will see the latest version.

Isolation

Isolation refers to the requirement that other operations cannot access or see the data in an intermediate state during a transaction. This constraint is required to maintain the performance as well as the consistency between transactions in a database. Thus, each transaction is unaware of another transactions executing concurrently in the system.

Durability

Durability refers to the guarantee that once the user has been notified of success, the transaction will persist, and not be undone. This means it will survive system failure, and that the database system has checked the integrity constraints and won't need to abort the transaction. Many databases implement durability by writing all transactions into a transaction log that can be played back to recreate the system state right before a failure. A transaction can only be deemed committed after it is safely in the log.
Durability does not imply a permanent state of the database. Another transaction may overwrite any changes made by the current transaction without hindering durability.

Monday, 9 September 2013

JAVA: Hypnosis Animation

Hypnosis animation
Hypnosis animation

package jay;

/**
 *
 * @author jay.thakkar
 */
import java.awt.Color;
import java.awt.Dimension;
import java.awt.GradientPaint;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Paint;
import java.awt.RenderingHints;
import java.awt.Shape;
import java.awt.geom.GeneralPath;

import javax.swing.JComponent;
import javax.swing.JFrame;

public class Hypnosis1 extends JComponent implements Runnable {

    private int[] coordinates;
    private int[] deltas;
    private Paint paint;

    public Hypnosis1(int numberOfSegments) {
        int numberOfCoordinates = numberOfSegments * 4 + 2;
        coordinates = new int[numberOfCoordinates];
        deltas = new int[numberOfCoordinates];
        for (int i = 0; i < numberOfCoordinates; i++) {
            coordinates[i] = (int) (Math.random() * 300);
            deltas[i] = (int) (Math.random() * 4 + 3);
            if (deltas[i] > 4) {
                deltas[i] = -(deltas[i] - 3);
            }
        }
        paint = new GradientPaint(0, 0, Color.blue, 20, 10, Color.red, true);

        Thread t = new Thread(this);
        t.start();
    }

    public void run() {
        try {
            while (true) {
                timeStep();
                repaint();
                Thread.sleep(1000 / 24);
            }
        } catch (InterruptedException ie) {
        }
    }

    public void paint(Graphics g) {
        Graphics2D g2 = (Graphics2D) g;
        g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
        Shape s = createShape();
        g2.setPaint(paint);
        g2.fill(s);
        g2.setPaint(Color.white);
        g2.draw(s);
    }

    private void timeStep() {
        Dimension d = getSize();
        if (d.width == 0 || d.height == 0) {
            return;
        }
        for (int i = 0; i < coordinates.length; i++) {
            coordinates[i] += deltas[i];
            int limit = (i % 2 == 0) ? d.width : d.height;
            if (coordinates[i] < 0) {
                coordinates[i] = 0;
                deltas[i] = -deltas[i];
            } else if (coordinates[i] > limit) {
                coordinates[i] = limit - 1;
                deltas[i] = -deltas[i];
            }
        }
    }

    private Shape createShape() {
        GeneralPath path = new GeneralPath();
        path.moveTo(coordinates[0], coordinates[1]);
        for (int i = 2; i < coordinates.length; i += 4) {
            path.quadTo(coordinates[i], coordinates[i + 1], coordinates[i + 2], coordinates[i + 3]);
        }
        path.closePath();
        return path;
    }

    public static void main(String[] args) {
        JFrame f = new JFrame("Hypnosis");
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        f.add(new Hypnosis1(4));
        f.setSize(300, 300);
        f.setVisible(true);
    }
}

Draw text along a curve


package jay;

/**
 *
 * @author jay.thakkar
 */
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.Shape;
import java.awt.font.FontRenderContext;
import java.awt.font.GlyphVector;
import java.awt.geom.AffineTransform;
import java.awt.geom.Point2D;

import javax.swing.JFrame;
import javax.swing.JPanel;

public class RollingText extends JPanel {
  public void paint(Graphics g) {
    Graphics2D g2 = (Graphics2D) g;

    g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
        RenderingHints.VALUE_ANTIALIAS_ON);

    String s = " http://jaypthakkar.blogspot.in ";
    Font font = new Font("Serif", Font.PLAIN, 24);
    FontRenderContext frc = g2.getFontRenderContext();
    g2.translate(40, 80);

    GlyphVector gv = font.createGlyphVector(frc, s);
    int length = gv.getNumGlyphs();
    for (int i = 0; i < length; i++) {
      Point2D p = gv.getGlyphPosition(i);
      double theta = (double) i / (double) (length - 1) * Math.PI / 4;
      AffineTransform at = AffineTransform.getTranslateInstance(p.getX(),
          p.getY());
      at.rotate(theta);
      Shape glyph = gv.getGlyphOutline(i);
      Shape transformedGlyph = at.createTransformedShape(glyph);
      g2.fill(transformedGlyph);
    }
  }

  public static void main(String[] args) {
    JFrame f = new JFrame("RollingText v1.0");
    f.getContentPane().add(new RollingText());
    f.setSize(600, 300);
    f.setVisible(true);
  }
}

How to Create CurveDraw In Java

In this section, you will learn how to create CurveDraw in java.awt package. This class,supported by thejava.awt.geom package, enables you to create a quadratic or cubic segment. Here, you will see in the following example that provide you complete code of the program.
Program Description:
Define class named CurveDraw, for creating  this component. 


QuadCurve2D.Double(): This QuadCurve2D class is defined as a quadratic parametric curve segment in (x, y) coordinate and the quadratic parametric curve segment is specified with Double Coordinate. This class supplies a coordinate space. Such that this class represents the coordinate parameter and is defined for using the CurveDraw component. A QuadCurve  draws the curve line with Double Coordinate. 

Here is the code of this program:
import java.awt.*;
import java.awt.event.*;
import java.awt.geom.*;

public class CurveDraw extends Frame {
  Stroke drawingStroke = new BasicStroke(2);
  QuadCurve2D curve = new QuadCurve2D.Double(30,50,20,200,100,100);

  public void paint(Graphics g) {
  Graphics2D ga = (Graphics2D)g;
  ga.setStroke(drawingStroke);
  ga.setPaint(Color.green);
  ga.draw(curve);

  }

  public static void main(String args[]) {
  Frame frame = new CurveDraw();
  frame.addWindowListener(new WindowAdapter(){
  public void windowClosing(WindowEvent we){
  System.exit(0);
  }
  });
  frame.setSize(200200);
  frame.setVisible(true);
  }
}
Output of this program:
 

Sunday, 8 September 2013

Drawing Multiplie Lines in a Buffered Image in Java

import java.awt.*;
import java.awt.image.*;
import javax.swing.*;

class GridLines {

    public static void main(String[] args) {

        Dimension imgDim = new Dimension(200,200);
        BufferedImage mazeImage = new BufferedImage(imgDim.width, imgDim.height, BufferedImage.TYPE_INT_RGB);


        Graphics2D g2d = mazeImage.createGraphics();
        g2d.setBackground(Color.WHITE);
        g2d.fillRect(0, 0, imgDim.width, imgDim.height);
        g2d.setColor(Color.BLACK);
        BasicStroke bs = new BasicStroke(2);
        g2d.setStroke(bs);
        // draw the black vertical and horizontal lines
        for(int i=0;i<21;i++){
            // unless divided by some factor, these lines were being
            // drawn outside the bound of the image..
            g2d.drawLine((imgDim.width+2)/20*i, 0, (imgDim.width+2)/20*i,imgDim.height-1);
            g2d.drawLine(0, (imgDim.height+2)/20*i, imgDim.width-1, (imgDim.height+2)/20*i);
        }

        ImageIcon ii = new ImageIcon(mazeImage);
        JOptionPane.showMessageDialog(null, ii);
    }
}