This project has retired. For details please refer to its Attic page.
BusinessLifeCycleManagerImpl xref
View Javadoc
1   /**
2    *
3    * Copyright 2004 The Apache Software Foundation
4    *
5    *  Licensed under the Apache License, Version 2.0 (the "License");
6    *  you may not use this file except in compliance with the License.
7    *  You may obtain a copy of the License at
8    *
9    *     http://www.apache.org/licenses/LICENSE-2.0
10   *
11   *  Unless required by applicable law or agreed to in writing, software
12   *  distributed under the License is distributed on an "AS IS" BASIS,
13   *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14   *  See the License for the specific language governing permissions and
15   *  limitations under the License.
16   */
17  package org.apache.ws.scout.registry;
18  
19  import java.io.Serializable;
20  import java.net.PasswordAuthentication;
21  import java.util.ArrayList;
22  import java.util.Collection;
23  import java.util.HashSet;
24  import java.util.Hashtable;
25  import java.util.Iterator;
26  import java.util.LinkedHashSet;
27  import java.util.List;
28  import java.util.Set;
29  import java.util.Vector;
30  
31  import javax.xml.registry.BulkResponse;
32  import javax.xml.registry.BusinessLifeCycleManager;
33  import javax.xml.registry.DeleteException;
34  import javax.xml.registry.InvalidRequestException;
35  import javax.xml.registry.JAXRException;
36  import javax.xml.registry.JAXRResponse;
37  import javax.xml.registry.LifeCycleManager;
38  import javax.xml.registry.RegistryService;
39  import javax.xml.registry.SaveException;
40  import javax.xml.registry.UnexpectedObjectException;
41  import javax.xml.registry.infomodel.Association;
42  import javax.xml.registry.infomodel.ClassificationScheme;
43  import javax.xml.registry.infomodel.Concept;
44  import javax.xml.registry.infomodel.Key;
45  import javax.xml.registry.infomodel.Organization;
46  import javax.xml.registry.infomodel.RegistryObject;
47  import javax.xml.registry.infomodel.Service;
48  import javax.xml.registry.infomodel.ServiceBinding;
49  
50  import org.apache.commons.logging.Log;
51  import org.apache.commons.logging.LogFactory;
52  import org.apache.ws.scout.model.uddi.v2.AssertionStatusItem;
53  import org.apache.ws.scout.model.uddi.v2.AssertionStatusReport;
54  import org.apache.ws.scout.model.uddi.v2.AuthToken;
55  import org.apache.ws.scout.model.uddi.v2.BindingDetail;
56  import org.apache.ws.scout.model.uddi.v2.BindingTemplate;
57  import org.apache.ws.scout.model.uddi.v2.BusinessDetail;
58  import org.apache.ws.scout.model.uddi.v2.BusinessEntity;
59  import org.apache.ws.scout.model.uddi.v2.BusinessInfo;
60  import org.apache.ws.scout.model.uddi.v2.BusinessService;
61  import org.apache.ws.scout.model.uddi.v2.Description;
62  import org.apache.ws.scout.model.uddi.v2.DispositionReport;
63  import org.apache.ws.scout.model.uddi.v2.ErrInfo;
64  import org.apache.ws.scout.model.uddi.v2.KeyedReference;
65  import org.apache.ws.scout.model.uddi.v2.Name;
66  import org.apache.ws.scout.model.uddi.v2.ObjectFactory;
67  import org.apache.ws.scout.model.uddi.v2.PublisherAssertion;
68  import org.apache.ws.scout.model.uddi.v2.PublisherAssertions;
69  import org.apache.ws.scout.model.uddi.v2.Result;
70  import org.apache.ws.scout.model.uddi.v2.ServiceDetail;
71  import org.apache.ws.scout.model.uddi.v2.ServiceInfo;
72  import org.apache.ws.scout.model.uddi.v2.TModel;
73  import org.apache.ws.scout.model.uddi.v2.TModelDetail;
74  import org.apache.ws.scout.registry.infomodel.ConceptImpl;
75  import org.apache.ws.scout.registry.infomodel.InternationalStringImpl;
76  import org.apache.ws.scout.registry.infomodel.KeyImpl;
77  import org.apache.ws.scout.registry.infomodel.OrganizationImpl;
78  import org.apache.ws.scout.registry.infomodel.ServiceImpl;
79  import org.apache.ws.scout.util.ScoutJaxrUddiHelper;
80  import org.apache.ws.scout.util.ScoutUddiJaxrHelper;
81  
82  /**
83   * Implements JAXR BusinessLifeCycleManager Interface.
84   * For futher details, look into the JAXR API Javadoc.
85   *
86   * @author <a href="mailto:anil@apache.org">Anil Saldhana</a>
87   * @author <a href="mailto:geirm@apache.org">Geir Magnusson Jr.</a>
88   * @author <a href="mailto:tcunning@apache.org">Tom Cunningham</a>
89   */
90  public class BusinessLifeCycleManagerImpl extends LifeCycleManagerImpl
91          implements BusinessLifeCycleManager, Serializable {
92  		
93  	private static final long serialVersionUID = -4533264314909343311L;
94  
95  	private Log log = LogFactory.getLog(this.getClass());
96      
97      private transient ObjectFactorytFactory.html#ObjectFactory">ObjectFactory objectFactory = new ObjectFactory();
98  	
99      public BusinessLifeCycleManagerImpl(RegistryService registry) {
100     	super(registry);
101         
102         if(objectFactory == null)
103         	objectFactory = new ObjectFactory();        
104     }
105 
106     /**
107      * Deletes one or more previously submitted objects from the registry
108      * using the object keys and a specified objectType attribute.
109      *
110      * @param keys
111      * @param objectType
112      * @return BulkResponse object
113      * @throws JAXRException
114      */
115     public BulkResponse deleteObjects(Collection keys, String objectType) throws JAXRException {
116         BulkResponse bulk = null;
117 
118         if (objectType == LifeCycleManager.ASSOCIATION) {
119             bulk = this.deleteAssociations(keys);
120         }
121         else if (objectType == LifeCycleManager.CLASSIFICATION_SCHEME) {
122             bulk = this.deleteClassificationSchemes(keys);
123         }
124         else if (objectType == LifeCycleManager.CONCEPT) {
125             bulk = this.deleteConcepts(keys);
126         }
127         else if (objectType == LifeCycleManager.ORGANIZATION) {
128             bulk = this.deleteOrganizations(keys);
129         }
130         else if (objectType == LifeCycleManager.SERVICE) {
131             bulk = this.deleteServices(keys);
132         }
133         else if (objectType == LifeCycleManager.SERVICE_BINDING) {
134             bulk = this.deleteServiceBindings(keys);
135         }
136         else {
137             throw new JAXRException("Delete Operation for " + objectType + " not implemented by Scout");
138         }
139 
140         return bulk;
141     }
142 
143     public BulkResponse deleteAssociations(Collection associationKeys) throws JAXRException {
144         return this.deleteOperation(associationKeys, "DELETE_ASSOCIATION");
145     }
146 
147     public BulkResponse deleteClassificationSchemes(Collection schemeKeys) throws JAXRException {
148         return this.deleteOperation(schemeKeys, "DELETE_CLASSIFICATIONSCHEME");
149     }
150 
151     public BulkResponse deleteConcepts(Collection conceptKeys) throws JAXRException {
152         return this.deleteOperation(conceptKeys, "DELETE_CONCEPT");
153     }
154 
155     public BulkResponse deleteOrganizations(Collection orgkeys) throws JAXRException {
156         return this.deleteOperation(orgkeys, "DELETE_ORG");
157     }
158 
159     public BulkResponse deleteServiceBindings(Collection bindingKeys) throws JAXRException {
160         return this.deleteOperation(bindingKeys, "DELETE_SERVICEBINDING");
161     }
162 
163     public BulkResponse deleteServices(Collection serviceKeys) throws JAXRException {
164         return this.deleteOperation(serviceKeys, "DELETE_SERVICE");
165     }
166 
167     /**
168      * Saves one or more Objects to the registry. An object may be a
169      * RegistryObject  subclass instance. If an object is not in the registry,
170      * it is created in the registry.  If it already exists in the registry
171      * and has been modified, then its  state is updated (replaced) in the
172      * registry
173      * <p/>
174      * TODO:Check if juddi can provide a facility to store a collection of heterogenous
175      * objects
176      * <p/>
177      * TODO - does this belong here?  it's really an overload of
178      * LifecycleManager.saveObjects, but all the help we need
179      * like saveOrganization() is up here...
180      *
181      * @param col
182      * @return a BulkResponse containing the Collection of keys for those objects
183      *         that were saved successfully and any SaveException that was encountered
184      *         in case of partial commit
185      * @throws JAXRException
186      */
187     public BulkResponse saveObjects(Collection col) throws JAXRException {
188 
189         Iterator iter = col.iterator();
190 
191         LinkedHashSet<Object> suc = new LinkedHashSet<Object>();
192         Collection<Exception> exc = new ArrayList<Exception>();
193 
194         while (iter.hasNext()) {
195             RegistryObject reg = (RegistryObject) iter.next();
196 
197             BulkResponse br = null;
198 
199             Collection<RegistryObject> c = new ArrayList<RegistryObject>();
200             c.add(reg);
201 
202             if (reg instanceof javax.xml.registry.infomodel.Association) {
203                 br = saveAssociations(c, true);
204             }
205             else if (reg instanceof javax.xml.registry.infomodel.ClassificationScheme) {
206                 br = saveClassificationSchemes(c);
207             }
208             else if (reg instanceof javax.xml.registry.infomodel.Concept) {
209                 br = saveConcepts(c);
210             }
211             else if (reg instanceof javax.xml.registry.infomodel.Organization) {
212                 br = saveOrganizations(c);
213             }
214             else if (reg instanceof javax.xml.registry.infomodel.Service) {
215                 br = saveServices(c);
216             }
217             else if (reg instanceof javax.xml.registry.infomodel.ServiceBinding) {
218                 br = saveServiceBindings(c);
219             }
220             else {
221                 throw new JAXRException("Delete Operation for " + reg.getClass() 
222                         + " not implemented by Scout");
223             }
224 
225             if (br.getCollection() != null) {
226                 suc.addAll(br.getCollection());
227             }
228 
229             if (br.getExceptions() != null) {
230                 exc.addAll(br.getExceptions());
231             }
232         }
233 
234         BulkResponseImplResponseImpl.html#BulkResponseImpl">BulkResponseImpl bulk = new BulkResponseImpl();
235 
236         /*
237          *  TODO - what is the right status?
238          */
239         bulk.setStatus(JAXRResponse.STATUS_SUCCESS);
240 
241         bulk.setCollection(suc);
242         bulk.setExceptions(exc);
243 
244         return bulk;
245     }
246 
247 
248     public BulkResponse saveAssociations(Collection associations, boolean replace) throws JAXRException {
249         BulkResponseImplResponseImpl.html#BulkResponseImpl">BulkResponseImpl bulk = new BulkResponseImpl();
250         PublisherAssertion[] sarr = new PublisherAssertion[associations.size()];
251 
252         Collection<Key> coll = new ArrayList<Key>();
253         Collection<Exception> exceptions = new ArrayList<Exception>();
254 
255         Iterator iter = associations.iterator();
256         int currLoc = 0;
257         while (iter.hasNext()) {
258             
259                 Association association = (Association) iter.next();
260                 association.getSourceObject();
261                 PublisherAssertion pa = ScoutJaxrUddiHelper.getPubAssertionFromJAXRAssociation(association);
262                 sarr[currLoc] = pa;
263                 currLoc++;
264             
265                 // Save PublisherAssertion
266                 PublisherAssertions bd = null;
267                 try {
268                     bd = (PublisherAssertions) executeOperation(sarr, "SAVE_ASSOCIATION");
269                 }
270                 catch (RegistryException e) {
271                     exceptions.add(new SaveException(e));
272                     bulk.setExceptions(exceptions);
273                     bulk.setStatus(JAXRResponse.STATUS_FAILURE);
274                     return bulk;
275                 }
276                 if(bd != null)
277                 {
278                 	List<PublisherAssertion> publisherAssertionList = bd.getPublisherAssertion();
279                 	PublisherAssertion[] keyarr = new PublisherAssertion[publisherAssertionList.size()];
280                 	publisherAssertionList.toArray(keyarr);
281                 	
282                 	for (int i = 0; keyarr != null && i < keyarr.length; i++) {
283                 		PublisherAssertion result = (PublisherAssertion) keyarr[i];
284                         KeyedReference keyr = result.getKeyedReference();
285                         Concept c = new ConceptImpl(getRegistryService().getBusinessLifeCycleManager());
286                         c.setName(new InternationalStringImpl(keyr.getKeyName()));
287                         c.setKey( new KeyImpl(keyr.getTModelKey()) );
288                         c.setValue(keyr.getKeyValue());
289                         association.setAssociationType(c);
290                         coll.add(association.getKey());
291                    }
292                 }
293         }
294         bulk.setCollection(coll);
295         bulk.setExceptions(exceptions);
296 
297         return bulk;
298     }
299 
300     public BulkResponse saveClassificationSchemes(Collection schemes) throws JAXRException {
301         //Now we need to convert the collection into a vector for juddi
302         BulkResponseImplResponseImpl.html#BulkResponseImpl">BulkResponseImpl bulk = new BulkResponseImpl();
303         TModel[] entityarr = new TModel[schemes.size()];
304 
305         LinkedHashSet<Key> coll = new LinkedHashSet<Key>();
306         Collection<Exception> exceptions = new ArrayList<Exception>();
307 
308         Iterator iter = schemes.iterator();
309         int currLoc = 0;
310         while (iter.hasNext()) {
311             try {
312                 TModel en =
313                         ScoutJaxrUddiHelper.getTModelFromJAXRClassificationScheme((ClassificationScheme) iter.next());
314                 entityarr[currLoc] = en;
315                 currLoc++;
316             }
317             catch (ClassCastException ce) {
318                 throw new UnexpectedObjectException();
319             }
320         }
321         log.debug("Method:save_classificationscheme: ENlength=" + entityarr.length);
322         // Save business
323         TModelDetail td = null;
324         try {
325             td = (TModelDetail) executeOperation(entityarr, "SAVE_TMODEL");
326         }
327         catch (RegistryException e) {
328             exceptions.add(new SaveException(e.getLocalizedMessage()));
329             bulk.setStatus(JAXRResponse.STATUS_FAILURE);
330             return bulk;
331         }
332 
333         List<TModel> tmodelList = td.getTModel();
334         entityarr = new TModel[tmodelList.size()];
335         tmodelList.toArray(entityarr); 
336         log.debug("After Saving TModel. Obtained vector size:" + ((entityarr != null) ? entityarr.length : 0));
337         for (int i = 0; entityarr != null && i < entityarr.length; i++) {
338             TModel tm = (TModel) entityarr[i];
339             coll.add(new KeyImpl(tm.getTModelKey()));
340         }
341 
342         bulk.setCollection(coll);
343         bulk.setExceptions(exceptions);
344 
345         return bulk;
346     }
347 
348     public BulkResponse saveConcepts(Collection concepts) throws JAXRException {
349         //Now we need to convert the collection into a vector for juddi
350         BulkResponseImplResponseImpl.html#BulkResponseImpl">BulkResponseImpl bulk = new BulkResponseImpl();
351         TModel[] entityarr = new TModel[concepts.size()];
352 
353         LinkedHashSet<Key> coll = new LinkedHashSet<Key>();
354         Collection<Exception> exceptions = new ArrayList<Exception>();
355 
356         Iterator iter = concepts.iterator();
357         int currLoc = 0;
358         while (iter.hasNext()) {
359             try {
360                 TModel en =
361                         ScoutJaxrUddiHelper.getTModelFromJAXRConcept((Concept) iter.next());
362                 entityarr[currLoc] = en;
363                 currLoc++;
364             }
365             catch (ClassCastException ce) {
366                 throw new UnexpectedObjectException();
367             }
368         }
369         log.debug("Method:save_concept: ENlength=" + entityarr.length);
370         // Save business
371         TModelDetail td = null;
372         try {
373             td = (TModelDetail) executeOperation(entityarr, "SAVE_TMODEL");
374         }
375         catch (RegistryException e) {
376             exceptions.add(new SaveException(e.getLocalizedMessage()));
377             bulk.setStatus(JAXRResponse.STATUS_FAILURE);
378             return bulk;
379         }
380 
381         List<TModel> tmodelList = td.getTModel();
382         entityarr = new TModel[tmodelList.size()];
383         tmodelList.toArray(entityarr);
384         
385         log.debug("After Saving TModel. Obtained vector size:" + ((entityarr != null) ? entityarr.length : 0));
386         for (int i = 0; entityarr != null && i < entityarr.length; i++) {
387             TModel tm = (TModel) entityarr[i];
388             coll.add(new KeyImpl(tm.getTModelKey()));
389         }
390 
391         bulk.setCollection(coll);
392         bulk.setExceptions(exceptions);
393 
394         return bulk;
395     }
396 
397     public BulkResponse saveOrganizations(Collection organizations) throws JAXRException {
398         //Now we need to convert the collection into a vector for juddi
399         BulkResponseImplResponseImpl.html#BulkResponseImpl">BulkResponseImpl bulk = new BulkResponseImpl();
400         BusinessEntity[] entityarr = new BusinessEntity[organizations.size()];
401 
402         LinkedHashSet<Key> coll = new LinkedHashSet<Key>();
403         Collection<Exception> exceptions = new ArrayList<Exception>();
404 
405         Iterator iter = organizations.iterator();
406         int currLoc = 0;
407         while (iter.hasNext()) {
408             try {
409                 BusinessEntity en =
410                         ScoutJaxrUddiHelper.getBusinessEntityFromJAXROrg((Organization) iter.next());
411                 entityarr[currLoc] = en;
412                 currLoc++;
413             }
414             catch (ClassCastException ce) {
415                 throw new UnexpectedObjectException();
416             }
417         }
418         log.debug("Method:save_business: ENlength=" + entityarr.length);
419         // Save business
420         BusinessDetail bd = null;
421         try {
422             bd = (BusinessDetail) executeOperation(entityarr, "SAVE_ORG");
423         }
424         catch (RegistryException e) {
425             exceptions.add(new SaveException(e.getLocalizedMessage()));
426             bulk.setStatus(JAXRResponse.STATUS_FAILURE);
427             bulk.setExceptions(exceptions);
428             return bulk;
429         }
430 
431         List<BusinessEntity> bizEntityList = bd.getBusinessEntity();
432         
433         entityarr = new BusinessEntity[bizEntityList.size()];
434         bizEntityList.toArray(entityarr);
435         
436         log.debug("After Saving Business. Obtained vector size:" + ((entityarr != null) ? entityarr.length : 0));
437         for (int i = 0; entityarr != null && i < entityarr.length; i++) {
438             BusinessEntity entity = (BusinessEntity) entityarr[i];
439             coll.add(new KeyImpl(entity.getBusinessKey()));
440         }
441 
442         bulk.setCollection(coll);
443         bulk.setExceptions(exceptions);
444 
445         return bulk;
446     }
447 
448     public BulkResponse saveServiceBindings(Collection bindings) throws JAXRException {
449         BulkResponseImplResponseImpl.html#BulkResponseImpl">BulkResponseImpl bulk = new BulkResponseImpl();
450         BindingTemplate[] sbarr = new BindingTemplate[bindings.size()];
451 
452         LinkedHashSet<Key> coll = new LinkedHashSet<Key>();
453         Collection<Exception> exceptions = new ArrayList<Exception>();
454 
455         Iterator iter = bindings.iterator();
456         int currLoc = 0;
457         while (iter.hasNext()) {
458             try {
459                 BindingTemplate bs = ScoutJaxrUddiHelper.getBindingTemplateFromJAXRSB((ServiceBinding) iter.next());
460                 sbarr[currLoc] = bs;
461                 currLoc++;
462             }
463             catch (ClassCastException ce) {
464                 throw new UnexpectedObjectException();
465             }
466         }
467         // Save ServiceBinding
468         BindingDetail bd = null;
469         try {
470             bd = (BindingDetail) executeOperation(sbarr, "SAVE_SERVICE_BINDING");
471         }
472         catch (RegistryException e) {
473             exceptions.add(new SaveException(e.getLocalizedMessage()));
474             bulk.setStatus(JAXRResponse.STATUS_FAILURE);
475             return bulk;
476         }
477 
478         List<BindingTemplate> bindingTemplateList = bd.getBindingTemplate();
479         sbarr = new BindingTemplate[bindingTemplateList.size()];
480         bindingTemplateList.toArray(sbarr);
481         
482         for (int i = 0; sbarr != null && i < sbarr.length; i++) {
483             BindingTemplate bt = (BindingTemplate) sbarr[i];
484             coll.add(new KeyImpl(bt.getBindingKey()));
485         }
486         if (coll.size()>0) {
487             bulk.setCollection(coll);
488         }
489         bulk.setExceptions(exceptions);
490 
491         return bulk;
492     }
493 
494     public BulkResponse saveServices(Collection services) throws JAXRException {
495         BulkResponseImplResponseImpl.html#BulkResponseImpl">BulkResponseImpl bulk = new BulkResponseImpl();
496         BusinessService[] sarr = new BusinessService[services.size()];
497 
498         LinkedHashSet<Key> coll = new LinkedHashSet<Key>();
499         Collection<Exception> exceptions = new ArrayList<Exception>();
500 
501 
502         Iterator iter = services.iterator();
503         int currLoc = 0;
504         while (iter.hasNext()) {
505             try {
506                 BusinessService bs = ScoutJaxrUddiHelper.getBusinessServiceFromJAXRService((Service) iter.next());
507                 sarr[currLoc] = bs;
508                 currLoc++;
509             }
510             catch (ClassCastException ce) {
511                 throw new UnexpectedObjectException();
512             }
513         }
514         // Save Service
515         ServiceDetail sd = null;
516         try {
517             sd = (ServiceDetail) executeOperation(sarr, "SAVE_SERVICE");
518         }
519         catch (RegistryException e) {
520             exceptions.add(new SaveException(e.getLocalizedMessage()));
521             bulk.setStatus(JAXRResponse.STATUS_FAILURE);
522             return bulk;
523         }
524 
525         List<BusinessService> bizServiceList = sd.getBusinessService();
526         sarr = new BusinessService[bizServiceList.size()];
527         bizServiceList.toArray(sarr);
528         
529         for (int i = 0; sarr != null && i < sarr.length; i++) {
530             BusinessService entity = (BusinessService) sarr[i];
531             coll.add(new KeyImpl(entity.getServiceKey()));
532         }
533         bulk.setCollection(coll);
534         bulk.setExceptions(exceptions);
535 
536         return bulk;
537     }
538 
539     public void confirmAssociation(Association assoc) throws JAXRException, InvalidRequestException {
540        //Store it in the UDDI registry
541        HashSet<Association> col = new HashSet<Association>();
542        col.add(assoc);
543        BulkResponse br = this.saveAssociations(col, true);
544        if(br.getExceptions()!= null)
545           throw new JAXRException("Confiming the Association Failed");
546     }
547 
548     public void unConfirmAssociation(Association assoc) throws JAXRException, InvalidRequestException {
549        //TODO
550        //Delete it from the UDDI registry
551        Collection<Key> col = new ArrayList<Key>();
552        col.add(assoc.getKey());
553        BulkResponse br = this.deleteAssociations(col);
554        if(br.getExceptions()!= null)
555           throw new JAXRException("UnConfiming the Association Failed");
556     }
557 
558     //Protected Methods
559     protected Object executeOperation(Object dataarray, String op)
560             throws RegistryException, JAXRException {
561         if (registry == null) {
562             throw new IllegalStateException("No registry");
563         }
564 
565         IRegistry/../../../../org/apache/ws/scout/registry/IRegistry.html#IRegistry">IRegistry ireg =  (IRegistry) registry.getRegistry();
566 
567         ConnectionImpl connection = registry.getConnection();
568         AuthToken token = getAuthToken(connection, ireg);
569         if (token == null) {
570             throw new IllegalStateException("No auth token returned");
571         }
572 
573         Object regobj;
574         if(op.equalsIgnoreCase("SAVE_ASSOCIATION"))
575         {
576         	try {
577         		regobj = ireg.setPublisherAssertions(token.getAuthInfo(), (PublisherAssertion[]) dataarray);
578         	} catch (RegistryException rve) {
579         		String username = getUsernameFromCredentials(connection.getCredentials());
580         		if (AuthTokenSingleton.getToken(username) != null) {
581         			AuthTokenSingleton.deleteAuthToken(username);
582         		}
583         		token = getAuthToken(connection, ireg);
584         		regobj = ireg.setPublisherAssertions(token.getAuthInfo(), (PublisherAssertion[]) dataarray);
585         	}
586         } 
587         else if (op.equalsIgnoreCase("SAVE_SERVICE")) {
588         	try {
589         		regobj = ireg.saveService(token.getAuthInfo(), (BusinessService[])dataarray);
590         	} catch (RegistryException rve) {
591         		String username = getUsernameFromCredentials(connection.getCredentials());
592         		if (AuthTokenSingleton.getToken(username) != null) {
593         			AuthTokenSingleton.deleteAuthToken(username);
594         		}
595         		token = getAuthToken(connection, ireg);
596         		regobj = ireg.saveService(token.getAuthInfo(), (BusinessService[])dataarray);
597         	}
598         }
599         else if (op.equalsIgnoreCase("SAVE_SERVICE_BINDING")) {
600         	try {
601         		regobj = ireg.saveBinding(token.getAuthInfo(), (BindingTemplate[]) dataarray);
602         	} catch (RegistryException rve) {
603         		String username = getUsernameFromCredentials(connection.getCredentials());
604         		if (AuthTokenSingleton.getToken(username) != null) {
605         			AuthTokenSingleton.deleteAuthToken(username);
606         		}
607         		token = getAuthToken(connection, ireg);
608         		regobj = ireg.saveBinding(token.getAuthInfo(), (BindingTemplate[]) dataarray);        		
609         	}
610         }
611         else if (op.equalsIgnoreCase("SAVE_ORG")) {
612         	try {
613         		regobj = ireg.saveBusiness(token.getAuthInfo(), (BusinessEntity[]) dataarray);
614         	} catch (RegistryException rve) {
615         		String username = getUsernameFromCredentials(connection.getCredentials());
616         		if (AuthTokenSingleton.getToken(username) != null) {
617         			AuthTokenSingleton.deleteAuthToken(username);
618         		}
619         		token = getAuthToken(connection, ireg);
620         		regobj = ireg.saveBusiness(token.getAuthInfo(), (BusinessEntity[]) dataarray);
621         	}
622         }
623         else if (op.equalsIgnoreCase("SAVE_TMODEL")) {
624         	try {
625         		regobj = ireg.saveTModel(token.getAuthInfo(), (TModel[]) dataarray);
626         	} catch (RegistryException rve) {
627         		String username = getUsernameFromCredentials(connection.getCredentials());
628         		if (AuthTokenSingleton.getToken(username) != null) {
629         			AuthTokenSingleton.deleteAuthToken(username);
630         		}
631         		token = getAuthToken(connection, ireg);
632         		regobj = ireg.saveTModel(token.getAuthInfo(), (TModel[]) dataarray);
633         	}
634         }
635         else if (op.equalsIgnoreCase("DELETE_ORG")) {
636             try {
637                 clearPublisherAssertions(token.getAuthInfo(), ireg);
638             	regobj = ireg.deleteBusiness(token.getAuthInfo(), (String[]) dataarray);
639         	} catch (RegistryException rve) {
640         		String username = getUsernameFromCredentials(connection.getCredentials());
641         		if (AuthTokenSingleton.getToken(username) != null) {
642         			AuthTokenSingleton.deleteAuthToken(username);
643         		}
644         		token = getAuthToken(connection, ireg);
645                 clearPublisherAssertions(token.getAuthInfo(), ireg);
646         		regobj = ireg.deleteBusiness(token.getAuthInfo(), (String[]) dataarray);
647         	} 
648         }
649         else if (op.equalsIgnoreCase("DELETE_SERVICE")) {
650         	try {
651         		regobj = ireg.deleteService(token.getAuthInfo(), (String[]) dataarray);
652 	    	} catch (RegistryException rve) {
653 	    		String username = getUsernameFromCredentials(connection.getCredentials());
654         		if (AuthTokenSingleton.getToken(username) != null) {
655         			AuthTokenSingleton.deleteAuthToken(username);
656 	    		}
657 	    		token = getAuthToken(connection, ireg);
658 	            //clearPublisherAssertions(token.getAuthInfo(), ireg);
659         		regobj = ireg.deleteService(token.getAuthInfo(), (String[]) dataarray);
660 	    	}
661         }
662         else if (op.equalsIgnoreCase("DELETE_SERVICEBINDING")) {
663         	try	{
664         		regobj = ireg.deleteBinding(token.getAuthInfo(), (String[]) dataarray);
665 	    	} catch (RegistryException rve) {
666 	    		String username = getUsernameFromCredentials(connection.getCredentials());
667         		if (AuthTokenSingleton.getToken(username) != null) {
668         			AuthTokenSingleton.deleteAuthToken(username);
669 	    		}
670 	    		token = getAuthToken(connection, ireg);
671 	            //clearPublisherAssertions(token.getAuthInfo(), ireg);
672         		regobj = ireg.deleteBinding(token.getAuthInfo(), (String[]) dataarray);
673 	    	}
674         }
675         else if (op.equalsIgnoreCase("DELETE_CONCEPT")) {
676             try {
677             	regobj = ireg.deleteTModel(token.getAuthInfo(), (String[]) dataarray);
678 	    	} catch (RegistryException rve) {
679 	    		String username = getUsernameFromCredentials(connection.getCredentials());
680         		if (AuthTokenSingleton.getToken(username) != null) {
681         			AuthTokenSingleton.deleteAuthToken(username);
682 	    		}
683 	    		token = getAuthToken(connection, ireg);
684 	            clearPublisherAssertions(token.getAuthInfo(), ireg);
685             	regobj = ireg.deleteTModel(token.getAuthInfo(), (String[]) dataarray);
686 	    	}
687         }
688         else if (op.equalsIgnoreCase("DELETE_ASSOCIATION")) {
689         	int len = ((String[]) dataarray).length;
690             PublisherAssertion[] paarr = new PublisherAssertion[len];
691             for(int i=0;i<len;i++)
692             {
693                String keystr = ((String[])dataarray)[i];
694                paarr[i] = ScoutJaxrUddiHelper.getPubAssertionFromJAXRAssociationKey(keystr);
695             }
696             try {
697                 regobj = ireg.deletePublisherAssertions(token.getAuthInfo(), paarr);
698             } catch (RegistryException rve) {
699 	    		String username = getUsernameFromCredentials(connection.getCredentials());
700         		if (AuthTokenSingleton.getToken(username) != null) {
701         			AuthTokenSingleton.deleteAuthToken(username);
702 	    		}
703 	    		token = getAuthToken(connection, ireg);
704 	            clearPublisherAssertions(token.getAuthInfo(), ireg);
705 	            regobj = ireg.deletePublisherAssertions(token.getAuthInfo(), paarr);
706 	    	}
707         }
708         else if (op.equalsIgnoreCase("DELETE_CLASSIFICATIONSCHEME")) {
709             try {
710                 regobj = ireg.deleteTModel(token.getAuthInfo(), (String[]) dataarray);
711 	    	} catch (RegistryException rve) {
712 	    		String username = getUsernameFromCredentials(connection.getCredentials());
713         		if (AuthTokenSingleton.getToken(username) != null) {
714         			AuthTokenSingleton.deleteAuthToken(username);
715 	    		}
716 	    		token = getAuthToken(connection, ireg);
717 	            clearPublisherAssertions(token.getAuthInfo(), ireg);
718 	            regobj = ireg.deleteTModel(token.getAuthInfo(), (String[]) dataarray);
719 	    	}
720         }
721         else {
722             throw new JAXRException("Unsupported operation:" + op);
723         }
724 
725         return regobj;
726     }
727 
728     private void clearPublisherAssertions( String authinfo,IRegistry ireg)
729     {
730        Vector<PublisherAssertion> pasvect  = new Vector<PublisherAssertion>();
731        
732        try
733        {
734           AssertionStatusReport report = ireg.getAssertionStatusReport(authinfo,"status:complete");
735           List<AssertionStatusItem> assertionStatusItemList = report.getAssertionStatusItem();
736           for (AssertionStatusItem assertionStatusItem : assertionStatusItemList) {
737               pasvect.add(this.getPublisherAssertion(assertionStatusItem));
738 		  }
739 
740           report = ireg.getAssertionStatusReport(authinfo,"status:toKey_incomplete");
741           assertionStatusItemList = report.getAssertionStatusItem();
742           for (AssertionStatusItem assertionStatusItem : assertionStatusItemList) {
743               pasvect.add(this.getPublisherAssertion(assertionStatusItem));
744 		  }
745 
746           report = ireg.getAssertionStatusReport(authinfo,"status:fromKey_incomplete");
747           assertionStatusItemList = report.getAssertionStatusItem();
748           for (AssertionStatusItem assertionStatusItem : assertionStatusItemList) {
749               pasvect.add(this.getPublisherAssertion(assertionStatusItem));
750 		  }
751 
752           if (pasvect.size() > 0) {
753         	  PublisherAssertion[] pasarr = new PublisherAssertion[pasvect.size()];
754         	  int i=0;
755               for (PublisherAssertion publisherAssertion : pasvect) {
756 				  pasarr[i++] = publisherAssertion;
757 			  }
758         	  ireg.deletePublisherAssertions(authinfo, pasarr);
759           }
760        }
761        catch (RegistryException e)
762        {
763            ConnectionImpl connection = registry.getConnection();
764     	   String username = getUsernameFromCredentials(connection.getCredentials());
765     	   if (AuthTokenSingleton.getToken(username) != null) {
766     		   AuthTokenSingleton.deleteAuthToken(username);
767     	   }
768     	   AuthToken token = null;
769     	   try {
770     		   token = getAuthToken(connection, ireg);
771     	   } catch (JAXRException je) {
772     	   }
773    		   clearPublisherAssertions( token.getAuthInfo(), ireg);
774        }
775     }
776 
777 
778 
779     protected BulkResponse deleteOperation(Collection<Key> keys, String op)
780             throws JAXRException {
781         if(keys == null)
782         throw new JAXRException("Keys provided to "+op+" are null");
783        
784         //Now we need to convert the collection into a vector for juddi
785         BulkResponseImplResponseImpl.html#BulkResponseImpl">BulkResponseImpl bulk = new BulkResponseImpl();
786         String[] keyarr = new String[keys.size()];
787         Result[] keyResultArr;
788 
789         LinkedHashSet<Key> coll = new LinkedHashSet<Key>();
790         Collection<Exception> exceptions = new ArrayList<Exception>();
791 
792         try {
793             Iterator iter = keys.iterator();
794             int currLoc = 0;
795             while (iter.hasNext()) {
796                 Key key = (Key) iter.next();
797                 keyarr[currLoc] = key.getId();
798                 currLoc++;
799             }
800             // Save business
801             DispositionReport bd = (DispositionReport) executeOperation(keyarr, op);
802             List<Result> resultList = bd.getResult();
803             keyResultArr = new Result[resultList.size()];
804             resultList.toArray(keyResultArr); 
805             
806             log.debug("After deleting Business. Obtained vector size:" + ((keyResultArr != null) ? keyResultArr.length : 0));
807             for (int i = 0; keyResultArr != null && i < keyResultArr.length; i++) {
808                 Result result = (Result) keyResultArr[i];
809                 int errno = result.getErrno();
810                 if (errno == 0) {
811                     coll.addAll(keys);
812                 }
813                 else {
814                     ErrInfo errinfo = result.getErrInfo();
815                     DeleteException de = new DeleteException(errinfo.getErrCode() + ":" + errinfo.getValue());
816                     bulk.setStatus(JAXRResponse.STATUS_FAILURE);
817                     exceptions.add(de);
818                 }
819             }
820         }
821         catch (RegistryException regExcept) {
822 
823             /*
824              * jUDDI (and prollie others) throw an exception on any fault in
825              * the transaction w/ the registry, so we don't get any partial
826              * success
827              */
828             DeleteException de = new DeleteException(regExcept.getFaultCode()
829                     + ":" + regExcept.getFaultString(), regExcept);
830 
831             bulk.setStatus(JAXRResponse.STATUS_FAILURE);
832             exceptions.add(de);
833         }
834         catch (JAXRException tran) {
835             exceptions.add(new JAXRException("Apache JAXR Impl:", tran));
836             bulk.setStatus(JAXRResponse.STATUS_FAILURE);
837         }
838 
839         bulk.setCollection(coll);
840         bulk.setExceptions(exceptions);
841 
842         return bulk;
843     }
844 
845     private String getUsernameFromCredentials(Set credentials) {
846         String username = "", pwd = "";
847                 
848         if (credentials != null) {
849         	Iterator it = credentials.iterator();
850         	while (it.hasNext()) {
851         		PasswordAuthentication pass = (PasswordAuthentication) it.next();
852         		username = pass.getUserName();
853         	}
854         }
855         return username;
856     }
857     
858     /**
859      * Get the Auth Token from the registry
860      *
861      * @param connection
862      * @param ireg
863      * @return auth token
864      * @throws JAXRException
865      */
866     private AuthToken getAuthToken(ConnectionImpl connection, IRegistry ireg)
867             throws JAXRException {    	
868         Set creds = connection.getCredentials();
869         String username = "", pwd = "";
870         if (creds != null) {
871         	Iterator it = creds.iterator();
872         	while (it.hasNext()) {
873         		PasswordAuthentication pass = (PasswordAuthentication) it.next();
874         		username = pass.getUserName	();
875         		pwd = new String(pass.getPassword());
876         	}
877         }
878 
879         if (AuthTokenSingleton.getToken(username) != null) {
880         	return (AuthToken) AuthTokenSingleton.getToken(username);
881         }
882         
883         AuthToken token = null;
884         try {
885             token = ireg.getAuthToken(username, pwd);
886         }
887         catch (Exception e)
888         { 
889             throw new JAXRException(e);
890         }
891         AuthTokenSingleton.addAuthToken(username, token);
892         return token;
893     }
894 
895     private PublisherAssertion getPublisherAssertion(AssertionStatusItem asi)
896     {
897     	PublisherAssertion pa = this.objectFactory.createPublisherAssertion();
898         
899     	if(asi != null)
900     	{
901             String sourceKey = asi.getFromKey();
902             String targetKey = asi.getToKey();
903         
904             if (sourceKey != null) {
905             pa.setFromKey(sourceKey);
906             }
907             
908             if (targetKey != null) {
909             pa.setToKey(targetKey);
910             }
911             
912             KeyedReference keyr = asi.getKeyedReference();
913             
914             if (keyr != null) {
915             pa.setKeyedReference(keyr);
916             }
917             //pa.setTModelKey(keyr.getTModelKey());
918             //pa.setKeyName(keyr.getKeyName());
919             //pa.setKeyValue(keyr.getKeyValue()); // -CBC- These are redundant?
920     		
921     	}return pa;
922     }
923 
924     Organization createOrganization(BusinessDetail bizDetail) throws JAXRException {
925         return ScoutUddiJaxrHelper.getOrganization(bizDetail, this);
926     }    
927     
928     Organization createOrganization(BusinessInfo bizInfo) throws JAXRException {
929         String key = bizInfo.getBusinessKey();
930         List<Name> names = bizInfo.getName(); 
931         
932         List<Description> descriptions = bizInfo.getDescription();
933         List<ServiceInfo> serviceInfos = bizInfo.getServiceInfos().getServiceInfo();
934         
935         OrganizationImplomodel/OrganizationImpl.html#OrganizationImpl">OrganizationImpl org = new OrganizationImpl(this);
936         org.setKey(createKey(key));
937         if (names != null && names.size() > 0) {
938             org.setName(createInternationalString(names.get(0).getValue()));
939         }
940         if (descriptions != null && descriptions.size() > 0) {
941             org.setDescription(createInternationalString(descriptions.get(0).getValue()));
942         }
943         if (serviceInfos != null && serviceInfos.size() > 0) {
944             List<Service> services = new ArrayList<Service>(serviceInfos.size());
945             for (int i = 0; i < serviceInfos.size(); i++) {
946                 ServiceInfo serviceInfo = serviceInfos.get(i);
947                 services.add(createService(serviceInfo));
948             }
949             org.addServices(services);
950         }
951 
952         return org;
953     }
954 
955     Service createService(ServiceInfo serviceInfo) throws JAXRException {
956         String key = serviceInfo.getServiceKey();
957         List<Name> names = serviceInfo.getName();
958         ServiceImplfomodel/ServiceImpl.html#ServiceImpl">ServiceImpl service = new ServiceImpl(this);
959         service.setKey(createKey(key));
960         if (names != null && names.size() > 0) {
961             service.setName(createInternationalString(names.get(0).getValue()));
962         }
963         return service;
964     }
965 
966 }