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.storm.hdfs.security.AutoHDFSNimbus.java

@SuppressWarnings("unchecked")
private byte[] getHadoopCredentials(Map conf, final Configuration configuration,
        final String topologySubmitterUser) {
    try {/*  w w w  . java  2  s  .  com*/
        if (UserGroupInformation.isSecurityEnabled()) {
            login(configuration);

            final URI nameNodeURI = conf.containsKey(TOPOLOGY_HDFS_URI)
                    ? new URI(conf.get(TOPOLOGY_HDFS_URI).toString())
                    : FileSystem.getDefaultUri(configuration);

            UserGroupInformation ugi = UserGroupInformation.getCurrentUser();

            final UserGroupInformation proxyUser = UserGroupInformation.createProxyUser(topologySubmitterUser,
                    ugi);

            Credentials creds = (Credentials) proxyUser.doAs(new PrivilegedAction<Object>() {
                @Override
                public Object run() {
                    try {
                        FileSystem fileSystem = FileSystem.get(nameNodeURI, configuration);
                        Credentials credential = proxyUser.getCredentials();

                        if (configuration.get(STORM_USER_NAME_KEY) == null) {
                            configuration.set(STORM_USER_NAME_KEY, hdfsPrincipal);
                        }

                        fileSystem.addDelegationTokens(configuration.get(STORM_USER_NAME_KEY), credential);
                        LOG.info("Delegation tokens acquired for user {}", topologySubmitterUser);
                        return credential;
                    } catch (IOException e) {
                        throw new RuntimeException(e);
                    }
                }
            });

            ByteArrayOutputStream bao = new ByteArrayOutputStream();
            ObjectOutputStream out = new ObjectOutputStream(bao);

            creds.write(out);
            out.flush();
            out.close();

            return bao.toByteArray();
        } else {
            throw new RuntimeException("Security is not enabled for HDFS");
        }
    } catch (Exception ex) {
        throw new RuntimeException("Failed to get delegation tokens.", ex);
    }
}

From source file:org.mule.util.ClassUtils.java

public static Enumeration<URL> getResources(final String resourceName, final Class<?> callingClass) {
    Enumeration<URL> enumeration = AccessController.doPrivileged(new PrivilegedAction<Enumeration<URL>>() {
        public Enumeration<URL> run() {
            try {
                final ClassLoader cl = Thread.currentThread().getContextClassLoader();
                return cl != null ? cl.getResources(resourceName) : null;
            } catch (IOException e) {
                return null;
            }/*  www  .j  av a2s.com*/
        }
    });

    if (enumeration == null) {
        enumeration = AccessController.doPrivileged(new PrivilegedAction<Enumeration<URL>>() {
            public Enumeration<URL> run() {
                try {
                    return ClassUtils.class.getClassLoader().getResources(resourceName);
                } catch (IOException e) {
                    return null;
                }
            }
        });
    }

    if (enumeration == null) {
        enumeration = AccessController.doPrivileged(new PrivilegedAction<Enumeration<URL>>() {
            public Enumeration<URL> run() {
                try {
                    return callingClass.getClassLoader().getResources(resourceName);
                } catch (IOException e) {
                    return null;
                }
            }
        });
    }

    return enumeration;
}

From source file:org.apache.axis2.jaxws.description.builder.converter.JavaClassToDBCConverter.java

/**
 * The only method we will expose to users of this class. It will trigger the creation of the
 * <code>DescriptionBuilderComposite</code> based on our service class. It will also handle the
 * case of an impl class that references an SEI.
 *
 * @return - <code>DescriptionBuilderComposite</code>
 *//*from  w w w . ja  v  a 2s  . c  o m*/
public HashMap<String, DescriptionBuilderComposite> produceDBC() {
    if (log.isDebugEnabled()) {
        log.debug("Creating DescriptionBuilderComposite map from Java Class.");
    }

    HashMap<String, DescriptionBuilderComposite> dbcMap = new HashMap<String, DescriptionBuilderComposite>();
    for (int i = 0; i < classes.size(); i++) {
        buildDBC(dbcMap, classes.get(i));
        if (seiClassName != null && !seiClassName.equals("")) {
            try {
                final ClassLoader contextClassLoader = (ClassLoader) AccessController
                        .doPrivileged(new PrivilegedAction() {
                            public Object run() {
                                return Thread.currentThread().getContextClassLoader();
                            }
                        });
                Class seiClass = null;
                try {
                    seiClass = (Class) AccessController.doPrivileged(new PrivilegedExceptionAction() {
                        public Object run() throws ClassNotFoundException {
                            return contextClassLoader.loadClass(seiClassName);
                        }
                    });
                } catch (PrivilegedActionException e) {
                    throw (ClassNotFoundException) e.getException();
                }
                buildDBC(dbcMap, seiClass);

                // Also try to see if the SEI has any super interfaces  
                Class[] interfaces = seiClass.getInterfaces();
                for (int j = 0; j < interfaces.length; j++) {
                    buildDBC(dbcMap, interfaces[j]);
                }
            } catch (ClassNotFoundException e) {
                if (log.isDebugEnabled()) {
                    log.debug("Class not found exception caught for class: " + seiClassName, e);
                }
            }
        }
    }
    return dbcMap;
}

