Example usage for java.lang System getSecurityManager

List of usage examples for java.lang System getSecurityManager

Introduction

In this page you can find the example usage for java.lang System getSecurityManager.

Prototype

public static SecurityManager getSecurityManager() 

Source Link

Document

Gets the system-wide security manager.

Usage

From source file:com.sshtools.sshvnc.SshVNCPanel.java

private void initActions() {

    //  Create the action menu groups

    registerActionMenu(new SshToolsApplicationPanel.ActionMenu("File", "File",

            'f', 0));

    registerActionMenu(new SshToolsApplicationPanel.ActionMenu("Edit", "Edit",

            'e', 10));

    registerActionMenu(new SshToolsApplicationPanel.ActionMenu("View", "View",

            'v', 20));

    vncTab = new VNCTab( /*vnc*/);

    newAction = new NewAction() {

        public void actionPerformed(ActionEvent evt) {

            SshToolsConnectionProfile newProfile = newConnectionProfile(null);

            if (newProfile != null) {

                connect(newProfile, true);

            }/*w w w.  j  av  a  2s  . c o m*/

            else {

                log.info("New connection cancelled");

            }

        }

    };

    registerAction(newAction);

    closeAction = new CloseAction() {

        public void actionPerformed(ActionEvent evt) {

            closing = true;
            // Close on a thread to avoid blocking the event queue
            Thread thread = new Thread() {
                public void run() {
                    closeConnection(true);
                }
            };

            thread.start();

        }

    };

    registerAction(closeAction);

    refreshAction = new RefreshAction() {

        public void actionPerformed(ActionEvent evt) {

            refresh();

        }

    };

    registerAction(refreshAction);

    ctrlAltDelAction = new CtrlAltDelAction() {

        public void actionPerformed(ActionEvent evt) {

            try {

                vnc.sendCtrlAltDel();

            }

            catch (IOException ioe) {

                closeConnection(true);

                showErrorMessage(SshVNCPanel.this, "Error", ioe);

            }

        }

    };

    registerAction(ctrlAltDelAction);

    clipboardAction = new ClipboardAction() {

        public void actionPerformed(ActionEvent evt) {

            vnc.setClipboardVisible(!vnc.isClipboardVisible());

        }

    };

    registerAction(clipboardAction);

    if (getApplication().getMRUModel() != null) {

        registerAction(

                mruAction = new MRUActionImpl(getApplication().getMRUModel()));

    }

    connectionPropertiesAction = new ConnectionPropertiesAction() {

        public void actionPerformed(ActionEvent evt) {

            editConnection(getCurrentConnectionProfile());

        }

    };

    registerAction(connectionPropertiesAction);

    //  Only allow opening of files if allowed by the security manager

    try {

        if (System.getSecurityManager() != null) {

            AccessController.checkPermission(

                    new FilePermission("<<ALL FILES>>", "read"));

        }

        openAction = new OpenAction() {

            public void actionPerformed(ActionEvent evt) {

                open();

            }

        };

        registerAction(openAction);

    }

    catch (AccessControlException ace) {

        ace.printStackTrace();

    }

    //  Only allow saving of files if allowed by the security manager

    try {

        if (System.getSecurityManager() != null) {

            AccessController.checkPermission(

                    new FilePermission("<<ALL FILES>>", "write"));

        }

        saveAction = new SaveAction() {

            public void actionPerformed(ActionEvent evt) {

                saveConnection(false, getCurrentConnectionFile(),

                        getCurrentConnectionProfile());

            }

        };

        registerAction(saveAction);

        saveAsAction = new SaveAsAction() {

            public void actionPerformed(ActionEvent evt) {

                saveConnection(true, getCurrentConnectionFile(),

                        getCurrentConnectionProfile());

            }

        };

        registerAction(saveAsAction);

        recordAction = new RecordAction() {

            public void actionPerformed(ActionEvent evt) {

                startRecording();

            }

        };

        registerAction(recordAction);

        stopAction = new StopAction() {

            public void actionPerformed(ActionEvent evt) {

                stopRecording();

            }

        };

        registerAction(stopAction);

    }

    catch (AccessControlException ace) {

        ace.printStackTrace();

    }

    //  Only allow editing of connection file if read / write is allowed

    try {

        if (System.getSecurityManager() != null) {

            AccessController.checkPermission(

                    new FilePermission("<<ALL FILES>>", "write"));

        }

        if (System.getSecurityManager() != null) {

            AccessController.checkPermission(

                    new FilePermission("<<ALL FILES>>", "read"));

        }

        editAction = new EditAction() {

            public void actionPerformed(ActionEvent evt) {

                editConnection();

            }

        };

        registerAction(editAction);

    }

    catch (AccessControlException ace) {

        ace.printStackTrace();

    }

    java.util.List providers = SessionProviderFactory.getInstance().getSessionProviders();
    SessionProvider provider;
    SessionProviderAction action;
    for (Iterator it = providers.iterator(); it.hasNext();) {
        provider = (SessionProvider) it.next();
        action = new SessionProviderAction(provider);
        sessionActions.put(action.getActionCommand(), action);
        action.addActionListener(this);
        registerAction(action);
    }

}

