Problem with PIE in JSP got some exception

Hi guys,

Good to see u all .

Iam working on Pie diagrams in JSP.I've tried but I got some errors in it .Iam pasting the code.Please don't mind if the code is big..

Iam not using any of the *.jar files.and my code doesn't use it.Help me in this code..

Pie.jsp

<%@ page language="java" %>

<%@ page import="java.io.OutputStream" %>

<%@ page import="java.sql.*" %>

<%@ page import="java.awt.*" %>

<%@ page import="java.awt.geom.*" %>

<%@ page import="java.awt.image.BufferedImage" %>

<%@ page import="com.sun.image.codec.jpeg.*" %>

<HR>

<HTML><BODY BGCOLOR="#BADAF2" >

<p align='center'><b><font face="verdana" size="3" color='#800000'>Pie Diagram</font></b>

<%!

////////////////////////////////////////////////////////////

// PieColors class manages the colors used in the pie chart

////////////////////////////////////////////////////////////

class PieColors

{

Color pieColorArray[] ;

int curPieColor = 0;

public Color getPieColor()

{

return pieColorArray[curPieColor];

}

public void setNewColor()

{

curPieColor++;

if(curPieColor >= pieColorArray.length)

{

curPieColor = 0;

}

}

}

%>

<%!

////////////////////////////////////////////////////////////

// Get the products from the database as a String array

////////////////////////////////////////////////////////////

public String[] getProducts()

{

String[] arr = new String[0];

Connection con;

Statement stmt;

ResultSet rs;

int count = 0;

String sql = "select * from dummy_products order by productID";

try

{

DriverManager.registerDriver(new oracle.jdbc.driver.OracleDriver());

con = DriverManager.getConnection("jdbc:oracle:thin:@dbadmin:1521:cgsdb","scott","tiger");

stmt = con.createStatement();

//Get ResultSet

rs = stmt.executeQuery(sql);

//Count the records

while(rs.next()){count++;}

//Create an array of the correct size

arr = new String[count];

//Get ResultSet (the most portable way of using rs a second time)

rs = stmt.executeQuery(sql);

while(rs.next())

{

arr[rs.getInt("productID")] = rs.getString("productname");

}

stmt.close();

con.close();

}

catch (java.lang.Exception ex)

{

arr[0] = ex.toString();

}

return arr;

}

////////////////////////////////////////////////////////////

// Get the sales totals from the database

////////////////////////////////////////////////////////////

public float[] getSales(int products)

{

float[] arr = new float[products];

Connection con;

Statement stmt;

ResultSet rs;

String sql = "select productID, amount from dummy_sales";

try

{

DriverManager.registerDriver(new oracle.jdbc.driver.OracleDriver());

con = DriverManager.getConnection("jdbc:oracle:thin:@dbadmin:1521:cgsdb","scott","tiger");

stmt = con.createStatement();

//Get ResultSet

rs = stmt.executeQuery(sql);

while (rs.next())

{

int product = rs.getInt("productID");

//Check that the productID is valid

if (product >= 0 && product < products)

{

//Add to product total

arr[product] += rs.getFloat("amount");

}

}

stmt.close();

con.close();

}

catch (java.lang.Exception ex)

{

arr[0] = -1.0f;

}

return arr;

}

%>

<%

//get an array that contains the product names

String products[] = getProducts();

//read the data and store the totals in an array

float sales[] = getSales(products.length);

//Declare PieColors

PieColors pc = new PieColors();

//Colors

Color dropShadow = new Color(240,240,240);

//inner padding to make sure bars never touch the outer border

int innerOffset = 20;

//Set the graph's outer width & height

int WIDTH = 400;

int HEIGHT = 200;

int pieHeight = HEIGHT - (innerOffset * 2);

int pieWidth = pieHeight;//To make a square (circular) pie

int halfWidth = WIDTH/2;

//Width of the inner graphable area

