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.coyote.http11.Http11Processor.java

/**
 * When committing the response, we have to validate the set of headers, as
 * well as setup the response filters.//from w w  w  . j  a  v  a 2 s  . com
 */
protected void prepareResponse() {

    boolean entityBody = true;
    contentDelimitation = false;

    OutputFilter[] outputFilters = outputBuffer.getFilters();

    if (http09 == true) {
        // HTTP/0.9
        outputBuffer.addActiveFilter(outputFilters[Constants.IDENTITY_FILTER]);
        return;
    }

    int statusCode = response.getStatus();
    if ((statusCode == 204) || (statusCode == 205) || (statusCode == 304)) {
        // No entity body
        outputBuffer.addActiveFilter(outputFilters[Constants.VOID_FILTER]);
        entityBody = false;
        contentDelimitation = true;
    }

    MessageBytes methodMB = request.method();
    if (methodMB.equals("HEAD")) {
        // No entity body
        outputBuffer.addActiveFilter(outputFilters[Constants.VOID_FILTER]);
        contentDelimitation = true;
    }

    // Check for compression
    boolean useCompression = false;
    if (entityBody && (compressionLevel > 0)) {
        useCompression = isCompressable();

        // Change content-length to -1 to force chunking
        if (useCompression) {
            response.setContentLength(-1);
        }
    }

    MimeHeaders headers = response.getMimeHeaders();
    if (!entityBody) {
        response.setContentLength(-1);
    } else {
        String contentType = response.getContentType();
        if (contentType != null) {
            headers.setValue("Content-Type").setString(contentType);
        }
        String contentLanguage = response.getContentLanguage();
        if (contentLanguage != null) {
            headers.setValue("Content-Language").setString(contentLanguage);
        }
    }

    int contentLength = response.getContentLength();
    if (contentLength != -1) {
        response.getMimeHeaders().setValue("Content-Length").setInt(contentLength);
        outputBuffer.addActiveFilter(outputFilters[Constants.IDENTITY_FILTER]);
        contentDelimitation = true;
    } else {
        if (entityBody && http11 && keepAlive) {
            outputBuffer.addActiveFilter(outputFilters[Constants.CHUNKED_FILTER]);
            contentDelimitation = true;
            response.addHeader("Transfer-Encoding", "chunked");
        }
    }

    if (useCompression) {
        outputBuffer.addActiveFilter(outputFilters[Constants.GZIP_FILTER]);
        // FIXME: Make content-encoding generation dynamic
        response.setHeader("Content-Encoding", "gzip");
        // Make Proxies happy via Vary (from mod_deflate)
        response.setHeader("Vary", "Accept-Encoding");
    }

    // Add date header
    if (!response.containsHeader("Date")) {

        String date = null;
        if (System.getSecurityManager() != null) {
            date = (String) AccessController.doPrivileged(new PrivilegedAction() {
                public Object run() {
                    return FastHttpDateFormat.getCurrentDate();
                }
            });
        } else {
            date = FastHttpDateFormat.getCurrentDate();
        }
        response.addHeader("Date", date);
    }

    // Add server header
    response.addHeader("Server", Constants.SERVER);

    // Add transfer encoding header
    // FIXME

    if ((entityBody) && (!contentDelimitation)) {
        // Mark as close the connection after the request, and add the 
        // connection: close header
        keepAlive = false;
    }

    // If we know that the request is bad this early, add the
    // Connection: close header.
    keepAlive = keepAlive && !statusDropsConnection(statusCode);
    if (!keepAlive) {
        response.addHeader("Connection", "close");
    } else if (!http11) {
        response.addHeader("Connection", "Keep-Alive");
    }

    // Build the response header
    outputBuffer.sendStatus();

    int size = headers.size();
    for (int i = 0; i < size; i++) {
        outputBuffer.sendHeader(headers.getName(i), headers.getValue(i));
    }
    outputBuffer.endHeaders();

}

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

