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.eclipse.gemini.blueprint.config.internal.adapter.OsgiServiceLifecycleListenerAdapter.java

/**
 * Initialise adapter. Determine custom methods and do validation.
 *//*w  ww  .j a v  a2  s  .  com*/
private void initialize() {

    Class<?> clazz = (target == null ? beanFactory.getType(targetBeanName) : target.getClass());

    Assert.notNull(clazz, "listener " + targetBeanName + " class type cannot be determined");

    isLifecycleListener = OsgiServiceLifecycleListener.class.isAssignableFrom(clazz);
    if (isLifecycleListener)
        if (log.isDebugEnabled())
            log.debug(clazz.getName() + " is a lifecycle listener");

    bindMethods = CustomListenerAdapterUtils.determineCustomMethods(clazz, bindMethod, isBlueprintCompliant);

    boolean isSecurityEnabled = System.getSecurityManager() != null;
    final Class<?> clz = clazz;

    // determine methods using ServiceReference signature
    if (StringUtils.hasText(bindMethod)) {
        if (isSecurityEnabled) {
            bindReference = AccessController.doPrivileged(new PrivilegedAction<Method>() {
                public Method run() {
                    return findServiceReferenceMethod(clz, bindMethod);
                }
            });
        } else {
            bindReference = findServiceReferenceMethod(clz, bindMethod);
        }

        if (bindMethods.isEmpty()) {
            String beanName = (target == null ? "" : " bean [" + targetBeanName + "] ;");
            throw new IllegalArgumentException(
                    "Custom bind method [" + bindMethod + "] not found on " + beanName + "class " + clazz);
        }
    }

    unbindMethods = CustomListenerAdapterUtils.determineCustomMethods(clazz, unbindMethod,
            isBlueprintCompliant);

    if (StringUtils.hasText(unbindMethod)) {
        if (isSecurityEnabled) {
            unbindReference = AccessController.doPrivileged(new PrivilegedAction<Method>() {
                public Method run() {
                    return findServiceReferenceMethod(clz, unbindMethod);
                }
            });
        } else {
            unbindReference = findServiceReferenceMethod(clz, unbindMethod);
        }

        if (unbindMethods.isEmpty()) {
            String beanName = (target == null ? "" : " bean [" + targetBeanName + "] ;");
            throw new IllegalArgumentException(
                    "Custom unbind method [" + unbindMethod + "] not found on " + beanName + "class " + clazz);
        }
    }

    if (!isLifecycleListener && (bindMethods.isEmpty() && unbindMethods.isEmpty() && bindReference == null
            && unbindReference == null))
        throw new IllegalArgumentException(
                "target object needs to implement " + OsgiServiceLifecycleListener.class.getName()
                        + " or custom bind/unbind methods have to be specified");

    if (log.isTraceEnabled()) {
        StringBuilder builder = new StringBuilder();
        builder.append("Discovered bind methods=");
        builder.append(bindMethods.values());
        builder.append(", bind ServiceReference=");
        builder.append(bindReference);
        builder.append("\nunbind methods=");
        builder.append(unbindMethods.values());
        builder.append(", unbind ServiceReference=");
        builder.append(unbindReference);
        log.trace(builder.toString());
    }
}

From source file:org.mobicents.slee.runtime.sbb.SbbObjectPoolFactory.java

/**
 * Create a new instance of this object and set the SbbContext This places
 * it into the object pool.// ww w .  j a  v a 2s.  c  o m
 */
public Object makeObject() {

    SbbObject retval;
    if (doTraceLogs) {
        logger.trace("makeObject() for " + serviceID + " and " + sbbComponent);
    }

    final ClassLoader oldClassLoader = SleeContainerUtils.getCurrentThreadClassLoader();

    try {
        final ClassLoader cl = sbbComponent.getClassLoader();
        if (System.getSecurityManager() != null)
            AccessController.doPrivileged(new PrivilegedAction<Object>() {
                public Object run() {
                    Thread.currentThread().setContextClassLoader(cl);
                    return null;

                }
            });
        else
            Thread.currentThread().setContextClassLoader(cl);

        retval = new SbbObjectImpl(serviceID, sbbComponent);

    } finally {
        if (System.getSecurityManager() != null)
            AccessController.doPrivileged(new PrivilegedAction<Object>() {
                public Object run() {
                    Thread.currentThread().setContextClassLoader(oldClassLoader);
                    return null;
                }
            });
        else
            Thread.currentThread().setContextClassLoader(oldClassLoader);
    }

    retval.setState(SbbObjectState.POOLED);

    return retval;
}

