KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > alfresco > repo > webservice > Utils


1 /*
2  * Copyright (C) 2005 Alfresco, Inc.
3  *
4  * Licensed under the Mozilla Public License version 1.1
5  * with a permitted attribution clause. You may obtain a
6  * copy of the License at
7  *
8  * http://www.alfresco.org/legal/license.txt
9  *
10  * Unless required by applicable law or agreed to in writing,
11  * software distributed under the License is distributed on an
12  * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
13  * either express or implied. See the License for the specific
14  * language governing permissions and limitations under the
15  * License.
16  */

17 package org.alfresco.repo.webservice;
18
19 import java.io.Serializable JavaDoc;
20 import java.util.ArrayList JavaDoc;
21 import java.util.Calendar JavaDoc;
22 import java.util.Date JavaDoc;
23 import java.util.List JavaDoc;
24 import java.util.Map JavaDoc;
25
26 import javax.servlet.ServletContext JavaDoc;
27 import javax.servlet.http.HttpServletRequest JavaDoc;
28 import javax.transaction.UserTransaction JavaDoc;
29
30 import org.alfresco.repo.webservice.axis.QueryConfigHandler;
31 import org.alfresco.repo.webservice.types.AssociationDefinition;
32 import org.alfresco.repo.webservice.types.Cardinality;
33 import org.alfresco.repo.webservice.types.ClassDefinition;
34 import org.alfresco.repo.webservice.types.NamedValue;
35 import org.alfresco.repo.webservice.types.ParentReference;
36 import org.alfresco.repo.webservice.types.Predicate;
37 import org.alfresco.repo.webservice.types.PropertyDefinition;
38 import org.alfresco.repo.webservice.types.Query;
39 import org.alfresco.repo.webservice.types.QueryLanguageEnum;
40 import org.alfresco.repo.webservice.types.Reference;
41 import org.alfresco.repo.webservice.types.RoleDefinition;
42 import org.alfresco.repo.webservice.types.Store;
43 import org.alfresco.repo.webservice.types.StoreEnum;
44 import org.alfresco.repo.webservice.types.Version;
45 import org.alfresco.service.ServiceRegistry;
46 import org.alfresco.service.cmr.repository.NodeRef;
47 import org.alfresco.service.cmr.repository.NodeService;
48 import org.alfresco.service.cmr.repository.StoreRef;
49 import org.alfresco.service.cmr.repository.datatype.DefaultTypeConverter;
50 import org.alfresco.service.cmr.search.ResultSet;
51 import org.alfresco.service.cmr.search.SearchService;
52 import org.alfresco.service.cmr.version.VersionType;
53 import org.alfresco.service.namespace.NamespaceService;
54 import org.alfresco.service.namespace.QName;
55 import org.alfresco.service.transaction.TransactionService;
56 import org.apache.axis.MessageContext;
57 import org.apache.axis.transport.http.HTTPConstants;
58 import org.apache.commons.logging.Log;
59 import org.apache.commons.logging.LogFactory;
60 import org.springframework.web.context.WebApplicationContext;
61 import org.springframework.web.context.support.WebApplicationContextUtils;
62
63 /**
64  * Helper class used by the web services
65  *
66  * @author gavinc
67  */