@RequestMapping(value = ("/browse_catalog"), method = RequestMethod.GET)
public String anonymousCatalog(ModelMap map,
        @RequestParam(value = "serviceInstanceUUID", required = false) final String serviceInstanceUUID,
        @RequestParam(value = "currencyCode", required = false) String currencyCode,
        @RequestParam(value = "resourceType", required = false) final String resourceType,
        @RequestParam(value = "channelCode", required = false) final String channelCode,
        final HttpServletRequest request) {
    logger.debug("### anonymousCatalog method starting...(GET)");
    final String successView = "anonymous.catalog";
    if (config.getValue(Names.com_citrix_cpbm_public_catalog_display).equals("true")) {

        Channel channel = null;/* w  w w .  j  a v  a 2  s  . c o  m*/
        if (StringUtils.isNotBlank(channelCode)) {
            channel = channelService.locateByChannelCode(channelCode);
        } else {
            channel = channelService.getDefaultServiceProviderChannel();
        }

        final Catalog catalog = channel.getCatalog();
        List<CurrencyValue> currencies = catalog.getSupportedCurrencyValuesByOrder();
        map.addAttribute("channel", channel);
        map.addAttribute("currencies", currencies);
        map.addAttribute("anonymousBrowsing", true);
        CurrencyValue currency = currencies.get(0);
        if (StringUtils.isNotBlank(currencyCode)) {
            currency = currencyValueService.locateBYCurrencyCode(currencyCode);
        }
        map.addAttribute("selectedCurrency", currency);
        map.addAttribute(UserContextInterceptor.MIN_FRACTION_DIGITS,
                Currency.getInstance(currency.getCurrencyCode()).getDefaultFractionDigits());

        final Tenant tenant = tenantService.getSystemTenant();
        final Channel finalChannel = channel;
        Map<String, Object> finalMap = privilegeService
                .runAsPortal(new PrivilegedAction<Map<String, Object>>() {

                    @Override
                    public Map<String, Object> run() {
                        ModelMap modelMap = new ModelMap();
                        try {
                            getResourceComponentsAndFilterData(tenant, null, serviceInstanceUUID, null,
                                    resourceType, modelMap, request, successView, finalChannel.getName());
                        } catch (ConnectorManagementServiceException e) {
                            logger.debug("Error occured ", e);
                        }
                        return modelMap;
                    }
                });
        map.addAllAttributes(finalMap);
        map.addAttribute("supportedLocaleList", this.getLocaleDisplayName(listSupportedLocales()));
        // anonymousBrowsing and preview catalog will have default UI Because in cutom UI SSO happens which can leads to
        // security threats
        map.addAttribute("customEditorTag", null);
        map.addAttribute("customComponentSelector", null);
    } else {
        throw new NoSuchDefinitionException();
    }
    return successView;
}

From source file:Tcpbw100.java

public void privileged_run_test() {
    AccessController.doPrivileged(new PrivilegedAction<Void>() {
        public Void run() {
            runtest();/* www  . ja  va 2s .co  m*/
            return null;
        }
    });
}

From source file:net.yasion.common.core.bean.wrapper.impl.ExtendedBeanWrapperImpl.java

