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.acoveo.tools.Reflection.java

/**
 * Return a PrivilegeAction object for clazz.getDeclaredMethods().
 * // ww w  . j ava2 s. co m
 * This method is from:
 * https://svn.apache.org/repos/asf/openjpa/trunk/openjpa-lib/src/main/java/org/apache/openjpa/lib/util/J2DoPrivHelper.java
 * 
 * Requires security policy:
 *   'permission java.lang.RuntimePermission "accessDeclaredMembers";'
 *   
 * @return Method[]
 */
public static final PrivilegedAction<Method[]> getDeclaredMethodsAction(final Class<?> clazz) {
    return new PrivilegedAction<Method[]>() {
        public Method[] run() {
            return clazz.getDeclaredMethods();
        }
    };
}

From source file:org.acoveo.tools.Reflection.java

/**
 * Return a PrivilegeAction object for class.getDeclaredFields().
 * /*from w  w  w  .ja  va 2s .c  o  m*/
 * This method is from:
 * https://svn.apache.org/repos/asf/openjpa/trunk/openjpa-lib/src/main/java/org/apache/openjpa/lib/util/J2DoPrivHelper.java
 * 
 * Requires security policy:
 *   'permission java.lang.RuntimePermission "accessDeclaredMembers";'
 *   
 * @return Field[]
 */
public static final PrivilegedAction<Field[]> getDeclaredFieldsAction(final Class<?> clazz) {
    return new PrivilegedAction<Field[]>() {
        public Field[] run() {
            return clazz.getDeclaredFields();
        }
    };
}

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

private static Object unmarshalArray(final XMLStreamReader reader, final Unmarshaller u, Class type)
        throws Exception {
    try {/*w w w  .j ava2  s.  c o  m*/
        if (DEBUG_ENABLED) {
            log.debug("Invoking unmarshalArray");
        }
        Object jaxb = AccessController.doPrivileged(new PrivilegedAction() {
            public Object run() {
                try {
                    return u.unmarshal(reader, String[].class);
                } catch (OMException e) {
                    throw e;
                } catch (Throwable t) {
                    throw new OMException(t);
                }
            }
        });

        Object typeObj = getTypeEnabledObject(jaxb);

        // Now convert String Array in to the required Type Array.
        if (typeObj instanceof String[]) {
            String[] strArray = (String[]) typeObj;
            Object obj = XSDListUtils.fromStringArray(strArray, type);
            QName qName = XMLRootElementUtil.getXmlRootElementQNameFromObject(jaxb);
            jaxb = new JAXBElement(qName, type, obj);
        }

        return jaxb;
    } catch (OMException e) {
        throw e;
    } catch (Throwable t) {
        throw new OMException(t);
    }
}

From source file:org.apache.axis2.context.ConfigurationContext.java

/**
 * This include all the major changes we have done from 1.2
 * release to 1.3 release. This will include API changes , class
 * deprecating etc etc.//  w  w w. j a v a 2  s  .  c om
 */
private void cleanupTemp() {
    File tempFile = (File) axisConfiguration.getParameterValue(Constants.Configuration.ARTIFACTS_TEMP_DIR);
    if (tempFile == null) {
        String property = (String) AccessController.doPrivileged(new PrivilegedAction() {
            public Object run() {
                return System.getProperty("java.io.tmpdir");
            }
        });
        tempFile = new File(property, "_axis2");
    }
    deleteTempFiles(tempFile);
}

From source file:org.apache.axis2.context.ConfigurationContext.java

private void deleteTempFiles(final File dir) {
    Boolean isDir = (Boolean) AccessController.doPrivileged(new PrivilegedAction() {
        public Object run() {
            return new Boolean(dir.isDirectory());
        }/*  www  .j av a2  s  .c  o m*/
    });
    if (isDir.booleanValue()) {
        String[] children = (String[]) AccessController.doPrivileged(new PrivilegedAction() {
            public Object run() {
                return dir.list();
            }
        });
        for (int i = 0; children != null && i < children.length; i++) {
            deleteTempFiles(new File(dir, children[i]));
        }
    }
    AccessController.doPrivileged(new PrivilegedAction() {
        public Object run() {
            dir.delete();
            return null;
        }
    });
}

