KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > dspace > content > BitstreamFormat


1 /*
2  * BitstreamFormat.java
3  *
4  * Version: $Revision: 1.24 $
5  *
6  * Date: $Date: 2006/11/10 19:39:17 $
7  *
8  * Copyright (c) 2002-2005, Hewlett-Packard Company and Massachusetts
9  * Institute of Technology. All rights reserved.
10  *
11  * Redistribution and use in source and binary forms, with or without
12  * modification, are permitted provided that the following conditions are
13  * met:
14  *
15  * - Redistributions of source code must retain the above copyright
16  * notice, this list of conditions and the following disclaimer.
17  *
18  * - Redistributions in binary form must reproduce the above copyright
19  * notice, this list of conditions and the following disclaimer in the
20  * documentation and/or other materials provided with the distribution.
21  *
22  * - Neither the name of the Hewlett-Packard Company nor the name of the
23  * Massachusetts Institute of Technology nor the names of their
24  * contributors may be used to endorse or promote products derived from
25  * this software without specific prior written permission.
26  *
27  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
28  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
29  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
30  * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
31  * HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
32  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
33  * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
34  * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
35  * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
36  * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
37  * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
38  * DAMAGE.
39  */

40 package org.dspace.content;
41
42 import java.sql.SQLException JavaDoc;
43 import java.util.ArrayList JavaDoc;
44 import java.util.List JavaDoc;
45
46 import org.apache.log4j.Logger;
47 import org.dspace.authorize.AuthorizeException;
48 import org.dspace.authorize.AuthorizeManager;
49 import org.dspace.core.ConfigurationManager;
50 import org.dspace.core.Context;
51 import org.dspace.core.LogManager;
52 import org.dspace.storage.rdbms.DatabaseManager;
53 import org.dspace.storage.rdbms.TableRow;
54 import org.dspace.storage.rdbms.TableRowIterator;
55
56 /**
57  * Class representing a particular bitstream format.
58  * <P>
59  * Changes to the bitstream format metadata are only written to the database
60  * when <code>update</code> is called.
61  *
62  * @author Robert Tansley
63  * @version $Revision: 1.24 $
64  */

