/*
(non-Javadoc)

@see net.jawr.web.resource.bundle.generator.StreamResourceGenerator#
createResourceAsStream
(net.jawr.web.resource.bundle.generator.GeneratorContext)
174131
@Override
	public InputStream createResourceAsStream(GeneratorContext context) {

		String path = context.getPath();
		InputStream is = null;
		if (FileNameUtils.hasImageExtension(path)) {
			try {
				is = context.getResourceReaderHandler().getResourceAsStream(path, false);
			} catch (ResourceNotFoundException e) {
				// Nothing to do
			}
		}

		return is;
	}
284990
public ResponseBuilder createResource() {
        final String baseUrl = getBaseUrl();
        final String identifier = baseUrl + req.getPartition() + req.getPath() + id;
        final String contentType = req.getContentType();
        final Session session = ofNullable(req.getSession()).orElseGet(HttpSession::new);

        LOGGER.info("Creating resource as {}", identifier);

        final Optional<RDFSyntax> rdfSyntax = ofNullable(contentType).flatMap(RDFSyntax::byMediaType)
            .filter(SUPPORTED_RDF_TYPES::contains);

        final IRI defaultType = nonNull(contentType) && !rdfSyntax.isPresent() ? LDP.NonRDFSource : LDP.RDFSource;
        final IRI internalId = rdf.createIRI(TRELLIS_PREFIX + req.getPartition() + req.getPath() + id);

        // Add LDP type (ldp:Resource results in the defaultType)
        final IRI ldpType = ofNullable(req.getLink())
            .filter(l -> "type".equals(l.getRel())).map(Link::getUri).map(URI::toString)
            .filter(l -> l.startsWith(LDP.URI)).map(rdf::createIRI)
            .filter(l -> !LDP.Resource.equals(l)).orElse(defaultType);

        if (ldpType.equals(LDP.NonRDFSource) && rdfSyntax.isPresent()) {
            return status(BAD_REQUEST).type(TEXT_PLAIN).entity("Cannot save a NonRDFSource with RDF syntax");
        }

        try (final TrellisDataset dataset = TrellisDataset.createDataset()) {

            // Add Audit quads
            audit.ifPresent(svc ->
                    svc.creation(internalId, session).stream().map(skolemizeQuads(resourceService, baseUrl))
                .forEachOrdered(dataset::add));

            dataset.add(rdf.createQuad(PreferServerManaged, internalId, RDF.type, ldpType));

            // Add user-supplied data
            if (ldpType.equals(LDP.NonRDFSource)) {
                // Check the expected digest value
                final Digest digest = req.getDigest();
                if (nonNull(digest) && !getDigestForEntity(digest).equals(digest.getDigest())) {
                    return status(BAD_REQUEST);
                }

                final Map<String, String> metadata = singletonMap(CONTENT_TYPE, ofNullable(contentType)
                        .orElse(APPLICATION_OCTET_STREAM));
                final IRI binaryLocation = rdf.createIRI(binaryService.getIdentifierSupplier(req.getPartition())
                        .get());
                dataset.add(rdf.createQuad(PreferServerManaged, internalId, DC.hasPart, binaryLocation));
                dataset.add(rdf.createQuad(PreferServerManaged, binaryLocation, DC.modified,
                            rdf.createLiteral(now().toString(), XSD.dateTime)));
                dataset.add(rdf.createQuad(PreferServerManaged, binaryLocation, DC.format,
                            rdf.createLiteral(ofNullable(contentType).orElse(APPLICATION_OCTET_STREAM))));
                dataset.add(rdf.createQuad(PreferServerManaged, binaryLocation, DC.extent,
                            rdf.createLiteral(Long.toString(entity.length()), XSD.long_)));

                // Persist the content
                persistContent(binaryLocation, metadata);
            } else {
                readEntityIntoDataset(identifier, baseUrl, PreferUserManaged, rdfSyntax.orElse(TURTLE), dataset);

                // Check for any constraints
                checkConstraint(dataset, PreferUserManaged, ldpType, TRELLIS_PREFIX + req.getPartition(),
                        rdfSyntax.orElse(TURTLE));
            }

            if (resourceService.put(internalId, dataset.asDataset())) {
                final ResponseBuilder builder = status(CREATED).location(create(identifier));

                // Add LDP types
                ldpResourceTypes(ldpType).map(IRI::getIRIString).forEach(type -> builder.link(type, "type"));

                return builder;
            }
        }

        LOGGER.error("Unable to persist data to location at {}", internalId.getIRIString());
        return serverError().type(TEXT_PLAIN)
            .entity("Unable to persist data. Please consult the logs for more information");
    }
472331
public InputStream getResourceAsStream(final String name) {
        for ( final ClassLoader classLoader : this.classLoaders ) {
            InputStream stream = classLoader.getResourceAsStream( name );
            if ( stream != null ) {
                return stream;
            }
        }

        return null;
    }
924804
@Nullable
  public InputStream getResourceAsStream (final String name)
  {
    InputStream ret = null;
    if (m_aBestCandidate != null)
    {
      ret = m_aBestCandidate.getResourceAsStream (name);
      if (ret != null)
        return ret;
      m_aBestCandidate = null;
    }

    IClassLoadHelper aLoadHelper = null;
    final Iterator <IClassLoadHelper> iter = m_aLoadHelpers.iterator ();
    while (iter.hasNext ())
    {
      aLoadHelper = iter.next ();
      ret = aLoadHelper.getResourceAsStream (name);
      if (ret != null)
        break;
    }

    m_aBestCandidate = aLoadHelper;
    return ret;
  }
493644
private StreamSource getSource(String pURI)
            throws IOException, MalformedURLException {
        if (pURI != null && pURI.indexOf("://") < 0) {
            // If local, get as stream
            return new StreamSource(getResourceAsStream(pURI));
        }

        // ...else, create from URI string
        return new StreamSource(pURI);
    }
1144331
public static InputStream getResourceAsStream(UimaContext context, String name)
      throws ResourceInitializationException {

    InputStream inResource = getOptionalResourceAsStream(context, name);

    if (inResource == null) {
      throw new ResourceInitializationException(
          ExceptionMessages.MESSAGE_CATALOG,
          ExceptionMessages.IO_ERROR_MODEL_READING, new Object[] { name
              + " could not be found!" });
    }

    return inResource;
  }
1204411
@Override
    public InputStream getResourceAsStream(String name) {
        byte[] b = null;
        try {
            Asset resource = AssetCache.getAsset(mdwPackage.getName() + "/" + name);
            if (resource != null)
                b = resource.getRawContent();
            if (b == null)
                b = findInJarAssets(name);
            if (b == null)
                b = findInFileSystem(name);
        }
        catch (Exception ex) {
            logger.severeException(ex.getMessage(),  ex);
        }

        if (b == null)
            return super.getResourceAsStream(name);
        else
            return new ByteArrayInputStream(b);
    }
858984
@Override
	public OutputStream getResourceAsOutputStream(String resourceName) throws IOException {

		// Create directories if needed
		String generatedFilePath = resourceName.substring(workingDir.length());
		if (!FileNameUtils.isExtension(generatedFilePath, JawrConstant.CSS_TYPE)
				&& binaryGeneratorRegistry.isGeneratedBinaryResource(generatedFilePath)) {
			// for generated image put it in the generated Image directory
			generatedFilePath = workingDir + JawrConstant.SPRITE_GENERATED_IMG_DIR
					+ generatedFilePath.replace(':', '/');
		} else if (cssGeneratorRegistry.isPathGenerated(generatedFilePath)) { // Rename
																				// resource
																				// for
																				// For
																				// generated
																				// CSS
			generatedFilePath = workingDir + JawrConstant.SPRITE_GENERATED_CSS_DIR
					+ generatedFilePath.replace(':', '/');
		} else {
			generatedFilePath = resourceName;
		}

		final File parentFile = new File(generatedFilePath).getParentFile();
		if (!parentFile.exists()) {
			if (!parentFile.mkdirs()) {
				throw new IOException("Unable to create the directory : " + parentFile.getPath());
			}
		}

		File file = new File(generatedFilePath);
		try {
			file = file.getCanonicalFile();
		} catch (final IOException e) {
			file = file.getAbsoluteFile();
		}

		return new FileOutputStream(file);
	}
57882
private static URL getUrlForResourceAsStream(final ExternalContext externalContext, String path)
            throws MalformedURLException
    {
        URLStreamHandler handler = new URLStreamHandler()
        {
            protected URLConnection openConnection(URL u) throws IOException
            {
                final String file = u.getFile();
                return new URLConnection(u)
                {
                    public void connect() throws IOException
                    {
                    }

                    public InputStream getInputStream() throws IOException
                    {
                        if (log.isLoggable(Level.FINE))
                        {
                            log.fine("Opening internal url to " + file);
                        }
                        Object ctx = externalContext.getContext();
                        // Or maybe fetch the external context afresh ?
                        // Object ctx =
                        // FacesContext.getCurrentInstance().getExternalContext().getContext();

                        if (ctx instanceof ServletContext)
                        {
                            ServletContext servletContext = (ServletContext) ctx;
                            InputStream stream = servletContext.getResourceAsStream(file);
                            if (stream == null)
                            {
                                throw new FileNotFoundException("Cannot open resource " + file);
                            }
                            return stream;
                        }
                        else
                        {
                            throw new IOException("Cannot open resource for an context of "
                                    + (ctx != null ? ctx.getClass() : null));
                        }
                    }
                };
            }
        };
        return new URL("internal", null, 0, path, handler);
    }
140081
@Override
	public InputStream getResourceAsStream(String resourceName, boolean processingBundle) {

		GeneratorContext context = new GeneratorContext(null, config,
				generator.getResolver().getResourcePath(resourceName));
		context.setResourceReaderHandler(rsHandler);
		context.setProcessingBundle(processingBundle);

		return generator.createResourceAsStream(context);
	}
81751
public Reader createResource(GeneratorContext context) {
		ServletContext servletContext = context.getServletContext();
		StringBuffer data = null;
		String path = context.getPath();
		if(ENGINE_KEY.equals(path)) {
			data = buildEngineScript(readDWRScript(ENGINE_PATH),servletContext);
		}
		else if(DWR_LIBRARIES.containsKey(path)){
			data = readDWRScript((String)DWR_LIBRARIES.get(path));
		}
		else if(ALL_INTERFACES_KEY.equals(path)) {
			data = new StringBuffer(ENGINE_INIT);
			data.append(getAllPublishedInterfaces(servletContext));
		}
		else {
			data = new StringBuffer(ENGINE_INIT);
			StringTokenizer tk = new StringTokenizer(path,"|");
			while(tk.hasMoreTokens()) {
				data.append(getInterfaceScript(tk.nextToken(),servletContext));
			}
		}
		
		return new StringReader(data.toString());
	}
682595
@Override
	public InputStream createResourceAsStream(GeneratorContext context) {

		InputStream is = null;
		if (FileNameUtils.hasImageExtension(context.getPath())) {
			is = helper.createStreamResource(context);
		}

		return is;
	}
756804
private void generateSources() {
        try {
            ExecutorService pool = Executors.newFixedThreadPool(context.getSettings().getNbThread());

            for (Java4CppType type : context.getClassesAlreadyDone()) {
                Class<?> clazz = type.getRawClass();
                if (isValid(clazz)) {
                    pool.execute(new SourceExecutor(context, type));
                }
            }

            pool.shutdown();
            while (!pool.isTerminated()) {
                pool.awaitTermination(TIMEOUT, TimeUnit.MILLISECONDS);
            }
        } catch (InterruptedException e) {
            throw new RuntimeException("Interrupted " + e.getMessage());
        }
    }
146956
@Override
	public InputStream getResourceAsStream(String resourceName, boolean processingBundle) {

		String path = resourceName;
		GeneratorRegistry generatorRegistry = jawrConfig.getGeneratorRegistry();
		if (generatorRegistry.isGeneratedBinaryResource(path)) {
			path = path.replace(':', '/');
			path = JawrConstant.SPRITE_GENERATED_IMG_DIR + path;
		}

		return ((StreamResourceReader) resourceReader).getResourceAsStream(path, processingBundle);
	}
389056
@FFDCIgnore({IOException.class})
    public static InputStream getResourceAsStream(String resourceName, Class<?> callingClass) {
        URL url = getResource(resourceName, callingClass);

        try {
            return (url != null) ? url.openStream() : null;
        } catch (IOException e) {
            return null;
        }
    }
1008465
@Override
	protected Reader generateResource(String path, GeneratorContext context) {

		Reader rd = null;
		if (FileNameUtils.isExtension(path, JawrConstant.JS_TYPE)) {
			rd = helper.createResource(context);
			String filePath = helper.getFilePath(path);
			if (filePath != null) {
				long lastModified = rsHandler.getLastModified(filePath);
				FilePathMapping fMapping = new FilePathMapping(filePath, lastModified);
				addLinkedResources(path, context, fMapping);
			}
		}
		return rd;
	}
283033
@Override
    public InputStream getResourceStream (String path)
        throws ResourceNotFoundException
    {
        SiteKey skey = new SiteKey(path);

        // load it on up
        try {
            InputStream stream = _loader.getResourceAsStream(
                skey.siteId, skey.path);
            if (stream == null) {
                String errmsg = "Unable to load resource via " +
                    "site-specific jar file [path=" + path + "].";
                throw new ResourceNotFoundException(errmsg);
            }
            return stream;

        } catch (IOException ioe) {
            throw new ResourceNotFoundException(ioe.getMessage());
        }
    }