From source file:org.eclipse.gemini.blueprint.test.AbstractDependencyManagerTests.java

private String readProperty(final String name) {
    if (System.getSecurityManager() != null) {
        return (String) AccessController.doPrivileged(new PrivilegedAction() {

            public Object run() {
                return System.getProperty(name);
            }//from w  w w.ja v  a2s. com
        });
    } else
        return System.getProperty(name);
}

From source file:com.reelfx.model.ScreenRecorder.java

public void run() {
    try {/*from   w w w .  ja  v a  2 s  .c o m*/
        if (Applet.IS_MAC) {
            List<String> macArgs = new ArrayList<String>();
            macArgs.add(MAC_EXEC.getAbsolutePath());
            macArgs.add(OUTPUT_FILE.getAbsolutePath());

            ProcessBuilder pb = new ProcessBuilder(macArgs);
            recordingProcess = pb.start();
            fireProcessUpdate(RECORDING_STARTED);

            errorGobbler = new StreamGobbler(recordingProcess.getErrorStream(), false, "mac E");
            inputGobbler = new StreamGobbler(recordingProcess.getInputStream(), false, "mac O");

            logger.info("Starting listener threads...");
            errorGobbler.start();
            inputGobbler.start();

            recordingProcess.waitFor();
            fireProcessUpdate(RECORDING_COMPLETE);
        }

        else if (Applet.IS_LINUX) {
            // can have problem with file permissions when methods are invoked via Javascript even if applet is signed, 
            // thus some code needs to wrapped in a privledged block
            AccessController.doPrivileged(new PrivilegedAction<Object>() {

                @Override
                public Object run() {

                    try {
                        int width = Applet.CAPTURE_VIEWPORT.width;
                        if (width % 2 != 0)
                            width--;
                        int height = Applet.CAPTURE_VIEWPORT.height;
                        if (height % 2 != 0)
                            height--;

                        List<String> ffmpegArgs = new ArrayList<String>();
                        //ffmpegArgs.add("/usr/bin/ffmpeg");
                        ffmpegArgs.add(Applet.BIN_FOLDER.getAbsoluteFile() + File.separator + "ffmpeg");
                        // screen capture settings
                        ffmpegArgs.addAll(
                                parseParameters("-y -f x11grab -s " + width + "x" + height + " -r 20 -i :0.0+"
                                        + Applet.CAPTURE_VIEWPORT.x + "," + Applet.CAPTURE_VIEWPORT.y));
                        // microphone settings (good resource: http://www.oreilly.de/catalog/multilinux/excerpt/ch14-05.htm)
                        /* 04/29/2010 - ffmpeg gets much better framerate when not recording microphone (let Java do this)
                         * if(audioSource != null) { 
                           String driver = audioIndex > 0 ? "/dev/dsp"+audioIndex : "/dev/dsp";
                           ffmpegArgs.addAll(parseParameters("-f oss -ac 1 -ar "+AudioRecorder.FREQ+" -i "+driver));
                        }*/
                        // output file settings
                        ffmpegArgs.addAll(parseParameters("-vcodec mpeg4 -r 20 -b 5000k")); // -s "+Math.round(width*SCALE)+"x"+Math.round(height*SCALE))
                        ffmpegArgs.add(OUTPUT_FILE.getAbsolutePath());

                        logger.info("Executing this command: " + prettyCommand(ffmpegArgs));

                        ProcessBuilder pb = new ProcessBuilder(ffmpegArgs);
                        recordingProcess = pb.start();
                        // fireProcessUpdate(RECORDING_STARTED); // moved to action listener method

                        errorGobbler = new StreamGobbler(recordingProcess.getErrorStream(), false, "ffmpeg E");
                        inputGobbler = new StreamGobbler(recordingProcess.getInputStream(), false, "ffmpeg O");

                        logger.info("Starting listener threads...");
                        errorGobbler.start();
                        errorGobbler.addActionListener("Stream mapping:", self);
                        inputGobbler.start();

                        recordingProcess.waitFor();

                        fireProcessUpdate(RECORDING_COMPLETE);

                    } catch (Exception e) {
                        logger.error("Error running Linux screen recorder!", e);
                    }
                    return null;
                }
            });
        }

        else if (Applet.IS_WINDOWS) {
            // can have problem with file permissions when methods are invoked via Javascript even if applet is signed, 
            // thus some code needs to wrapped in a privileged block
            AccessController.doPrivileged(new PrivilegedAction<Object>() {

                @Override
                public Object run() {

                    try {
                        List<String> ffmpegArgs = new ArrayList<String>();
                        ffmpegArgs.add(FFMPEG_EXEC.getAbsolutePath());
                        // for full screen, use simply "cursor:desktop"
                        int width = Applet.CAPTURE_VIEWPORT.width % 2 == 0 ? Applet.CAPTURE_VIEWPORT.width
                                : Applet.CAPTURE_VIEWPORT.width - 1;
                        int height = Applet.CAPTURE_VIEWPORT.height % 2 == 0 ? Applet.CAPTURE_VIEWPORT.height
                                : Applet.CAPTURE_VIEWPORT.height - 1;
                        String viewport = ":offset=" + Applet.CAPTURE_VIEWPORT.x + ","
                                + Applet.CAPTURE_VIEWPORT.y;
                        viewport += ":size=" + width + "," + height;
                        ffmpegArgs.addAll(parseParameters("-y -f gdigrab -r 20 -i cursor:desktop" + viewport
                                + " -vcodec mpeg4 -b 5000k " + OUTPUT_FILE));

                        logger.info("Executing this command: " + prettyCommand(ffmpegArgs));
                        ProcessBuilder pb = new ProcessBuilder(ffmpegArgs);
                        recordingProcess = pb.start();
                        //fireProcessUpdate(RECORDING_STARTED); // moved to action listener method

                        // ffmpeg doesn't get the microphone on Windows, but this allows it to record a better frame rate anyway

                        errorGobbler = new StreamGobbler(recordingProcess.getErrorStream(), false, "ffmpeg E");
                        inputGobbler = new StreamGobbler(recordingProcess.getInputStream(), false, "ffmpeg O");

                        logger.info("Starting listener threads...");
                        errorGobbler.start();
                        errorGobbler.addActionListener("Stream mapping:", self);
                        inputGobbler.start();

                        recordingProcess.waitFor();

                        fireProcessUpdate(RECORDING_COMPLETE);

                    } catch (Exception e) {
                        logger.error("Error while running Windows screen recorder!", e);
                    }
                    return null;
                }
            });

        }

    } catch (Exception ie) {
        logger.error("Exception while running ScreenRecorder!", ie);
    }
}

