1 /*
2 * Licensed to the Apache Software Foundation (ASF) under one or more
3 * contributor license agreements. See the NOTICE file distributed with
4 * this work for additional information regarding copyright ownership.
5 * The ASF licenses this file to You under the Apache License, Version 2.0
6 * (the "License"); you may not use this file except in compliance with
7 * the License. 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.commons.discovery.ant;
18
19 import java.util.LinkedList;
20 import java.util.List;
21
22 import org.apache.commons.discovery.ResourceNameIterator;
23 import org.apache.commons.discovery.jdk.JDKHooks;
24 import org.apache.commons.discovery.resource.DiscoverResources;
25
26 /**
27 * Small ant task that will use discovery to locate a particular impl.
28 * and display all values.
29 *
30 * You can execute this and save it with an id, then other classes can use it.
31 */
32 public class ServiceDiscoveryTask {
33
34 String name;
35
36 int debug=0;
37
38 String[] drivers = null;
39
40 /**
41 * Sets the service name has to be discovered.
42 *
43 * @param name The service name has to be discovered.
44 */
45 public void setServiceName(String name) {
46 this.name=name;
47 }
48
49 /**
50 * Sets the debug level.
51 *
52 * @param i The debug level
53 */
54 public void setDebug(int i) {
55 this.debug=i;
56 }
57
58 /**
59 * Returns the discovered SPIs name.
60 *
61 * @return The discovered SPIs name
62 */
63 public String[] getServiceInfo() {
64 return drivers;
65 }
66
67 /**
68 * Executes the Apache Ant task, discovering the set service name
69 *
70 * @throws Exception if any error occurs
71 */
72 public void execute() throws Exception {
73 System.out.printf("Discovering service '%s'...%n", name);
74
75 DiscoverResources disc = new DiscoverResources();
76 disc.addClassLoader( JDKHooks.getJDKHooks().getThreadContextClassLoader() );
77 disc.addClassLoader( this.getClass().getClassLoader() );
78
79 ResourceNameIterator iterator = disc.findResources(name);
80
81 List<String> resources = new LinkedList<String>();
82 while (iterator.hasNext()) {
83 String resourceInfo = iterator.nextResourceName();
84 resources.add(resourceInfo);
85 if (debug > 0) {
86 System.out.printf("Found '%s'%n", resourceInfo);
87 }
88 }
89
90 drivers = new String[resources.size()];
91 resources.toArray(drivers);
92 }
93
94 }