Creates the temporary resource

@param context
the context
@param cacheMode
the cache mode
@param rd
the reader of the compiled resource
@return the reader
349494
protected Reader createTempResource(GeneratorContext context, CacheMode cacheMode, Reader rd) {
		String filePath = getTempFilePath(context, cacheMode);
		Writer wr = null;
		FileOutputStream fos = null;
		try {
			File f = new File(filePath);
			if (!f.getParentFile().exists()) {
				f.getParentFile().mkdirs();
			}
			String content = IOUtils.toString(rd);
			fos = new FileOutputStream(f);
			FileChannel channel = fos.getChannel();
			wr = Channels.newWriter(channel, config.getResourceCharset().newEncoder(), -1);
			wr.write(content);

			rd = new StringReader(content);
		} catch (IOException e) {
			throw new BundlingProcessException("Unable to create temporary resource for '" + context.getPath() + "'",
					e);
		} finally {
			IOUtils.close(wr);
			IOUtils.close(fos);
		}

		return rd;
	}
717881
public Reader createResource(GeneratorContext context) {
		String data = null;
		try {
			if (dwrLibraries.containsKey(context.getPath())) {
				// Static script
				data = getStaticScript(dwrLibraries.get(context.getPath()),
						context);
			} else if (ALL_INTERFACES_KEY.equals(context.getPath())) {
				// All interfaces
				data = getAllPublishedInterfaces(context);
			} else {
				// This must be a specific interface ...
				StringBuilder sb = new StringBuilder();
				StringTokenizer tk = new StringTokenizer(context.getPath(), "|");
				while (tk.hasMoreTokens()) {
					sb.append(getInterfaceScript(tk.nextToken(), context));
				}
				data = sb.toString();
			}

		} catch (IOException e) {
			throw new RuntimeException(
					"An IO error occured while getting content from DWR", e);
		}
		return new StringReader(data);
	}
19855
public static DeserializerStringCache from(DeserializationContext context) {
        return withCache(context, cache -> {
            if (cache == null) {
                cache = new DeserializerStringCache(new HashMap<CharBuffer, String>(),
                        new HashMap<CharBuffer, String>());
            }
            return cache;
        });
    }
243138
protected RefMetadata createRef(ParserContext context, String id) {
        MutableRefMetadata idref = context.createMetadata(MutableRefMetadata.class);
        idref.setComponentId(id);
        return idref;
    }
990577
@Override
    @SuppressWarnings("unchecked")
    public <T> T get(Contextual<T> contextual, CreationalContext<T> creationalContext) {
        Bean bean = (Bean) contextual;
        // you can store the bean somewhere
        if (somewhere.containsKey(bean.getName())) {
            return (T) somewhere.get(bean.getName());
        } else {
            T t = (T) bean.create(creationalContext);
            somewhere.put(bean.getName(), t);
            return t;
        }
    }
461153
private CacheLoader<Object, Optional<Map<String, Object>>> createCacheLoader(
      final Repository<Entity> repository) {
    return new CacheLoader<Object, Optional<Map<String, Object>>>() {
      /**
       * Loads a single entity from the repository.
       *
       * @param id ID value of the entity to retrieve
       * @return dehydrated entity or empty if the entity was not present in the repository
       */
      @Override
      public Optional<Map<String, Object>> load(@Nonnull Object id) {
        return Optional.ofNullable(repository.findOneById(id)).map(entityHydration::dehydrate);
      }

      /**
       * Loads multiple entities from the repository.
       *
       * @param ids Iterable of String representations of the ID values
       * @return Map mapping id to loaded entity, or to empty optional if the entity was not present
       *     in the repository
       */
      @Override
      public Map<Object, Optional<Map<String, Object>>> loadAll(Iterable<?> ids) {
        Stream<Object> typedIds = stream(ids).map(id -> id);
        Map<Object, Optional<Map<String, Object>>> result =
            repository.findAll(typedIds).collect(toMap(Entity::getIdValue, this::dehydrateEntity));
        for (Object key : ids) {
          // cache the absence of these entities in the backend as empty values
          result.putIfAbsent(key, empty());
        }
        return result;
      }

      private Optional<Map<String, Object>> dehydrateEntity(Entity entity) {
        return Optional.of(entityHydration.dehydrate(entity));
      }
    };
  }
