001/** 002 * Copyright 2010-2016 Boxfuse GmbH 003 * <p/> 004 * Licensed under the Apache License, Version 2.0 (the "License"); 005 * you may not use this file except in compliance with the License. 006 * You may obtain a copy of the License at 007 * <p/> 008 * http://www.apache.org/licenses/LICENSE-2.0 009 * <p/> 010 * Unless required by applicable law or agreed to in writing, software 011 * distributed under the License is distributed on an "AS IS" BASIS, 012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 013 * See the License for the specific language governing permissions and 014 * limitations under the License. 015 */ 016package org.avaje.classpath.scanner.internal.scanner.classpath.android; 017 018import android.content.res.AssetManager; 019import org.avaje.classpath.scanner.internal.FileCopyUtils; 020import org.avaje.classpath.scanner.Resource; 021import org.avaje.classpath.scanner.core.ClassPathScanException; 022 023import java.io.IOException; 024import java.io.InputStreamReader; 025 026/** 027 * Resource within an Android App. 028 */ 029public class AndroidResource implements Resource { 030 private final AssetManager assetManager; 031 private final String path; 032 private final String name; 033 034 public AndroidResource(AssetManager assetManager, String path, String name) { 035 this.assetManager = assetManager; 036 this.path = path; 037 this.name = name; 038 } 039 040 public String toString() { 041 return getLocation(); 042 } 043 044 @Override 045 public String getLocation() { 046 return path + "/" + name; 047 } 048 049 @Override 050 public String getLocationOnDisk() { 051 return null; 052 } 053 054 @Override 055 public String loadAsString(String encoding) { 056 try { 057 return FileCopyUtils.copyToString(new InputStreamReader(assetManager.open(getLocation()), encoding)); 058 } catch (IOException e) { 059 throw new ClassPathScanException("Unable to load asset: " + getLocation(), e); 060 } 061 } 062 063 @Override 064 public byte[] loadAsBytes() { 065 try { 066 return FileCopyUtils.copyToByteArray(assetManager.open(getLocation())); 067 } catch (IOException e) { 068 throw new ClassPathScanException("Unable to load asset: " + getLocation(), e); 069 } 070 } 071 072 @Override 073 public String getFilename() { 074 return name; 075 } 076}