KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > mmbase > module > gui > flash > MMFlash


1 /*
2
3 This software is OSI Certified Open Source Software.
4 OSI Certified is a certification mark of the Open Source Initiative.
5
6 The license (Mozilla version 1.0) can be read at the MMBase site.
7 See http://www.MMBase.org/license
8
9 */

10
11 package org.mmbase.module.gui.flash;
12
13 import java.util.*;
14 import java.io.*;
15
16 import org.mmbase.util.*;
17 import org.mmbase.module.*;
18 import org.mmbase.module.core.*;
19 import org.mmbase.module.builders.*;
20 import org.mmbase.module.gui.html.*;
21
22 import org.mmbase.util.logging.Logger;
23 import org.mmbase.util.logging.Logging;
24
25 /**
26  * Implements the parsing and generating of dynamic flash files
27  * @author Johannes Verelst
28  * @author Daniel Ockeloen
29  * @version $Id: MMFlash.java,v 1.23 2005/08/26 09:09:42 michiel Exp $
30  */

31 public class MMFlash extends Module {
32
33     static final Logger log = Logging.getLoggerInstance(MMFlash.class);
34
35     private String JavaDoc classname = getClass().getName();
36     private boolean debug = false;
37     private String JavaDoc htmlroot;
38
39     private int count=0;
40     scanparser scanp;
41     String JavaDoc subdir;
42     String JavaDoc generatortemppath;
43     String JavaDoc generatorpath;
44     String JavaDoc generatorprogram;
45     LRUHashtable lru=new LRUHashtable(128);
46     MMBase mmb;
47
48     public void init() {
49         htmlroot = MMBaseContext.getHtmlRoot();
50         mmb=(MMBase)getModule("MMBASEROOT");
51         scanp=(scanparser)getModule("SCANPARSER");
52         generatortemppath=getInitParameter("generatortemppath");
53         log.debug("generatortemppath:'"+generatortemppath+"'");
54         generatorpath=getInitParameter("generatorpath");
55         log.debug("generatorpath:'"+generatorpath+"'");
56         generatorprogram=getInitParameter("generatorprogram");
57         log.debug("generatorprogram:'"+generatorprogram+"'");
58         subdir=getInitParameter("subdir");
59         log.debug("subdir:'"+subdir+"'");
60
61         // check if we may create a file on location of generatorTempPath
62
File tempPath = new File(generatortemppath);
63         if(!tempPath.isDirectory()) {
64             log.error("Generator Temp Path was not a direcory('" + generatortemppath + "'), please edit mmflash.xml, or create directory");
65         }
66         try {
67             File test = File.createTempFile("flash", "test", tempPath);
68             test.delete();
69         } catch (Exception JavaDoc e) {
70             log.error("Could not create a temp file in directory:'" + generatortemppath + "' for flash, please edit mmflash.xml or change rights");
71         }
72         if (!generatortemppath.endsWith(File.separator)) {
73             generatortemppath += File.separator;
74         }
75
76
77         // check if there is a program on this location
78
try {
79             (Runtime.getRuntime()).exec(generatorpath + generatorprogram);
80         } catch (Exception JavaDoc e) {
81             log.error("Could not execute command:'" + generatorpath+generatorprogram + "' for flash, please edit mmflash.xml");
82         }
83         log.debug("Module MMFlash started (flash-generator='" + generatorpath + generatorprogram + "' and can be executed and tmpdir is checked)");
84     }
85
86     public void onload() {
87     }
88
89     public MMFlash() {
90     }
91
92     /**
93     * Return the generated flash with debug information.
94     * @param sp the scanpage that includes the parameters needed to generate the flash
95     * @return array of bytes containing the flash data
96     */

97     public byte[] getDebugSwt(scanpage sp) {
98         String JavaDoc filename=htmlroot+sp.req.getRequestURI();
99         byte[] bytes=generateSwtDebug(filename);
100         return(bytes);
101     }
102
103     /**
104     * Dynamically generated flash.
105     *
106     * This method parses a xml-script and generate flash.
107     * This is done in 2 stages, first the xml is parsed through
108     * scan, the next stage will generate the flash which will then
109     * be returned.
110     *
111     * @param sp scanpage
112     * @return the dynamically generated flash or null when error occured
113     */

114     public byte[] getScanParsedFlash(scanpage sp) {
115
116         byte[] result = null;
117
118         // get inputfile
119
// -------------
120
String JavaDoc url = sp.req.getRequestURI();
121         String JavaDoc filename = htmlroot+url;
122         String JavaDoc query = sp.req.getQueryString();
123
124         log.debug("url("+url+"), filename("+filename+"), query("+query+")");
125
126         // cache stage 1
127
// -------------
128
if (!sp.reload) {
129             result =(byte[])lru.get(url+query);
130             if (result!=null) {
131                 log.debug("Cache hit from disk+lru");
132             } else {
133                 result=loadDiskCache(filename,query);
134                 if (result!=null) {
135                     log.debug("Cache hit from from disk");
136                     lru.put(url+query,result);
137                 }
138             }
139         }
140
141         // cache miss or reload
142
// --------------------
143
if(result==null) {
144             byte[] inp = readBytesFile(filename);
145
146             // check if file exists
147
// --------------------
148
if (inp == null) {
149                 log.error("Cannot find the sxf-file: '" + filename + "'!");
150                 return null;
151             }
152
153             sp.body = new String JavaDoc(inp);
154
155             // oke try to parse it
156
// -------------------
157
if (scanp!=null) {
158                 try {
159                     sp.body = scanp.handle_line(sp.body,sp.session,sp);
160                 } catch(Exception JavaDoc e) {}
161             } else {
162                 log.error("The scanparser cannot be found! Check scanparser.xml in config-directory!");
163             }
164
165             File outputFile = createTemporaryFile("export", ".swf");
166             outputFile.delete();
167             Vector tempFiles = new Vector();
168             tempFiles.add(outputFile);
169
170             // now feed it to the xml reader
171
CharArrayReader reader = new CharArrayReader(sp.body.toCharArray());
172             XMLDynamicFlashReader script = new XMLDynamicFlashReader(reader);
173
174             String JavaDoc body="";
175             String JavaDoc SRC=script.getSrcName();
176             if (src.startsWith("/")) {
177                 body+="INPUT \""+htmlroot+src+"\"\n";
178             } else {
179                 String JavaDoc purl=url.substring(0,url.lastIndexOf('/')+1);
180                 src=purl+src;
181                 body+="INPUT \""+htmlroot+src+"\"\n";
182             }
183             body+="OUTPUT \"" + outputFile.getAbsolutePath() + "\"\n";
184
185             String JavaDoc scriptpath=src;
186             scriptpath=scriptpath.substring(0,scriptpath.lastIndexOf('/')+1);
187
188             body+=addDefines(script.getDefines(),scriptpath,tempFiles);
189             body+=addReplaces(script.getReplaces(),scriptpath);
190
191             File inputFile = createTemporaryFile("input", ".sws");
192             inputFile.delete();
193
194             tempFiles.add(inputFile);
195             saveFile(inputFile.getAbsolutePath(), body);
196
197             generateFlash(scriptpath, inputFile.getAbsolutePath());
198
199             result = readBytesFile(outputFile.getAbsolutePath());
200             lru.put(url+query,result);
201             saveDiskCache(filename,query,result);
202             cleanup(tempFiles);
203         } else {
204             // log.debug("cache hit");
205
}
206         return result;
207     }
208
209     /**
210      * This function cleans up the temporary files in the given vector
211      */

212     private void cleanup(Vector tempFiles) {
213         for (int i = 0; i < tempFiles.size(); i++) {
214             File tf = (File)tempFiles.get(i);
215             log.debug("Deleting temporary file " + tf.getAbsolutePath());
216             tf.delete();
217        }
218     }
219
220     /**
221      * Create a temporary file given the prefix and postfix
222      * @param postfix
223      * @param prefix
224      **/

225     private File createTemporaryFile(String JavaDoc prefix, String JavaDoc postfix) {
226        File tempFile = null;
227         try {
228            tempFile = File.createTempFile(prefix, postfix, new File(generatortemppath));
229        } catch (IOException e) {
230            log.warn("Cannot create temporary file using File.createTempFile(), falling back to Las-Vegas method");
231            while (tempFile == null || tempFile.exists()) {
232                tempFile = new File(generatortemppath + prefix + (new Random()).nextLong() + postfix);
233             }
234        }
235        return tempFile;
236     }
237
238     /**
239      * This function will try to generate a new flash thingie, generated from a template.
240      * the only thing which has to be specified is the XML, and the working direcotory.
241      * This function was added, so that there is the possibility to use the generater
242      * from a place without SCAN
243      * @param flashXML a xml which contains the manipulations on the flash template
244      * @param workingdir the path where there has to be searched for the template and the
245      * other things, like pictures.(THIS LOOKS BELOW THE mmbase.htmlroot !!)
246      * @return a byte thingie, which contains the newly generated flash file
247      */

248     public byte[] getParsedFlash(String JavaDoc flashXML, String JavaDoc workingdir) {
249         CharArrayReader reader=new CharArrayReader(flashXML.toCharArray());
250         XMLDynamicFlashReader script=new XMLDynamicFlashReader(reader);
251         String JavaDoc body="";
252
253         // retrieve the template flash file path...
254
String JavaDoc SRC=script.getSrcName();
255         File inputFile;
256         if (src.startsWith("/")) {
257             inputFile = new File(htmlroot+src);
258         }
259         else {
260             inputFile = new File(htmlroot+workingdir+src);
261         }
262         // get absolute path, and add it to our script..
263
inputFile = inputFile.getAbsoluteFile();
264         src = inputFile.getAbsolutePath();
265
266         // is there a caching option set ?
267
String JavaDoc caching=script.getCaching();
268         if (caching!=null && (caching.equals("lru") || caching.equals("disk")) ) {
269             // lru caching, always took here first... if we are caching on disk or on lru..
270
byte[] bytes=(byte[])lru.get(src + flashXML);
271             if (bytes!=null) {
272                 return(bytes);
273             }
274
275             // when we also have to check the disk..
276
if(caching.equals("disk")) {
277                 // try to find on disk..
278
bytes=loadDiskCache(src, flashXML);
279                 if (bytes!=null) {
280                     // found on disk...
281
log.error("WOW from disk");
282                     lru.put(src + flashXML, bytes);
283                     return(bytes);
284                 }
285             }
286         }
287
288         File outputFile = createTemporaryFile("export", ".swf");
289         outputFile.delete();
290
291         Vector tempFiles = new Vector();
292         tempFiles.add(outputFile);
293
294         // hey ho, generate our template..
295
body+="INPUT \""+inputFile.getAbsolutePath()+"\"\n";
296         body+="OUTPUT \""+outputFile.getAbsolutePath()+"\"\n";
297
298         String JavaDoc scriptpath=src;
299         scriptpath=scriptpath.substring(0,scriptpath.lastIndexOf('/')+1);
300
301         body+=addDefines(script.getDefines(),scriptpath,tempFiles);
302         body+=addReplaces(script.getReplaces(),scriptpath);
303
304         // save the created input file for the generator
305
File genInputFile = createTemporaryFile("input", ".sws");
306         genInputFile.delete();
307         tempFiles.add(genInputFile);
308         saveFile(genInputFile.getAbsolutePath(), body);
309
310         // lets generate the file
311
generateFlash(scriptpath, genInputFile.getAbsolutePath());
312
313         // retrieve the result of the genererator..
314
byte[] bytes=readBytesFile(outputFile.getAbsolutePath());
315
316         // store the flash in cache, when needed...
317
if (caching!=null && (caching.equals("lru")|| caching.equals("disk")) ) {
318             lru.put(src + flashXML, bytes);
319             if(caching.equals("disk")) {
320                     saveDiskCache(src, flashXML, bytes);
321             }
322         }
323         cleanup(tempFiles);
324         return(bytes);
325     }
326
327     /**
328      * Generate text to add to the swift-genertor input file. This text specifies
329      * how the flash should be manipulated. It allows replacements of colors,
330      * fontsizes, etc.
331      */

332     private String JavaDoc addReplaces(Vector replaces, String JavaDoc scriptpath) {
333         String JavaDoc part="";
334         for (Enumeration e=replaces.elements();e.hasMoreElements();) {
335             Hashtable rep=(Hashtable)e.nextElement();
336             String JavaDoc type=(String JavaDoc)rep.get("type");
337             if (type.equals("text")) {
338                 part+="SUBSTITUTE TEXT";
339                 String JavaDoc id=(String JavaDoc)rep.get("id");
340                 if (id!=null) part+=" "+id;
341                 part+=" {\n";
342                 String JavaDoc fonttype=(String JavaDoc)rep.get("fonttype");
343                 if (fonttype!=null) {
344                     part+="\tFONT "+fonttype;
345                     String JavaDoc fontsize=(String JavaDoc)rep.get("fontsize");
346                     if (fontsize!=null) part+=" HEIGHT "+fontsize;
347                     String JavaDoc fontkerning=(String JavaDoc)rep.get("fontkerning");
348                     if (fontkerning!=null) part+=" KERNING "+fontkerning;
349                     String JavaDoc fontcolor=(String JavaDoc)rep.get("fontcolor");
350                     if (fontcolor!=null) part+=" COLOR "+fontcolor;
351                     part+="\n";
352                 }
353                 String JavaDoc str=(String JavaDoc)rep.get("string");
354                 if (str!=null) {
355                     str = replaceQuote(str);
356                     part+="\tSTRING \""+str+"\"\n";
357                 }
358                 String JavaDoc strfile=(String JavaDoc)rep.get("stringfile");
359                 if (strfile!=null) {
360                     if (!strfile.startsWith("/")) {
361                         strfile=scriptpath+strfile;
362                     }
363                     strfile=htmlroot+strfile;
364                     byte[] txt=readBytesFile(strfile);
365                     if (txt!=null) {
366                         String JavaDoc body=new String JavaDoc(txt);
367                         body = replaceQuote(body);
368                         part+="\tSTRING \""+body+"\"\n";
369                     }
370                 }
371                 part+="}\n";
372             } else if (type.equals("textfield")) {
373                 part+="SUBSTITUTE TEXTFIELD";
374                 String JavaDoc id=(String JavaDoc)rep.get("id");
375                 if (id!=null) part+=" "+id;
376                 part+=" {\n";
377                 String JavaDoc fonttype=(String JavaDoc)rep.get("fonttype");
378                 if (fonttype!=null) {
379                     part+="\tFONT "+fonttype;
380                     String JavaDoc fontsize=(String JavaDoc)rep.get("fontsize");
381                     if (fontsize!=null) part+=" HEIGHT "+fontsize;
382                     String JavaDoc fontkerning=(String JavaDoc)rep.get("fontkerning");
383                     if (fontkerning!=null) part+=" KERNING "+fontkerning;
384                     String JavaDoc fontcolor=(String JavaDoc)rep.get("fontcolor");
385                     if (fontcolor!=null) part+=" COLOR "+fontcolor;
386                     part+="\n";
387                 }
388                 String JavaDoc str=(String JavaDoc)rep.get("string");
389                 if (str!=null) {
390                     str = replaceQuote(str);
391                     part+="\tSTRING \""+str+"\"\n";
392                 }
393                 String JavaDoc strfile=(String JavaDoc)rep.get("stringfile");
394                 if (strfile!=null) {
395                     if (!strfile.startsWith("/")) {
396                         strfile=scriptpath+strfile;
397                     }
398                     strfile=htmlroot+strfile;
399                     System.out.println(strfile);
400                     byte[] txt=readBytesFile(strfile);
401                     if (txt!=null) {
402                         String JavaDoc body=new String JavaDoc(txt);
403                         body = replaceQuote(body);
404                         part+="\tSTRING \""+body+"\"\n";
405                     }
406                 }
407                 part+="}\n";
408             }
409             part+="\n";
410         }
411         return(part);
412     }
413
414     /**
415      * Add all defined media files (sound, images, etc.) to the text
416      * that is used for the swift-generator. Images that come from inside
417      * MMBase are saved to disk using temporary files that are deleted when
418      * generation is finished
419      * @param defines
420      * @param scriptpath
421      * @param tempFiles Vector where all the temporary files are put into.
422      */

423     private String JavaDoc addDefines(Vector defines,String JavaDoc scriptpath,Vector tempFiles) {
424         String JavaDoc part="";
425         int counter=1;
426         for (Enumeration e=defines.elements();e.hasMoreElements();) {
427             Hashtable rep=(Hashtable)e.nextElement();
428             String JavaDoc type=(String JavaDoc)rep.get("type");
429             if (type.equals("image")) {
430                 String JavaDoc id=(String JavaDoc)rep.get("id");
431                 part+="DEFINE IMAGE \""+id+"\"";
432                 String JavaDoc width=(String JavaDoc)rep.get("width");
433                 String JavaDoc height=(String JavaDoc)rep.get("height");
434                 if (width!=null && height!=null) {
435                     part+=" -size "+width+","+height;
436                 }
437                 String JavaDoc SRC=(String JavaDoc)rep.get("src");
438                 if (src!=null) {
439                     // bad way to test for MMBase images!
440
if (src.startsWith("/img.db?")) {
441                         String JavaDoc result=mapImage(src.substring(8),tempFiles);
442                         part+=" \""+result+"\"";
443                     } else if (src.startsWith("/")) {
444                         part+=" \""+htmlroot+src+"\"";
445                     } else {
446                         part+=" \""+htmlroot+scriptpath+src+"\"";
447                     }
448                 }
449             } else if (type.equals("sound")) {
450                 String JavaDoc id=(String JavaDoc)rep.get("id");
451                 part+="DEFINE SOUND \""+id+"\"";
452                 String JavaDoc SRC=(String JavaDoc)rep.get("src");
453                 if (src!=null) {
454                     if (src.startsWith("/")) {
455                         part+=" \""+htmlroot+src+"\"";
456                     } else {
457                         System.out.println("REL="+htmlroot+scriptpath+src);
458                         part+=" \""+htmlroot+scriptpath+src+"\"";
459                     }
460                 }
461             } else if (type.equals("variable")) {
462                 String JavaDoc var=(String JavaDoc)rep.get("id");
463                 String JavaDoc val=(String JavaDoc)rep.get("value");
464                 if (val==null) {
465                     String JavaDoc strfile=(String JavaDoc)rep.get("valuefile");
466                     if (strfile!=null) {
467                         if (!strfile.startsWith("/")) {
468                             strfile=scriptpath+strfile;
469                         }
470                         strfile=htmlroot+strfile;
471                             byte[] txt=readBytesFile(strfile);
472                         if (txt!=null) {
473                             val=new String JavaDoc(txt);
474                         }
475                     }
476                 }
477                 part+="SET "+var+" \""+val+"\"\n";
478             } else if (type.equals("speed")) {
479                 String JavaDoc val=(String JavaDoc)rep.get("value");
480                 part+="FLASH {\n";
481                 part+="\tFRAMERATE "+val+"\n";
482                 part+="}\n\n";
483             }
484             part+="\n";
485         }
486         return(part);
487     }
488
489     /**
490     * Read a file from disk.
491     *
492     * @param filename
493     * @return bytes from file
494     */

495     private byte[] readBytesFile(String JavaDoc filename) {
496         File bfile = new File(filename);
497         int filesize = (int)bfile.length();
498         byte[] buffer = new byte[filesize];
499         try {
500             FileInputStream scan = new FileInputStream(bfile);
501             int len = scan.read(buffer,0,filesize);
502             scan.close();
503         } catch(FileNotFoundException e) {
504             log.error("Cannot find file: "+filename);
505             return(null);
506          } catch(IOException e) {
507             log.error("Cannot read file: "+filename);
508             return null;
509         }
510         return(buffer);
511     }
512
513
514     /**
515     * Reads a file from disk.
516     *
517     * @param filename filename (+query) constructs the real filename
518     * @param query query, is put after filename to construct real file on disk
519     * @return bytes from file
520     */

521     private byte[] loadDiskCache(String JavaDoc filename,String JavaDoc query) {
522         if(query!=null && !query.equals(""))
523             filename = filename.substring(0,filename.length()-3) + "swf?" + query;
524         else
525             filename = filename.substring(0,filename.length()-3) + "swf";
526
527         if (subdir!=null && !subdir.equals("")) {
528             int pos=filename.lastIndexOf('/');
529             filename=filename.substring(0,pos)+"/"+subdir+filename.substring(pos);
530         }
531         log.debug("load from disk: " + filename);
532         return readBytesFile(filename);
533     }
534
535
536     private byte[] generateSwtDebug(String JavaDoc filename) {
537         Process JavaDoc p=null;
538         DataInputStream dip= null;
539         DataInputStream diperror= null;
540         String JavaDoc command="";
541         RandomAccessFile dos=null;
542
543         try {
544             command=generatorpath+generatorprogram+" -d "+filename;
545             p = (Runtime.getRuntime()).exec(command);
546         } catch (Exception JavaDoc e) {
547             log.error("could not execute command:'"+command+"'");
548         }
549         log.service("Executed command: "+command+" succesfull, now gonna parse");
550         dip = new DataInputStream(new BufferedInputStream(p.getInputStream()));
551         byte[] result=new byte[32000];
552
553         // look on the input stream
554
try {
555             int len3=0;
556             int len2=0;
557
558             len2=dip.read(result,0,result.length);
559             if (len2==-1) {
560                 return(null);
561             }
562             while (len2!=-1 && len3!=-1) {
563                 len3=dip.read(result,len2,result.length-len2);
564                 if (len3==-1) {
565                     break;
566                 } else {
567                     len2+=len3;
568                 }
569             }
570             dip.close();
571         } catch (Exception JavaDoc e) {
572             log.error("could not parse output from '"+command+"'");
573             e.printStackTrace();
574             try {
575                 dip.close();
576             } catch (Exception JavaDoc f) {}
577         }
578         return(result);
579     }
580
581     /**
582      * Generate a flash file for a given input filename
583      * @param scriptpath Unused parameter
584      * @param inputfile File to generate flash for
585      */

586     private void generateFlash(String JavaDoc scriptpath, String JavaDoc inputfile) {
587         Process JavaDoc p=null;
588         DataInputStream dip= null;
589         DataInputStream diperror= null;
590         String JavaDoc command="";
591         RandomAccessFile dos=null;
592
593         try {
594             command=generatorpath+generatorprogram+" "+inputfile;
595             p = (Runtime.getRuntime()).exec(command);
596         } catch (Exception JavaDoc e) {
597             log.error("could not execute command:'"+command+"'");
598         }
599         log.debug("Executed command: "+command+" succesfull, now gonna parse");
600         dip = new DataInputStream(new BufferedInputStream(p.getInputStream()));
601         byte[] result=new byte[1024];
602
603         // look on the input stream
604
try {
605             int len3=0;
606             int len2=0;
607
608             len2=dip.read(result,0,result.length);
609             while (len2!=-1) {
610                 len3=dip.read(result,len2,result.length-len2);
611                 if (len3==-1) {
612                     break;
613                 } else {
614                     len2+=len3;
615                 }
616             }
617             dip.close();
618         } catch (Exception JavaDoc e) {
619             log.error("could not parse output from '"+command+"'");
620             e.printStackTrace();
621             try {
622                 dip.close();
623             } catch (Exception JavaDoc f) {}
624         }
625     }
626
627     /**
628      * Save a stringvalue to a file on the filesystem
629      * @param filename File to save the stringvalue to
630      * @param value Value to save to disk
631      * @return Boolean indicating succes
632      */

633     static boolean saveFile(String JavaDoc filename,String JavaDoc value) {
634         File sfile = new File(filename);
635         try {
636             DataOutputStream scan = new DataOutputStream(new FileOutputStream(sfile));
637             scan.writeBytes(value);
638             scan.flush();
639             scan.close();
640             return true;
641         } catch(Exception JavaDoc e) {
642             log.error("Could not write values to file:" +filename+ " with value" + value);
643             e.printStackTrace();
644             return false;
645         }
646     }
647
648     private boolean saveDiskCache(String JavaDoc filename,String JavaDoc query,byte[] value) {
649         if(query!=null && !query.equals(""))
650             filename = filename.substring(0,filename.length()-3) + "swf?" + query;
651         else
652             filename = filename.substring(0,filename.length()-3) + "swf";
653
654         if (subdir!=null && !subdir.equals("")) {
655             int pos=filename.lastIndexOf('/');
656             filename=filename.substring(0,pos)+File.separator+subdir+filename.substring(pos);
657             // Create dir if it doesn't exist
658
File d=new File(filename.substring(0,pos)+File.separator+subdir);
659             if (!d.exists()) {
660                 d.mkdir();
661             }
662         }
663
664         log.debug("save to disk: "+filename);
665         //System.out.println("filename="+filename);
666

667         File sfile = new File(filename);
668         try {
669             DataOutputStream scan = new DataOutputStream(new FileOutputStream(sfile));
670             scan.write(value);
671             scan.flush();
672             scan.close();
673         } catch(Exception JavaDoc e) {
674             log.error("Could not write to disk cache, file:"+filename+" query:" + query);
675             log.error(Logging.stackTrace(e));
676         }
677         return(true);
678     }
679
680     /**
681      * Get an image from MMBase given a list of parameters, and save it to disk
682      * @param imageline The image number with it's manipulations (eg: 34235+s(50))
683      * @param tempFiles The vector to put temporary files in
684      * @return The complete path to the image
685      */

686     private String JavaDoc mapImage(String JavaDoc imageline, Vector tempFiles) {
687         Images bul=(Images)mmb.getMMObject("images");
688         Vector params=new Vector();
689         if (bul!=null) {
690             // rebuild the param
691
log.debug("rebuilding param");
692             String JavaDoc imageId = null;
693             StringBuffer JavaDoc template = new StringBuffer JavaDoc();
694             if (imageline != null) {
695                 StringTokenizer tok=new StringTokenizer(imageline,"+\n\r");
696                 // rico
697
if(tok.hasMoreTokens()) {
698                     imageId = tok.nextToken();
699                     params.addElement(tok.nextToken());
700                 }
701                 while(tok.hasMoreTokens()) {
702                     template.append(tok.nextToken());
703                     if (tok.hasMoreTokens()) {
704                         template.append("+");
705                     }
706                 }
707                 
708             }
709             byte[] bytes = bul.getCachedNode(bul.getNode(imageId), template.toString()).getByteValue("handle");
710             File tempFile = createTemporaryFile("image", ".jpg");
711             saveFile(tempFile.getAbsolutePath(), bytes);
712             tempFiles.add(tempFile);
713             return tempFile.getAbsolutePath();
714         } else {
715             log.error("Cannot locate images builder, make sure you activated it!");
716         }
717         return "";
718     }
719
720     /**
721      * Save a byte-array to disk
722      * @param filename The name of the file to save the data to
723      * @param value The byte-array containing the data for the file
724      * @return Boolean indicating the success of the operation
725      */

726     static boolean saveFile(String JavaDoc filename,byte[] value) {
727         File sfile = new File(filename);
728         try {
729             DataOutputStream scan = new DataOutputStream(new FileOutputStream(sfile));
730             scan.write(value);
731             scan.flush();
732             scan.close();
733             return true;
734         } catch(Exception JavaDoc e) {
735             log.error("Could not save to file:"+filename);
736             log.error(Logging.stackTrace(e));
737             return false;
738         }
739     }
740
741     /**
742      * Escape quotes in a string, because flash generator will fail otherwise
743      * @param unquoted The string with quotes (") in it
744      * @return The string where all quotes are escaped as \"
745      */

746     String JavaDoc replaceQuote(String JavaDoc unquoted) {
747         StringObject so = new StringObject(unquoted);
748         so.replace("\"", "\\\"");
749         return so.toString();
750     }
751 }
752
Popular Tags