From source file:com.ideabase.repository.core.service.UserServiceImpl.java

/**
 * {@inheritDoc}/*from  w  w  w  .j a  v  a2 s.co  m*/
 */
public boolean isAllowed(final Subject pSubject, final Permission pPermission) {
    final SecurityManager securityManager;
    if (System.getSecurityManager() == null) {
        mLog.debug("No predefined security manager found.");
        securityManager = new SecurityManager();
    } else {
        securityManager = System.getSecurityManager();
    }

    try {
        mLog.debug("Do as privileged action.");
        Subject.doAsPrivileged(pSubject, new PrivilegedAction() {
            public Object run() {
                securityManager.checkPermission(pPermission);
                return null;
            }
        }, null);
        mLog.debug("user action is previleged.");
        return true;
    } catch (RuntimeException e) {
        // No logging here, because, if exception raised it refers to permission
        // failure.
        mLog.warn("Exception raised during verifying the authorization", e);
        return false;
    }
}

From source file:io.gravitee.common.util.RelaxedPropertySource.java

protected boolean isSecurityManagerPresent() {
    return (System.getSecurityManager() != null);
}

From source file:com.sshtools.common.ui.SshToolsApplication.java

/**
 * Creates a new SshToolsApplication object.
 *
 * @param panelClass//from  w  w  w.j  ava2 s  .  c  om
 * @param defaultContainerClass
 */
public SshToolsApplication(Class panelClass, Class defaultContainerClass) {
    this.panelClass = panelClass;
    this.defaultContainerClass = defaultContainerClass;
    additionalOptionsTabs = new java.util.ArrayList();

    try {
        if (System.getSecurityManager() != null) {
            AccessController.checkPermission(new FilePermission("<<ALL FILES>>", "write"));
        }

        File a = getApplicationPreferencesDirectory();

        if (a == null) {
            throw new AccessControlException("Application preferences directory not specified.");
        }

        InputStream in = null;
        MRUList mru = new MRUList();

        try {
            File f = new File(a, getApplicationName() + ".mru");

            if (f.exists()) {
                if (log.isDebugEnabled()) {
                    log.debug("Loading MRU from " + f.getAbsolutePath());
                }

                in = new FileInputStream(f);
                mru.reload(in);
            } else {
                if (log.isDebugEnabled()) {
                    log.debug("MRU file " + f.getAbsolutePath() + " doesn't exist, creating empty list");
                }
            }
        } catch (Exception e) {
            log.error("Could not load MRU list.", e);
        } finally {
            IOUtil.closeStream(in);
        }

        mruModel = new MRUListModel();
        mruModel.setMRUList(mru);
    } catch (AccessControlException ace) {
        log.error("Could not load MRU.", ace);
    }
}

From source file:SwingUtil.java

/**
 * Get a file selection using the FileChooser dialog.
 *
 * @param owner// w  w  w. j a v a2s.c om
 * The parent of this modal dialog.
 * @param defaultSelection
 * The default file selection as a file.
 * @param filter
 * An extension filter
 * @param title
 * The caption for the dialog.
 *
 * @return
 * A selected file or null if no selection is made.
 */
public static File getFileChoice(Component owner, File defaultSelection, FileFilter filter, String title) {
    //
    // There is apparently a bug in the native Windows FileSystem class that
    // occurs when you use a file chooser and there is a security manager
    // active. An error dialog is displayed indicating there is no disk in
    // Drive A:. To avoid this, the security manager is temporarily set to
    // null and then reset after the file chooser is closed.
    //
    SecurityManager sm = null;
    File choice = null;
    JFileChooser chooser = null;

    sm = System.getSecurityManager();
    System.setSecurityManager(null);

    chooser = new JFileChooser();
    if (defaultSelection.isDirectory()) {
        chooser.setCurrentDirectory(defaultSelection);
    } else {
        chooser.setSelectedFile(defaultSelection);
    }
    chooser.setFileFilter(filter);
    chooser.setDialogTitle(title);
    chooser.setApproveButtonText("OK");
    int v = chooser.showOpenDialog(owner);

    owner.requestFocus();
    switch (v) {
    case JFileChooser.APPROVE_OPTION:
        if (chooser.getSelectedFile() != null) {
            choice = chooser.getSelectedFile();
        }
        break;
    case JFileChooser.CANCEL_OPTION:
    case JFileChooser.ERROR_OPTION:
    }
    chooser.removeAll();
    chooser = null;
    System.setSecurityManager(sm);
    return choice;
}

