KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > de > jwi > jgallery > Folder


1
2 package de.jwi.jgallery;
3
4 /*
5  * jGallery - Java web application to display image galleries
6  *
7  * Copyright (C) 2004 Juergen Weber
8  *
9  * This file is part of jGallery.
10  *
11  * jGallery is free software; you can redistribute it and/or modify it under the terms of the GNU General Public
12  * License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later
13  * version.
14  *
15  * jGallery is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied
16  * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
17  * details.
18  *
19  * You should have received a copy of the GNU General Public License along with jGallery; if not, write to the Free
20  * Software Foundation, Inc., 59 Temple Place, Suite 330, Boston
21  */

22
23 import imageinfo.ImageInfo;
24
25 import java.io.BufferedReader JavaDoc;
26 import java.io.File JavaDoc;
27 import java.io.FileInputStream JavaDoc;
28 import java.io.FileNotFoundException JavaDoc;
29 import java.io.FileReader JavaDoc;
30 import java.io.FilenameFilter JavaDoc;
31 import java.io.IOException JavaDoc;
32 import java.io.InputStream JavaDoc;
33 import java.io.Serializable JavaDoc;
34 import java.sql.SQLException JavaDoc;
35 import java.util.ArrayList JavaDoc;
36 import java.util.Arrays JavaDoc;
37 import java.util.Comparator JavaDoc;
38 import java.util.HashMap JavaDoc;
39 import java.util.Hashtable JavaDoc;
40 import java.util.List JavaDoc;
41 import java.util.Properties JavaDoc;
42
43 import javax.servlet.ServletContext JavaDoc;
44
45 import de.jwi.jgallery.db.DBManager;
46
47 /**
48  * @author Juergen Weber Source file created on 17.02.2004
49  *
50  */

