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.apache.openjpa.enhance.PCEnhancer.java

/**
 * Return the field assigned in the given method, or null if none.
 * Package-protected and static for testing.
 *///from w w w.jav a 2s .c  o  m
static BCField getAssignedField(BCMethod meth) {
    return findField(meth, (AccessController.doPrivileged(J2DoPrivHelper.newCodeAction())).putfield(), true);
}

From source file:org.apache.openjpa.kernel.AbstractBrokerFactory.java

/**
 * This method is invoked AFTER a BrokerFactory has been instantiated. 
 *//*from  www . ja  v  a 2s  .co m*/
public void postCreationCallback() {
    Auditor auditor = _conf.getAuditorInstance();
    if (auditor != null) {
        addTransactionListener(new AuditManager(auditor));
    }
    if (_conf.isInitializeEagerly()) {
        newBroker(_conf.getConnectionUserName(), _conf.getConnectionPassword(),
                _conf.isConnectionFactoryModeManaged(), _conf.getConnectionRetainModeConstant(), false).close();
    }

    // Don't get a MetaDataRepository yet if not preloading because it is possible that someone has extended the MDR
    // and the extension hasn't been plugged in yet.
    if (MetaDataRepository.needsPreload(_conf) == true) {
        // Don't catch any exceptions here because we want to fail-fast if something bad happens when we're
        // preloading.
        MetaDataRepository mdr = _conf.getMetaDataRepositoryInstance();
        mdr.setValidate(MetaDataRepository.VALIDATE_RUNTIME, true);
        mdr.setResolve(MetaDataRepository.MODE_MAPPING_INIT, true);

        // Load persistent classes and hook in subclasser
        loadPersistentTypes(
                (ClassLoader) AccessController.doPrivileged(J2DoPrivHelper.getContextClassLoaderAction()));
        mdr.preload();
    }

    // Get a DataCacheManager instance up front to avoid threading concerns on first call.
    // _conf.getDataCacheManagerInstance();

    InstrumentationManager imgr = _conf.getInstrumentationManagerInstance();
    if (imgr != null) {
        // Start all factory level instrumentation
        imgr.start(InstrumentationLevel.FACTORY, this);
    }
}

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

/**
 * Retuns a method matching the name which takes the given parameters
 * /*from   w  w w . ja  v  a 2s . c o m*/
 * @param cls The class to search
 * @param name The name of the method
 * @param params The parameter types
 * @param mustExist Whether the method should throw an exception if no matching method has been found
 * @exception RuntimeException Thrown if mustExist == true and no matching method was found
 * @return The method or null in case none was found and mustExist == false
 */
public static Method findMethod(Class cls, String name, Class[] params, boolean mustExist) {
    Method m;
    for (Class c = cls; c != null && c != Object.class; c = c.getSuperclass()) {
        Method[] methods = (Method[]) AccessController.doPrivileged(getDeclaredMethodsAction(cls));
        Method candidate = null;
        for (int i = 0; i < methods.length; i++) {
            if (name.equals(methods[i].getName())) {
                Class[] methodParams = methods[i].getParameterTypes();
                if (methodParams.length != params.length) {
                    continue;
                }
                boolean paramsMatch = true;
                int paramIndex = 0;
                for (Class methodParam : methodParams) {
                    if (methodParam != params[paramIndex]) {
                        paramsMatch = false;
                        break;
                    }
                    paramIndex++;
                }
                if (paramsMatch) {
                    candidate = mostDerived(methods[i], candidate);
                }
            }
        }
        if (candidate != null)
            return candidate;
    }
    if (mustExist)
        throw new RuntimeException("Could not find method " + name + " in class " + cls.getCanonicalName());
    return null;
}

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