From source file:org.apache.axis2.jaxws.client.async.CallbackFuture.java

@SuppressWarnings("unchecked")
public CallbackFuture(InvocationContext ic, AsyncHandler handler) {

    // We need to save off the classloader associated with the AsyncHandler instance
    // since we'll need to set this same classloader on the thread where
    // handleResponse() is invoked.
    // This is required so that we don't encounter ClassCastExceptions.
    final Object handlerObj = handler;
    final ClassLoader handlerCL = (ClassLoader) AccessController.doPrivileged(new PrivilegedAction() {
        public Object run() {
            return handlerObj.getClass().getClassLoader();
        }/*  w  ww. ja  v a2 s. c o m*/
    });

    // Allow the AsyncHandlerProxyFactory to create the proxy for the AsyncHandler
    // passed in (which was provided by the client on the async invocation).
    // This allows any server-specific work to be done, such as thread context management, etc.
    AsyncHandler originalHandler = handler;
    try {
        if (debug) {
            log.debug("Calling factory to create proxy for AsyncHandler instance: " + displayHandle(handler));
        }
        AsyncHandlerProxyFactory proxyFactory = (AsyncHandlerProxyFactory) FactoryRegistry
                .getFactory(AsyncHandlerProxyFactory.class);
        handler = proxyFactory.createAsyncHandlerProxy(handler);
        if (debug) {
            log.debug("Factory returned AsyncHandler proxy instance: " + displayHandle(handler));
        }
    } catch (Exception e) {
        if (debug) {
            log.debug("AsyncHandlerProxyFactory threw an exception: " + e.toString());
            e.printStackTrace();
        }

        // Just use the original handler provided by the client if we 
        // failed to create a proxy for it.
        handler = originalHandler;
    }

    cft = new CallbackFutureTask(ic.getAsyncResponseListener(), handler, handlerCL);
    task = new FutureTask(cft);
    executor = ic.getExecutor();

    /*
    * TODO review.  We need to save the invocation context so we can set it on the
    * response (or fault) context so the FutureCallback has access to the handler list.
    */
    invocationCtx = ic;
}

