java.security.PrivilegedAction Java Examples

The following examples show how to use java.security.PrivilegedAction. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: ProcessImpl.java    From JDKSourceCode1.8 with MIT License 6 votes vote down vote up
/**
 * Open a file for writing. If {@code append} is {@code true} then the file
 * is opened for atomic append directly and a FileOutputStream constructed
 * with the resulting handle. This is because a FileOutputStream created
 * to append to a file does not open the file in a manner that guarantees
 * that writes by the child process will be atomic.
 */
private static FileOutputStream newFileOutputStream(File f, boolean append)
    throws IOException
{
    if (append) {
        String path = f.getPath();
        SecurityManager sm = System.getSecurityManager();
        if (sm != null)
            sm.checkWrite(path);
        long handle = openForAtomicAppend(path);
        final FileDescriptor fd = new FileDescriptor();
        fdAccess.setHandle(fd, handle);
        return AccessController.doPrivileged(
            new PrivilegedAction<FileOutputStream>() {
                public FileOutputStream run() {
                    return new FileOutputStream(fd);
                }
            }
        );
    } else {
        return new FileOutputStream(f);
    }
}
 
Example #2
Source File: ResourceLeakDetectorFactory.java    From netty-4.1.22 with Apache License 2.0 6 votes vote down vote up
DefaultResourceLeakDetectorFactory() {
    String customLeakDetector;
    try {
        customLeakDetector = AccessController.doPrivileged(new PrivilegedAction<String>() {
            @Override
            public String run() {
                return SystemPropertyUtil.get("io.netty.customResourceLeakDetector");
            }
        });
    } catch (Throwable cause) {
        logger.error("Could not access System property: io.netty.customResourceLeakDetector", cause);
        customLeakDetector = null;
    }
    if (customLeakDetector == null) {
        obsoleteCustomClassConstructor = customClassConstructor = null;
    } else {
        obsoleteCustomClassConstructor = obsoleteCustomClassConstructor(customLeakDetector);
        customClassConstructor = customClassConstructor(customLeakDetector);
    }
}
 
Example #3
Source File: RTFReader.java    From jdk8u-jdk with GNU General Public License v2.0 6 votes vote down vote up
/** Looks up a named character set. A character set is a 256-entry
 *  array of characters, mapping unsigned byte values to their Unicode
 *  equivalents. The character set is loaded if necessary.
 *
 *  @returns the character set
 */
public static Object
getCharacterSet(final String name)
    throws IOException
{
    char[] set = characterSets.get(name);
    if (set == null) {
        InputStream charsetStream = AccessController.doPrivileged(
                new PrivilegedAction<InputStream>() {
                    public InputStream run() {
                        return RTFReader.class.getResourceAsStream("charsets/" + name + ".txt");
                    }
                });
        set = readCharset(charsetStream);
        defineCharacterSet(name, set);
    }
    return set;
}
 
Example #4
Source File: Finalizer.java    From dragonwell8_jdk with GNU General Public License v2.0 6 votes vote down vote up
private static void forkSecondaryFinalizer(final Runnable proc) {
    AccessController.doPrivileged(
        new PrivilegedAction<Void>() {
            public Void run() {
                ThreadGroup tg = Thread.currentThread().getThreadGroup();
                for (ThreadGroup tgn = tg;
                     tgn != null;
                     tg = tgn, tgn = tg.getParent());
                Thread sft = new Thread(tg, proc, "Secondary finalizer");

                if (TenantGlobals.isDataIsolationEnabled() && TenantContainer.current() != null) {
                    SharedSecrets.getTenantAccess()
                            .registerServiceThread(TenantContainer.current(), sft);
                }

                sft.start();
                try {
                    sft.join();
                } catch (InterruptedException x) {
                    Thread.currentThread().interrupt();
                }
                return null;
            }});
}
 
Example #5
Source File: LimitedDoPrivilegedWithThread.java    From jdk8u-jdk with GNU General Public License v2.0 6 votes vote down vote up
public void runTest(AccessControlContext acc, Permission perm,
        boolean expectACE, int id) {

    AccessController.doPrivileged(
            (PrivilegedAction) () -> {
                try {
                    AccessController.getContext().checkPermission(P1);
                } catch (AccessControlException ace) {
                    catchACE = true;
                }
                if (catchACE ^ expectACE) {
                    throw new RuntimeException("test" + id + " failed");
                }
                return null;
            }, acc, perm);
}
 
