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 **/
019/**
020 * Implements the CFML Function tobinary
021 */
022package lucee.runtime.functions.other;
023
024import java.nio.charset.Charset;
025
026import lucee.commons.io.CharsetUtil;
027import lucee.commons.lang.StringUtil;
028import lucee.runtime.PageContext;
029import lucee.runtime.PageContextImpl;
030import lucee.runtime.exp.PageException;
031import lucee.runtime.ext.function.Function;
032import lucee.runtime.op.Caster;
033
034public final class ToBinary implements Function {
035
036        private static final long serialVersionUID = 4541724601337401920L;
037
038        public static byte[] call(PageContext pc , Object data) throws PageException {
039                return call(pc, data, null);
040        }
041        public static byte[] call(PageContext pc , Object data, String charset) throws PageException {
042                if(!StringUtil.isEmpty(charset)) {
043                        charset=charset.trim().toLowerCase();
044                        Charset cs;
045                        if("web".equalsIgnoreCase(charset))cs=((PageContextImpl)pc).getWebCharset();
046                        if("resource".equalsIgnoreCase(charset))cs=((PageContextImpl)pc).getResourceCharset();
047                        else cs=CharsetUtil.toCharset(charset);
048                                
049                        String str=Caster.toString(data);
050                        return str.getBytes(cs);
051                }
052                return Caster.toBinary(data);
053        }
054}