From source file:org.apache.jasper.runtime.PageContextImpl.java

public void handlePageException(final Throwable t) throws IOException, ServletException {
    if (t == null)
        throw new NullPointerException("null Throwable");

    if (System.getSecurityManager() != null) {
        try {//from w w  w  . ja  v a  2s .com
            AccessController.doPrivileged(new PrivilegedExceptionAction() {
                public Object run() throws Exception {
                    doHandlePageException(t);
                    return null;
                }
            });
        } catch (PrivilegedActionException e) {
            Exception ex = e.getException();
            if (ex instanceof IOException) {
                throw (IOException) ex;
            } else {
                throw (ServletException) ex;
            }
        }
    } else {
        doHandlePageException(t);
    }

}

From source file:org.apache.catalina.loader.WebappLoader.java

/**
 * Configure associated class loader permissions.
 *//*  w w w .ja v a 2  s  .  c om*/
private void setPermissions() {

    if (System.getSecurityManager() == null)
        return;
    if (!(container instanceof Context))
        return;

    // Tell the class loader the root of the context
    ServletContext servletContext = ((Context) container).getServletContext();

    // Assigning permissions for the work directory
    File workDir = (File) servletContext.getAttribute(Globals.WORK_DIR_ATTR);
    if (workDir != null) {
        try {
            String workDirPath = workDir.getCanonicalPath();
            classLoader.addPermission(new FilePermission(workDirPath, "read,write"));
            classLoader
                    .addPermission(new FilePermission(workDirPath + File.separator + "-", "read,write,delete"));
        } catch (IOException e) {
            // Ignore
        }
    }

    try {

        URL rootURL = servletContext.getResource("/");
        classLoader.addPermission(rootURL);

        String contextRoot = servletContext.getRealPath("/");
        if (contextRoot != null) {
            try {
                contextRoot = (new File(contextRoot)).getCanonicalPath();
                classLoader.addPermission(contextRoot);
            } catch (IOException e) {
                // Ignore
            }
        }

        URL classesURL = servletContext.getResource("/WEB-INF/classes/");
        classLoader.addPermission(classesURL);
        URL libURL = servletContext.getResource("/WEB-INF/lib/");
        classLoader.addPermission(libURL);

        if (contextRoot != null) {

            if (libURL != null) {
                File rootDir = new File(contextRoot);
                File libDir = new File(rootDir, "WEB-INF/lib/");
                try {
                    String path = libDir.getCanonicalPath();
                    classLoader.addPermission(path);
                } catch (IOException e) {
                }
            }

        } else {

            if (workDir != null) {
                if (libURL != null) {
                    File libDir = new File(workDir, "WEB-INF/lib/");
                    try {
                        String path = libDir.getCanonicalPath();
                        classLoader.addPermission(path);
                    } catch (IOException e) {
                    }
                }
                if (classesURL != null) {
                    File classesDir = new File(workDir, "WEB-INF/classes/");
                    try {
                        String path = classesDir.getCanonicalPath();
                        classLoader.addPermission(path);
                    } catch (IOException e) {
                    }
                }
            }

        }

    } catch (MalformedURLException e) {
    }

}

From source file:org.apache.catalina.core.ContainerBase.java

