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.apache.catalina.core.ApplicationContextFacade.java

public String getRealPath(String path) {
    if (System.getSecurityManager() != null) {
        return (String) doPrivileged("getRealPath", new Object[] { path });
    } else {// w ww.ja v a  2 s.  c o  m
        return context.getRealPath(path);
    }
}

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

public String getServerInfo() {
    if (System.getSecurityManager() != null) {
        return (String) doPrivileged("getServerInfo", null);
    } else {/*from w  w  w. j  av  a  2 s.c o m*/
        return context.getServerInfo();
    }
}

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

@Override
public void destroy() {
    if (!CollectionUtils.isEmpty(this.beanPostProcessors)) {
        for (DestructionAwareBeanPostProcessor processor : this.beanPostProcessors) {
            processor.postProcessBeforeDestruction(this.bean, this.beanName);
        }// w  w w .  j  a  v a  2 s .co m
    }

    if (this.invokeDisposableBean) {
        if (logger.isDebugEnabled()) {
            logger.debug("Invoking destroy() on bean with name '" + this.beanName + "'");
        }
        try {
            if (System.getSecurityManager() != null) {
                AccessController.doPrivileged((PrivilegedExceptionAction<Object>) () -> {
                    ((DisposableBean) bean).destroy();
                    return null;
                }, acc);
            } else {
                ((DisposableBean) bean).destroy();
            }
        } catch (Throwable ex) {
            String msg = "Invocation of destroy method failed on bean with name '" + this.beanName + "'";
            if (logger.isDebugEnabled()) {
                logger.warn(msg, ex);
            } else {
                logger.warn(msg + ": " + ex);
            }
        }
    }

    if (this.destroyMethod != null) {
        invokeCustomDestroyMethod(this.destroyMethod);
    } else if (this.destroyMethodName != null) {
        Method methodToCall = determineDestroyMethod(this.destroyMethodName);
        if (methodToCall != null) {
            invokeCustomDestroyMethod(methodToCall);
        }
    }
}

From source file:org.wso2.carbon.appfactory.ext.Util.java

public static boolean isRequestFromSystemCode() {
    SecurityManager secMan = System.getSecurityManager();
    if (secMan != null) {
        try {/*from   w  ww.  j av  a2  s  .  com*/
            secMan.checkPermission(new AppFactorySecurityPermission("RegistryPermission"));
        } catch (RuntimeException e) {
            if (log.isDebugEnabled()) {
                log.debug(e);
            }
            return false;
        }
    }
    return true;
}

From source file:org.pepstock.jem.jbpm.tasks.JemWorkItemHandler.java

/**
 * Executes the work item, creating all JEM features and therefore reachable by JNDI.
 * /*from w  w  w .  j  a  va2  s  .  c o  m*/
 * @param task current JBPM task
 * @param item sub workitem to execute
 * @param parms list of parameters, created by JBPM for this work item
 * @return return code of work item execution
 * @throws JemException if any error occurs
 */
