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.OsgiServiceRegistrationListenerAdapter.java

public void unregistered(final Object service, final Map serviceProperties) {

    boolean trace = log.isTraceEnabled();

    if (trace)/*from  w ww.ja v  a  2  s  . c o  m*/
        log.trace("Invoking unregistered 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).unregistered(service, serviceProperties);
                        return null;
                    }
                }, acc);
            } else {
                ((OsgiServiceRegistrationListener) target).unregistered(service, serviceProperties);
            }
        } catch (Exception ex) {
            log.warn("Standard unregistered method on [" + target.getClass().getName() + "] threw exception",
                    ex);
        }
    }

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

From source file:com.nanyou.framework.jdbc.sql.beans.ClassInfo.java

private boolean canAccessPrivateMethods() {
    try {//from w  w w .j a v a  2s . co m
        System.getSecurityManager().checkPermission(new ReflectPermission("suppressAccessChecks"));
        return true;
    } catch (SecurityException e) {
        return false;
    } catch (NullPointerException e) {
        return true;
    }
}

From source file:org.apache.hadoop.fs.s3r.S3RFileSystem.java

/**
 * Returns a {@link ThreadFactory} that names each created thread uniquely,
 * with a common prefix./*from   ww  w  . ja  va 2 s. c  o m*/
 * @param prefix The prefix of every created Thread's name
 * @return a {@link ThreadFactory} that names threads
 */
public static ThreadFactory getNamedThreadFactory(final String prefix) {
    SecurityManager s = System.getSecurityManager();
    final ThreadGroup threadGroup = (s != null) ? s.getThreadGroup() : Thread.currentThread().getThreadGroup();

    return new ThreadFactory() {
        final AtomicInteger threadNumber = new AtomicInteger(1);
        private final int poolNum = poolNumber.getAndIncrement();
        final ThreadGroup group = threadGroup;

        @Override
        public Thread newThread(Runnable r) {
            final String name = prefix + "-pool" + poolNum + "-t" + threadNumber.getAndIncrement();
            return new Thread(group, r, name);
        }
    };
}

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

public InputStream getResourceAsStream(String path) {
    if (System.getSecurityManager() != null) {
        return (InputStream) doPrivileged("getResourceAsStream", new Object[] { path });
    } else {//from  www  .  j  a v a 2s  . c  o  m
        return context.getResourceAsStream(path);
    }
}

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

/**
 * Construct a new ClassLoader with no defined repositories and no
 * parent ClassLoader./*w ww  .  j a  v  a2 s.  c  o  m*/
 */
public WebappClassLoader() {

    super(new URL[0]);
    this.parent = getParent();
    system = getSystemClassLoader();
    securityManager = System.getSecurityManager();

    if (securityManager != null) {
        refreshPolicy();
    }

}

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

/**
 * Called by ANT engine when job is ended.<br>
 * Notifies to JEM the job is ending, cleaning the subject loaded.
 * /*from  w  w w .j a v a2 s .  c o m*/
 * @param event ANT event
 */
@Override
public void buildFinished(BuildEvent event) {
    // sets the SM for internal actions
    AntBatchSecurityManager batchSM = (AntBatchSecurityManager) System.getSecurityManager();
    // sets internal action to true so it can perform same authorized action
    batchSM.setInternalAction(true);
    // flush STD OUT and ERR
    // probably is useless
    System.out.flush();
    System.err.flush();
    try {
        // calls node for job ened
        door.setJobEnded(JobId.VALUE);

        // if job locking is set, performs unlock
        if (isJobLockingScope()) {
            locker.unlock();
        }
    } catch (RemoteException e) {
        throw new BuildException(e.getMessage(), e);
    } catch (AntException e) {
        throw new BuildException(e.getMessage(), e);
    } finally {
        // sets onternal action to false
        batchSM.setInternalAction(false);
    }
}

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

public RequestDispatcher getRequestDispatcher(final String path) {
    if (System.getSecurityManager() != null) {
        return (RequestDispatcher) doPrivileged("getRequestDispatcher", new Object[] { path });
    } else {//from  w w w. jav  a  2 s .c om
        return context.getRequestDispatcher(path);
    }
}

From source file:org.pepstock.jem.ant.tasks.StepJava.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 java
 * main class defined in the task.//from  ww w .j  a v  a2  s  . c om
 * 
 * @throws BuildException occurs if an error occurs
 */
