You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

LfsServerTest.java 8.9KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269
  1. /*
  2. * Copyright (C) 2015, Matthias Sohn <matthias.sohnk@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. import static java.nio.charset.StandardCharsets.UTF_8;
  45. import static org.junit.Assert.assertEquals;
  46. import java.io.BufferedInputStream;
  47. import java.io.FileNotFoundException;
  48. import java.io.IOException;
  49. import java.io.InputStream;
  50. import java.nio.ByteBuffer;
  51. import java.nio.channels.Channels;
  52. import java.nio.channels.FileChannel;
  53. import java.nio.channels.ReadableByteChannel;
  54. import java.nio.file.Files;
  55. import java.nio.file.Path;
  56. import java.nio.file.Paths;
  57. import java.nio.file.StandardOpenOption;
  58. import java.security.DigestInputStream;
  59. import java.security.SecureRandom;
  60. import org.apache.http.HttpEntity;
  61. import org.apache.http.HttpResponse;
  62. import org.apache.http.StatusLine;
  63. import org.apache.http.client.ClientProtocolException;
  64. import org.apache.http.client.methods.CloseableHttpResponse;
  65. import org.apache.http.client.methods.HttpGet;
  66. import org.apache.http.client.methods.HttpPut;
  67. import org.apache.http.entity.ContentType;
  68. import org.apache.http.entity.InputStreamEntity;
  69. import org.apache.http.entity.StringEntity;
  70. import org.apache.http.impl.client.CloseableHttpClient;
  71. import org.apache.http.impl.client.HttpClientBuilder;
  72. import org.eclipse.jetty.servlet.ServletContextHandler;
  73. import org.eclipse.jetty.servlet.ServletHolder;
  74. import org.eclipse.jgit.junit.http.AppServer;
  75. import org.eclipse.jgit.lfs.lib.AnyLongObjectId;
  76. import org.eclipse.jgit.lfs.lib.Constants;
  77. import org.eclipse.jgit.lfs.lib.LongObjectId;
  78. import org.eclipse.jgit.lfs.test.LongObjectIdTestUtils;
  79. import org.eclipse.jgit.util.FileUtils;
  80. import org.eclipse.jgit.util.IO;
  81. import org.junit.After;
  82. import org.junit.Before;
  83. @SuppressWarnings("restriction")
  84. public abstract class LfsServerTest {
  85. private static final long timeout = /* 10 sec */ 10 * 1000;
  86. protected static final int MiB = 1024 * 1024;
  87. /** In-memory application server; subclass must start. */
  88. protected AppServer server;
  89. private Path tmp;
  90. private Path dir;
  91. protected FileLfsRepository repository;
  92. protected FileLfsServlet servlet;
  93. public LfsServerTest() {
  94. super();
  95. }
  96. public Path getTempDirectory() {
  97. return tmp;
  98. }
  99. public Path getDir() {
  100. return dir;
  101. }
  102. @Before
  103. public void setup() throws Exception {
  104. tmp = Files.createTempDirectory("jgit_test_");
  105. server = new AppServer();
  106. ServletContextHandler app = server.addContext("/lfs");
  107. dir = Paths.get(tmp.toString(), "lfs");
  108. this.repository = new FileLfsRepository(null, dir);
  109. servlet = new FileLfsServlet(repository, timeout);
  110. app.addServlet(new ServletHolder(servlet), "/objects/*");
  111. server.setUp();
  112. }
  113. @After
  114. public void tearDown() throws Exception {
  115. server.tearDown();
  116. FileUtils.delete(tmp.toFile(), FileUtils.RECURSIVE | FileUtils.RETRY);
  117. }
  118. protected AnyLongObjectId putContent(String s)
  119. throws IOException, ClientProtocolException {
  120. AnyLongObjectId id = LongObjectIdTestUtils.hash(s);
  121. return putContent(id, s);
  122. }
  123. protected AnyLongObjectId putContent(AnyLongObjectId id, String s)
  124. throws ClientProtocolException, IOException {
  125. try (CloseableHttpClient client = HttpClientBuilder.create().build()) {
  126. HttpEntity entity = new StringEntity(s,
  127. ContentType.APPLICATION_OCTET_STREAM);
  128. String hexId = id.name();
  129. HttpPut request = new HttpPut(
  130. server.getURI() + "/lfs/objects/" + hexId);
  131. request.setEntity(entity);
  132. try (CloseableHttpResponse response = client.execute(request)) {
  133. StatusLine statusLine = response.getStatusLine();
  134. int status = statusLine.getStatusCode();
  135. if (status >= 400) {
  136. throw new RuntimeException("Status: " + status + ". "
  137. + statusLine.getReasonPhrase());
  138. }
  139. }
  140. return id;
  141. }
  142. }
  143. protected LongObjectId putContent(Path f)
  144. throws FileNotFoundException, IOException {
  145. try (CloseableHttpClient client = HttpClientBuilder.create().build()) {
  146. LongObjectId id1, id2;
  147. String hexId1, hexId2;
  148. try (DigestInputStream in = new DigestInputStream(
  149. new BufferedInputStream(Files.newInputStream(f)),
  150. Constants.newMessageDigest())) {
  151. InputStreamEntity entity = new InputStreamEntity(in,
  152. Files.size(f), ContentType.APPLICATION_OCTET_STREAM);
  153. id1 = LongObjectIdTestUtils.hash(f);
  154. hexId1 = id1.name();
  155. HttpPut request = new HttpPut(
  156. server.getURI() + "/lfs/objects/" + hexId1);
  157. request.setEntity(entity);
  158. HttpResponse response = client.execute(request);
  159. checkResponseStatus(response);
  160. id2 = LongObjectId.fromRaw(in.getMessageDigest().digest());
  161. hexId2 = id2.name();
  162. assertEquals(hexId1, hexId2);
  163. }
  164. return id1;
  165. }
  166. }
  167. private void checkResponseStatus(HttpResponse response) {
  168. StatusLine statusLine = response.getStatusLine();
  169. int status = statusLine.getStatusCode();
  170. if (statusLine.getStatusCode() >= 400) {
  171. String error;
  172. try {
  173. ByteBuffer buf = IO.readWholeStream(new BufferedInputStream(
  174. response.getEntity().getContent()), 1024);
  175. if (buf.hasArray()) {
  176. error = new String(buf.array(),
  177. buf.arrayOffset() + buf.position(), buf.remaining(),
  178. UTF_8);
  179. } else {
  180. final byte[] b = new byte[buf.remaining()];
  181. buf.duplicate().get(b);
  182. error = new String(b, UTF_8);
  183. }
  184. } catch (IOException e) {
  185. error = statusLine.getReasonPhrase();
  186. }
  187. throw new RuntimeException("Status: " + status + " " + error);
  188. }
  189. assertEquals(200, status);
  190. }
  191. protected long getContent(AnyLongObjectId id, Path f) throws IOException {
  192. String hexId = id.name();
  193. return getContent(hexId, f);
  194. }
  195. protected long getContent(String hexId, Path f) throws IOException {
  196. try (CloseableHttpClient client = HttpClientBuilder.create().build()) {
  197. HttpGet request = new HttpGet(
  198. server.getURI() + "/lfs/objects/" + hexId);
  199. HttpResponse response = client.execute(request);
  200. checkResponseStatus(response);
  201. HttpEntity entity = response.getEntity();
  202. long pos = 0;
  203. try (InputStream in = entity.getContent();
  204. ReadableByteChannel inChannel = Channels.newChannel(in);
  205. FileChannel outChannel = FileChannel.open(f,
  206. StandardOpenOption.CREATE_NEW,
  207. StandardOpenOption.WRITE)) {
  208. long transferred;
  209. do {
  210. transferred = outChannel.transferFrom(inChannel, pos, MiB);
  211. pos += transferred;
  212. } while (transferred > 0);
  213. }
  214. return pos;
  215. }
  216. }
  217. /**
  218. * Creates a file with random content, repeatedly writing a random string of
  219. * 4k length to the file until the file has at least the specified length.
  220. *
  221. * @param f
  222. * file to fill
  223. * @param size
  224. * size of the file to generate
  225. * @return length of the generated file in bytes
  226. * @throws IOException
  227. */
  228. protected long createPseudoRandomContentFile(Path f, long size)
  229. throws IOException {
  230. SecureRandom rnd = new SecureRandom();
  231. byte[] buf = new byte[4096];
  232. rnd.nextBytes(buf);
  233. ByteBuffer bytebuf = ByteBuffer.wrap(buf);
  234. try (FileChannel outChannel = FileChannel.open(f,
  235. StandardOpenOption.CREATE_NEW, StandardOpenOption.WRITE)) {
  236. long len = 0;
  237. do {
  238. len += outChannel.write(bytebuf);
  239. if (bytebuf.position() == 4096) {
  240. bytebuf.rewind();
  241. }
  242. } while (len < size);
  243. }
  244. return Files.size(f);
  245. }
  246. }