Example usage for java.security AccessController doPrivileged

List of usage examples for java.security AccessController doPrivileged

Introduction

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

Prototype

@CallerSensitive
public static <T> T doPrivileged(PrivilegedExceptionAction<T> action) throws PrivilegedActionException 

Source Link

Document

Performs the specified PrivilegedExceptionAction with privileges enabled.

Usage

From source file:org.beangle.model.persist.hibernate.internal.ChainedClassLoader.java

public URL getResource(final String name) {
    if (System.getSecurityManager() != null) {
        return AccessController.doPrivileged(new PrivilegedAction<URL>() {

            public URL run() {
                return doGetResource(name);
            }/*from   ww  w .j a  v a2  s  .co m*/
        });
    } else {
        return doGetResource(name);
    }
}

From source file:com.fitbur.jestify.junit.spring.IntegrationTestReifier.java

@Override
public Object reifyField(FieldDescriptor fieldDescriptor, ParameterDescriptor parameterDescriptor) {
    return AccessController.doPrivileged((PrivilegedAction<Object>) () -> {
        try {/*from w  ww .  ja v a2 s .c o  m*/
            Object instance;
            Field field = fieldDescriptor.getField();
            Type fieldType = field.getGenericType();
            field.setAccessible(true);

            Optional<Mock> optMock = fieldDescriptor.getMock();
            if (optMock.isPresent()) {
                Mock mock = optMock.get();
                Object value = field.get(testInstance);
                //if the field value is set then create a mock otherwise create a mock
                //that delegates to the value
                if (value == null) {
                    MockSettings settings = withSettings().defaultAnswer(mock.answer());

                    if (mock.extraInterfaces().length > 0) {
                        settings.extraInterfaces(mock.extraInterfaces());

                    }

                    instance = mock(field.getType(), settings);
                } else {
                    instance = mock(field.getType(), delegatesTo(value));
                }

            } else {
                ResolvableType resolver = ResolvableType.forType(fieldType);

                Class rawType;

                if (resolver.hasGenerics()) {
                    if (resolver.isAssignableFrom(Provider.class)
                            || resolver.isAssignableFrom(Optional.class)) {
                        rawType = resolver.getRawClass();
                    } else {
                        rawType = resolver.resolve();
                    }
                } else {
                    rawType = (Class) fieldType;
                }

                instance = appContext.getBean(rawType);
            }

            field.set(testInstance, instance);
            fieldDescriptor.setInstance(instance);
            parameterDescriptor.setInstance(instance);

            return instance;
        } catch (IllegalAccessException | IllegalArgumentException e) {
            throw new RuntimeException(e);
        }
    });

}

From source file:com.scoredev.scores.HighScore.java

public void setHighScore(final int score) throws IOException {
    //check permission first
    SecurityManager sm = System.getSecurityManager();
    if (sm != null) {
        sm.checkPermission(new HighScorePermission(gameName));
    }/*from   w  ww  . j  a v  a 2s  .  c o  m*/

    // need a doPrivileged block to manipulate the file
    try {
        AccessController.doPrivileged(new PrivilegedExceptionAction() {
            public Object run() throws IOException {
                Hashtable scores = null;
                // try to open the existing file. Should have a locking
                // protocol (could use File.createNewFile).
                try {
                    FileInputStream fis = new FileInputStream(highScoreFile);
                    ObjectInputStream ois = new ObjectInputStream(fis);
                    scores = (Hashtable) ois.readObject();
                } catch (Exception e) {
                    // ignore, try and create new file
                }

                // if scores is null, create a new hashtable
                if (scores == null)
                    scores = new Hashtable(13);

                // update the score and save out the new high score
                scores.put(gameName, new Integer(score));
                FileOutputStream fos = new FileOutputStream(highScoreFile);
                ObjectOutputStream oos = new ObjectOutputStream(fos);
                oos.writeObject(scores);
                oos.close();
                return null;
            }
        });
    } catch (PrivilegedActionException pae) {
        throw (IOException) pae.getException();
    }
}

From source file:org.apache.clerezza.platform.dashboard.UserLoginNode.java

@Override
public GraphNode addUserContext(GraphNode node) {

    final AccessControlContext context = AccessController.getContext();
    GraphNode agent = AccessController.doPrivileged(new PrivilegedAction<GraphNode>() {
        @Override/*from w ww .j  a  v a  2  s .c o  m*/
        public GraphNode run() {
            final String userName = UserUtil.getUserName(context);
            if (userName == null) {
                return null;
            }
            return userManager.getUserGraphNode(userName);
        }
    });
    if (agent != null) {
        if (agent.getNode() instanceof UriRef) {
            WebIdInfo webIdInfo = webIdGraphsService.getWebIdInfo((UriRef) agent.getNode());
            MGraph userGraph = webIdInfo.localPublicUserData();
            agent = new GraphNode(agent.getNode(), new UnionMGraph(agent.getGraph(), userGraph));
        }
        node.addProperty(PLATFORM.user, agent.getNode());
        MGraph userContext = new SimpleMGraph(agent.getNodeContext());
        removeTripleWithProperty(userContext, PERMISSION.password);
        removeTripleWithProperty(userContext, PERMISSION.passwordSha1);
        node.getGraph().addAll(userContext);
    }
    return node;
}