From source file:org.acoveo.tools.Reflection.java

/**
 * Return a PrivilegeAction object for aObj.setAccessible().
 * //from ww  w . j  av  a  2s.  c  o m
 * This method is from:
 * https://svn.apache.org/repos/asf/openjpa/trunk/openjpa-lib/src/main/java/org/apache/openjpa/lib/util/J2DoPrivHelper.java
 * 
 * Requires security policy: 'permission java.lang.reflect.ReflectPermission
 * "suppressAccessChecks";'
 */
public static final PrivilegedAction<Object> setAccessibleAction(final AccessibleObject aObj,
        final boolean flag) {
    return new PrivilegedAction<Object>() {
        public Object run() {
            aObj.setAccessible(flag);
            return (Object) null;
        }
    };
}

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

@RequestMapping(value = "/verify_additional_email", method = RequestMethod.GET)
public String verifyAdditionalEmail(@RequestParam(value = "a", required = true) final String auth,
        @RequestParam(value = "i", required = true) final String userParam,
        @RequestParam(value = "pi", required = true) final String cryptedEmail,
        final HttpServletRequest request, ModelMap map, HttpSession session) {
    logger.debug("###Entering in verifyAlertEmail(map) method @GET");
    privilegeService.runAsPortal(new PrivilegedAction<User>() {

        @Override//from ww w. j  a v  a  2s.  co m
        public User run() {
            User user = userService.get(userParam);
            userService.verifyAuthorization(user, auth, 0);
            String emailAdd = CryptoUtils.decrypt(cryptedEmail, CryptoUtils.keyGenerationSeed);
            UserAlertPreferences userAlertPreferences = userAlertPreferencesService
                    .locateUserAlertPreference(user, emailAdd);

            if (userAlertPreferences.getAlertType() == AlertType.USER_EMAIL) {
                user.setEmail(userAlertPreferences.getEmailAddress());
                userService.save(user);
            } else {
                userAlertPreferences.setEmailVerified(true);
                userAlertPreferencesService.save(userAlertPreferences);
            }
            return user;
        }
    });

    map.clear(); // No need for map to propagate
    session.setAttribute("email_verified", "Y");
    logger.debug("##Exiting verifyAlertEmail(map) method @GET");
    return "redirect:/portal/home";
}

From source file:org.openconcerto.sql.model.SQLBase.java