int innerWIDTH = WIDTH - (innerOffset * 2);

//graph dimensions

Dimension graphDim = new Dimension(WIDTH,HEIGHT);

Rectangle graphRect = new Rectangle(graphDim);

//border dimensions

Dimension borderDim = new Dimension(halfWidth-2,HEIGHT-2);

Rectangle borderRect = new Rectangle(borderDim);

///////////////////////////////////////////////////////////////////////////////////////

//Set up the graph

///////////////////////////////////////////////////////////////////////////////////////

//Set content type

response.setContentType("image/jpeg");

//Create BufferedImage & Graphics2D

BufferedImage bi = new BufferedImage(WIDTH, HEIGHT, BufferedImage.TYPE_INT_RGB);

Graphics2D g2d = bi.createGraphics();

// Set Antialiasing

RenderingHints renderHints =

new RenderingHints(

RenderingHints.KEY_ANTIALIASING,

RenderingHints.VALUE_ANTIALIAS_ON);

g2d.setRenderingHints(renderHints);

//Set graph background color to white:

g2d.setColor(Color.white);

g2d.fill(graphRect);

//Draw black border

g2d.setColor(Color.black);

borderRect.setLocation(1,1);

g2d.draw(borderRect);

//Now draw border for legend

borderRect.setLocation((WIDTH/2) + 1,1);

g2d.draw(borderRect);

/////////////////////////////////////////////////////////////////////////////////////

//Draw data onto the graph:

/////////////////////////////////////////////////////////////////////////////////////

int x_pie = innerOffset;

int y_pie = innerOffset;

int border = 20;

//Main chart Ellipse

//Ellipse2D.Double el = new Ellipse2D.Double(x_pie, y_pie, pieWidth, pieHeight);

Ellipse2D.Double elb = new Ellipse2D.Double(x_pie - border/2, y_pie - border/2, pieWidth + border, pieHeight + border);

//Shadow

g2d.setColor(dropShadow);

g2d.fill(elb);

//Border

g2d.setColor(Color.black);

g2d.draw(elb);

/////////////////////////////////////////////////////////////////////////////////////

// Calculate the total sales

/////////////////////////////////////////////////////////////////////////////////////

float salesTotal = 0.0f;

int lastElement = 0;

for(int i=0; i<products.length; i++)

{

if(sales > 0.0f)

{

salesTotal += sales;

lastElement = i;

}

}

/////////////////////////////////////////////////////////////////////////////////////

// Draw the pie chart

/////////////////////////////////////////////////////////////////////////////////////

//Chart variables

int startAngle = 0;

//Legend variables

int legendWidth = 20;

int x_legendText = halfWidth + innerOffset/2 + legendWidth + 5;

int x_legendBar = halfWidth + innerOffset/2;

int textHeight = 20;

int curElement = 0;

int y_legend = 0;

//Dimensions of the legend bar

Dimension legendDim = new Dimension(legendWidth , textHeight/2);

Rectangle legendRect = new Rectangle(legendDim);

for(int i=0; i<products.length; i++)

{

if(sales > 0.0f)

{

//Calculate percentage sales

float perc = (sales/salesTotal);

//Calculate new angle

int sweepAngle = (int)(perc * 360);

//Check that the last element goes back to 0 position

if (i == lastElement)

{

sweepAngle = 360-startAngle;

}

// Draw Arc

g2d.setColor(pc.getPieColor());

g2d.fillArc(x_pie, y_pie, pieWidth, pieHeight, startAngle, sweepAngle);

//Increment startAngle with the sweepAngle

startAngle += sweepAngle;

///////////////Draw Legend/////////////

//Set y position for bar

y_legend = curElement * textHeight + innerOffset;

//Display the current product

String display = products;

g2d.setColor(Color.black);

g2d.drawString(display, x_legendText, y_legend);

//Display the total sales

display = "" + (int)sales;

g2d.setColor(Color.black);

g2d.drawString(display, x_legendText + 80, y_legend);

//Display the sales percentage

display = " (" + (int)(perc*100) + "%)";

g2d.setColor(Color.red);

g2d.drawString(display, x_legendText + 110, y_legend);

//Draw the bar

g2d.setColor(pc.getPieColor());

legendRect.setLocation(x_legendBar,y_legend - textHeight/2);

g2d.fill(legendRect);

//Set new pie color

pc.setNewColor();

//IncrementcurElement++;

}

}

