001/**
002 *
003 * Copyright (c) 2014, the Railo Company Ltd. All rights reserved.
004 *
005 * This library is free software; you can redistribute it and/or
006 * modify it under the terms of the GNU Lesser General Public
007 * License as published by the Free Software Foundation; either 
008 * version 2.1 of the License, or (at your option) any later version.
009 * 
010 * This library is distributed in the hope that it will be useful,
011 * but WITHOUT ANY WARRANTY; without even the implied warranty of
012 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
013 * Lesser General Public License for more details.
014 * 
015 * You should have received a copy of the GNU Lesser General Public 
016 * License along with this library.  If not, see <http://www.gnu.org/licenses/>.
017 * 
018 **/
019package lucee.runtime.functions.other;
020
021import java.io.ByteArrayInputStream;
022import java.io.IOException;
023import java.io.Serializable;
024
025import lucee.commons.io.IOUtil;
026import lucee.commons.io.res.Resource;
027import lucee.commons.io.res.util.ResourceUtil;
028import lucee.commons.lang.StringUtil;
029import lucee.runtime.PageContext;
030import lucee.runtime.converter.JavaConverter;
031import lucee.runtime.exp.ApplicationException;
032import lucee.runtime.exp.PageException;
033import lucee.runtime.op.Caster;
034
035import org.apache.commons.io.output.ByteArrayOutputStream;
036
037public class ObjectSave {
038    
039        public synchronized static Object call(PageContext pc, Object input) throws PageException {
040        return call(pc,input,null);
041    }
042        
043    public synchronized static Object call(PageContext pc, Object input,String filepath) throws PageException {
044        if(!(input instanceof Serializable))
045                throw new ApplicationException("can only serialize object from type Serializable");
046        
047        ByteArrayOutputStream baos = new ByteArrayOutputStream();
048        try {
049                        JavaConverter.serialize((Serializable)input,baos);
050                
051
052                byte[] barr = baos.toByteArray();
053                        
054                        // store to file
055                        if(!StringUtil.isEmpty(filepath,true)) {
056                                Resource res = ResourceUtil.toResourceNotExisting(pc, filepath);
057                                pc.getConfig().getSecurityManager().checkFileLocation(res);
058                        IOUtil.copy(new ByteArrayInputStream(barr),res,true);
059                        }
060                return barr;
061        
062        }
063        catch (IOException e) {
064                        throw Caster.toPageException(e);
065                }
066    }
067}