/*
(non-Javadoc)

@see net.jawr.web.resource.handler.reader.StreamResourceReader#
getResourceAsStream(net.jawr.web.resource.bundle.JoinableResourceBundle,
java.lang.String, boolean)
329765
@Override
	public InputStream getResourceAsStream(String resourceName, boolean processingBundle) {

		InputStream is = null;
		if (!resourceName.contains(":") && isAccessPermitted(resourceName)) {
			is = context.getResourceAsStream(resourceName);
		}
		return is;
	}
844275
private InputStream getBundleMappingStream() {

		InputStream is = null;
		try {
			is = getTemporaryResourceAsStream(PathNormalizer.concatWebPath(tempDirPath + "/", mappingFileName));
		} catch (ResourceNotFoundException e) {
			// Nothing to do
		}
		return is;
	}
1059124
public static InputStream getRequiredStream(Class<?> root, String resourceName) {
        return getStream(root, resourceName, true);
    }
318972
@Override
	public Reader getResource(JoinableResourceBundle bundle, String resourceName, boolean processingBundle) {

		Reader rd = null;
		FileInputStream fis = (FileInputStream) getResourceAsStream(resourceName);
		if (fis != null) {
			FileChannel inchannel = fis.getChannel();
			rd = Channels.newReader(inchannel, charset.newDecoder(), -1);
		}

		return rd;
	}
727685
public InputStream createStreamResource(GeneratorContext context) {
		InputStream is = null;
		try {

			String resourcePath = context.getPath();
			String path = getCompletePath(resourcePath);
			is = ClassLoaderResourceUtils.getResourceAsStream(path, this);
		} catch (FileNotFoundException e) {
			throw new BundlingProcessException(e);
		}
		return is;
	}
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;
    }
839400
@Override
	public InputStream getResourceAsStream(String resourceName) {
		URL url = getResourceUrl(resourceName);
		if (url != null) {
			try {
				return url.openStream();
			} catch (IOException e) {
				throw new JKException(e);
			}
		}
		return null;
	}
906248
@Override
    public InputStream getResourceAsStream(final String path) {
        final ResourceList resourceList = scanResult.getResourcesWithPath(path);
        if (resourceList == null || resourceList.isEmpty()) {
            return super.getResourceAsStream(path);
        } else {
            try {
                return resourceList.get(0).open();
            } catch (final IOException e) {
                return null;
            }
        }
    }
1300801
public @Nonnull Optional<InputStream> getResourceAsStream(@Nonnull String path) {
        ArgumentUtils.requireNonNull("path", path);
        Optional<ResourceLoader> resourceLoader = getSupportingLoader(path);
        if (resourceLoader.isPresent()) {
            return resourceLoader.get().getResourceAsStream(path);
        }
        return Optional.empty();
    }
1138348
@Override
	public List<PathMapping> getPathMappings(JoinableResourceBundle bundle, String resourcePath,
			ResourceReaderHandler rsReader) {

		List<PathMapping> pathMappings = new ArrayList<>();
		PathMapping pathMapping = null;
		GeneratorMappingHelper helper = new GeneratorMappingHelper(resourcePath);
		String path = resolver.getResourcePath(helper.getPath());
		String[] names = path.split(RESOURCE_BUNDLE_SEPARATOR);

		for (String resourceName : names) {

			path = resourceName.replace(PACKAGE_SEPARATOR, JawrConstant.URL_SEPARATOR_CHAR);
			path = control.toBundleName(path, new Locale("", "")) + PROPERTIES_FILE_SUFFIX;
			URL rbURL = LocaleUtils.getResourceBundleURL(path, config.getContext());
			if (rbURL != null) {
				String strURL = rbURL.toString();
				// returns the path mapping only if the MessageBundle are on a
				// filesystem
				if (strURL.startsWith(JawrConstant.FILE_URL_PREFIX)) {
					String parentPath = "/WEB-INF/classes/" + PathNormalizer.getParentPath(path);
					String resourceBundleName = FileNameUtils.getBaseName(path);
					MessageBundleFileFilter filter = new MessageBundleFileFilter(resourceBundleName);
					pathMapping = new PathMapping(bundle, parentPath, filter);
					pathMappings.add(pathMapping);
				}
			}
		}
		return pathMappings;
	}
664824
@Override
	public Reader generateResource(String path, GeneratorContext context) {

		Reader rd = null;
		try {
			List<Class<?>> excluded = new ArrayList<>();
			excluded.add(ICoffeeScriptGenerator.class);
			JoinableResourceBundle bundle = context.getBundle();
			rd = rsHandler.getResource(bundle, path, false, excluded);
			StringWriter swr = new StringWriter();
			IOUtils.copy(rd, swr);

			String result = compile(path, swr.toString());
			rd = new StringReader(result);

			// Update linked resource map
			FilePathMapping fMapping = FilePathMappingUtils.buildFilePathMapping(path, rsHandler);
			if (fMapping != null) {
				addLinkedResources(path, context, fMapping);
			}

		} catch (ResourceNotFoundException | IOException e) {
			throw new BundlingProcessException(e);
		}

		return rd;
	}
340046
@Override
	public void writeBundleTo(String bundlePath, Writer writer) throws ResourceNotFoundException {
		
		String text = (String) cacheMgr.get(TEXT_CACHE_PREFIX + bundlePath);
		try {
			// If it's not cached yet
			if (null == text) {
				String charsetName = rsHandler.getConfig().getResourceCharset().name();
				ByteArrayOutputStream baOs = new ByteArrayOutputStream();
				WritableByteChannel wrChannel = Channels.newChannel(baOs);
				Writer tempWriter = Channels.newWriter(wrChannel, charsetName);
				rsHandler.writeBundleTo(bundlePath, tempWriter);
				text = baOs.toString(charsetName);
				cacheMgr.put(TEXT_CACHE_PREFIX + bundlePath, text);
			}

			// Write the text to the outputstream
			writer.write(text);
			writer.flush();

		} catch (IOException e) {
			throw new BundlingProcessException("Unexpected IOException writing bundle[" + bundlePath + "]", e);
		}finally {
			IOUtils.close(writer);
		}
	}
650158
protected InputStream getStream (String bundle, String path, String query)
        throws IOException
    {
        // we can only do this with PNGs
        if (!path.endsWith(".png")) {
            log.warning("Requested sub-tile of non-PNG resource",
                "bundle", bundle, "path", path, "dims", query);
            return _rmgr.getResource(bundle, path);
        }

        // parse the query string
        String[] bits = StringUtil.split(query, "&");
        int width = -1, height = -1, tidx = -1;
        HashMap<String, String> zations = null;
        try {
            for (String bit : bits) {
                if (bit.startsWith("width=")) {
                    width = Integer.parseInt(bit.substring(6));
                } else if (bit.startsWith("height=")) {
                    height = Integer.parseInt(bit.substring(7));
                } else if (bit.startsWith("tile=")) {
                    tidx = Integer.parseInt(bit.substring(5));
                } else if (bit.startsWith("zation=")) {
                    String[] zation = bit.substring(7).split(":");
                    if (zations == null) {
                        zations = Maps.newHashMap();
                    }

                    zations.put(zation[0], zation[1]);
                }
            }
        } catch (NumberFormatException nfe) {
        }
        if (width <= 0 || height <= 0 || tidx < 0) {
            log.warning("Bogus sub-image dimensions",
                "bundle", bundle, "path", path, "dims", query);
            throw new FileNotFoundException(path);
        }

        // locate the tile image, then write that subimage back out in PNG format into memory and
        // return an input stream for that
        BufferedImage src = StringUtil.isBlank(bundle) ?
            _rmgr.getImageResource(path) : _rmgr.getImageResource(bundle, path);
        Rectangle trect = GeomUtil.getTile(src.getWidth(), src.getHeight(), width, height, tidx);
        BufferedImage tile = src.getSubimage(trect.x, trect.y, trect.width, trect.height);
        if (zations != null) {
            ColorPository pository = ColorPository.loadColorPository(_rmgr);
            ArrayList<Colorization> colorizations = Lists.newArrayList();
            for (Map.Entry<String, String> entry : zations.entrySet()) {
                String zClass = entry.getKey();
                String zColor = entry.getValue();

                Colorization zation = null;

                // First try looking if we got a number
                try {
                    zation = pository.getColorization(zClass, Integer.parseInt(zColor));
                } catch (NumberFormatException nfe) { }

                // If that didn't work, try it as a zation name
                if (zation == null) {
                    zation = pository.getColorization(zClass, zColor);
                }

                if (zation == null) {
                    log.warning("Couldn't figure out requested zation",
                        "class", zClass, "color", zColor);
                } else {
                    colorizations.add(zation);
                }

            }

            tile = ImageUtil.recolorImage(tile,
                colorizations.toArray(new Colorization[colorizations.size()]));
        }

        ByteArrayOutInputStream data = new ByteArrayOutInputStream();
        ImageIO.write(tile, "PNG", data);
        return data.getInputStream();
    }
47276
@Override
    public HasInputStream readResource(Path path, ResourceMetaBuilder resourceMetaBuilder, final HasInputStream
            hasResourceStream) {
        if (wasEncoded(resourceMetaBuilder)) {
            return decode(hasResourceStream);
        }
        //return null to indicate no change was performed on the data
        return null;
    }
305897
@Override
	public URL getResource(String resourceName) {
		final String sourceMethod = "getResource"; //$NON-NLS-1$
		boolean isTraceLogging = log.isLoggable(Level.FINER);
		if (isTraceLogging) {
			log.entering(PlatformServicesImpl.class.getName(), sourceMethod, new Object[]{resourceName});
		}
		URL result = null;
		if (contributingBundle != null) {
			result = contributingBundle.getResource(resourceName);
		}
		if (isTraceLogging) {
			log.exiting(PlatformServicesImpl.class.getName(), sourceMethod, result);
		}
		return result;
	}
20325
public InputStream getResource (String path)
        throws IOException
    {
        String localePath = getLocalePath(path);
        InputStream in;

        // first look for this resource in our default resource bundle
        for (ResourceBundle bundle : _default) {
            // Try a localized version first.
            if (localePath != null) {
                in = bundle.getResource(localePath);
                if (in != null) {
                    return in;
                }
            }
            // If that didn't work, try generic.
            in = bundle.getResource(path);
            if (in != null) {
                return in;
            }
        }

        // fallback next to an unpacked resource file
        File file = getResourceFile(path);
        if (file != null && file.exists()) {
            return new FileInputStream(file);
        }

        // if we still didn't find anything, try the classloader; first try a locale-specific file
        if (localePath != null) {
            in = getInputStreamFromClasspath(PathUtil.appendPath(_rootPath, localePath));
            if (in != null) {
                return in;
            }
        }

        // if we didn't find that, try locale-neutral
        in = getInputStreamFromClasspath(PathUtil.appendPath(_rootPath, path));
        if (in != null) {
            return in;
        }

        // if we still haven't found it, we throw an exception
        throw new FileNotFoundException("Unable to locate resource [path=" + path + "]");
    }
472061
public InputStream getResourceAsStream(String resourceName, BeanContextChild child) throws IllegalArgumentException
	{
		if (resourceName == null || child == null)
		{
			throw new NullPointerException();
		}
		if (!contains(child))
		{
			throw new IllegalArgumentException(Messages.getString("beans.6D"));
		}

		return ClassLoader.getSystemResourceAsStream(resourceName);
	}