@SuppressWarnings("unchecked")
private Object getPropertyValue(PropertyTokenHolder tokens) throws BeansException {
    String propertyName = tokens.canonicalName;
    String actualName = tokens.actualName;
    PropertyDescriptor pd = getCachedIntrospectionResults().getPropertyDescriptor(actualName);
    if (pd == null || pd.getReadMethod() == null) {
        throw new NotReadablePropertyException(getRootClass(), this.nestedPath + propertyName);
    }/* w w w.j  ava 2s. c  o m*/
    final Method readMethod = pd.getReadMethod();
    try {
        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);
            }
        }

        Object value;
        if (System.getSecurityManager() != null) {
            try {
                value = AccessController.doPrivileged(new PrivilegedExceptionAction<Object>() {
                    @Override
                    public Object run() throws Exception {
                        return readMethod.invoke(object, (Object[]) null);
                    }
                }, acc);
            } catch (PrivilegedActionException pae) {
                throw pae.getException();
            }
        } else {
            value = readMethod.invoke(object, (Object[]) null);
        }

        if (tokens.keys != null) {
            if (value == null) {
                if (isAutoGrowNestedPaths()) {
                    value = setDefaultValue(tokens.actualName);
                } else {
                    throw new NullValueInNestedPathException(getRootClass(), this.nestedPath + propertyName,
                            "Cannot access indexed value of property referenced in indexed " + "property path '"
                                    + propertyName + "': returned null");
                }
            }
            String indexedPropertyName = tokens.actualName;
            // apply indexes and map keys
            for (int i = 0; i < tokens.keys.length; i++) {
                String key = tokens.keys[i];
                if (value == null) {
                    throw new NullValueInNestedPathException(getRootClass(), this.nestedPath + propertyName,
                            "Cannot access indexed value of property referenced in indexed " + "property path '"
                                    + propertyName + "': returned null");
                } else if (value.getClass().isArray()) {
                    int index = Integer.parseInt(key);
                    value = growArrayIfNecessary(value, index, indexedPropertyName);
                    value = Array.get(value, index);
                } else if (value instanceof List) {
                    int index = Integer.parseInt(key);
                    List<Object> list = (List<Object>) value;
                    growCollectionIfNecessary(list, index, indexedPropertyName, pd, i + 1);
                    value = list.get(index);
                } else if (value instanceof Set) {
                    // Apply index to Iterator in case of a Set.
                    Set<Object> set = (Set<Object>) value;
                    int index = Integer.parseInt(key);
                    if (index < 0 || index >= set.size()) {
                        throw new InvalidPropertyException(getRootClass(), this.nestedPath + propertyName,
                                "Cannot get element with index " + index + " from Set of size " + set.size()
                                        + ", accessed using property path '" + propertyName + "'");
                    }
                    Iterator<Object> it = set.iterator();
                    for (int j = 0; it.hasNext(); j++) {
                        Object elem = it.next();
                        if (j == index) {
                            value = elem;
                            break;
                        }
                    }
                } else if (value instanceof Map) {
                    Map<Object, Object> map = (Map<Object, Object>) value;
                    Class<?> mapKeyType = GenericCollectionTypeResolver.getMapKeyReturnType(pd.getReadMethod(),
                            i + 1);
                    // 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);
                    value = map.get(convertedMapKey);
                } else {
                    throw new InvalidPropertyException(getRootClass(), this.nestedPath + propertyName,
                            "Property referenced in indexed property path '" + propertyName
                                    + "' is neither an array nor a List nor a Set nor a Map; returned value was ["
                                    + value + "]");
                }
                indexedPropertyName += PROPERTY_KEY_PREFIX + key + PROPERTY_KEY_SUFFIX;
            }
        }
        return value;
    } catch (IndexOutOfBoundsException ex) {
        throw new InvalidPropertyException(getRootClass(), this.nestedPath + propertyName,
                "Index of out of bounds in property path '" + propertyName + "'", ex);
    } catch (NumberFormatException ex) {
        throw new InvalidPropertyException(getRootClass(), this.nestedPath + propertyName,
                "Invalid index in property path '" + propertyName + "'", ex);
    } catch (TypeMismatchException ex) {
        throw new InvalidPropertyException(getRootClass(), this.nestedPath + propertyName,
                "Invalid index in property path '" + propertyName + "'", ex);
    } catch (InvocationTargetException ex) {
        throw new InvalidPropertyException(getRootClass(), this.nestedPath + propertyName,
                "Getter for property '" + actualName + "' threw exception", ex);
    } catch (Exception ex) {
        throw new InvalidPropertyException(getRootClass(), this.nestedPath + propertyName,
                "Illegal attempt to get property '" + actualName + "' threw exception", ex);
    }
}

