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.*; 26 27 /** 28 * A mechanism for accessing service providers via JVMCI. 29 */ 30 public final class Services { 31 32 private Services() { 33 } 34 35 /** 36 * Gets an {@link Iterable} of the JVMCI providers available for a given service. 37 */ 38 public static <S> Iterable<S> load(Class<S> service) { 39 return ServiceLoader.load(service); 40 } 41 42 /** 43 * Gets the JVMCI provider for a given service for which at most one provider must be available. 44 * 45 * @param service the service whose provider is being requested 46 * @param required specifies if an {@link InternalError} should be thrown if no provider of 47 * {@code service} is available 48 */ 49 public static <S> S loadSingle(Class<S> service, boolean required) { 50 Iterable<S> providers = ServiceLoader.load(service); 51 S singleProvider = null; 52 try { 53 for (Iterator<S> it = providers.iterator(); it.hasNext();) { 54 singleProvider = it.next(); 55 if (it.hasNext()) { 56 throw new InternalError(String.format("Multiple %s providers found", service.getName())); 57 } 58 } 59 } catch (ServiceConfigurationError e) { 60 // If the service is required we will bail out below. 61 } 62 if (singleProvider == null && required) { 63 String javaHome = System.getProperty("java.home"); 64 String vmName = System.getProperty("java.vm.name"); 65 Formatter errorMessage = new Formatter(); 66 errorMessage.format("The VM does not expose required service %s.%n", service.getName()); 67 errorMessage.format("Currently used Java home directory is %s.%n", javaHome); 68 errorMessage.format("Currently used VM configuration is: %s", vmName); 69 throw new UnsupportedOperationException(errorMessage.toString()); 70 } 71 return singleProvider; 72 } 73 }