Example usage for java.security PrivilegedAction PrivilegedAction

List of usage examples for java.security PrivilegedAction PrivilegedAction

Introduction

In this page you can find the example usage for java.security PrivilegedAction PrivilegedAction.

Prototype

PrivilegedAction

Source Link

Usage

From source file:org.apache.axis2.description.AxisService.java

/**
 * Constructor AxisService.//from w w w.j a  v  a2s. com
 */
public AxisService() {
    super();
    this.operationsAliasesMap = new HashMap();
    this.invalidOperationsAliases = new ArrayList();
    moduleConfigmap = new HashMap();
    // by default service scope is for the request
    scope = Constants.SCOPE_REQUEST;
    httpLocationDispatcherMap = new HashMap();
    messageReceivers = new HashMap();
    moduleRefs = new ArrayList();
    schemaList = new ArrayList();
    serviceClassLoader = (ClassLoader) org.apache.axis2.java.security.AccessController
            .doPrivileged(new PrivilegedAction<ClassLoader>() {
                public ClassLoader run() {
                    return Thread.currentThread().getContextClassLoader();
                }
            });
    objectSupplier = new DefaultObjectSupplier();
    dataLocators = new HashMap();
    dataLocatorClassNames = new HashMap();
}

From source file:com.inmobi.conduit.distcp.tools.mapred.TestCopyMapper.java

@Test
public void testPreserve() {
    try {/* w  w w . j  a  va2s . c  o  m*/
        deleteState();
        createSourceData();

        UserGroupInformation tmpUser = UserGroupInformation.createRemoteUser("guest");

        final CopyMapper copyMapper = new CopyMapper();

        final Mapper<Text, FileStatus, NullWritable, Text>.Context context = tmpUser
                .doAs(new PrivilegedAction<Mapper<Text, FileStatus, NullWritable, Text>.Context>() {
                    @Override
                    public Mapper<Text, FileStatus, NullWritable, Text>.Context run() {
                        try {
                            StatusReporter reporter = new StubStatusReporter();
                            InMemoryWriter writer = new InMemoryWriter();
                            return getMapperContext(copyMapper, reporter, writer);
                        } catch (Exception e) {
                            LOG.error("Exception encountered ", e);
                            throw new RuntimeException(e);
                        }
                    }
                });

        EnumSet<DistCpOptions.FileAttribute> preserveStatus = EnumSet.allOf(DistCpOptions.FileAttribute.class);

        context.getConfiguration().set(DistCpConstants.CONF_LABEL_PRESERVE_STATUS,
                DistCpUtils.packAttributes(preserveStatus));

        touchFile(SOURCE_PATH + "/src/file.gz");
        mkdirs(TARGET_PATH);
        cluster.getFileSystem().setPermission(new Path(TARGET_PATH), new FsPermission((short) 511));

        final FileSystem tmpFS = tmpUser.doAs(new PrivilegedAction<FileSystem>() {
            @Override
            public FileSystem run() {
                try {
                    return FileSystem.get(configuration);
                } catch (IOException e) {
                    LOG.error("Exception encountered ", e);
                    Assert.fail("Test failed: " + e.getMessage());
                    throw new RuntimeException("Test ought to fail here");
                }
            }
        });

        tmpUser.doAs(new PrivilegedAction<Integer>() {
            @Override
            public Integer run() {
                try {
                    copyMapper.setup(context);
                    copyMapper.map(new Text("/src/file.gz"),
                            tmpFS.getFileStatus(new Path(SOURCE_PATH + "/src/file.gz")), context);
                    Assert.fail("Expected copy to fail");
                } catch (AccessControlException e) {
                    Assert.assertTrue("Got exception: " + e.getMessage(), true);
                } catch (Exception e) {
                    throw new RuntimeException(e);
                }
                return null;
            }
        });
    } catch (Exception e) {
        LOG.error("Exception encountered ", e);
        Assert.fail("Test failed: " + e.getMessage());
    }
}