/////////////////////////////////////////////////////////////////////////////////////

// Encode the graph

/////////////////////////////////////////////////////////////////////////////////////

OutputStream output = response.getOutputStream();

JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(output);

encoder.encode(bi);

output.close();

%>

</BODY>

</HTML>

///////////

I got the following Exception on executing the above code

java.lang.NoClassDefFoundError: sun/awt/X11GraphicsEnvironment

at java.lang.Class.forName0(Native Method)

at java.lang.Class.forName0(Compiled Code)

at java.lang.Class.forName(Compiled Code)

at java.awt.GraphicsEnvironment.getLocalGraphicsEnvironment(GraphicsEnvironment.java:63)

at java.awt.image.BufferedImage.createGraphics(Compiled Code)

at _qs._icms._pie1._jspService(Compiled Code)

[10366 byte] By [prawina] at [2007-10-2 4:03:57]
# 1
Can you tell me your environment(Operating system etc.) The Sun AWT classes on Unix and Linux have a dependence on the X Window System: when you use the classes, they expect to load X client libraries and be able to talk to an X display server.
Java_Kida at 2007-7-15 23:26:28 > top of Java-index,Java Essentials,New To Java...
# 2
Iam executing my code in the Server itself which is in Solaris PlatformThe webserver iam using is ApacheDoes java import the package below or do we have to use some package. <%@ page import="com.sun.image.codec.jpeg.*" %>Thanks for the reply
prawina at 2007-7-15 23:26:28 > top of Java-index,Java Essentials,New To Java...
# 3
Nice formatting
ScarletPimpernela at 2007-7-15 23:26:28 > top of Java-index,Java Essentials,New To Java...
# 4

<%@ page language="java" %>

<%@ page import="java.io.OutputStream" %>

<%@ page import="java.sql.*" %>

<%@ page import="java.awt.*" %>

<%@ page import="java.awt.geom.*" %>

<%@ page import="java.awt.image.BufferedImage" %>

<%@ page import="com.sun.image.codec.jpeg.*" %>

<HR>

<HTML><BODY BGCOLOR="#BADAF2" >

<p align='center'><b><font face="verdana" size="3" color='#800000'>Pie Diagram</font></b>

<%!

////////////////////////////////////////////////////////////

// PieColors class manages the colors used in the pie chart

////////////////////////////////////////////////////////////

class PieColors

{

Color pieColorArray[] ;

int curPieColor = 0;

public Color getPieColor()

{

return pieColorArray[curPieColor];

}

public void setNewColor()

{

curPieColor++;

if(curPieColor >= pieColorArray.length)

{

curPieColor = 0;

}

}

}

%>

<%!

////////////////////////////////////////////////////////////

// Get the products from the database as a String array

////////////////////////////////////////////////////////////

public String[] getProducts()

{

String[] arr = new String[0];

Connection con;

Statement stmt;

ResultSet rs;

int count = 0;

String sql = "select * from dummy_products order by productID";

try

{

DriverManager.registerDriver(new oracle.jdbc.driver.OracleDriver());

con = DriverManager.getConnection("jdbc:oracle:thin:@dbadmin:1521:cgsdb","scott","tiger");

stmt = con.createStatement();

//Get ResultSet

rs = stmt.executeQuery(sql);

//Count the records

while(rs.next()){count++;}

//Create an array of the correct size

arr = new String[count];

//Get ResultSet (the most portable way of using rs a second time)

rs = stmt.executeQuery(sql);

while(rs.next())

{

arr[rs.getInt("productID")] = rs.getString("productname");

}

stmt.close();

con.close();

}

catch (java.lang.Exception ex)

{

arr[0] = ex.toString();

}

return arr;

}

