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:org.springframework.context.expression.ApplicationContextExpressionTests.java

@Test
public void systemPropertiesSecurityManager() {
    GenericApplicationContext ac = new GenericApplicationContext();
    AnnotationConfigUtils.registerAnnotationConfigProcessors(ac);

    GenericBeanDefinition bd = new GenericBeanDefinition();
    bd.setBeanClass(TestBean.class);
    bd.getPropertyValues().add("country", "#{systemProperties.country}");
    ac.registerBeanDefinition("tb", bd);

    SecurityManager oldSecurityManager = System.getSecurityManager();
    try {/*from   w  w  w . j a va  2  s. co m*/
        System.setProperty("country", "NL");

        SecurityManager securityManager = new SecurityManager() {
            @Override
            public void checkPropertiesAccess() {
                throw new AccessControlException("Not Allowed");
            }

            @Override
            public void checkPermission(Permission perm) {
                // allow everything else
            }
        };
        System.setSecurityManager(securityManager);
        ac.refresh();

        TestBean tb = ac.getBean("tb", TestBean.class);
        assertEquals("NL", tb.getCountry());

    } finally {
        System.setSecurityManager(oldSecurityManager);
        System.getProperties().remove("country");
    }
}

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

public void setAttribute(final String name, final Object o, final int scope) {

    if (name == null) {
        throw new NullPointerException(Localizer.getMessage("jsp.error.attribute.null_name"));
    }//from w w  w  . j a  va 2  s  .  co m

    if (System.getSecurityManager() != null) {
        AccessController.doPrivileged(new PrivilegedAction() {
            public Object run() {
                doSetAttribute(name, o, scope);
                return null;
            }
        });
    } else {
        doSetAttribute(name, o, scope);
    }

}

From source file:org.apache.hadoop.hdfs.TestDFSShell.java

@Test
public void testPut() throws IOException {
    Configuration conf = new HdfsConfiguration();
    MiniDFSCluster cluster = new MiniDFSCluster.Builder(conf).numDataNodes(2).build();
    FileSystem fs = cluster.getFileSystem();
    assertTrue("Not a HDFS: " + fs.getUri(), fs instanceof DistributedFileSystem);
    final DistributedFileSystem dfs = (DistributedFileSystem) fs;

    try {//w  ww.  j av  a 2  s. co m
        // remove left over crc files:
        new File(TEST_ROOT_DIR, ".f1.crc").delete();
        new File(TEST_ROOT_DIR, ".f2.crc").delete();
        final File f1 = createLocalFile(new File(TEST_ROOT_DIR, "f1"));
        final File f2 = createLocalFile(new File(TEST_ROOT_DIR, "f2"));

        final Path root = mkdir(dfs, new Path("/test/put"));
        final Path dst = new Path(root, "dst");

        show("begin");

        final Thread copy2ndFileThread = new Thread() {
            @Override
            public void run() {
                try {
                    show("copy local " + f2 + " to remote " + dst);
                    dfs.copyFromLocalFile(false, false, new Path(f2.getPath()), dst);
                } catch (IOException ioe) {
                    show("good " + StringUtils.stringifyException(ioe));
                    return;
                }
                //should not be here, must got IOException
                assertTrue(false);
            }
        };

        //use SecurityManager to pause the copying of f1 and begin copying f2
        SecurityManager sm = System.getSecurityManager();
        System.out.println("SecurityManager = " + sm);
        System.setSecurityManager(new SecurityManager() {
            private boolean firstTime = true;

            @Override
            public void checkPermission(Permission perm) {
                if (firstTime) {
                    Thread t = Thread.currentThread();
                    if (!t.toString().contains("DataNode")) {
                        String s = "" + Arrays.asList(t.getStackTrace());
                        if (s.contains("FileUtil.copyContent")) {
                            //pause at FileUtil.copyContent

                            firstTime = false;
                            copy2ndFileThread.start();
                            try {
                                Thread.sleep(5000);
                            } catch (InterruptedException e) {
                            }
                        }
                    }
                }
            }
        });
        show("copy local " + f1 + " to remote " + dst);
        dfs.copyFromLocalFile(false, false, new Path(f1.getPath()), dst);
        show("done");

        try {
            copy2ndFileThread.join();
        } catch (InterruptedException e) {
        }
        System.setSecurityManager(sm);

        // copy multiple files to destination directory
        final Path destmultiple = mkdir(dfs, new Path("/test/putmultiple"));
        Path[] srcs = new Path[2];
        srcs[0] = new Path(f1.getPath());
        srcs[1] = new Path(f2.getPath());
        dfs.copyFromLocalFile(false, false, srcs, destmultiple);
        srcs[0] = new Path(destmultiple, "f1");
        srcs[1] = new Path(destmultiple, "f2");
        assertTrue(dfs.exists(srcs[0]));
        assertTrue(dfs.exists(srcs[1]));

        // move multiple files to destination directory
        final Path destmultiple2 = mkdir(dfs, new Path("/test/movemultiple"));
        srcs[0] = new Path(f1.getPath());
        srcs[1] = new Path(f2.getPath());
        dfs.moveFromLocalFile(srcs, destmultiple2);
        assertFalse(f1.exists());
        assertFalse(f2.exists());
        srcs[0] = new Path(destmultiple2, "f1");
        srcs[1] = new Path(destmultiple2, "f2");
        assertTrue(dfs.exists(srcs[0]));
        assertTrue(dfs.exists(srcs[1]));

        f1.delete();
        f2.delete();
    } finally {
        try {
            dfs.close();
        } catch (Exception e) {
        }
        cluster.shutdown();
    }
}

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