From source file:org.eclipse.gemini.blueprint.service.exporter.support.OsgiServiceFactoryBean.java

/**
 * Registration method.//from  w  w  w.java2 s.c  o  m
 * 
 * @param classes
 * @param serviceProperties
 * @return the ServiceRegistration
 */
ServiceRegistration registerService(Class<?>[] classes, final Dictionary serviceProperties) {
    Assert.notEmpty(classes, "at least one class has to be specified for exporting "
            + "(if autoExport is enabled then maybe the object doesn't implement any interface)");

    // create an array of classnames (used for registering the service)
    final String[] names = ClassUtils.toStringArray(classes);
    // sort the names in alphabetical order (eases debugging)
    Arrays.sort(names);

    log.info("Publishing service under classes [" + ObjectUtils.nullSafeToString(names) + "]");

    ServiceFactory serviceFactory = new PublishingServiceFactory(resolver, classes,
            (ExportContextClassLoaderEnum.SERVICE_PROVIDER.equals(contextClassLoader)), classLoader,
            aopClassLoader, bundleContext);

    if (isBeanBundleScoped())
        serviceFactory = new OsgiBundleScope.BundleScopeServiceFactory(serviceFactory);

    if (System.getSecurityManager() != null) {
        AccessControlContext acc = SecurityUtils.getAccFrom(beanFactory);
        final ServiceFactory serviceFactoryFinal = serviceFactory;
        return AccessController.doPrivileged(new PrivilegedAction<ServiceRegistration>() {
            public ServiceRegistration run() {
                return bundleContext.registerService(names, serviceFactoryFinal, serviceProperties);
            }
        }, acc);
    } else {
        return bundleContext.registerService(names, serviceFactory, serviceProperties);
    }
}

From source file:org.apache.axis2.datasource.jaxb.JAXBDSContext.java

/**
 * Preferred way to marshal objects.// ww w .  j a  va 2s.c o m
 * 
 * @param b Object that can be rendered as an element and the element name is known by the
 * Marshaller
 * @param m Marshaller
 * @param writer XMLStreamWriter
 */
private static void marshalByElement(final Object b, final Marshaller m, final XMLStreamWriter writer,
        final boolean optimize) {
    AccessController.doPrivileged(new PrivilegedAction() {
        public Object run() {
            // Marshalling directly to the output stream is faster than marshalling through the
            // XMLStreamWriter. 
            // Take advantage of this optimization if there is an output stream.
            try {
                OutputStream os = (optimize) ? getOutputStream(writer, m) : null;
                if (os != null) {
                    if (DEBUG_ENABLED) {
                        log.debug("Invoking marshalByElement.  " + "Marshaling to an OutputStream. "
                                + "Object is " + getDebugName(b));
                    }
                    writer.flush();
                    m.marshal(b, os);
                } else {
                    if (DEBUG_ENABLED) {
                        log.debug("Invoking marshalByElement.  " + "Marshaling to an XMLStreamWriter. "
                                + "Object is " + getDebugName(b));
                    }
                    m.marshal(b, writer);
                }
            } catch (OMException e) {
                throw e;
            } catch (Throwable t) {
                throw new OMException(t);
            }
            return null;
        }
    });
}

From source file:de.betterform.agent.betty.AppletProcessor.java

private void ensureContextClassLoader() {
    AccessController.doPrivileged(new PrivilegedAction() {
        public Object run() {
            Thread.currentThread().setContextClassLoader(contextClassLoader);
            return null;
        }/*from w w w  .jav  a  2 s. c om*/
    });
}

From source file:org.jwebsocket.plugins.scripting.ScriptingPlugIn.java

/**
 * Loads an script application.//from   w w  w .  ja va  2 s.  c o m
 *
 * @param aAppName The application name
 * @param aAppPath The application home path
 * @param aHotLoad
 * @return
 * @throws Exception
 */