@SuppressWarnings("unchecked")
private void setPropertyValue(PropertyTokenHolder tokens, PropertyValue pv2) throws BeansException {
    net.yasion.common.core.bean.wrapper.PropertyValue pv = new net.yasion.common.core.bean.wrapper.PropertyValue(
            "", null);
    AfxBeanUtils.copySamePropertyValue(pv2, pv);
    String propertyName = tokens.canonicalName;
    String actualName = tokens.actualName;

    if (tokens.keys != null) {
        // Apply indexes and map keys: fetch value for all keys but the last one.
        PropertyTokenHolder getterTokens = new PropertyTokenHolder();
        getterTokens.canonicalName = tokens.canonicalName;
        getterTokens.actualName = tokens.actualName;
        getterTokens.keys = new String[tokens.keys.length - 1];
        System.arraycopy(tokens.keys, 0, getterTokens.keys, 0, tokens.keys.length - 1);
        Object propValue;//from  ww  w  .  j  a  va2  s . c om
        try {
            propValue = getPropertyValue(getterTokens);
        } catch (NotReadablePropertyException ex) {
            throw new NotWritablePropertyException(getRootClass(), this.nestedPath + propertyName,
                    "Cannot access indexed value in property referenced " + "in indexed property path '"
                            + propertyName + "'",
                    ex);
        }
        // Set value for last key.
        String key = tokens.keys[tokens.keys.length - 1];
        if (propValue == null) {
            // null map value case
            if (isAutoGrowNestedPaths()) {
                // #TO#DO#: cleanup, this is pretty hacky
                int lastKeyIndex = tokens.canonicalName.lastIndexOf('[');
                getterTokens.canonicalName = tokens.canonicalName.substring(0, lastKeyIndex);
                propValue = setDefaultValue(getterTokens);
            } else {
                throw new NullValueInNestedPathException(getRootClass(), this.nestedPath + propertyName,
                        "Cannot access indexed value in property referenced " + "in indexed property path '"
                                + propertyName + "': returned null");
            }
        }
        if (propValue.getClass().isArray()) {
            PropertyDescriptor pd = getCachedIntrospectionResults().getPropertyDescriptor(actualName);
            Class<?> requiredType = propValue.getClass().getComponentType();
            int arrayIndex = Integer.parseInt(key);
            Object oldValue = null;
            try {
                if (isExtractOldValueForEditor() && arrayIndex < Array.getLength(propValue)) {
                    oldValue = Array.get(propValue, arrayIndex);
                }
                Object convertedValue = convertIfNecessary(propertyName, oldValue, pv.getValue(), requiredType,
                        TypeDescriptor.nested(property(pd), tokens.keys.length));
                Array.set(propValue, arrayIndex, convertedValue);
            } catch (IndexOutOfBoundsException ex) {
                throw new InvalidPropertyException(getRootClass(), this.nestedPath + propertyName,
                        "Invalid array index in property path '" + propertyName + "'", ex);
            }
        } else if (propValue instanceof List) {
            PropertyDescriptor pd = getCachedIntrospectionResults().getPropertyDescriptor(actualName);
            Class<?> requiredType = GenericCollectionTypeResolver.getCollectionReturnType(pd.getReadMethod(),
                    tokens.keys.length);
            List<Object> list = (List<Object>) propValue;
            int index = Integer.parseInt(key);
            Object oldValue = null;
            if (isExtractOldValueForEditor() && index < list.size()) {
                oldValue = list.get(index);
            }
            Object convertedValue = convertIfNecessary(propertyName, oldValue, pv.getValue(), requiredType,
                    TypeDescriptor.nested(property(pd), tokens.keys.length));
            int size = list.size();
            if (index >= size && index < this.autoGrowCollectionLimit) {
                for (int i = size; i < index; i++) {
                    try {
                        list.add(null);
                    } catch (NullPointerException ex) {
                        throw new InvalidPropertyException(getRootClass(), this.nestedPath + propertyName,
                                "Cannot set element with index " + index + " in List of size " + size
                                        + ", accessed using property path '" + propertyName
                                        + "': List does not support filling up gaps with null elements");
                    }
                }
                list.add(convertedValue);
            } else {
                try {
                    list.set(index, convertedValue);
                } catch (IndexOutOfBoundsException ex) {
                    throw new InvalidPropertyException(getRootClass(), this.nestedPath + propertyName,
                            "Invalid list index in property path '" + propertyName + "'", ex);
                }
            }
        } else if (propValue instanceof Map) {
            PropertyDescriptor pd = getCachedIntrospectionResults().getPropertyDescriptor(actualName);
            Class<?> mapKeyType = GenericCollectionTypeResolver.getMapKeyReturnType(pd.getReadMethod(),
                    tokens.keys.length);
            Class<?> mapValueType = GenericCollectionTypeResolver.getMapValueReturnType(pd.getReadMethod(),
                    tokens.keys.length);
            Map<Object, Object> map = (Map<Object, Object>) propValue;
            // IMPORTANT: Do not pass full property name in here - property editors
            // must not kick in for map keys but rather only for map values.
            TypeDescriptor typeDescriptor = TypeDescriptor.valueOf(mapKeyType);
            Object convertedMapKey = convertIfNecessary(null, null, key, mapKeyType, typeDescriptor);
            Object oldValue = null;
            if (isExtractOldValueForEditor()) {
                oldValue = map.get(convertedMapKey);
            }
            // Pass full property name and old value in here, since we want full
            // conversion ability for map values.
            Object convertedMapValue = convertIfNecessary(propertyName, oldValue, pv.getValue(), mapValueType,
                    TypeDescriptor.nested(property(pd), tokens.keys.length));
            map.put(convertedMapKey, convertedMapValue);
        } else {
            throw new InvalidPropertyException(getRootClass(), this.nestedPath + propertyName,
                    "Property referenced in indexed property path '" + propertyName
                            + "' is neither an array nor a List nor a Map; returned value was [" + pv.getValue()
                            + "]");
        }
    }

    else {
        PropertyDescriptor pd = pv.getResolvedDescriptor();
        if (pd == null || !pd.getWriteMethod().getDeclaringClass().isInstance(this.object)) {
            pd = getCachedIntrospectionResults().getPropertyDescriptor(actualName);
            if (pd == null || pd.getWriteMethod() == null) {
                if (pv.isOptional()) {
                    logger.debug("Ignoring optional value for property '" + actualName
                            + "' - property not found on bean class [" + getRootClass().getName() + "]");
                    return;
                } else {
                    PropertyMatches matches = PropertyMatches.forProperty(propertyName, getRootClass());
                    throw new NotWritablePropertyException(getRootClass(), this.nestedPath + propertyName,
                            matches.buildErrorMessage(), matches.getPossibleMatches());
                }
            }
            pv.getOriginalPropertyValue().setResolvedDescriptor(pd);
        }

        Object oldValue = null;
        try {
            Object originalValue = pv.getValue();
            Object valueToApply = originalValue;
            if (!Boolean.FALSE.equals(pv.getConversionNecessary())) {
                if (pv.isConverted()) {
                    valueToApply = pv.getConvertedValue();
                } else {
                    if (isExtractOldValueForEditor() && pd.getReadMethod() != null) {
                        final Method readMethod = pd.getReadMethod();
                        if (!Modifier.isPublic(readMethod.getDeclaringClass().getModifiers())
                                && !readMethod.isAccessible()) {
                            if (System.getSecurityManager() != null) {
                                AccessController.doPrivileged(new PrivilegedAction<Object>() {
                                    @Override
                                    public Object run() {
                                        readMethod.setAccessible(true);
                                        return null;
                                    }
                                });
                            } else {
                                readMethod.setAccessible(true);
                            }
                        }
                        try {
                            if (System.getSecurityManager() != null) {
                                oldValue = AccessController
                                        .doPrivileged(new PrivilegedExceptionAction<Object>() {
                                            @Override
                                            public Object run() throws Exception {
                                                return readMethod.invoke(object);
                                            }
                                        }, acc);
                            } else {
                                oldValue = readMethod.invoke(object);
                            }
                        } catch (Exception ex) {
                            if (ex instanceof PrivilegedActionException) {
                                ex = ((PrivilegedActionException) ex).getException();
                            }
                            if (logger.isDebugEnabled()) {
                                logger.debug("Could not read previous value of property '" + this.nestedPath
                                        + propertyName + "'", ex);
                            }
                        }
                    }
                    valueToApply = convertForProperty(propertyName, oldValue, originalValue,
                            new TypeDescriptor(property(pd)));
                }
                pv.getOriginalPropertyValue().setConversionNecessary(valueToApply != originalValue);
            }
            final Method writeMethod = (pd instanceof GenericTypeAwarePropertyDescriptor
                    ? ((GenericTypeAwarePropertyDescriptor) pd).getWriteMethodForActualAccess()
                    : pd.getWriteMethod());
            if (!Modifier.isPublic(writeMethod.getDeclaringClass().getModifiers())
                    && !writeMethod.isAccessible()) {
                if (System.getSecurityManager() != null) {
                    AccessController.doPrivileged(new PrivilegedAction<Object>() {
                        @Override
                        public Object run() {
                            writeMethod.setAccessible(true);
                            return null;
                        }
                    });
                } else {
                    writeMethod.setAccessible(true);
                }
            }
            final Object value = valueToApply;
            if (System.getSecurityManager() != null) {
                try {
                    AccessController.doPrivileged(new PrivilegedExceptionAction<Object>() {
                        @Override
                        public Object run() throws Exception {
                            writeMethod.invoke(object, value);
                            return null;
                        }
                    }, acc);
                } catch (PrivilegedActionException ex) {
                    throw ex.getException();
                }
            } else {
                writeMethod.invoke(this.object, value);
            }
        } catch (TypeMismatchException ex) {
            throw ex;
        } catch (InvocationTargetException ex) {
            PropertyChangeEvent propertyChangeEvent = new PropertyChangeEvent(this.rootObject,
                    this.nestedPath + propertyName, oldValue, pv.getValue());
            if (ex.getTargetException() instanceof ClassCastException) {
                throw new TypeMismatchException(propertyChangeEvent, pd.getPropertyType(),
                        ex.getTargetException());
            } else {
                throw new MethodInvocationException(propertyChangeEvent, ex.getTargetException());
            }
        } catch (Exception ex) {
            PropertyChangeEvent pce = new PropertyChangeEvent(this.rootObject, this.nestedPath + propertyName,
                    oldValue, pv.getValue());
            throw new MethodInvocationException(pce, ex);
        }
    }
}

