1 /* 2 * Copyright (c) 2014, 2015, Oracle and/or its affiliates. All rights reserved. 3 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. 4 * 5 * This code is free software; you can redistribute it and/or modify it 6 * under the terms of the GNU General Public License version 2 only, as 7 * published by the Free Software Foundation. 8 * 9 * This code is distributed in the hope that it will be useful, but WITHOUT 10 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or 11 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License 12 * version 2 for more details (a copy is included in the LICENSE file that 13 * accompanied this code). 14 * 15 * You should have received a copy of the GNU General Public License version 16 * 2 along with this work; if not, write to the Free Software Foundation, 17 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. 18 * 19 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA 20 * or visit www.oracle.com if you need additional information or have any 21 * questions. 22 */ 23 package jdk.vm.ci.service; 24 25 import java.util.Formatter; 26 import java.util.Iterator; 27 import java.util.ServiceConfigurationError; 28 import java.util.ServiceLoader; 29 30 /** 31 * A mechanism for accessing service providers via JVMCI. 32 */ 33 public final class Services { 34 35 private Services() { 36 } 37 38 /** 39 * Gets an {@link Iterable} of the JVMCI providers available for a given service. 40 */ 41 public static <S> Iterable<S> load(Class<S> service) { 42 return ServiceLoader.load(service); 43 } 44 45 /** 46 * Gets the JVMCI provider for a given service for which at most one provider must be available. 47 * 48 * @param service the service whose provider is being requested 49 * @param required specifies if an {@link InternalError} should be thrown if no provider of 50 * {@code service} is available 51 */ 52 public static <S> S loadSingle(Class<S> service, boolean required) { 53 Iterable<S> providers = ServiceLoader.load(service); 54 S singleProvider = null; 55 try { 56 for (Iterator<S> it = providers.iterator(); it.hasNext();) { 57 singleProvider = it.next(); 58 if (it.hasNext()) { 59 throw new InternalError(String.format("Multiple %s providers found", service.getName())); 60 } 61 } 62 } catch (ServiceConfigurationError e) { 63 // If the service is required we will bail out below. 64 } 65 if (singleProvider == null && required) { 66 String javaHome = System.getProperty("java.home"); 67 String vmName = System.getProperty("java.vm.name"); 68 Formatter errorMessage = new Formatter(); 69 errorMessage.format("The VM does not expose required service %s.%n", service.getName()); 70 errorMessage.format("Currently used Java home directory is %s.%n", javaHome); 71 errorMessage.format("Currently used VM configuration is: %s", vmName); 72 throw new UnsupportedOperationException(errorMessage.toString()); 73 } 74 return singleProvider; 75 } 76 }