933629
public static RecurrenceIterator createRecurrenceIterator(
            String rdata, DateValue dtStart, TimeZone tzid)
            throws ParseException {
        return createRecurrenceIterator(rdata, dtStart, tzid, true);
    }
597879
public Cache createRAMCache(Struct arguments) throws IOException {
	RamCache rc = new RamCache();
	if (arguments == null) arguments = new StructImpl();
	rc.init(this, "" + CreateUniqueId.invoke(), arguments);
	return rc;
    }
876702
@Override
    public Object createResource(final ResourceInfo resInfo) throws Exception {
        final boolean trace = TraceComponent.isAnyTracingEnabled();
        if (trace && tc.isEntryEnabled())
            Tr.entry(this, tc, "createResource", resInfo);

        Object connectionFactory;

        lock.readLock().lock();
        try {
            if (!isInitialized.get()) {
                // Switch to write lock for lazy initialization
                lock.readLock().unlock();
                lock.writeLock().lock();
                try {
                    if (!isInitialized.get())
                        initPrivileged();
                } finally {
                    // Downgrade to read lock for rest of method
                    lock.readLock().lock();
                    lock.writeLock().unlock();
                }
            }
            checkAccess();
            ConnectionManager conMgr = AccessController.doPrivileged(new PrivilegedExceptionAction<ConnectionManager>() {
                @Override
                public ConnectionManager run() throws Exception {
                    return conMgrSvc.getConnectionManager(resInfo, AbstractConnectionFactoryService.this);
                }
            });
            connectionFactory = getManagedConnectionFactory(null).createConnectionFactory(conMgr);
        } catch (Exception x) {
            if (trace && tc.isEntryEnabled())
                Tr.exit(this, tc, "createResource", x);
            throw x;
        } catch (Error x) {
            if (trace && tc.isEntryEnabled())
                Tr.exit(this, tc, "createResource", x);
            throw x;
        } finally {
            lock.readLock().unlock();
        }

        // Only connection factories defined in the server configuration are tracked for the app recycle coordinator.
        if (isServerDefined) {
            ComponentMetaData cData = ComponentMetaDataAccessorImpl.getComponentMetaDataAccessor().getComponentMetaData();
            if (cData != null)
                appsToRecycle.add(cData.getJ2EEName().getApplication());
        }

        if (trace && tc.isEntryEnabled())
            Tr.exit(this, tc, "createResource", connectionFactory);
        return connectionFactory;
    }
605308
protected FaceletFactory createFaceletFactory(FacesContext context, Compiler compiler)
    {
        ExternalContext eContext = context.getExternalContext();

        // refresh period
        long refreshPeriod;
        if (context.isProjectStage(ProjectStage.Production))
        {
            refreshPeriod = WebConfigParamUtils.getLongInitParameter(eContext, PARAMS_REFRESH_PERIOD,
                    DEFAULT_REFRESH_PERIOD_PRODUCTION);
        }
        else
        {
            refreshPeriod = WebConfigParamUtils.getLongInitParameter(eContext, PARAMS_REFRESH_PERIOD,
                    DEFAULT_REFRESH_PERIOD);
        }

        // resource resolver
        ResourceResolver resolver = new DefaultResourceResolver();
        ArrayList<String> classNames = new ArrayList<String>();
        String faceletsResourceResolverClassName = WebConfigParamUtils.getStringInitParameter(eContext,
                PARAMS_RESOURCE_RESOLVER, null);
        List<String> resourceResolversFromAnnotations = RuntimeConfig.getCurrentInstance(
            context.getExternalContext()).getResourceResolvers();
        if (faceletsResourceResolverClassName != null)
        {
            classNames.add(faceletsResourceResolverClassName);
        }
        if (!resourceResolversFromAnnotations.isEmpty())
        {
            classNames.addAll(resourceResolversFromAnnotations);
        }
        if (!classNames.isEmpty())
        {
            resolver = ClassUtils.buildApplicationObject(ResourceResolver.class, classNames, resolver);
        }

        _resourceResolver = resolver;

        return new DefaultFaceletFactory(compiler, resolver, refreshPeriod);
    }
