source: trunk/src/org/expeditee/io/Conversion.java@ 376

Last change on this file since 376 was 362, checked in by ra33, 16 years ago

Added Spell Checker
Added word count stats
Fixed some mail stuff

File size: 15.9 KB
Line 
1package org.expeditee.io;
2
3import java.awt.Color;
4import java.awt.Font;
5import java.awt.Point;
6import java.lang.reflect.Field;
7import java.lang.reflect.Method;
8import java.util.LinkedList;
9import java.util.List;
10import java.util.StringTokenizer;
11
12import org.expeditee.actions.Actions;
13import org.expeditee.items.Item;
14import org.expeditee.items.Justification;
15import org.expeditee.items.Permission;
16import org.expeditee.items.Text;
17
18import com.lowagie.text.FontFactory;
19
20/**
21 * This class provides various methods for converting values to\from Java
22 * objects and Expeditee file values.
23 *
24 * @author jdm18
25 *
26 */
27public class Conversion {
28
29 public static final int RGB_MAX = 255;
30
31 private static final float RGB_CONVERSION_FACTOR = 2.55F;
32
33 /**
34 * Returns the Color corresponding to the given Expeditee color code. For
35 * example: <br>
36 * green4 = 0% red, 40% green, 0% blue.
37 *
38 * @param colorCode
39 * The Expeditee color code to convert
40 * @return The Color object corresponding to the given code
41 */
42 public static Color getColor(String colorCode, Color current) {
43 if (colorCode == null) {
44 return null;
45 }
46 // The if we dont do this then we end up getting black
47 colorCode = colorCode.toLowerCase();
48 if (colorCode.equals("null"))
49 return null;
50
51 // check if its a normal rgb code ie. 100 0 40
52 Color rgb = getRGBColor(colorCode, current);
53 if (rgb != null)
54 return rgb;
55
56 // separate percentage from color (if necessary)
57 String num = "";
58 int last = colorCode.length() - 1;
59
60 char c = colorCode.charAt(last);
61
62 while (Character.isDigit(c)) {
63 num = c + num;
64 if (last <= 0)
65 break;
66
67 c = colorCode.charAt(--last);
68 }
69
70 final float MAX_AMOUNT = 10F;
71 float amount = MAX_AMOUNT;
72 if (num.length() > 0)
73 amount = Float.parseFloat(num);
74
75 if (amount > MAX_AMOUNT)
76 amount = MAX_AMOUNT;
77
78 float color[] = { 0, 0, 0 };
79 // Assert.assertTrue(color.length == 3);
80
81 if (colorCode.startsWith("red"))
82 color[0] = amount / MAX_AMOUNT;
83 else if (colorCode.startsWith("green"))
84 color[1] = amount / MAX_AMOUNT;
85 else if (colorCode.startsWith("blue"))
86 color[2] = amount / MAX_AMOUNT;
87 else
88 return null;
89
90 return new Color(color[0], color[1], color[2]);
91 }
92
93 private static Color getRGBColor(String colorCode, Color current) {
94 int color[] = new int[3];
95 // Assert.assertTrue(color.length == 3);
96
97 try {
98 String[] values = colorCode.trim().split("\\s+");
99 // For now no transparency only RGB
100 if (values.length > color.length)
101 return null;
102
103 String r = values.length > 0 ? values[0] : "0";
104 String g = values.length > 1 ? values[1] : "0";
105 String b = values.length > 2 ? values[2] : "0";
106
107 int red = (current == null ? 0 : toColorPercent(current.getRed()));
108 int green = (current == null ? 0 : toColorPercent(current
109 .getGreen()));
110 int blue = (current == null ? 0 : toColorPercent(current.getBlue()));
111 color[0] = (Integer) Convert(int.class, r, red);
112 color[1] = (Integer) Convert(int.class, g, green);
113 color[2] = (Integer) Convert(int.class, b, blue);
114
115 for (int i = 0; i < color.length; i++) {
116 color[i] = toRGB(color[i]);
117 }
118 return new Color(color[0], color[1], color[2]);
119 } catch (Exception e) {
120 return null;
121 }
122 }
123
124 private static Integer toColorPercent(int rgb) {
125 assert (rgb >= 0);
126 assert (rgb <= RGB_MAX);
127
128 int percent = (int) Math.round(rgb / RGB_CONVERSION_FACTOR);
129
130 // Dont need to do the checking below because this method will always be
131 // called with good values
132 // if (percent > PERCENT_MAX)
133 // percent = PERCENT_MAX;
134 // else if (percent < 0)
135 // percent = 0;
136
137 return percent;
138 }
139
140 private static Integer toRGB(int percent) {
141 int rgb = Math.round(percent * RGB_CONVERSION_FACTOR);
142 if (rgb > RGB_MAX)
143 rgb = RGB_MAX;
144 else if (rgb < 0)
145 rgb = 0;
146
147 return rgb;
148 }
149
150 /**
151 * Converts the given Color object to the corresponding Expeditee color code
152 *
153 * @param color
154 * The Color to be turned into Expeditee color code.
155 * @return A String containing the Expeditee color code, NULL if the color
156 * is black.
157 */
158 public static String getExpediteeColorCode(Color color) {
159 if (color == null)
160 return null;
161
162 int r = (int) Math.round((color.getRed() / RGB_CONVERSION_FACTOR));
163 int g = (int) Math.round((color.getGreen() / RGB_CONVERSION_FACTOR));
164 int b = (int) Math.round((color.getBlue() / RGB_CONVERSION_FACTOR));
165
166 return r + " " + g + " " + b;
167 }
168
169 /**
170 * Converts the given Font to a corresponding Expeditee font code.
171 *
172 * @param font
173 * The Font to convert to a code.
174 * @return The Expeditee font code that corresponds to the given Font.
175 */
176 public static String getExpediteeFontCode(Font font) {
177 String fontName = font.getFamily();
178 String code = font.getFamily() + '_';
179
180 for (int i = 0; i < Text.FONT_WHEEL.length; i++) {
181 if (Text.FONT_WHEEL[i].equalsIgnoreCase(fontName)) {
182 code = "" + Text.FONT_CHARS[i];
183 break;
184 }
185 }
186
187 switch (font.getStyle()) {
188 case Font.BOLD:
189 code += "b";
190 break;
191 case Font.PLAIN:
192 code += "r";
193 break;
194 case Font.ITALIC:
195 code += "i";
196 break;
197 default:
198 code += "p";
199 break;
200 }
201
202 code += font.getSize();
203 return code;
204 }
205
206 /**
207 * Converts the given Expeditee font code to a Font object.<br>
208 * For example: <br>
209 * tr16 = times, roman, 16pt
210 *
211 * @param fontCode
212 * The font code to convert to a Font
213 * @return the Font that corresponds to the given font code.
214 */
215 public static Font getFont(String fontCode) {
216 assert (fontCode != null);
217
218 int separator = fontCode.indexOf('_');
219 String code = Text.FONT_WHEEL[0];
220 if (separator > 0) {
221 code = Actions.getCapitalizedFontName(fontCode.substring(0,
222 separator)) + '-';
223 fontCode = fontCode.substring(separator);
224 } else {
225 char c = fontCode.charAt(0);
226 for (int i = 0; i < Text.FONT_CHARS.length; i++) {
227 if (c == Text.FONT_CHARS[i]) {
228 code = Text.FONT_WHEEL[i] + '-';
229 break;
230 }
231 }
232 }
233
234 switch (fontCode.charAt(1)) {
235 case 'r':
236 code += "Plain";
237 break;
238 case 'b':
239 code += "Bold";
240 break;
241 case 'i':
242 code += "Italic";
243 break;
244 case 'p':
245 code += "BoldItalic";
246 break;
247 }
248
249 code += "-";
250
251 Font font = null;
252
253 try {
254 int size = Integer.parseInt(fontCode.substring(2));
255 // double dsize = size * FONT_SCALE;
256 // if (dsize - ((int) dsize) > FONT_ROUNDING)
257 // dsize = Math.ceil(dsize);
258
259 // code += (int) dsize;
260 code += size;
261
262 font = Font.decode(code);
263 } catch (NumberFormatException nfe) {
264 font = Font.decode(fontCode);
265 }
266
267 return font;
268 }
269
270 /**
271 * Returns the number portion (Frame Number) of the given Frame name.
272 *
273 * @param framename
274 * The Frame name to extract the number from
275 * @return The Frame number
276 */
277 public static int getFrameNumber(String framename) {
278 String num = null;
279 // The framename must end in a digit
280 assert (Character.isDigit(framename.charAt(framename.length() - 1)));
281 // And start with a letter
282 assert (Character.isLetter(framename.charAt(0)));
283 // start at the end and find the first non digit char
284 for (int i = framename.length() - 2; i >= 0; i--) {
285 if (!Character.isDigit(framename.charAt(i))) {
286 num = framename.substring(i + 1);
287 break;
288 }
289 }
290 return Integer.parseInt(num);
291 }
292
293 /**
294 * Returns the frameset poriton of the given Frame name (frame number
295 * removed) converted to lower case.
296 *
297 * @param frame
298 * The full name to extract the Frameset name from
299 * @return the name of the Frameset extracted from the given Frame name.
300 */
301 public static String getFramesetName(String frame) {
302 return getFramesetName(frame, true);
303 }
304
305 public static String getFramesetName(String framename,
306 boolean convertToLower) {
307 String set = null;
308 assert (Character.isDigit(framename.charAt(framename.length() - 1)));
309 // And start with a letter
310 assert (Character.isLetter(framename.charAt(0)));
311 // start at the end and find the first non digit char
312 for (int i = framename.length() - 2; i >= 0; i--) {
313 if (!Character.isDigit(framename.charAt(i))) {
314 set = framename.substring(0, i + 1);
315 break;
316 }
317 }
318
319 if (convertToLower)
320 return set.toLowerCase();
321
322 return set;
323 }
324
325 public static Object Convert(Class type, String value) {
326 return Convert(type, value, null);
327 }
328
329 // Will convert from Expeditee color values to RGB...
330 public static Object Convert(Class type, String value, Object orig) {
331 // System.out.println("Orig: " + orig);
332 assert (type != null);
333
334 if (value == null)
335 return null;
336
337 String fullCaseValue = value;
338 value = fullCaseValue.trim().toLowerCase();
339
340 if (type == Font.class) {
341 return getFont(value);
342 }
343
344 if (type.equals(Color.class)) {
345 if (value.length() == 0)
346 return null;
347
348 try {
349 // Find the field and value of colorName
350 Field[] fields = java.awt.Color.class.getFields();
351 Field field = null;
352 for (int i = 0; i < fields.length; i++) {
353 if (fields[i].getName().equalsIgnoreCase(value)) {
354 field = fields[i];
355 break;
356 }
357 }
358 return (Color) field.get(null);
359 } catch (Exception e) {
360 return getColor(value, (Color) orig);
361 }
362 }
363
364 if (type.equals(int.class)) {
365 if (orig instanceof Integer
366 && (value.startsWith("+") || value.startsWith("-"))) {
367 value = value.replace("+", "");
368
369 return ((Integer) orig) + Integer.decode(value);
370 }
371
372 if (value.length() == 0 || value.equals("null"))
373 return Item.DEFAULT_INTEGER;
374
375 return Integer.decode(value);
376 }
377
378 if (type.equals(float.class)) {
379 if (orig instanceof Float
380 && (value.startsWith("+") || value.startsWith("-"))) {
381 value = value.replace("+", "");
382
383 return ((Float) orig) + Float.parseFloat(value);
384 }
385
386 return Float.parseFloat(value);
387 }
388
389 if (type.equals(Float.class)) {
390 if (orig instanceof Float
391 && (value.startsWith("+") || value.startsWith("-"))) {
392 value = value.replace("+", "");
393
394 return ((Float) orig) + Float.parseFloat(value);
395 }
396
397 if (value.length() == 0 || value.equals("null"))
398 return null;
399
400 return Float.parseFloat(value);
401 }
402
403 if (type.equals(double.class)) {
404 if (orig instanceof Double
405 && (value.startsWith("+") || value.startsWith("-"))) {
406 value = value.replace("+", "");
407
408 return ((Double) orig) + Double.parseDouble(value);
409 }
410
411 return Double.parseDouble(value);
412 }
413
414 if (type.equals(int[].class)) {
415 StringTokenizer st = new StringTokenizer(value, " ");
416 int[] param = new int[st.countTokens()];
417 for (int i = 0; i < param.length; i++) {
418 try {
419 param[i] = Integer.parseInt(st.nextToken());
420 } catch (Exception e) {
421 return null;
422 }
423 }
424
425 return param;
426 }
427
428 if (type.equals(Font.class)) {
429 return Conversion.getFont(value);
430 }
431
432 if (type.equals(boolean.class)) {
433 if (value.equals("t") || value.equals("true")
434 || value.equals("yes") || value.equals("y")
435 || value.equals(""))
436 return true;
437 return false;
438
439 }
440
441 if (type.equals(Point.class)) {
442 Point p = new Point();
443 String xPos = value.substring(0, value.indexOf(" "));
444 String yPos = value.substring(value.indexOf(" ") + 1);
445
446 if (orig == null) {
447 p.x = Integer.parseInt(xPos.trim());
448 p.y = Integer.parseInt(yPos.trim());
449 } else {
450 assert (orig instanceof Point);
451 Point originalPoint = (Point) orig;
452 p.x = (Integer) Convert(int.class, xPos, originalPoint.x);
453 p.y = (Integer) Convert(int.class, yPos, originalPoint.y);
454 }
455 return p;
456 }
457
458 assert (type == String.class);
459 if (value.equals(""))
460 return null;
461 return fullCaseValue;
462 }
463
464 public static Object[] Convert(Method method, String value) {
465 return Convert(method, value, null);
466 }
467
468 /**
469 * Converts parameters for setting an attribute from a string form into an
470 * object array form. The object array can then be passed when invoke the
471 * set method via reflection.
472 *
473 * @param method
474 * a method which sets an attribute
475 * @param value
476 * new value for the attribute
477 * @param current
478 * current value of the attribute
479 * @return
480 */
481 public static Object[] Convert(Method method, String value, Object current) {
482
483 String name = method.getName();
484 Class[] types = method.getParameterTypes();
485
486 String fullValue = value;
487 value = value.trim();
488
489 if (name.endsWith("Justification")) {
490 Justification[] just = new Justification[1];
491 just[0] = Justification.getJustification(value);
492 return just;
493 } else if (name.endsWith("Permission")) {
494 Permission[] permission = new Permission[1];
495 permission[0] = Permission.getPermission(value);
496 return permission;
497 }
498
499 if (name.endsWith("Arrow")) {
500 if (value.indexOf(" ") < 0)
501 return null;
502
503 Float length = null;
504 Double ratio = null;
505
506 if (current == null) {
507 length = getArrowLength(value);
508 ratio = getArrowRatio(value);
509 } else {
510 assert (current instanceof String);
511 float oldLength = getArrowLength(current.toString());
512 double oldRatio = getArrowRatio(current.toString());
513 length = (Float) Convert(float.class, value.substring(0, value
514 .indexOf(" ")), oldLength);
515 ratio = (Double) Convert(double.class, value.substring(
516 value.indexOf(" ")).trim(), oldRatio);
517 }
518
519 Object[] vals = new Object[2];
520 vals[0] = length;
521 vals[1] = ratio;
522 return vals;
523 }
524
525 if (types.length == 1 && types[0] == List.class) {
526 StringTokenizer st = new StringTokenizer(value, "\n");
527 List<String> list = new LinkedList<String>();
528 while (st.hasMoreTokens())
529 list.add(st.nextToken());
530
531 Object[] vals = new Object[1];
532 vals[0] = list;
533 return vals;
534 }
535
536 assert (types.length == 1);
537
538 Object o[] = new Object[1];
539 o[0] = Convert(types[0], fullValue, current);
540 return o;
541 }
542
543 private static float getArrowLength(String s) {
544 return Float.parseFloat(s.substring(0, s.indexOf(" ")));
545 }
546
547 private static double getArrowRatio(String s) {
548 return Double.parseDouble(s.substring(s.indexOf(" ")).trim());
549 }
550
551 public static Object ConvertToExpeditee(Method method, Object output) {
552 if (output == null)
553 return null;
554
555 assert (method != null);
556
557 String name = method.getName();
558
559 if (output instanceof List)
560 return output;
561
562 if (name.endsWith("Text")) {
563 List<String> list = new LinkedList<String>();
564 for (String s : output.toString().split("\n")) {
565 list.add(s);
566 }
567 return list;
568 }
569 if (name.endsWith("Justification"))
570 return ((Justification) output).getCode();
571
572 if (name.endsWith("Permission"))
573 return ((Permission) output).getCode();
574
575 // strings can be returned immediately
576 if (output instanceof String)
577 return (String) output;
578
579 // integers can also be returned immediately
580 if (output instanceof Integer && (Integer) output >= 0)
581 return "" + output;
582
583 // floats can also be returned immediately
584 if (output instanceof Float && (Float) output >= 0)
585 return "" + output;
586
587 // convert fonts
588 if (output instanceof Font)
589 return getExpediteeFontCode((Font) output);
590
591 // convert colors
592 if (output instanceof Color)
593 return getExpediteeColorCode((Color) output);
594
595 // covert points
596 if (output instanceof Point)
597 return ((Point) output).x + " " + ((Point) output).y;
598
599 if (output instanceof Boolean)
600 if ((Boolean) output)
601 return null;
602 else
603 return "F";
604
605 if (output instanceof int[]) {
606 int[] out = (int[]) output;
607 String res = "";
608 for (int i : out)
609 res += i + " ";
610
611 res = res.trim();
612 if (res.length() > 0)
613 return res;
614 }
615 // default
616 return null;
617 }
618
619 public static String getPdfFont(String family) {
620 family = family.toLowerCase();
621 if (family.equals(Text.FONT_WHEEL[0])) {
622 return FontFactory.HELVETICA;
623 } else if (family.equals(Text.FONT_WHEEL[2])) {
624 return FontFactory.TIMES_ROMAN;
625 }
626 return FontFactory.COURIER;
627 }
628
629 public static String getCssColor(Color c) {
630 assert (c != null);
631 return "rgb(" + c.getRed() + "," + c.getGreen() + "," + c.getBlue()
632 + ")";
633 }
634
635 public static String getCssFontFamily(String family) {
636 family = family.toLowerCase();
637 if(family.equals("monospaced") || family.equals("dialog")){
638 return "courier";
639 }else if(family.equals("sansserif")){
640 return "sans-serif";
641 }else{
642 return family;
643 }
644 }
645}
Note: See TracBrowser for help on using the repository browser.