public String getServletContextName() {
    if (System.getSecurityManager() != null) {
        return (String) doPrivileged("getServletContextName", null);
    } else {//from   w w  w  . j ava2s.c o m
        return context.getServletContextName();
    }
}

From source file:eu.europa.ejusticeportal.dss.applet.DssApplet.java

/**
 * Check that all required privilege are granted, stop applet if not.
 *///from   ww w .ja  va  2  s  . c  o m
private void checkPrivileges() {

    try {
        final SecurityManager security = System.getSecurityManager();
        if (security != null) {
            final Permission perm = new AllPermission();
            // Throws a security exception if not allowed
            security.checkPermission(perm);
        }
    } catch (Exception ex) {
        ExceptionUtils.log(new UnexpectedException(ex, "Fail to check privileges."), LOG);
        initFailure();
    }
}

From source file:org.pentaho.di.job.entries.hadoopjobexecutor.JobEntryHadoopJobExecutor.java

public Result execute(final Result result, int arg1) throws KettleException {
    result.setNrErrors(0);// w ww .ja v a2s. co m

    Log4jFileAppender appender = null;
    String logFileName = "pdi-" + this.getName(); //$NON-NLS-1$

    try {
        appender = LogWriter.createFileAppender(logFileName, true, false);
        LogWriter.getInstance().addAppender(appender);
        log.setLogLevel(parentJob.getLogLevel());
    } catch (Exception e) {
        logError(BaseMessages.getString(PKG, "JobEntryHadoopJobExecutor.FailedToOpenLogFile", logFileName, //$NON-NLS-1$
                e.toString()));
        logError(Const.getStackTracker(e));
    }

    try {
        URL resolvedJarUrl = resolveJarUrl(jarUrl);
        if (log.isDetailed()) {
            logDetailed(BaseMessages.getString(PKG, "JobEntryHadoopJobExecutor.ResolvedJar",
                    resolvedJarUrl.toExternalForm()));
        }
        HadoopShim shim = getHadoopConfiguration().getHadoopShim();

        if (isSimple) {
            String simpleLoggingIntervalS = environmentSubstitute(getSimpleLoggingInterval());
            int simpleLogInt = 60;
            try {
                simpleLogInt = Integer.parseInt(simpleLoggingIntervalS, 10);
            } catch (NumberFormatException e) {
                logError(BaseMessages.getString(PKG, "ErrorParsingLogInterval", simpleLoggingIntervalS,
                        simpleLogInt));
            }

            final Class<?> mainClass = locateDriverClass(resolvedJarUrl, shim);

            if (log.isDetailed()) {
                logDetailed(BaseMessages.getString(PKG, "JobEntryHadoopJobExecutor.UsingDriverClass",
                        mainClass == null ? "null" : mainClass.getName()));
                logDetailed(BaseMessages.getString(PKG, "JobEntryHadoopJobExecutor.SimpleMode"));
            }
            final AtomicInteger threads = new AtomicInteger(1);
            final NoExitSecurityManager nesm = new NoExitSecurityManager(System.getSecurityManager());
            smStack.setSecurityManager(nesm);
            try {
                Runnable r = new Runnable() {
                    public void run() {
                        try {
                            try {
                                executeMainMethod(mainClass);
                            } finally {
                                restoreSecurityManager(threads, nesm);
                            }
                        } catch (NoExitSecurityManager.NoExitSecurityException ex) {
                            // Only log if we're blocking and waiting for this to complete
                            if (simpleBlocking) {
                                logExitStatus(result, mainClass, ex);
                            }
                        } catch (InvocationTargetException ex) {
                            if (ex.getTargetException() instanceof NoExitSecurityManager.NoExitSecurityException) {
                                // Only log if we're blocking and waiting for this to complete
                                if (simpleBlocking) {
                                    logExitStatus(result, mainClass,
                                            (NoExitSecurityManager.NoExitSecurityException) ex
                                                    .getTargetException());
                                }
                            } else {
                                throw new RuntimeException(ex);
                            }
                        } catch (Exception ex) {
                            throw new RuntimeException(ex);
                        }
                    }
                };
                Thread t = new Thread(r);
                t.setDaemon(true);
                t.setUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {
                    @Override
                    public void uncaughtException(Thread t, Throwable e) {
                        restoreSecurityManager(threads, nesm);
                        if (simpleBlocking) {
                            // Only log if we're blocking and waiting for this to complete
                            logError(BaseMessages.getString(JobEntryHadoopJobExecutor.class,
                                    "JobEntryHadoopJobExecutor.ErrorExecutingClass", mainClass.getName()), e);
                            result.setResult(false);
                        }
                    }
                });
                nesm.addBlockedThread(t);
                t.start();
                if (simpleBlocking) {
                    // wait until the thread is done
                    do {
                        logDetailed(BaseMessages.getString(JobEntryHadoopJobExecutor.class,
                                "JobEntryHadoopJobExecutor.Blocking", mainClass.getName()));
                        t.join(simpleLogInt * 1000);
                    } while (!parentJob.isStopped() && t.isAlive());
                    if (t.isAlive()) {
                        // Kill thread if it's still running. The job must have been stopped.
                        t.interrupt();
                    }
                }
            } finally {
                // If we're not performing simple blocking spawn a watchdog thread to restore the security manager when all
                // threads are complete
                if (!simpleBlocking) {
                    Runnable threadWatchdog = new Runnable() {
                        @Override
                        public void run() {
                            while (threads.get() > 0) {
                                try {
                                    Thread.sleep(100);
                                } catch (InterruptedException e) {
                                    /* ignore */
                                }
                            }
                            restoreSecurityManager(threads, nesm);
                        }
                    };
                    Thread watchdog = new Thread(threadWatchdog);
                    watchdog.setDaemon(true);
                    watchdog.start();
                }
            }
        } else {
            if (log.isDetailed()) {
                logDetailed(BaseMessages.getString(PKG, "JobEntryHadoopJobExecutor.AdvancedMode"));
            }
            Configuration conf = shim.createConfiguration();
            FileSystem fs = shim.getFileSystem(conf);
            URL[] urls = new URL[] { resolvedJarUrl };
            URLClassLoader loader = new URLClassLoader(urls, shim.getClass().getClassLoader());
            String hadoopJobNameS = environmentSubstitute(hadoopJobName);
            conf.setJobName(hadoopJobNameS);

            String outputKeyClassS = environmentSubstitute(outputKeyClass);
            conf.setOutputKeyClass(loader.loadClass(outputKeyClassS));
            String outputValueClassS = environmentSubstitute(outputValueClass);
            conf.setOutputValueClass(loader.loadClass(outputValueClassS));

            if (mapperClass != null) {
                String mapperClassS = environmentSubstitute(mapperClass);
                Class<?> mapper = loader.loadClass(mapperClassS);
                conf.setMapperClass(mapper);
            }
            if (combinerClass != null) {
                String combinerClassS = environmentSubstitute(combinerClass);
                Class<?> combiner = loader.loadClass(combinerClassS);
                conf.setCombinerClass(combiner);
            }
            if (reducerClass != null) {
                String reducerClassS = environmentSubstitute(reducerClass);
                Class<?> reducer = loader.loadClass(reducerClassS);
                conf.setReducerClass(reducer);
            }

            if (inputFormatClass != null) {
                String inputFormatClassS = environmentSubstitute(inputFormatClass);
                Class<?> inputFormat = loader.loadClass(inputFormatClassS);
                conf.setInputFormat(inputFormat);
            }
            if (outputFormatClass != null) {
                String outputFormatClassS = environmentSubstitute(outputFormatClass);
                Class<?> outputFormat = loader.loadClass(outputFormatClassS);
                conf.setOutputFormat(outputFormat);
            }

            String hdfsHostnameS = environmentSubstitute(hdfsHostname);
            String hdfsPortS = environmentSubstitute(hdfsPort);
            String jobTrackerHostnameS = environmentSubstitute(jobTrackerHostname);
            String jobTrackerPortS = environmentSubstitute(jobTrackerPort);

            List<String> configMessages = new ArrayList<String>();
            shim.configureConnectionInformation(hdfsHostnameS, hdfsPortS, jobTrackerHostnameS, jobTrackerPortS,
                    conf, configMessages);
            for (String m : configMessages) {
                logBasic(m);
            }

            String inputPathS = environmentSubstitute(inputPath);
            String[] inputPathParts = inputPathS.split(",");
            List<Path> paths = new ArrayList<Path>();
            for (String path : inputPathParts) {
                paths.add(fs.asPath(conf.getDefaultFileSystemURL(), path));
            }
            Path[] finalPaths = paths.toArray(new Path[paths.size()]);

            conf.setInputPaths(finalPaths);
            String outputPathS = environmentSubstitute(outputPath);
            conf.setOutputPath(fs.asPath(conf.getDefaultFileSystemURL(), outputPathS));

            // process user defined values
            for (UserDefinedItem item : userDefined) {
                if (item.getName() != null && !"".equals(item.getName()) && item.getValue() != null
                        && !"".equals(item.getValue())) {
                    String nameS = environmentSubstitute(item.getName());
                    String valueS = environmentSubstitute(item.getValue());
                    conf.set(nameS, valueS);
                }
            }

            conf.setJar(environmentSubstitute(jarUrl));

            String numMapTasksS = environmentSubstitute(numMapTasks);
            String numReduceTasksS = environmentSubstitute(numReduceTasks);
            int numM = 1;
            try {
                numM = Integer.parseInt(numMapTasksS);
            } catch (NumberFormatException e) {
                logError("Can't parse number of map tasks '" + numMapTasksS + "'. Setting num"
                        + "map tasks to 1");
            }
            int numR = 1;
            try {
                numR = Integer.parseInt(numReduceTasksS);
            } catch (NumberFormatException e) {
                logError("Can't parse number of reduce tasks '" + numReduceTasksS + "'. Setting num"
                        + "reduce tasks to 1");
            }

            conf.setNumMapTasks(numM);
            conf.setNumReduceTasks(numR);

            RunningJob runningJob = shim.submitJob(conf);

            String loggingIntervalS = environmentSubstitute(getLoggingInterval());
            int logIntv = 60;
            try {
                logIntv = Integer.parseInt(loggingIntervalS);
            } catch (NumberFormatException e) {
                logError(BaseMessages.getString(PKG, "ErrorParsingLogInterval", loggingIntervalS, logIntv));
            }
            if (blocking) {
                try {
                    int taskCompletionEventIndex = 0;
                    while (!parentJob.isStopped() && !runningJob.isComplete()) {
                        if (logIntv >= 1) {
                            printJobStatus(runningJob);
                            taskCompletionEventIndex = logTaskMessages(runningJob, taskCompletionEventIndex);
                            Thread.sleep(logIntv * 1000);
                        } else {
                            Thread.sleep(60000);
                        }
                    }

                    if (parentJob.isStopped() && !runningJob.isComplete()) {
                        // We must stop the job running on Hadoop
                        runningJob.killJob();
                        // Indicate this job entry did not complete
                        result.setResult(false);
                    }

                    printJobStatus(runningJob);
                    // Log any messages we may have missed while polling
                    logTaskMessages(runningJob, taskCompletionEventIndex);
                } catch (InterruptedException ie) {
                    logError(ie.getMessage(), ie);
                }

                // Entry is successful if the MR job is successful overall
                result.setResult(runningJob.isSuccessful());
            }

        }
    } catch (Throwable t) {
        t.printStackTrace();
        result.setStopped(true);
        result.setNrErrors(1);
        result.setResult(false);
        logError(t.getMessage(), t);
    }

    if (appender != null) {
        LogWriter.getInstance().removeAppender(appender);
        appender.close();

        ResultFile resultFile = new ResultFile(ResultFile.FILE_TYPE_LOG, appender.getFile(),
                parentJob.getJobname(), getName());
        result.getResultFiles().put(resultFile.getFile().toString(), resultFile);
    }

    return result;
}

