View Javadoc

1   /*
2    * Copyright 2001-2004 The Apache Software Foundation.
3    * 
4    * Licensed under the Apache License, Version 2.0 (the "License");
5    * you may not use this file except in compliance with the License.
6    * You may obtain a copy of the License at
7    * 
8    *      http://www.apache.org/licenses/LICENSE-2.0
9    * 
10   * Unless required by applicable law or agreed to in writing, software
11   * distributed under the License is distributed on an "AS IS" BASIS,
12   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13   * See the License for the specific language governing permissions and
14   * limitations under the License.
15   */
16  package org.apache.juddi.function;
17  
18  import java.util.Properties;
19  import java.util.Vector;
20  
21  import org.apache.commons.logging.Log;
22  import org.apache.commons.logging.LogFactory;
23  import org.apache.juddi.datastore.DataStore;
24  import org.apache.juddi.datastore.DataStoreFactory;
25  import org.apache.juddi.datatype.CategoryBag;
26  import org.apache.juddi.datatype.DiscoveryURL;
27  import org.apache.juddi.datatype.DiscoveryURLs;
28  import org.apache.juddi.datatype.Email;
29  import org.apache.juddi.datatype.KeyedReference;
30  import org.apache.juddi.datatype.Name;
31  import org.apache.juddi.datatype.RegistryObject;
32  import org.apache.juddi.datatype.business.BusinessEntity;
33  import org.apache.juddi.datatype.business.Contact;
34  import org.apache.juddi.datatype.business.Contacts;
35  import org.apache.juddi.datatype.publisher.Publisher;
36  import org.apache.juddi.datatype.request.AuthInfo;
37  import org.apache.juddi.datatype.request.GetAuthToken;
38  import org.apache.juddi.datatype.request.SaveBusiness;
39  import org.apache.juddi.datatype.response.AuthToken;
40  import org.apache.juddi.datatype.response.BusinessDetail;
41  import org.apache.juddi.datatype.service.BusinessService;
42  import org.apache.juddi.datatype.service.BusinessServices;
43  import org.apache.juddi.datatype.tmodel.TModel;
44  import org.apache.juddi.error.InvalidKeyPassedException;
45  import org.apache.juddi.error.RegistryException;
46  import org.apache.juddi.error.UnsupportedException;
47  import org.apache.juddi.error.UserMismatchException;
48  import org.apache.juddi.handler.BusinessEntityHandler;
49  import org.apache.juddi.registry.RegistryEngine;
50  import org.apache.juddi.util.Config;
51  import org.apache.juddi.uuidgen.UUIDGen;
52  import org.apache.juddi.uuidgen.UUIDGenFactory;
53  
54  /***
55   * @author Steve Viens (sviens@apache.org)
56   */
57  public class SaveBusinessFunction extends AbstractFunction
58  {
59    // private reference to jUDDI Logger
60    private static Log log = LogFactory.getLog(SaveBusinessFunction.class);
61  
62    /***
63     *
64     */
65    public SaveBusinessFunction(RegistryEngine registry)
66    {
67      super(registry);
68    }
69  
70    /***
71     *
72     */
73    public RegistryObject execute(RegistryObject regObject)
74      throws RegistryException
75    {
76      SaveBusiness request = (SaveBusiness)regObject;
77      String generic = request.getGeneric();
78      AuthInfo authInfo = request.getAuthInfo();
79      Vector businessVector = request.getBusinessEntityVector();
80      Vector uploadRegVector = request.getUploadRegisterVector();
81      UUIDGen uuidgen = UUIDGenFactory.getUUIDGen();
82  
83      // UploadRegistry functionality is not currently supported.
84      if ((uploadRegVector != null) && (uploadRegVector.size() > 0))
85        throw new UnsupportedException("save_business: "+
86            "UploadRegistry is not supported.");
87  
88      // aquire a jUDDI datastore instance
89      DataStore dataStore = DataStoreFactory.getDataStore();
90  
91      try
92      {
93        dataStore.beginTrans();
94  
95        // Validate authentication parameters
96        Publisher publisher = getPublisher(authInfo,dataStore);
97  
98        String publisherID = publisher.getPublisherID();
99        String authorizedName = publisher.getName();
100 
101       // Validate request parameters & execute
102       for (int i=0; i<businessVector.size(); i++)
103       {
104         // Move the BusinessEntity into a form we can work with easily
105         BusinessEntity business = (BusinessEntity)businessVector.elementAt(i);
106 
107         String businessKey = business.getBusinessKey();
108 
109         // If a BusinessKey was specified then make sure it's a valid one.
110         if ((businessKey != null) && (businessKey.length() > 0) && (!dataStore.isValidBusinessKey(businessKey)))
111           throw new InvalidKeyPassedException("save_business: "+
112               "businessKey="+businessKey);
113 
114         // If a BusinessKey was specified then make sure 'publisherID' controls it.
115         if ((businessKey != null) && (businessKey.length() > 0) && (!dataStore.isBusinessPublisher(businessKey,publisherID)))
116           throw new UserMismatchException("save_business: "+
117               "userID="+publisherID+", "+
118               "businessKey="+businessKey);
119 
120         // Normally, a valid tModelKey MUST be specified for the keyedReference 
121         // to be valid. However, in the case of a keyedReference that is used in 
122         // a categoryBag, the tModelKey may be omitted or specified as a 
123         // zero-length string to indicate that the taxonomy being used is
124         // uddi-org:general_keywords. When it is omitted in this manner, the UDDI 
125         // registry will insert the proper key during the save_xx operation.
126         // - UDDI Programmers API v2.04 Section 4.3.5.1 Specifying keyedReferences
127         //
128         CategoryBag categoryBag = business.getCategoryBag();
129         if (categoryBag != null)
130         {
131           Vector keyedRefVector = categoryBag.getKeyedReferenceVector();
132           if (keyedRefVector != null)
133           {
134             int vectorSize = keyedRefVector.size();
135             if (vectorSize > 0)
136             {
137               for (int j=0; j<vectorSize; j++)
138               {
139                 KeyedReference keyedRef = (KeyedReference)keyedRefVector.elementAt(j);
140                 String key = keyedRef.getTModelKey();
141                 
142                 // A null or zero-length tModelKey is treated as 
143                 // though the tModelKey for uddiorg:general_keywords 
144                 // had been specified.
145                 //
146                 if ((key == null) || (key.trim().length() == 0))
147                   keyedRef.setTModelKey(TModel.GENERAL_KEYWORDS_TMODEL_KEY);
148               }
149             }
150           }
151         }
152       }
153 
154       for (int i=0; i<businessVector.size(); i++)
155       {
156         // move the BusinessEntity into a form we can work with easily
157         BusinessEntity business = (BusinessEntity)businessVector.elementAt(i);
158 
159         String businessKey = business.getBusinessKey();
160 
161         // If the new BusinessEntity has a BusinessKey then it must already
162         // exists so delete the old one. It a BusinessKey isn't specified then
163         // this is a new BusinessEntity so create a new BusinessKey for it.
164         //
165         if ((businessKey != null) && (businessKey.length() > 0))
166         {
167           dataStore.deleteBusiness(businessKey);
168         }
169         else
170         {
171           business.setBusinessKey(uuidgen.uuidgen());
172         }
173 
174         // check if the business has DiscoveryURL with
175         // useType as 'businessEntity' if not create one
176         // and add it to the business object.
177         //
178         addBusinessEntityDiscoveryURL(business);
179 
180         // Everything checks out so let's save it. First
181         // store 'authorizedName' and 'operator' values
182         // in each BusinessEntity.
183         //
184         business.setAuthorizedName(authorizedName);
185         business.setOperator(Config.getOperator());
186 
187         // If no contacts were specified with the Business
188         // Entity then add a new contact of type 'publisher'
189         // using the publishers information.
190 
191         Contacts contacts = business.getContacts();
192         if ((contacts == null) ||
193             (contacts.getContactVector() == null) ||
194             (contacts.getContactVector().isEmpty()))
195         {
196           Contact contact = new Contact();
197           contact.setPersonNameValue(publisher.getName());
198           contact.setUseType("publisher");
199 
200           String email = publisher.getEmailAddress();
201           if (email != null)
202             contact.addEmail(new Email(email,"email"));
203 
204           business.addContact(contact);
205         }
206 
207         dataStore.saveBusiness(business,publisherID);
208       }
209 
210       dataStore.commit();
211 
212       BusinessDetail detail = new BusinessDetail();
213       detail.setGeneric(generic);
214       detail.setOperator(Config.getOperator());
215       detail.setTruncated(false);
216       detail.setBusinessEntityVector(businessVector);
217       return detail;
218     }
219     catch(UnsupportedException suppex)
220     {
221       try { dataStore.rollback(); } catch(Exception e) { }
222       log.info(suppex);
223       throw (RegistryException)suppex;
224     }
225     catch(InvalidKeyPassedException ikpex)
226     {
227       try { dataStore.rollback(); } catch(Exception e) { }
228       log.info(ikpex);
229       throw (RegistryException)ikpex;
230     }
231     catch(UserMismatchException umex)
232     {
233       try { dataStore.rollback(); } catch(Exception e) { }
234       log.info(umex);
235       throw (RegistryException)umex;
236     }
237     catch(RegistryException regex)
238     {
239       try { dataStore.rollback(); } catch(Exception e) { }
240       log.error(regex);
241       throw (RegistryException)regex;
242     }
243     catch(Exception ex)
244     {
245       try { dataStore.rollback(); } catch(Exception e) { }
246       log.error(ex);
247       throw new RegistryException(ex);
248     }
249     finally
250     {
251       if (dataStore != null)
252         dataStore.release();
253     }
254   }
255 
256   private void addBusinessEntityDiscoveryURL(BusinessEntity business)
257   {
258     // get the discovery URLs from the business entity
259     DiscoveryURLs discoveryURLs = business.getDiscoveryURLs();
260 
261     boolean businessEntityURLExists = false;
262     String businessEntityUseType = BusinessEntityHandler.TAG_NAME;
263 
264     if(discoveryURLs != null)
265     {
266       Vector discoveryURLVector = discoveryURLs.getDiscoveryURLVector();
267       if(discoveryURLVector != null)
268       {
269 
270         String useType  = null;
271 
272         for (int j=0; j<discoveryURLVector.size(); j++)
273         {
274           DiscoveryURL discoveryURL = (DiscoveryURL)discoveryURLVector.get(j);
275           if(discoveryURL != null)
276           {
277             useType = discoveryURL.getUseType();
278             // check if the business has DiscoveryURL with useType as 'businessEntity'
279             if(useType.equals(businessEntityUseType))
280             {
281               businessEntityURLExists = true;
282               j = discoveryURLVector.size();
283             }
284           }
285         }
286       }
287     }
288     else
289     {
290       // create create a discoveryURLs and add it to business entity
291       business.setDiscoveryURLs(new DiscoveryURLs());
292     }
293 
294     // add the businessEntity if businessEntity URL doesn't exist
295     if(!businessEntityURLExists)
296     {
297       // get the DiscoveryURL from the juddi properties file
298       StringBuffer siteURL = new StringBuffer();
299       siteURL.append(Config.getDiscoveryURL());
300       siteURL.append("businesskey=");
301       siteURL.append(business.getBusinessKey());
302       
303       // add to the business entity
304       business.addDiscoveryURL(new DiscoveryURL(businessEntityUseType,siteURL.toString()));
305     }
306   }
307   
308   
309   /****************************************************************************/
310   /****************************** TEST DRIVER *********************************/
311   /****************************************************************************/
312 
313 
314   public static void main(String[] args)
315   {
316     // be sure to use the jUDDI-manged pool
317     Properties props = new Properties();
318     props.put("juddi.useConnectionPool","true");
319 
320     // initialize the registry
321     RegistryEngine reg = new RegistryEngine(props);
322     reg.init();
323 
324     try
325     {
326       // create & execute the GetAuthToken request
327       GetAuthToken authTokenRequest = new GetAuthToken("sviens","password");
328       AuthToken authToken = (AuthToken)reg.execute(authTokenRequest);
329       AuthInfo authInfo = authToken.getAuthInfo();
330 
331       // generate a Name Vector
332       Vector nameVector = new Vector();
333       nameVector.add(new Name("IBM"));
334       nameVector.add(new Name("Microsoft"));
335 
336       // generate a new BusinessService
337       BusinessService service = new BusinessService();
338       service.setNameVector(nameVector);
339       
340       // generate a BusinessService Vector
341       Vector serviceVector = new Vector();
342       serviceVector.add(service);
343       
344       // generate a BusinessServices instance
345       BusinessServices services = new BusinessServices();
346       services.setBusinessServiceVector(serviceVector);
347       
348       // generate a BusinessEntity
349       BusinessEntity businessEntity = new BusinessEntity();
350       businessEntity.setBusinessKey(null);
351       businessEntity.setNameVector(nameVector);
352       businessEntity.setBusinessServices(services);
353 
354       // generate a BusinessEntity Vector
355       Vector businessEntityVector = new Vector();
356       businessEntityVector.add(businessEntity);
357 
358       // create & execute the SaveBusiness request
359       SaveBusiness request = new SaveBusiness();
360       request.setAuthInfo(authInfo);
361       request.setBusinessEntityVector(businessEntityVector);
362       BusinessDetail detail = (BusinessDetail)reg.execute(request);
363       
364       System.out.println(detail);
365     }
366     catch (Exception ex)
367     {
368       // write execption to the console
369       ex.printStackTrace();
370     }
371     finally
372     {
373       // destroy the registry
374       reg.dispose();
375     }
376   }
377 }