boolean save(final String schemaName) {
    final DBItemFileCache schemaFileCache = this.getSchemaFileCache(schemaName);
    if (schemaFileCache == null) {
        return false;
    } else {/*from w  ww .j  av  a 2 s . co m*/
        final File schemaFile = schemaFileCache.getFile(FILENAME);
        return AccessController.doPrivileged(new PrivilegedAction<Boolean>() {
            @Override
            public Boolean run() {
                Writer pWriter = null;
                try {
                    final String schema = getSchema(schemaName).toXML();
                    if (schema == null)
                        return false;
                    FileUtils.mkdir_p(schemaFile.getParentFile());
                    // Might save garbage if two threads open the same file
                    synchronized (this) {
                        pWriter = FileUtils.createXMLWriter(schemaFile);
                        pWriter.write("<root codecVersion=\"" + XMLStructureSource.version + "\" >\n" + schema
                                + "\n</root>\n");
                    }

                    return true;
                } catch (Exception e) {
                    Log.get().log(Level.WARNING, "unable to save files in " + schemaFile, e);
                    return false;
                } finally {
                    if (pWriter != null) {
                        try {
                            pWriter.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
        });
    }
}

From source file:org.apache.hadoop.yarn.server.resourcemanager.scheduler.TestSchedulerUtils.java

@Test
public void testValidateResourceBlacklistRequest() throws Exception {

    final Configuration conf = new YarnConfiguration();
    RMStorageFactory.setConfiguration(conf);
    YarnAPIStorageFactory.setConfiguration(conf);
    DBUtility.InitializeDB();//  w  w  w. ja v a2  s  .  c  o  m

    MyContainerManager containerManager = new MyContainerManager();
    final MockRMWithAMS rm = new MockRMWithAMS(conf, containerManager);
    rm.start();

    MockNM nm1 = rm.registerNode("localhost:1234", 5120);

    Map<ApplicationAccessType, String> acls = new HashMap<ApplicationAccessType, String>(2);
    acls.put(ApplicationAccessType.VIEW_APP, "*");
    RMApp app = rm.submitApp(1024, "appname", "appuser", acls);

    nm1.nodeHeartbeat(true);

    RMAppAttempt attempt = app.getCurrentAppAttempt();
    ApplicationAttemptId applicationAttemptId = attempt.getAppAttemptId();
    waitForLaunchedState(attempt);

    // Create a client to the RM.
    final YarnRPC rpc = YarnRPC.create(conf);

    UserGroupInformation currentUser = UserGroupInformation.createRemoteUser(applicationAttemptId.toString());
    Credentials credentials = containerManager.getContainerCredentials();
    final InetSocketAddress rmBindAddress = rm.getApplicationMasterService().getBindAddress();
    Token<? extends TokenIdentifier> amRMToken = MockRMWithAMS.setupAndReturnAMRMToken(rmBindAddress,
            credentials.getAllTokens());
    currentUser.addToken(amRMToken);
    ApplicationMasterProtocol client = currentUser.doAs(new PrivilegedAction<ApplicationMasterProtocol>() {
        @Override
        public ApplicationMasterProtocol run() {
            return (ApplicationMasterProtocol) rpc.getProxy(ApplicationMasterProtocol.class, rmBindAddress,
                    conf);
        }
    });

    RegisterApplicationMasterRequest request = Records.newRecord(RegisterApplicationMasterRequest.class);
    client.registerApplicationMaster(request);

    ResourceBlacklistRequest blacklistRequest = ResourceBlacklistRequest
            .newInstance(Collections.singletonList(ResourceRequest.ANY), null);

    AllocateRequest allocateRequest = AllocateRequest.newInstance(0, 0.0f, null, null, blacklistRequest);
    boolean error = false;
    try {
        client.allocate(allocateRequest);
    } catch (InvalidResourceBlacklistRequestException e) {
        error = true;
    }

    rm.stop();

    Assert.assertTrue("Didn't not catch InvalidResourceBlacklistRequestException", error);
}

From source file:com.ecyrd.jspwiki.auth.SecurityVerifier.java

/**
 * Verifies that a particular Principal possesses a Permission, as defined
 * in the security policy file./*from w  w  w. j  a  v  a2  s .com*/
 * @param principal the principal
 * @param permission the permission
 * @return the result, based on consultation with the active Java security
 *         policy
 */
protected final boolean verifyStaticPermission(Principal principal, final Permission permission) {
    Subject subject = new Subject();
    subject.getPrincipals().add(principal);
    boolean allowedByGlobalPolicy = ((Boolean) Subject.doAsPrivileged(subject, new PrivilegedAction<Object>() {
        public Object run() {
            try {
                AccessController.checkPermission(permission);
                return Boolean.TRUE;
            } catch (AccessControlException e) {
                return Boolean.FALSE;
            }
        }
    }, null)).booleanValue();

    if (allowedByGlobalPolicy) {
        return true;
    }

    // Check local policy
    Principal[] principals = new Principal[] { principal };
    return m_engine.getAuthorizationManager().allowedByLocalPolicy(principals, permission);
}