From source file:org.openremote.controller.service.Deployer.java

/**
 * Returns the system user login name, or an empty string if access to system user information
 * has been denied./*from w  w  w  .  j a va 2  s  .c o m*/
 *
 * @return    system user login name or empty string
 */
private String getSystemUser() {
    try {
        // ----- BEGIN PRIVILEGED CODE BLOCK ------------------------------------------------------

        return AccessController.doPrivilegedWithCombiner(new PrivilegedAction<String>() {
            @Override
            public String run() {
                return System.getProperty("user.name");
            }
        });

        // ----- END PRIVILEGED CODE BLOCK --------------------------------------------------------
    }

    catch (SecurityException e) {
        log.info("Security manager has denied access to user login name: {0}", e, e.getMessage());

        return "";
    }
}

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

/**
 * Usage: java org.apache.openjpa.util.proxy.ProxyManagerImpl [option]*
 * &lt;class name&gt;+<br />
 * Where the following options are recognized:
 * <ul> // ww  w. j  a  va  2s. com
 * <li><i>-utils/-u &lt;number&gt;</i>: Generate proxies for the standard
 * java.util collection, map, date, and calendar classes of the given Java
 * version.  Use 4 for Java 1.4, 5 for Java 5, etc.</li>
 * </ul>
 *
 * The main method generates .class files for the proxies to the classes    
 * given on the command line.  It writes the generated classes to beside the
 * ProxyManagerImpl.class file if possible; otherwise it writes to the 
 * current directory.  The proxy manager looks for these classes 
 * before generating its own proxies at runtime.
 */
