001 /*
002 * Licensed to the Apache Software Foundation (ASF) under one or more
003 * contributor license agreements. See the NOTICE file distributed with
004 * this work for additional information regarding copyright ownership.
005 * The ASF licenses this file to You under the Apache License, Version 2.0
006 * (the "License"); you may not use this file except in compliance with
007 * the License. You may obtain a copy of the License at
008 *
009 * http://www.apache.org/licenses/LICENSE-2.0
010 *
011 * Unless required by applicable law or agreed to in writing, software
012 * distributed under the License is distributed on an "AS IS" BASIS,
013 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
014 * See the License for the specific language governing permissions and
015 * limitations under the License.
016 */
017 package org.apache.commons.discovery.ant;
018
019 import java.util.LinkedList;
020 import java.util.List;
021
022 import org.apache.commons.discovery.ResourceNameIterator;
023 import org.apache.commons.discovery.jdk.JDKHooks;
024 import org.apache.commons.discovery.resource.DiscoverResources;
025
026 /**
027 * Small ant task that will use discovery to locate a particular impl.
028 * and display all values.
029 *
030 * You can execute this and save it with an id, then other classes can use it.
031 */
032 public class ServiceDiscoveryTask {
033
034 String name;
035
036 int debug=0;
037
038 String[] drivers = null;
039
040 /**
041 * Sets the service name has to be discovered.
042 *
043 * @param name The service name has to be discovered.
044 */
045 public void setServiceName(String name) {
046 this.name=name;
047 }
048
049 /**
050 * Sets the debug level.
051 *
052 * @param i The debug level
053 */
054 public void setDebug(int i) {
055 this.debug=i;
056 }
057
058 /**
059 * Returns the discovered SPIs name.
060 *
061 * @return The discovered SPIs name
062 */
063 public String[] getServiceInfo() {
064 return drivers;
065 }
066
067 /**
068 * Executes the Apache Ant task, discovering the set service name
069 *
070 * @throws Exception if any error occurs
071 */
072 public void execute() throws Exception {
073 System.out.printf("Discovering service '%s'...%n", name);
074
075 DiscoverResources disc = new DiscoverResources();
076 disc.addClassLoader( JDKHooks.getJDKHooks().getThreadContextClassLoader() );
077 disc.addClassLoader( this.getClass().getClassLoader() );
078
079 ResourceNameIterator iterator = disc.findResources(name);
080
081 List<String> resources = new LinkedList<String>();
082 while (iterator.hasNext()) {
083 String resourceInfo = iterator.nextResourceName();
084 resources.add(resourceInfo);
085 if (debug > 0) {
086 System.out.printf("Found '%s'%n", resourceInfo);
087 }
088 }
089
090 drivers = new String[resources.size()];
091 resources.toArray(drivers);
092 }
093
094 }