From source file:org.eclipse.gemini.blueprint.extender.internal.blueprint.event.EventAdminDispatcher.java

public void afterRefresh(final BlueprintEvent event) {
    if (dispatcher != null) {
        try {/*from  www.j  a v a2 s .  com*/
            if (System.getSecurityManager() != null) {
                AccessController.doPrivileged(new PrivilegedAction<Object>() {
                    public Object run() {
                        dispatcher.afterRefresh(event);
                        return null;
                    }
                });
            } else {
                dispatcher.afterRefresh(event);
            }
        } catch (Throwable th) {
            log.warn("Cannot dispatch event " + event, th);
        }
    }
}

From source file:org.eclipse.gemini.blueprint.config.internal.adapter.OsgiServiceRegistrationListenerAdapter.java

public void registered(final Object service, final Map serviceProperties) {
    boolean trace = log.isTraceEnabled();

    if (trace)/* w  ww. j a va  2  s.com*/
        log.trace("Invoking registered method with props=" + serviceProperties);

    if (!initialized)
        retrieveTarget();

    boolean isSecurityEnabled = System.getSecurityManager() != null;
    AccessControlContext acc = null;
    if (isSecurityEnabled) {
        acc = SecurityUtils.getAccFrom(beanFactory);
    }

    // first call interface method (if it exists)
    if (isListener) {
        if (trace)
            log.trace("Invoking listener interface methods");

        try {
            if (isSecurityEnabled) {
                AccessController.doPrivileged(new PrivilegedExceptionAction<Object>() {
                    public Object run() throws Exception {
                        ((OsgiServiceRegistrationListener) target).registered(service, serviceProperties);
                        return null;
                    }
                }, acc);
            } else {
                ((OsgiServiceRegistrationListener) target).registered(service, serviceProperties);
            }
        } catch (Exception ex) {
            if (ex instanceof PrivilegedActionException) {
                ex = ((PrivilegedActionException) ex).getException();
            }
            log.warn("Standard registered method on [" + target.getClass().getName() + "] threw exception", ex);
        }
    }

    if (isSecurityEnabled) {
        AccessController.doPrivileged(new PrivilegedAction<Object>() {
            public Object run() {
                CustomListenerAdapterUtils.invokeCustomMethods(target, registrationMethods, service,
                        serviceProperties);
                return null;
            }
        }, acc);
    } else {
        CustomListenerAdapterUtils.invokeCustomMethods(target, registrationMethods, service, serviceProperties);
    }
}

From source file:org.pepstock.jem.ant.tasks.WrapperTask.java

/**
 * Prepares the files required by ANT file using the data description, locks
 * them, and prepares the right file name for GDG. Afterwards calls the
 * defined task.//ww w .ja  v  a 2  s  .c  o m
 * 
 * @throws BuildException occurs if an error occurs
 */