public static void main(String[] args) throws ClassNotFoundException, IOException {
    File dir = Files.getClassFile(ProxyManagerImpl.class);
    dir = (dir == null) ? new File(AccessController.doPrivileged(J2DoPrivHelper.getPropertyAction("user.dir")))
            : dir.getParentFile();

    Options opts = new Options();
    args = opts.setFromCmdLine(args);

    List types = new ArrayList();
    types.addAll(Arrays.asList(args));
    int utils = opts.removeIntProperty("utils", "u", 0);
    if (utils >= 4) {
        types.addAll(Arrays.asList(new String[] { java.sql.Date.class.getName(), java.sql.Time.class.getName(),
                java.sql.Timestamp.class.getName(), java.util.ArrayList.class.getName(),
                java.util.Date.class.getName(), java.util.GregorianCalendar.class.getName(),
                java.util.HashMap.class.getName(), java.util.HashSet.class.getName(),
                java.util.Hashtable.class.getName(), java.util.LinkedList.class.getName(),
                java.util.Properties.class.getName(), java.util.TreeMap.class.getName(),
                java.util.TreeSet.class.getName(), java.util.Vector.class.getName(), }));
    }
    if (utils >= 5) {
        types.addAll(Arrays.asList(new String[] { "java.util.EnumMap", "java.util.IdentityHashMap",
                "java.util.LinkedHashMap", "java.util.LinkedHashSet", "java.util.PriorityQueue", }));
    }

    final ProxyManagerImpl mgr = new ProxyManagerImpl();
    Class cls;
    BCClass bc;
    for (int i = 0; i < types.size(); i++) {
        cls = Class.forName((String) types.get(i));
        try {
            if (Class.forName(getProxyClassName(cls, false), true,
                    GeneratedClasses.getMostDerivedLoader(cls, Proxy.class)) != null)
                continue;
        } catch (Throwable t) {
            // expected if the class hasn't been generated
        }

        if (Collection.class.isAssignableFrom(cls))
            bc = mgr.generateProxyCollectionBytecode(cls, false);
        else if (Map.class.isAssignableFrom(cls))
            bc = mgr.generateProxyMapBytecode(cls, false);
        else if (Date.class.isAssignableFrom(cls))
            bc = mgr.generateProxyDateBytecode(cls, false);
        else if (Calendar.class.isAssignableFrom(cls))
            bc = mgr.generateProxyCalendarBytecode(cls, false);
        else {
            final Class fCls = cls;
            // TODO Move this to J2DOPrivHelper
            bc = AccessController.doPrivileged(new PrivilegedAction<BCClass>() {
                public BCClass run() {
                    return mgr.generateProxyBeanBytecode(fCls, false);
                }
            });
        }

        System.out.println(bc.getName());
        AsmAdaptor.write(bc, new File(dir, bc.getClassName() + ".class"));
    }
}

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