private void loadApp(final String aAppName, String aAppPath, boolean aHotLoad) throws Exception {
    // notifying before app reload event here
    BaseScriptApp lScript = mApps.get(aAppName);
    if (null != lScript) {
        lScript.notifyEvent(BaseScriptApp.EVENT_BEFORE_APP_RELOAD, new Object[] { aHotLoad });
        if (!aHotLoad) {
            destroyAppBeans(lScript);
        }
    }

    // parsing app manifest
    File lManifestFile = new File(aAppPath + "/manifest.json");

    // parsing app manifest file
    ObjectMapper lMapper = new ObjectMapper();
    Map<String, Object> lTree = lMapper.readValue(lManifestFile, Map.class);
    Token lManifestJSON = TokenFactory.createToken();
    lManifestJSON.setMap(lTree);

    // getting script language extension
    String lExt = lManifestJSON.getString(Manifest.LANGUAGE_EXT, "js");

    // validating bootstrap file
    final File lBootstrap = new File(aAppPath + "/App." + lExt);

    // support hot app load
    if (aHotLoad && mApps.containsKey(aAppName)) {
        try {
            // loading app
            mApps.get(aAppName).eval(lBootstrap.getPath());
        } catch (ScriptException lEx) {
            mLog.error("Script applicaton '" + aAppName + "' failed to start: " + lEx.getMessage());
            mApps.remove(aAppName);
            throw new ScriptException(lEx.getMessage());
        }
    } else {
        LocalLoader lClassLoader = new LocalLoader((URLClassLoader) ClassLoader.getSystemClassLoader());
        ScriptEngineManager lManager = new ScriptEngineManager(lClassLoader);

        final ScriptEngine lScriptApp;
        if ("js".equals(lExt)) {
            // making "nashorn" the default engine for JavaScript
            if (null != lManager.getEngineByName("nashorn")) {
                lScriptApp = lManager.getEngineByName("nashorn");
            } else {
                lScriptApp = lManager.getEngineByExtension(lExt);
            }
        } else {
            lScriptApp = lManager.getEngineByExtension(lExt);
        }

        // crating the high level script app instance
        if ("js".equals(lExt)) {
            mApps.put(aAppName, new JavaScriptApp(this, aAppName, aAppPath, lScriptApp, lClassLoader));
        } else {
            String lMsg = "The extension '" + lExt + "' is not currently supported!";
            mLog.error(lMsg);
            throw new Exception(lMsg);
        }

        final BaseScriptApp lApp = mApps.get(aAppName);
        // loading application into security sandbox
        Tools.doPrivileged(mSettings.getAppPermissions(aAppName, aAppPath), new PrivilegedAction<Object>() {
            @Override
            public Object run() {
                try {
                    // loading app
                    lApp.eval(lBootstrap.getPath());
                    return null;
                } catch (Exception lEx) {
                    mLog.error("Script applicaton '" + aAppName + "' failed to start: " + lEx.getMessage());
                    mApps.remove(aAppName);
                    throw new RuntimeException(lEx);
                }
            }
        });
    }

    // notifying app loaded event
    mApps.get(aAppName).notifyEvent(BaseScriptApp.EVENT_APP_LOADED, new Object[] { aHotLoad });

    if (mLog.isDebugEnabled()) {
        mLog.debug(aAppName + "(" + lExt + ") application loaded successfully!");
    }
}

From source file:com.citrix.cpbm.portal.fragment.controllers.AbstractUsersController.java

/**
 * This method used for validation of Username
 * //  w  ww.  j  a  va2s  . c o  m
 * @param username
 * @return String
 */