/**
 * Add a new child Container to those associated with this Container,
 * if supported.  Prior to adding this Container to the set of children,
 * the child's <code>setParent()</code> method must be called, with this
 * Container as an argument.  This method may thrown an
 * <code>IllegalArgumentException</code> if this Container chooses not
 * to be attached to the specified Container, in which case it is not added
 *
 * @param child New child Container to be added
 *
 * @exception IllegalArgumentException if this exception is thrown by
 *  the <code>setParent()</code> method of the child Container
 * @exception IllegalArgumentException if the new child does not have
 *  a name unique from that of existing children of this Container
 * @exception IllegalStateException if this Container does not support
 *  child Containers//  w w w  .j a  v  a 2  s  .  c  om
 */
public void addChild(Container child) {
    if (System.getSecurityManager() != null) {
        PrivilegedAction dp = new PrivilegedAddChild(child);
        AccessController.doPrivileged(dp);
    } else {
        addChildInternal(child);
    }
}

From source file:org.apache.catalina.session.PersistentManagerBase.java

/**
 * Write the provided session to the Store without modifying
 * the copy in memory or triggering passivation events. Does
 * nothing if the session is invalid or past its expiration.
 *///w ww  .j a v  a  2s  .c om
protected void writeSession(Session session) throws IOException {

    if (store == null || !session.isValid()) {
        return;
    }

    try {
        if (System.getSecurityManager() != null) {
            try {
                AccessController.doPrivileged(new PrivilegedStoreSave(session));
            } catch (PrivilegedActionException ex) {
                Exception exception = ex.getException();
                log.error("Exception clearing the Store: " + exception);
                exception.printStackTrace();
            }
        } else {
            store.save(session);
        }
    } catch (IOException e) {
        log.error(sm.getString("persistentManager.serializeError", session.getId(), e));
        throw e;
    }

}

From source file:org.rhq.bundle.ant.AntMain.java

private void initProject(Project project, ClassLoader coreLoader, DeploymentPhase phase) {
    if (coreLoader == null) {
        coreLoader = getClass().getClassLoader();
    }//ww w. j a  va 2  s. c  o  m

    project.setCoreLoader(coreLoader);
    project.setProperty(DeployPropertyNames.DEPLOY_PHASE, phase.name());

    addBuildListeners(project);
    addInputHandler(project);

    PrintStream savedErr = System.err;
    PrintStream savedOut = System.out;
    InputStream savedIn = System.in;

    // use a system manager that prevents from System.exit()
    SecurityManager oldsm = null;
    oldsm = System.getSecurityManager();

    //SecurityManager can not be installed here for backwards
    //compatibility reasons (PD). Needs to be loaded prior to
    //ant class if we are going to implement it.
    //System.setSecurityManager(new NoExitSecurityManager());
    try {
        if (allowInput) {
            project.setDefaultInputStream(System.in);
        }
        System.setIn(new DemuxInputStream(project));
        System.setOut(new PrintStream(new DemuxOutputStream(project, false)));
        System.setErr(new PrintStream(new DemuxOutputStream(project, true)));

        if (!projectHelp) {
            project.fireBuildStarted();
        }

        // set the thread priorities
        if (threadPriority != null) {
            try {
                project.log("Setting Ant's thread priority to " + threadPriority, Project.MSG_VERBOSE);
                Thread.currentThread().setPriority(threadPriority.intValue());
            } catch (SecurityException swallowed) {
                //we cannot set the priority here.
                project.log("A security manager refused to set the -nice value");
            }
        }

        project.init();

        // set user-define properties
        Enumeration e = definedProps.keys();
        while (e.hasMoreElements()) {
            String arg = (String) e.nextElement();
            String value = (String) definedProps.get(arg);
            project.setProperty(arg, value);
        }

        try {
            addTaskDefsForBundledTasks(project);
        } catch (IOException ie) {
            throw new RuntimeException(ie);
        } catch (ClassNotFoundException ce) {
            throw new RuntimeException(ce);
        }

        project.setProperty(MagicNames.ANT_FILE, buildFile.getAbsolutePath());
        project.setProperty(MagicNames.ANT_FILE_TYPE, MagicNames.ANT_FILE_TYPE_FILE);

        project.setKeepGoingMode(keepGoingMode);
        if (proxy) {
            //proxy setup if enabled
            ProxySetup proxySetup = new ProxySetup(project);
            proxySetup.enableProxies();
        }

        // RHQ NOTE: Besides parsing the build file, this will also execute the implicit ("") target.
        ProjectHelper.configureProject(project, buildFile);
    } finally {
        // put back the original security manager
        //The following will never eval to true. (PD)
        if (oldsm != null) {
            System.setSecurityManager(oldsm);
        }

        System.setOut(savedOut);
        System.setErr(savedErr);
        System.setIn(savedIn);
    }
}