/**
 * @author amitpals/*from   ww w  .  j a  v  a 2s . co  m*/
 * @param request
 * @param map
 * @param session
 * @return String
 */
@RequestMapping(value = "/verify_email", method = RequestMethod.GET)
public String verifyEmail(final HttpServletRequest request, ModelMap map, final HttpSession session) {
    logger.debug("###Entering in verifyEmail(Req,model,session) method @GET");
    String redirect = null;
    redirect = "/?verify";
    final String auth = (String) session.getAttribute("regAuth");
    final String userParam = (String) session.getAttribute("regParam");

    User user = privilegeService.runAsPortal(new PrivilegedAction<User>() {

        @Override
        public User run() {
            try {
                User user = userService.get(userParam);
                return user;
            } catch (NoSuchUserException e) {
                throw new UserAuthorizationInvalidException(e);

            }
        }
    });

    if (!config.getBooleanValue(Configuration.Names.com_citrix_cpbm_portal_directory_service_enabled)) {
        if (user.getPassword() == null) {
            logger.debug("AbstractRegistrationCont userpassword is null returning to register.setpassword");
            return "register.setpassword";
        }
    }
    if (user.isEmailVerified()) {
        logger.debug("verifyEmail: email already verified forwarding to Login page");
        return "redirect:" + redirect;
    }
    logger.debug("verifyEmail: email not yet verified verifying...");
    user = privilegeService.runAsPortal(new PrivilegedAction<User>() {

        @Override
        public User run() {
            User user = userService.get(userParam);
            userService.verifyAuthorization(user.getId(), auth, 0);
            logger.debug("verifyEmail: user enabled " + user.isEnabled());

            if (!user.isEnabled() && user.getTenant().getState() != State.TERMINATED) {

                logger.debug("verifyEmail: Activating user...");
                userService.activate(user);
                try {
                    String message = "email.verified";
                    String messageArguments = user.getUsername();
                    Event alert = new Event(new Date(), message, messageArguments, user, Source.PORTAL,
                            Scope.USER, Category.ACCOUNT, Severity.INFORMATION, true);
                    eventService.createEvent(alert, false);
                } catch (Exception e) {
                    logger.debug(e);
                }
            }
            return user;
        }
    });
    logger.debug("###Exiting verifyEmail(Req,model,session) method @GET  redirecting to " + redirect);
    return "redirect:" + redirect;
}

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