From source file:org.javascool.polyfilewriter.Gateway.java

/**
 * Create a new directory/*w w w. j  av a  2 s .  c  om*/
 *
 * @param location The path of new folder
 * @return true On success false If the folder already exists
 */
public boolean createDirectory(final String location) throws Exception {
    assertSafeUsage();
    try {
        return AccessController.doPrivileged(new PrivilegedAction<Boolean>() {
            public Boolean run() {
                try {
                    if (location != null) {
                        if (new File(location).exists()) {
                            throw new IllegalArgumentException("Directory " + location + " already exists");
                        }
                        new File(location).mkdirs();
                    } else {
                        throw new IllegalArgumentException("location is null");
                    }
                } catch (Exception e) {
                    return false;
                }
                return true;
            }
        });

    } catch (Exception e) {
        popException(e);
        throw e;
    }
}

From source file:org.apache.axis2.jaxws.description.builder.DescriptionBuilderComposite.java

/**
 * Get an annotation by introspecting on a class.  This is wrappered to avoid a Java2Security violation.
 * @param cls Class that contains annotation 
 * @param annotation Class of requrested Annotation
 * @return annotation or null//from   www .  j av a 2  s  .  c  o m
 */
private static Annotation getAnnotationFromClass(final Class cls, final Class annotation) {
    return (Annotation) AccessController.doPrivileged(new PrivilegedAction() {
        public Object run() {

            Annotation a = cls.getAnnotation(annotation);
            return a;
        }
    });
}

From source file:org.apache.axis2.jaxws.lifecycle.BaseLifecycleManager.java

protected Method getPostConstructMethod() {
    // REVIEW: This method should not be called in performant situations.
    // Plus the super class methods are not being considered 

    //return Method with @PostConstruct Annotation.
    if (instance != null) {
        final Class endpointClazz = instance.getClass();
        Method[] methods = (Method[]) AccessController.doPrivileged(new PrivilegedAction() {
            public Object run() {
                return endpointClazz.getMethods();
            }/*w ww  .  j av  a2s.c  o m*/
        });

        for (Method method : methods) {
            if (isPostConstruct(method)) {
                return method;
            }
        }
    }
    return null;
}

From source file:org.eclipse.gemini.blueprint.blueprint.container.support.BlueprintContainerServicePublisher.java

private void registerService(ApplicationContext applicationContext) {
    final Dictionary<String, Object> serviceProperties = new Hashtable<String, Object>();

    Bundle bundle = bundleContext.getBundle();
    String symName = bundle.getSymbolicName();
    serviceProperties.put(Constants.BUNDLE_SYMBOLICNAME, symName);
    serviceProperties.put(BLUEPRINT_SYMNAME, symName);

    Version version = OsgiBundleUtils.getBundleVersion(bundle);
    serviceProperties.put(Constants.BUNDLE_VERSION, version);
    serviceProperties.put(BLUEPRINT_VERSION, version);

    log.info("Publishing BlueprintContainer as OSGi service with properties " + serviceProperties);

    // export just the interface
    final String[] serviceNames = new String[] { BlueprintContainer.class.getName() };

    if (log.isDebugEnabled())
        log.debug("Publishing service under classes " + ObjectUtils.nullSafeToString(serviceNames));

    AccessControlContext acc = SecurityUtils.getAccFrom(applicationContext);

    // publish service
    if (System.getSecurityManager() != null) {
        registration = AccessController.doPrivileged(new PrivilegedAction<ServiceRegistration>() {
            public ServiceRegistration run() {
                return bundleContext.registerService(serviceNames, blueprintContainer, serviceProperties);
            }/*from  w  ww .j a  v a 2  s .c  om*/
        }, acc);
    } else {
        registration = bundleContext.registerService(serviceNames, blueprintContainer, serviceProperties);
    }
}