001 package railo.runtime.functions.file; 002 003 import java.io.ByteArrayOutputStream; 004 import java.io.IOException; 005 import java.io.InputStream; 006 007 import railo.commons.io.IOUtil; 008 import railo.commons.io.res.Resource; 009 import railo.runtime.PageContext; 010 import railo.runtime.exp.PageException; 011 import railo.runtime.op.Caster; 012 import railo.runtime.op.Decision; 013 014 public class FileRead { 015 016 public static Object call(PageContext pc, Object path) throws PageException { 017 return _call(pc,Caster.toResource(pc,path,true),pc.getConfig().getResourceCharset()); 018 } 019 020 public static Object call(PageContext pc, Object obj, Object charsetOrSize) throws PageException { 021 if(charsetOrSize==null) return call(pc, obj); 022 023 if(obj instanceof FileStreamWrapper) { 024 return _call((FileStreamWrapper)obj,Caster.toIntValue(charsetOrSize)); 025 } 026 Resource res = Caster.toResource(pc,obj,true); 027 String charset=Caster.toString(charsetOrSize); 028 if(Decision.isInteger(charset)){ 029 charset=pc.getConfig().getResourceCharset(); 030 return _call(pc,res,charset,Caster.toIntValue(charset)); 031 } 032 033 return _call(pc,res,charset); 034 } 035 036 private static Object _call(FileStreamWrapper fs, int size) throws PageException { 037 try { 038 return fs.read(size); 039 } catch (IOException e) { 040 throw Caster.toPageException(e); 041 } 042 } 043 044 private static Object _call(PageContext pc,Resource res, String charset) throws PageException { 045 pc.getConfig().getSecurityManager().checkFileLocation(res); 046 try { 047 return IOUtil.toString(res,charset); 048 } catch (IOException e) { 049 throw Caster.toPageException(e); 050 } 051 } 052 053 private static Object _call(PageContext pc, Resource res, String charset,int size) throws PageException { 054 pc.getConfig().getSecurityManager().checkFileLocation(res); 055 056 InputStream is=null; 057 ByteArrayOutputStream baos = new ByteArrayOutputStream(); 058 try { 059 is=res.getInputStream(); 060 IOUtil.copy(is, baos, 0, size); 061 return new String(baos.toByteArray(),charset); 062 } 063 catch (IOException e) { 064 throw Caster.toPageException(e); 065 } 066 finally { 067 IOUtil.closeEL(is); 068 } 069 070 071 // TODO Auto-generated method stub 072 } 073 074 }