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

/**
 * When committing the response, we have to validate the set of headers, as
 * well as setup the response filters.//from  ww w . j ava2 s.  co m
 */
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:org.apache.openjpa.meta.MetaDataRepository.java

/**
 * Make some guesses about the name of a target class for an unknown application identity class.
 *//*from   ww  w  .j av a  2 s  .co  m*/
private void resolveIdentityClass(Object oid) {
    if (oid == null)
        return;

    Class<?> oidClass = oid.getClass();
    if (_log.isTraceEnabled())
        _log.trace(_loc.get("resolve-identity", oidClass));

    ClassLoader cl = AccessController.doPrivileged(J2DoPrivHelper.getClassLoaderAction(oidClass));
    String className;
    while (oidClass != null && oidClass != Object.class) {
        className = oidClass.getName();

        // we take a brute-force approach: try to load all the class'
        // substrings. this will handle the following common naming cases:
        //
        // com.company.MyClass$ID -> com.company.MyClass
        // com.company.MyClassId -> com.company.MyClass
        // com.company.MyClassOid -> com.company.MyClass
        // com.company.MyClassPK -> com.company.MyClass
        //
        // this isn't the fastest thing possible, but this method will
        // only be called once per JVM per unknown app id class
        for (int i = className.length(); i > 1; i--) {
            if (className.charAt(i - 1) == '.')
                break;

            try {
                Class.forName(className.substring(0, i), true, cl);
            } catch (Exception e) {
            } // consume all exceptions
        }

        // move up the OID hierarchy
        oidClass = oidClass.getSuperclass();
    }
}

From source file:edu.ku.brc.af.ui.forms.formatters.DataObjFieldFormatMgr.java

/**
 * Returns the instance to the singleton
 * @return  the instance to the singleton
 *///w  ww  .j  ava  2s  .  c om
public static DataObjFieldFormatMgr getInstance() {
    if (instance.get() != null) {
        return instance.get();
    }

    synchronized (instance) {
        if (StringUtils.isEmpty(factoryName)) {
            instance.set(new DataObjFieldFormatMgr());

        } else {

            // else
            String factoryNameStr = AccessController.doPrivileged(new java.security.PrivilegedAction<String>() {
                public String run() {
                    return System.getProperty(factoryName);
                }
            });

            if (StringUtils.isNotEmpty(factoryNameStr)) {
                try {
                    instance.set((DataObjFieldFormatMgr) Class.forName(factoryNameStr).newInstance());

                } catch (Exception e) {
                    edu.ku.brc.af.core.UsageTracker.incrHandledUsageCount();
                    edu.ku.brc.exceptions.ExceptionTracker.getInstance().capture(DataObjFieldFormatMgr.class,
                            e);
                    InternalError error = new InternalError(
                            "Can't instantiate DataObjFieldFormatMgr factory " + factoryNameStr);
                    error.initCause(e);
                    throw error;
                }
            }

            if (instance.get() == null) {
                instance.set(new DataObjFieldFormatMgr());
            }
        }

        // now that all formats have been loaded, set table/field/formatter
        // info\
        // must be executed after the instance is set
        for (DataObjSwitchFormatter format : instance.get().formatHash.values()) {
            format.setTableAndFieldInfo();
        }
    }
    return instance.get();
}

From source file:Tcpbw100.java

public void privileged_run_test() {
    AccessController.doPrivileged(new PrivilegedAction<Void>() {
        public Void run() {
            runtest();/*from ww w .  j  a  va  2s .c om*/
            return null;
        }
    });
}

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> /*from   ww  w. j a v  a 2s  . c  o m*/
 * <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:org.apache.openjpa.enhance.ApplicationIdTool.java

/**
 * Run the tool. Returns false if invalid options were given.
 */// w ww. ja  v  a 2 s  . c om