Example #6
Source File: AppContext.java    From Bytecoder with Apache License 2.0 6 votes vote down vote up
/**
 * Constructor for AppContext.  This method is <i>not</i> public,
 * nor should it ever be used as such.  The proper way to construct
 * an AppContext is through the use of SunToolkit.createNewAppContext.
 * A ThreadGroup is created for the new AppContext, a Thread is
 * created within that ThreadGroup, and that Thread calls
 * SunToolkit.createNewAppContext before calling anything else.
 * That creates both the new AppContext and its EventQueue.
 *
 * @param   threadGroup     The ThreadGroup for the new AppContext
 * @see     sun.awt.SunToolkit
 * @since   1.2
 */
AppContext(ThreadGroup threadGroup) {
    numAppContexts.incrementAndGet();

    this.threadGroup = threadGroup;
    threadGroup2appContext.put(threadGroup, this);

    this.contextClassLoader =
         AccessController.doPrivileged(new PrivilegedAction<ClassLoader>() {
                public ClassLoader run() {
                    return Thread.currentThread().getContextClassLoader();
                }
            });

    // Initialize push/pop lock and its condition to be used by all the
    // EventQueues within this AppContext
    Lock eventQueuePushPopLock = new ReentrantLock();
    put(EVENT_QUEUE_LOCK_KEY, eventQueuePushPopLock);
    Condition eventQueuePushPopCond = eventQueuePushPopLock.newCondition();
    put(EVENT_QUEUE_COND_KEY, eventQueuePushPopCond);
}
 
Example #7
Source File: RepaintManager.java    From Bytecoder with Apache License 2.0 6 votes vote down vote up
/**
 * Validate all of the components that have been marked invalid.
 * @see #addInvalidComponent
 */
public void validateInvalidComponents() {
    final java.util.List<Component> ic;
    synchronized(this) {
        if (invalidComponents == null) {
            return;
        }
        ic = invalidComponents;
        invalidComponents = null;
    }
    int n = ic.size();
    for(int i = 0; i < n; i++) {
        final Component c = ic.get(i);
        AccessControlContext stack = AccessController.getContext();
        AccessControlContext acc =
            AWTAccessor.getComponentAccessor().getAccessControlContext(c);
        javaSecurityAccess.doIntersectionPrivilege(
            new PrivilegedAction<Void>() {
                public Void run() {
                    c.validate();
                    return null;
                }
            }, stack, acc);
    }
}
 
Example #8
Source File: RepaintManager.java    From TencentKona-8 with GNU General Public License v2.0 6 votes vote down vote up
void nativeQueueSurfaceDataRunnable(AppContext appContext,
                                    final Component c, final Runnable r)
{
    synchronized(this) {
        if (runnableList == null) {
            runnableList = new LinkedList<Runnable>();
        }
        runnableList.add(new Runnable() {
            public void run() {
                AccessControlContext stack = AccessController.getContext();
                AccessControlContext acc =
                    AWTAccessor.getComponentAccessor().getAccessControlContext(c);
                javaSecurityAccess.doIntersectionPrivilege(new PrivilegedAction<Void>() {
                    public Void run() {
                        r.run();
                        return null;
                    }
                }, stack, acc);
            }
        });
    }
    scheduleProcessingRunnable(appContext);
}
 
Example #9
Source File: PreserveCombinerTest.java    From TencentKona-8 with GNU General Public License v2.0 6 votes vote down vote up
public static void main(String[]args) throws Exception {
    final DomainCombiner dc = new DomainCombiner() {
        @Override
        public ProtectionDomain[] combine(ProtectionDomain[] currentDomains, ProtectionDomain[] assignedDomains) {
            return currentDomains; // basically a no-op
        }
    };

    // Get an instance of the saved ACC
    AccessControlContext saved = AccessController.getContext();
    // Simulate the stack ACC with a DomainCombiner attached
    AccessControlContext stack = new AccessControlContext(AccessController.getContext(), dc);

    // Now try to run JavaSecurityAccess.doIntersectionPrivilege() and assert
    // whether the DomainCombiner from the stack ACC is preserved
    boolean ret = SharedSecrets.getJavaSecurityAccess().doIntersectionPrivilege(new PrivilegedAction<Boolean>() {
        @Override
        public Boolean run() {
            return dc == AccessController.getContext().getDomainCombiner();
        }
    }, stack, saved);

    if (!ret) {
        System.exit(1);
    }
}
 
