1 /**********************************************************************
2 * UTF8StringAdapter.java
3 * created on 18.03.2005 by netseeker
4 * $Source: /cvsroot/ejoe/EJOE/src/de/netseeker/ejoe/adapter/UTF8StringAdapter.java,v $
5 * $Date: 2006/11/05 16:33:37 $
6 * $Revision: 1.9 $
7 *
8 * ====================================================================
9 *
10 * Copyright 2005-2006 netseeker aka Michael Manske
11 *
12 * Licensed under the Apache License, Version 2.0 (the "License");
13 * you may not use this file except in compliance with the License.
14 * You may obtain a copy of the License at
15 *
16 * http://www.apache.org/licenses/LICENSE-2.0
17 *
18 * Unless required by applicable law or agreed to in writing, software
19 * distributed under the License is distributed on an "AS IS" BASIS,
20 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
21 * See the License for the specific language governing permissions and
22 * limitations under the License.
23 * ====================================================================
24 *
25 * This file is part of the ejoe framework.
26 * For more information on the author, please see
27 * <http://www.manskes.de/>.
28 *
29 */
30 package de.netseeker.ejoe.adapter;
31
32 import java.io.InputStream;
33 import java.io.InputStreamReader;
34 import java.io.OutputStream;
35 import java.io.OutputStreamWriter;
36 import java.io.Reader;
37 import java.io.Writer;
38
39 import de.netseeker.ejoe.EJConstants;
40
41 /***
42 * Simple raw string (de)Serializer for serializing/deserializing string messages. This adapter will always use UTF8
43 * encoding.
44 *
45 * @author netseeker
46 * @since 0.3.4
47 */
48 public class UTF8StringAdapter extends BaseAdapter
49 {
50 private static final long serialVersionUID = 1L;
51
52
53
54
55
56
57 public Object read( InputStream in ) throws Exception
58 {
59 Reader reader = new InputStreamReader( in, "UTF-8" );
60 char[] buffer = new char[EJConstants.BUFFERED_STREAM_SIZE];
61 char[] result = null;
62 char[] tmp = null;
63 int n = 0;
64 int pos = 1;
65 while ( -1 != (n = reader.read( buffer )) )
66 {
67 if ( result == null )
68 {
69 result = new char[n];
70 }
71 else
72 {
73 pos = result.length;
74 tmp = new char[pos + n];
75 System.arraycopy( result, 0, tmp, 0, pos - 1 );
76 result = tmp;
77 }
78
79 System.arraycopy( buffer, 0, result, pos - 1, n );
80 }
81
82 reader.close();
83
84 if ( result != null )
85 {
86 return new String( result );
87 }
88 else
89 {
90 return null;
91 }
92 }
93
94
95
96
97
98
99 public void write( Object obj, OutputStream out ) throws Exception
100 {
101 Writer writer = new OutputStreamWriter( out, "UTF-8" );
102 writer.write( obj.toString() );
103 writer.close();
104 }
105
106
107
108
109
110
111 public String getContentType()
112 {
113 return "text/plain";
114 }
115 }