KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > teamkonzept > webman > mainint > db > MediaManager


1 package com.teamkonzept.webman.mainint.db;
2
3 import com.teamkonzept.db.*;
4 import com.teamkonzept.lib.*;
5 import com.teamkonzept.web.TKEvent;
6 import com.teamkonzept.web.servlet.ServletInterface;
7 import com.teamkonzept.webman.db.*;
8 import com.teamkonzept.webman.mainint.db.queries.*;
9 import com.teamkonzept.webman.mainint.db.queries.content.*;
10 import com.teamkonzept.webman.mainint.db.queries.sitetree.SiteTreeTreeID;
11 import de.webman.content.eventhandler.CEUtils;
12 import de.webman.sitetree.eventhandler.SiteTreeUtils;
13 import de.webman.generator.GeneratorContext;
14 import de.webman.generator.GenDocument;
15 import de.webman.generator.GenNode;
16
17 import java.io.*;
18 import java.math.BigDecimal JavaDoc;
19 import java.sql.*;
20 import java.util.Calendar JavaDoc;
21 import java.util.GregorianCalendar JavaDoc;
22 import oracle.jdbc.driver.OracleResultSet;
23 import oracle.sql.BLOB;
24 import org.apache.log4j.Category;
25
26 /**
27  *
28  * @author marwan
29  * @version
30  */