private int execute(Task task, JemWorkItem item, Map<String, Object> parms) throws JemException {
    // this boolean is necessary to understand if I have an exception 
    // before calling the main class
    boolean isExecutionStarted = false;

    JBpmBatchSecurityManager batchSM = (JBpmBatchSecurityManager) System.getSecurityManager();

    // object serializer and deserializer into XML
    XStream xstream = new XStream();

    List<DataDescriptionImpl> ddList = null;
    InitialContext ic = null;

    try {
        // gets all data description requested by this task
        ddList = ImplementationsContainer.getInstance().getDataDescriptionsByItem(task);
        // new intial context for JNDI
        ic = ContextUtils.getContext();

        // LOADS DataPaths Container
        Reference referencePaths = new DataPathsReference();
        // loads dataPaths on static name
        String xmlPaths = xstream.toXML(DataPathsContainer.getInstance());
        // adds the String into a data stream reference
        referencePaths.add(new StringRefAddr(StringRefAddrKeys.DATAPATHS_KEY, xmlPaths));
        // re-bind the object inside the JNDI context
        ic.rebind(JBpmKeys.JBPM_DATAPATHS_BIND_NAME, referencePaths);

        // scans all datasource passed
        for (DataSource source : task.getDataSources()) {
            // checks if datasource is well defined
            if (source.getResource() == null) {
                throw new MessageException(JBpmMessage.JEMM027E);
            } else if (source.getName() == null) {
                // if name is missing, it uses the same string 
                // used to define the resource
                source.setName(source.getResource());
            }

            // gets the RMi object to get resources
            CommonResourcer resourcer = InitiatorManager.getCommonResourcer();
            // lookups by RMI for the database 
            Resource res = resourcer.lookup(JobId.VALUE, source.getResource());
            if (!batchSM.checkResource(res)) {
                throw new MessageException(JBpmMessage.JEMM028E, res.toString());
            }

            // all properties create all StringRefAddrs necessary  
            Map<String, ResourceProperty> properties = res.getProperties();
            // scans all properteis set by JCL
            for (Property property : source.getProperties()) {
                if (property.isCustom()) {
                    if (res.getCustomProperties() == null) {
                        res.setCustomProperties(new HashMap<String, String>());
                    }
                    if (!res.getCustomProperties().containsKey(property.getName())) {
                        res.getCustomProperties().put(property.getName(), property.getText().toString());
                    } else {
                        throw new MessageException(JBpmMessage.JEMM028E, property.getName(), res);
                    }
                } else {
                    // if a key is defined FINAL, throw an exception
                    for (ResourceProperty resProperty : properties.values()) {
                        if (resProperty.getName().equalsIgnoreCase(property.getName())
                                && !resProperty.isOverride()) {
                            throw new MessageException(JBpmMessage.JEMM028E, property.getName(), res);
                        }
                    }
                    ResourcePropertiesUtil.addProperty(res, property.getName(), property.getText().toString());
                }
            }

            // creates a JNDI reference
            Reference ref = getReference(resourcer, res, source, ddList);

            // loads all properties into RefAddr
            for (ResourceProperty property : properties.values()) {
                ref.add(new StringRefAddr(property.getName(),
                        replaceProperties(property.getValue(), JobsProperties.getInstance().getProperties())));
            }

            // loads custom properties in a string format
            if (res.getCustomProperties() != null && !res.getCustomProperties().isEmpty()) {
                // loads all entries and substitute variables
                for (Entry<String, String> entry : res.getCustomProperties().entrySet()) {
                    String value = replaceProperties(entry.getValue(),
                            JobsProperties.getInstance().getProperties());
                    entry.setValue(value);
                }
                // adds to reference
                ref.add(new StringRefAddr(CommonKeys.RESOURCE_CUSTOM_PROPERTIES,
                        res.getCustomPropertiesString()));
            }

            // binds the object with format [type]/[name]
            LogAppl.getInstance().emit(JBpmMessage.JEMM035I, res);
            ic.rebind(source.getName(), ref);
        }

        // if list of data description is empty, go to execute java main
        // class
        if (!ddList.isEmpty()) {

            // 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) {
                // creates a reference, accessible by name. Is data stream
                // reference because
                // contains a stream of data which represents a object
                Reference reference = new DataStreamReference();
                // loads GDG generation!! it meeans the real file name of
                // generation
                GDGManager.load(ddImpl);

                LogAppl.getInstance().emit(JBpmMessage.JEMM034I, ddImpl);
                // serialize data descriptor object into xml string
                // in this way is easier pass to object across different
                // classloader, by JNDI.
                // This xml, by reference, will be used by DataStreamFactory
                // when
                // java main class requests a resource by a JNDI call
                String xml = xstream.toXML(ddImpl);
                // adds the String into a data stream reference
                reference.add(new StringRefAddr(StringRefAddrKeys.DATASTREAMS_KEY, xml));
                // re-bind the object inside the JNDI context
                ic.rebind(ddImpl.getName(), reference);
            }

        }
        batchSM.setInternalAction(false);
        // executes the java main class defined in JCL
        // setting the boolean to TRUE
        isExecutionStarted = true;
        return item.execute(parms);
    } catch (RemoteException e) {
        throw new JemException(e);
    } catch (RuntimeException e) {
        throw e;
    } catch (Exception e) {
        throw new JemException(e);
    } finally {
        batchSM.setInternalAction(true);
        // checks datasets list
        if (ddList != null && !ddList.isEmpty()) {
            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);
                    LogAppl.getInstance().emit(JBpmMessage.JEMM036E, e.getMessage());
                    if (exceptions.length() == 0) {
                        exceptions.append(JBpmMessage.JEMM036E.toMessage().getFormattedMessage(e.getMessage()));
                    } else {
                        exceptions.append(JBpmMessage.JEMM036E.toMessage().getFormattedMessage(e.getMessage()))
                                .append("\n");
                    }
                }
                // unbinds all data sources
                try {
                    ic.unbind(ddImpl.getName());
                } catch (NamingException e) {
                    // ignore
                    LogAppl.getInstance().ignore(e.getMessage(), e);
                    LogAppl.getInstance().emit(JBpmMessage.JEMM037E, e.getMessage());
                }
            }
            // checks if has exception using the stringbuffer
            // used to collect exception string. 
            // Stringbuffer is not empty, throws an exception
            if (exceptions.length() > 0) {
                LogAppl.getInstance().emit(JBpmMessage.JEMM055E, exceptions.toString());
            }
        }
        for (DataSource source : task.getDataSources()) {
            if (source.getName() != null) {
                // unbinds all resources
                try {
                    ic.unbind(source.getName());
                } catch (NamingException e) {
                    // ignore
                    LogAppl.getInstance().ignore(e.getMessage(), e);
                    LogAppl.getInstance().emit(JBpmMessage.JEMM037E, e.getMessage());
                }
            }
        }
        batchSM.setInternalAction(false);
    }
}

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

