001: /*
002:
003: This software is OSI Certified Open Source Software.
004: OSI Certified is a certification mark of the Open Source Initiative.
005:
006: The license (Mozilla version 1.0) can be read at the MMBase site.
007: See http://www.MMBase.org/license
008:
009: */
010: package org.mmbase.util.transformers;
011:
012: import java.util.HashMap;
013: import java.util.Map;
014:
015: /**
016: * Encode a bytearray to a string by converting every byte to a hexadecimal (00 - FF)
017: * representation, and decode the other way around.
018: *
019: * @author Johannes Verelst
020: * @since MMBase-1.8.1
021: * @version $Id: Hex.java,v 1.5 2007/08/04 08:09:14 michiel Exp $
022: */
023:
024: public class Hex extends ByteArrayToCharTransformer implements
025: ByteToCharTransformer, ConfigurableTransformer {
026: private final static String ENCODING = "HEX";
027: private final static int HEX = 1;
028:
029: int to = HEX;
030:
031: public void configure(int t) {
032: to = t;
033: }
034:
035: /**
036: * Used when registering this class as a possible Transformer
037: */
038:
039: public Map<String, Config> transformers() {
040: Map<String, Config> h = new HashMap<String, Config>();
041: h
042: .put(
043: ENCODING,
044: new Config(Hex.class, HEX,
045: "Encoding bytearrays to and from a hexidecimal string"));
046: return h;
047: }
048:
049: /**
050: * Transform a bytearray to a string of hexadecimal digits.
051: */
052: public String transform(byte[] bytes) {
053: StringBuilder strbuf = new StringBuilder(bytes.length * 2);
054: for (byte element : bytes) {
055: if ((element & 0xff) < 0x10) {
056: strbuf.append("0");
057: }
058: strbuf.append(Long.toString(element & 0xff, 16));
059: }
060:
061: return strbuf.toString();
062: }
063:
064: /**
065: * Transform a string of hexadecimal digits to a bytearray.
066: * @param r The string to transform
067: * @return an array of bytes
068: * @throws IllegalArgumentException whenever the input string is not correctly formatted.
069: */
070: public byte[] transformBack(String r) {
071: try {
072: int strlen = r.length();
073: byte[] retval = new byte[strlen / 2];
074: for (int i = 0; i < strlen; i += 2) {
075: char c1 = r.charAt(i);
076: char c2 = r.charAt(i + 1);
077: int b = 0;
078: if (c1 >= '0' && c1 <= '9') {
079: b += 16 * (c1 - '0');
080: } else {
081: b += 16 * (10 + c1 - 'a');
082: }
083: if (c2 >= '0' && c2 <= '9') {
084: b += (c2 - '0');
085: } else {
086: b += (10 + c2 - 'a');
087: }
088: retval[i / 2] = (byte) b;
089: }
090: return retval;
091: } catch (Exception e) {
092: e.printStackTrace();
093: throw new IllegalArgumentException(
094: "the entered string to decode properly was wrong: "
095: + e);
096: }
097: }
098:
099: public String getEncoding() {
100: return ENCODING;
101: }
102: }
|