1094125
@WorkerThread
  public static LottieResult<LottieComposition> fromRawResSync(Context context, @RawRes int rawRes) {
    try {
      return fromJsonInputStreamSync(context.getResources().openRawResource(rawRes), rawResCacheKey(rawRes));
    } catch (Resources.NotFoundException e) {
      return new LottieResult<>(e);
    }
  }
729069
@Override
    @SuppressFBWarnings(value = "UL_UNRELEASED_LOCK", justification = "False positive from FindBugs")
    public <T> T get(Contextual<T> contextual, CreationalContext<T> creationalContext) {
        if (!isActive()) {
            throw new ContextNotActiveException();
        }
        checkContextInitialized();
        final BeanStore beanStore = getBeanStore();
        if (beanStore == null) {
            return null;
        }
        if (contextual == null) {
            throw ContextLogger.LOG.contextualIsNull();
        }
        BeanIdentifier id = getId(contextual);
        ContextualInstance<T> beanInstance = beanStore.get(id);
        if (beanInstance != null) {
            return beanInstance.getInstance();
        } else if (creationalContext != null) {
            LockedBean lock = null;
            try {
                if (multithreaded) {
                    lock = beanStore.lock(id);
                    beanInstance = beanStore.get(id);
                    if (beanInstance != null) {
                        return beanInstance.getInstance();
                    }
                }
                T instance = contextual.create(creationalContext);
                if (instance != null) {
                    beanInstance = new SerializableContextualInstanceImpl<Contextual<T>, T>(contextual, instance, creationalContext, serviceRegistry.get(ContextualStore.class));
                    beanStore.put(id, beanInstance);
                }
                return instance;
            } finally {
                if (lock != null) {
                    lock.unlock();
                }
            }
        } else {
            return null;
        }
    }
425576
public Reader createReader(byte[] cachedBytes) throws IOException {
	if (cachedBytes != null) {
	    return new InputStreamReader(new ByteArrayInputStream(cachedBytes));
	}
        if (inputStream != null) {
            return new InputStreamReader(inputStream, charset);
        }
        if (reader != null) {
            return reader;
        }
        return new InputStreamReader(new FileInputStream(file), charset);
    }