Example #10
Source File: AppContext.java    From jdk8u60 with GNU General Public License v2.0 6 votes vote down vote up
static void stopEventDispatchThreads() {
    for (AppContext appContext: getAppContexts()) {
        if (appContext.isDisposed()) {
            continue;
        }
        Runnable r = new PostShutdownEventRunnable(appContext);
        // For security reasons EventQueue.postEvent should only be called
        // on a thread that belongs to the corresponding thread group.
        if (appContext != AppContext.getAppContext()) {
            // Create a thread that belongs to the thread group associated
            // with the AppContext and invokes EventQueue.postEvent.
            PrivilegedAction<Thread> action = new CreateThreadAction(appContext, r);
            Thread thread = AccessController.doPrivileged(action);
            thread.start();
        } else {
            r.run();
        }
    }
}
 
Example #11
Source File: EventQueue.java    From jdk8u-jdk with GNU General Public License v2.0 6 votes vote down vote up
final void initDispatchThread() {
    pushPopLock.lock();
    try {
        if (dispatchThread == null && !threadGroup.isDestroyed() && !appContext.isDisposed()) {
            dispatchThread = AccessController.doPrivileged(
                new PrivilegedAction<EventDispatchThread>() {
                    public EventDispatchThread run() {
                        EventDispatchThread t =
                            new EventDispatchThread(threadGroup,
                                                    name,
                                                    EventQueue.this);
                        t.setContextClassLoader(classLoader);
                        t.setPriority(Thread.NORM_PRIORITY + 1);
                        t.setDaemon(false);
                        AWTAutoShutdown.getInstance().notifyThreadBusy(t);
                        return t;
                    }
                }
            );
            dispatchThread.start();
        }
    } finally {
        pushPopLock.unlock();
    }
}
 
Example #12
Source File: DefaultMBeanServerInterceptor.java    From jdk8u-jdk with GNU General Public License v2.0 6 votes vote down vote up
private static void checkMBeanTrustPermission(final Class<?> theClass)
    throws SecurityException {
    SecurityManager sm = System.getSecurityManager();
    if (sm != null) {
        Permission perm = new MBeanTrustPermission("register");
        PrivilegedAction<ProtectionDomain> act =
            new PrivilegedAction<ProtectionDomain>() {
                public ProtectionDomain run() {
                    return theClass.getProtectionDomain();
                }
            };
        ProtectionDomain pd = AccessController.doPrivileged(act);
        AccessControlContext acc =
            new AccessControlContext(new ProtectionDomain[] { pd });
        sm.checkPermission(perm, acc);
    }
}
 
Example #13
Source File: MarshalledObject.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Creates a new <code>MarshalledObjectInputStream</code> that
 * reads its objects from <code>objIn</code> and annotations
 * from <code>locIn</code>.  If <code>locIn</code> is
 * <code>null</code>, then all annotations will be
 * <code>null</code>.
 */
MarshalledObjectInputStream(InputStream objIn, InputStream locIn,
            ObjectInputFilter filter)
    throws IOException
{
    super(objIn);
    this.locIn = (locIn == null ? null : new ObjectInputStream(locIn));
    if (filter != null) {
        AccessController.doPrivileged(new PrivilegedAction<Void>() {
            @Override
            public Void run() {
                ObjectInputFilter.Config.setObjectInputFilter(MarshalledObjectInputStream.this, filter);
                if (MarshalledObjectInputStream.this.locIn != null) {
                    ObjectInputFilter.Config.setObjectInputFilter(MarshalledObjectInputStream.this.locIn, filter);
                }
                return null;
            }
        });
    }
}
 
Example #14
Source File: PageContextImpl.java    From Tomcat7.0.67 with Apache License 2.0 6 votes vote down vote up
@Override
public Object findAttribute(final String name) {
    if (SecurityUtil.isPackageProtectionEnabled()) {
        return AccessController.doPrivileged(
                new PrivilegedAction<Object>() {
            @Override
            public Object run() {
                if (name == null) {
                    throw new NullPointerException(Localizer
                            .getMessage("jsp.error.attribute.null_name"));
                }

                return doFindAttribute(name);
            }
        });
    } else {
        if (name == null) {
            throw new NullPointerException(Localizer
                    .getMessage("jsp.error.attribute.null_name"));
        }

        return doFindAttribute(name);
    }
}
 