From source file:org.eclipse.gemini.blueprint.extender.internal.dependencies.startup.DependencyServiceManager.java

protected void findServiceDependencies() throws Exception {
    try {//w w w . j  av  a  2  s .  c  o  m
        if (System.getSecurityManager() != null) {
            final AccessControlContext acc = getAcc();

            PrivilegedUtils.executeWithCustomTCCL(context.getClassLoader(),
                    new PrivilegedUtils.UnprivilegedThrowableExecution<Object>() {
                        public Object run() throws Throwable {
                            AccessController.doPrivileged(new PrivilegedExceptionAction<Object>() {
                                public Object run() throws Exception {
                                    doFindDependencies();
                                    return null;
                                }
                            }, acc);
                            return null;
                        }
                    });
        } else {
            doFindDependencies();
        }
    } catch (Throwable th) {
        if (th instanceof Exception)
            throw ((Exception) th);
        throw (Error) th;
    }

    Collection<String> unsatisfiedDependencyValues = getUnsatisfiedDependencies().values();

    if (log.isDebugEnabled()) {
        int numDependencies;
        int numUnsatisfiedDependencies;
        synchronized (monitor) {
            numDependencies = dependencies.size();
            numUnsatisfiedDependencies = unsatisfiedDependencies.size();
        }
        log.debug(numDependencies + " OSGi service dependencies, " + numUnsatisfiedDependencies
                + " unsatisfied (for beans " + unsatisfiedDependencyValues + ") in "
                + context.getDisplayName());
    }

    if (!isSatisfied()) {
        log.info(context.getDisplayName() + " is waiting for unsatisfied dependencies ["
                + unsatisfiedDependencyValues + "]");
    }
    if (log.isTraceEnabled()) {
        Collection<String> dependencyValues;
        synchronized (monitor) {
            dependencyValues = new ArrayList<String>(dependencies.values());
        }
        log.trace("Total OSGi service dependencies beans " + dependencyValues);
        log.trace("Unsatified OSGi service dependencies beans " + unsatisfiedDependencyValues);
    }
}

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