@Override
public void execute() throws BuildException {
    int returnCode = Result.SUCCESS;
    // 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);

    // 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(this);
        // 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(AntKeys.ANT_DATAPATHS_BIND_NAME, referencePaths);

        // scans all datasource passed
        for (DataSource source : sources) {
            // checks if datasource is well defined
            if (source.getResource() == null) {
                throw new BuildException(AntMessage.JEMA027E.toMessage().getFormattedMessage());
            } 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 BuildException(AntMessage.JEMA028E.toMessage().getFormattedMessage(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 BuildException(
                                AntMessage.JEMA028E.toMessage().getFormattedMessage(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 BuildException(AntMessage.JEMA028E.toMessage()
                                    .getFormattedMessage(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())));
            }

            // 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());
                    entry.setValue(value);
                }
                // adds to reference
                ref.add(new StringRefAddr(CommonKeys.RESOURCE_CUSTOM_PROPERTIES,
                        res.getCustomPropertiesString()));
            }

            // binds the object with [name]
            log(AntMessage.JEMA035I.toMessage().getFormattedMessage(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);

                log(AntMessage.JEMA034I.toMessage().getFormattedMessage(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);
            }

        }
        // sets fork to false
        // in this way java main class runs inside the same process
        // this is mandatory if wants to JNDI without any network
        // connection, like RMI
        super.setFork(false);

        // changes the main class to apply the annotations of JEM
        setCustomMainClass();

        batchSM.setInternalAction(false);
        // executes the java main class defined in JCL
        // setting the boolean to TRUE
        isExecutionStarted = true;
        // tried to set fields where
        // annotations are used
        super.execute();
    } catch (BuildException e) {
        returnCode = Result.ERROR;
        throw e;
    } catch (RemoteException e) {
        returnCode = Result.ERROR;
        throw new BuildException(e);
    } catch (IOException e) {
        returnCode = Result.ERROR;
        throw new BuildException(e);
    } catch (NamingException e) {
        returnCode = Result.ERROR;
        throw new BuildException(e);
    } finally {
        batchSM.setInternalAction(true);
        String rcObject = System.getProperty(RESULT_KEY);
        if (rcObject != null) {
            returnCode = Parser.parseInt(rcObject, Result.SUCCESS);
        }
        ReturnCodesContainer.getInstance().setReturnCode(getProject(), this, returnCode);
        // 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);
                    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");
                    }
                }
                // unbinds all data sources
                try {
                    ic.unbind(ddImpl.getName());
                } catch (NamingException e) {
                    // ignore
                    LogAppl.getInstance().ignore(e.getMessage(), e);
                    log(AntMessage.JEMA037E.toMessage().getFormattedMessage(e.getMessage()));
                }
            }
            for (DataSource source : sources) {
                if (source.getName() != null) {
                    // unbinds all resources
                    try {
                        ic.unbind(source.getName());
                    } catch (NamingException e) {
                        // ignore
                        LogAppl.getInstance().ignore(e.getMessage(), e);
                        log(AntMessage.JEMA037E.toMessage().getFormattedMessage(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) {
                log(StringUtils.center("ATTENTION", 40, "-"));
                log(exceptions.toString());
            }
            batchSM.setInternalAction(false);
        }
    }
}

From source file:com.enioka.jqm.tools.JqmEngine.java

/**
 * Starts the engine//from  w  w  w . ja  v a2  s  .c om
 * 
 * @param nodeName
 *            the name of the node to start, as in the NODE table of the database.
 * @throws JqmInitError
 */
void start(String nodeName) {
    if (nodeName == null || nodeName.isEmpty()) {
        throw new IllegalArgumentException("nodeName cannot be null or empty");
    }

    // Set thread name - used in audits
    Thread.currentThread().setName("JQM engine;;" + nodeName);
    Helpers.setLogFileName(nodeName);

    // Log: we are starting...
    jqmlogger.info("JQM engine version " + this.getVersion() + " for node " + nodeName + " is starting");
    jqmlogger.info("Java version is " + System.getProperty("java.version") + ". JVM was made by "
            + System.getProperty("java.vendor") + " as " + System.getProperty("java.vm.name") + " version "
            + System.getProperty("java.vm.version"));

    // JNDI first - the engine itself uses JNDI to fetch its connections!
    Helpers.registerJndiIfNeeded();

    // Database connection
    EntityManager em = Helpers.getNewEm();

    // Node configuration is in the database
    node = em.createQuery("SELECT n FROM Node n WHERE n.name = :l", Node.class).setParameter("l", nodeName)
            .getSingleResult();

    // Check if double-start
    long toWait = (long) (1.1 * Long.parseLong(Helpers.getParameter("internalPollingPeriodMs", "60000", em)));
    if (node.getLastSeenAlive() != null
            && Calendar.getInstance().getTimeInMillis() - node.getLastSeenAlive().getTimeInMillis() <= toWait) {
        long r = Calendar.getInstance().getTimeInMillis() - node.getLastSeenAlive().getTimeInMillis();
        throw new JqmInitErrorTooSoon("Another engine named " + nodeName + " was running less than " + r / 1000
                + " seconds ago. Either stop the other node, or if it already stopped, please wait "
                + (toWait - r) / 1000 + " seconds");
    }

    // Prevent very quick multiple starts by immediately setting the keep-alive
    em.getTransaction().begin();
    node.setLastSeenAlive(Calendar.getInstance());
    em.getTransaction().commit();

    // Only start if the node configuration seems OK
    Helpers.checkConfiguration(nodeName, em);

    // Log parameters
    Helpers.dumpParameters(em, node);

    // Log level
    Helpers.setLogLevel(node.getRootLogLevel());

    // Log multicasting (& log4j stdout redirect)
    GlobalParameter gp1 = em
            .createQuery("SELECT g FROM GlobalParameter g WHERE g.key = :k", GlobalParameter.class)
            .setParameter("k", "logFilePerLaunch").getSingleResult();
    if ("true".equals(gp1.getValue()) || "both".equals(gp1.getValue())) {
        RollingFileAppender a = (RollingFileAppender) Logger.getRootLogger().getAppender("rollingfile");
        MultiplexPrintStream s = new MultiplexPrintStream(System.out, FilenameUtils.getFullPath(a.getFile()),
                "both".equals(gp1.getValue()));
        System.setOut(s);
        ((ConsoleAppender) Logger.getRootLogger().getAppender("consoleAppender"))
                .setWriter(new OutputStreamWriter(s));
        s = new MultiplexPrintStream(System.err, FilenameUtils.getFullPath(a.getFile()),
                "both".equals(gp1.getValue()));
        System.setErr(s);
    }

    // Remote JMX server
    if (node.getJmxRegistryPort() != null && node.getJmxServerPort() != null && node.getJmxRegistryPort() > 0
            && node.getJmxServerPort() > 0) {
        JmxAgent.registerAgent(node.getJmxRegistryPort(), node.getJmxServerPort(), node.getDns());
    } else {
        jqmlogger.info(
                "JMX remote listener will not be started as JMX registry port and JMX server port parameters are not both defined");
    }

    // Jetty
    this.server = new JettyServer();
    this.server.start(node, em);

    // JMX
    if (node.getJmxServerPort() != null && node.getJmxServerPort() > 0) {
        try {
            MBeanServer mbs = ManagementFactory.getPlatformMBeanServer();
            name = new ObjectName("com.enioka.jqm:type=Node,name=" + this.node.getName());
            mbs.registerMBean(this, name);
        } catch (Exception e) {
            throw new JqmInitError("Could not create JMX beans", e);
        }
        jqmlogger.info("JMX management bean for the engine was registered");
    } else {
        loadJmxBeans = false;
        jqmlogger.info("JMX management beans will not be loaded as JMX server port is null or zero");
    }

    // Security
    if (System.getSecurityManager() == null) {
        System.setSecurityManager(new SecurityManagerPayload());
    }
    jqmlogger.info("Security manager was registered");

    // Cleanup
    purgeDeadJobInstances(em, this.node);

    // Force Message EMF load
    em.createQuery("SELECT m FROM Message m WHERE 1=0", Message.class).getResultList();

    // Pollers
    syncPollers(em, this.node);
    jqmlogger.info("All required queues are now polled");

    // Internal poller (stop notifications, keepalive)
    intPoller = new InternalPoller(this);
    Thread t = new Thread(intPoller);
    t.start();

    // Kill notifications
    killHook = new SignalHandler(this);
    Runtime.getRuntime().addShutdownHook(killHook);

    // Done
    em.close();
    em = null;
    latestNodeStartedName = node.getName();
    jqmlogger.info("End of JQM engine initialization");
}

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

/**
 * Construct a new ClassLoader with no defined repositories and no
 * parent ClassLoader./*from w  w w. j  a  v  a  2s  .  co  m*/
 */
public WebappClassLoader(ClassLoader parent) {

    super(new URL[0], parent);

    this.parent = getParent();

    system = getSystemClassLoader();
    securityManager = System.getSecurityManager();

    if (securityManager != null) {
        refreshPolicy();
    }
}