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.shiro.lang.util;
021
022import java.io.Closeable;
023import java.io.IOException;
024
025/**
026 * To use try-with-resources idiom, this class supports wrapping existing ByteSource
027 * object or byte array. At end of try block, it gets zeroed out automatically.
028 */
029public final class ByteSourceWrapper implements Closeable {
030    private final byte[] bytes;
031
032    private ByteSourceWrapper(byte[] bytes) {
033        this.bytes = bytes;
034    }
035
036    /**
037     * This method generically accepts byte array or ByteSource instance.
038     */
039    public static ByteSourceWrapper wrap(Object value) {
040        if (value instanceof byte[]) {
041            byte[] bytes = (byte[]) value;
042            return new ByteSourceWrapper(bytes);
043        } else if (value instanceof ByteSource) {
044            byte[] bytes = ((ByteSource) value).getBytes();
045            return new ByteSourceWrapper(bytes);
046        }
047        throw new IllegalArgumentException();
048    }
049
050    public byte[] getBytes() {
051        return bytes;
052    }
053
054    public void close() throws IOException {
055        ByteUtils.wipe(bytes);
056    }
057}