////////////////////////////////////////////////////////////

// Get the sales totals from the database

////////////////////////////////////////////////////////////

public float[] getSales(int products)

{

float[] arr = new float[products];

Connection con;

Statement stmt;

ResultSet rs;

String sql = "select productID, amount from dummy_sales";

try

{

DriverManager.registerDriver(new oracle.jdbc.driver.OracleDriver());

con = DriverManager.getConnection("jdbc:oracle:thin:@dbadmin:1521:cgsdb","scott","tiger");

stmt = con.createStatement();

//Get ResultSet

rs = stmt.executeQuery(sql);

while (rs.next())

{

int product = rs.getInt("productID");

//Check that the productID is valid

if (product >= 0 && product < products)

{

//Add to product total

arr[product] += rs.getFloat("amount");

}

}

stmt.close();

con.close();

}

catch (java.lang.Exception ex)

{

arr[0] = -1.0f;

}

return arr;

}

%>

<%

//get an array that contains the product names

String products[] = getProducts();

//read the data and store the totals in an array

float sales[] = getSales(products.length);

//Declare PieColors

PieColors pc = new PieColors();

//Colors

Color dropShadow = new Color(240,240,240);

//inner padding to make sure bars never touch the outer border

int innerOffset = 20;

//Set the graph's outer width & height

int WIDTH = 400;

int HEIGHT = 200;

int pieHeight = HEIGHT - (innerOffset * 2);

int pieWidth = pieHeight;//To make a square (circular) pie

int halfWidth = WIDTH/2;

//Width of the inner graphable area

int innerWIDTH = WIDTH - (innerOffset * 2);

//graph dimensions

Dimension graphDim = new Dimension(WIDTH,HEIGHT);

Rectangle graphRect = new Rectangle(graphDim);

//border dimensions

Dimension borderDim = new Dimension(halfWidth-2,HEIGHT-2);

Rectangle borderRect = new Rectangle(borderDim);

///////////////////////////////////////////////////////////////////////////////////////

//Set up the graph

///////////////////////////////////////////////////////////////////////////////////////

//Set content type

response.setContentType("image/jpeg");

//Create BufferedImage & Graphics2D

BufferedImage bi = new BufferedImage(WIDTH, HEIGHT, BufferedImage.TYPE_INT_RGB);

Graphics2D g2d = bi.createGraphics();

// Set Antialiasing

RenderingHints renderHints =

new RenderingHints(

RenderingHints.KEY_ANTIALIASING,

RenderingHints.VALUE_ANTIALIAS_ON);

g2d.setRenderingHints(renderHints);

//Set graph background color to white:

g2d.setColor(Color.white);

g2d.fill(graphRect);

//Draw black border

g2d.setColor(Color.black);

borderRect.setLocation(1,1);

g2d.draw(borderRect);

//Now draw border for legend

borderRect.setLocation((WIDTH/2) + 1,1);

g2d.draw(borderRect);

/////////////////////////////////////////////////////////////////////////////////////

//Draw data onto the graph:

/////////////////////////////////////////////////////////////////////////////////////

int x_pie = innerOffset;

int y_pie = innerOffset;

int border = 20;

//Main chart Ellipse

//Ellipse2D.Double el = new Ellipse2D.Double(x_pie, y_pie, pieWidth, pieHeight);

Ellipse2D.Double elb = new Ellipse2D.Double(x_pie - border/2, y_pie - border/2, pieWidth + border, pieHeight + border);

//Shadow

g2d.setColor(dropShadow);

g2d.fill(elb);

//Border

g2d.setColor(Color.black);

g2d.draw(elb);

/////////////////////////////////////////////////////////////////////////////////////