/**
 * "autowire constructor" (with constructor arguments by type) behavior.
 * Also applied if explicit constructor argument values are specified,
 * matching all remaining arguments with beans from the bean factory.
 * <p>This corresponds to constructor injection: In this mode, a Spring
 * bean factory is able to host components that expect constructor-based
 * dependency resolution.//  w w  w  .ja  v  a 2 s  .  c  o  m
 * @param beanName the name of the bean
 * @param mbd the merged bean definition for the bean
 * @param chosenCtors chosen candidate constructors (or {@code null} if none)
 * @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 autowireConstructor(final String beanName, final RootBeanDefinition mbd,
        @Nullable Constructor<?>[] chosenCtors, @Nullable final Object[] explicitArgs) {

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

    Constructor<?> constructorToUse = null;
    ArgumentsHolder argsHolderToUse = null;
    Object[] argsToUse = null;

    if (explicitArgs != null) {
        argsToUse = explicitArgs;
    } else {
        Object[] argsToResolve = null;
        synchronized (mbd.constructorArgumentLock) {
            constructorToUse = (Constructor<?>) mbd.resolvedConstructorOrFactoryMethod;
            if (constructorToUse != null && mbd.constructorArgumentsResolved) {
                // Found a cached constructor...
                argsToUse = mbd.resolvedConstructorArguments;
                if (argsToUse == null) {
                    argsToResolve = mbd.preparedConstructorArguments;
                }
            }
        }
        if (argsToResolve != null) {
            argsToUse = resolvePreparedArguments(beanName, mbd, bw, constructorToUse, argsToResolve, true);
        }
    }

    if (constructorToUse == null) {
        // Need to resolve the constructor.
        boolean autowiring = (chosenCtors != null
                || mbd.getResolvedAutowireMode() == RootBeanDefinition.AUTOWIRE_CONSTRUCTOR);
        ConstructorArgumentValues resolvedValues = null;

        int minNrOfArgs;
        if (explicitArgs != null) {
            minNrOfArgs = explicitArgs.length;
        } else {
            ConstructorArgumentValues cargs = mbd.getConstructorArgumentValues();
            resolvedValues = new ConstructorArgumentValues();
            minNrOfArgs = resolveConstructorArguments(beanName, mbd, bw, cargs, resolvedValues);
        }

        // Take specified constructors, if any.
        Constructor<?>[] candidates = chosenCtors;
        if (candidates == null) {
            Class<?> beanClass = mbd.getBeanClass();
            try {
                candidates = (mbd.isNonPublicAccessAllowed() ? beanClass.getDeclaredConstructors()
                        : beanClass.getConstructors());
            } catch (Throwable ex) {
                throw new BeanCreationException(mbd.getResourceDescription(), beanName,
                        "Resolution of declared constructors on bean Class [" + beanClass.getName()
                                + "] from ClassLoader [" + beanClass.getClassLoader() + "] failed",
                        ex);
            }
        }
        AutowireUtils.sortConstructors(candidates);
        int minTypeDiffWeight = Integer.MAX_VALUE;
        Set<Constructor<?>> ambiguousConstructors = null;
        LinkedList<UnsatisfiedDependencyException> causes = null;

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

            if (constructorToUse != null && argsToUse.length > paramTypes.length) {
                // Already found greedy constructor that can be satisfied ->
                // do not look any further, there are only less greedy constructors left.
                break;
            }
            if (paramTypes.length < minNrOfArgs) {
                continue;
            }

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

            int typeDiffWeight = (mbd.isLenientConstructorResolution()
                    ? argsHolder.getTypeDifferenceWeight(paramTypes)
                    : argsHolder.getAssignabilityWeight(paramTypes));
            // Choose this constructor if it represents the closest match.
            if (typeDiffWeight < minTypeDiffWeight) {
                constructorToUse = candidate;
                argsHolderToUse = argsHolder;
                argsToUse = argsHolder.arguments;
                minTypeDiffWeight = typeDiffWeight;
                ambiguousConstructors = null;
            } else if (constructorToUse != null && typeDiffWeight == minTypeDiffWeight) {
                if (ambiguousConstructors == null) {
                    ambiguousConstructors = new LinkedHashSet<>();
                    ambiguousConstructors.add(constructorToUse);
                }
                ambiguousConstructors.add(candidate);
            }
        }

        if (constructorToUse == null) {
            if (causes != null) {
                UnsatisfiedDependencyException ex = causes.removeLast();
                for (Exception cause : causes) {
                    this.beanFactory.onSuppressedException(cause);
                }
                throw ex;
            }
            throw new BeanCreationException(mbd.getResourceDescription(), beanName,
                    "Could not resolve matching constructor "
                            + "(hint: specify index/type/name arguments for simple parameters to avoid type ambiguities)");
        } else if (ambiguousConstructors != null && !mbd.isLenientConstructorResolution()) {
            throw new BeanCreationException(mbd.getResourceDescription(), beanName,
                    "Ambiguous constructor matches found in bean '" + beanName + "' "
                            + "(hint: specify index/type/name arguments for simple parameters to avoid type ambiguities): "
                            + ambiguousConstructors);
        }

        if (explicitArgs == null) {
            argsHolderToUse.storeCache(mbd, constructorToUse);
        }
    }

    try {
        final InstantiationStrategy strategy = this.beanFactory.getInstantiationStrategy();
        Object beanInstance;

        if (System.getSecurityManager() != null) {
            final Constructor<?> ctorToUse = constructorToUse;
            final Object[] argumentsToUse = argsToUse;
            beanInstance = AccessController
                    .doPrivileged(
                            (PrivilegedAction<Object>) () -> strategy.instantiate(mbd, beanName,
                                    this.beanFactory, ctorToUse, argumentsToUse),
                            this.beanFactory.getAccessControlContext());
        } else {
            beanInstance = strategy.instantiate(mbd, beanName, this.beanFactory, constructorToUse, argsToUse);
        }

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

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

/**
 * Invoke the specified custom destroy method on the given bean.
 * <p>This implementation invokes a no-arg method if found, else checking
 * for a method with a single boolean argument (passing in "true",
 * assuming a "force" parameter), else logging an error.
 *///w  w  w. j a  va 2  s  . co m