From source file:org.eclipse.wb.internal.xwt.parser.XwtEditorContext.java

@Override
protected void addParentClassLoaders(final CompositeClassLoader parentClassLoader) throws Exception {
    super.addParentClassLoaders(parentClassLoader);
    AccessController.doPrivileged(new PrivilegedExceptionAction<Object>() {
        public Object run() throws Exception {
            addParentClassLoaders_impl(parentClassLoader);
            return null;
        }/*w  w w  .j a va2s.  c  o m*/
    });
}

From source file:freemarker.ext.jsp._FreeMarkerPageContext21.java

/**
 * Attempts to locate and manufacture an expression evaulator instance. For this
 * to work you <b>must</b> have the Apache Commons-EL package in the classpath. If
 * Commons-EL is not available, this method will throw an UnsupportedOperationException. 
 *//* w ww.j  ava2s. c  o  m*/
@Override
public ExpressionEvaluator getExpressionEvaluator() {
    try {
        Class type = ((ClassLoader) AccessController.doPrivileged(new PrivilegedAction() {
            public Object run() {
                return Thread.currentThread().getContextClassLoader();
            }
        })).loadClass("org.apache.commons.el.ExpressionEvaluatorImpl");
        return (ExpressionEvaluator) type.newInstance();
    } catch (Exception e) {
        throw new UnsupportedOperationException("In order for the getExpressionEvaluator() "
                + "method to work, you must have downloaded the apache commons-el jar and "
                + "made it available in the classpath.");
    }
}

From source file:ch.algotrader.util.FieldUtil.java

private static void setAccessible(final AccessibleObject object) {

    if (object.isAccessible())
        return;/*from ww w  .  j  a  v  a  2s .c o m*/

    AccessController.doPrivileged((PrivilegedAction<Object>) () -> {
        object.setAccessible(true);
        return null;
    });
}

From source file:org.broadleafcommerce.common.extensibility.InstrumentationRuntimeFactory.java

/**
 * This method returns the Instrumentation object provided by the JVM. If the Instrumentation object is null,
 * it does its best to add an instrumentation agent to the JVM and then the instrumentation object.
 * @return Instrumentation//w  w w.j a va 2  s .c  o  m
 */
public static synchronized Instrumentation getInstrumentation() {
    if (inst != null) {
        return inst;
    }

    if (System.getProperty("java.vendor").toUpperCase().contains("IBM")) {
        isIBM = true;
    }

    AccessController.doPrivileged(new PrivilegedAction<Object>() {
        public Object run() {
            try {
                if (!InstrumentationRuntimeFactory.class.getClassLoader()
                        .equals(ClassLoader.getSystemClassLoader())) {
                    return null;
                }
            } catch (Throwable t) {
                return null;
            }
            File toolsJar = null;
            // When running on IBM, the attach api classes are packaged in vm.jar which is a part
            // of the default vm classpath.
            if (!isIBM) {
                // If we can't find the tools.jar and we're not on IBM we can't load the agent.
                toolsJar = findToolsJar();
                if (toolsJar == null) {
                    return null;
                }
            }

            Class<?> vmClass = loadVMClass(toolsJar);
            if (vmClass == null) {
                return null;
            }
            String agentPath = getAgentJar();
            if (agentPath == null) {
                return null;
            }
            loadAgent(agentPath, vmClass);
            return null;
        }
    });

    return inst;
}

From source file:com.marmalade.studio.android.gcm.s3eGCMClientBroadcastReceiver.java

@SuppressWarnings({ "unchecked", "rawtypes" })
private void doNotificationCallback() {

    try {/*  ww w  .ja  v  a2s  .c o m*/

        // Get extension class
        final Class extension_class = Class.forName("s3eGCMClient");

        // Get notification method
        final Method notification_method = extension_class.getMethod("s3eGCMClientNotificationReceived",
                new Class[] {});

        // Access method
        AccessController.doPrivileged(new PrivilegedExceptionAction() {
            public Object run() throws Exception {

                // Set accessible
                if (!notification_method.isAccessible()) {
                    notification_method.setAccessible(true);
                }

                // Invoke
                notification_method.invoke(extension_class.newInstance());

                return null;
            }
        });

    } catch (Exception e) {

        // Do nothing
        // e.printStackTrace();
    }
}

From source file:com.datos.vfs.impl.PrivilegedFileReplicator.java

/**
 * Initializes the component.//from   ww w  .  j  a  va 2 s.com
 *
 * @throws FileSystemException if an error occurs.
 */
@Override
public void init() throws FileSystemException {
    if (replicatorComponent != null) {
        try {
            AccessController.doPrivileged(new InitAction());
        } catch (final PrivilegedActionException e) {
            throw new FileSystemException("vfs.impl/init-replicator.error", e);
        }
    }
}