public static boolean run(OpenJPAConfiguration conf, String[] args, Flags flags, ClassLoader loader)
        throws IOException, ClassNotFoundException {
    MetaDataRepository repos = conf.newMetaDataRepositoryInstance();
    repos.setValidate(repos.VALIDATE_NONE, true);
    loadObjectIds(repos, flags.name == null && flags.suffix == null);

    Log log = conf.getLog(OpenJPAConfiguration.LOG_TOOL);
    Collection classes;
    if (args.length == 0) {
        log.info(_loc.get("running-all-classes"));
        classes = repos.loadPersistentTypes(true, loader);
    } else {
        ClassArgParser cap = conf.getMetaDataRepositoryInstance().getMetaDataFactory().newClassArgParser();
        cap.setClassLoader(loader);
        classes = new HashSet();
        for (int i = 0; i < args.length; i++)
            classes.addAll(Arrays.asList(cap.parseTypes(args[i])));
    }
    if (flags.name != null && classes.size() > 1)
        throw new UserException(_loc.get("name-mult-args", classes));

    ApplicationIdTool tool;
    Class cls;
    ClassMetaData meta;
    BCClassLoader bc = AccessController.doPrivileged(J2DoPrivHelper.newBCClassLoaderAction(new Project()));
    for (Iterator itr = classes.iterator(); itr.hasNext();) {
        cls = (Class) itr.next();
        log.info(_loc.get("appid-running", cls));

        meta = repos.getMetaData(cls, null, false);
        setObjectIdType(meta, flags, bc);

        tool = new ApplicationIdTool(conf, cls, meta);
        tool.setDirectory(flags.directory);
        tool.setIgnoreErrors(flags.ignoreErrors);
        tool.setToken(flags.token);
        tool.setCodeFormat(flags.format);
        if (tool.run()) {
            log.info(_loc.get("appid-output", tool.getFile()));
            tool.record();
        } else
            log.info(_loc.get("appid-norun"));
    }
    bc.getProject().clear();
    return true;
}

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 w  ww  .j a v a2 s  .  co  m*/
        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.apache.openjpa.enhance.ApplicationIdTool.java

/**
 * Load the given class name even if it does not exist.
 *///from  ww  w . j a va2 s .c o  m
private static Class loadClass(Class context, String name, BCClassLoader bc) throws ClassNotFoundException {
    if (name.indexOf('.') == -1 && context.getName().indexOf('.') != -1)
        name = Strings.getPackageName(context) + "." + name;

    // first try with regular class loader
    ClassLoader loader = AccessController.doPrivileged(J2DoPrivHelper.getClassLoaderAction(context));
    if (loader == null)
        loader = AccessController.doPrivileged(J2DoPrivHelper.getContextClassLoaderAction());
    try {
        return Class.forName(name, false, loader);
    } catch (Throwable t) {
    }

    // create class
    BCClass oid = bc.getProject().loadClass(name, null);
    oid.addDefaultConstructor();
    return Class.forName(name, false, bc);
}

From source file:org.apache.catalina.loader.WebappClassLoader.java

/**
 * Find specified resource in local repositories.
 *
 * @return the loaded resource, or null if the resource isn't found
 *///from   w w w .ja  v  a2s.  com