private void invokeCustomDestroyMethod(final Method destroyMethod) {
    Class<?>[] paramTypes = destroyMethod.getParameterTypes();
    final Object[] args = new Object[paramTypes.length];
    if (paramTypes.length == 1) {
        args[0] = Boolean.TRUE;
    }
    if (logger.isDebugEnabled()) {
        logger.debug("Invoking destroy method '" + this.destroyMethodName + "' on bean with name '"
                + this.beanName + "'");
    }
    try {
        if (System.getSecurityManager() != null) {
            AccessController.doPrivileged((PrivilegedAction<Object>) () -> {
                ReflectionUtils.makeAccessible(destroyMethod);
                return null;
            });
            try {
                AccessController.doPrivileged(
                        (PrivilegedExceptionAction<Object>) () -> destroyMethod.invoke(bean, args), acc);
            } catch (PrivilegedActionException pax) {
                throw (InvocationTargetException) pax.getException();
            }
        } else {
            ReflectionUtils.makeAccessible(destroyMethod);
            destroyMethod.invoke(bean, args);
        }
    } catch (InvocationTargetException ex) {
        String msg = "Invocation of destroy method '" + this.destroyMethodName + "' failed on bean with name '"
                + this.beanName + "'";
        if (logger.isDebugEnabled()) {
            logger.warn(msg, ex.getTargetException());
        } else {
            logger.warn(msg + ": " + ex.getTargetException());
        }
    } catch (Throwable ex) {
        logger.error("Couldn't invoke destroy method '" + this.destroyMethodName + "' on bean with name '"
                + this.beanName + "'", ex);
    }
}

From source file:org.red5.server.war.RootContextLoaderServlet.java

protected void initRegistry(ServletContext ctx) {
    Registry r = null;/*from   w w w  .  j av a2  s  . c o  m*/
    try {
        Object o = ctx.getInitParameter("rmiPort");
        if (o != null) {
            rmiPort = Integer.valueOf((String) o);
        }
        if (System.getSecurityManager() != null) {
            System.setSecurityManager(new RMISecurityManager());
        }
        // lookup the registry
        r = LocateRegistry.getRegistry(rmiPort);
        // ensure we are not already registered with the registry
        for (String regName : r.list()) {
            logger.debug("Registry entry: " + regName);
        }
    } catch (RemoteException re) {
        logger.info("RMI Registry server was not found on port " + rmiPort);
        // if we didnt find the registry and the user wants it created
        try {
            logger.info("Starting an internal RMI registry");
            // create registry for rmi
            r = LocateRegistry.createRegistry(rmiPort);
        } catch (RemoteException e) {
            logger.info("RMI Registry server was not started on port " + rmiPort);
        }

    }
}