View Javadoc
1   /*
2    * Copyright (C) 2015, Matthias Sohn <matthias.sohn@sap.com>
3    * and other copyright owners as documented in the project's IP log.
4    *
5    * This program and the accompanying materials are made available
6    * under the terms of the Eclipse Distribution License v1.0 which
7    * accompanies this distribution, is reproduced below, and is
8    * available at http://www.eclipse.org/org/documents/edl-v10.php
9    *
10   * All rights reserved.
11   *
12   * Redistribution and use in source and binary forms, with or
13   * without modification, are permitted provided that the following
14   * conditions are met:
15   *
16   * - Redistributions of source code must retain the above copyright
17   *   notice, this list of conditions and the following disclaimer.
18   *
19   * - Redistributions in binary form must reproduce the above
20   *   copyright notice, this list of conditions and the following
21   *   disclaimer in the documentation and/or other materials provided
22   *   with the distribution.
23   *
24   * - Neither the name of the Eclipse Foundation, Inc. nor the
25   *   names of its contributors may be used to endorse or promote
26   *   products derived from this software without specific prior
27   *   written permission.
28   *
29   * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
30   * CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
31   * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
32   * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
33   * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
34   * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
35   * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
36   * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
37   * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
38   * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
39   * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
40   * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
41   * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
42   */
43  package org.eclipse.jgit.lfs.server.fs;
44  
45  import java.io.IOException;
46  import java.io.PrintWriter;
47  import java.text.MessageFormat;
48  
49  import javax.servlet.AsyncContext;
50  import javax.servlet.ServletException;
51  import javax.servlet.annotation.WebServlet;
52  import javax.servlet.http.HttpServlet;
53  import javax.servlet.http.HttpServletRequest;
54  import javax.servlet.http.HttpServletResponse;
55  
56  import org.apache.http.HttpStatus;
57  import org.eclipse.jgit.lfs.errors.InvalidLongObjectIdException;
58  import org.eclipse.jgit.lfs.lib.AnyLongObjectId;
59  import org.eclipse.jgit.lfs.lib.Constants;
60  import org.eclipse.jgit.lfs.lib.LongObjectId;
61  import org.eclipse.jgit.lfs.server.internal.LfsServerText;
62  
63  import com.google.gson.FieldNamingPolicy;
64  import com.google.gson.Gson;
65  import com.google.gson.GsonBuilder;
66  
67  /**
68   * Servlet supporting upload and download of large objects as defined by the
69   * GitHub Large File Storage extension API extending git to allow separate
70   * storage of large files
71   * (https://github.com/github/git-lfs/tree/master/docs/api).
72   *
73   * @since 4.3
74   */
75  @WebServlet(asyncSupported = true)
76  public class FileLfsServlet extends HttpServlet {
77  
78  	private static final long serialVersionUID = 1L;
79  
80  	private final FileLfsRepository repository;
81  
82  	private final long timeout;
83  
84  	private static Gson gson = createGson();
85  
86  	/**
87  	 * @param repository
88  	 *            the repository storing the large objects
89  	 * @param timeout
90  	 *            timeout for object upload / download in milliseconds
91  	 */
92  	public FileLfsServlet(FileLfsRepository repository, long timeout) {
93  		this.repository = repository;
94  		this.timeout = timeout;
95  	}
96  
97  	/**
98  	 * Handles object downloads
99  	 *
100 	 * @param req
101 	 *            servlet request
102 	 * @param rsp
103 	 *            servlet response
104 	 * @throws ServletException
105 	 *             if a servlet-specific error occurs
106 	 * @throws IOException
107 	 *             if an I/O error occurs
108 	 */
109 	@Override
110 	protected void doGet(HttpServletRequest req,
111 			HttpServletResponse rsp) throws ServletException, IOException {
112 		AnyLongObjectId obj = getObjectToTransfer(req, rsp);
113 		if (obj != null) {
114 			if (repository.getSize(obj) == -1) {
115 				sendError(rsp, HttpStatus.SC_NOT_FOUND, MessageFormat
116 						.format(LfsServerText.get().objectNotFound,
117 								obj.getName()));
118 				return;
119 			}
120 			AsyncContext context = req.startAsync();
121 			context.setTimeout(timeout);
122 			rsp.getOutputStream()
123 					.setWriteListener(new ObjectDownloadListener(repository,
124 							context, rsp, obj));
125 		}
126 	}
127 
128 	/**
129 	 * Retrieve object id from request
130 	 *
131 	 * @param req
132 	 *            servlet request
133 	 * @param rsp
134 	 *            servlet response
135 	 * @return object id, or <code>null</code> if the object id could not be
136 	 *         retrieved
137 	 * @throws IOException
138 	 *             if an I/O error occurs
139          * @since 4.6
140 	 */
141 	protected AnyLongObjectId getObjectToTransfer(HttpServletRequest req,
142 			HttpServletResponse rsp) throws IOException {
143 		String info = req.getPathInfo();
144 		int length = 1 + Constants.LONG_OBJECT_ID_STRING_LENGTH;
145 		if (info.length() != length) {
146 			sendError(rsp, HttpStatus.SC_UNPROCESSABLE_ENTITY, MessageFormat
147 					.format(LfsServerText.get().invalidPathInfo, info));
148 			return null;
149 		}
150 		try {
151 			return LongObjectId.fromString(info.substring(1, length));
152 		} catch (InvalidLongObjectIdException e) {
153 			sendError(rsp, HttpStatus.SC_UNPROCESSABLE_ENTITY, e.getMessage());
154 			return null;
155 		}
156 	}
157 
158 	/**
159 	 * Handle object uploads
160 	 *
161 	 * @param req
162 	 *            servlet request
163 	 * @param rsp
164 	 *            servlet response
165 	 * @throws ServletException
166 	 *             if a servlet-specific error occurs
167 	 * @throws IOException
168 	 *             if an I/O error occurs
169 	 */
170 	@Override
171 	protected void doPut(HttpServletRequest req,
172 			HttpServletResponse rsp) throws ServletException, IOException {
173 		AnyLongObjectId id = getObjectToTransfer(req, rsp);
174 		if (id != null) {
175 			AsyncContext context = req.startAsync();
176 			context.setTimeout(timeout);
177 			req.getInputStream().setReadListener(new ObjectUploadListener(
178 					repository, context, req, rsp, id));
179 		}
180 	}
181 
182 	static class Error {
183 		String message;
184 
185 		Error(String m) {
186 			this.message = m;
187 		}
188 	}
189 
190 	/**
191 	 * Send an error response.
192 	 *
193 	 * @param rsp
194 	 *            the servlet response
195 	 * @param status
196 	 *            HTTP status code
197 	 * @param message
198 	 *            error message
199 	 * @throws IOException
200 	 *             on failure to send the response
201 	 * @since 4.6
202 	 */
203 	protected static void sendError(HttpServletResponse rsp, int status, String message)
204 			throws IOException {
205 		rsp.setStatus(status);
206 		PrintWriter writer = rsp.getWriter();
207 		gson.toJson(new Error(message), writer);
208 		writer.flush();
209 		writer.close();
210 		rsp.flushBuffer();
211 	}
212 
213 	private static Gson createGson() {
214 		GsonBuilder gb = new GsonBuilder()
215 				.setFieldNamingPolicy(
216 						FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES)
217 				.setPrettyPrinting().disableHtmlEscaping();
218 		return gb.create();
219 	}
220 }