Monday 27 January 2014

How much memory do Enums take?

Java programming language enum types are much more powerful than their counterparts in other languages. The enum declaration defines a class (called an enum type). The enum class body can include methods and other fields.
In order to see the actual size of each enum, let's make an actual enum and examine the contents of the class file it creates.
Let's say we have the following Constants enum class:
public enum Constants {
  ONE,
  TWO,
  THREE;
}
Compiling the above enum and disassembling resulting class file with javap gives the following:
Compiled from "Constants.java"
public final class Constants extends java.lang.Enum{
    public static final Constants ONE;
    public static final Constants TWO;
    public static final Constants THREE;
    public static Constants[] values();
    public static Constants valueOf(java.lang.String);
    static {};
}
The disassembly shows that that each field of an enum is an instance of the Constants enum class. (Further analysis with javap will reveal that each field is initialized by creating a new object by calling the new Constants(String) constructor in the static initialization block.)
Therefore, we can tell that each enum field that we create will be at least as much as the overhead of creating an object in the JVM.

ZIP and UNZIP with Passwords in Java

Zip and Unzip are a very common activities for a computer user. A user normally uses the zip utility to compress a directory to create a zip file. There are many ready-made software such as winzip,7zip, and winrar that are available to achieve this. 

However, it is also possible to protect the zip file with a password so that the end user has to provide the password to unzip the zip file. This is the very common scenario that can be achieved by a zip utility tool. The significant part of my article is to provide you with the solution to achieve this using a Java program. While developing the project you may encounter a scenario in which you have to create a password-protected zip file that can be unzipped by any zip tool like winzip. Let me provide a complete scenario for your understanding.

In a system, some files are generated for a user and all the files are zipped with a password. The generated password protected zip file is sent to the user through email and the password for the zip file to open is sent to the particular user as an SMS to the user's mobile. 

 Similarly the end-user creates a password protected zip file and uploads to a online system with the user's password in a text field. In this case we have to develop a system where the system will be able to create a password protected zip file and should be able to extract all the files from a password protected zip file. Let me show you how you can achieve it.

Technicalities
However, Java provides the feature of creating a zip file and also provides the feature to unzip or decompress a zip file. But there is no default java API to create a password protected zip file and also there is no default java API to unzip a password protected zip file. To facilitate this feature of zip utility some developers have developed java API in this regard. We have to use their API to achieve this. We have to look into the following aspects of zip utility.
  1. Java-enabled system should be able to generate a password protected zip file and that password protected zip file can be unzipped by any zip utility like winzip and others
  2. Java-enabled system should be able to decompress or unzip a password protected zip file created by any zip utility like winzip and others.
The followings are the APIs you have to use for this objective:

1.To create a password protected zip file in java, you have to use “winzipaes”. It is avilable in Google code. You can download the .jar file and the source code from the following link.

This API helps to add a password to a already created zip file. It means that if you want to create a password protected zip file, first you have to create a zip file and then you can add a password that zip file. It is a pure java API works with any operating system. You have to download the following jar file from the above URL.

passwordcompressor.jar

2.To unzip or decompress a password protected zip file, you have to use “sevenzipjbind”. It is available in sourceforge.net site. You can download the .jar files from the following link: http://sourceforge.net/projects/sevenzipjbind/files/. This API helps to extract all the files and folders from password protected zip file created by any zip utility tool. You have to download the following .jar files from the above URL.
sevenzipjbinding-AllPlatforms.jar
sevenzipjbinding.jar

3.For password protection, you have to use Bouncecastle cryptographic API. You can download the .jar file from the following link.
http://www.bouncycastle.org/
You have to download the following .jar files from the above URL.
bcprov-jdk15-145.jar

After downloading all the .jar files, put all the .jar files in your classpath. I have written a java program by using all these APIs to achieve all the above mentioned functionalities.
Have a look at the following code structure.

Code for ZipUtil.java


Saturday 25 January 2014

DicomMultiframePlayer in JAVA

package packageTestDcm4che3;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.Iterator;
import java.util.Vector;
import javax.imageio.ImageIO;
import javax.imageio.ImageReadParam;