1143687
public V getCachedObject(TaskRequest req, TaskResponse res, K key, Factory<K, V> factory) {
        final CacheMode cacheMode = CacheMode.valueOf((String) this.cacheModelPhrase.evaluate(req, res));
        
        if (this.logger.isDebugEnabled()) {
            this.logger.debug("Getting cached object for '" + key + "' using cache mode " + cacheMode + " and factory " + factory);
        }
        
        //Load the cache only if cache-all is enabled
        final ConcurrentMap<Tuple<Serializable, K>, Object> cache;
        final Tuple<Serializable, K> compoundCacheKey;
        switch (cacheMode) {
            case NONE: {
                return factory.createObject(key);
            }
            
            default:
            case ONE: {
                cache = null;
                compoundCacheKey = null;
            }
            break;
            
            case ALL: {
                cache = (ConcurrentMap<Tuple<Serializable, K>, Object>) this.cachePhrase.evaluate(req, res);
                final Serializable cacheNamespace = factory.getCacheNamespace(key);
                compoundCacheKey = new Tuple<Serializable, K>(cacheNamespace, key);
            }
            break;
        }
        
        //Determine the object to synchronize around
        final Object syncTarget = factory.getMutex(key);

        //get or create & cache the target object
        V instance = null;
        synchronized (syncTarget) {
            //Get the object from the local variables if no cache is available
            if (cache == null) {
                //Try for a thread-local instance first
                if (this.compareKeys(key, this.threadKeyHolder.get())) {
                    instance = this.threadInstanceHolder.get();
                }
                //Next try for a singleton instance
                else if (this.compareKeys(key, this.key)) {
                    instance = this.instance;
                } 
            }
            //Look in the passed cache for the instance
            else {
                final Object object = cache.get(compoundCacheKey);
                
                //If the cached object is a ThreadLocal use it for the instance
                if (object instanceof ThreadLocal<?>) {
                    instance = ((ThreadLocal<V>) object).get();
                }
                //If not assume it is the instance 
                else {
                    instance = (V) object;
                }
            }
            
            //If no instance was found create and cache one
            if (instance == null) {
                instance = factory.createObject(key);
                final boolean threadSafe = factory.isThreadSafe(key, instance);
                
                if (this.logger.isDebugEnabled()) {
                    this.logger.debug("Cache miss for '" + key + "' created '" + instance + "' threadSafe=" + threadSafe);
                }
                
                //If no cache is available store the instance in the local variables
                if (cache == null) {
                    if (threadSafe) {
                        this.instance = instance;
                        this.key = key;
                    }
                    else {
                        this.threadInstanceHolder.set(instance);
                        this.threadKeyHolder.set(key);
                    }
                }
                //Cache available store there
                else {
                    if (threadSafe) {
                        cache.put(compoundCacheKey, instance);
                    }
                    else {
                        ThreadLocal<V> threadInstanceHolder = (ThreadLocal<V>)cache.get(compoundCacheKey);
                        if (threadInstanceHolder == null) {
                            threadInstanceHolder = new ThreadLocal<V>();
                            
                            while (true) {
                                Object existing = cache.putIfAbsent(compoundCacheKey, threadInstanceHolder);
                                if (existing == null) {
                                    //nothing existed for that key, put was successful
                                    break;
                                }
                                
                                if (existing instanceof ThreadLocal) {
                                    //Existing ThreadLocal, just use it
                                    threadInstanceHolder = (ThreadLocal)existing;
                                    break;
                                }
                                
                                //something other than a ThreadLocal already exists, try replacing with the ThreadLocal
                                final boolean replaced = cache.replace(compoundCacheKey, threadInstanceHolder, existing);
                                if (replaced) {
                                    //Replace worked!
                                    break;
                                }
                                
                                //Replace didn't work, try the whole process again, yay non-blocking!
                            }
                            
                            if (cache instanceof EvictionAwareCache) {
                                ((EvictionAwareCache) cache).registerCacheEvictionListener(ThreadLocalCacheEvictionListener.INSTANCE);
                            }
                        }

                        threadInstanceHolder.set(instance);
                    }
                }
            }
            else if (this.logger.isDebugEnabled()) {
                this.logger.debug("Cache hit for '" + key + "' using '" + instance + "'");
            }
        }
        
        return instance;
    }
753761
public static MemoryCache createMemoryCache(Context context, int memoryCacheSize) {
		if (memoryCacheSize == 0) {
			ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
			int memoryClass = am.getMemoryClass();
			if (hasHoneycomb() && isLargeHeap(context)) {
				memoryClass = getLargeMemoryClass(am);
			}
			memoryCacheSize = 1024 * 1024 * memoryClass / 8;
		}
		return new LruMemoryCache(memoryCacheSize);
	}
1046568
@Override
    public <T> T readInstance(DatastoreType datastoreType) {
        return getInstance(datastoreType, TransactionalCache.Mode.READ);
    }
877457
@Override
	public void addResourceReader(ResourceReader rd) {

		if (rd instanceof TextResourceReader) {
			resourceReaders.add((TextResourceReader) rd);
			Collections.sort(resourceReaders, new ResourceReaderComparator(config));
		}

		if (rd instanceof StreamResourceReader) {
			streamResourceReaders.add((StreamResourceReader) rd);
			Collections.sort(streamResourceReaders, new ResourceReaderComparator(config));
		}

		initReader(rd);
	}