Strings.java
01 /*
02  *
03  * Licensed to the Apache Software Foundation (ASF) under one
04  * or more contributor license agreements.  See the NOTICE file
05  * distributed with this work for additional information
06  * regarding copyright ownership.  The ASF licenses this file
07  * to you under the Apache License, Version 2.0 (the
08  * "License"); you may not use this file except in compliance
09  * with the License.  You may obtain a copy of the License at
10  *
11  *   http://www.apache.org/licenses/LICENSE-2.0
12  *
13  * Unless required by applicable law or agreed to in writing,
14  * software distributed under the License is distributed on an
15  * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
16  * KIND, either express or implied.  See the License for the
17  * specific language governing permissions and limitations
18  * under the License.
19  *
20  */
21 package org.apache.qpid.util;
22 
23 import java.io.UnsupportedEncodingException;
24 
25 
26 /**
27  * Strings
28  *
29  */
30 
31 public final class Strings
32 {
33 
34     private static final byte[] EMPTY = new byte[0];
35 
36     private static final ThreadLocal<char[]> charbuf = new ThreadLocal()
37     {
38         public char[] initialValue()
39         {
40             return new char[4096];
41         }
42     };
43 
44     public static final byte[] toUTF8(String str)
45     {
46         if (str == null)
47         {
48             return EMPTY;
49         }
50         else
51         {
52             final int size = str.length();
53             char[] chars = charbuf.get();
54             if (size > chars.length)
55             {
56                 chars = new char[Math.max(size, 2*chars.length)];
57                 charbuf.set(chars);
58             }
59 
60             str.getChars(0, size, chars, 0);
61             final byte[] bytes = new byte[size];
62             for (int i = 0; i < size; i++)
63             {
64                 if (chars[i127)
65                 {
66                     try
67                     {
68                         return str.getBytes("UTF-8");
69                     }
70                     catch (UnsupportedEncodingException e)
71                     {
72                         throw new RuntimeException(e);
73                     }
74                 }
75 
76                 bytes[i(bytechars[i];
77             }
78             return bytes;
79         }
80     }
81 
82     public static final String fromUTF8(byte[] bytes)
83     {
84         try
85         {
86             return new String(bytes, "UTF-8");
87         }
88         catch (UnsupportedEncodingException e)
89         {
90             throw new RuntimeException(e);
91         }
92     }
93 
94 }