protected ResourceEntry findResourceInternal(String name, String path) {

    if (!started) {
        log.info(sm.getString("webappClassLoader.stopped"));
        return null;
    }

    if ((name == null) || (path == null))
        return null;

    ResourceEntry entry = (ResourceEntry) resourceEntries.get(name);
    if (entry != null)
        return entry;

    int contentLength = -1;
    InputStream binaryStream = null;

    int jarFilesLength = jarFiles.length;
    int repositoriesLength = repositories.length;

    int i;

    Resource resource = null;

    for (i = 0; (entry == null) && (i < repositoriesLength); i++) {
        try {

            String fullPath = repositories[i] + path;

            Object lookupResult = resources.lookup(fullPath);
            if (lookupResult instanceof Resource) {
                resource = (Resource) lookupResult;
            }

            // Note : Not getting an exception here means the resource was
            // found
            if (securityManager != null) {
                PrivilegedAction dp = new PrivilegedFindResource(files[i], path);
                entry = (ResourceEntry) AccessController.doPrivileged(dp);
            } else {
                entry = findResourceInternal(files[i], path);
            }

            ResourceAttributes attributes = (ResourceAttributes) resources.getAttributes(fullPath);
            contentLength = (int) attributes.getContentLength();
            entry.lastModified = attributes.getLastModified();

            if (resource != null) {

                try {
                    binaryStream = resource.streamContent();
                } catch (IOException e) {
                    return null;
                }

                // Register the full path for modification checking
                // Note: Only syncing on a 'constant' object is needed
                synchronized (allPermission) {

                    int j;

                    long[] result2 = new long[lastModifiedDates.length + 1];
                    for (j = 0; j < lastModifiedDates.length; j++) {
                        result2[j] = lastModifiedDates[j];
                    }
                    result2[lastModifiedDates.length] = entry.lastModified;
                    lastModifiedDates = result2;

                    String[] result = new String[paths.length + 1];
                    for (j = 0; j < paths.length; j++) {
                        result[j] = paths[j];
                    }
                    result[paths.length] = fullPath;
                    paths = result;

                }

            }

        } catch (NamingException e) {
        }
    }

    if ((entry == null) && (notFoundResources.containsKey(name)))
        return null;

    JarEntry jarEntry = null;

    synchronized (jarFiles) {

        openJARs();
        for (i = 0; (entry == null) && (i < jarFilesLength); i++) {

            jarEntry = jarFiles[i].getJarEntry(path);

            if (jarEntry != null) {

                entry = new ResourceEntry();
                try {
                    entry.codeBase = getURL(jarRealFiles[i]);
                    String jarFakeUrl = getURI(jarRealFiles[i]).toString();
                    jarFakeUrl = "jar:" + jarFakeUrl + "!/" + path;
                    entry.source = new URL(jarFakeUrl);
                    entry.lastModified = jarRealFiles[i].lastModified();
                } catch (MalformedURLException e) {
                    return null;
                }
                contentLength = (int) jarEntry.getSize();
                try {
                    entry.manifest = jarFiles[i].getManifest();
                    binaryStream = jarFiles[i].getInputStream(jarEntry);
                } catch (IOException e) {
                    return null;
                }

                // Extract resources contained in JAR to the workdir
                if (!(path.endsWith(".class"))) {
                    byte[] buf = new byte[1024];
                    File resourceFile = new File(loaderDir, jarEntry.getName());
                    if (!resourceFile.exists()) {
                        Enumeration entries = jarFiles[i].entries();
                        while (entries.hasMoreElements()) {
                            JarEntry jarEntry2 = (JarEntry) entries.nextElement();
                            if (!(jarEntry2.isDirectory()) && (!jarEntry2.getName().endsWith(".class"))) {
                                resourceFile = new File(loaderDir, jarEntry2.getName());
                                // No need to check mkdirs result because an
                                // IOException will occur anyway
                                resourceFile.getParentFile().mkdirs();
                                FileOutputStream os = null;
                                InputStream is = null;
                                try {
                                    is = jarFiles[i].getInputStream(jarEntry2);
                                    os = new FileOutputStream(resourceFile);
                                    while (true) {
                                        int n = is.read(buf);
                                        if (n <= 0) {
                                            break;
                                        }
                                        os.write(buf, 0, n);
                                    }
                                } catch (IOException e) {
                                    // Ignore
                                } finally {
                                    try {
                                        if (is != null) {
                                            is.close();
                                        }
                                    } catch (IOException e) {
                                    }
                                    try {
                                        if (os != null) {
                                            os.close();
                                        }
                                    } catch (IOException e) {
                                    }
                                }
                            }
                        }
                    }
                }

            }

        }

        if (entry == null) {
            synchronized (notFoundResources) {
                notFoundResources.put(name, name);
            }
            return null;
        }

        if (binaryStream != null) {

            byte[] binaryContent = new byte[contentLength];

            try {
                int pos = 0;

                while (true) {
                    int n = binaryStream.read(binaryContent, pos, binaryContent.length - pos);
                    if (n <= 0)
                        break;
                    pos += n;
                }
                binaryStream.close();
            } catch (IOException e) {
                e.printStackTrace();
                return null;
            } catch (Exception e) {
                e.printStackTrace();
                return null;
            }

            entry.binaryContent = binaryContent;

            // The certificates are only available after the JarEntry 
            // associated input stream has been fully read
            if (jarEntry != null) {
                entry.certificates = jarEntry.getCertificates();
            }

        }

    }

    // Add the entry in the local resource repository
    synchronized (resourceEntries) {
        // Ensures that all the threads which may be in a race to load
        // a particular class all end up with the same ResourceEntry
        // instance
        ResourceEntry entry2 = (ResourceEntry) resourceEntries.get(name);
        if (entry2 == null) {
            resourceEntries.put(name, entry);
        } else {
            entry = entry2;
        }
    }

    return entry;

}

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

public Class classForName(String name, String[] imports) {
    // full class name or primitive type?
    Class type = toClass(name);/*w ww.j a  va  2s  .com*/
    if (type != null)
        return type;

    // first check the aliases map in the MetaDataRepository
    ClassLoader loader = (_class == null) ? _loader
            : AccessController.doPrivileged(J2DoPrivHelper.getClassLoaderAction(_class));
    ClassMetaData meta = _broker.getConfiguration().getMetaDataRepositoryInstance().getMetaData(name, loader,
            false);
    if (meta != null)
        return meta.getDescribedType();

    // try the name in the package of the candidate class
    if (_class != null) {
        String fullName = _class.getName().substring(0, _class.getName().lastIndexOf('.') + 1) + name;
        type = toClass(fullName);
        if (type != null)
            return type;
    }

    // try java.lang
    type = toClass("java.lang." + name);
    if (type != null)
        return type;

    // try each import
    if (imports != null && imports.length > 0) {
        String dotName = "." + name;
        String importName;
        for (int i = 0; i < imports.length; i++) {
            importName = imports[i];

            // full class name import
            if (importName.endsWith(dotName))
                type = toClass(importName);
            // wildcard; strip to package
            else if (importName.endsWith(".*")) {
                importName = importName.substring(0, importName.length() - 1);
                type = toClass(importName + name);
            }
            if (type != null)
                return type;
        }
    }
    return null;
}