import javax.imageio.ImageReader;
import javax.imageio.spi.ImageReaderSpi;
import javax.imageio.stream.FileImageInputStream;
import javax.imageio.stream.ImageInputStream;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import org.dcm4che.imageio.plugins.dcm.DicomImageReadParam;
import org.dcm4che.imageio.plugins.dcm.DicomImageReader;

/**
 * Plays a multiframe DICOM instance.
 *
 * @author dimitri PIANETA
 *
 * <p>The code for this came from <a href="http://samucs.blogspot.com" target="_blank">http://samucs.blogspot.com</a>
 *    and was dated 6-January-2010.</p>
 *
 * <p> code modification 14 January 2014 for dcm4che3 <p>
 */   
public class DicomMultiframePlayer extends JFrame implements ActionListener, Runnable {
   
    private static final long serialVersionUID = 1L;
    private JLabel fileLabel;
    /**
     * Will contain name of file to be read.
     */
    private JTextField fileField;
    /**
     * Triggers process for selecting file to be read.
     * @see #actionPerformed(ActionEvent)
     */
    private JButton btnChoose;
    /**
     * Starts playing of images.
     * @see #actionPerformed(ActionEvent)
     */
    private JButton btnPlay;
    /**
     * Pauses playing of images.
     * @see #actionPerformed(ActionEvent)
     */
    private JButton btnPause;
    /**
     * Halts playing of images.
     * @see #actionPerformed(ActionEvent)
     */
    private JButton btnStop;
    private JButton btnExit;   
    private Vector<BufferedImage> images;
    private ImagePanel imagePanel;   
    private boolean stop;
    private int currentFrame;
   
       
        private int frame = 1;

       
       
       
          private final ImageReader imageReader =
            ImageIO.getImageReadersByFormatName("DICOM").next();
       
       
    public DicomMultiframePlayer() {
        super("DICOM Multiframe Player using dcm4che - by samucs-dev");
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        this.getContentPane().setLayout(new BorderLayout());
       
        images = new Vector<BufferedImage>();
        imagePanel = new ImagePanel();
       
        fileLabel = new JLabel("File:");
        fileField = new JTextField(30);
        btnChoose = this.createJButton(25, 25, "...");
       
        btnPlay = this.createJButton(80,25,"Play");
        btnPause = this.createJButton(80,25,"Pause");
        btnStop = this.createJButton(80,25,"Stop");       
        btnExit = this.createJButton(80,25,"Exit");
        btnPause.setEnabled(false);
        btnStop.setEnabled(false);
       
        JPanel panelNorth = new JPanel();
        panelNorth.add(fileLabel);
        panelNorth.add(fileField);
        panelNorth.add(btnChoose);
       
        JPanel panelSouth = new JPanel();
        panelSouth.add(btnPlay);
        panelSouth.add(btnPause);
        panelSouth.add(btnStop);
        panelSouth.add(btnExit);
       
        this.getContentPane().add(panelNorth, BorderLayout.NORTH);
        this.getContentPane().add(imagePanel, BorderLayout.CENTER);
        this.getContentPane().add(panelSouth, BorderLayout.SOUTH);
       
        this.setSize(new Dimension(500,500));
        this.setLocationRelativeTo(null);
        this.setVisible(true);
    }
    /**
     * Plays the frames in order.
     *
     * <p>I removed the Override annotation.</p>
     */
    // @Override
    public void run() {
        while(true) {
            if (!btnPlay.isEnabled()) {               
                if (stop) break;               
                currentFrame++;
                if (currentFrame == images.size())
                    currentFrame = 0;
                imagePanel.setImage(images.get(currentFrame));               
                try {
                    Thread.sleep(70);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }
    /**
     * Detects clicking of button and carries out appropriate action.
     *
     * <p>I removed the Override annotation.</p>
     */
    // @Override
    public void actionPerformed(ActionEvent e) {       
        if (e.getSource().equals(btnChoose)) {
            JFileChooser chooser = new JFileChooser();
            int action = chooser.showOpenDialog(this);
            switch(action) {
                case JFileChooser.APPROVE_OPTION:
                    this.openFile(chooser.getSelectedFile());
                    break;
                case JFileChooser.CANCEL_OPTION:
                    return;
            }
        }       
        if (e.getSource().equals(btnPlay)) {
            btnPlay.setEnabled(false);
            btnPause.setEnabled(true);
            btnStop.setEnabled(true);
            stop = false;
            new Thread(this).start();           
        }
        if (e.getSource().equals(btnPause)) {
            btnPlay.setEnabled(true);
            btnPause.setEnabled(false);
            btnStop.setEnabled(true);
            stop = false;
        }
        if (e.getSource().equals(btnStop)) {
            btnPlay.setEnabled(true);
            btnPause.setEnabled(false);
            btnStop.setEnabled(false);
            stop = true;
            currentFrame = 0;
            imagePanel.setImage(images.get(0));           
        }
        if (e.getSource().equals(btnExit)) {
            System.exit(0);
        }
    }
    /**
     * Creates JButton objects on window.
     * @param width width of button in pixels.
     * @param height height of button in pixels
     * @param text text to appear in button
     * @return JButton object
     */
    private JButton createJButton(int width, int height, String text) {
        JButton b = new JButton(text);
        b.setMinimumSize(new Dimension(width, height));
        b.setMaximumSize(new Dimension(width, height));
        b.setPreferredSize(new Dimension(width, height));
        b.addActionListener(this);
        return b;
    }
    /**
     * Reads the contents of the dicom file
     * @param file file to be opened
     * @see org.dcm4che2.imageioimpl.plugins.dcm.DicomImageReaderSpi
     * @see org.dcm4che2.imageioimpl.plugins.dcm.DicomImageReader
     */
    private void openFile(File file) {
        images.clear();
        try {
           
                   
                       
            int numFrames =setNumber(file);
            //System.out.println("DICOM image has "+ numFrames +" frames...");           
            System.out.println("Extracting frames...");
            for (int i=0; i < numFrames; i++) {
                     
                       
                          
                BufferedImage img =  chargeImageDicomBufferise(file,i);
                images.add(img);
                System.out.println(" > Frame "+ (i+1));
            }           
            System.out.println("Finished.");
        } catch(Exception e) {
            e.printStackTrace();
            imagePanel.setImage(null);
            return;
        }
        stop = false;
        currentFrame = 0;
        imagePanel.setImage(images.get(0));
    }

     
       
        /**
         * Building BufferingImage
         * @param file : input file
         * @param value : number frame
         * @return
         * @throws IOException
         */
       
        public BufferedImage chargeImageDicomBufferise(File file, int value) throws IOException  {

                Iterator<ImageReader> iter = ImageIO.getImageReadersByFormatName("DICOM");//sp?cifie l'image

                              
                         

              ImageReader readers = iter.next();//on se d?place dans l'image dicom

         DicomImageReadParam   param1 =  (DicomImageReadParam) readers.getDefaultReadParam();//return DicomImageReadParam
               //    Adjust the values of Rows and Columns in it and add a Pixel Data attribute with the byte array from the DataBuffer of the scaled Raster

                ImageInputStream iis = ImageIO.createImageInputStream(file);

             readers.setInput(iis, false);//sets the input source to use the given ImageInputSteam or other  Object

               BufferedImage image = readers.read(value,param1);//BufferedImage image = reader.read(frameNumber, param); frameNumber = int qui est l'imageIndex
                System.out.println(image);//affichage au terminal des caract?res de l'image

                readers.dispose();//Releases all of the native sreen resources used by this Window, its subcomponents, and all of its owned children
              return  image;

            }
   
         /**
 *  Find number frame
 * @param file : input file
 * @return numbre frame in Dicom
 * @throws IOException
 */
   public int setNumber(File file) throws IOException  {

            /* Parcourt le fichier dicom*/
             Iterator<ImageReader> iter = ImageIO.getImageReadersByFormatName("DICOM");//sp?cifie l'image
           ImageReader readers = (ImageReader)iter.next();//on se d?place dans l'image dicom

            DicomImageReadParam   param1=  (DicomImageReadParam) readers.getDefaultReadParam();//return DicomImageReadParam
           //    Adjust the values of Rows and Columns in it and add a Pixel Data attribute with the byte array from the DataBuffer of the scaled Raster

            ImageInputStream iis = ImageIO.createImageInputStream(file);//cr?ation du fichier image


           readers.setInput(iis, false);//sets the input source to use the given ImageInputSteam or other  Object

            //iis.close();
            int  number = readers.getNumImages(true);//numberOfFrame on a "readers" qui doit ?tre DicomImage
            System.out.println(number);//return NumberOfFrame (Tag : (0028, 0008))
           return  number;
        }
   
   
   
    private class ImagePanel extends JPanel {
        private static final long serialVersionUID = 1L;
        private BufferedImage image;
        private int frame;
        public ImagePanel() {
            super();
            this.setPreferredSize(new Dimension(1024,1024));
            this.setBackground(Color.black);           
        }
        public void setImage(BufferedImage image) {
            this.image = image;
            this.updateUI();
        }
        @Override
        public void paint(Graphics g) {
            if (this.image != null) {
                g.drawImage(this.image, 0, 0, image.getWidth(), image.getHeight(), null);
            }
        }
   
        };

    public static void main(String[] args) {
        new DicomMultiframePlayer();
    }

}

Friday 24 January 2014

JAVAFX: Dynamically fire event to Node

Event.fireEvent(vbox, new MouseEvent(MouseEvent.MOUSE_CLICKED, 0,
                    0, 0, 0, MouseButton.PRIMARY, 1, true, true, true, true,
                    true, true, true, true, true, true, null));

Thursday 23 January 2014

How do I implement task prioritization using an ExecutorService in Java 5?


package example;

import java.util.Comparator;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.PriorityBlockingQueue;
import java.util.concurrent.RunnableFuture;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

class PriorityFuture<T> implements RunnableFuture<T> {

    private RunnableFuture<T> src;
    private int priority;

    public PriorityFuture(RunnableFuture<T> other, int priority) {
        this.src = other;
        this.priority = priority;
    }

    public int getPriority() {
        return priority;
    }

    public boolean cancel(boolean mayInterruptIfRunning) {
        return src.cancel(mayInterruptIfRunning);
    }

    public boolean isCancelled() {
        return src.isCancelled();
    }

    public boolean isDone() {
        return src.isDone();
    }

    public T get() throws InterruptedException, ExecutionException {
        return src.get();
    }

    public T get(long timeout, TimeUnit unit) throws InterruptedException,
            ExecutionException, TimeoutException {
        return src.get();
    }

    public void run() {
        src.run();
    }

    public static Comparator<Runnable> COMP = new Comparator<Runnable>() {
        public int compare(Runnable o1, Runnable o2) {
            if (o1 == null && o2 == null)
                return 0;
            else if (o1 == null)
                return -1;
            else if (o2 == null)
                return 1;
            else {
                int p1 = ((PriorityFuture<?>) o1).getPriority();
                int p2 = ((PriorityFuture<?>) o2).getPriority();

                return p1 > p2 ? 1 : (p1 == p2 ? 0 : -1);
            }
        }
    };
}

interface PriorityCallable<T> extends Callable<T> {
    int getPriority();
}

class LenthyJob implements PriorityCallable<Long> {
    private int priority;

    public LenthyJob(int priority) {
        this.priority = priority;
    }

    public Long call() throws Exception {
        System.out.println("Executing: " + priority);
        long num = 1000000;
        for (int i = 0; i < 1000000; i++) {
            num *= Math.random() * 1000;
            num /= Math.random() * 1000;
            if (num == 0)
                num = 1000000;
        }
        return num;
    }

    public int getPriority() {
        return priority;
    }
}

public class TestPQ {

    public static ThreadPoolExecutor getPriorityExecutor(int nThreads) {
        return new ThreadPoolExecutor(nThreads, nThreads, 0L,
                TimeUnit.MILLISECONDS, new PriorityBlockingQueue<Runnable>(10,
                        PriorityFuture.COMP)) {

            protected <T> RunnableFuture<T> newTaskFor(Callable<T> callable) {
                System.out.println("######## newTaskFor : -------");
                RunnableFuture<T> newTaskFor = super.newTaskFor(callable);
               
                return new PriorityFuture<T>(newTaskFor,
                        ((PriorityCallable<T>) callable).getPriority());
            }
        };
    }

    public static void main(String[] args) throws InterruptedException,
            ExecutionException {
        ThreadPoolExecutor exec = getPriorityExecutor(2);

        for (int i = 0; i < 20; i++) {
            int priority = (int) (Math.random() * 100);
            System.out.println("Scheduling: " + priority);
            LenthyJob job = new LenthyJob(priority);
            exec.submit(job);
        }
    }
}

Friday 10 January 2014

Thread output in certain order

package threadseq;

import java.util.*;

public class OrderThreads {
public static void main(String... args) {
Results results = new Results();
new Thread(new Task(0, "red", results)).start();
new Thread(new Task(1, "orange", results)).start();
new Thread(new Task(2, "yellow", results)).start();
new Thread(new Task(3, "green", results)).start();
new Thread(new Task(4, "blue", results)).start();
new Thread(new Task(5, "indigo", results)).start();
new Thread(new Task(6, "violet", results)).start();
}
}

class Results {
private List<String> results = new ArrayList<String>();
private int i = 0;

public synchronized void submit(int order, String result) {
while (results.size() <= order){
results.add(null);
}
results.set(order, result);
while ((i < results.size()) && (results.get(i) != null)) {
System.out.println("result delivered: " + i + " " + results.get(i));
++i;
}
}
}

class Task implements Runnable {
private final int order;
private final String result;
private final Results results;

public Task(int order, String result, Results results) {
this.order = order;
this.result = result;
this.results = results;
}

public void run() {
try {
Thread.sleep(Math.abs(result.hashCode() % 1000)); // simulate a
// long-running
// computation
} catch (InterruptedException e) {
} // you'd want to think about what to do if interrupted
System.out.println("task finished: " + order + " " + result);
results.submit(order, result);
}
}

Thursday 9 January 2014

Convert BufferedImage To ByteBuffer

In applet its very simple to do this

BufferedImage originalImage = ImageIO.read(new File("c:\\image\\mypic.jpg"));
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ImageIO.write( originalImage, "jpg", baos );
baos.flush();
byte[] imageInByte = baos.toByteArray();
baos.close()
ByteBuffer buf = ByteBuffer.wrap(imageInByte);

Rotating Points and/or Polygons around a center Point

After searching for what seems like hours to find a simple solution to this problem...and yes I know that AffineTransform can do this, but I knew there was a lot simpler/faster solution and one that doesn’t require creating new Objects.
The trick is to cache the angle and distance of each point from the center point. After doing so, the points can be rotated and the center point can be moved.
Here is the code...the angles are adjusted to 360 degrees...due north is zero.
import java.awt.*;
import javax.swing.*;

public class PointRotation extends JPanel
{
private Point points[] = new Point[4];
private double angles[] = new double[4];
private double distances[] = new double[4];
private Point center = new Point();
private float angle = 0;

public PointRotation()
{
setLayout(null);

int size = 20;
center.setLocation(100, 100);

points[0] = new Point(center.x - size, center.y - size);
points[1] = new Point(center.x + size, center.y - size);
points[2] = new Point(center.x + size, center.y + size);
points[3] = new Point(center.x - size, center.y + size);

angles[0] = this.getAngle360(center.x, center.y, points[0].x, points[0].y);
angles[1] = this.getAngle360(center.x, center.y, points[1].x, points[1].y);
angles[2] = this.getAngle360(center.x, center.y, points[2].x, points[2].y);
angles[3] = this.getAngle360(center.x, center.y, points[3].x, points[3].y);

distances[0] = center.distance(points[0]);
distances[1] = center.distance(points[1]);
distances[2] = center.distance(points[2]);
distances[3] = center.distance(points[3]);
}

protected void paintComponent(Graphics g)
{
super.paintComponent(g);
Graphics2D g2 = (Graphics2D) g;

g2.setPaint(Color.red);
g2.drawLine(points[0].x, points[0].y, points[1].x, points[1].y);
g2.setPaint(Color.blue);
g2.drawLine(points[1].x, points[1].y, points[2].x, points[2].y);
g2.setPaint(Color.green);
g2.drawLine(points[2].x, points[2].y, points[3].x, points[3].y);
g2.setPaint(Color.cyan);
g2.drawLine(points[3].x, points[3].y, points[0].x, points[0].y);

angle ++;
if (angle >= 360)
{
angle = 0;
}

for (int index = 0; index < points.length; index ++)
{
this.rotatePoint(index, angle);
}

try
{
Thread.sleep(20);
}
catch (Exception exception)
{
// Ignore
}

repaint();
}

private double getAngle360(double x1, double y1, double x2, double y2)
{
double angle = Math.toDegrees(Math.atan2(y2 - y1, x2 - x1));
if (angle < 0) angle = 180 + (180 - -angle);
angle += 90;
if (angle >= 360) angle -= 360;
return angle;
}

private void rotatePoint(int index, float angle)
{
double newAngle = angles


    + angle;
    if (newAngle >= 360) newAngle -= 360;

    double radians = Math.toRadians(newAngle);
    double distance = this.distances

      ;
      int deltaX = (int) (distance * Math.sin(radians));
      int deltaY = (int) (distance * -Math.cos(radians));

      points

        .setLocation(center.x + deltaX, center.y + deltaY);
        }

        public static void main(String[] args)
        {
        PointRotation c = new PointRotation();
        JFrame f = new JFrame();
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        f.getContentPane().add(c);
        f.setSize(400, 450);
        f.setLocation(0, 325);
        f.setVisible(true);
        }
        }

        Find length of sub sequence array in increasing order

        public class MyCode {

        public static void main(String[] args) {

        System.out.println("L :"
        + longestSeq(new int[] { 10, 22, 9, 33, 21, 50, 41, 60, 80 }));
        System.out.println("L :"
        + longestSeq(new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 7, 6, 5, 4, 5,
        6, 7, 8, 9, 10, 11 }));
        System.out.println("**************************");
        System.out.println("L :"
        + longestSeq(new int[] { 0, 8, 4, 12, 2, 10, 6, 14, 1, 9, 5,
        13, 3, 11, 7, 15 }));
        }

        public static int longestSeq(int[] input1) {
        int[] L = new int[input1.length];
        L[0] = 1;
        for (int i = 1; i < L.length; i++) {
        int maxn = 0;
        for (int j = 0; j < i; j++) {
        if (input1[j] < input1[i] && L[j] > maxn) {
        maxn = L[j];
        }
        }
        L[i] = maxn + 1;
        }
        int maxi = 0;
        for (int i = 0; i < L.length; i++) {
        if (L[i] > maxi) {
        maxi = L[i];
        }
        }
        return (maxi);
        }

        }
        Output:
        L :6
        L :11
        **************************
        L :6

        Wednesday 1 January 2014

        Create Tube(Pipe) in Java3D and also apply curve




        /*
        This method create ellipse at given x,y,z  point
        */

        LineArray buildEllipse1(double x, double y, double z, double semiMajorAxis,
        double semiMinorAxis) {
        // build geometry
        int totalLines = 50;
        int totalPoints = totalLines * 2;
        double tInc = 1.0 / (double) totalLines;

        Point3d p0 = new Point3d();
        Point3d p1 = new Point3d();

        LineArray lineArray = new LineArray(totalPoints, LineArray.COORDINATES);

        double t = 0.0;
        int lineIndex = 0;
        for (int i = 0; i < totalLines; i++) {
        p0.x = (semiMinorAxis * Math.cos(2.0 * Math.PI * t)) + x;
        p0.y = y;
        p0.z = (semiMajorAxis * Math.sin(2.0 * Math.PI * t)) + z;
        lineArray.setCoordinate(lineIndex++, p0);

        p1.x = (semiMinorAxis * Math.cos(2.0 * Math.PI * (t + tInc))) + x;
        p1.y = y;
        p1.z = (semiMajorAxis * Math.sin(2.0 * Math.PI * (t + tInc))) + z;
        // p1.z=10;
        lineArray.setCoordinate(lineIndex++, p1);
        t += tInc;
        }



        return lineArray;

        }
        / *
        Add tube function add tube by merging of circle and make 3d tube(Pipe)
         */
        private void addTube_onAction() {

        Shape3D circleShape3d = new Shape3D();
        // build appearance
        Appearance appearance = new Appearance();

        LineAttributes lineAttrib = new LineAttributes(2.0f,
        LineAttributes.PATTERN_SOLID, true);
        appearance.setLineAttributes(lineAttrib);

        ColoringAttributes colorAttributes = new ColoringAttributes( new Color3f(Color.YELLOW),
        ColoringAttributes.SHADE_GOURAUD);
        appearance.setColoringAttributes(colorAttributes);

        RenderingAttributes renderAttrib = new RenderingAttributes();
        renderAttrib.setDepthBufferEnable(false);
        renderAttrib.setDepthBufferWriteEnable(false);
        appearance.setRenderingAttributes(renderAttrib);
        BranchGroup branchGroup1 = new BranchGroup();



        BranchGroup branchGroup = new BranchGroup();
        branchGroup.setCapability(Content.ALLOW_DETACH);

        Shape3D shape3d = new Shape3D();
        Color3f color3f = new Color3f(Color.red);

        Point3f pt1 = new Point3f(strToFloat(pt1_x_textField.getText()),
        strToFloat(pt1_y_textField.getText()),
        strToFloat(pt1_z_textField.getText()));
        Point3f pt2 = new Point3f(strToFloat(pt2_x_textField.getText()),
        strToFloat(pt2_y_textField.getText()),
        strToFloat(pt2_z_textField.getText()));

        ArrayList<Point2D> point2ds = generateCurve(
        new Point2D.Double(pt1.getX(), pt1.getY()), new Point2D.Double(
        pt2.getX(), pt2.getY()), 2000, 1);



        Point3d[] coords = new Point3d[point2ds.size()];
        int cnt = 0;
        for (Point2D point2d : point2ds) {
        coords[cnt] = new Point3d(point2d.getX(), point2d.getY(), 250);
        circleShape3d.addGeometry(buildEllipse1(point2d.getX(),
        point2d.getY(), 250,3,3));
        cnt++;
        }
        //circleShape3d.setAppearance(appearance);
        branchGroup1.addChild(circleShape3d);
        image3DUniverse.getScene().addChild(branchGroup1);
        // // Point3f[] coords = { onX, onY };
        //
        int N = coords.length;

        Color3f colors[] = new Color3f[N];
        for (int i = 0; i < N; i++) {
        colors[i] = color3f;
        }

        int[] strip = { N };

        LineStripArray ta = new LineStripArray(N, LineStripArray.COORDINATES
        | LineStripArray.COLOR_3, strip);
        ta.setCoordinates(0, coords);
        ta.setColors(0, colors);

        shape3d.addGeometry(ta);
        branchGroup.addChild(shape3d);
        image3DUniverse.getScene().addChild(branchGroup);

        }

        private static double GetAngle(Point2D x, Point2D o, double R) {
        double cosa = (x.getX() - o.getX()) / R;
        double sina = (x.getY() - o.getY()) / R;

        double angle = Math.acos(cosa);

        return Math.sin(angle) * sina >= 0 ? angle : 2 * Math.PI - angle;
        }


             /*
              This method apply curve on tube depend on radius value 
              */
        private static ArrayList<Point2D> generateCurve(Point2D pFrom, Point2D pTo,
        float pRadius, float pMinDistance) {

        ArrayList<Point2D> pOutPut = new ArrayList<Point2D>();

        double dist = pFrom.distance(pTo);
        double h = Math.sqrt(pRadius * pRadius - (dist * dist / 4.0));
        double angleStep = pMinDistance / pRadius;

        System.out.println(" #### dist ::" + dist);
        System.out.println(" #### pRadius ::" + pRadius);

        // pRadius = (float) ((dist/ 2 ) + 100) ;

        if (2 * pRadius <= dist)
        throw new Error("Radius is too small");

        // find center
        double x1 = pFrom.getX(), x2 = pFrom.getY();
        double y1 = pTo.getX(), y2 = pTo.getY();
        double m1 = (x1 + y1) / 2, m2 = (x2 + y2) / 2;
        double u1 = -(y2 - x2) / dist, u2 = (y1 - x1) / dist;
        double o1 = m1 + h * u1, o2 = m2 + h * u2;
        Point2D o = new Point2D.Double(o1, o2);

        double startAngle = GetAngle(pFrom, o, pRadius);
        double endAngle = GetAngle(pTo, o, pRadius);

        if (endAngle < startAngle)
        endAngle += 2 * Math.PI;

        for (double a = startAngle; a < endAngle; a += angleStep) {
        pOutPut.add(new Point2D.Double(o1 + pRadius * Math.cos(a), o2
        + pRadius * Math.sin(a)));
        }

        pOutPut.add(pTo);

        return pOutPut;
        }