51 public class Folder implements Serializable JavaDoc
52 {
53
54     private static final String JavaDoc FOLDER_KEY = "folder";
55
56     private static final String JavaDoc CAPTIONSFILE = "captions.txt";
57
58     private static final String JavaDoc JGALLERYIGNOREFILE = ".jGalleryIgnore";
59
60     private ConfigData configData;
61
62     private static final String JavaDoc GENERATORURL = "http://www.jwi.de/jgallery/";
63
64
65     private String JavaDoc thumbsdir = "thumbs";
66
67     private float thumbQuality = 0.98f;
68
69     private int thumbSize = 150;
70
71     private boolean isDirectoryParsed = false;
72
73     private boolean isProcessSubdirectories = true;
74
75     private boolean isCreateThumbs = true;
76
77     private IThumbnailWriter thumbnailWriter = null;
78
79     private File JavaDoc directory;
80
81     private List JavaDoc parentFolderList;
82
83     private Configuration configuration;
84
85     protected String JavaDoc[] imageFiles;
86
87     private Properties JavaDoc captions = new Properties JavaDoc();
88
89     private int[] imageCounters;
90
91     private int folderCounter = -1;
92
93     String JavaDoc[] subDirectories;
94
95     private String JavaDoc iconWidth;
96
97     private String JavaDoc iconHeight;
98
99     private final int FOLDER_ICON_RANDOM = 0;
100
101     private final int FOLDER_ICON_ICON = 1;
102
103     private int folderIconStyle = FOLDER_ICON_RANDOM;
104
105     protected String JavaDoc folderPath;
106
107     protected String JavaDoc imagePath;
108
109     protected String JavaDoc jgalleryContextPath;
110
111     private String JavaDoc parentIndexPage;
112
113     private String JavaDoc parentlink;
114
115     private Hashtable JavaDoc images = new Hashtable JavaDoc();
116
117     private Image[] imagesArray;
118
119     private Image image; // the current image
120

121     private int imageNum; // Number of the current image
122

123     private String JavaDoc template = "Standard"; // Name (and folder) of template
124

125     private String JavaDoc textEncoding = "iso-8859-1";
126
127     private String JavaDoc indexJsp;
128
129     private String JavaDoc slideJsp;
130
131     private String JavaDoc templatePath;
132
133     private String JavaDoc resPath;
134
135     private String JavaDoc resResourcePath;
136
137     private String JavaDoc stylePath;
138
139     private String JavaDoc style = "Black";
140
141     private int level;
142
143     private int cols = 2; // Number of image columns on index pages
144

145     private int currentCols;
146
147     private int currentRows;
148
149     private int rows = 3; // Max number of image rows on index pages
150

151     private boolean isShowImageNum = true;
152
153     private boolean isShowDates = true;
154
155     private int totalIndexes; // Total number of index pages
156

157     private int totalAlbumImages; // Total number of images in an album
158

159     // (subdirectory images included)
160
private int totalImages; // Total number of images in a directory
161

162     private int indexNum; // The number of the current index page
163

164     private String JavaDoc albumPath;
165
166     private String JavaDoc title;
167
168     private String JavaDoc name;
169
170     private HashMap JavaDoc variables = new HashMap JavaDoc();
171
172     private DBManager dBManager;
173
174     private ServletContext JavaDoc appContext;
175
176     public Folder(File JavaDoc directory, ServletContext JavaDoc appContext,
177             Configuration configuration, ConfigData configData,
178             String JavaDoc jgalleryContextPath, String JavaDoc folderPath, String JavaDoc imagePath,
179             DBManager dBManager) throws GalleryException
180     {
181         this.directory = directory;
182
183         this.appContext = appContext;
184         this.configData = configData;
185
186         this.configuration = configuration;
187
188         this.jgalleryContextPath = jgalleryContextPath;
189         this.folderPath = folderPath;
190         this.imagePath = imagePath;
191
192         this.dBManager = dBManager;
193
194         readConfiguration();
195
196         thumbnailWriter = configuration.getThumbnailWriter();
197
198     }
199
200     public HashMap JavaDoc getVariables()
201     {
202         return variables;
203     }
204
205     private int sortingOrder = ImageComparator.SORTNONE;
206
207
208     private Configuration readTemplateConfiguration(String JavaDoc templateConfigFile,
209             Configuration c)
210     {
211         Configuration c1 = c;
212
213         InputStream JavaDoc is = appContext.getResourceAsStream(templateConfigFile);
214
215         if (is != null)
216         {
217             try
218             {
219                 c1 = new Configuration(is, c);
220             }
221             catch (IOException JavaDoc e)
222             {
223                 // NOP
224
}
225             finally
226             {
227                 try
228                 {
229                     is.close();
230                 }
231                 catch (IOException JavaDoc e1)
232                 {
233                     // NOP
234
}
235             }
236         }
237         return c1;
238     }
239
240     private void readConfiguration() throws GalleryException
241     {
242         template = configuration.getString("template", template);
243         String JavaDoc templateConfig = "/templates/" + template
244                 + "/template.properties";
245
246         // Template Configurations cannot be overridden
247
configuration = readTemplateConfiguration(templateConfig, configuration);
248
249         cols = configuration.getInt("index.columns", cols);
250         rows = configuration.getInt("index.rows", rows);
251
252         indexJsp = "/templates/" + template + "/index.jsp";
253         slideJsp = "/templates/" + template + "/slide.jsp";
254
255
256         style = configuration.getString("style", style);
257
258         textEncoding = configuration.getString("textEncoding", textEncoding);
259
260         String JavaDoc s = configuration.getString("sortingOrder");
261         if ("filedate".equals(s))
262         {
263             sortingOrder = ImageComparator.SORTBYFILEDATE;
264         }
265         else if ("exifdate".equals(s))
266         {
267             sortingOrder = ImageComparator.SORTBYEXIFDATE;
268         }
269         else if ("name".equals(s))
270         {
271             sortingOrder = ImageComparator.SORTBYNAME;
272         }
273         else if ("none".equals(s))
274         {
275             sortingOrder = ImageComparator.SORTNONE;
276         }
277         else
278         {
279             sortingOrder = ImageComparator.SORTNONE;
280         }
281
282         isShowImageNum = configuration.getBoolean("showImageNum",
283                 isShowImageNum);
284
285         folderIconStyle = FOLDER_ICON_RANDOM;
286
287         s = configuration.getString("foldericon.style");
288         if ("icon".equalsIgnoreCase(s))
289         {
290             folderIconStyle = FOLDER_ICON_ICON;
291         }
292
293         thumbsdir = configuration.getString("thumbnails.dir", thumbsdir);
294
295         isCreateThumbs = configuration.getBoolean("thumbnails.create",
296                 isCreateThumbs);
297
298         thumbSize = configuration.getInt("thumbnails.size", thumbSize);
299         thumbQuality = configuration.getFloat("thumbnails.quality",
300                 thumbQuality);
301
302
303         // parentlink.galleries=
304

305         templatePath = jgalleryContextPath + "/templates/" + template;
306         resResourcePath = "/templates/" + template + "/res";
307         resPath = jgalleryContextPath + "/templates/" + template + "/res";
308         stylePath = jgalleryContextPath + "/templates/" + template + "/styles/"
309                 + style + ".css";
310
311         s = configuration.getString("parentlink");
312         if (s == null)
313         {
314             String JavaDoc s1 = folderPath.substring(1, folderPath.indexOf('/', 1));
315             s = configuration.getString("parentlink." + s1);
316         }
317
318         if (s != null)
319         {
320             parentlink = s;
321         }
322
323         setIconDimensions();
324
325         configuration.getUserVariables(variables);
326     }
327
328
329     private void setIconDimensions()
330     {
331         InputStream JavaDoc is = appContext.getResourceAsStream(resResourcePath
332                 + "/folder.gif");
333         if (null != is)
334         {
335
336             ImageInfo ii = new ImageInfo();
337             ii.setInput(is);
338             if (ii.check())
339             {
340                 iconWidth = Integer.toString(ii.getWidth());
341                 iconHeight = Integer.toString(ii.getHeight());
342             }
343         }
344     }
345
346     File JavaDoc getDirectory()
347     {
348         return directory;
349     }
350
351     public String JavaDoc getUrlExtention()
352     {
353         return configData.urlExtention;
354     }
355
356     public String JavaDoc getShowDates()
357     {
358         return Boolean.toString(isShowDates);
359     }
360
361     public String JavaDoc getShowImageNum()
362     {
363         return Boolean.toString(isShowImageNum);
364     }
365
366     public String JavaDoc getComment()
367     {
368         String JavaDoc s = captions.getProperty(FOLDER_KEY);
369
370         if (s != null)
371         {
372             return s;
373         }
374
375         s = configuration.getString(FOLDER_KEY);
376         return (s == null) ? "" : s;
377     }
378
379     public String JavaDoc getIndexJsp()
380     {
381         return indexJsp;
382     }
383
384     public String JavaDoc getSlideJsp()
385     {
386         return slideJsp;
387     }
388
389     public Image getImage()
390     {
391         return image;
392     }
393
394     protected IImageAccessor makeImageAccessor(String JavaDoc name)
395     {
396         return new FileImageAccessor(name, this);
397     }
398
399     private ThumbNailInfo makeThumbNailInfoFromRandom(String JavaDoc name)
400             throws GalleryException
401     {
402         File JavaDoc f = null;
403         String JavaDoc subImages[] = null;
404
405         for (int i = 0; i < 2; i++)
406         {
407             f = new File JavaDoc(getDirectory(), name + "/" + getThumbsdir());
408             subImages = f.list(new FilenameFilter JavaDoc()
409             {
410                 public boolean accept(File JavaDoc dir, String JavaDoc name)
411                 {
412                     File JavaDoc f1 = new File JavaDoc(dir, name);
413                     if (!isJPEGExtension(name))
414                     {
415                         return false;
416                     }
417                     return !f1.isDirectory();
418                 };
419             });
420
421             if (subImages == null)
422             {
423                 Folder subFolder = new Folder(new File JavaDoc(directory, name),
424                         appContext, configuration, configData,
425                         jgalleryContextPath, folderPath + "/" + name, imagePath
426                                 + "/" + name, dBManager);
427
428                 subFolder.loadFolder();
429
430                 // no thumbnails created yet
431

432             }
433             else
434             {
435                 break;
436             }
437         }
438         int n = (int) (Math.random() * subImages.length);
439
440         File JavaDoc f1 = new File JavaDoc(f, subImages[n]);
441
442         InputStream JavaDoc is = null;
443         try
444         {
445             is = new FileInputStream JavaDoc(f1);
446         }
447         catch (FileNotFoundException JavaDoc e)
448         {
449             // guaranteed that file exists
450
}
451         ImageInfo ii = new ImageInfo();
452
453         ii.setInput(is);
454
455         if (!ii.check())
456         {
457             throw new GalleryException("Not a supported image file format.");
458         }
459
460         String JavaDoc thumbWidth = Integer.toString(ii.getWidth());
461         String JavaDoc thumbHeight = Integer.toString(ii.getHeight());
462
463         try
464         {
465             is.close();
466         }
467         catch (IOException JavaDoc e1)
468         {
469             // NOP
470
}
471
472         ThumbNailInfo info = new ThumbNailInfo(getImageBasePath() + name + "/"
473                 + getThumbsdir() + "/" + subImages[n], thumbWidth, thumbHeight);
474
475         return info;
476
477     }
478
479     public Image getSubDirOrImage(int n) throws GalleryException
480     {
481         Image image;
482         if (isProcessSubdirectories)
483         {
484             if (n > subDirectories.length)
485             {
486                 // get an image
487
image = getImage(n);
488             }
489             else
490             {
491                 ThumbNailInfo thumbNailInfo = null;
492
493                 if (folderIconStyle == FOLDER_ICON_ICON)
494                 {
495                     thumbNailInfo = new ThumbNailInfo(getIconPath(),
496                             getIconHeight(), getIconWidth());
497                 }
498                 else
499                 {
500                     thumbNailInfo = makeThumbNailInfoFromRandom(subDirectories[n - 1]);
501                     if (thumbNailInfo == null)
502                     {
503                         // no thumbnails created yet, use icon for now
504
thumbNailInfo = new ThumbNailInfo(getIconPath(),
505                                 getIconHeight(), getIconWidth());
506                     }
507                 }
508                 // get a subfolder representation
509
image = new Image(subDirectories[n - 1], true, this,
510                         makeImageAccessor(subDirectories[n - 1]), thumbNailInfo);
511
512                 imagesArray[n - 1] = image;
513             }
514         }
515         else
516         {
517             image = getImage(n);
518         }
519         return image;
520     }
521
522     // lazy load Image n (1..)
523
public Image getImage(int n) throws GalleryException
524     {
525         if (null == imagesArray[n - 1])
526         {
527             // create the thumb first, as it is needed in the Image constructor
528

529             if (isJPEGExtension(imageFiles[n - 1]))
530             {
531                 checkAndCreateThumb(n - 1);
532             }
533             imagesArray[n - 1] = new Image(imageFiles[n - 1], false, this,
534                     makeImageAccessor(imageFiles[n - 1]), null);
535
536             String JavaDoc s = captions.getProperty(imageFiles[n - 1]);
537             if (s != null)
538             {
539                 imagesArray[n - 1].setComment(s);
540             }
541         }
542         return imagesArray[n - 1];
543     }
544
545     // n = 0..
546
private void checkAndCreateThumb(int n) throws GalleryException
547     {
548         if (!isCreateThumbs)
549         {
550             return;
551         }
552
553         File JavaDoc thumbsDir = new File JavaDoc(directory, thumbsdir);
554
555         if (!thumbsDir.exists())
556         {
557             if (!thumbsDir.mkdir())
558             {
559                 throw new GalleryException(
560                         "Could not create thumbnail directory: " + thumbsDir);
561             }
562         }
563
564         File JavaDoc thumb = new File JavaDoc(directory, thumbsdir + "/" + imageFiles[n]);
565         File JavaDoc original = new File JavaDoc(directory, imageFiles[n]);
566         long l1, l2;
567
568         if (!thumb.exists())
569         {
570             try
571             {
572                 thumbnailWriter.write(original, thumb, thumbQuality, thumbSize);
573             }
574             catch (IOException JavaDoc e)
575             {
576                 throw new GalleryException("Error creating thumbnail" + thumb
577                         + " :" + e.getMessage());
578             }
579         }
580     }
581
582     public String JavaDoc getFirstIndexImage()
583     {
584         int firstImageOnIndexPage = getImageNumI();
585
586         return Integer.toString(firstImageOnIndexPage);
587     }
588
589     public String JavaDoc getLastIndexImage()
590     {
591         int n = Math.min(getCurrentImagesPerPage(), imagesArray.length);
592         int lastImageOnIndexPage = getImageNumI() + n - 1;
593
594         return Integer.toString(lastImageOnIndexPage);
595     }
596
597
598     public List JavaDoc getPageIndexes()
599     {
600         List JavaDoc l = new ArrayList JavaDoc();
601
602         if (totalIndexes > 1)
603         {
604             for (int i = 0; i < totalIndexes; i++)
605             {
606                 String JavaDoc page = getCalculatedIndexPage(i);
607                 String JavaDoc number = Integer.toString(i);
608                 String JavaDoc selected = getIndexNum().equals(number)
609                         ? "selected"
610                         : "";
611
612                 PageIndex p = new PageIndex();
613                 p.setPage(page);
614                 p.setNumber(number);
615                 p.setSelected(selected);
616
617                 l.add(p);
618             }
619         }
620
621         return l;
622     }
623
624     public List JavaDoc getImages() throws GalleryException
625     {
626         return getImages(false);
627     }
628
629     // return all images of a page as List(rows) of List(images)
630
public List JavaDoc getImageRows() throws GalleryException
631     {
632         return getImages(true);
633     }
634
635
636     private List JavaDoc getImages(boolean inRows) throws GalleryException
637     {
638         int cols = getColsI();
639         int n = Math.min(getCurrentImagesPerPage(), imagesArray.length);
640         int i = getImageNumI();
641
642         List JavaDoc rl = new ArrayList JavaDoc();
643         List JavaDoc cl = null;
644
645         while (n > 0)
646         {
647             int r = Math.min(n, cols);
648
649             if (inRows)
650             {
651                 cl = new ArrayList JavaDoc(r);
652             }
653             for (int j = 0; j < r; j++)
654             {
655                 Image img = getSubDirOrImage(i); // getImage(i);
656
if (inRows)
657                 {
658                     cl.add(img);
659                 }
660                 else
661                 {
662                     rl.add(img);
663                 }
664                 i++;
665             }
666
667             if (inRows)
668             {
669                 rl.add(cl);
670             }
671             n -= r;
672         }
673
674         return rl;
675     }
676
677     List JavaDoc getNeighbourImages(Image image) throws GalleryException
678     {
679         String JavaDoc baseName = image.getName();
680
681         Integer JavaDoc imgnum = (Integer JavaDoc) images.get(baseName.substring(0, baseName
682                 .indexOf('.')));
683
684         int i = imgnum.intValue();
685
686         int neighbourThumbCount = 3;
687
688         int a = Math.max(i - neighbourThumbCount, 0);
689         int b = Math.min(i + neighbourThumbCount, imagesArray.length - 1);
690
691         List JavaDoc l = new ArrayList JavaDoc(b - a + 1);
692
693         for (i = a; i <= b; i++)
694         {
695             l.add(getImage(i + 1));
696         }
697
698         return l;
699     }
700
701     public String JavaDoc getHTMLBase()
702     {
703         return jgalleryContextPath + folderPath;
704     }
705
706     public String JavaDoc toString()
707     {
708         return getHTMLBase();
709     }
710
711     private String JavaDoc getImageHTMLBase(int imageNum)
712     {
713         String JavaDoc image = imageFiles[imageNum - 1];
714         return getHTMLBase() + image.substring(0, image.indexOf('.'));
715     }
716
717     private void calculateVariables()
718     {
719         totalAlbumImages = totalImages = imageFiles.length;
720
721         totalIndexes = totalImages / (cols * rows);
722         if (totalImages % (cols * rows) > 0)
723         {
724             totalIndexes++;
725         }
726
727     }
728
729     /**
730      * @return Number of current Index Page (1...)
731      */

732     private int calculateIndexNum(int imageNum)
733     {
734         int n;
735         int i = imageNum + subDirectories.length;
736
737         int maxImagesPerIndex = cols * rows;
738
739         if (maxImagesPerIndex > 1)
740         {
741             n = i / maxImagesPerIndex;
742             if ((i % maxImagesPerIndex) != 0)
743             {
744                 n++;
745             }
746         }
747         else
748         {
749             n = i;
750         }
751         return n;
752     }
753
754     public String JavaDoc getClassName()
755     {
756         return getClass().getName();
757     }
758
759     /**
760      * @return Number of image columns on index pages
761      */

762     public String JavaDoc getCols()
763     {
764         return Integer.toString(cols);
765     }
766
767     public int getColsI()
768     {
769         return cols;
770     }
771
772     /**
773      * @return Number of image rows on current index page
774      */

775     public String JavaDoc getCurrentRows()
776     {
777         return Integer.toString(currentRows);
778     }
779
780     /**
781      * @return Name and version of jGallery
782      */

783     public String JavaDoc getGenerator()
784     {
785         return "jGallery " + getInternalVersion();
786     }
787
788     public String JavaDoc getGeneratorurl()
789     {
790         return GENERATORURL;
791     }
792
793     /**
794      * @return Number of the current image within a slide
795      */

796     public String JavaDoc getImageNum()
797     {
798         return Integer.toString(imageNum);
799     }
800
801     public int getImageNumI()
802     {
803         return imageNum;
804     }
805
806     /**
807      * @return Number of images on current index page
808      */

809     public String JavaDoc getIndexImageCount()
810     {
811         return Integer.toString(20);
812     }
813
814     /**
815      * @return The number of the current index page
816      */

817     public String JavaDoc getIndexNum()
818     {
819         return Integer.toString(indexNum);
820     }
821
822     /**
823      * @return Internal version number
824      */

825     public String JavaDoc getInternalVersion()
826     {
827         return configData.version;
828     }
829
830     /**
831      * @return Level of album directory (0 meaning root level)
832      */

833     public String JavaDoc getLevel()
834     {
835         return Integer.toString(level);
836     }
837
838     /**
839      * @return Max image width as set by user
840      */

841     public String JavaDoc getMaxImageWidth()
842     {
843         String JavaDoc s = (String JavaDoc) variables.get("maxImageWidth");
844         return s != null ? s : "";
845     }
846
847     /**
848      * @return Max image height as set by user
849      */

850     public String JavaDoc getMaxImageHeight()
851     {
852         String JavaDoc s = (String JavaDoc) variables.get("maxImageHeight");
853         return s != null ? s : "";
854     }
855
856     /**
857      * @return Max thumbnail width as set by user
858      */

859     public String JavaDoc getMaxThumbWidth()
860     {
861         String JavaDoc s = (String JavaDoc) variables.get("maxThumbWidth");
862         return s != null ? s : "";
863     }
864
865     /**
866      * @return Max thumbnail height as set by user
867      */

868     public String JavaDoc getMaxThumbHeight()
869     {
870         String JavaDoc s = (String JavaDoc) variables.get("maxThumbHeight");
871         return s != null ? s : "";
872     }
873
874     /**
875      * @return Max number of image rows on index pages
876      */

877     public String JavaDoc getRows()
878     {
879         return Integer.toString(rows);
880     }
881
882     /**
883      * @return Name of current template
884      */

885     public String JavaDoc getTemplate()
886     {
887         return template;
888     }
889
890     /**
891      * @return Name of current style sheet
892      */

893     public String JavaDoc getStyle()
894     {
895         return style;
896     }
897
898     /**
899      * @return Name of album directory
900      */

901     public String JavaDoc getTitle()
902     {
903         return title;
904     }
905
906     public String JavaDoc getName()
907     {
908         return name;
909     }
910
911
912     /**
913      * @return Total number of index pages
914      */

915     public String JavaDoc getTotalIndexes()
916     {
917         return totalIndexes > 1 ? Integer.toString(totalIndexes) : "";
918     }
919
920     /**
921      * @return Total number of images in an album (subdirectory images included)
922      */

923     public String JavaDoc getTotalAlbumImages()
924     {
925         return Integer.toString(totalAlbumImages);
926     }
927
928     /**
929      * @return Total number of images in a directory
930      */

931     public String JavaDoc getTotalImages()
932     {
933         return Integer.toString(totalImages);
934     }
935
936     /**
937      * @return Character set and encoding of generated pages and comments
938      */

939     public String JavaDoc getTextEncoding()
940     {
941         return textEncoding;
942     }
943
944     /**
945      * @return Define as user defined variable to explicitly set a language for
946      * a multilingual template (ISO two character language code)
947      */

948     public String JavaDoc getLanguage()
949     {
950         return "en";
951     }
952
953     // 1 ..
954
public String JavaDoc getCalculatedIndexPage(int index)
955     {
956         if ((index < 1) || (index > totalIndexes))
957         {
958             return "";
959         }
960
961         StringBuffer JavaDoc sb = new StringBuffer JavaDoc();
962
963         sb.append(getHTMLBase()).append("index");
964         if (index > 1)
965         {
966             sb.append(Integer.toString(index - 1));
967         }
968         sb.append(".").append(configData.urlExtention);
969
970         return sb.toString();
971     }
972
973     /**
974      * @return Filename of index page for current slide + delta
975      */

976     public String JavaDoc getIndexPage()
977     {
978         int i = calculateIndexNum(imageNum);
979
980         return getCalculatedIndexPage(i);
981     }
982
983     /**
984      * @return Filename of the first index page
985      */

986     public String JavaDoc getFirstIndexPage()
987     {
988         return getCalculatedIndexPage(1);
989     }
990
991     /**
992      * @return Filename of the last index page
993      */

994     public String JavaDoc getLastIndexPage()
995     {
996         return getCalculatedIndexPage(totalIndexes);
997     }
998
999     /**
1000     * @return Filename of the previous index page
1001     */

1002    public String JavaDoc getPreviousIndexPage()
1003    {
1004        int i = calculateIndexNum(imageNum);
1005
1006        return getCalculatedIndexPage(i - 1);
1007    }
1008
1009    /**
1010     * @return Filename of the next index page
1011     */

1012    public String JavaDoc getNextIndexPage()
1013    {
1014        int i = calculateIndexNum(imageNum);
1015
1016        return getCalculatedIndexPage(i + 1);
1017    }
1018
1019    /**
1020     * @return Filename of parent index page
1021     */

1022    public String JavaDoc getParentIndexPage()
1023    {
1024        return parentIndexPage;
1025    }
1026
1027    /**
1028     * used by Image.getIconPath();
1029     */

1030    String JavaDoc getIconPath()
1031    {
1032        return getResPath() + "/folder.gif";
1033    }
1034
1035    String JavaDoc getIconWidth()
1036    {
1037        return iconWidth;
1038    }
1039
1040    String JavaDoc getIconHeight()
1041    {
1042        return iconHeight;
1043    }
1044
1045    public String JavaDoc getThumbsdir()
1046    {
1047        return thumbsdir;
1048    }
1049
1050    public String JavaDoc getFileContent(String JavaDoc fname)
1051            throws FileNotFoundException JavaDoc, IOException JavaDoc, GalleryException
1052    {
1053        File JavaDoc f = new File JavaDoc(directory, fname);
1054        StringBuffer JavaDoc sb = new StringBuffer JavaDoc();
1055        String JavaDoc s;
1056
1057        if (f.getParentFile().getCanonicalPath().equals(
1058                directory.getCanonicalPath()))
1059        {
1060            // only allow to read in Folder's directory
1061

1062            BufferedReader JavaDoc in = new BufferedReader JavaDoc(new FileReader JavaDoc(f));
1063            while ((s = in.readLine()) != null)
1064            {
1065                sb.append(s);
1066            }
1067        }
1068        else
1069        {
1070            throw new GalleryException("Will only read in current directory.");
1071        }
1072
1073        return sb.toString();
1074    }
1075
1076    /**
1077     * @return Path to get back to the top of a multi directory level album
1078     */

1079    public String JavaDoc getRootPath()
1080    {
1081        return folderPath;
1082    }
1083
1084    /**
1085     * @return Path to the image that is shown in slides
1086     */

1087    /*
1088     * TODO
1089     *
1090     * public String getImagePath() { return imageNum > 0 ? folderPath +
1091     * imageFiles[imageNum - 1] : ""; }
1092     */

1093    /**
1094     * @return Path to the selected style file
1095     */

1096    public String JavaDoc getStylePath()
1097    {
1098        return stylePath;
1099    }
1100
1101    /**
1102     * @return Path to the "res" directory containing album resources (support
1103     * files like gif buttons etc)
1104     */

1105    public String JavaDoc getResPath()
1106    {
1107        return resPath;
1108    }
1109
1110    public String JavaDoc getTemplatePath()
1111    {
1112        return templatePath;
1113    }
1114
1115
1116    // 1..
1117
private String JavaDoc getSlidePage(int n)
1118    {
1119        return getImageHTMLBase(n) + "." + configData.urlExtention;
1120    }
1121
1122    /**
1123     * @return Filename of the first slide page
1124     */

1125    public String JavaDoc getFirstPage()
1126    {
1127        return getSlidePage(1);
1128    }
1129
1130    /**
1131     * @return Filename of the last slide page
1132     */

1133    public String JavaDoc getLastPage()
1134    {
1135        return getSlidePage(imageFiles.length + 1);
1136    }
1137
1138    public Image getPrevious() throws GalleryException
1139    {
1140        image = imageNum > 1 ? getImage(imageNum - 1) : null;
1141        return image;
1142    }
1143
1144    public Image getNext() throws GalleryException
1145    {
1146        image = imageNum < totalImages ? getImage(imageNum + 1) : null;
1147        return image;
1148    }
1149
1150    /**
1151     * @return Filename of the previous slide page
1152     */

1153    public String JavaDoc getPreviousPage()
1154    {
1155        return imageNum > 1 + subDirectories.length
1156                ? getSlidePage(imageNum - 1)
1157                : "";
1158    }
1159
1160    /**
1161     * @return Filename of the current slide page
1162     */

1163    public String JavaDoc getCurrentPage()
1164    {
1165        return getSlidePage(imageNum);
1166    }
1167
1168    /**
1169     * @return Filename of the next slide page
1170     */

1171    public String JavaDoc getNextPage()
1172    {
1173        return imageNum < totalImages ? getSlidePage(imageNum + 1) : "";
1174    }
1175
1176    public static boolean isJPEGExtension(String JavaDoc s)
1177    {
1178        String JavaDoc s1 = s.toLowerCase();
1179        return s1.endsWith(".jpg") | s1.endsWith(".jpeg");
1180    }
1181
1182
1183    public static final int INDEX = 1, SLIDE = 2;
1184
1185    protected String JavaDoc[] getSubDirectories()
1186    {
1187        File JavaDoc f = new File JavaDoc(directory, JGALLERYIGNOREFILE);
1188        if (f.exists())
1189        {
1190            return new String JavaDoc[0];
1191        }
1192
1193        return directory.list(new DirectoriesFilter(getThumbsdir(),
1194                JGALLERYIGNOREFILE));
1195    }
1196
1197    public int setFileName(String JavaDoc pathInfoFileName) throws GalleryException
1198    {
1199        String JavaDoc s = pathInfoFileName.startsWith("/") ? pathInfoFileName
1200                .substring(1) : pathInfoFileName;
1201        String JavaDoc s1;
1202        int n = 0;
1203
1204        if (s.startsWith("index"))
1205        {
1206            // GalleryException
1207

1208            if (s.equals("index." + configData.urlExtention))
1209            {
1210                indexNum = 1;
1211            }
1212            else
1213            {
1214                int i = 0;
1215
1216                s1 = s.substring("index".length(), s.indexOf('.'));
1217                try
1218                {
1219                    i = Integer.parseInt(s1);
1220                }
1221                catch (NumberFormatException JavaDoc e)
1222                {
1223                    throw new GalleryNotFoundException("URL not found", e);
1224                }
1225
1226                indexNum = 1 + i;
1227
1228                if (indexNum > totalIndexes)
1229                {
1230                    throw new GalleryNotFoundException("URL not found");
1231                }
1232
1233            }
1234
1235            int maxImagesPerIndex = cols * rows;
1236
1237            imageNum = 1 + (indexNum - 1) * maxImagesPerIndex;
1238
1239            if (indexNum < totalIndexes)
1240            {
1241                currentCols = cols;
1242                currentRows = rows;
1243            }
1244            else
1245            {
1246                int r = totalImages % maxImagesPerIndex;
1247
1248                currentRows = r / cols;
1249                if (r % cols > 0)
1250                    currentRows++;
1251
1252                currentCols = Math.min(r, cols);
1253            }
1254
1255            n = INDEX;
1256        }
1257        else
1258        // a slide page
1259
{
1260            s1 = s.substring(0, s.indexOf('.'));
1261
1262            Integer JavaDoc theImage = (Integer JavaDoc) images.get(s1);
1263            if (null == theImage)
1264            {
1265                throw new GalleryNotFoundException("URL not found");
1266            }
1267
1268            imageNum = theImage.intValue();
1269            indexNum = calculateIndexNum(imageNum);
1270
1271            image = getImage(imageNum);
1272
1273            n = SLIDE;
1274        }
1275
1276        return n;
1277    }
1278
1279    public void loadFolder() throws GalleryException
1280    {
1281        if (!isDirectoryParsed)
1282        {
1283            calculateParentFolderList(folderPath);
1284
1285            // "/testalbum/second/"
1286

1287            String JavaDoc[] parts = folderPath.split("/");
1288
1289            StringBuffer JavaDoc sb = new StringBuffer JavaDoc();
1290
1291            if (parts.length > 2) // [0] is empty, [1..n-2] are parents, [n-1]
1292
// is current
1293
{
1294                for (int i = 1; i < parts.length - 1; i++)
1295                {
1296                    level = i;
1297                    sb.append(parts[i]);
1298                    sb.append('/');
1299                }
1300                String JavaDoc parent = sb.toString();
1301
1302                String JavaDoc hTMLBase = jgalleryContextPath;
1303                parentIndexPage = hTMLBase + "/" + parent + "index."
1304                        + configData.urlExtention;
1305
1306                // Check, if parent directory is to be ignored
1307

1308                File JavaDoc parentFile = directory.getParentFile();
1309                if (null != parentFile)
1310                {
1311                    File JavaDoc f = new File JavaDoc(parentFile, JGALLERYIGNOREFILE);
1312                    if (f.exists())
1313                    {
1314                        parentIndexPage = "";
1315                    }
1316                }
1317
1318            }
1319            if ("".equals(parentIndexPage))
1320            {
1321                parentIndexPage = parentlink != null ? parentlink : ""; // set
1322
// to
1323
// non
1324
// defined
1325
}
1326
1327            File JavaDoc f = new File JavaDoc(directory, JGALLERYIGNOREFILE);
1328            if (f.exists())
1329            {
1330                imageFiles = new String JavaDoc[0];
1331            }
1332            else
1333            {
1334                imageFiles = directory.list(new FilenameFilter JavaDoc()
1335                {
1336                    public boolean accept(File JavaDoc dir, String JavaDoc name)
1337                    {
1338                        File JavaDoc f1 = new File JavaDoc(dir, name);
1339                        return (f1.isDirectory() && !thumbsdir.equals(name))
1340                                | isJPEGExtension(name);
1341                        // return isJPEGExtension(name);
1342
};
1343                });
1344
1345                subDirectories = getSubDirectories();
1346            }
1347
1348            f = new File JavaDoc(directory, CAPTIONSFILE);
1349            InputStream JavaDoc is = null;
1350            try
1351            {
1352                is = new FileInputStream JavaDoc(f);
1353                captions.load(is);
1354            }
1355            catch (FileNotFoundException JavaDoc e)
1356            {
1357                // ignore, no captions
1358
}
1359            catch (IOException JavaDoc e)
1360            {
1361                throw new GalleryException(e.getMessage(), e);
1362            }
1363
1364            imageCounters = new int[imageFiles.length];
1365            Arrays.fill(imageCounters, -1);
1366
1367            endLoad();
1368        }
1369    }
1370
1371    public class ParentLink
1372    {
1373        private String JavaDoc name;
1374
1375        private String JavaDoc url;
1376
1377        private ParentLink(String JavaDoc name, String JavaDoc url)
1378        {
1379            this.name = name;
1380            this.url = url;
1381        }
1382
1383        public String JavaDoc getName()
1384        {
1385            return name;
1386        }
1387
1388        public String JavaDoc getUrl()
1389        {
1390            return url;
1391        }
1392    }
1393
1394    private void calculateParentFolderList(String JavaDoc folderPath)
1395    {
1396        // folderPath is URL part after context
1397
// e.g. /galleries/TemplateTest/
1398

1399        parentFolderList = new ArrayList JavaDoc();
1400
1401        String JavaDoc s = folderPath.substring(1, folderPath.length() - 1);
1402
1403        String JavaDoc hTMLBase = jgalleryContextPath;
1404
1405        String JavaDoc[] s1 = s.split("/");
1406
1407        String JavaDoc p = jgalleryContextPath;
1408
1409        StringBuffer JavaDoc sb = new StringBuffer JavaDoc(jgalleryContextPath).append('/')
1410                .append(s1[0]).append('/');
1411        StringBuffer JavaDoc sb1;
1412
1413        for (int i = 1; i < s1.length; i++)
1414        {
1415            sb1 = new StringBuffer JavaDoc(sb.toString()).append("index.").append(
1416                    configData.urlExtention);
1417            parentFolderList.add(new ParentLink(s1[i - 1], sb1.toString()));
1418            sb.append(s1[i]).append('/');
1419        }
1420
1421        int x = 5;
1422    }
1423
1424    public List JavaDoc getParentFolderList()
1425    {
1426        return parentFolderList;
1427    }
1428
1429    protected void endLoad() throws GalleryException
1430    {
1431        imagesArray = new Image[imageFiles.length];
1432
1433        // if sorting is wished for, need to load all images first
1434
// and sort them
1435
if (sortingOrder != ImageComparator.SORTNONE)
1436        {
1437            for (int i = 0; i < imageFiles.length; i++)
1438            {
1439                // getImage(i + 1);
1440
getSubDirOrImage(i + 1);
1441            }
1442            Comparator JavaDoc c = new ImageComparator(sortingOrder);
1443
1444            Arrays.sort(imagesArray, subDirectories.length, imagesArray.length,
1445                    c);
1446
1447            for (int i = 0; i < imageFiles.length; i++)
1448            {
1449                imageFiles[i] = imagesArray[i].getFileName();
1450            }
1451
1452        }
1453
1454        for (int i = 0; i < imageFiles.length; i++)
1455        {
1456            String JavaDoc s = isJPEGExtension(imageFiles[i]) ? imageFiles[i]
1457                    .substring(0, imageFiles[i].indexOf('.')) : imageFiles[i];
1458            images.put(s, new Integer JavaDoc(i + 1));
1459
1460        }
1461        calculateVariables();
1462        isDirectoryParsed = true;
1463
1464        title = folderPath.substring(folderPath.indexOf('/') + 1);
1465        if (title.endsWith("/"))
1466        {
1467            title = title.substring(0, title.lastIndexOf('/'));
1468        }
1469
1470        int p = title.lastIndexOf('/');
1471        if (p > -1)
1472        {
1473            name = title.substring(p + 1);
1474        }
1475        else
1476        {
1477            name = title;
1478        }
1479
1480    }
1481
1482    public int getCurrentImagesPerPage()
1483    {
1484        if (indexNum < totalIndexes)
1485        {
1486            return rows * cols;
1487        }
1488        else
1489        {
1490            return totalImages /* + subDirectories.length */- (indexNum - 1)
1491                    * rows * cols;
1492        }
1493    }
1494
1495    public String JavaDoc getCurrentCols()
1496    {
1497        return Integer.toString(currentCols);
1498    }
1499
1500    public String JavaDoc getFolderPath()
1501    {
1502        return folderPath;
1503    }
1504
1505    public String JavaDoc getImageBasePath()
1506    {
1507        return imagePath;
1508    }
1509
1510    public String JavaDoc getThumbsPath()
1511    {
1512        return getImageBasePath() + thumbsdir;
1513    }
1514
1515    public String JavaDoc getCounter()
1516    {
1517        if (folderCounter == -1)
1518        {
1519            // increment counter only once per Session
1520

1521            if (null != dBManager)
1522            {
1523                try
1524                {
1525                    folderCounter = dBManager.getAndIncFolderCounter(
1526                            folderPath, this.configData.doCount);
1527                }
1528                catch (SQLException JavaDoc e)
1529                {
1530                    appContext.log(e.getMessage(), e);
1531                }
1532            }
1533        }
1534        String JavaDoc s = folderCounter > -1 ? Integer.toString(folderCounter) : null;
1535
1536        return s;
1537    }
1538
1539    public String JavaDoc getImageCounter(String JavaDoc name)
1540    {
1541        // trigger first putting folder into DB
1542
getCounter();
1543
1544        String JavaDoc s = name.substring(0, name.indexOf('.'));
1545
1546        String JavaDoc rc = null;
1547
1548        Integer JavaDoc theImage = (Integer JavaDoc) images.get(s);
1549        imageNum = theImage.intValue();
1550
1551        int c = imageCounters[imageNum - 1];
1552
1553        if (null != dBManager)
1554        {
1555            // increment counter only once per Session
1556

1557            if (c == -1)
1558            {
1559                try
1560                {
1561                    c = dBManager.getAndIncImageCounter(folderPath,
1562                            imageFiles[imageNum - 1], this.configData.doCount);
1563
1564                    imageCounters[imageNum - 1] = c;
1565
1566                    rc = Integer.toString(c);
1567                }
1568                catch (SQLException JavaDoc e)
1569                {
1570                    appContext.log(e.getMessage(), e);
1571                    rc = null;
1572                }
1573            }
1574            else
1575            {
1576                rc = Integer.toString(c);
1577            }
1578        }
1579        return rc;
1580    }
1581}
Popular Tags