68 public class Utils
69 {
70     public static final String JavaDoc REPOSITORY_SERVICE_NAMESPACE = "http://www.alfresco.org/ws/service/repository/1.0";
71     
72     /** Get the logger for this class */
73     private static Log logger = LogFactory.getLog(Utils.class);
74
75     private Utils()
76     {
77         // don't allow construction
78
}
79
80     /**
81      * Converts the web service Store type to a StoreRef used by the repository
82      *
83      * @param store
84      * The Store to convert
85      * @return The converted StoreRef
86      */

87     public static StoreRef convertToStoreRef(Store store)
88     {
89         return new StoreRef(store.getScheme().getValue(), store.getAddress());
90     }
91
92     /**
93      * Converts a store reference ot a Store type
94      *
95      * @param ref
96      * the store reference
97      * @return the store
98      */

99     public static Store convertToStore(StoreRef ref)
100     {
101         return new Store(StoreEnum.fromValue(ref.getProtocol()), ref
102                 .getIdentifier());
103     }
104
105     /**
106      * Converts the given Reference web service type into a repository NodeRef
107      *
108      * @param ref
109      * The Reference to convert
110      * @return The NodeRef representation of the Reference
111      */

112     public static NodeRef convertToNodeRef(Reference ref,
113             NodeService nodeService, SearchService searchService,
114             NamespaceService namespaceService)
115     {
116         return resolveToNodeRef(ref.getStore(), ref.getUuid(), ref.getPath(),
117                 nodeService, searchService, namespaceService);
118     }
119
120     /**
121      * Converts the given ParentReference web service type into a repository
122      * NodeRef
123      *
124      * @param parentRef
125      * The ParentReference to convert
126      * @return The NodeRef representation of the ParentReference
127      */

128     public static NodeRef convertToNodeRef(ParentReference parentRef,
129             NodeService nodeService, SearchService searchService,
130             NamespaceService namespaceService)
131     {
132         // TODO: Also take into account any association information passed in
133
// the ParentReference
134

135         return resolveToNodeRef(parentRef.getStore(), parentRef.getUuid(),
136                 parentRef.getPath(), nodeService, searchService,
137                 namespaceService);
138     }
139
140     /**
141      * Converts the given repository NodeRef object into a web service Reference
142      * type
143      *
144      * @param node
145      * The node to create a Reference for
146      * @return The Reference
147      */

148     public static Reference convertToReference(NodeRef node)
149     {
150         Reference ref = new Reference();
151         Store store = new Store(StoreEnum.fromValue(node.getStoreRef()
152                 .getProtocol()), node.getStoreRef().getIdentifier());
153         ref.setStore(store);
154         ref.setUuid(node.getId());
155         return ref;
156     }
157
158     /**
159      * Resolves the given parameters to a repository NodeRef
160      *
161      * @param store
162      * The Store to search within
163      * @param uuid
164      * The id of the node, or the id of the starting node if a path
165      * is also present
166      * @param path
167      * The path to the required node, if a uuid is given the search
168      * starts from that node otherwise the search will start from the
169      * root node
170      * @param nodeService
171      * NodeService to use
172      * @param searchService
173      * SearchService to use
174      * @param namespaceService
175      * NamespaceService to use
176      * @return A repository NodeRef
177      */

178     public static NodeRef resolveToNodeRef(Store store, String JavaDoc uuid,
179             String JavaDoc path, NodeService nodeService, SearchService searchService,
180             NamespaceService namespaceService)
181     {
182         if (store == null)
183         {
184             throw new IllegalArgumentException JavaDoc(
185                     "A Store must be supplied to resolve to a NodeRef");
186         }
187
188         NodeRef nodeRef = null;
189
190         // find out where we are starting from, either the root or the node
191
// represented by the uuid
192
NodeRef rootNodeRef = null;
193         if (uuid == null || uuid.length() == 0)
194         {
195             rootNodeRef = nodeService.getRootNode(convertToStoreRef(store));
196         }
197         else
198         {
199             rootNodeRef = new NodeRef(convertToStoreRef(store), uuid);
200         }
201
202         // see if we have a path to further define the node being requested
203
if (path != null && path.length() != 0)
204         {
205             if (logger.isDebugEnabled() == true)
206             {
207                 logger.debug("Resolving path: " + path);
208             }
209             
210             List JavaDoc<NodeRef> nodes = searchService.selectNodes(rootNodeRef, path,
211                     null, namespaceService, false);
212
213             // make sure we only have one result
214
if (nodes.size() != 1)
215             {
216                 StringBuilder JavaDoc builder = new StringBuilder JavaDoc(
217                         "Failed to resolve to a single NodeRef with parameters (store=");
218                 builder.append(store.getScheme().getValue()).append(":")
219                         .append(store.getAddress());
220                 builder.append(" uuid=").append(uuid);
221                 builder.append(" path=").append(path).append("), found ");
222                 builder.append(nodes.size()).append(" nodes.");
223                 throw new IllegalStateException JavaDoc(builder.toString());
224             }
225
226             nodeRef = nodes.get(0);
227         }
228         else
229         {
230             if (logger.isDebugEnabled() == true)
231             {
232                 logger.debug("There was no path to resolve so using root or specified node");
233             }
234             
235             // if there is no path just use whatever the rootNodeRef currently
236
// is
237
nodeRef = rootNodeRef;
238         }
239
240         return nodeRef;
241     }
242
243     /**
244      * Resolves the given predicate into a list of NodeRefs that can be acted
245      * upon
246      *
247      * @param predicate
248      * The predicate passed from the client
249      * @param nodeService
250      * NodeService to use
251      * @param searchService
252      * SearchService to use
253      * @param namespaceService
254      * NamespaceService to use
255      * @return A List of NodeRef objects
256      */

257     public static List JavaDoc<NodeRef> resolvePredicate(Predicate predicate,
258             NodeService nodeService, SearchService searchService,
259             NamespaceService namespaceService)
260     {
261         List JavaDoc<NodeRef> nodeRefs = null;
262
263         if (predicate.getNodes() != null)
264         {
265             Reference[] nodes = predicate.getNodes();
266             nodeRefs = new ArrayList JavaDoc<NodeRef>(nodes.length);
267
268             for (int x = 0; x < nodes.length; x++)
269             {
270                 nodeRefs.add(convertToNodeRef(nodes[x], nodeService,
271                         searchService, namespaceService));
272             }
273         }
274         else if (predicate.getQuery() != null)
275         {
276             // make sure a query is present
277
Query query = predicate.getQuery();
278
279             if (query == null)
280             {
281                 throw new IllegalStateException JavaDoc(
282                         "Either a set of nodes or a query must be supplied in a Predicate.");
283             }
284
285             // make sure a Store has been supplied too
286
if (predicate.getStore() == null)
287             {
288                 throw new IllegalStateException JavaDoc(
289                         "A Store has to be supplied to in order to execute a query.");
290             }
291
292             QueryLanguageEnum langEnum = query.getLanguage();
293
294             if (langEnum.equals(QueryLanguageEnum.cql)
295                     || langEnum.equals(QueryLanguageEnum.xpath))
296             {
297                 throw new IllegalArgumentException JavaDoc("Only '"
298                         + QueryLanguageEnum.lucene.getValue()
299                         + "' queries are currently supported!");
300             }
301
302             // execute the query
303
ResultSet searchResults = null;
304             try
305             {
306                 searchResults = searchService.query(Utils
307                     .convertToStoreRef(predicate.getStore()), langEnum
308                     .getValue(), query.getStatement());
309                 // get hold of all the NodeRef's from the results
310
nodeRefs = searchResults.getNodeRefs();
311             }
312             finally
313             {
314                 if (searchResults != null)
315                 {
316                     searchResults.close();
317                 }
318             }
319         }
320         else if (predicate.getStore() != null)
321         {
322             // Since only the store was supplied interpret this to mean the predicate should be resolved to the
323
// stores root node
324
Store store = predicate.getStore();
325             NodeRef rootNode = nodeService.getRootNode(Utils.convertToStoreRef(store));
326             
327             nodeRefs = new ArrayList JavaDoc<NodeRef>();
328             nodeRefs.add(rootNode);
329         }
330
331         return nodeRefs;
332     }
333
334     /**
335      * Returns the current Spring WebApplicationContext object
336      *
337      * @param msgContext
338      * SOAP message context
339      * @return The Spring WebApplicationContext
340      */

341     public static WebApplicationContext getSpringContext(
342             MessageContext msgContext)
343     {
344         // get hold of the web application context via the message context
345
HttpServletRequest JavaDoc req = (HttpServletRequest JavaDoc) msgContext
346                 .getProperty(HTTPConstants.MC_HTTP_SERVLETREQUEST);
347         ServletContext JavaDoc servletCtx = req.getSession().getServletContext();
348         return WebApplicationContextUtils
349                 .getRequiredWebApplicationContext(servletCtx);
350     }
351
352     /**
353      * Returns a UserTransaction that can be used within a service call
354      *
355      * @param msgContext
356      * SOAP message context
357      * @return a UserTransaction
358      */

359     public static UserTransaction JavaDoc getUserTransaction(MessageContext msgContext)
360     {
361         // get the service regsistry
362
ServiceRegistry svcReg = (ServiceRegistry) getSpringContext(msgContext)
363                 .getBean(ServiceRegistry.SERVICE_REGISTRY);
364
365         TransactionService transactionService = svcReg.getTransactionService();
366         return transactionService.getUserTransaction();
367     }
368
369     /**
370      * Returns the value of the <code>fetchSize</code> from the
371      * QueryConfiguration SOAP header (if present)
372      *
373      * @param msgContext
374      * The SOAP MessageContext
375      * @return The current batch size or -1 if the header is not present
376      */

377     public static int getBatchSize(MessageContext msgContext)
378     {
379         int batchSize = -1;
380
381         Integer JavaDoc batchConfigSize = (Integer JavaDoc) MessageContext.getCurrentContext()
382                 .getProperty(QueryConfigHandler.ALF_FETCH_SIZE);
383         if (batchConfigSize != null)
384         {
385             batchSize = batchConfigSize.intValue();
386         }
387
388         return batchSize;
389     }
390
391     /**
392      * Converts a repository version object into a web service version object.
393      *
394      * @param version
395      * the repository version object
396      * @return the web service version object
397      */

398     public static Version convertToVersion(
399             org.alfresco.service.cmr.version.Version version)
400     {
401         Version webServiceVersion = new Version();
402
403         // Set the basic properties
404
webServiceVersion.setId(Utils.convertToReference(version
405                 .getFrozenStateNodeRef()));
406         webServiceVersion.setCreator(version.getCreator());
407         webServiceVersion.setLabel(version.getVersionLabel());
408
409         // Set the created date
410
Date JavaDoc createdDate = version.getCreatedDate();
411         Calendar JavaDoc calendar = Calendar.getInstance();
412         calendar.setTime(createdDate);
413         webServiceVersion.setCreated(calendar);
414
415         // Set the falg to indicate whether the version was mojor or minor
416
boolean isMajor = false;
417         VersionType versionType = version.getVersionType();
418         if (versionType != null
419                 && versionType.equals(VersionType.MAJOR) == true)
420         {
421             isMajor = true;
422         }
423         webServiceVersion.setMajor(isMajor);
424
425         // Set the commetary values
426
Map JavaDoc<String JavaDoc, Serializable JavaDoc> versionProps = version.getVersionProperties();
427         NamedValue[] namedValues = new NamedValue[versionProps.size()];
428         int iIndex = 0;
429         for (Map.Entry JavaDoc<String JavaDoc, Serializable JavaDoc> entry : versionProps.entrySet())
430         {
431             String JavaDoc value = null;
432             try
433             {
434                 value = DefaultTypeConverter.INSTANCE.convert(String JavaDoc.class, entry.getValue());
435             }
436             catch (Throwable JavaDoc exception)
437             {
438                 value = entry.getValue().toString();
439             }
440             namedValues[iIndex] = new NamedValue(entry.getKey(), value);
441             iIndex++;
442         }
443         webServiceVersion.setCommentaries(namedValues);
444
445         return webServiceVersion;
446     }
447     
448     /**
449      * Creates a ClassDefinition web service type object for the given
450      * repository ClassDefinition
451      *
452      * @param ddClassDef The repository ClassDefinition to generate
453      * @return The web service ClassDefinition representation
454      */

455     public static ClassDefinition setupClassDefObject(org.alfresco.service.cmr.dictionary.ClassDefinition ddClassDef)
456     {
457        ClassDefinition classDef = new ClassDefinition();
458        classDef.setName(ddClassDef.getName().toString());
459        classDef.setIsAspect(ddClassDef.isAspect());
460        
461        if (ddClassDef.getTitle() != null)
462        {
463           classDef.setTitle(ddClassDef.getTitle());
464        }
465        if (ddClassDef.getDescription() != null)
466        {
467           classDef.setDescription(ddClassDef.getDescription());
468        }
469        if (ddClassDef.getParentName() != null)
470        {
471           classDef.setSuperClass(ddClassDef.getParentName().toString());
472        }
473        
474        // represent the properties
475
Map JavaDoc<QName, org.alfresco.service.cmr.dictionary.PropertyDefinition> props = ddClassDef.getProperties();
476        if (props != null)
477        {
478           PropertyDefinition[] propDefs = new PropertyDefinition[props.size()];
479           int pos = 0;
480           for (org.alfresco.service.cmr.dictionary.PropertyDefinition ddPropDef : props.values())
481           {
482              PropertyDefinition propDef = new PropertyDefinition();
483              propDef.setName(ddPropDef.getName().toString());
484              propDef.setDataType(ddPropDef.getDataType().getName().toString());
485              propDef.setMandatory(ddPropDef.isMandatory());
486              propDef.setReadOnly(ddPropDef.isProtected());
487              if (ddPropDef.getDefaultValue() != null)
488              {
489                 propDef.setDefaultValue(ddPropDef.getDefaultValue());
490              }
491              if (ddPropDef.getTitle() != null)
492              {
493                 propDef.setTitle(ddPropDef.getTitle());
494              }
495              if (ddPropDef.getDescription() != null)
496              {
497                 propDef.setDescription(ddPropDef.getDescription());
498              }
499              
500              // add it to the array
501
propDefs[pos] = propDef;
502              pos++;
503           }
504           
505           // add properties to the overall ClassDefinition
506
classDef.setProperties(propDefs);
507        }
508        
509        // TODO need to get the child associations as well !!
510

511        // represent the associations
512
Map JavaDoc<QName, org.alfresco.service.cmr.dictionary.AssociationDefinition> assocs = ddClassDef.getAssociations();
513        if (assocs != null)
514        {
515           AssociationDefinition[] assocDefs = new AssociationDefinition[assocs.size()];
516           int pos = 0;
517           for (org.alfresco.service.cmr.dictionary.AssociationDefinition ddAssocDef : assocs.values())
518           {
519              AssociationDefinition assocDef = new AssociationDefinition();
520              assocDef.setName(ddAssocDef.getName().toString());
521              assocDef.setIsChild(ddAssocDef.isChild());
522              if (ddAssocDef.getTitle() != null)
523              {
524                 assocDef.setTitle(ddAssocDef.getTitle());
525              }
526              if (ddAssocDef.getDescription() != null)
527              {
528                 assocDef.setDescription(ddAssocDef.getDescription());
529              }
530              
531              RoleDefinition sourceRole = new RoleDefinition();
532              if (ddAssocDef.getSourceRoleName() != null)
533              {
534                 sourceRole.setName(ddAssocDef.getSourceRoleName().toString());
535              }
536              sourceRole.setCardinality(setupSourceCardinalityObject(ddAssocDef));
537              assocDef.setSourceRole(sourceRole);
538              
539              RoleDefinition targetRole = new RoleDefinition();
540              if (ddAssocDef.getTargetRoleName() != null)
541              {
542                 targetRole.setName(ddAssocDef.getTargetRoleName().toString());
543              }
544              targetRole.setCardinality(setupTargetCardinalityObject(ddAssocDef));;
545              assocDef.setTargetRole(targetRole);
546              assocDef.setTargetClass(ddAssocDef.getTargetClass().getName().toString());
547              
548              assocDefs[pos] = assocDef;
549              pos++;
550           }
551           
552           classDef.setAssociations(assocDefs);
553        }
554        
555        return classDef;
556     }
557     
558     /**
559      * Creates a web service Cardinality type for the source from the given repository AssociationDefinition
560      *
561      * @param ddAssocDef The AssociationDefinition to get the cardinality from
562      * @return The Cardinality
563      */

564     private static Cardinality setupSourceCardinalityObject(org.alfresco.service.cmr.dictionary.AssociationDefinition ddAssocDef)
565     {
566        if (ddAssocDef.isSourceMandatory() == false && ddAssocDef.isSourceMany() == false)
567        {
568           // 0..1
569
return Cardinality.value1;
570        }
571        else if (ddAssocDef.isSourceMandatory() && ddAssocDef.isSourceMany() == false)
572        {
573           // 1
574
return Cardinality.value2;
575        }
576        else if (ddAssocDef.isSourceMandatory() && ddAssocDef.isSourceMany())
577        {
578           // 1..*
579
return Cardinality.value4;
580        }
581        else
582        {
583           // *
584
return Cardinality.value3;
585        }
586     }
587     
588     /**
589      * Creates a web service Cardinality type for the target from the given repository AssociationDefinition
590      *
591      * @param ddAssocDef The AssociationDefinition to get the cardinality from
592      * @return The Cardinality
593      */

594     private static Cardinality setupTargetCardinalityObject(org.alfresco.service.cmr.dictionary.AssociationDefinition ddAssocDef)
595     {
596        if (ddAssocDef.isTargetMandatory() == false && ddAssocDef.isTargetMany() == false)
597        {
598           // 0..1
599
return Cardinality.value1;
600        }
601        else if (ddAssocDef.isTargetMandatory() && ddAssocDef.isTargetMany() == false)
602        {
603           // 1
604
return Cardinality.value2;
605        }
606        else if (ddAssocDef.isTargetMandatory() && ddAssocDef.isTargetMany())
607        {
608           // 1..*
609
return Cardinality.value4;
610        }
611        else
612        {
613           // *
614
return Cardinality.value3;
615        }
616     }
617 }
618
Popular Tags