@Test(timeout = 30000)
public void testAllocateDoesNotBlockOnSchedulerLock() throws Exception {
    final YarnConfiguration conf = new YarnConfiguration();
    conf.setClass(YarnConfiguration.RM_SCHEDULER, CapacityScheduler.class, ResourceScheduler.class);
    MyContainerManager containerManager = new MyContainerManager();
    final MockRMWithAMS rm = new MockRMWithAMS(conf, containerManager);
    rm.start();//from w w  w  . j  a va2  s. co m

    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();
    int msecToWait = 10000;
    int msecToSleep = 100;
    while (attempt.getAppAttemptState() != RMAppAttemptState.LAUNCHED && msecToWait > 0) {
        LOG.info("Waiting for AppAttempt to reach LAUNCHED state. " + "Current state is "
                + attempt.getAppAttemptState());
        Thread.sleep(msecToSleep);
        msecToWait -= msecToSleep;
    }
    Assert.assertEquals(attempt.getAppAttemptState(), RMAppAttemptState.LAUNCHED);

    // 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 = RegisterApplicationMasterRequest.newInstance("localhost", 12345,
            "");
    client.registerApplicationMaster(request);

    // Allocate a container
    List<ResourceRequest> asks = Collections.singletonList(
            ResourceRequest.newInstance(Priority.newInstance(1), "*", Resources.createResource(2 * GB), 1));
    AllocateRequest allocateRequest = AllocateRequest.newInstance(0, 0.0f, asks, null, null);
    client.allocate(allocateRequest);

    // Make sure the container is allocated in RM
    nm1.nodeHeartbeat(true);
    ContainerId containerId2 = ContainerId.newContainerId(applicationAttemptId, 2);
    Assert.assertTrue(rm.waitForState(nm1, containerId2, RMContainerState.ALLOCATED, 10 * 1000));

    // Acquire the container
    allocateRequest = AllocateRequest.newInstance(1, 0.0f, null, null, null);
    client.allocate(allocateRequest);

    // Launch the container
    final CapacityScheduler cs = (CapacityScheduler) rm.getResourceScheduler();
    RMContainer rmContainer = cs.getRMContainer(containerId2);
    rmContainer.handle(new RMContainerEvent(containerId2, RMContainerEventType.LAUNCHED));

    // grab the scheduler lock from another thread
    // and verify an allocate call in this thread doesn't block on it
    final CyclicBarrier barrier = new CyclicBarrier(2);
    Thread otherThread = new Thread(new Runnable() {
        @Override
        public void run() {
            synchronized (cs) {
                try {
                    barrier.await();
                    barrier.await();
                } catch (InterruptedException | BrokenBarrierException e) {
                    e.printStackTrace();
                }
            }
        }
    });
    otherThread.start();
    barrier.await();
    List<ContainerId> release = Collections.singletonList(containerId2);
    allocateRequest = AllocateRequest.newInstance(2, 0.0f, null, release, null);
    client.allocate(allocateRequest);
    barrier.await();
    otherThread.join();

    rm.stop();
}

From source file:org.apache.hadoop.hdfs.TestAclsEndToEnd.java

/**
 * Perform an operation as the given user.  This method requires setting the
 * login user. This method does not restore the login user to the setting
 * from prior to the method call./*from   w  w  w .  j a  v a  2  s .  c o  m*/
 *
 * @param ugi the target user
 * @param op the operation to perform
 * @return true if the operation succeeded without throwing an exception
 */
private boolean doUserOp(UserGroupInformation ugi, final UserOp op) {
    UserGroupInformation.setLoginUser(ugi);

    // Create a test key
    return ugi.doAs(new PrivilegedAction<Boolean>() {
        @Override
        public Boolean run() {
            try {
                op.execute();

                return true;
            } catch (IOException ex) {
                LOG.error("IOException thrown during doAs() operation", ex);

                return false;
            }
        }
    });
}

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

/**
 * This method used for validation of Username
 * /*from   www  . j  a  v a 2 s . 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
    try {
        privilegeService.runAsPortal(new PrivilegedAction<Void>() {

            @Override
            public Void run() {
                userService.getUserByParam("username", username, true);
                return null;
            }
        });
    } catch (NoSuchUserException ex) {
        logger.debug(username + ": not exits in users table");
        return Boolean.TRUE.toString();
    }
    logger.debug("In validateUsername() method end");
    return Boolean.FALSE.toString();
}