View Javadoc

1   /**
2    * Copyright 2010-2012 The Kuali Foundation
3    *
4    * Licensed under the Educational Community 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.opensource.org/licenses/ecl2.php
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 org.kuali.common.util;
17  
18  import java.io.IOException;
19  
20  import junit.framework.Assert;
21  
22  import org.apache.commons.lang3.StringUtils;
23  import org.junit.Test;
24  import org.slf4j.Logger;
25  import org.slf4j.LoggerFactory;
26  
27  public class HexUtilsTest {
28  
29  	private static final Logger logger = LoggerFactory.getLogger(HexUtilsTest.class);
30  
31  	@Test
32  	public void testInvalidHex() throws IOException {
33  		try {
34  			logger.info(HexUtils.toStringFromHex("3", "UTF-8"));
35  			Assert.fail("Strings with an odd number of characters should fail");
36  		} catch (IllegalArgumentException e) {
37  			logger.info(e.getMessage());
38  		}
39  		try {
40  			logger.info(HexUtils.toStringFromHex("FFA019z7AA", "UTF-8"));
41  			Assert.fail("Strings with characters outside the range 0-9, a-f, and A-F should fail");
42  		} catch (IllegalArgumentException e) {
43  			logger.info(e.getMessage());
44  		}
45  	}
46  
47  	@Test
48  	public void testRoundTripSimple() throws IOException {
49  		testString("123");
50  	}
51  
52  	@Test
53  	public void testRoundTrip() throws IOException {
54  		testString("𝟙𝟚𝟛");
55  	}
56  
57  	protected void testString(String s) throws IOException {
58  		String[] encodings = new String[] { "UTF-8", "UTF-16", "UTF-32" };
59  		String oldString = s;
60  		for (String encoding : encodings) {
61  			String hex = HexUtils.toHexString(oldString, encoding);
62  			logger.info("Converting '" + oldString + "' into hex using " + StringUtils.rightPad(encoding, 7, " ") + "[" + hex + "]");
63  			String newString = HexUtils.toStringFromHex(hex, encoding);
64  			logger.debug("originalString=" + oldString + " newString=" + newString);
65  			Assert.assertEquals(oldString, newString);
66  		}
67  	}
68  }