001/** 002 * GRANITE DATA SERVICES 003 * Copyright (C) 2006-2013 GRANITE DATA SERVICES S.A.S. 004 * 005 * This file is part of the Granite Data Services Platform. 006 * 007 * Granite Data Services is free software; you can redistribute it and/or 008 * modify it under the terms of the GNU Lesser General Public 009 * License as published by the Free Software Foundation; either 010 * version 2.1 of the License, or (at your option) any later version. 011 * 012 * Granite Data Services is distributed in the hope that it will be useful, 013 * but WITHOUT ANY WARRANTY; without even the implied warranty of 014 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser 015 * General Public License for more details. 016 * 017 * You should have received a copy of the GNU Lesser General Public 018 * License along with this library; if not, write to the Free Software 019 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, 020 * USA, or see <http://www.gnu.org/licenses/>. 021 */ 022package org.granite.messaging.jmf.codec.std.impl; 023 024import org.granite.messaging.jmf.JMFEncodingException; 025import org.granite.messaging.jmf.codec.StandardCodec; 026 027/** 028 * @author Franck WOLFF 029 */ 030public abstract class AbstractStandardCodec<T> implements StandardCodec<T> { 031 032 protected JMFEncodingException newBadTypeJMFEncodingException(int jmfType, int parameterizedJmfType) { 033 return new JMFEncodingException( 034 "Bad JMF type for " + getClass().getName() + ": " + jmfType + 035 " (parameterized: " + parameterizedJmfType + ")" 036 ); 037 } 038 039 protected String escape(String s) { 040 if (s == null || s.length() == 0) 041 return s; 042 043 StringBuilder sb = new StringBuilder(s.length()); 044 045 final int max = s.length(); 046 for (int i = 0; i < max; i++) { 047 char c = s.charAt(i); 048 escape(c, sb); 049 } 050 051 return sb.toString(); 052 } 053 054 protected String escape(char c) { 055 StringBuilder sb = new StringBuilder(6); 056 escape(c, sb); 057 return sb.toString(); 058 } 059 060 protected void escape(char c, StringBuilder sb) { 061 if (c >= 0x20 && c <= 0x7F) 062 sb.append(c); 063 else { 064 switch (c) { 065 case '\n': sb.append("\\n"); break; 066 case '\t': sb.append("\\t"); break; 067 case '\r': sb.append("\\r"); break; 068 case '\'': sb.append("\\\'"); break; 069 case '\"': sb.append("\\\""); break; 070 case '\\': sb.append("\\\\"); break; 071 case '\b': sb.append("\\b"); break; 072 case '\f': sb.append("\\f"); break; 073 default: { 074 String hex = Integer.toHexString(c); 075 switch (hex.length()) { 076 case 1: sb.append("\\u000"); break; 077 case 2: sb.append("\\u00"); break; 078 case 3: sb.append("\\u0"); break; 079 default: sb.append("\\u"); break; 080 } 081 sb.append(hex); 082 break; 083 } 084 } 085 } 086 } 087}