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