// Calculate the total sales

/////////////////////////////////////////////////////////////////////////////////////

float salesTotal = 0.0f;

int lastElement = 0;

for(int i=0; i<products.length; i++)

{

if(sales[i] > 0.0f)

{

salesTotal += sales[i];

lastElement = i;

}

}

/////////////////////////////////////////////////////////////////////////////////////

// Draw the pie chart

/////////////////////////////////////////////////////////////////////////////////////

//Chart variables

int startAngle = 0;

//Legend variables

int legendWidth = 20;

int x_legendText = halfWidth + innerOffset/2 + legendWidth + 5;

int x_legendBar = halfWidth + innerOffset/2;

int textHeight = 20;

int curElement = 0;

int y_legend = 0;

//Dimensions of the legend bar

Dimension legendDim = new Dimension(legendWidth , textHeight/2);

Rectangle legendRect = new Rectangle(legendDim);

for(int i=0; i<products.length; i++)

{

if(sales[i] > 0.0f)

{

//Calculate percentage sales

float perc = (sales[i]/salesTotal);

//Calculate new angle

int sweepAngle = (int)(perc * 360);

//Check that the last element goes back to 0 position

if (i == lastElement)

{

sweepAngle = 360-startAngle;

}

// Draw Arc

g2d.setColor(pc.getPieColor());

g2d.fillArc(x_pie, y_pie, pieWidth, pieHeight, startAngle, sweepAngle);

//Increment startAngle with the sweepAngle

startAngle += sweepAngle;

///////////////Draw Legend/////////////

//Set y position for bar

y_legend = curElement * textHeight + innerOffset;

//Display the current product

String display = products[i];

g2d.setColor(Color.black);

g2d.drawString(display, x_legendText, y_legend);

//Display the total sales

display = "" + (int)sales[i];

g2d.setColor(Color.black);

g2d.drawString(display, x_legendText + 80, y_legend);

//Display the sales percentage

display = " (" + (int)(perc*100) + "%)";

g2d.setColor(Color.red);

g2d.drawString(display, x_legendText + 110, y_legend);

//Draw the bar

g2d.setColor(pc.getPieColor());

legendRect.setLocation(x_legendBar,y_legend - textHeight/2);

g2d.fill(legendRect);

//Set new pie color

pc.setNewColor();

//IncrementcurElement++;

}

}

/////////////////////////////////////////////////////////////////////////////////////

// Encode the graph

/////////////////////////////////////////////////////////////////////////////////////

OutputStream output = response.getOutputStream();

JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(output);

encoder.encode(bi);

output.close();

%>

</BODY>

</HTML>

prawina at 2007-7-15 23:26:28 > top of Java-index,Java Essentials,New To Java...
# 5

The Sun AWT classes on Unix and Linux have a dependence on the X Window System: when you use the classes, they expect to load X client libraries and be able to talk to an X display server. This makes sense if your client has a GUI... unfortunately, it's required even if your client uses AWT but does not have a GUI. For example, you need access to an X server to use the java.awt.BufferedImage class.

Access to an X display server means a few things:

An X display server is running somewhere.

The environment in which you run Java includes an environment variable DISPLAY identifying how to reach the server.

There are no security settings in the server to prevent your client from opening a connection.

In general, if you're running your program from a terminal within the X Window System, all these things are true and the program just works. If you can run other X applications, like xterm or xclock, you should be able to run your Java AWT application.

In non-graphical environments, such as a servlet engine, your program may not know how to find or connect to an X display server. A common solution here is to run a special non-display version of the X display server, Xvfb, and set DISPLAY to point to it.

New information for JDK1.4: JDK1.4 evidently includes a new property that will allow the AWT to run in a headless (without a display) environment. This setting is supposed to solve the problem: java.awt.headless=true

Java_Kida at 2007-7-15 23:26:28 > top of Java-index,Java Essentials,New To Java...