public String getInitParameter(String name) {
    if (System.getSecurityManager() != null) {
        return (String) doPrivileged("getInitParameter", new Object[] { name });
    } else {/*from   ww w  . ja v a2 s. co  m*/
        return context.getInitParameter(name);
    }
}

From source file:org.lilyproject.runtime.LilyRuntime.java

public void stop() {
    if (state != LifeCycle.STARTED) {
        throw new LilyRTException(
                "Cannot stop the runtime, it is in state " + state + " instead of " + LifeCycle.STARTED);
    }/*from  ww  w .  j  ava  2  s.  co  m*/

    // TODO temporarily disabled because FAM.stop() is slow
    // See JCI jira patch: https://issues.apache.org/jira/browse/JCI-57 (the newer one in commons-io has the same problem)
    // fam.stop();
    // Added the following workaround:
    if (System.getSecurityManager() == null) {
        try {
            Field famRunningField = fam.getClass().getDeclaredField("running");
            famRunningField.setAccessible(true);
            Field threadField = fam.getClass().getDeclaredField("thread");
            threadField.setAccessible(true);
            Thread famThread = (Thread) threadField.get(fam);
            if (famThread != null) {
                famRunningField.setBoolean(fam, false);
                famThread.interrupt();
                fam.stop();
            }
        } catch (Exception e) {
            infolog.error("Error stopping FilesystemAlterationMonitor", e);
        }
    } else {
        infolog.warn(
                "Unable to stop the FilesystemAlterationMonitor using workaround since a security manager is installed.");
    }

    // In case starting the runtime failed, modules might be null
    if (modules != null) {
        infolog.info("Shutting down the modules.");
        List<Module> reversedModules = new ArrayList<Module>(this.modules);
        Collections.reverse(reversedModules);
        this.modules = null;
        this.javaServiceManager.stop();

        for (Module module : reversedModules) {
            try {
                module.shutdown();
            } catch (Throwable t) {
                infolog.error("Error shutting down module " + module.getDefinition().getId(), t);
            }
        }
    }

    settings.getConfManager().shutdown();

}

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

/**
 * Set the filter definition we are configured for.  This has the side
 * effect of instantiating an instance of the corresponding filter class.
 *
 * @param filterDef The new filter definition
 *
 * @exception ClassCastException if the specified class does not implement
 *  the <code>javax.servlet.Filter</code> interface
 * @exception ClassNotFoundException if the filter class cannot be found
 * @exception IllegalAccessException if the filter class cannot be
 *  publicly instantiated/*from  www .java 2 s . co  m*/
 * @exception InstantiationException if an exception occurs while
 *  instantiating the filter object
 * @exception ServletException if thrown by the filter's init() method
 */
void setFilterDef(FilterDef filterDef) throws ClassCastException, ClassNotFoundException,
        IllegalAccessException, InstantiationException, ServletException {

    this.filterDef = filterDef;
    if (filterDef == null) {

        // Release any previously allocated filter instance
        if (this.filter != null) {
            if (System.getSecurityManager() != null) {
                try {
                    SecurityUtil.doAsPrivilege("destroy", filter);
                    SecurityUtil.remove(filter);
                } catch (java.lang.Exception ex) {
                    log.error("ApplicationFilterConfig.doAsPrivilege", ex);
                }
            } else {
                filter.destroy();
            }
        }
        this.filter = null;

    } else {

        // Allocate a new filter instance
        Filter filter = getFilter();

    }

}

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

public Enumeration getInitParameterNames() {
    if (System.getSecurityManager() != null) {
        return (Enumeration) doPrivileged("getInitParameterNames", null);
    } else {//ww  w  . j a  v  a  2s . co m
        return context.getInitParameterNames();
    }
}

From source file:org.wso2.carbon.core.ServerManagement.java

/**
 * Method to change the state of a node from "maintenance" to "normal"
 *
 * @throws Exception If an error occurs while trying to connect to the Tomcat MBean
 *///from   ww  w .  j  a va2s.  c  o  m
public void endMaintenance() throws Exception {
    SecurityManager secMan = System.getSecurityManager();
    if (secMan != null) {
        secMan.checkPermission(new ManagementPermission("control"));
    }
    log.info("Switching to normal mode...");
    for (Iterator iter = inTransports.values().iterator(); iter.hasNext();) {
        TransportInDescription tinDesc = (TransportInDescription) iter.next();
        TransportListener transport = tinDesc.getReceiver();
        transport.start();
    }
    log.info("Switched to normal mode");
}