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.qa;
18  
19  import static org.junit.Assert.assertEquals;
20  import static org.junit.Assert.fail;
21  
22  import java.util.ArrayList;
23  import java.util.Collection;
24  import java.util.Iterator;
25  
26  import javax.xml.registry.BulkResponse;
27  import javax.xml.registry.BusinessQueryManager;
28  import javax.xml.registry.FindQualifier;
29  import javax.xml.registry.JAXRException;
30  import javax.xml.registry.JAXRResponse;
31  import javax.xml.registry.RegistryService;
32  import javax.xml.registry.infomodel.Association;
33  import javax.xml.registry.infomodel.Concept;
34  import javax.xml.registry.infomodel.Key;
35  import javax.xml.registry.infomodel.Organization;
36  import javax.xml.registry.infomodel.RegistryObject;
37  
38  import junit.framework.JUnit4TestAdapter;
39  
40  import org.apache.ws.scout.BaseTestCase;
41  import org.apache.ws.scout.Creator;
42  import org.junit.After;
43  import org.junit.Before;
44  import org.junit.Test;
45  
46  
47  /**
48   * Tests Publish, Delete (and indirectly, find) for associations.
49   * 
50   * You can comment out the deletion portion and use Open source UDDI Browser
51   * <http://www.uddibrowser.org> to check your intermediate results.
52   * 
53   * Based on query/publish tests written by <a href="mailto:anil@apache.org">Anil
54   * Saldhana</a>.
55   * 
56   * @author <a href="mailto:dbhole@redhat.com">Deepak Bhole</a>
57   * @author <a href="mailto:anil@apache.org">Anil Saldhana</a>
58   * 
59   * @since Sep 27, 2005
60   */
61  public class JAXR030AssociationsTest extends BaseTestCase {
62  
63  	private BusinessQueryManager bqm = null;
64  
65  	String associationType = "AssociationType/RelatedTo";
66  	private static String tempSrcOrgName = "Apache Source Org -- APACHE SCOUT TEST";
67  	private static String tempTgtOrgName = "Apache Target Org -- APACHE SCOUT TEST";
68  
69  	private Organization sOrg=null;
70  	private Organization tOrg=null;
71  
72      @Before
73  	public void setUp() {
74  		super.setUp();
75  	}
76  
77      @After
78  	public void tearDown() {
79  		super.tearDown();
80  	}
81  
82  	/**
83  	 * Tests publishing and deleting of associations.
84  	 * 
85  	 * Do not break this into testPublish(), testDelete(), etc. Order is
86  	 * important, and not all jvms can guarantee order since the JUnit framework
87  	 * uses getMethods() to gather test methods, and getMethods() does not
88  	 * guarantee order.
89  	 */
90      @Test
91  	public void testPublishFindAndDeleteAssociation() {
92  		login();
93  		
94  		try {
95  			
96  			RegistryService rs = connection.getRegistryService();
97  			bqm = rs.getBusinessQueryManager();
98  			blm = rs.getBusinessLifeCycleManager();
99  			
100 			//deleting any pre-exisiting organizations
101 			ArrayList<Organization> orgs = findTempOrgs();
102 			for (Organization organization : orgs) {
103 				Collection<Key> keys = new ArrayList<Key>();
104 				keys.add(organization.getKey());
105 				blm.deleteOrganizations(keys);
106 			}
107 			
108             Creator creator = new Creator(blm);
109 
110 			System.out.println("\nCreating temporary organizations...\n");
111             Organization org1 = creator.createOrganization(tempSrcOrgName);
112             Organization org2 = creator.createOrganization(tempTgtOrgName);
113             Collection<Organization> organizations = new ArrayList<Organization>();
114             organizations.add(org1);
115             organizations.add(org2);
116             blm.saveOrganizations(organizations);
117            
118 			System.out.println("\nSearching for newly created organizations...\n");
119 			ArrayList<Organization> newOrgs = findTempOrgs();
120 			sOrg = newOrgs.get(0);
121 			tOrg = newOrgs.get(1);
122 
123 			System.out.println("\nCreating association...\n");
124 			createAssociation(sOrg, tOrg);
125 
126 			// All created ... now try to delete.
127 			String associationID = findAndDeleteAssociation();
128 			
129 			//Let us look for associations now
130 			BulkResponse associationResp = 
131 				bqm.findCallerAssociations(null, Boolean.TRUE, Boolean.TRUE, null);
132 			
133 			if(associationResp.getExceptions() != null)
134 			{
135 				System.out.println(associationResp.getExceptions());
136 				fail("Association lookup failed");
137 			}
138 			else
139 			{
140 				Collection retAssocs = associationResp.getCollection();
141                 if (retAssocs.size() == 0)
142                 {
143                     //Pass
144                 } else
145                 {
146                    Iterator iterAss = retAssocs.iterator();
147                    while(iterAss.hasNext())
148                    {
149                       Association assc = (Association) iterAss.next();
150                       if(assc.getKey().getId().equals(associationID)) {
151                     	  System.out.println("found: " + associationID);
152                           fail("Deleted Association found");
153                       }
154                    }
155                 } 
156 			}
157 			 
158 		} catch (Exception e) {
159 			e.printStackTrace();
160 			fail(e.getMessage());
161 		} 
162 	}
163     
164 	private void createAssociation(Organization sOrg, Organization tOrg)
165 			throws JAXRException {
166 
167 		Concept type = bqm.findConceptByPath(associationType);
168 		Association association = blm.createAssociation(tOrg, type);
169 		sOrg.addAssociation(association);
170 
171 		ArrayList<Association> associations = new ArrayList<Association>();
172 		associations.add(association);
173 
174 		BulkResponse br = blm.saveAssociations(associations, true);
175 		if (br.getStatus() == JAXRResponse.STATUS_SUCCESS) {
176 			System.out.println("Association Saved");
177 			Collection coll = br.getCollection();
178 			Iterator iter = coll.iterator();
179 			while (iter.hasNext()) {
180 				System.out.println("Saved Key=" + iter.next());
181 			}// end while
182 		} else {
183 			System.err.println("JAXRExceptions " + "occurred during save:");
184 			Collection exceptions = br.getExceptions();
185 			Iterator iter = exceptions.iterator();
186 			while (iter.hasNext()) {
187 				Exception e = (Exception) iter.next();
188 				System.err.println(e.toString());
189 			}
190             deleteTempOrgs();
191 		}
192 	}
193 
194 	private String findAndDeleteAssociation() throws JAXRException {
195 
196 		String id = null;
197 		
198 		String sOrgID = sOrg.getKey().getId();
199 		String tOrgID = tOrg.getKey().getId();
200 
201 		Collection<String> findQualifiers = new ArrayList<String>();
202 		findQualifiers.add(FindQualifier.SORT_BY_NAME_ASC);
203 
204 		Concept type = bqm.findConceptByPath(associationType);
205 		ArrayList<Concept> conceptTypes = new ArrayList<Concept>(1);
206 		conceptTypes.add(type);
207 
208 		BulkResponse br = bqm.findAssociations(findQualifiers, sOrgID, tOrgID,
209 				conceptTypes);
210 		Collection associations = br.getCollection();
211 
212 		if (associations == null) {
213 			System.out.println("\n-- Matched 0 orgs");
214             fail("Expected 1 association");
215 
216 		} else {
217 			System.out.println("\n-- Matched " + associations.size()
218 					+ " associations --\n");
219             assertEquals(1,associations.size());
220 
221 			// then step through them
222 			for (Iterator conceptIter = associations.iterator(); conceptIter
223 					.hasNext();) {
224 				Association a = (Association) conceptIter.next();
225 
226 				System.out.println("Id: " + a.getKey().getId());
227 				System.out.println("Name: " + a.getName().getValue());
228 
229 				// Print spacer between messages
230 				System.out.println(" --- ");
231 
232 				id = a.getKey().getId();
233 				deleteAssociation(a.getKey());
234 
235 				System.out.println("\n ============================== \n");
236 			} 
237 		}
238 		return id;
239 	}
240 
241 	private void deleteAssociation(Key key) throws JAXRException {
242 
243 		String id = key.getId();
244 
245 		System.out.println("\nDeleting association with id " + id + "\n");
246 
247 		Collection<Key> keys = new ArrayList<Key>();
248 		keys.add(key);
249 		BulkResponse response = blm.deleteAssociations(keys);
250 
251         assertEquals(BulkResponse.STATUS_SUCCESS, response.getStatus());
252 		Collection exceptions = response.getExceptions();
253 		if (exceptions == null) {
254 			Collection retKeys = response.getCollection();
255 			Iterator keyIter = retKeys.iterator();
256 			javax.xml.registry.infomodel.Key orgKey = null;
257 			if (keyIter.hasNext()) {
258 				orgKey = (javax.xml.registry.infomodel.Key) keyIter.next();
259 				id = orgKey.getId();
260 				System.out
261 						.println("Association with ID=" + id + " was deleted");
262 			}
263 		}
264 	}
265 
266 	private ArrayList<Organization> findTempOrgs() throws JAXRException {
267 
268 		ArrayList<Organization> toReturn = new ArrayList<Organization>();
269 
270 		// Define find qualifiers and name patterns
271 		Collection<String> findQualifiers = new ArrayList<String>();
272 		findQualifiers.add(FindQualifier.SORT_BY_NAME_ASC);
273 		Collection<String> namePatterns = new ArrayList<String>();
274 		if ("3.0".equals(uddiversion)) {
275 			namePatterns.add(tempSrcOrgName);
276 			namePatterns.add(tempTgtOrgName);
277 		} else {
278 			namePatterns.add("%" + tempSrcOrgName + "%");
279 			namePatterns.add("%" + tempTgtOrgName + "%");
280 		}
281 		// Find based upon qualifier type and values
282 		System.out.println("\n-- searching the registry --\n");
283 		BulkResponse response = bqm.findOrganizations(findQualifiers,
284 				namePatterns, null, null, null, null);
285 
286 		// check how many organisation we have matched
287 		Collection orgs = response.getCollection();
288 		if (orgs == null) {
289 			System.out.println("\n-- Matched 0 orgs");
290 
291 		} else {
292 			System.out.println("\n-- Matched " + orgs.size()
293 					+ " organisations --\n");
294 
295 			// then step through them
296 			for (Iterator orgIter = orgs.iterator(); orgIter.hasNext();) {
297 				Organization org = (Organization) orgIter.next();
298 
299 				System.out.println("Org name: " + getName(org));
300 				System.out.println("Org description: " + getDescription(org));
301 				System.out.println("Org key id: " + getKey(org));
302 
303 				if (getName(org).indexOf(tempSrcOrgName) > -1) {
304 					toReturn.add(0, org);
305 				} else {
306 					toReturn.add(1, org);
307 				}
308 
309 				// Print spacer between organizations
310 				System.out.println("\n ============================== \n");
311 			}
312 		}// end else
313 
314 		return toReturn;
315 	}
316 
317 	private void deleteTempOrgs() {
318 
319 		try {
320 
321 			Key sOrgKey = sOrg.getKey();
322 			Key tOrgKey = tOrg.getKey();
323 
324 			System.out.println("\nDeleting temporary organizations with ids "
325 					+ sOrgKey + " and " + tOrgKey + "\n");
326 
327 			Collection<Key> keys = new ArrayList<Key>();
328 			keys.add(sOrgKey);
329 			keys.add(tOrgKey);
330 			BulkResponse response = blm.deleteOrganizations(keys);
331 
332 			Collection exceptions = response.getExceptions();
333 			if (exceptions == null) {
334 				Collection retKeys = response.getCollection();
335 				Iterator keyIter = retKeys.iterator();
336 				Key orgKey = null;
337 				while (keyIter.hasNext()) {
338 					orgKey = (javax.xml.registry.infomodel.Key) keyIter.next();
339 					String id = orgKey.getId();
340 					System.out.println("Organization with ID=" + id
341 							+ " was deleted");
342 				}
343 			}
344 		} catch (JAXRException jaxre) {
345 			jaxre.printStackTrace();
346 		}
347 	}
348 
349 	private static String getName(RegistryObject ro) throws JAXRException {
350 		if (ro != null && ro.getName() != null) {
351 			return ro.getName().getValue();
352 		}
353 		return "";
354 	}
355 
356 	private static String getDescription(RegistryObject ro)
357 			throws JAXRException {
358 		if (ro != null && ro.getDescription() != null) {
359 			return ro.getDescription().getValue();
360 		}
361 		return "";
362 	}
363 
364 	private static String getKey(RegistryObject ro) throws JAXRException {
365 		if (ro != null && ro.getKey() != null) {
366 			return ro.getKey().getId();
367 		}
368 		return "";
369 	}
370     
371     public static junit.framework.Test suite() {
372         return new JUnit4TestAdapter(JAXR030AssociationsTest.class);
373     }
374 }