@Override
public void execute() throws BuildException {
    // this boolean is necessary to understand if I have an exception
    // before calling the main class
    boolean isExecutionStarted = false;

    AntBatchSecurityManager batchSM = (AntBatchSecurityManager) System.getSecurityManager();
    batchSM.setInternalAction(true);
    // creates a list with all data description impl
    List<DataDescriptionImpl> ddList = null;

    PropertyHelper propertyHelper = PropertyHelper.getPropertyHelper(getProject());

    // creates a thread local properties
    LocalProperties localProperties = LocalProperties.get(getProject());

    try {
        // gets all data description requested by this task
        ddList = ImplementationsContainer.getInstance().getDataDescriptionsByItem(this);

        // if list of data description is empty, go to execute the command
        if (!ddList.isEmpty()) {
            // sets scope per properties and calls task
            // MUST BE CALLED BEFORE ADDLOCAL
            localProperties.enterScope();

            // this cycle must load variables to local properties
            for (DataDescriptionImpl ddImpl : ddList) {
                // MUST BE CALLED BEFORE setProperty of all proprties
                localProperties.addLocal(StepExec.DD_PREFIX + ddImpl.getName());
            }

            // after locking, checks for GDG
            // is sure here the root (is a properties file) of GDG is locked
            // (doesn't matter if in READ or WRITE)
            // so can read a consistent data from root and gets the right
            // generation
            // starting from relative position
            for (DataDescriptionImpl ddImpl : ddList) {
                // loads GDG generation!! it meeans the real file name of
                // generation
                GDGManager.load(ddImpl);
                log(AntMessage.JEMA034I.toMessage().getFormattedMessage(ddImpl));
                // scans all datasets of datadescription adding new
                // environment variable
                for (DataSetImpl dataset : ddImpl.getDatasets()) {
                    propertyHelper.setProperty(StepExec.DD_PREFIX + ddImpl.getName(),
                            dataset.getRealFile().getAbsolutePath(), true);
                }
            }

        }
        // calls super-method to execute the command configured into JCL
        batchSM.setInternalAction(false);
        // executes the program defined in JCL
        // setting the boolean to TRUE
        isExecutionStarted = true;
        nestedTask.perform();
    } catch (BuildException e1) {
        throw e1;
    } catch (RemoteException e) {
        throw new BuildException(e);
    } catch (IOException e) {
        throw new BuildException(e);
    } finally {
        batchSM.setInternalAction(true);
        // finally and always must release the locks previously asked
        // checks datasets list
        if (ddList != null && !ddList.isEmpty()) {
            // clean scope of properties
            localProperties.exitScope();

            StringBuilder exceptions = new StringBuilder();
            // scans data descriptions
            for (DataDescriptionImpl ddImpl : ddList) {
                try {
                    // consolidates the GDG situation
                    // changing the root (is a properties file)
                    // only if execution started
                    if (isExecutionStarted) {
                        GDGManager.store(ddImpl);
                    }
                } catch (IOException e) {
                    // ignore
                    LogAppl.getInstance().ignore(e.getMessage(), e);
                    log(AntMessage.JEMA036E.toMessage().getFormattedMessage(e.getMessage()));
                    if (exceptions.length() == 0) {
                        exceptions.append(AntMessage.JEMA036E.toMessage().getFormattedMessage(e.getMessage()));
                    } else {
                        exceptions.append(AntMessage.JEMA036E.toMessage().getFormattedMessage(e.getMessage()))
                                .append("\n");
                    }
                }
            }
            if (exceptions.length() > 0) {
                log(StringUtils.center("ATTENTION", 40, "-"));
                log(exceptions.toString());
            }
        }
        batchSM.setInternalAction(false);
    }
}

From source file:io.fabric8.elasticsearch.plugin.auth.OpenShiftTokenAuthentication.java

private Collection<String> retrieveBackendRoles(OpenshiftRequestContext context) {
    List<String> roles = new ArrayList<>();
    if (PluginServiceFactory.isReady()) {
        final SecurityManager sm = System.getSecurityManager();
        if (sm != null) {
            sm.checkPermission(new SpecialPermission());
        }//from   w  w w  .  java  2  s  .  c  o m
        OpenshiftAPIService apiService = PluginServiceFactory.getApiService();
        for (Map.Entry<String, Settings> sar : sars.entrySet()) {
            boolean allowed = AccessController.doPrivileged(new PrivilegedAction<Boolean>() {

                @Override
                public Boolean run() {
                    try {
                        Settings params = sar.getValue();
                        return apiService.localSubjectAccessReview(context.getToken(), params.get("namespace"),
                                params.get("verb"), params.get("resource"), params.get("resourceAPIGroup"),
                                ArrayUtils.EMPTY_STRING_ARRAY);
                    } catch (Exception e) {
                        LOGGER.error("Exception executing LSAR", e);
                    }
                    return false;
                }

            });
            if (allowed) {
                roles.add(sar.getKey());
            }
        }
    }
    return roles;
}