01: /*
02: * Licensed to the Apache Software Foundation (ASF) under one or more
03: * contributor license agreements. See the NOTICE file distributed with
04: * this work for additional information regarding copyright ownership.
05: * The ASF licenses this file to You under the Apache License, Version 2.0
06: * (the "License"); you may not use this file except in compliance with
07: * the License. You may obtain a copy of the License at
08: *
09: * http://www.apache.org/licenses/LICENSE-2.0
10: *
11: * Unless required by applicable law or agreed to in writing, software
12: * distributed under the License is distributed on an "AS IS" BASIS,
13: * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14: * See the License for the specific language governing permissions and
15: * limitations under the License.
16: */
17:
18: package org.apache.harmony.auth.jgss;
19:
20: import java.io.UnsupportedEncodingException;
21:
22: import org.ietf.jgss.GSSException;
23:
24: public class GSSUtils {
25:
26: public static final String DEFAULT_CHARSET_NAME = "UTF-8";
27:
28: public static final int DEFAULT_GSSEXCEPTION_MAJOR_CODE = 3;
29:
30: public static final int DEFAULT_GSSEXCEPTION_MINOR_CODE = 0;
31:
32: public static String toString(byte[] bytes) throws GSSException {
33: try {
34: return new String(bytes, DEFAULT_CHARSET_NAME);
35: } catch (UnsupportedEncodingException e) {
36: throw new GSSException(DEFAULT_GSSEXCEPTION_MAJOR_CODE,
37: DEFAULT_GSSEXCEPTION_MINOR_CODE, e.getMessage());
38: }
39: }
40:
41: public static byte[] getBytes(String s) throws GSSException {
42: try {
43: return s.getBytes(DEFAULT_CHARSET_NAME);
44: } catch (UnsupportedEncodingException e) {
45: throw new GSSException(DEFAULT_GSSEXCEPTION_MAJOR_CODE,
46: DEFAULT_GSSEXCEPTION_MINOR_CODE, e.getMessage());
47: }
48: }
49:
50: public static byte[] getBytes(int source, int length) {
51: if (source < 0) {
52: throw new Error(
53: "org.apache.harmony.auth.jgss.GSSUtils.getBytes(int i, int length) does not support negative integer");
54: }
55: if (length <= 0 || length > 4) {
56: throw new Error(
57: "org.apache.harmony.auth.jgss.GSSUtils.getBytes(int i, int length) must have 0<length<=4");
58: }
59: byte[] target = new byte[length];
60: int shift = (length - 1) * 8;
61: for (int j = 0; j < length; j++) {
62: target[j] = (byte) (source >>> shift);
63: shift -= 8;
64: }
65: return target;
66: }
67:
68: public static int toInt(byte[] source, int offset, int length) {
69: if (length == 0 || length > 4) {
70: throw new Error(
71: "org.apache.harmony.auth.jgss.GSSUtils.toInt(byte[] source) must have 0<source.length<=4");
72: }
73: if (source[0] < 0) {
74: throw new Error(
75: "org.apache.harmony.auth.jgss.GSSUtils.toInt(byte[] source) does not support negative integer.");
76: }
77: int target = 0;
78: for (int index = offset; index < offset + length; index++) {
79: byte b = source[index];
80: target <<= 8;
81: target += (b & 0xFF);
82: }
83: return target;
84: }
85: }
|