Skip to content

Instantly share code, notes, and snippets.

@atma
Forked from chethann/WebviewResourceMappingHelper.java
Last active October 2, 2023 05:01
Show Gist options
  • Save atma/4f42debb4a8f0f8ebdd253c448981cd8 to your computer and use it in GitHub Desktop.
Save atma/4f42debb4a8f0f8ebdd253c448981cd8 to your computer and use it in GitHub Desktop.
@Override
public WebResourceResponse shouldInterceptRequest(WebView view, WebResourceRequest request) {
String resourceUrl = request.getUrl().toString();
String fileExtension = WebviewResourceMappingHelper.getInstance().getFileExt(resourceUrl);
if(WebviewResourceMappingHelper.getInstance().getOverridableExtensions().contains(fileExtension)){
String encoding = "UTF-8";
String assetName = WebviewResourceMappingHelper.getInstance().getLocalAssetPath(resourceUrl);
if (StringUtils.isNotEmpty(assetName)) {
String mimeType = WebviewResourceMappingHelper.getInstance().getMimeType(fileExtension);
if (StringUtils.isNotEmpty(mimeType)) {
try {
Log.e(TAG, assetName);
return WebviewResourceMappingHelper.getWebResourceResponseFromAsset(assetName, mimeType, encoding);
} catch (IOException e) {
return super.shouldInterceptRequest(view, request);
}
}
}
String localFilePath = WebviewResourceMappingHelper.getInstance().getLocalFilePath(resourceUrl);
if (StringUtils.isNotEmpty(localFilePath)) {
String mimeType = WebviewResourceMappingHelper.getInstance().getMimeType(fileExtension);
if(StringUtils.isNotEmpty(mimeType)){
try {
Log.e(TAG, localFilePath);
return WebviewResourceMappingHelper.getWebResourceResponseFromFile(localFilePath, mimeType, encoding);
} catch (FileNotFoundException e) {
return super.shouldInterceptRequest(view,request);
}
}
}
}
if (fileExtension.endsWith("jpg")) {
try {
InputStream inputStream = ImageUtils.readFromCacheSync(resourceUrl);
if (inputStream != null) {
return new WebResourceResponse("image/jpg", "UTF-8", inputStream);
}
} catch (Exception e) {
return super.shouldInterceptRequest(view,request);
}
}
return super.shouldInterceptRequest(view,request);
}
public static InputStream readFromCacheSync(String imageUrl) {
CacheKey cacheKey = DefaultCacheKeyFactory.getInstance().getEncodedCacheKey(ImageRequest.fromUri(imageUrl), null);
StagingArea stagingArea = StagingArea.getInstance();
EncodedImage encodedImage = stagingArea.get(cacheKey);
if (encodedImage != null) {
return encodedImage.getInputStream();
}
try {
return readFromDiskCache(cacheKey);
} catch (Exception e) {
return null;
}
}
private static InputStream readFromDiskCache(final CacheKey key) throws IOException {
try {
FileCache fileCache = ImagePipelineFactory.getInstance().getMainFileCache();
final BinaryResource diskCacheResource = fileCache.getResource(key);
if (diskCacheResource == null) {
FLog.v(TAG, "Disk cache miss for %s", key.toString());
return null;
}
PooledByteBuffer byteBuffer;
final InputStream is = diskCacheResource.openStream();
FLog.v(TAG, "Successful read from disk cache for %s", key.toString());
return is;
} catch (IOException ioe) {
return null;
}
}
package com.test.android.helpers;
import android.os.Build;
import android.webkit.WebResourceResponse;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.test.android.Application;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class WebviewResourceMappingHelper {
private static WebviewResourceMappingHelper instance;
private List<LocalAssetMapModel> localAssetMapModelList;
private List<String> overridableExtensions = new ArrayList<>(Arrays.asList("js", "css", "png", "jpg", "woff", "ttf", "eot", "ico"));
private WebviewResourceMappingHelper(){
}
public static WebviewResourceMappingHelper getInstance(){
if(instance == null){
instance = new WebviewResourceMappingHelper();
}
return instance;
}
public String getLocalAssetPath(String url){
if(StringUtils.isEmpty(url)){
return "";
}
if(localAssetMapModelList == null){
localAssetMapModelList = getLocalAssetList();
}
if(CollectionUtils.isNotEmpty(localAssetMapModelList)){
for(LocalAssetMapModel localAssetMapModel : localAssetMapModelList){
if(localAssetMapModel.url.equals(url)){
return localAssetMapModel.asset_url;
}
}
}
return "";
}
public String getLocalFilePath(String url){
String localFilePath = "";
String fileNameForUrl = getLocalFileNameForUrl(url);
if(StringUtils.isNotEmpty(fileNameForUrl) && fileExists(fileNameForUrl)){
localFilePath = getFileFullPath(fileNameForUrl);
}
return localFilePath;
}
public String getLocalFileNameForUrl(String url){
String localFileName = "";
String[] parts = url.split("/");
if(parts.length > 0){
localFileName = parts[parts.length-1];
}
return localFileName;
}
private boolean fileExists(String fileName){
String path = Application.getInstance()
.getFilesDir() + "/cart/" + fileName;
return new File(path).exists();
}
private String getFileFullPath(String relativePath){
return Application.getInstance().getFilesDir() + "/cart/" + relativePath;
}
private List<LocalAssetMapModel> getLocalAssetList(){
List<LocalAssetMapModel> localAssetMapModelList = new ArrayList<>();
String pageData = null;
try {
pageData = ResourceAccessHelper.getJsonData(Application.getCurrentInstance(), "web-assets/map.json");
} catch (IOException e) {
}
if(pageData !=null){
Type listType = new TypeToken<ArrayList<LocalAssetMapModel>>() {
}.getType();
localAssetMapModelList = new Gson().fromJson(pageData,listType);
}
pageData = null;
try {
pageData = ResourceAccessHelper.getJsonData(Application.getCurrentInstance(), "web-assets/fonts-map.json");
} catch (IOException e) {
}
if(pageData !=null){
Type listType = new TypeToken<ArrayList<LocalAssetMapModel>>() {
}.getType();
List<LocalAssetMapModel> fontsMap = new Gson().fromJson(pageData,listType);
localAssetMapModelList.addAll(fontsMap);
}
return localAssetMapModelList;
}
public List<String> getOverridableExtensions(){
return overridableExtensions;
}
public String getFileExt(String fileName) {
return fileName.substring(fileName.lastIndexOf(".") + 1, fileName.length());
}
public String getMimeType(String fileExtension){
String mimeType = "";
switch (fileExtension){
case "css" :
mimeType = "text/css";
break;
case "js" :
mimeType = "text/javascript";
break;
case "png" :
mimeType = "image/png";
break;
case "jpg" :
mimeType = "image/jpeg";
break;
case "ico" :
mimeType = "image/x-icon";
break;
case "woff" :
case "ttf" :
case "eot" :
mimeType = "application/x-font-opentype";
break;
}
return mimeType;
}
public static WebResourceResponse getWebResourceResponseFromAsset(String assetPath, String mimeType, String encoding) throws IOException{
InputStream inputStream = Application.getInstance().getAssets().open(assetPath);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
int statusCode = 200;
String reasonPhase = "OK";
Map<String, String> responseHeaders = new HashMap<String, String>();
responseHeaders.put("Access-Control-Allow-Origin", "*");
return new WebResourceResponse(mimeType, encoding, statusCode, reasonPhase, responseHeaders, inputStream);
}
return new WebResourceResponse(mimeType, encoding, inputStream);
}
public static WebResourceResponse getWebResourceResponseFromFile(String filePath, String mimeType, String encoding) throws FileNotFoundException {
File file = new File(filePath);
FileInputStream fileInputStream = new FileInputStream(file);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
int statusCode = 200;
String reasonPhase = "OK";
Map<String, String> responseHeaders = new HashMap<String, String>();
responseHeaders.put("Access-Control-Allow-Origin","*");
return new WebResourceResponse(mimeType, encoding, statusCode, reasonPhase, responseHeaders, fileInputStream);
}
return new WebResourceResponse(mimeType, encoding, fileInputStream);
}
private class LocalAssetMapModel{
String url;
String asset_url;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment