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.commons.io; 020 021import java.nio.charset.Charset; 022 023import lucee.commons.lang.ExceptionUtil; 024import lucee.commons.lang.StringUtil; 025import lucee.runtime.PageContext; 026import lucee.runtime.PageContextImpl; 027import lucee.runtime.config.Config; 028import lucee.runtime.config.ConfigImpl; 029import lucee.runtime.engine.ThreadLocalPageContext; 030 031public class CharsetUtil { 032 public static final Charset UTF8; 033 public static final Charset ISO88591; 034 public static final Charset UTF16BE; 035 public static final Charset UTF16LE; 036 public static final Charset UTF32BE; 037 public static final Charset UTF32LE; 038 039 static { 040 UTF8=toCharset("utf-8",null); 041 ISO88591=toCharset("iso-8859-1",null); 042 043 UTF16BE=toCharset("utf-16BE",null); 044 UTF16LE=toCharset("utf-16LE",null); 045 046 UTF32BE=toCharset("utf-32BE",null); 047 UTF32LE=toCharset("utf-32LE",null); 048 } 049 050 public static Charset toCharset(String charset) { 051 if(StringUtil.isEmpty(charset,true)) return null; 052 return Charset.forName(charset.trim()); 053 } 054 055 public static Charset toCharset(String charset,Charset defaultValue) { 056 if(StringUtil.isEmpty(charset)) return defaultValue; 057 try{ 058 return Charset.forName(charset); 059 } 060 catch(Throwable t){ 061 ExceptionUtil.rethrowIfNecessary(t); 062 return defaultValue; 063 } 064 } 065 066 public static Charset getWebCharset() { 067 PageContext pc = ThreadLocalPageContext.get(); 068 if(pc!=null) return ((PageContextImpl)pc).getWebCharset(); 069 Config config = ThreadLocalPageContext.getConfig(); 070 if(config!=null) return ((ConfigImpl)config)._getWebCharset(); 071 072 return CharsetUtil.ISO88591; 073 } 074 075}