31 public class MediaManager implements MediaInterface, QueryConstants {
32
33
34
35     /** sollen Bilderpfade relativ generiert werden ? */
36     private static boolean pathRelative = true;
37
38     /** Logging Category */
39     private static Category cat = Category.getInstance(MediaManager.class);
40
41     /** Groesse des Zwischenspeichers beim Kopieren zwischen Streams */
42     private static final int BUF_SIZE = 4096;
43
44     /** bei Sybase benutzt */
45     static final Integer JavaDoc MAX_TEXTSIZE = new Integer JavaDoc(1000000000);
46
47     /**
48      * The key of the databasetable MEDIA
49      */

50     private Integer JavaDoc mediaID;
51
52     /**
53      * The key of the databasetable CONTENT
54      */

55     private Integer JavaDoc contentID;
56
57
58     /**
59      * Contains the webservers document root, for situations where no TKEvent is available
60      */

61     private static String JavaDoc documentRoot;
62
63     /** ob ein Verzeichnis bei der Generierung davorliegt - noch wichtig ? */
64     private static String JavaDoc appContext;
65
66     /**
67     * Attributes retrieved from the database
68     */

69     private TKHashtable dbAttributes;
70
71
72     public MediaManager(int mediaID){
73         this.mediaID = new Integer JavaDoc(mediaID);
74     }
75
76     static
77     {
78         try
79         {
80             PropertyManager back = PropertyManager.getPropertyManager("UPLOAD");
81             String JavaDoc value = back.getValue("ABSOLUTE_PATH", "");
82             pathRelative = !value.equalsIgnoreCase("TRUE");
83         }
84         catch (Throwable JavaDoc t)
85         {
86               cat.debug("Error during reading UPLOAD group", t);
87         }
88     }
89
90     public static void setDocumentRoot(String JavaDoc root){
91         documentRoot = root;
92     }
93
94     /**
95         The _path is prepended to the return value of the toString() mehtod
96     */

97     public static void setContextPath(String JavaDoc _path)
98     {
99         appContext = _path;
100     }
101
102     /**
103      * holt den eigentlichen Stream aus der Datenbank
104      * wir setzen von außen ! autoCommit auf false bei Postgres !
105      */

106     private static InputStream getMedia(int mediaID, Connection con)throws SQLException
107     {
108         InputStream mediaStream=null;
109         if(TKWebmanDBManager.getDBVendor() == QueryConstants.SYBASE)
110         {
111             // Set the maximal number of bytes to be fetched from db
112
Statement stmtTextsize = TKWebmanDBManager.getConnection().createStatement();
113             stmtTextsize.executeUpdate("set textsize " + MAX_TEXTSIZE.intValue() );
114             stmtTextsize.close();
115         }
116
117         String JavaDoc getMediaStatement = "SELECT VALUE FROM MEDIA WHERE MEDIA_ID = ? ";
118         PreparedStatement pstmt = con.prepareStatement(getMediaStatement);
119         pstmt.setInt(1,mediaID);
120         ResultSet rs = pstmt.executeQuery();
121
122         if(rs.next()){
123             if(TKWebmanDBManager.getDBVendor() == QueryConstants.ORACLE)
124             {
125                 Blob blob = rs.getBlob("VALUE");
126                 mediaStream = blob.getBinaryStream();
127             }
128             else
129                 mediaStream = rs.getBinaryStream(QueryConstants.VALUE);
130         }
131         // con.commit();
132
return mediaStream;
133     }
134
135
136     public static Integer JavaDoc getMediaSize(int mediaID)throws SQLException{
137         Integer JavaDoc size = null;
138         TKHashtable attrs = getAttributesFromDB(mediaID);
139         if(attrs.containsKey(MEDIA_SIZE)){
140             size = (Integer JavaDoc)attrs.get(MEDIA_SIZE);
141         }
142         return size;
143     }
144
145     public Integer JavaDoc getMediaSize()throws SQLException{
146         Integer JavaDoc retInt = (Integer JavaDoc) getAttributesFromDB().get(MEDIA_SIZE) ;
147         return retInt;
148     }
149
150 /* public static void setMediaName(int mediaID, String name)throws SQLException{
151
152         TKQuery getMediaQuery = TKWebmanDBManager.newQuery(MediaSetName.class);
153         getMediaQuery.setQueryParams(MEDIA_ID, new Integer(mediaID));
154         getMediaQuery.setQueryParams(NAME,name);
155         getMediaQuery.execute();
156         getMediaQuery.close();
157         return;
158     }
159
160     public static void setMediaDate(int mediaID, Calendar calendar)throws SQLException{
161
162         Timestamp stamp = new Timestamp(calendar.getTime().getTime());
163         TKQuery getMediaQuery = TKWebmanDBManager.newQuery(MediaSetDate.class);
164         getMediaQuery.setQueryParams(MEDIA_ID, new Integer(mediaID));
165         getMediaQuery.setQueryParams(UP_DATE, stamp);
166         getMediaQuery.execute();
167         getMediaQuery.close();
168         return;
169     }
170 */

171
172     public static int storeMedia(File file)throws IOException, SQLException, FileNotFoundException{
173         return storeMedia(file, null);
174     }
175
176     public static int storeMedia(File file, String JavaDoc filename)throws IOException, SQLException, FileNotFoundException{
177
178         InputStream fin = new FileInputStream(file);
179         int fileLength = (int)file.length();
180         int nextMediaID=0;
181
182         if(filename == null || filename.trim().equals("") ){
183             filename = file.getName();
184         }
185
186         synchronized(MediaManager.class){
187
188             nextMediaID = getNextMediaID();
189
190             Connection con = TKWebmanDBManager.getConnection();
191             boolean oldCommit = con.getAutoCommit();
192
193             // only Sybase does not need a transaction here
194
if(TKWebmanDBManager.getDBVendor() != QueryConstants.SYBASE ){
195                 con.setAutoCommit(false);
196             }
197
198             String JavaDoc insertMediaStmt =
199                 "INSERT INTO MEDIA ( MEDIA_ID, VALUE, NAME, UP_DATE, MEDIA_SIZE ) VALUES (?, ?, ?, ?, ?)";
200             PreparedStatement pstmt = con.prepareStatement(insertMediaStmt);
201
202             pstmt.setInt(1, nextMediaID);
203             // pstmt.setInt(6, nextMediaID);
204
if (TKWebmanDBManager.getDBVendor() == QueryConstants.ORACLE)
205             {
206                 // empty BLOB
207
// pstmt.setBlob(2, null);
208
byte[] byteArr = new byte[1];
209                 byteArr[0] = (byte)'\u0020';
210                 pstmt.setBytes(2, byteArr);
211             }
212             else
213             {
214                 if(fileLength > 0){
215                     pstmt.setBinaryStream(2, fin, fileLength);
216                 }
217                 else{
218                     byte[] byteArr = new byte[1];
219                     byteArr[0] = (byte)'\u0020'; // space, sybase's representation for an empty string
220
pstmt.setObject(2,byteArr,Types.LONGVARBINARY);
221                 }
222             }
223             pstmt.setString(3, filename);
224             pstmt.setTimestamp(4, new Timestamp((new GregorianCalendar JavaDoc()).getTime().getTime()));
225             pstmt.setInt(5, fileLength);
226
227             pstmt.executeUpdate();
228             if (TKWebmanDBManager.getDBVendor() == QueryConstants.ORACLE)
229             {
230                String JavaDoc selectString = "SELECT VALUE FROM MEDIA WHERE MEDIA_ID = ?";
231                pstmt = con.prepareStatement(selectString);
232                pstmt.setInt(1, nextMediaID);
233                ResultSet rs = pstmt.executeQuery();
234                rs.next();
235                BLOB blob = ((OracleResultSet)rs).getBLOB("VALUE");
236
237                OutputStream out = blob.getBinaryOutputStream();
238                byte[] buffer = new byte[BUF_SIZE];
239                int bytesRead;
240                while((bytesRead = fin.read(buffer)) != -1){
241                 out.write(buffer, 0, bytesRead);
242                }
243                 out.close();
244             }
245             con.commit();
246
247             if(TKWebmanDBManager.getDBVendor() != QueryConstants.SYBASE){
248                 con.setAutoCommit(oldCommit);
249             }
250
251         }
252
253         return nextMediaID;
254     }
255
256     public static void writeToOutputStream(OutputStream out, int mediaID)throws SQLException, IOException
257     {
258         Connection con = TKWebmanDBManager.getConnection();
259         boolean oldCommit = con.getAutoCommit();
260         if(TKWebmanDBManager.getDBVendor() != QueryConstants.SYBASE)
261         {
262             con.setAutoCommit(false);
263         }
264         InputStream in = null;
265         try{
266             in = getMedia(mediaID, con);
267             byte[] buf = new byte[BUF_SIZE];
268             int bytesRead;
269             while((bytesRead = in.read(buf)) != -1){
270                 out.write(buf, 0, bytesRead);
271             }
272         }
273         finally{
274
275             if(TKWebmanDBManager.getDBVendor() != QueryConstants.SYBASE)
276             {
277                  in.close();
278                 con.commit();
279
280                 in = null;
281                 con.setAutoCommit(oldCommit);
282             }
283             if(in != null){
284                 in.close();
285             }
286         }
287     }
288
289
290     public static String JavaDoc getContextPath(){
291         String JavaDoc contextPath = null;
292         TKEvent event = TKEvent.getEventForThread();
293         if(event != null){
294             contextPath = ((ServletInterface)event.getHttpInterface()).getContextPath();
295         }
296         else if(documentRoot != null){
297             contextPath = parseContextPath(documentRoot);
298         }
299         return contextPath;
300     }
301
302     private static String JavaDoc parseContextPath(String JavaDoc docRoot){
303         if(docRoot.endsWith(File.separator)){
304             docRoot = docRoot.substring(0,docRoot.length() - 1);
305         }
306         int lastSlash = docRoot.lastIndexOf(File.separatorChar);
307         if (lastSlash == -1)
308             return docRoot;
309         docRoot = docRoot.substring(lastSlash);
310         return docRoot;
311     }
312
313     private static String JavaDoc parseFilenameExtension(String JavaDoc filename){
314         if (filename == null)
315             return "";
316         String JavaDoc extension = null;
317         int dot = filename.lastIndexOf('.');
318         if(dot > 0){
319             extension = filename.substring(dot+1);
320         }
321         return extension;
322     }
323
324
325     private static int getNextMediaID()throws SQLException{
326         int nextMediaID=0;
327         TKQuery queryNextID = TKWebmanDBManager.newQuery(MediaGetNextID.class);
328         queryNextID.execute();
329         ResultSet rs = queryNextID.fetchResultSet();
330         if(rs.next()){
331             nextMediaID = rs.getInt(NEXT_MEDIA_ID);
332         }
333         if (nextMediaID == 0){
334             throw new Error JavaDoc("Media insertion failed");
335         }
336
337
338         return nextMediaID;
339     }
340
341 /* public static void setMediaSize(int mediaID, int fileLength)throws SQLException{
342         TKQuery getMediaQuery = TKWebmanDBManager.newQuery(MediaSetSize.class);
343         getMediaQuery.setQueryParams(MEDIA_ID, new Integer(mediaID));
344         getMediaQuery.setQueryParams(MEDIA_SIZE, new Integer(fileLength));
345         getMediaQuery.execute();
346         getMediaQuery.close();
347
348     }
349 */

350     /**
351         @author marwan
352
353         Deletes all MEDIA Records referenced from the subtree of contenttree
354         rooted at contentRootID, that are not referenced from outside this
355         subtree.
356         (Might be expensive)
357     */

358     public static void deleteAccordingToContenttree(int contentRootID)throws SQLException{
359         TKQuery getMediaIDs = TKWebmanDBManager.newQuery(GetMediaIDsAccContTree.class);
360         getMediaIDs.setQueryParams(CONTENT_TREE_ID, new Integer JavaDoc(contentRootID));
361         getMediaIDs.execute();
362         ResultSet rsMediaIDs = getMediaIDs.fetchResultSet();
363         while(rsMediaIDs.next()){
364             int mediaID = rsMediaIDs.getInt(MEDIA_ID);
365             /* Set references to NULL */
366             TKQuery delRefs = TKWebmanDBManager.newQuery(MediaIDSetNullInContVal.class);
367             delRefs.setQueryParams(MEDIA_ID, new Integer JavaDoc(mediaID));
368             delRefs.execute();
369
370             /* Delete MEDIA record */
371             TKQuery delMedia = TKWebmanDBManager.newQuery(MediaDelete.class);
372             delMedia.setQueryParams(MEDIA_ID, new Integer JavaDoc(mediaID) );
373             delMedia.execute();
374         }
375     }
376
377
378     /*
379         @author marwan
380         Brute Force!
381         Deletes all MEDIA records that are not referenced from CONTENT_VALUE.
382     */

383     public static void cleanUpMediaTable()throws SQLException{
384             TKQuery delMedia = TKWebmanDBManager.newQuery(MediaDeleteUnreferenced.class);
385             delMedia.execute();
386     }
387
388     // instancemethods
389

390
391     public Integer JavaDoc setMediaID(int newID){
392         Integer JavaDoc oldID = mediaID;
393         mediaID = new Integer JavaDoc(newID);
394         return oldID;
395     }
396
397     public Integer JavaDoc getMediaID(){
398         return mediaID;
399     }
400
401     public Integer JavaDoc setContentID(int newID){
402         contentID = new Integer JavaDoc(newID);
403         return contentID;
404     }
405
406     public Integer JavaDoc getContentID(){
407         return contentID;
408     }
409
410     public static String JavaDoc getPath(int contentID)throws SQLException
411     {
412         String JavaDoc path = null;
413         TKQuery qContentTreeID = TKWebmanDBManager.newQuery(ContentTreeID.class);
414         qContentTreeID.setQueryParams(CONTENT_ID, new Integer JavaDoc(contentID));
415         qContentTreeID.execute();
416         ResultSet rs = qContentTreeID.fetchResultSet();
417         int contentTreeID;
418         if(rs.next())
419         {
420             contentTreeID = rs.getInt(CONTENT_NODE_ID);
421             path = CEUtils.getCurrentPath( new Integer JavaDoc(contentTreeID));
422         }
423         else
424         {
425             // Sitestruktur Parameter
426
qContentTreeID = TKWebmanDBManager.newQuery(SiteTreeTreeID.class);
427             qContentTreeID.setQueryParams(CONTENT_ID, new Integer JavaDoc(contentID));
428             qContentTreeID.execute();
429             rs = qContentTreeID.fetchResultSet();
430             if(rs.next())
431             {
432                 int siteNodeID = rs.getInt("SITE_NODE_ID");
433                 path = SiteTreeUtils.getCurrentPath( new Integer JavaDoc(siteNodeID));
434             }
435             // path = SITE_PATH;
436
}
437         return path;
438     }
439
440     /**
441      * @return den Pfad absolut zur Dokumentroot
442      */

443     public String JavaDoc getPath()throws SQLException{
444         if(contentID == null) throw new Error JavaDoc("contentID == null! setContentID() has to be called previously");
445         return getPath(contentID.intValue());
446     }
447
448     public String JavaDoc getFilenameExtension()throws SQLException{
449         return parseFilenameExtension(getMediaName());
450
451     }
452
453     public String JavaDoc getFilenameWithoutExt()throws SQLException{
454         String JavaDoc shortName = null;
455         String JavaDoc fileName = getMediaName();
456         if (fileName == null)
457             return "";
458         int dot = fileName.lastIndexOf('.');
459         if(dot > 0){
460             shortName = fileName .substring(0, dot);
461         }
462         return shortName;
463     }
464
465     public String JavaDoc writeToDisk()throws IOException, SQLException, Throwable JavaDoc{
466         return writeToDiskIfModified();
467     }
468
469     public String JavaDoc writeToDiskIfModified()throws IOException, SQLException, Throwable JavaDoc{
470         String JavaDoc path = getPath(contentID.intValue());
471         String JavaDoc documentRoot;
472
473         TKEvent event = TKEvent.getEventForThread();
474         if(event == null){
475             documentRoot = this.documentRoot;
476             //appContext = parseContextPath(documentRoot);
477
}
478         else{
479             documentRoot = event.getHttpInterface().getDocumentRoot();
480         }
481
482         String JavaDoc fileNamePath = path + getMediaName();
483
484         File file = new File(documentRoot + fileNamePath);
485
486         File directory = file.getParentFile();
487         if(!directory.isDirectory()){
488             directory.mkdirs();
489         }
490
491         long lastModified = file.lastModified();
492         long uploaded = getMediaTimestamp()!= null ? getMediaTimestamp().getTime() : new GregorianCalendar JavaDoc().getTime().getTime();
493         if(uploaded >= lastModified){
494             FileOutputStream out = new FileOutputStream(file);
495             writeToOutputStream(out, mediaID.intValue());
496         }
497         return fileNamePath;
498
499     }
500
501     private static TKHashtable getAttributesFromDB(int mediaID)throws SQLException{
502         TKHashtable attrs = new TKHashtable();
503         TKQuery getMediaQuery = TKWebmanDBManager.newQuery(MediaGetAttributes.class);
504         getMediaQuery.setQueryParams(MEDIA_ID, new Integer JavaDoc(mediaID));
505         getMediaQuery.execute();
506         ResultSet rs = getMediaQuery.fetchResultSet();
507         ResultSetMetaData meta = rs.getMetaData();
508         int columnCount = meta.getColumnCount();
509
510         if(rs.next()){
511             for(int i = 1 ; i <= columnCount; i++){
512
513                 String JavaDoc columnName = meta.getColumnName(i).toUpperCase();
514                 int columnType = meta.getColumnType(i);
515                 Object JavaDoc objectValue = null;
516
517                 if(columnType == Types.INTEGER || columnType == Types.NUMERIC){
518                     objectValue = new Integer JavaDoc(rs.getInt(columnName));
519                 }
520                 else if(columnType == Types.VARCHAR ){
521                     objectValue = rs.getString(columnName);
522                 }
523                 else if(columnType == Types.DATE || columnType == Types.TIMESTAMP || columnType == Types.TIME ){
524                     objectValue = rs.getTimestamp(columnName);
525                 }
526                 // certain names
527
else if(columnName.equals( MEDIA_SIZE) ){
528                     objectValue = new Integer JavaDoc(rs.getInt(columnName));
529
530                 }
531                 else{
532                     objectValue = rs.getObject(columnName);
533                 }
534                 if(objectValue != null){
535                     attrs.put(columnName, objectValue);
536                 }
537             }
538         }
539
540         return attrs;
541     }
542
543     public TKHashtable getAttributesFromDB()throws SQLException{
544         if (mediaID == null) throw new Error JavaDoc("MediaManager instance not properly initialized");
545         if(dbAttributes == null){
546             dbAttributes = getAttributesFromDB(mediaID.intValue());
547         }
548         return dbAttributes;
549     }
550
551     public static String JavaDoc getMediaName(int mediaID){
552         String JavaDoc name = null;
553         try{
554             TKQuery getMediaQuery = TKWebmanDBManager.newQuery(MediaGetName.class);
555             getMediaQuery.setQueryParams(MEDIA_ID, new Integer JavaDoc(mediaID));
556             getMediaQuery.execute();
557             ResultSet rs = getMediaQuery.fetchResultSet();
558             if(rs.next()){
559                 name = rs.getString(NAME);
560             }
561         }
562         catch(SQLException e){
563             throw new Error JavaDoc(e.getMessage());
564         }
565         return name;
566     }
567
568     public String JavaDoc getMediaName()throws SQLException{
569         return (String JavaDoc)getAttributesFromDB().get(NAME);
570     }
571
572     public Timestamp getMediaTimestamp()throws SQLException{
573         return (Timestamp)getAttributesFromDB().get(UP_DATE);
574     }
575
576     public static Timestamp getMediaTimestamp(int mediaID)throws SQLException{
577         Timestamp stamp = null;
578         TKHashtable attrs = getAttributesFromDB(mediaID);
579         if(attrs.containsKey(UP_DATE)){
580             stamp = (Timestamp)attrs.get(UP_DATE);
581         }
582         return stamp;
583     }
584
585     /**
586         gibt den Pfad zurueck, der beim Generieren geschrieben wird
587         fuer das Property FILE_PATH
588     */

589     public String JavaDoc getFilePath() throws SQLException
590     {
591         String JavaDoc path = getPath();
592         if(appContext != null){
593             return appContext + path;
594         }
595         else{
596             return path;
597         }
598
599     }
600
601     /**
602      * Bild wird hier rausgeschrieben, damit es bei TKMLnur dann geschrieben wird,
603      * wenn es wirklich gebraucht wird
604      * @return den Pfad zum Bild
605      */

606     public String JavaDoc toString(){
607         String JavaDoc path = null;
608         try{
609             path = writeToDisk();
610             return getRelativePath(path);
611         }
612         catch (Error JavaDoc er)
613         {
614             throw er;
615         }
616         catch(Throwable JavaDoc e){
617             cat.error("MediaManager.toString()", e);
618             throw new Error JavaDoc(e.getMessage());
619         }
620
621     }
622
623     /**
624      * macht den Pfad des Images relativ zur Generierung/Preview
625      * @param path der Pfad zum Image
626      * @return den relativen Pfad
627      */

628     public static String JavaDoc getRelativePath(String JavaDoc path)
629     {
630        if (GeneratorContext.isPreviewMode())
631         {
632             return getContextPath() + path;
633         }
634         else if (!pathRelative)
635         {
636             if(appContext != null){
637                 return appContext + path;
638             }
639             else{
640                 return path;
641             }
642         }
643         String JavaDoc prefix = "";
644         GenDocument doc = GeneratorContext.getCurrentDocument();
645         if (doc != null)
646         {
647             GenNode node = doc.getAnchor();
648             int depth = node.depth(); // root hat depth 1
649
for (int i = 1;i < depth; i++)
650             {
651                 prefix += "..";
652                 if (i < depth-1)
653                     prefix += "/";
654             }
655             if (depth == 1)
656                 prefix = ".";
657         }
658         // System.out.println("Neuer Pfad: " + prefix + path);
659
return prefix + path;
660     }
661 }
662
Popular Tags