001/* 002 * Licensed to the Apache Software Foundation (ASF) under one 003 * or more contributor license agreements. See the NOTICE file 004 * distributed with this work for additional information 005 * regarding copyright ownership. The ASF licenses this file 006 * to you under the Apache License, Version 2.0 (the 007 * "License"); you may not use this file except in compliance 008 * with the License. You may obtain a copy of the License at 009 * 010 * http://www.apache.org/licenses/LICENSE-2.0 011 * 012 * Unless required by applicable law or agreed to in writing, 013 * software distributed under the License is distributed on an 014 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 015 * KIND, either express or implied. See the License for the 016 * specific language governing permissions and limitations 017 * under the License. 018 */ 019 020package org.apache.isis.core.commons.encoding; 021 022import java.io.ByteArrayInputStream; 023import java.io.ByteArrayOutputStream; 024import java.io.IOException; 025 026import org.apache.commons.codec.DecoderException; 027import org.apache.commons.codec.binary.Hex; 028 029import org.apache.isis.core.commons.exceptions.IsisException; 030 031public final class HexUtils { 032 033 private HexUtils() { 034 } 035 036 public static String encoded(final Object object) { 037 final ByteArrayOutputStream baos = new ByteArrayOutputStream(); 038 final DataOutputStreamExtended outputImpl = new DataOutputStreamExtended(baos); 039 try { 040 outputImpl.writeEncodable(object); 041 final byte[] byteArray = baos.toByteArray(); 042 return new String(Hex.encodeHex(byteArray)); 043 } catch (final IOException e) { 044 throw new IsisException("Failed to write object", e); 045 } 046 } 047 048 public static <T> T decoded(final String hexEncoded, Class<T> cls) { 049 final char[] chars = hexEncoded.toCharArray(); 050 byte[] bytes; 051 try { 052 bytes = Hex.decodeHex(chars); 053 final ByteArrayInputStream bais = new ByteArrayInputStream(bytes); 054 final DataInputStreamExtended inputImpl = new DataInputStreamExtended(bais); 055 return inputImpl.readEncodable(cls); 056 } catch (final IOException ex) { 057 throw new IsisException("Failed to read object", ex); 058 } catch (final DecoderException ex) { 059 throw new IsisException("Failed to hex decode object", ex); 060 } 061 } 062 063}