Privileged factory method.

@param bundle bundle to be used for class loading. Cannot be null.
@param parent parent class loader

@return created bundle class loader

@see BundleClassLoader#BundleClassLoader(Bundle,ClassLoader)
516876
public static BundleClassLoader newPriviledged( final Bundle bundle, final ClassLoader parent )
    {
        return AccessController.doPrivileged( new PrivilegedAction<BundleClassLoader>()
        {
            public BundleClassLoader run()
            {
                return new BundleClassLoader( bundle, parent );
            }
        } );
    }
915264
public static <T1> TypeAdapterFactory newTypeHierarchyFactory(
      final Class<T1> clazz, final TypeAdapter<T1> typeAdapter) {
    return new TypeAdapterFactory() {
      @SuppressWarnings("unchecked")
      @Override public <T2> TypeAdapter<T2> create(Gson gson, TypeToken<T2> typeToken) {
        final Class<? super T2> requestedType = typeToken.getRawType();
        if (!clazz.isAssignableFrom(requestedType)) {
          return null;
        }
        return (TypeAdapter<T2>) new TypeAdapter<T1>() {
          @Override public void write(JsonWriter out, T1 value) throws IOException {
            typeAdapter.write(out, value);
          }

          @Override public T1 read(JsonReader in) throws IOException {
            T1 result = typeAdapter.read(in);
            if (result != null && !requestedType.isInstance(result)) {
              throw new JsonSyntaxException("Expected a " + requestedType.getName()
                  + " but was " + result.getClass().getName());
            }
            return result;
          }
        };
      }
      @Override public String toString() {
        return "Factory[typeHierarchy=" + clazz.getName() + ",adapter=" + typeAdapter + "]";
      }
    };
  }
38504
public static Class getGenericClassFromParent(Object parent) {
		return (Class) ((ParameterizedType) parent.getClass().getGenericSuperclass()).getActualTypeArguments()[0];
	}
874448
private void startBundle( final Bundle bundle )
        throws BundleException
    {
        // Don't start if bundle already active
        int bundleState = bundle.getState();
        if( bundleState == Bundle.ACTIVE )
        {
            return;
        }

        // Don't start if bundle is a fragment bundle
        Dictionary bundleHeaders = bundle.getHeaders();
        if( bundleHeaders.get( Constants.FRAGMENT_HOST ) != null )
        {
            return;
        }

        // Start bundle
        bundle.start();

        bundleState = bundle.getState();
        if( bundleState != Bundle.ACTIVE )
        {
            long bundleId = bundle.getBundleId();
            String bundleName = bundle.getSymbolicName();
            String bundleStateStr = bundleStateToString( bundleState );
            throw new BundleException(
                "Bundle (" + bundleId + ", " + bundleName + ") not started (still " + bundleStateStr + ")"
            );
        }
    }
1042630
public static DynamicClassLoader create(ClassLoader parent, PathImpl path)
  {
    DynamicClassLoader loader = new DynamicClassLoader(parent);

    LibraryLoader dirLoader = new LibraryLoader(loader, path);
    dirLoader.init();

    loader.init();
    
    return loader;
  }
1049335
@Override
	public void setup(AbstractInvokable parent) {
		@SuppressWarnings("unchecked")
		final ReduceFunction<IT> red = BatchTask.instantiateUserCode(this.config, userCodeClassLoader, ReduceFunction.class);
		this.reducer = red;
		FunctionUtils.setFunctionRuntimeContext(red, getUdfRuntimeContext());

		TypeSerializerFactory<IT> serializerFactory = this.config.getInputSerializer(0, userCodeClassLoader);
		this.serializer = serializerFactory.getSerializer();

		if (LOG.isDebugEnabled()) {
			LOG.debug("ChainedAllReduceDriver object reuse: " + (this.objectReuseEnabled ? "ENABLED" : "DISABLED") + ".");
		}
	}
448812
public static DynamicClassLoader create(ClassLoader parent,
                                          PathImpl classDir, PathImpl sourceDir,
                                          String args, String encoding)
  {
    DynamicClassLoader loader = new DynamicClassLoader(parent);
    loader.addLoader(new CompilingLoader(loader, classDir, sourceDir, args, encoding));

    loader.init();
    
    return loader;
  }