Example #15
Source File: JRELocaleProviderAdapter.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Getter methods for java.util.spi.* providers
 */
@Override
public CurrencyNameProvider getCurrencyNameProvider() {
    if (currencyNameProvider == null) {
        CurrencyNameProvider provider = AccessController.doPrivileged(
            (PrivilegedAction<CurrencyNameProvider>) () ->
                new CurrencyNameProviderImpl(
                    getAdapterType(),
                    getLanguageTagSet("CurrencyNames")));

        synchronized (this) {
            if (currencyNameProvider == null) {
                currencyNameProvider = provider;
            }
        }
    }
    return currencyNameProvider;
}
 
Example #16
Source File: ObjectStreamClass.java    From openjdk-jdk8u with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Returns the value contained by this EntryFuture, blocking if
 * necessary until a value is set.
 */
synchronized Object get() {
    boolean interrupted = false;
    while (entry == unset) {
        try {
            wait();
        } catch (InterruptedException ex) {
            interrupted = true;
        }
    }
    if (interrupted) {
        AccessController.doPrivileged(
            new PrivilegedAction<Void>() {
                public Void run() {
                    Thread.currentThread().interrupt();
                    return null;
                }
            }
        );
    }
    return entry;
}
 
Example #17
Source File: ClassLoader.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 6 votes vote down vote up
private void checkPackageAccess(Class<?> cls, ProtectionDomain pd) {
    final SecurityManager sm = System.getSecurityManager();
    if (sm != null) {
        if (ReflectUtil.isNonPublicProxyClass(cls)) {
            for (Class<?> intf: cls.getInterfaces()) {
                checkPackageAccess(intf, pd);
            }
            return;
        }

        final String name = cls.getName();
        final int i = name.lastIndexOf('.');
        if (i != -1) {
            AccessController.doPrivileged(new PrivilegedAction<Void>() {
                public Void run() {
                    sm.checkPackageAccess(name.substring(0, i));
                    return null;
                }
            }, new AccessControlContext(new ProtectionDomain[] {pd}));
        }
    }
    domains.add(pd);
}
 
Example #18
Source File: Control.java    From TencentKona-8 with GNU General Public License v2.0 6 votes vote down vote up
private String combineSafe(Set<String> values) {
    if (context == null) {
        // VM events requires no access control context
        return combine(values);
    }
    return AccessController.doPrivileged(new PrivilegedAction<String>() {
        @Override
        public String run() {
            try {
                combine(Collections.unmodifiableSet(values));
            } catch (Throwable t) {
                // Prevent malicious user to propagate exception callback in the wrong context
                Logger.log(LogTag.JFR_SETTING, LogLevel.WARN, "Exception occured when combining " + values + " for " + getClass());
            }
            return null;
        }
    }, context);
}
 
Example #19
Source File: DefaultMBeanServerInterceptor.java    From openjdk-jdk8u with GNU General Public License v2.0 6 votes vote down vote up
private static void checkMBeanTrustPermission(final Class<?> theClass)
    throws SecurityException {
    SecurityManager sm = System.getSecurityManager();
    if (sm != null) {
        Permission perm = new MBeanTrustPermission("register");
        PrivilegedAction<ProtectionDomain> act =
            new PrivilegedAction<ProtectionDomain>() {
                public ProtectionDomain run() {
                    return theClass.getProtectionDomain();
                }
            };
        ProtectionDomain pd = AccessController.doPrivileged(act);
        AccessControlContext acc =
            new AccessControlContext(new ProtectionDomain[] { pd });
        sm.checkPermission(perm, acc);
    }
}
 
Example #20
Source File: LimitedDoPrivilegedWithThread.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
public static void main(String args[]) {
    //parent thread without any permission
    AccessController.doPrivileged(
            (PrivilegedAction) () -> {
                Thread ct = new Thread(
                        new ChildThread(PROPERTYPERM, FILEPERM));
                ct.start();
                try {
                    ct.join();
                } catch (InterruptedException ie) {
                    Thread.currentThread().interrupt();
                    ie.printStackTrace();
                    throw new RuntimeException("Unexpected InterruptedException");
                }
                return null;
            }, ACC);
}
 
