changing license to BSD, assigning Yahoo copyrights where appropriate
[lwes-java.git] / src / main / java / org / lwes / util / EncodedString.java
blob9868ad8f56d6766811703649e045dd27bcda9716
1 /*======================================================================*
2 * Copyright (c) 2008, Yahoo! Inc. All rights reserved. *
3 * *
4 * Licensed under the New BSD License (the "License"); you may not use *
5 * this file except in compliance with the License. Unless required *
6 * by applicable law or agreed to in writing, software distributed *
7 * under the License is distributed on an "AS IS" BASIS, WITHOUT *
8 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. *
9 * See the License for the specific language governing permissions and *
10 * limitations under the License. See accompanying LICENSE file. *
11 *======================================================================*/
13 package org.lwes.util;
15 import java.io.UnsupportedEncodingException;
17 /**
18 * EncodedString is a wrapper class which wraps a String, but replaces all
19 * methods using a string representation of a character encoding with
20 * ones using the CharacterEncoding class, thereby guaranteeing
21 * validity and eliminating the need to throw any exceptions.
23 * @author Kevin Scaldeferri
24 * @version %I%, %G%
25 * @since 0.0.1
27 public class EncodedString {
28 private String myString;
29 private CharacterEncoding myEncoding;
31 public static String bytesToString(byte[] bytes, CharacterEncoding enc) {
32 if (bytes == null) {
33 return null;
36 try {
37 return new String(bytes, enc.getEncodingString());
38 } catch (UnsupportedEncodingException e) {
39 throw new IllegalArgumentException("Unknown Encoding");
43 public static String bytesToString(byte[] bytes, int offset, int length, CharacterEncoding enc) {
44 if (bytes == null) {
45 return null;
48 try {
49 return new String(bytes, offset, length, enc.getEncodingString());
50 } catch (UnsupportedEncodingException e) {
51 throw new IllegalArgumentException("Unknown Encoding");
55 public static byte[] getBytes(String string, CharacterEncoding enc) {
56 if (string == null) {
57 return null;
60 try {
61 return string.getBytes(enc.getEncodingString());
62 } catch (UnsupportedEncodingException e) {
63 throw new IllegalArgumentException("Unknown Encoding");
67 public EncodedString(String string, CharacterEncoding enc) {
68 myString = string;
69 myEncoding = enc;
72 public EncodedString(byte[] bytes, CharacterEncoding enc) {
73 myString = bytesToString(bytes, enc);
74 myEncoding = enc;
77 public EncodedString(byte[] bytes, int offset,
78 int length, CharacterEncoding enc)
80 myString = bytesToString(bytes, offset, length, enc);
81 myEncoding = enc;
84 public byte[] getBytes() { return getBytes(myString, myEncoding); }
85 public String toString() { return myString; }