1 22 23 package de.laures.cewolf.util; 24 25 import java.awt.Color ; 26 import java.awt.Font ; 27 import java.awt.Graphics ; 28 import java.awt.image.BufferedImage ; 29 import java.io.IOException ; 30 import java.io.OutputStream ; 31 import java.io.PrintWriter ; 32 import java.io.StringWriter ; 33 import java.util.Enumeration ; 34 import java.util.StringTokenizer ; 35 36 import com.sun.image.codec.jpeg.JPEGCodec; 37 import com.sun.image.codec.jpeg.JPEGEncodeParam; 38 import com.sun.image.codec.jpeg.JPEGImageEncoder; 39 40 44 public class RenderingHelper { 45 46 private final static int PADDING_X = 5; 47 48 public static String renderMessage(String msg, int width, int height, OutputStream out) throws IOException { 49 BufferedImage image = ImageHelper.createImage(width, height); 50 Graphics gr = image.getGraphics(); 51 gr.setColor(Color.white); 52 gr.fillRect(0, 0, width, height); 53 gr.setColor(Color.black); 54 gr.drawString(msg, PADDING_X, height/2 - 7); 55 JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out); 56 JPEGEncodeParam param = encoder.getDefaultJPEGEncodeParam(image); 57 param.setQuality(1.0f, true); 58 encoder.encode(image, param); 59 return "image/jpeg"; 60 } 61 62 public static String renderException(Throwable ex, int width, int height, OutputStream out) throws IOException { 63 BufferedImage image = ImageHelper.createImage(width, height); 64 Graphics gr = image.getGraphics(); 65 gr.setColor(Color.white); 66 gr.fillRect(0, 0, width, height); 67 gr.setColor(Color.red); 68 gr.drawString(ex.getClass().getName() + " raised:", PADDING_X, 15); 69 gr.drawString(String.valueOf(ex.getMessage()), PADDING_X, 30); 70 gr.setColor(Color.black); 71 Font stFont = gr.getFont().deriveFont(9f); 72 gr.setFont(stFont); 73 drawStackTrace(gr, PADDING_X, 50, ex); 74 JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out); 75 JPEGEncodeParam param = encoder.getDefaultJPEGEncodeParam(image); 76 param.setQuality(1.0f, true); 77 encoder.encode(image, param); 78 return "image/jpeg"; 79 } 80 81 private static void drawStackTrace(Graphics gr, int x, int y, Throwable ex) { 82 final int linePadding = 4; 83 int lineHeight = gr.getFont().getSize() + linePadding; 84 int currY = y; 85 Enumeration lines = new StringTokenizer (getStackTrace(ex), "\n", false); 86 while (lines.hasMoreElements()) { 87 gr.drawString(((String )lines.nextElement()).trim(), x, currY); 88 currY += lineHeight; 89 } 90 } 91 92 private static String getStackTrace(Throwable t) { 93 StringWriter sw = new StringWriter (); 94 PrintWriter pw = new PrintWriter (sw); 95 t.printStackTrace(pw); 96 pw.close(); 97 return sw.getBuffer().toString(); 98 } 99 100 } 101 | Popular Tags |