Example #21
Source File: CLDRLocaleProviderAdapter.java    From Bytecoder with Apache License 2.0 6 votes vote down vote up
@Override
public TimeZoneNameProvider getTimeZoneNameProvider() {
    if (timeZoneNameProvider == null) {
        TimeZoneNameProvider provider = AccessController.doPrivileged(
            (PrivilegedAction<TimeZoneNameProvider>) () ->
                new CLDRTimeZoneNameProviderImpl(
                    getAdapterType(),
                    getLanguageTagSet("TimeZoneNames")));

        synchronized (this) {
            if (timeZoneNameProvider == null) {
                timeZoneNameProvider = provider;
            }
        }
    }
    return timeZoneNameProvider;
}
 
Example #22
Source File: TestJHSSecurity.java    From hadoop with Apache License 2.0 6 votes vote down vote up
private MRClientProtocol getMRClientProtocol(Token token,
    final InetSocketAddress hsAddress, String user, final Configuration conf) {
  UserGroupInformation ugi = UserGroupInformation.createRemoteUser(user);
  ugi.addToken(ConverterUtils.convertFromYarn(token, hsAddress));

  final YarnRPC rpc = YarnRPC.create(conf);
  MRClientProtocol hsWithDT = ugi
      .doAs(new PrivilegedAction<MRClientProtocol>() {

        @Override
        public MRClientProtocol run() {
          return (MRClientProtocol) rpc.getProxy(HSClientProtocol.class,
              hsAddress, conf);
        }
      });
  return hsWithDT;
}
 
Example #23
Source File: ApplicationContextAwareProcessor.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
@Override
public Object postProcessBeforeInitialization(final Object bean, String beanName) throws BeansException {
	AccessControlContext acc = null;

	if (System.getSecurityManager() != null &&
			(bean instanceof EnvironmentAware || bean instanceof EmbeddedValueResolverAware ||
					bean instanceof ResourceLoaderAware || bean instanceof ApplicationEventPublisherAware ||
					bean instanceof MessageSourceAware || bean instanceof ApplicationContextAware)) {
		acc = this.applicationContext.getBeanFactory().getAccessControlContext();
	}

	if (acc != null) {
		AccessController.doPrivileged(new PrivilegedAction<Object>() {
			@Override
			public Object run() {
				invokeAwareInterfaces(bean);
				return null;
			}
		}, acc);
	}
	else {
		invokeAwareInterfaces(bean);
	}

	return bean;
}
 
Example #24
Source File: SSLSocketImpl.java    From jdk8u60 with GNU General Public License v2.0 6 votes vote down vote up
@Override
public void run() {
    // Don't need to synchronize, as it only runs in one thread.
    for (Map.Entry<HandshakeCompletedListener,AccessControlContext>
        entry : targets) {

        final HandshakeCompletedListener l = entry.getKey();
        AccessControlContext acc = entry.getValue();
        AccessController.doPrivileged(new PrivilegedAction<Void>() {
            @Override
            public Void run() {
                l.handshakeCompleted(event);
                return null;
            }
        }, acc);
    }
}
 
Example #25
Source File: OptimisticTypesPersistence.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
private static File createCacheDirPrivileged(final File baseDir) {
    return AccessController.doPrivileged(new PrivilegedAction<File>() {
        @Override
        public File run() {
            final String versionDirName;
            try {
                versionDirName = getVersionDirName();
            } catch(final Exception e) {
                reportError("Failed to calculate version dir name", e);
                return null;
            }
            final File versionDir = new File(baseDir, versionDirName);
            if (isSymbolicLink(versionDir)) {
                return null;
            }
            versionDir.mkdirs();
            if (versionDir.isDirectory()) {
                //FIXME:Logger is disabled as Context.getContext() always returns null here because global scope object will not be created
                //by the time this method gets invoked
                getLogger().info("Optimistic type persistence directory is " + versionDir);
                return versionDir;
            }
            getLogger().warning("Could not create optimistic type persistence directory " + versionDir);
            return null;
        }
    });
}
 
