001/* 002 * Licensed to DuraSpace under one or more contributor license agreements. 003 * See the NOTICE file distributed with this work for additional information 004 * regarding copyright ownership. 005 * 006 * DuraSpace licenses this file to you under the Apache License, 007 * Version 2.0 (the "License"); you may not use this file except in 008 * compliance 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, software 013 * distributed under the License is distributed on an "AS IS" BASIS, 014 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 015 * See the License for the specific language governing permissions and 016 * limitations under the License. 017 */ 018package org.fcrepo.kernel.api.utils; 019 020import static org.apache.commons.codec.binary.Hex.encodeHexString; 021import static org.slf4j.LoggerFactory.getLogger; 022 023import java.net.URI; 024import java.net.URISyntaxException; 025 026import org.fcrepo.config.DigestAlgorithm; 027import org.fcrepo.kernel.api.exception.RepositoryRuntimeException; 028import org.slf4j.Logger; 029 030/** 031 * Digest helpers to convert digests (checksums) into URI strings 032 * (based loosely on Magnet URIs) 033 * @author Chris Beer 034 * @since Mar 6, 2013 035 */ 036public final class ContentDigest { 037 038 private static final Logger LOGGER = getLogger(ContentDigest.class); 039 040 private ContentDigest() { 041 } 042 043 /** 044 * Convert a MessageDigest algorithm and checksum value to a URN 045 * @param algorithm the message digest algorithm 046 * @param value the checksum value 047 * @return URI 048 */ 049 public static URI asURI(final String algorithm, final String value) { 050 try { 051 final String scheme = DigestAlgorithm.getScheme(algorithm); 052 053 return new URI(scheme, value, null); 054 } catch (final URISyntaxException unlikelyException) { 055 LOGGER.warn("Exception creating checksum URI: alg={}; value={}", 056 algorithm, value); 057 throw new RepositoryRuntimeException(unlikelyException.getMessage(), unlikelyException); 058 } 059 } 060 061 /** 062 * Convert a MessageDigest algorithm and checksum byte-array data to a URN 063 * @param algorithm the message digest algorithm 064 * @param data the checksum byte-array data 065 * @return URI 066 */ 067 public static URI asURI(final String algorithm, final byte[] data) { 068 return asURI(algorithm, asString(data)); 069 } 070 071 /** 072 * Given a digest URI, get the corresponding MessageDigest algorithm 073 * @param digestUri the digest uri 074 * @return MessageDigest algorithm 075 */ 076 public static String getAlgorithm(final URI digestUri) { 077 return DigestAlgorithm.fromScheme(digestUri.getScheme() + ":" + 078 digestUri.getSchemeSpecificPart().split(":", 2)[0]).getAlgorithm(); 079 } 080 081 private static String asString(final byte[] data) { 082 return encodeHexString(data); 083 } 084 085}