Manu
Location : Paris / France
Member since : Apr 29, 2003
Messages : 394
|
Aug 8, 2003 at 7:12 AM
If you have troubles running this servlet try the following PJATeksSurveyPie servlet which is a modified version of TeksSurveyPie that directly extends HttpServlet and uses PJA classes explicitly. This avoids changing some system properties and runs on any machine even if no X11 libs are installed. You'll have to create at least one .pjaf font file and copy it in your WEB-INF directory (see the init method to change paths if necessary) :
--------
package com.eteks.servlet;
import javax.servlet.http.*;
import javax.servlet.*;
import java.io.*;
import java.util.*;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.image.FilteredImageSource;
import Acme.JPM.Encoders.GifEncoderNoCM;
import com.eteks.filter.Web216ColorsFilter;
import com.eteks.awt.*;
/**
* This servlet manages in a simple way a dynamic survey and returns the pie of the survey.
* It can be called in either ways :
* <UL><LI><code>.../servlet/com.eteks.servlet.TeksSurveyPie?survey=mySurvey&answer=myAnswer</code>
* adds the answer <code>myAnswer</code> to the survey <code>mySurvey</code>,
* and then returns the pie of the current state of <code>mySurvey</code>.
* <LI><code>.../servlet/com.eteks.servlet.TeksSurveyPie?survey=mySurvey</code>
* simply returns the pie of the current state of <code>mySurvey</code>.</UL>
*
* @author Emmanuel Puybaret
*/
public class PJATeksSurveyPie extends HttpServlet
{
Properties surveysParam = new Properties ();
String surveysFile;
// Colors used to fill the pie
final int colors [][] = {{0, 0, 255}, // Blue
{0, 255, 0}, // Green
{255, 0, 0}, // Red
{0, 255, 255}, // Cyan
{255, 0, 255}, // Magenta
{128, 128, 128}, // Gray
{255, 255, 0}, // Yellow
{255, 175, 175}, // Pink
{255, 200, 0}, // Orange
{255, 255, 255}}; // White
final int [] penColor = {0, 0, 0};
public void init (ServletConfig config) throws ServletException
{
// Store the ServletConfig object and log the initialization
super.init (config);
// Default value for "java.awt.fonts" .pjaf fonts directory
fontsDir = getServletContext().getRealPath("/WEB-INF");
// Retrieves .pjaf fonts directory if specified in init parameter
String param = getInitParameter ("fontsDir");
if (param != null)
fontsDir = param;
// Change java.awt.fonts System property
String currentFontsDir = System.getProperty ("java.awt.fonts");
if (currentFontsDir == null)
System.setProperty ("java.awt.fonts", fontsDir);
else if (currentFontsDir.indexOf (File.pathSeparator + fontsDir + File.pathSeparator) == -1)
System.setProperty ("java.awt.fonts", currentFontsDir + File.pathSeparator + fontsDir + File.pathSeparator);
// Default value for survey file
surveysFile = getServletContext().getRealPath("/WEB-INF") + File.separator + "survey.txt";
// Retrieves surveys file path if specified in init parameter
param = getInitParameter ("surveysFile");
if (param != null)
surveysFile = param;
// Read surveys file
FileInputStream in = null;
try
{
in = new FileInputStream (surveysFile);
surveysParam.load (in);
}
catch (IOException e)
{ } // Empty properties
finally
{
try
{
if (in != null)
in.close ();
}
catch (IOException ex)
{ }
}
}
public void destroy ()
{
try
{
surveysParam.save (new FileOutputStream (surveysFile), "Survey file");
}
catch (IOException e)
{
throw new RuntimeException ("Properties can't be saved");
}
}
public void doPost (HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException
{
doGet (request, response);
}
public void doGet (HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException
{
String survey = request.getParameter ("survey"); // Survey name
String answer = request.getParameter ("answer"); // Proposed answer
String paramWidth = request.getParameter ("width");
String paramHeight = request.getParameter ("height");
int width = paramWidth == null ? 200 : Integer.parseInt (paramWidth);
int height = paramHeight == null ? 100 : Integer.parseInt (paramHeight);
Image image = new PJAImage (width, height);
if (survey == null)
survey = "";
if (answer != null)
{
String key = survey + "_" + answer;
String value = surveysParam.getProperty (key);
if (value != null)
// If the answer already exists, increase its value
surveysParam.put (key, String.valueOf (Integer.parseInt (value) + 1));
else
{
String surveyAnswers = surveysParam.getProperty (survey);
// Add this answer to the other ones
if (surveyAnswers == null)
surveysParam.put (survey, answer);
else
surveysParam.put (survey, surveyAnswers + "," + answer);
surveysParam.put (key, "1");
}
}
Hashtable answers = new Hashtable ();
Vector sortedAnswers = new Vector ();
synchronized (surveysParam)
{
String surveyAnswers = surveysParam.getProperty (survey);
if (surveyAnswers != null)
for (StringTokenizer tokens = new StringTokenizer (surveyAnswers, ",");
tokens.hasMoreTokens (); )
{
String token = tokens.nextToken ();
int answerCount = Integer.parseInt (surveysParam.getProperty (survey + "_" + token));
answers.put (token, new Integer (answerCount));
// Seek the good place to insert this element
int i;
for (i = 0; i < sortedAnswers.size (); i++)
if (answerCount > ((Integer)answers.get (sortedAnswers.elementAt (i))).intValue ())
break;
sortedAnswers.insertElementAt (token, i);
}
}
// Compute the pies of the survey
drawSurveyPies (image, answers, sortedAnswers, width, height);
// Send generated image
sendGIFImage (image, response);
}
/**
* Generates a GIF image on the response stream from image.
*/
public void sendGIFImage (Image image, HttpServletResponse response) throws ServletException, IOException
{
// Set content type and other response header fields first
response.setContentType("image/gif");
// Then write the data of the response
OutputStream out = response.getOutputStream ();
try
{
new GifEncoderNoCM (image, out).encode ();
}
catch (IOException e)
{
// GifEncoder may throw an IOException because "too many colors for a GIF" (> 256)
// were found in the image
// Reduce the number of colors in that case with Web216ColorsFilter basic filter
new GifEncoderNoCM (new FilteredImageSource (image.getSource (),
new Web216ColorsFilter ()),
out).encode ();
}
out.flush ();
}
private void drawSurveyPies (Image image,
Hashtable answers,
Vector sortedAnswers,
int width,
int height)
{
PJAGraphics gc = (PJAGraphics)image.getGraphics ();
// Draw a shadow
gc.setColor (63, 63, 63);
gc.fillOval (1, 1, height - 3, height - 3);
gc.fillOval (2, 2, height - 3, height - 3);
// Compute the sum of all values
int sum = 0;
for (Enumeration e = answers.elements ();
e.hasMoreElements (); )
sum += ((Integer)e.nextElement ()).intValue ();
for (int accum = 0, i = 0, deltaY = 0; i < sortedAnswers.size (); i++, deltaY += 15)
{
int answerValue = ((Integer)answers.get (sortedAnswers.elementAt (i))).intValue ();
int startAngle = accum * 360 / sum;
int angle = answerValue * 360 / sum;
// Fill the anwser pie
gc.setColor (colors[i % colors.length][0],
colors[i % colors.length][1],
colors[i % colors.length][2]);
gc.fillArc (0, 0, height - 3, height - 3, startAngle, angle);
// Draw a separating line
gc.setColor (penColor[0], penColor[1], penColor[2]);
gc.drawLine ((height - 3) / 2, (height - 3) / 2,
(int)((height - 3) / 2. * (1 + Math.cos (startAngle / 180. * Math.PI)) + 0.5),
(int)((height - 3) / 2. * (1 - Math.sin (startAngle / 180. * Math.PI)) + 0.5));
accum += answerValue;
if (deltaY + 15 < height)
{
// Add a comment
gc.setColor (colors[i % colors.length][0],
colors[i % colors.length][1],
colors[i % colors.length][2]);
gc.fillRect (height + 6, deltaY + 1, 13, 10);
gc.setColor (penColor[0], penColor[1], penColor[2]);
gc.drawRect (height + 5, deltaY, 14, 11);
// Draw is done with default font
gc.drawString (String.valueOf (100 * answerValue / sum) + "% " + (String)sortedAnswers.elementAt (i),
height + 22, deltaY + 10);
}
}
gc.drawLine ((height - 3) / 2, (height - 3) / 2, height - 3, (height - 3) / 2);
// Draw a surrounding oval
gc.drawOval (0, 0, height - 3, height - 3);
}
} --- Manu (moderator/modérateur)
|