Example #26
Source File: Logger.java    From jdk1.8-source-analysis with Apache License 2.0 5 votes vote down vote up
private static ResourceBundle findSystemResourceBundle(final Locale locale) {
    // the resource bundle is in a restricted package
    return AccessController.doPrivileged(new PrivilegedAction<ResourceBundle>() {
        @Override
        public ResourceBundle run() {
            try {
                return ResourceBundle.getBundle(SYSTEM_LOGGER_RB_NAME,
                                                locale,
                                                ClassLoader.getSystemClassLoader());
            } catch (MissingResourceException e) {
                throw new InternalError(e.toString());
            }
        }
    });
}
 
Example #27
Source File: TCPTransport.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 5 votes vote down vote up
public void run() {
    Thread t = Thread.currentThread();
    String name = t.getName();
    try {
        t.setName("RMI TCP Connection(" +
                  connectionCount.incrementAndGet() +
                  ")-" + remoteHost);
        AccessController.doPrivileged((PrivilegedAction<Void>)() -> {
            run0();
            return null;
        }, NOPERMS_ACC);
    } finally {
        t.setName(name);
    }
}
 
Example #28
Source File: URLClassLoader.java    From jdk8u-jdk with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Creates a new instance of URLClassLoader for the specified
 * URLs and default parent class loader. If a security manager is
 * installed, the {@code loadClass} method of the URLClassLoader
 * returned by this method will invoke the
 * {@code SecurityManager.checkPackageAccess} before
 * loading the class.
 *
 * @param urls the URLs to search for classes and resources
 * @exception  NullPointerException if {@code urls} is {@code null}.
 * @return the resulting class loader
 */
public static URLClassLoader newInstance(final URL[] urls) {
    // Save the caller's context
    final AccessControlContext acc = AccessController.getContext();
    // Need a privileged block to create the class loader
    URLClassLoader ucl = AccessController.doPrivileged(
        new PrivilegedAction<URLClassLoader>() {
            public URLClassLoader run() {
                return new FactoryURLClassLoader(urls, acc);
            }
        });
    return ucl;
}
 
Example #29
Source File: ClientNotifForwarder.java    From dragonwell8_jdk with GNU General Public License v2.0 5 votes vote down vote up
private final ClassLoader setContextClassLoader(final ClassLoader loader) {
    final AccessControlContext ctxt = ClientNotifForwarder.this.acc;
    // if ctxt is null, log a config message and throw a
    // SecurityException.
    if (ctxt == null) {
        logOnce("AccessControlContext must not be null.",null);
        throw new SecurityException("AccessControlContext must not be null");
    }
    return AccessController.doPrivileged(
        new PrivilegedAction<ClassLoader>() {
            public ClassLoader run() {
                try {
                    // get context class loader - may throw
                    // SecurityException - though unlikely.
                    final ClassLoader previous =
                        Thread.currentThread().getContextClassLoader();

                    // if nothing needs to be done, break here...
                    if (loader == previous) return previous;

                    // reset context class loader - may throw
                    // SecurityException
                    Thread.currentThread().setContextClassLoader(loader);
                    return previous;
                } catch (SecurityException x) {
                    logOnce("Permission to set ContextClassLoader missing. " +
                            "Notifications will not be dispatched. " +
                            "Please check your Java policy configuration: " +
                            x, x);
                    throw x;
                }
            }
        }, ctxt);
}
 
Example #30
Source File: FactoryFinder.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 5 votes vote down vote up
private static <T> T findServiceProvider(final Class<T> type)
    throws TransformerFactoryConfigurationError
{
  try {
        return AccessController.doPrivileged(new PrivilegedAction<T>() {
            public T run() {
                final ServiceLoader<T> serviceLoader = ServiceLoader.load(type);
                final Iterator<T> iterator = serviceLoader.iterator();
                if (iterator.hasNext()) {
                    return iterator.next();
                } else {
                    return null;
                }
             }
        });
    } catch(ServiceConfigurationError e) {
        // It is not possible to wrap an error directly in
        // FactoryConfigurationError - so we need to wrap the
        // ServiceConfigurationError in a RuntimeException.
        // The alternative would be to modify the logic in
        // FactoryConfigurationError to allow setting a
        // Throwable as the cause, but that could cause
        // compatibility issues down the road.
        final RuntimeException x = new RuntimeException(
                "Provider for " + type + " cannot be created", e);
        final TransformerFactoryConfigurationError error =
                new TransformerFactoryConfigurationError(x, x.getMessage());
        throw error;
    }
}