View Javadoc
1   /*
2    * Copyright (C) 2014 Christian Halstrick <christian.halstrick@sap.com> and others
3    *
4    * This program and the accompanying materials are made available under the
5    * terms of the Eclipse Distribution License v. 1.0 which is available at
6    * https://www.eclipse.org/org/documents/edl-v10.php.
7    *
8    * SPDX-License-Identifier: BSD-3-Clause
9    */
10  package org.eclipse.jgit.transport.http.apache;
11  
12  import java.io.IOException;
13  import java.io.InputStream;
14  import java.io.OutputStream;
15  
16  import org.apache.http.entity.AbstractHttpEntity;
17  import org.eclipse.jgit.util.TemporaryBuffer;
18  
19  /**
20   * A {@link org.apache.http.HttpEntity} which takes its content from a
21   * {@link org.eclipse.jgit.util.TemporaryBuffer}
22   *
23   * @since 3.3
24   */
25  public class TemporaryBufferEntity extends AbstractHttpEntity
26  		implements AutoCloseable {
27  	private TemporaryBuffer buffer;
28  
29  	private Integer contentLength;
30  
31  	/**
32  	 * Construct a new {@link org.apache.http.HttpEntity} which will contain the
33  	 * content stored in the specified buffer
34  	 *
35  	 * @param buffer
36  	 */
37  	public TemporaryBufferEntity(TemporaryBuffer buffer) {
38  		this.buffer = buffer;
39  	}
40  
41  	/**
42  	 * Get the <code>buffer</code> containing the content
43  	 *
44  	 * @return buffer containing the content
45  	 */
46  	public TemporaryBuffer getBuffer() {
47  		return buffer;
48  	}
49  
50  	/** {@inheritDoc} */
51  	@Override
52  	public boolean isRepeatable() {
53  		return true;
54  	}
55  
56  	/** {@inheritDoc} */
57  	@Override
58  	public long getContentLength() {
59  		if (contentLength != null)
60  			return contentLength.intValue();
61  		return buffer.length();
62  	}
63  
64  	/** {@inheritDoc} */
65  	@Override
66  	public InputStream getContent() throws IOException, IllegalStateException {
67  		return buffer.openInputStream();
68  	}
69  
70  	/** {@inheritDoc} */
71  	@Override
72  	public void writeTo(OutputStream outstream) throws IOException {
73  		// TODO: dont we need a progressmonitor
74  		buffer.writeTo(outstream, null);
75  	}
76  
77  	/** {@inheritDoc} */
78  	@Override
79  	public boolean isStreaming() {
80  		return false;
81  	}
82  
83  	/**
84  	 * Set the <code>contentLength</code>
85  	 *
86  	 * @param contentLength
87  	 */
88  	public void setContentLength(int contentLength) {
89  		this.contentLength = Integer.valueOf(contentLength);
90  	}
91  
92  	/**
93  	 * {@inheritDoc}
94  	 *
95  	 * Close destroys the associated buffer used to buffer the entity
96  	 * @since 4.5
97  	 */
98  	@Override
99  	public void close() {
100 		if (buffer != null) {
101 			buffer.destroy();
102 		}
103 	}
104 }