1 /*
2 * Copyright 2006 Simon Raess
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16 package net.sf.beep4j.internal.util;
17
18 import java.io.UnsupportedEncodingException;
19
20 import net.sf.beep4j.ProtocolException;
21
22 /**
23 * Utility class for parsing stuff.
24 *
25 * @author Simon Raess
26 */
27 public final class ByteUtil {
28
29 private ByteUtil() { }
30
31 public static final byte[] toASCII(String s) {
32 try {
33 return s.getBytes("US-ASCII");
34 } catch (UnsupportedEncodingException e) {
35 throw new RuntimeException(e);
36 }
37 }
38
39 public static final String base64Encode(byte[] data) {
40 Base64Encoder encoder = new Base64Encoder();
41 return encoder.encode(data);
42 }
43
44 /**
45 * Parses a String field that must be in the range 0..2147483647.
46 *
47 * @param field the name of the field
48 * @param s the String to parse
49 * @return the value returned as an int
50 * @throws ProtocolException if the parsed value does not conform to the
51 * expected format and range
52 */
53 public static final int parseUnsignedInt(String field, String s) {
54 try {
55 int result = Integer.parseInt(s);
56 if (result < 0 || result > 2147483647) {
57 throw new ProtocolException(field + " must be in range 0..2147483647");
58 }
59 return result;
60 } catch (NumberFormatException e) {
61 throw new ProtocolException(field + ": " + e.getMessage(), e);
62 }
63 }
64
65 /**
66 * Parses a String field that must be in the range 0..4294967295.
67 *
68 * @param field the name of the field
69 * @param s the String to parse
70 * @return the value returned as a long
71 * @throws ProtocolException if the parsed value does not conform to the
72 * expected format and range
73 */
74 public static final long parseUnsignedLong(String field, String s) {
75 try {
76 long result = Long.parseLong(s);
77 if (result < 0 || result > 4294967295L) {
78 throw new ProtocolException(field + " must be in range 0..4294967295");
79 }
80 return result;
81 } catch (NumberFormatException e) {
82 throw new ProtocolException(field + ": " + e.getMessage(), e);
83 }
84 }
85
86 }