65 public class BitstreamFormat
66 {
67     /** log4j logger */
68     private static Logger log = Logger.getLogger(BitstreamFormat.class);
69
70     /**
71      * The "unknown" support level - for bitstream formats that are unknown to
72      * the system
73      */

74     public static final int UNKNOWN = 0;
75
76     /**
77      * The "known" support level - for bitstream formats that are known to the
78      * system, but not fully supported
79      */

80     public static final int KNOWN = 1;
81
82     /**
83      * The "supported" support level - for bitstream formats known to the system
84      * and fully supported.
85      */

86     public static final int SUPPORTED = 2;
87
88     /** Our context */
89     private Context bfContext;
90
91     /** The row in the table representing this format */
92     private TableRow bfRow;
93
94     /** File extensions for this format */
95     private List JavaDoc extensions;
96
97     /**
98      * Class constructor for creating a BitstreamFormat object based on the
99      * contents of a DB table row.
100      *
101      * @param context
102      * the context this object exists in
103      * @param row
104      * the corresponding row in the table
105      * @throws SQLException
106      */

107     BitstreamFormat(Context context, TableRow row) throws SQLException JavaDoc
108     {
109         bfContext = context;
110         bfRow = row;
111         extensions = new ArrayList JavaDoc();
112
113         TableRowIterator tri = DatabaseManager.query(context,
114                 "SELECT * FROM fileextension WHERE bitstream_format_id= ? ",
115                  getID());
116
117         while (tri.hasNext())
118         {
119             extensions.add(tri.next().getStringColumn("extension"));
120         }
121         // close the TableRowIterator to free up resources
122
tri.close();
123
124         // Cache ourselves
125
context.cache(this, row.getIntColumn("bitstream_format_id"));
126     }
127
128     /**
129      * Get a bitstream format from the database.
130      *
131      * @param context
132      * DSpace context object
133      * @param id
134      * ID of the bitstream format
135      *
136      * @return the bitstream format, or null if the ID is invalid.
137      * @throws SQLException
138      */

139     public static BitstreamFormat find(Context context, int id)
140             throws SQLException JavaDoc
141     {
142         // First check the cache
143
BitstreamFormat fromCache = (BitstreamFormat) context.fromCache(
144                 BitstreamFormat.class, id);
145
146         if (fromCache != null)
147         {
148             return fromCache;
149         }
150
151         TableRow row = DatabaseManager.find(context, "bitstreamformatregistry",
152                 id);
153
154         if (row == null)
155         {
156             if (log.isDebugEnabled())
157             {
158                 log.debug(LogManager.getHeader(context,
159                         "find_bitstream_format",
160                         "not_found,bitstream_format_id=" + id));
161             }
162
163             return null;
164         }
165
166         // not null, return format object
167
if (log.isDebugEnabled())
168         {
169             log.debug(LogManager.getHeader(context, "find_bitstream_format",
170                     "bitstream_format_id=" + id));
171         }
172
173         return new BitstreamFormat(context, row);
174     }
175
176     /**
177      * Find a bitstream format by its (unique) MIME type.
178      * If more than one bitstream format has the same MIME type, the
179      * one returned is unpredictable.
180      *
181      * @param context
182      * DSpace context object
183      * @param mimeType
184      * MIME type value
185      *
186      * @return the corresponding bitstream format, or <code>null</code> if
187      * there's no bitstream format with the given MIMEtype.
188      * @throws SQLException
189      */

190     public static BitstreamFormat findByMIMEType(Context context,
191             String JavaDoc mimeType) throws SQLException JavaDoc
192     {
193         // NOTE: Avoid internal formats since e.g. "License" also has
194
// a MIMEtype of text/plain.
195
TableRow formatRow = DatabaseManager.querySingle(context,
196             "SELECT * FROM bitstreamformatregistry "+
197             "WHERE mimetype LIKE ? AND internal = '0' ",
198             mimeType);
199
200         if (formatRow == null)
201             return null;
202         return findByFinish(context, formatRow);
203     }
204
205     /**
206      * Find a bitstream format by its (unique) short description
207      *
208      * @param context
209      * DSpace context object
210      * @param desc
211      * the short description
212      *
213      * @return the corresponding bitstream format, or <code>null</code> if
214      * there's no bitstream format with the given short description
215      * @throws SQLException
216      */

217     public static BitstreamFormat findByShortDescription(Context context,
218             String JavaDoc desc) throws SQLException JavaDoc
219     {
220         TableRow formatRow = DatabaseManager.findByUnique(context,
221                 "bitstreamformatregistry", "short_description", desc);
222
223         if (formatRow == null)
224         {
225             return null;
226         }
227
228         return findByFinish(context, formatRow);
229     }
230
231     // shared final logic in findBy... methods;
232
// use context's cache for object mapped from table row.
233
private static BitstreamFormat findByFinish(Context context,
234                                                 TableRow formatRow)
235         throws SQLException JavaDoc
236     {
237         // not null
238
if (log.isDebugEnabled())
239         {
240             log.debug(LogManager.getHeader(context, "find_bitstream",
241                     "bitstream_format_id="
242                             + formatRow.getIntColumn("bitstream_format_id")));
243         }
244
245         // From cache?
246
BitstreamFormat fromCache = (BitstreamFormat) context.fromCache(
247                 BitstreamFormat.class, formatRow
248                         .getIntColumn("bitstream_format_id"));
249
250         if (fromCache != null)
251         {
252             return fromCache;
253         }
254
255         return new BitstreamFormat(context, formatRow);
256     }
257
258     /**
259      * Get the generic "unknown" bitstream format.
260      *
261      * @param context
262      * DSpace context object
263      *
264      * @return the "unknown" bitstream format.
265      * @throws SQLException
266      *
267      * @throws IllegalStateException
268      * if the "unknown" bitstream format couldn't be found
269      */

270     public static BitstreamFormat findUnknown(Context context)
271             throws SQLException JavaDoc
272     {
273         BitstreamFormat bf = findByShortDescription(context, "Unknown");
274
275         if (bf == null)
276         {
277             throw new IllegalStateException JavaDoc(
278                     "No `Unknown' bitstream format in registry");
279         }
280
281         return bf;
282     }
283
284     /**
285      * Retrieve all bitstream formats from the registry, ordered by ID
286      *
287      * @param context
288      * DSpace context object
289      *
290      * @return the bitstream formats.
291      * @throws SQLException
292      */

293     public static BitstreamFormat[] findAll(Context context)
294             throws SQLException JavaDoc
295     {
296         List JavaDoc formats = new ArrayList JavaDoc();
297
298         TableRowIterator tri = DatabaseManager.queryTable(context, "bitstreamformatregistry",
299                         "SELECT * FROM bitstreamformatregistry ORDER BY bitstream_format_id");
300
301         while (tri.hasNext())
302         {
303             TableRow row = tri.next();
304
305             // From cache?
306
BitstreamFormat fromCache = (BitstreamFormat) context.fromCache(
307                     BitstreamFormat.class, row
308                             .getIntColumn("bitstream_format_id"));
309
310             if (fromCache != null)
311             {
312                 formats.add(fromCache);
313             }
314             else
315             {
316                 formats.add(new BitstreamFormat(context, row));
317             }
318         }
319         // close the TableRowIterator to free up resources
320
tri.close();
321
322         // Return the formats as an array
323
BitstreamFormat[] formatArray = new BitstreamFormat[formats.size()];
324         formatArray = (BitstreamFormat[]) formats.toArray(formatArray);
325
326         return formatArray;
327     }
328
329     /**
330      * Retrieve all non-internal bitstream formats from the registry. The
331      * "unknown" format is not included, and the formats are ordered by support
332      * level (highest first) first then short description.
333      *
334      * @param context
335      * DSpace context object
336      *
337      * @return the bitstream formats.
338      * @throws SQLException
339      */

340     public static BitstreamFormat[] findNonInternal(Context context)
341             throws SQLException JavaDoc
342     {
343         List JavaDoc formats = new ArrayList JavaDoc();
344
345         String JavaDoc myQuery = "SELECT * FROM bitstreamformatregistry WHERE internal='0' "
346                 + "AND short_description NOT LIKE 'Unknown' "
347                 + "ORDER BY support_level DESC, short_description";
348
349         TableRowIterator tri = DatabaseManager.queryTable(context,
350                 "bitstreamformatregistry", myQuery);
351
352         while (tri.hasNext())
353         {
354             TableRow row = tri.next();
355
356             // From cache?
357
BitstreamFormat fromCache = (BitstreamFormat) context.fromCache(
358                     BitstreamFormat.class, row
359                             .getIntColumn("bitstream_format_id"));
360
361             if (fromCache != null)
362             {
363                 formats.add(fromCache);
364             }
365             else
366             {
367                 formats.add(new BitstreamFormat(context, row));
368             }
369         }
370         // close the TableRowIterator to free up resources
371
tri.close();
372
373         // Return the formats as an array
374
BitstreamFormat[] formatArray = new BitstreamFormat[formats.size()];
375         formatArray = (BitstreamFormat[]) formats.toArray(formatArray);
376
377         return formatArray;
378     }
379
380     /**
381      * Create a new bitstream format
382      *
383      * @param context
384      * DSpace context object
385      * @return the newly created BitstreamFormat
386      * @throws SQLException
387      * @throws AuthorizeException
388      */

389     public static BitstreamFormat create(Context context) throws SQLException JavaDoc,
390             AuthorizeException
391     {
392         // Check authorisation - only administrators can create new formats
393
if (!AuthorizeManager.isAdmin(context))
394         {
395             throw new AuthorizeException(
396                     "Only administrators can create bitstream formats");
397         }
398
399         // Create a table row
400
TableRow row = DatabaseManager.create(context,
401                 "bitstreamformatregistry");
402
403         log.info(LogManager.getHeader(context, "create_bitstream_format",
404                 "bitstream_format_id="
405                         + row.getIntColumn("bitstream_format_id")));
406
407         return new BitstreamFormat(context, row);
408     }
409
410     /**
411      * Get the internal identifier of this bitstream format
412      *
413      * @return the internal identifier
414      */

415     public int getID()
416     {
417         return bfRow.getIntColumn("bitstream_format_id");
418     }
419
420     /**
421      * Get a short (one or two word) description of this bitstream format
422      *
423      * @return the short description
424      */

425     public String JavaDoc getShortDescription()
426     {
427         return bfRow.getStringColumn("short_description");
428     }
429
430     /**
431      * Set the short description of the bitstream format
432      *
433      * @param s
434      * the new short description
435      */

436     public void setShortDescription(String JavaDoc s)
437        throws SQLException JavaDoc
438     {
439         // You can not reset the unknown's registry's name
440
BitstreamFormat unknown = null;;
441         try {
442             unknown = findUnknown(bfContext);
443         } catch (IllegalStateException JavaDoc e) {
444             // No short_description='Unknown' found in bitstreamformatregistry
445
// table. On first load of registries this is expected because it
446
// hasn't been inserted yet! So, catch but ignore this runtime
447
// exception thrown by method findUnknown.
448
}
449         
450         // If the exception was thrown, unknown will == null so goahead and
451
// load s. If not, check that the unknown's registry's name is not
452
// being reset.
453
if (unknown == null || unknown.getID() != getID()) {
454             bfRow.setColumn("short_description", s);
455         }
456     }
457
458     /**
459      * Get a description of this bitstream format, including full application or
460      * format name
461      *
462      * @return the description
463      */

464     public String JavaDoc getDescription()
465     {
466         return bfRow.getStringColumn("description");
467     }
468
469     /**
470      * Set the description of the bitstream format
471      *
472      * @param s
473      * the new description
474      */

475     public void setDescription(String JavaDoc s)
476     {
477         bfRow.setColumn("description", s);
478     }
479
480     /**
481      * Get the MIME type of this bitstream format, for example
482      * <code>text/plain</code>
483      *
484      * @return the MIME type
485      */

486     public String JavaDoc getMIMEType()
487     {
488         return bfRow.getStringColumn("mimetype");
489     }
490
491     /**
492      * Set the MIME type of the bitstream format
493      *
494      * @param s
495      * the new MIME type
496      */

497     public void setMIMEType(String JavaDoc s)
498     {
499         bfRow.setColumn("mimetype", s);
500     }
501
502     /**
503      * Get the support level for this bitstream format - one of
504      * <code>UNKNOWN</code>,<code>KNOWN</code> or <code>SUPPORTED</code>.
505      *
506      * @return the support level
507      */

508     public int getSupportLevel()
509     {
510         return bfRow.getIntColumn("support_level");
511     }
512
513     /**
514      * Set the support level for this bitstream format - one of
515      * <code>UNKNOWN</code>,<code>KNOWN</code> or <code>SUPPORTED</code>.
516      *
517      * @param sl
518      * the new support level
519      */

520     public void setSupportLevel(int sl)
521     {
522         // Sanity check
523
if ((sl < 0) || (sl > 2))
524         {
525             throw new IllegalArgumentException JavaDoc("Invalid support level");
526         }
527
528         bfRow.setColumn("support_level", sl);
529     }
530
531     /**
532      * Find out if the bitstream format is an internal format - that is, one
533      * that is used to store system information, rather than the content of
534      * items in the system
535      *
536      * @return <code>true</code> if the bitstream format is an internal type
537      */

538     public boolean isInternal()
539     {
540         return bfRow.getBooleanColumn("internal");
541     }
542
543     /**
544      * Set whether the bitstream format is an internal format
545      *
546      * @param b
547      * pass in <code>true</code> if the bitstream format is an
548      * internal type
549      */

550     public void setInternal(boolean b)
551     {
552         bfRow.setColumn("internal", b);
553     }
554
555     /**
556      * Update the bitstream format metadata
557      *
558      * @throws SQLException
559      * @throws AuthorizeException
560      */

561     public void update() throws SQLException JavaDoc, AuthorizeException
562     {
563         // Check authorisation - only administrators can change formats
564
if (!AuthorizeManager.isAdmin(bfContext))
565         {
566             throw new AuthorizeException(
567                     "Only administrators can modify bitstream formats");
568         }
569
570         log.info(LogManager.getHeader(bfContext, "update_bitstream_format",
571                 "bitstream_format_id=" + getID()));
572
573         // Delete extensions
574
DatabaseManager.updateQuery(bfContext,
575                 "DELETE FROM fileextension WHERE bitstream_format_id= ? ",
576                 getID());
577
578         // Rewrite extensions
579
for (int i = 0; i < extensions.size(); i++)
580         {
581             String JavaDoc s = (String JavaDoc) extensions.get(i);
582             TableRow r = DatabaseManager.create(bfContext, "fileextension");
583             r.setColumn("bitstream_format_id", getID());
584             r.setColumn("extension", s);
585             DatabaseManager.update(bfContext, r);
586         }
587
588         DatabaseManager.update(bfContext, bfRow);
589     }
590
591     /**
592      * Delete this bitstream format. This converts the types of any bitstreams
593      * that may have this type to "unknown". Use this with care!
594      *
595      * @throws SQLException
596      * @throws AuthorizeException
597      */

598     public void delete() throws SQLException JavaDoc, AuthorizeException
599     {
600         // Check authorisation - only administrators can delete formats
601
if (!AuthorizeManager.isAdmin(bfContext))
602         {
603             throw new AuthorizeException(
604                     "Only administrators can delete bitstream formats");
605         }
606
607         // Find "unknown" type
608
BitstreamFormat unknown = findUnknown(bfContext);
609
610         if (unknown.getID() == getID())
611          throw new IllegalArgumentException JavaDoc("The Unknown bitstream format may not be deleted.");
612
613         // Remove from cache
614
bfContext.removeCached(this, getID());
615
616         // Set bitstreams with this format to "unknown"
617
int numberChanged = DatabaseManager.updateQuery(bfContext,
618                 "UPDATE bitstream SET bitstream_format_id= ? " +
619                 " WHERE bitstream_format_id= ? ",
620                 unknown.getID(),getID());
621
622         // Delete extensions
623
DatabaseManager.updateQuery(bfContext,
624                 "DELETE FROM fileextension WHERE bitstream_format_id= ? ",
625                 getID());
626
627         // Delete this format from database
628
DatabaseManager.delete(bfContext, bfRow);
629
630         log.info(LogManager.getHeader(bfContext, "delete_bitstream_format",
631                 "bitstream_format_id=" + getID() + ",bitstreams_changed="
632                         + numberChanged));
633     }
634
635     /**
636      * Get the filename extensions associated with this format
637      *
638      * @return the extensions
639      */

640     public String JavaDoc[] getExtensions()
641     {
642         String JavaDoc[] exts = new String JavaDoc[extensions.size()];
643         exts = (String JavaDoc[]) extensions.toArray(exts);
644
645         return exts;
646     }
647
648     /**
649      * Set the filename extensions associated with this format
650      *
651      * @param exts
652      * String [] array of extensions
653      */

654     public void setExtensions(String JavaDoc[] exts)
655     {
656         extensions = new ArrayList JavaDoc();
657
658         for (int i = 0; i < exts.length; i++)
659         {
660             extensions.add(exts[i]);
661         }
662     }
663 }
664
Popular Tags