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.nio.file.*; 022 023import org.apache.juneau.http.*; 024import static org.apache.juneau.commons.utils.Shorts.*; 025 026/** 027 * A repeatable {@link HttpBody} that streams content from a {@link File}. 028 * 029 * <p> 030 * {@link #getContentLength()} returns the file size, allowing transports to set {@code Content-Length}. 031 * 032 * @since 9.2.1 033 */ 034public final class FileBody implements HttpBody { 035 036 private final File file; 037 private final String contentType; 038 039 private FileBody(File file, String contentType) { 040 this.file = reqnn("file", file); 041 this.contentType = contentType; 042 } 043 044 /** 045 * Creates a {@link FileBody} with {@code application/octet-stream} content type. 046 * 047 * @param file The file. Must not be <jk>null</jk>. 048 * @return A new instance. Never <jk>null</jk>. 049 */ 050 public static FileBody of(File file) { 051 return new FileBody(file, "application/octet-stream"); 052 } 053 054 /** 055 * Creates a {@link FileBody} with the given content type. 056 * 057 * @param file The file. Must not be <jk>null</jk>. 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 FileBody of(File file, String contentType) { 062 return new FileBody(file, contentType); 063 } 064 065 /** 066 * Returns the underlying file. 067 * 068 * @return The file. Never <jk>null</jk>. 069 */ 070 public File getFile() { 071 return file; 072 } 073 074 @Override /* HttpBody */ 075 public String getContentType() { 076 return contentType; 077 } 078 079 @Override /* HttpBody */ 080 public long getContentLength() { 081 return file.length(); 082 } 083 084 @Override /* HttpBody */ 085 public void writeTo(OutputStream out) throws IOException { 086 Files.copy(file.toPath(), out); 087 } 088 089 @Override /* HttpBody */ 090 public boolean isRepeatable() { 091 return true; 092 } 093}