From source file:org.cruxframework.crux.tools.compile.AbstractCruxCompiler.java

/**
 * /*from   ww w  .  j  a  v a2  s .  com*/
 */
private void setSecurityManagerToAvoidSystemExit() {
    AccessController.doPrivileged(new PrivilegedAction<Boolean>() {
        public Boolean run() {
            originalSecurityManager = System.getSecurityManager();
            System.setSecurityManager(new SecurityManager() {

                @Override
                public void checkExit(int status) {
                    if (status == 0) {
                        throw new DoNotExitException();
                    }
                    super.checkExit(status);
                }

                @Override
                public void checkPermission(Permission perm) {
                }

                @Override
                public void checkPermission(Permission perm, Object context) {
                }
            });
            return true;
        }
    });
}

From source file:com.sshtools.powervnc.PowerVNCPanel.java

private void initActions() {

    //  Create the action menu groups

    System.out.println("initActions");
    registerActionMenu(new SshToolsApplicationPanel.ActionMenu("File", "File",

            'f', 0));

    registerActionMenu(new SshToolsApplicationPanel.ActionMenu("Edit", "Edit",

            'e', 10));

    registerActionMenu(new SshToolsApplicationPanel.ActionMenu("View", "View",

            'v', 20));

    vncTab = new VNCTab( /*vnc*/);

    desktopAction = new DesktopAction() {

        public void actionPerformed(ActionEvent evt) {

            try {
                authenticationComplete(false);
            } catch (SshException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();//from  w  w w. jav  a2 s  .co m
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            /*
                    newProfile = newConnectionProfile(null);
                    
                    if (newProfile != null) {
                    
                      connect(newProfile, true);
                    
                    }
                    
                    else {
                    
                      log.info("New connection cancelled");
                    
                    }
            */
        }

    };

    registerAction(desktopAction);

    closeAction = new CloseAction() {

        public void actionPerformed(ActionEvent evt) {

            closing = true;
            // Close on a thread to avoid blocking the event queue
            Thread thread = new Thread() {
                public void run() {
                    closeConnection(true);
                }
            };

            thread.start();

        }

    };

    registerAction(closeAction);

    filemanagerAction = new FileManagerAction() {

        public void actionPerformed(ActionEvent evt) {

            new JFtp(ssh);
            //         refresh();

        }

    };

    registerAction(filemanagerAction);

    ctrlAltDelAction = new CtrlAltDelAction() {

        public void actionPerformed(ActionEvent evt) {

            try {

                vnc.sendCtrlAltDel();

            }

            catch (IOException ioe) {

                closeConnection(true);

                showErrorMessage(PowerVNCPanel.this, "Error", ioe);

            }

        }

    };

    registerAction(ctrlAltDelAction);

    clipboardAction = new ClipboardAction() {

        public void actionPerformed(ActionEvent evt) {

            vnc.setClipboardVisible(!vnc.isClipboardVisible());

        }

    };

    registerAction(clipboardAction);

    if (getApplication().getMRUModel() != null) {

        registerAction(

                mruAction = new MRUActionImpl(getApplication().getMRUModel()));

    }

    connectionPropertiesAction = new ConnectionPropertiesAction() {

        public void actionPerformed(ActionEvent evt) {

            editConnection(getCurrentConnectionProfile());

        }

    };

    registerAction(connectionPropertiesAction);

    //  Only allow opening of files if allowed by the security manager

    try {

        if (System.getSecurityManager() != null) {

            AccessController.checkPermission(

                    new FilePermission("<<ALL FILES>>", "read"));

        }

        openAction = new OpenAction() {

            public void actionPerformed(ActionEvent evt) {

                open();

            }

        };

        registerAction(openAction);

    }

    catch (AccessControlException ace) {

        ace.printStackTrace();

    }

    //  Only allow saving of files if allowed by the security manager

    try {

        if (System.getSecurityManager() != null) {

            AccessController.checkPermission(

                    new FilePermission("<<ALL FILES>>", "write"));

        }

        saveAction = new SaveAction() {

            public void actionPerformed(ActionEvent evt) {

                saveConnection(false, getCurrentConnectionFile(),

                        getCurrentConnectionProfile());

            }

        };

        registerAction(saveAction);

        saveAsAction = new SaveAsAction() {

            public void actionPerformed(ActionEvent evt) {

                saveConnection(true, getCurrentConnectionFile(),

                        getCurrentConnectionProfile());

            }

        };

        registerAction(saveAsAction);

        recordAction = new RecordAction() {

            public void actionPerformed(ActionEvent evt) {

                startRecording();

            }

        };

        registerAction(recordAction);

        stopAction = new StopAction() {

            public void actionPerformed(ActionEvent evt) {

                stopRecording();

            }

        };

        registerAction(stopAction);

    }

    catch (AccessControlException ace) {

        ace.printStackTrace();

    }

    //  Only allow editing of connection file if read / write is allowed

    try {

        if (System.getSecurityManager() != null) {

            AccessController.checkPermission(

                    new FilePermission("<<ALL FILES>>", "write"));

        }

        if (System.getSecurityManager() != null) {

            AccessController.checkPermission(

                    new FilePermission("<<ALL FILES>>", "read"));

        }

        editAction = new EditAction() {

            public void actionPerformed(ActionEvent evt) {

                editConnection();

            }

        };

        registerAction(editAction);

    }

    catch (AccessControlException ace) {

        ace.printStackTrace();

    }

    java.util.List providers = SessionProviderFactory.getInstance().getSessionProviders();
    SessionProvider provider;
    SessionProviderAction action;
    for (Iterator it = providers.iterator(); it.hasNext();) {
        provider = (SessionProvider) it.next();
        action = new SessionProviderAction(provider);
        sessionActions.put(action.getActionCommand(), action);
        action.addActionListener(this);
        registerAction(action);
    }

}

From source file:org.lnicholls.galleon.server.Server.java

public static synchronized Server getServer() {
    if (mServer == null) {
        try {//from ww w.j  a  v a  2  s .  c  om
            mServer = new Server();
            mServer.start();
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }
    if (true || System.getSecurityManager() instanceof CustomSecurityManager)
        return mServer;
    else
        return null;
}

From source file:org.springframework.beans.factory.support.ConstructorResolver.java

/**
 * Instantiate the bean using a named factory method. The method may be static, if the
 * bean definition parameter specifies a class, rather than a "factory-bean", or
 * an instance variable on a factory object itself configured using Dependency Injection.
 * <p>Implementation requires iterating over the static or instance methods with the
 * name specified in the RootBeanDefinition (the method may be overloaded) and trying
 * to match with the parameters. We don't have the types attached to constructor args,
 * so trial and error is the only way to go here. The explicitArgs array may contain
 * argument values passed in programmatically via the corresponding getBean method.
 * @param beanName the name of the bean//from   w  w  w .jav  a 2s .  co m
 * @param mbd the merged bean definition for the bean
 * @param explicitArgs argument values passed in programmatically via the getBean
 * method, or {@code null} if none (-> use constructor argument values from bean definition)
 * @return a BeanWrapper for the new instance
 */
public BeanWrapper instantiateUsingFactoryMethod(final String beanName, final RootBeanDefinition mbd,
        @Nullable final Object[] explicitArgs) {

    BeanWrapperImpl bw = new BeanWrapperImpl();
    this.beanFactory.initBeanWrapper(bw);

    Object factoryBean;
    Class<?> factoryClass;
    boolean isStatic;

    String factoryBeanName = mbd.getFactoryBeanName();
    if (factoryBeanName != null) {
        if (factoryBeanName.equals(beanName)) {
            throw new BeanDefinitionStoreException(mbd.getResourceDescription(), beanName,
                    "factory-bean reference points back to the same bean definition");
        }
        factoryBean = this.beanFactory.getBean(factoryBeanName);
        if (mbd.isSingleton() && this.beanFactory.containsSingleton(beanName)) {
            throw new ImplicitlyAppearedSingletonException();
        }
        factoryClass = factoryBean.getClass();
        isStatic = false;
    } else {
        // It's a static factory method on the bean class.
        if (!mbd.hasBeanClass()) {
            throw new BeanDefinitionStoreException(mbd.getResourceDescription(), beanName,
                    "bean definition declares neither a bean class nor a factory-bean reference");
        }
        factoryBean = null;
        factoryClass = mbd.getBeanClass();
        isStatic = true;
    }

    Method factoryMethodToUse = null;
    ArgumentsHolder argsHolderToUse = null;
    Object[] argsToUse = null;

    if (explicitArgs != null) {
        argsToUse = explicitArgs;
    } else {
        Object[] argsToResolve = null;
        synchronized (mbd.constructorArgumentLock) {
            factoryMethodToUse = (Method) mbd.resolvedConstructorOrFactoryMethod;
            if (factoryMethodToUse != null && mbd.constructorArgumentsResolved) {
                // Found a cached factory method...
                argsToUse = mbd.resolvedConstructorArguments;
                if (argsToUse == null) {
                    argsToResolve = mbd.preparedConstructorArguments;
                }
            }
        }
        if (argsToResolve != null) {
            argsToUse = resolvePreparedArguments(beanName, mbd, bw, factoryMethodToUse, argsToResolve, true);
        }
    }

    if (factoryMethodToUse == null || argsToUse == null) {
        // Need to determine the factory method...
        // Try all methods with this name to see if they match the given arguments.
        factoryClass = ClassUtils.getUserClass(factoryClass);

        Method[] rawCandidates = getCandidateMethods(factoryClass, mbd);
        List<Method> candidateSet = new ArrayList<>();
        for (Method candidate : rawCandidates) {
            if (Modifier.isStatic(candidate.getModifiers()) == isStatic && mbd.isFactoryMethod(candidate)) {
                candidateSet.add(candidate);
            }
        }
        Method[] candidates = candidateSet.toArray(new Method[0]);
        AutowireUtils.sortFactoryMethods(candidates);

        ConstructorArgumentValues resolvedValues = null;
        boolean autowiring = (mbd.getResolvedAutowireMode() == RootBeanDefinition.AUTOWIRE_CONSTRUCTOR);
        int minTypeDiffWeight = Integer.MAX_VALUE;
        Set<Method> ambiguousFactoryMethods = null;

        int minNrOfArgs;
        if (explicitArgs != null) {
            minNrOfArgs = explicitArgs.length;
        } else {
            // We don't have arguments passed in programmatically, so we need to resolve the
            // arguments specified in the constructor arguments held in the bean definition.
            if (mbd.hasConstructorArgumentValues()) {
                ConstructorArgumentValues cargs = mbd.getConstructorArgumentValues();
                resolvedValues = new ConstructorArgumentValues();
                minNrOfArgs = resolveConstructorArguments(beanName, mbd, bw, cargs, resolvedValues);
            } else {
                minNrOfArgs = 0;
            }
        }

        LinkedList<UnsatisfiedDependencyException> causes = null;

        for (Method candidate : candidates) {
            Class<?>[] paramTypes = candidate.getParameterTypes();

            if (paramTypes.length >= minNrOfArgs) {
                ArgumentsHolder argsHolder;

                if (explicitArgs != null) {
                    // Explicit arguments given -> arguments length must match exactly.
                    if (paramTypes.length != explicitArgs.length) {
                        continue;
                    }
                    argsHolder = new ArgumentsHolder(explicitArgs);
                } else {
                    // Resolved constructor arguments: type conversion and/or autowiring necessary.
                    try {
                        String[] paramNames = null;
                        ParameterNameDiscoverer pnd = this.beanFactory.getParameterNameDiscoverer();
                        if (pnd != null) {
                            paramNames = pnd.getParameterNames(candidate);
                        }
                        argsHolder = createArgumentArray(beanName, mbd, resolvedValues, bw, paramTypes,
                                paramNames, candidate, autowiring, candidates.length == 1);
                    } catch (UnsatisfiedDependencyException ex) {
                        if (logger.isTraceEnabled()) {
                            logger.trace("Ignoring factory method [" + candidate + "] of bean '" + beanName
                                    + "': " + ex);
                        }
                        // Swallow and try next overloaded factory method.
                        if (causes == null) {
                            causes = new LinkedList<>();
                        }
                        causes.add(ex);
                        continue;
                    }
                }

                int typeDiffWeight = (mbd.isLenientConstructorResolution()
                        ? argsHolder.getTypeDifferenceWeight(paramTypes)
                        : argsHolder.getAssignabilityWeight(paramTypes));
                // Choose this factory method if it represents the closest match.
                if (typeDiffWeight < minTypeDiffWeight) {
                    factoryMethodToUse = candidate;
                    argsHolderToUse = argsHolder;
                    argsToUse = argsHolder.arguments;
                    minTypeDiffWeight = typeDiffWeight;
                    ambiguousFactoryMethods = null;
                }
                // Find out about ambiguity: In case of the same type difference weight
                // for methods with the same number of parameters, collect such candidates
                // and eventually raise an ambiguity exception.
                // However, only perform that check in non-lenient constructor resolution mode,
                // and explicitly ignore overridden methods (with the same parameter signature).
                else if (factoryMethodToUse != null && typeDiffWeight == minTypeDiffWeight
                        && !mbd.isLenientConstructorResolution()
                        && paramTypes.length == factoryMethodToUse.getParameterCount()
                        && !Arrays.equals(paramTypes, factoryMethodToUse.getParameterTypes())) {
                    if (ambiguousFactoryMethods == null) {
                        ambiguousFactoryMethods = new LinkedHashSet<>();
                        ambiguousFactoryMethods.add(factoryMethodToUse);
                    }
                    ambiguousFactoryMethods.add(candidate);
                }
            }
        }

        if (factoryMethodToUse == null) {
            if (causes != null) {
                UnsatisfiedDependencyException ex = causes.removeLast();
                for (Exception cause : causes) {
                    this.beanFactory.onSuppressedException(cause);
                }
                throw ex;
            }
            List<String> argTypes = new ArrayList<>(minNrOfArgs);
            if (explicitArgs != null) {
                for (Object arg : explicitArgs) {
                    argTypes.add(arg != null ? arg.getClass().getSimpleName() : "null");
                }
            } else if (resolvedValues != null) {
                Set<ValueHolder> valueHolders = new LinkedHashSet<>(resolvedValues.getArgumentCount());
                valueHolders.addAll(resolvedValues.getIndexedArgumentValues().values());
                valueHolders.addAll(resolvedValues.getGenericArgumentValues());
                for (ValueHolder value : valueHolders) {
                    String argType = (value.getType() != null ? ClassUtils.getShortName(value.getType())
                            : (value.getValue() != null ? value.getValue().getClass().getSimpleName()
                                    : "null"));
                    argTypes.add(argType);
                }
            }
            String argDesc = StringUtils.collectionToCommaDelimitedString(argTypes);
            throw new BeanCreationException(mbd.getResourceDescription(), beanName,
                    "No matching factory method found: "
                            + (mbd.getFactoryBeanName() != null
                                    ? "factory bean '" + mbd.getFactoryBeanName() + "'; "
                                    : "")
                            + "factory method '" + mbd.getFactoryMethodName() + "(" + argDesc + ")'. "
                            + "Check that a method with the specified name "
                            + (minNrOfArgs > 0 ? "and arguments " : "") + "exists and that it is "
                            + (isStatic ? "static" : "non-static") + ".");
        } else if (void.class == factoryMethodToUse.getReturnType()) {
            throw new BeanCreationException(mbd.getResourceDescription(), beanName, "Invalid factory method '"
                    + mbd.getFactoryMethodName() + "': needs to have a non-void return type!");
        } else if (ambiguousFactoryMethods != null) {
            throw new BeanCreationException(mbd.getResourceDescription(), beanName,
                    "Ambiguous factory method matches found in bean '" + beanName + "' "
                            + "(hint: specify index/type/name arguments for simple parameters to avoid type ambiguities): "
                            + ambiguousFactoryMethods);
        }

        if (explicitArgs == null && argsHolderToUse != null) {
            argsHolderToUse.storeCache(mbd, factoryMethodToUse);
        }
    }

    try {
        Object beanInstance;

        if (System.getSecurityManager() != null) {
            final Object fb = factoryBean;
            final Method factoryMethod = factoryMethodToUse;
            final Object[] args = argsToUse;
            beanInstance = AccessController.doPrivileged(
                    (PrivilegedAction<Object>) () -> this.beanFactory.getInstantiationStrategy()
                            .instantiate(mbd, beanName, this.beanFactory, fb, factoryMethod, args),
                    this.beanFactory.getAccessControlContext());
        } else {
            beanInstance = this.beanFactory.getInstantiationStrategy().instantiate(mbd, beanName,
                    this.beanFactory, factoryBean, factoryMethodToUse, argsToUse);
        }

        bw.setBeanInstance(beanInstance);
        return bw;
    } catch (Throwable ex) {
        throw new BeanCreationException(mbd.getResourceDescription(), beanName,
                "Bean instantiation via factory method failed", ex);
    }
}