From source file:ddf.catalog.source.solr.SolrMetacardClientImpl.java

private static String accessProperty(String key, String defaultValue) {
    String value = AccessController
            .doPrivileged((PrivilegedAction<String>) () -> System.getProperty(key, defaultValue));
    LOGGER.debug("Read system property [{}] with value [{}]", key, value);
    return value;
}

From source file:org.apache.openjpa.enhance.PCEnhancer.java

/**
 * Return the field returned / assigned by <code>meth</code>. Returns
 * null if non-fields (methods, literals, parameters, variables) are
 * returned, or if non-parameters are assigned to fields.
 *//*  ww w  . j  a  va 2 s. c om*/
private static BCField findField(BCMethod meth, Instruction template, boolean findAccessed) {
    // ignore any static methods. OpenJPA only currently supports
    // non-static setters and getters
    if (meth.isStatic())
        return null;

    Code code = meth.getCode(false);
    if (code == null)
        return null;
    code.beforeFirst();

    BCField field = null, cur;
    Instruction templateIns, prevIns, earlierIns;
    while (code.searchForward(template)) {
        int backupCount = 3;
        templateIns = code.previous();
        if (!code.hasPrevious())
            return null;
        prevIns = code.previous();

        if (prevIns instanceof ClassInstruction && code.hasPrevious()) {
            prevIns = code.previous();
            backupCount++;
        }

        if (!code.hasPrevious())
            return null;
        earlierIns = code.previous();

        // if the opcode two before the template was an aload_0, check
        // against the middle instruction based on what type of find
        // we're doing
        if (!(earlierIns instanceof LoadInstruction) || !((LoadInstruction) earlierIns).isThis())
            return null;

        // if the middle instruction was a getfield, then it's the
        // field that's being accessed
        if (!findAccessed && prevIns instanceof GetFieldInstruction) {
            final FieldInstruction fPrevIns = (FieldInstruction) prevIns;
            cur = AccessController.doPrivileged(J2DoPrivHelper.getFieldInstructionFieldAction(fPrevIns));
            // if the middle instruction was an xload_1, then the
            // matched instruction is the field that's being set.
        } else if (findAccessed && prevIns instanceof LoadInstruction
                && ((LoadInstruction) prevIns).getParam() == 0) {
            final FieldInstruction fTemplateIns = (FieldInstruction) templateIns;
            cur = AccessController.doPrivileged(J2DoPrivHelper.getFieldInstructionFieldAction(fTemplateIns));
        } else
            return null;

        if (field != null && cur != field)
            return null;
        field = cur;

        // ready for next search iteration
        while (backupCount > 0) {
            code.next();
            backupCount--;
        }
    }
    return field;
}

From source file:org.apache.openjpa.meta.ClassMetaData.java

/**
 * Return whether the given name represents a managed or static field of
 * this class, including superclass fields.
 *//*  w  w  w .  j  a v a2  s .  com*/
public boolean isAccessibleField(String field) {
    if (getDeclaredField(field) != null)
        return true;
    if (_staticFields == null) {
        Field[] fields = (Field[]) AccessController.doPrivileged(J2DoPrivHelper.getDeclaredFieldsAction(_type));
        Set<String> names = new HashSet<String>();
        for (int i = 0; i < fields.length; i++)
            if (Modifier.isStatic(fields[i].getModifiers()))
                names.add(fields[i].getName());
        _staticFields = names;
    }
    if (_staticFields.contains(field))
        return true;
    if (_super != null)
        return getPCSuperclassMetaData().isAccessibleField(field);
    return false;
}