@RequestMapping(value = "/validate_username")
@ResponseBody
public String validateUsername(@RequestParam("user.username") final String username) {
    logger.debug("In validateUsername() method start and username is : " + username);
    // validate with portal users table
    User loggedInUser = getCurrentUser();
    final String loggedInTenantSuffix = loggedInUser.getTenant().getUsernameSuffix();

    String exists = Boolean.FALSE.toString();
    try {
        privilegeService.runAsPortal(new PrivilegedAction<Void>() {

            @Override
            public Void run() {
                if (config.getValue(Names.com_citrix_cpbm_username_duplicate_allowed).equals("true")) {
                    userService.getUserByParam("username", username + "@" + loggedInTenantSuffix, true);
                    logger.debug("In validateUsername() method end");
                } else {
                    userService.getUserByParam("username", username, true);
                    logger.debug("In validateUsername() method end");
                }
                return null;
            }
        });
    } catch (NoSuchUserException ex) {
        logger.debug(username + ": not exits in users table");
        return Boolean.TRUE.toString();
    }
    return exists;
}

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

/**
 * Cancel waiting due to timeout./*from www  . jav  a 2 s. c  o  m*/
 */
private void timeout() {
    ApplicationContextException e;
    List<OsgiServiceDependencyEvent> events = null;
    String filterAsString = null;

    synchronized (monitor) {
        // deregister listener to get an accurate snapshot of the
        // unsatisfied dependencies.

        if (dependencyDetector != null) {
            dependencyDetector.deregister();
            events = dependencyDetector.getUnsatisfiedDependenciesAsEvents();
            filterAsString = dependencyDetector.createUnsatisfiedDependencyFilter();
        }
    }

    Filter filter = (filterAsString != null ? OsgiFilterUtils.createFilter(filterAsString) : null);

    log.warn("Timeout occurred before finding service dependencies for [" + delegateContext.getDisplayName()
            + "]");

    String bundleName = null;
    if (System.getSecurityManager() != null) {
        bundleName = AccessController.doPrivileged(new PrivilegedAction<String>() {
            public String run() {
                return OsgiStringUtils.nullSafeSymbolicName(getBundle());
            }
        });
    } else {
        bundleName = OsgiStringUtils.nullSafeSymbolicName(getBundle());
    }

    // generate exception
    e = new ApplicationContextException("Application context " + "initialization for '" + bundleName
            + "' has timed out waiting for " + filterAsString);
    e.fillInStackTrace();

    // send notification
    delegatedMulticaster.multicastEvent(new BootstrappingDependenciesFailedEvent(delegateContext,
            delegateContext.getBundle(), e, events, filter));

    fail(e, true);
}

From source file:org.apache.openjpa.util.ProxyManagerImpl.java

/**
 * Return the cached factory proxy for the given bean type.
 *///  w  w  w  . j  a  v  a2 s .  co  m
private ProxyBean getFactoryProxyBean(Object orig) {
    final Class type = orig.getClass();
    if (isUnproxyable(type))
        return null;

    // we don't lock here; ok if two proxies get generated for same type
    ProxyBean proxy = (ProxyBean) _proxies.get(type);
    if (proxy == null && !_proxies.containsKey(type)) {
        ClassLoader l = GeneratedClasses.getMostDerivedLoader(type, ProxyBean.class);
        Class pcls = loadBuildTimeProxy(type, l);
        if (pcls == null) {
            // TODO Move this to J2DOPrivHelper? 
            BCClass bc = AccessController.doPrivileged(new PrivilegedAction<BCClass>() {
                public BCClass run() {
                    return generateProxyBeanBytecode(type, true);
                }
            });
            if (bc != null)
                pcls = GeneratedClasses.loadBCClass(bc, l);
        }
        if (pcls != null)
            proxy = (ProxyBean) instantiateProxy(pcls, findCopyConstructor(type), new Object[] { orig });
        _proxies.put(type, proxy);
    }
    return proxy;
}

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

public void removeAttribute(final String name) {

    if (name == null) {
        throw new NullPointerException(Localizer.getMessage("jsp.error.attribute.null_name"));
    }/*from  w  w w.j ava 2  s. c o m*/

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