KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > mmbase > module > core > MMTable


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

10 package org.mmbase.module.core;
11
12 import java.util.*;
13
14 import org.mmbase.core.*;
15 import org.mmbase.core.util.StorageConnector;
16 import org.mmbase.module.corebuilders.*;
17 import org.mmbase.storage.*;
18 import org.mmbase.storage.search.*;
19 import org.mmbase.storage.search.implementation.*;
20 import org.mmbase.util.functions.FunctionProvider;
21 import org.mmbase.util.logging.Logger;
22 import org.mmbase.util.logging.Logging;
23
24 /**
25  * MMTable is the base abstraction of a cloud of objects stored in one database table,
26  * essentially a cloud of objects of the same type.
27  * It provides a starting point for MMObjectBuilder by defining a scope - the database table -
28  * and basic functionality to create the table and query properties such as its size.
29  * This class does not contain actual management of nodes (this is left to MMOBjectBuilder).
30  *
31  * @author Daniel Ockeloen
32  * @author Pierre van Rooden (javadoc)
33  * @version $Id: MMTable.java,v 1.23 2006/06/16 09:08:42 michiel Exp $
34  */

35 public abstract class MMTable extends FunctionProvider {
36
37     private static final Logger log = Logging.getLoggerInstance(MMTable.class);
38
39     /**
40      * The MMBase module that this table belongs to
41      */

42     protected MMBase mmb;
43
44     /**
45      * The table name
46      */

47     protected String JavaDoc tableName;
48
49     /**
50      * Maximum number of nodes to return on a query (-1 means no limit, and is also the default)
51      */

52     protected int maxNodesFromQuery = -1;
53
54     // indices for the storage layer
55
private Map indices = new HashMap();
56
57     // link to the storage layer
58
protected StorageConnector storageConnector;
59
60     /**
61      * Empty constructor.
62      */

63     public MMTable() {
64     }
65
66     /**
67      * Set the MMBase object, and retrieve the storage layer.
68      * @param m the MMBase object to set as owner of this builder
69      */

70     public void setMMBase(MMBase m) {
71         mmb = m;
72     }
73
74     /**
75      * Return the MMBase object
76      * @since 1.7
77      */

78     public MMBase getMMBase() {
79         return mmb;
80     }
81
82     /**
83      * Set tablename of the builder. Should be used to initialize a MMTable object before calling init().
84      * @param tableName the name of the table
85      */

86     public void setTableName(String JavaDoc tableName) {
87         this.tableName=tableName;
88     }
89
90     /**
91      * Retrieve the table name (without the clouds' base name)
92      * @return a <code>String</code> containing the table name
93      * @since MMBase-1.7
94      */

95     public String JavaDoc getTableName() {
96         return tableName;
97     }
98
99     /**
100      * Retrieve the full table name (including the clouds' base name)
101      * @return a <code>String</code> containing the full table name
102      * @since MMBase-1.7
103      */

104     public String JavaDoc getFullTableName() {
105         return mmb.baseName + "_" + tableName;
106     }
107
108     /**
109      * Determine the number of objects in this table.
110      * @return The number of entries in the table.
111      */

112     public int size() {
113         return storageConnector.size();
114     }
115
116     /**
117      * Check whether the table is accessible.
118      * In general, this means the table does not exist. Please note that this routine may
119      * also return false if the table is inaccessible due to insufficient rights.
120      * @return <code>true</code> if the table is accessible, <code>false</code> otherwise.
121      */

122     public boolean created() {
123         return storageConnector.created();
124     }
125
126     public StorageConnector getStorageConnector() {
127         return storageConnector;
128     }
129
130 /*
131     public Map getIndices() {
132         return storageConnector.getIndices();
133     }
134
135     public void addIndex(Index index) {
136         storageConnector.addIndex(index);
137     }
138
139     public void addIndices(List indexList) {
140         storageConnector.addIndices(indexList);
141     }
142
143     public Index getIndex(String key) {
144         return storageConnector.getIndex(key);
145     }
146
147     public Index createIndex(String key) {
148         return storageConnector.createIndex(key);
149     }
150
151     public void addToIndex(String key, Field field) {
152         createIndex(key).add(field);
153     }
154
155     public void removeFromIndex(String key, Field field) {
156         storageConnector.removeFromIndex(key, field);
157     }
158
159     public boolean isInIndex(String key, Field field) {
160         storageConnector.isInIndex(key, field);
161     }
162 */

163
164     // retrieve nodes
165
/**
166      * Retrieves a node based on it's number (a unique key).
167      * @todo when something goes wrong, the method currently catches the exception and returns null.
168      * It should actually throw a NotFoundException instead.
169      * @param number The number of the node to search for
170      * @param useCache If true, the node is retrieved from the node cache if possible.
171      * @return <code>null</code> if the node does not exist, the key is invalid,or a
172      * <code>MMObjectNode</code> containing the contents of the requested node.
173      */

174     public MMObjectNode getNode(final int number, boolean useCache) {
175         try {
176             return storageConnector.getNode(number, useCache);
177         } catch(IllegalArgumentException JavaDoc iae) {
178             log.warn(iae.getMessage());
179             if (log.isDebugEnabled()) {
180                 log.debug(iae);
181             }
182             return null;
183         } catch(StorageNotFoundException se) {
184             return null;
185         } catch(StorageException se) {
186             log.error(se.getMessage(), se);
187             return null;
188         }
189     }
190
191     /**
192      * Retrieves an object's type. If necessary, the type is added to the cache.
193      * @todo when something goes wrong, the method currently catches the exception and returns -1.
194      * It should actually throw a NotFoundException instead.
195      * @param number The number of the node to search for
196      * @return an <code>int</code> value which is the object type (otype) of the node.
197      */

198     public int getNodeType(int number) {
199         try {
200             return storageConnector.getNodeType(number);
201         } catch(StorageException se) {
202             log.error(Logging.stackTrace(se));
203             return -1;
204         }
205     }
206
207     // Search and query methods on a table
208

209     /**
210      * Convert virtual nodes to real nodes based on their otype
211      *
212      * Normally a multirelations-search will return virtual nodes. These nodes
213      * will only contain values which where specified in the field-vector.
214      * This method will make real nodes of those virtual nodes.
215      *
216      * @param virtuals containing virtual nodes
217      * @return List containing real nodes, directly from this Builders
218      * @since MMBase-1.6.2
219      */

220     protected List getNodes(Collection virtuals) {
221         List result = new ArrayList();
222         try {
223             result = storageConnector.getNodes(virtuals);
224         } catch (SearchQueryException sqe) {
225             log.error(sqe.getMessage() + Logging.stackTrace(sqe));
226         }
227         return result;
228     }
229
230     /**
231      * Counts number of nodes matching a specified constraint.
232      *
233      * @param where The constraint, can be a SQL where-clause, a MMNODE
234      * expression or an altavista-formatted expression.
235      * @return The number of nodes, or -1 when failing to retrieve the data.
236      * @deprecated Use {@link #count(NodeSearchQuery) count(NodeSearchQuery)}
237      * instead.
238      */

239     public int count(String JavaDoc where) {
240         // In order to support this method:
241
// - Exceptions of type SearchQueryExceptions are caught.
242
int result = -1;
243         NodeSearchQuery query = storageConnector.getSearchQuery(where);
244         try {
245             result = count(query);
246         } catch (SearchQueryException e) {
247             log.error(e);
248         }
249         return result;
250     }
251
252     /**
253      * Counts number of nodes matching a specified constraint.
254      * The constraint is specified by a query that selects nodes of
255      * a specified type, which must be the nodetype corresponding
256      * to this builder.
257      *
258      * @param query The query.
259      * @return The number of nodes.
260      * @throws IllegalArgumentException when an invalid argument is supplied.
261      * @throws SearchQueryException when failing to retrieve the data.
262      * @since MMBase-1.7
263      */

264     public int count(NodeSearchQuery query) throws SearchQueryException {
265         return storageConnector.count(query);
266     }
267
268     /**
269      * Returns nodes matching a specified constraint.
270      * The constraint is specified by a query that selects nodes of
271      * a specified type, which must be the nodetype corresponding
272      * to this builder.
273      *
274      * @param query The query.
275      * @return The nodes.
276      * @throws IllegalArgumentException When the nodetype specified
277      * by the query is not the nodetype corresponding to this builder.
278      * @since MMBase-1.7
279      */

280     public List getNodes(NodeSearchQuery query) throws SearchQueryException {
281         return storageConnector.getNodes(query);
282     }
283
284     // most of those below are deprecated
285

286     /**
287      * Build a set command string from a set nodes
288      * @param nodes Vector containg the nodes to put in the set
289      * @param fieldName fieldname whose values should be put in the set
290      * @return a comma-seperated list of values, as a <code>String</code>
291      * @deprecated should be moved?
292      */

293     /*
294     public String buildSet(Vector nodes, String fieldName) {
295         StringBuffer result = new StringBuffer("(");
296         Enumeration enumeration = nodes.elements();
297         MMObjectNode node;
298
299         while (enumeration.hasMoreElements()) {
300             node = (MMObjectNode)enumeration.nextElement();
301
302             if(enumeration.hasMoreElements()) {
303                 result.append(node.getValue(fieldName)).append(", ");
304             } else {
305                 result.append(node.getValue(fieldName));
306             }
307
308         }
309         result.append(')');
310         return result.toString();
311     }
312     */

313
314     /**
315      * Enumerate all the objects that match the searchkeys
316      * @param where scan expression that the objects need to fulfill
317      * @return an <code>Enumeration</code> containing all the objects that apply.
318      * @deprecated Use {@link #getNodes(NodeSearchQuery)
319      * getNodes(NodeSearchQuery} to perform a node search.
320      */

321     public Enumeration search(String JavaDoc where) {
322         return searchVector(where).elements();
323     }
324
325     /**
326      * Enumerate all the objects that match the searchkeys
327      * @param where where clause that the objects need to fulfill
328      * @param sort order in which to return the objects
329      * @return an <code>Enumeration</code> containing all the objects that apply.
330      * @deprecated Use {@link #getNodes(NodeSearchQuery)
331      * getNodes(NodeSearchQuery} to perform a node search.
332      */

333     /*
334     public Enumeration search(String where, String sort) {
335         return searchVector(where, sort).elements();
336     }
337     */

338
339     /**
340      * Enumerate all the objects that match the searchkeys
341      * @param where where clause that the objects need to fulfill
342      * @param sort order in which to return the objects
343      * @param direction sorts ascending if <code>true</code>, descending if <code>false</code>.
344      * Only applies if a sorted order is given.
345      * @return an <code>Enumeration</code> containing all the objects that apply.
346      * @deprecated Use {@link #getNodes(NodeSearchQuery)
347      * getNodes(NodeSearchQuery} to perform a node search.
348      */

349     /*
350     public Enumeration search(String where, String sort, boolean direction) {
351         return searchVector(where, sort, direction).elements();
352     }
353     */

354
355     /**
356      * Returns a vector containing all the objects that match the searchkeys
357      * @param where scan expression that the objects need to fulfill
358      * @return a vector containing all the objects that apply.
359      * @deprecated Use {@link #getNodes(NodeSearchQuery)
360      * getNodes(NodeSearchQuery} to perform a node search.
361      */

362     public Vector searchVector(String JavaDoc where) {
363         // In order to support this method:
364
// - Exceptions of type SearchQueryExceptions are caught.
365
// - The result is converted to a vector.
366
Vector result = new Vector();
367         NodeSearchQuery query = storageConnector.getSearchQuery(where);
368         try {
369             List nodes = getNodes(query);
370             result.addAll(nodes);
371         } catch (SearchQueryException e) {
372             log.error(e);
373         }
374         return result;
375     }
376
377     /**
378      * Returns all the nodes from the builder.
379      * @return The nodes.
380      */

381     public List getNodes() {
382         try {
383             List nodes = storageConnector.getNodes();
384             if (nodes != null) {
385                 return nodes;
386             }
387         } catch (SearchQueryException e) {
388             log.error(e);
389         }
390         return new ArrayList();
391     }
392
393     /**
394      * Returns a vector containing all the objects that match the searchkeys
395      * @param where where clause that the objects need to fulfill
396      * @param sorted a comma separated list of field names on wich the
397      * returned list should be sorted
398      * @return a vector containing all the objects that apply.
399      * @deprecated Use {@link #getNodes(NodeSearchQuery)
400      * getNodes(NodeSearchQuery} to perform a node search.
401      */

402     /*
403     public Vector searchVector(String where, String sorted) {
404         return searchVector(where, sorted, true);
405     }
406     */

407
408     /**
409      * Returns a vector containing all the objects that match the searchkeys
410      * @param where where clause that the objects need to fulfill
411      * @param sorted order in which to return the objects
412      * @param direction sorts ascending if <code>true</code>, descending if <code>false</code>.
413      * Only applies if a sorted order is given.
414      * @return a vector containing all the objects that apply.
415      * @deprecated Use {@link #getNodes(NodeSearchQuery)
416      * getNodes(NodeSearchQuery} to perform a node search.
417      */

418     /*
419     public Vector searchVector(String where, String sorted, boolean direction) {
420         String directions = (direction? "UP": "DOWN");
421         return searchVector(where, sorted, directions);
422     }
423     */

424
425     /**
426      * Returns a vector containing all the objects that match the searchkeys in
427      * a given order.
428      *
429      * @param where where clause that the objects need to fulfill
430      * @param sorted a comma separated list of field names on wich the
431      * returned list should be sorted
432      * @param directions A comma separated list of the values indicating wether
433      * to sort up (ascending) or down (descending) on the
434      * corresponding field in the <code>sorted</code>
435      * parameter or <code>null</code> if sorting on all
436      * fields should be up.
437      * The value DOWN (case insensitive) indicates
438      * that sorting on the corresponding field should be
439      * down, all other values (including the
440      * empty value) indicate that sorting on the
441      * corresponding field should be up.
442      * If the number of values found in this parameter are
443      * less than the number of fields in the
444      * <code>sorted</code> parameter, all fields that
445      * don't have a corresponding direction value are
446      * sorted according to the last specified direction
447      * value.
448      * @return a vector containing all the objects that apply in the
449      * requested order
450      * @deprecated Use {@link #getNodes(NodeSearchQuery)
451      * getNodes(NodeSearchQuery} to perform a node search.
452      */

453     /*
454     public Vector searchVector(String where, String sorted, String directions) {
455         // In order to support this method:
456         // - Exceptions of type SearchQueryExceptions are caught.
457         // - The result is converted to a vector.
458         Vector result = new Vector();
459         NodeSearchQuery query = getSearchQuery(where, sorted, directions);
460         try {
461             List nodes = getNodes(query);
462             result.addAll(nodes);
463         } catch (SearchQueryException e) {
464             log.error(e);
465         }
466         return result;
467     }
468     */

469
470     /**
471      * As searchVector. Differences are:
472      * - Throws exception on SQL errors
473      * @since MMBase-1.6
474      * @deprecated Use {@link #getNodes(NodeSearchQuery)
475      * getNodes(NodeSearchQuery} to perform a node search.
476      */

477     /*
478     public List searchList(String where) {
479         // In order to support this method:
480         // - Exceptions of type SearchQueryExceptions are wrapped
481         // inside an RuntimeException.
482         NodeSearchQuery query = getSearchQuery(where);
483         try {
484             return getNodes(query);
485         } catch (SearchQueryException e) {
486             throw new RuntimeException(e);
487         }
488     }
489     */

490
491     /**
492      * As searchVector
493      * But
494      * - throws Exception on error
495      * - returns List
496      *
497      * @param where Constraint, represented by scan MMNODE expression,
498      * AltaVista format or SQL "where"-clause.
499      * @param sorted Comma-separated list of names of fields to sort on.
500      * @param directions Comma-separated list of sorting directions ("UP"
501      * or "DOWN") of the fields to sort on.
502      * @since MMBase-1.6
503      * @deprecated Use {@link #getNodes(NodeSearchQuery)
504      * getNodes(NodeSearchQuery} to perform a node search.
505      */

506     /*
507     public List searchList(String where, String sorted, String directions) {
508         // In order to support this method:
509         // - Exceptions of type SearchQueryExceptions are wrapped
510         // inside an RuntimeException.
511         NodeSearchQuery query = getSearchQuery(where, sorted, directions);
512         try {
513             return getNodes(query);
514         } catch (SearchQueryException e) {
515             if (log.isDebugEnabled()) {
516                 log.debug(e + Logging.stackTrace(e));
517             }
518             throw new RuntimeException(e);
519         }
520     }
521     */

522
523     /**
524      * Creates search query that retrieves nodes matching a specified
525      * constraint.
526      *
527      * @param where The constraint, can be a SQL where-clause, a MMNODE
528      * expression, an altavista-formatted expression, empty or
529      * <code>null</code>.
530      * @return The query.
531      * @since MMBase-1.7
532      */

533     /*
534     NodeSearchQuery getSearchQuery(String where) {
535         NodeSearchQuery query;
536
537         if (where != null && where.startsWith("MMNODE ")) {
538             // MMNODE expression.
539             query = storageConnector.convertMMNodeSearch2Query(where);
540         } else {
541             query = new NodeSearchQuery((MMObjectBuilder)this);
542             QueryConvertor.setConstraint(query, where);
543         }
544
545         return query;
546     }
547     */

548
549     /**
550      * Creates search query that retrieves a sorted list of nodes,
551      * matching a specified constraint.
552      *
553      * @param where The constraint, can be a SQL where-clause, a MMNODE
554      * expression or an altavista-formatted expression.
555      * @param sorted Comma-separated list of names of fields to sort on.
556      * @param directions Comma-separated list of sorting directions ("UP"
557      * or "DOWN") of the fields to sort on.
558      * If the number of sorting directions is less than the number of
559      * fields to sort on, the last specified direction is applied to
560      * the remaining fields.
561      * @since MMBase-1.7
562      */

563     /*
564     NodeSearchQuery getSearchQuery(String where, String sorted, String directions) {
565         NodeSearchQuery query = getSearchQuery(where);
566         if (directions == null) {
567             directions = "";
568         }
569         StringTokenizer sortedTokenizer = new StringTokenizer(sorted, ",");
570         StringTokenizer directionsTokenizer = new StringTokenizer(directions, ",");
571
572         String direction = "UP";
573         while (sortedTokenizer.hasMoreElements()) {
574             String fieldName = sortedTokenizer.nextToken().trim();
575             CoreField coreField = getField(fieldName);
576             if (coreField == null) {
577                 throw new IllegalArgumentException(
578                 "Not a known field of builder " + getTableName()
579                 + ": '" + fieldName + "'");
580             }
581             StepField field = query.getField(coreField);
582             BasicSortOrder sortOrder = query.addSortOrder(field);
583             if (directionsTokenizer.hasMoreElements()) {
584                 direction = directionsTokenizer.nextToken().trim();
585             }
586             if (direction.equalsIgnoreCase("DOWN")) {
587                 sortOrder.setDirection(SortOrder.ORDER_DESCENDING);
588             } else {
589                 sortOrder.setDirection(SortOrder.ORDER_ASCENDING);
590             }
591         }
592         return query;
593     }
594     */

595
596     /**
597      * Adds nodenumbers to be included to query retrieving nodes.
598      *
599      * @param query The query.
600      * @param nodeNumbers Comma-separated list of nodenumbers.
601      * @since MMBase-1.7
602      */

603     /*
604     void addNodesToQuery(NodeSearchQuery query, String nodeNumbers) {
605         BasicStep step = (BasicStep) query.getSteps().get(0);
606         StringTokenizer st = new StringTokenizer(nodeNumbers, ",");
607         while (st.hasMoreTokens()) {
608             String str = st.nextToken().trim();
609             int nodeNumber = Integer.parseInt(str);
610             step.addNode(nodeNumber);
611         }
612     }
613     */

614
615 }
616
Popular Tags