From source file:org.apache.openjpa.persistence.AnnotationPersistenceMetaDataParser.java

/**
 * Parse @DetachedState. The annotation may be null.
 *//*from ww  w.  j av  a  2  s.co m*/
private void parseDetachedState(ClassMetaData meta, DetachedState detached) {
    if (detached != null) {
        if (!detached.enabled())
            meta.setDetachedState(null);
        else if (StringUtils.isEmpty(detached.fieldName()))
            meta.setDetachedState(ClassMetaData.SYNTHETIC);
        else
            meta.setDetachedState(detached.fieldName());
    } else {
        Field[] fields = (Field[]) AccessController
                .doPrivileged(J2DoPrivHelper.getDeclaredFieldsAction(meta.getDescribedType()));
        for (int i = 0; i < fields.length; i++)
            if ((AccessController
                    .doPrivileged(J2DoPrivHelper.isAnnotationPresentAction(fields[i], DetachedState.class)))
                            .booleanValue())
                meta.setDetachedState(fields[i].getName());
    }
}

From source file:org.elasticsearch.xpack.core.ssl.SSLServiceTests.java

private CloseableHttpAsyncClient getAsyncHttpClient(SSLIOSessionStrategy sslStrategy) throws Exception {
    try {/*from   w w w. j  a v a2 s. c o  m*/
        return AccessController
                .doPrivileged((PrivilegedExceptionAction<CloseableHttpAsyncClient>) () -> HttpAsyncClientBuilder
                        .create().setSSLStrategy(sslStrategy).build());
    } catch (PrivilegedActionException e) {
        throw (Exception) e.getCause();
    }
}

From source file:org.apache.myfaces.ov2021.application.jsp.JspStateManagerImpl.java

protected Object deserializeView(Object state) {
    if (log.isLoggable(Level.FINEST))
        log.finest("Entering deserializeView");

    if (state instanceof byte[]) {
        if (log.isLoggable(Level.FINEST))
            log.finest("Processing deserializeView - deserializing serialized state. Bytes : "
                    + ((byte[]) state).length);

        try {/*from w  w  w  . jav a 2 s .c o  m*/
            ByteArrayInputStream bais = new ByteArrayInputStream((byte[]) state);
            InputStream is = bais;
            if (is.read() == COMPRESSED_FLAG) {
                is = new GZIPInputStream(is);
            }
            ObjectInputStream ois = null;
            try {
                final ObjectInputStream in = new MyFacesObjectInputStream(is);
                ois = in;
                Object object = null;
                if (System.getSecurityManager() != null) {
                    object = AccessController.doPrivileged(new PrivilegedExceptionAction<Object[]>() {
                        public Object[] run()
                                throws PrivilegedActionException, IOException, ClassNotFoundException {
                            return new Object[] { in.readObject(), in.readObject() };
                        }
                    });
                } else {
                    object = new Object[] { in.readObject(), in.readObject() };
                }
                return object;
            } finally {
                if (ois != null) {
                    ois.close();
                    ois = null;
                }
            }
        } catch (PrivilegedActionException e) {
            log.log(Level.SEVERE, "Exiting deserializeView - Could not deserialize state: " + e.getMessage(),
                    e);
            return null;
        } catch (IOException e) {
            log.log(Level.SEVERE, "Exiting deserializeView - Could not deserialize state: " + e.getMessage(),
                    e);
            return null;
        } catch (ClassNotFoundException e) {
            log.log(Level.SEVERE, "Exiting deserializeView - Could not deserialize state: " + e.getMessage(),
                    e);
            return null;
        }
    } else if (state instanceof Object[]) {
        if (log.isLoggable(Level.FINEST))
            log.finest("Exiting deserializeView - state not serialized.");

        return state;
    } else if (state == null) {
        log.severe("Exiting deserializeView - this method should not be called with a null-state.");
        return null;
    } else {
        log.severe("Exiting deserializeView - this method should not be called with a state of type : "
                + state.getClass());
        return null;
    }
}