001/* 002 * Licensed to the Apache Software Foundation (ASF) under one or more 003 * contributor license agreements. See the NOTICE file distributed with 004 * this work for additional information regarding copyright ownership. 005 * The ASF licenses this file to You under the Apache License, Version 2.0 006 * (the "License"); you may not use this file except in compliance with 007 * the License. You may obtain a copy of the License at 008 * 009 * http://www.apache.org/licenses/LICENSE-2.0 010 * 011 * Unless required by applicable law or agreed to in writing, software 012 * distributed under the License is distributed on an "AS IS" BASIS, 013 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 014 * See the License for the specific language governing permissions and 015 * limitations under the License. 016 */ 017package org.apache.juneau.http.entity; 018 019 020import java.io.*; 021import java.util.*; 022 023import org.apache.juneau.http.*; 024import static org.apache.juneau.commons.utils.Shorts.*; 025 026/** 027 * An {@link HttpBody} backed by a raw byte array. 028 * 029 * <p> 030 * Repeatable: the same instance may be written multiple times. 031 * 032 * @since 9.2.1 033 */ 034public final class ByteArrayBody implements HttpBody { 035 036 private final byte[] content; 037 private final String contentType; 038 039 private ByteArrayBody(byte[] content, String contentType) { 040 this.content = Arrays.copyOf(reqnn("content", content), content.length); 041 this.contentType = contentType; 042 } 043 044 /** 045 * Creates a {@link ByteArrayBody} with {@code application/octet-stream} content type. 046 * 047 * @param content The byte array. Must not be <jk>null</jk>. The array is defensively copied. 048 * @return A new instance. Never <jk>null</jk>. 049 */ 050 public static ByteArrayBody of(byte[] content) { 051 return new ByteArrayBody(content, "application/octet-stream"); 052 } 053 054 /** 055 * Creates a {@link ByteArrayBody} with the given content type. 056 * 057 * @param content The byte array. Must not be <jk>null</jk>. The array is defensively copied. 058 * @param contentType The MIME content type. May be <jk>null</jk>. 059 * @return A new instance. Never <jk>null</jk>. 060 */ 061 public static ByteArrayBody of(byte[] content, String contentType) { 062 return new ByteArrayBody(content, contentType); 063 } 064 065 @Override /* HttpBody */ 066 public String getContentType() { 067 return contentType; 068 } 069 070 @Override /* HttpBody */ 071 public long getContentLength() { 072 return content.length; 073 } 074 075 @Override /* HttpBody */ 076 public void writeTo(OutputStream out) throws IOException { 077 out.write(content); 078 } 079 080 @Override /* HttpBody */ 081 public boolean isRepeatable() { 082 return true; 083 } 084}