141181
@SuppressFBWarnings("DP_CREATE_CLASSLOADER_INSIDE_DO_PRIVILEGED") // TODO: clarify and use service loader instead
    public static TerminalFactory loadTerminalFactory(String jar, String classname, String type, String arg) throws NoSuchAlgorithmException {
        try {
            // To support things like host:port pairs, urldecode the arguments component if provided
            if (arg != null) {
                arg = URLDecoder.decode(arg, "UTF-8");
            }
            final TerminalFactory tf;
            final Class<?> cls; // XXX: stricter type
            if (jar != null) {
                // Specify class loader
                URLClassLoader loader = new URLClassLoader(new URL[]{new File(jar).toURI().toURL()}, TerminalManager.class.getClassLoader());
                // Load custom provider
                cls = Class.forName(classname, true, loader);
            } else {
                // Load provider
                cls = Class.forName(classname);
            }
            Provider p = (Provider) cls.getConstructor().newInstance();
            tf = TerminalFactory.getInstance(type == null ? "PC/SC" : type, arg, p);
            return tf;
        } catch (UnsupportedEncodingException | MalformedURLException | ClassNotFoundException | InstantiationException | IllegalAccessException | IllegalArgumentException | InvocationTargetException | NoSuchMethodException | SecurityException e) {
            throw new NoSuchAlgorithmException("Could not load " + classname + ": " + e.getMessage());
        } catch (NoSuchAlgorithmException e) {
            if (e.getCause() != null) {
                Class<?> cause = e.getCause().getClass();
                if (cause.equals(java.lang.UnsupportedOperationException.class)) {
                    throw new NoSuchAlgorithmException(e.getCause().getMessage());
                }
                if (cause.equals(java.lang.UnsatisfiedLinkError.class)) {
                    throw new NoSuchAlgorithmException(e.getCause().getMessage());
                }
            }
            throw e;
        }
    }
393034
@Override
	public Loader createLoader(ClassLoader parent) {

        if( log.isDebugEnabled() )
            log.debug("Creating Loader with parent class loader '" +
                       parent + "'");

        WebappLoader loader = new WebappLoader(parent);
        return (loader);

    }
604303
public ClassLoader beginContextClassLoader(ClassLoader raClassLoader) {
        return raClassLoader == null ? null
                        : AccessController.doPrivileged(new GetAndSetContextClassLoader(raClassLoader));
    }
1189569
protected void generateMethodCreateBundle(SourceWriter sourceWriter, TreeLogger logger,
      GeneratorContext context) {

    // method declaration
    sourceWriter.print("public <BUNDLE extends ");
    sourceWriter.print(NlsBundle.class.getSimpleName());
    sourceWriter.println("> BUNDLE createBundle(Class<BUNDLE> bundleInterface) {");
    sourceWriter.indent();

    // method body
    sourceWriter.println("BUNDLE bundle = getBundle(bundleInterface);");
    sourceWriter.println("if (bundle == null) {");
    sourceWriter.indent();
    // create and register
    generateBlockBundleCreation(sourceWriter, logger, context);
    sourceWriter.outdent();
    sourceWriter.println("}");

    sourceWriter.println("return bundle;");

    // end method...
    sourceWriter.outdent();
    sourceWriter.println("}");

  }
962263
public static EnvironmentClassLoader create(ClassLoader parent)
  {
    String id = null;
    
    return create(parent, id);
  }
66959
@SuppressWarnings("static-method")
	protected ClassLoader createClassLoader(Iterable<File> jarsAndFolders, ClassLoader parentClassLoader) {
		return new URLClassLoader(Iterables.toArray(Iterables.transform(jarsAndFolders, from -> {
			try {
				final URL url = from.toURI().toURL();
				assert url != null;
				return url;
			} catch (Exception e) {
				throw new RuntimeException(e);
			}
		}), URL.class), parentClassLoader);
	}
73034
private BundleContext getBundleContext(Bundle bundle, long timeout) {
        long endTime = System.currentTimeMillis() + timeout;
        BundleContext bc = null;
        while (bc == null) {
            bc = bundle.getBundleContext();
            if (bc == null) {
                if (System.currentTimeMillis() >= endTime) {
                    throw new TestContainerException(
                        "Unable to retrieve bundle context from bundle " + bundle);
                }
                try {
                    Thread.sleep(100);
                }
                catch (InterruptedException e) {
                    // Ignore
                }
            }
        }
        return bc;
    }
972638
private static ClassLoader pluginClassLoader(final Path plugin,
                                               final ClassLoader environment,
                                               final ClassLoader parent) {
    final URL url;
    try {
      url = plugin.toFile().toURI().toURL();
    } catch (MalformedURLException e) {
      throw new RuntimeException("Failed to load plugin jar " + plugin, e);
    }
    final ClassLoader providedClassLoader = new FilteringClassLoader(PROVIDED, environment, parent);
    return new URLClassLoader(new URL[]{ url }, providedClassLoader);
  }
894667
private static final CClassLoader createLoader(final ClassLoader parent,
			final String name) {
		try {
			return new CClassLoader(parent, name);
		} catch (final Exception ignore) {
			return null;
		}
	}
1280014
public static EnvironmentClassLoader create(ClassLoader parent, String id)
  {
    if (parent == null)
      parent = Thread.currentThread().getContextClassLoader();
    
    ClassLoader systemClassLoader = getSystemClassLoaderSafe();
    
    if (parent == null || isParent(parent, systemClassLoader))
      parent = systemClassLoader;
    
    String className = System.getProperty("caucho.environment.class.loader");

    if (className != null) {
      try {
        Class<?> cl = Thread.currentThread().getContextClassLoader().loadClass(className);
        Constructor<?> ctor = cl.getConstructor(new Class[] { ClassLoader.class, String.class});
        Object instance = ctor.newInstance(parent, id);

        return (EnvironmentClassLoader) instance;
      }
      catch (Exception e) {
        e.printStackTrace();
      }
    }

    return new EnvironmentClassLoader(parent, id);
  }