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.beans.factory.support.ConstructorResolver.java

/**
 * Retrieve all candidate methods for the given class, considering
 * the {@link RootBeanDefinition#isNonPublicAccessAllowed()} flag.
 * Called as the starting point for factory method determination.
 *//*from   w w w .j a va 2s.com*/
private Method[] getCandidateMethods(final Class<?> factoryClass, final RootBeanDefinition mbd) {
    if (System.getSecurityManager() != null) {
        return AccessController.doPrivileged((PrivilegedAction<Method[]>) () -> (mbd.isNonPublicAccessAllowed()
                ? ReflectionUtils.getAllDeclaredMethods(factoryClass)
                : factoryClass.getMethods()));
    } else {
        return (mbd.isNonPublicAccessAllowed() ? ReflectionUtils.getAllDeclaredMethods(factoryClass)
                : factoryClass.getMethods());
    }
}

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

public Object findAttribute(final String name) {
    if (System.getSecurityManager() != null) {
        return AccessController.doPrivileged(new PrivilegedAction() {
            public Object run() {
                if (name == null) {
                    throw new NullPointerException(Localizer.getMessage("jsp.error.attribute.null_name"));
                }/*from   w  w  w  . ja  v  a2  s  .c o m*/

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

        return doFindAttribute(name);
    }
}

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

/** Use /dev/random-type special device. This is new code, but may reduce the
*  big delay in generating the random.//from   w  w  w. j a  v a 2 s . c  om
*
*  You must specify a path to a random generator file. Use /dev/urandom
*  for linux ( or similar ) systems. Use /dev/random for maximum security
*  ( it may block if not enough "random" exist ). You can also use
*  a pipe that generates random.
*
*  The code will check if the file exists, and default to java Random
*  if not found. There is a significant performance difference, very
*  visible on the first call to getSession ( like in the first JSP )
*  - so use it if available.
*/
public void setRandomFile(String s) {
    // as a hack, you can use a static file - and genarate the same
    // session ids ( good for strange debugging )
    if (System.getSecurityManager() != null) {
        randomIS = (DataInputStream) AccessController.doPrivileged(new PrivilegedSetRandomFile());
    } else {
        try {
            devRandomSource = s;
            File f = new File(devRandomSource);
            if (!f.exists())
                return;
            randomIS = new DataInputStream(new FileInputStream(f));
            randomIS.readLong();
            if (log.isDebugEnabled())
                log.debug("Opening " + devRandomSource);
        } catch (IOException ex) {
            randomIS = null;
        }
    }
}

From source file:org.springframework.osgi.extender.internal.dependencies.startup.DependencyWaiterApplicationContextExecutor.java

/**
 * Fail creating the context. Figure out unsatisfied dependencies and provide a very nice log message before closing
 * the appContext./*from   w  ww . j  av a  2 s.co m*/
 * 
 * <p/> Normally this method is called when an exception is caught.
 * 
 * @param t - the offending Throwable which caused our demise
 */
private void fail(Throwable t, boolean skipEvent) {

    // this will not thrown any exceptions (it just logs them)
    close();

    StringBuilder buf = new StringBuilder();

    synchronized (monitor) {
        if (dependencyDetector == null || dependencyDetector.getUnsatisfiedDependencies().isEmpty()) {
            buf.append("none");
        } else {
            for (Iterator<MandatoryServiceDependency> iterator = dependencyDetector.getUnsatisfiedDependencies()
                    .keySet().iterator(); iterator.hasNext();) {
                MandatoryServiceDependency dependency = iterator.next();
                buf.append(dependency.toString());
                if (iterator.hasNext()) {
                    buf.append(", ");
                }
            }
        }
    }

    final StringBuilder message = new StringBuilder();
    message.append("Unable to create application context for [");
    if (System.getSecurityManager() != null) {
        AccessController.doPrivileged(new PrivilegedAction<Object>() {
            public Object run() {
                message.append(OsgiStringUtils.nullSafeSymbolicName(getBundle()));
                return null;
            }
        });
    } else {
        message.append(OsgiStringUtils.nullSafeSymbolicName(getBundle()));
    }

    message.append("], unsatisfied dependencies: ");
    message.append(buf.toString());

    log.error(message.toString(), t);

    // send notification
    if (!skipEvent) {
        delegatedMulticaster.multicastEvent(
                new OsgiBundleContextFailedEvent(delegateContext, delegateContext.getBundle(), t));
    }
}

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

/**
 * Fail creating the context. Figure out unsatisfied dependencies and provide a very nice log message before closing
 * the appContext.//from   w ww. ja va2s . co m
 * 
 * <p/> Normally this method is called when an exception is caught.
 * 
 * @param t - the offending Throwable which caused our demise
 */
private void fail(Throwable t, boolean skipEvent) {

    // this will not thrown any exceptions (it just logs them)
    close();

    StringBuilder buf = new StringBuilder();

    synchronized (monitor) {
        if (dependencyDetector == null || dependencyDetector.isSatisfied()) {
            buf.append("none");
        } else {
            for (Iterator<MandatoryServiceDependency> iterator = dependencyDetector.getUnsatisfiedDependencies()
                    .keySet().iterator(); iterator.hasNext();) {
                MandatoryServiceDependency dependency = iterator.next();
                buf.append(dependency.toString());
                if (iterator.hasNext()) {
                    buf.append(", ");
                }
            }
        }
    }

    final StringBuilder message = new StringBuilder();
    message.append("Unable to create application context for [");
    if (System.getSecurityManager() != null) {
        AccessController.doPrivileged(new PrivilegedAction<Object>() {
            public Object run() {
                message.append(OsgiStringUtils.nullSafeSymbolicName(getBundle()));
                return null;
            }
        });
    } else {
        message.append(OsgiStringUtils.nullSafeSymbolicName(getBundle()));
    }

    message.append("], unsatisfied dependencies: ");
    message.append(buf.toString());

    log.error(message.toString(), t);

    // send notification
    if (!skipEvent) {
        delegatedMulticaster.multicastEvent(
                new OsgiBundleContextFailedEvent(delegateContext, delegateContext.getBundle(), t));
    }
}

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

/**
 * Executes the method of the specified <code>ApplicationContext</code>
 * @param method The method object to be invoked.
 * @param context The AppliationContext object on which the method
 *                   will be invoked//from ww  w. j a  va2s  .c o  m
 * @param params The arguments passed to the called method.
 */
private Object executeMethod(final Method method, final ApplicationContext context, final Object[] params)
        throws PrivilegedActionException, IllegalAccessException, InvocationTargetException {

    if (System.getSecurityManager() != null) {
        return AccessController.doPrivileged(new PrivilegedExceptionAction() {
            public Object run() throws IllegalAccessException, InvocationTargetException {
                return method.invoke(context, params);
            }
        });
    } else {
        return method.invoke(context, params);
    }
}

From source file:com.sshtools.j2ssh.forwarding.ForwardingClient.java

/**
 *
 *
 * @param uniqueName/* w  ww .ja  va2s .c om*/
 * @param addressToBind
 * @param portToBind
 * @param hostToConnect
 * @param portToConnect
 *
 * @throws ForwardingConfigurationException
 */
public ForwardingConfiguration addRemoteForwarding(String uniqueName, String addressToBind, int portToBind,
        String hostToConnect, int portToConnect) throws ForwardingConfigurationException {
    // Check that the name does not exist
    if (remoteForwardings.containsKey(uniqueName)) {
        throw new ForwardingConfigurationException("The remote forwaring configuration name already exists!");
    }

    // Check that the address to bind and port are not already being used
    Iterator it = remoteForwardings.values().iterator();
    ForwardingConfiguration config;

    while (it.hasNext()) {
        config = (ForwardingConfiguration) it.next();

        if (config.getAddressToBind().equals(addressToBind) && (config.getPortToBind() == portToBind)) {
            throw new ForwardingConfigurationException(
                    "The remote forwarding address and port are already in use");
        }
    }

    // Check the security mananger
    SecurityManager manager = System.getSecurityManager();

    if (manager != null) {
        try {
            manager.checkPermission(
                    new SocketPermission(hostToConnect + ":" + String.valueOf(portToConnect), "connect"));
        } catch (SecurityException e) {
            throw new ForwardingConfigurationException("The security manager has denied connect permision on "
                    + hostToConnect + ":" + String.valueOf(portToConnect));
        }
    }

    // Create the configuration object
    ForwardingConfiguration cf = new ForwardingConfiguration(uniqueName, addressToBind, portToBind,
            hostToConnect, portToConnect);
    remoteForwardings.put(uniqueName, cf);
    return cf;
}

From source file:com.cisco.dvbu.ps.deploytool.dao.wsapi.VCSWSDAOImpl.java

public void vcsDiffMergerCommand(String prefix, String arguments, String vcsIgnoreMessages, String propertyFile)
        throws CompositeException {

    String identifier = "VCSWSDAOImpl.vcsDiffMergerCommand"; // some unique identifier that characterizes this invocation.
    String actionName = "DIFF";

    try {/*from w  ww . j  a va2 s  .co  m*/
        boolean preserveQuotes = false;
        boolean initArgsList = true;
        List<String> argsList = new ArrayList<String>();
        argsList = CommonUtils.parseArguments(argsList, initArgsList, arguments, preserveQuotes, propertyFile);

        String[] args = argsList.toArray(new String[0]);

        /*
         * 2014-06-30 (mtinius): Removed the PDTool Diffmerger capability
         */
        //         DiffMerger.startCommand(null, null, args);
        /*
         * 2014-06-30 (mtinius): Added security manager around the Composite native Diffmerger code because
         *                    it has System.out.println and System.exit commands.  Need to trap both.
         */
        String maskedargsList = CommonUtils.getArgumentListMasked(argsList);
        if (logger.isDebugEnabled()) {
            logger.debug(identifier + "(prefix, arguments, vcsIgnoreMessages, propertyFile).  prefix=" + prefix
                    + "  arguments=[" + maskedargsList + "]" + "  vcsIgnoreMessages=" + vcsIgnoreMessages
                    + "  propertyFile=" + propertyFile);
        }

        // Get the existing security manager
        SecurityManager sm = System.getSecurityManager();
        PrintStream originalOut = System.out;
        PrintStream originalErr = System.err;
        String command = "DiffMerger.startCommand";
        try {
            // Get the offset location of the java.policy file [offset from PDTool home].
            String javaPolicyOffset = CommonConstants.javaPolicy;
            String javaPolicyLocation = CommonUtils.extractVariable(prefix,
                    CommonUtils.getFileOrSystemPropertyValue(propertyFile, "PROJECT_HOME_PHYSICAL"),
                    propertyFile, true) + javaPolicyOffset;
            // Set the java security policy
            System.getProperties().setProperty("java.security.policy", javaPolicyLocation);

            // Create a new System.out Logger
            Logger exportLogger = Logger.getLogger(DiffMerger.class);
            System.setOut(new PrintStream(new LogOutputStream(exportLogger, Level.INFO)));
            System.setErr(new PrintStream(new LogOutputStream(exportLogger, Level.ERROR)));
            // Create a new security manager
            System.setSecurityManager(new NoExitSecurityManager());

            // Don't execute if -noop (NO_OPERATION) has been set otherwise execute under normal operation.
            if (CommonUtils.isExecOperation()) {
                // Invoke the Composite native DiffMerger command.
                DiffMerger.startCommand(null, null, args);
            } else {
                logger.info("\n\nWARNING - NO_OPERATION: COMMAND [" + command + "], ACTION [" + actionName
                        + "] WAS NOT PERFORMED.\n");
            }
        } catch (NoExitSecurityExceptionStatusNonZero nesesnz) {
            String error = identifier + ":: Exited with exception from System.exit(): " + command
                    + "(null, null, " + maskedargsList + ")";
            logger.error(error);
            throw new CompositeException(error);
        } catch (NoExitSecurityExceptionStatusZero nesezero) {
            if (logger.isDebugEnabled()) {
                logger.debug(identifier + ":: Exited successfully from System.exit(): " + command
                        + "(null, null, " + maskedargsList + ")");
            }
        } finally {
            System.setSecurityManager(sm);
            System.setOut(originalOut);
            System.setErr(originalErr);
        }

    } catch (Exception e) {
        if (resolveExecCommandLineError(prefix, e.getMessage().toString(), vcsIgnoreMessages)) {
            ApplicationException applicationException = new ApplicationException(
                    "DiffMerger execution returned an error=" + e.getMessage().toString());
            if (logger.isErrorEnabled()) {
                logger.error(applicationException);
            }
            throw applicationException;
        }
    }
}

From source file:com.sshtools.daemon.vfs.VirtualFileSystem.java

/**
 *
 *
 * @param handle//from  ww w.  j ava  2  s .c om
 *
 * @return
 *
 * @throws IOException
 * @throws InvalidHandleException
 */
public FileAttributes getFileAttributes(byte[] handle) throws IOException, InvalidHandleException {
    String shandle = new String(handle);

    if (openFiles.containsKey(shandle)) {
        Object obj = openFiles.get(shandle);
        File f;

        if (obj instanceof OpenFile) {
            f = ((OpenFile) obj).getFile();
        } else if (obj instanceof OpenDirectory) {
            f = ((OpenDirectory) obj).getFile();
        } else {
            throw new IOException("Unexpected open file handle");
        }

        VFSPermission permissions = getVFSPermission(f.getAbsolutePath());

        if (permissions == null) {
            throw new IOException("No default permissions set");
        }

        FileAttributes attrs = new FileAttributes();
        attrs.setSize(new UnsignedInteger64(String.valueOf(f.length())));
        attrs.setTimes(new UnsignedInteger32(f.lastModified() / 1000),
                new UnsignedInteger32(f.lastModified() / 1000));

        boolean canExec = true;

        try {
            if (System.getSecurityManager() != null) {
                System.getSecurityManager().checkExec(f.getCanonicalPath());
            }
        } catch (SecurityException ex1) {
            canExec = false;
        }

        attrs.setPermissions((((f.canRead() && permissions.canRead()) ? "r" : "-")
                + ((f.canWrite() && permissions.canWrite()) ? "w" : "-")
                + ((canExec && permissions.canExecute()) ? "x" : "-")));
        attrs.setPermissions(new UnsignedInteger32(attrs.getPermissions().longValue()
                | (f.isDirectory() ? FileAttributes.S_IFDIR : FileAttributes.S_IFREG)));

        return attrs;
    } else {
        throw new InvalidHandleException("The handle is invalid");
    }
}

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

public Enumeration getAttributeNamesInScope(final int scope) {
    if (System.getSecurityManager() != null) {
        return (Enumeration) AccessController.doPrivileged(new PrivilegedAction() {
            public Object run() {
                return doGetAttributeNamesInScope(scope);
            }/*from  w  ww. j  a  va  2 s.co  m*/
        });
    } else {
        return doGetAttributeNamesInScope(scope);
    }
}