Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Support for download files as zip archive #807

Merged
merged 5 commits into from
Sep 23, 2014
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,8 @@
import java.io.File;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.nio.file.Path;
import java.util.List;

import javax.enterprise.inject.Vetoed;

Expand Down Expand Up @@ -73,6 +75,23 @@ public static ByteArrayDownloadBuilder of(byte[] input) {
return new ByteArrayDownloadBuilder(input);
}

/**
* Creates an instance for build a {@link ZipDownload}.<br>
*
* <code>
* List<Path> listOfFiles = [...];
* Download download = DownloadBuilder.of(listOfFiles)
* .withFileName("resume.zip")
* .build();
* </code>
*
* @param files List of input files
* @throws NullPointerException If the {@code input} argument is {@code null}
*/
public static ZipDownloadBuilder of(List<Path> files) {
return new ZipDownloadBuilder(files);
}

static abstract class AbstractDownloadBuilder<T> {
protected String fileName;
protected String contentType;
Expand Down Expand Up @@ -136,4 +155,16 @@ public ByteArrayDownload build() {
return new ByteArrayDownload(buff, contentType, fileName, doDownload);
}
}
}

public static class ZipDownloadBuilder extends AbstractDownloadBuilder<ZipDownloadBuilder> {
private final List<Path> files;

ZipDownloadBuilder(List<Path> files) {
this.files = requireNonNull(files, "files can't be null");
}

public ZipDownload build() {
return new ZipDownload(fileName, files);
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
package br.com.caelum.vraptor.observer.download;

import static java.nio.file.Files.copy;
import static java.util.Arrays.asList;

import java.io.IOException;
import java.nio.file.Path;
import java.util.zip.CRC32;
import java.util.zip.CheckedOutputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

import javax.servlet.http.HttpServletResponse;

/**
* Supports multiple files download as a zip file.
*
* @author Otávio Scherer Garcia
* @since 4.1
*/
public class ZipDownload implements Download {

private final String filename;
private final Iterable<Path> files;

public ZipDownload(String filename, Iterable<Path> files) {
this.filename = filename;
this.files = files;
}

public ZipDownload(String filename, Path... files) {
this(filename, asList(files));
}

@Override
public void write(HttpServletResponse response)
throws IOException {
response.setHeader("Content-disposition", "attachment; filename=" + filename);
response.setHeader("Content-type", "application/zip");

CheckedOutputStream stream = new CheckedOutputStream(response.getOutputStream(), new CRC32());
try (ZipOutputStream zip = new ZipOutputStream(stream)) {
for (Path file : files) {
zip.putNextEntry(new ZipEntry(file.getFileName().toString()));
copy(file, zip);
zip.closeEntry();
}
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,6 @@
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;

Expand Down Expand Up @@ -50,9 +49,9 @@ public void setUp() throws Exception {
MockitoAnnotations.initMocks(this);

bytes = new byte[] { (byte) 0x0 };
this.outputStream = new ByteArrayOutputStream();
outputStream = new ByteArrayOutputStream();

this.socketStream = new ServletOutputStream() {
socketStream = new ServletOutputStream() {
@Override
public void write(int b) throws IOException {
outputStream.write(b);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -23,8 +23,8 @@
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.file.Files;

import javax.servlet.ServletOutputStream;
import javax.servlet.WriteListener;
Expand Down Expand Up @@ -56,15 +56,12 @@ public class FileDownloadTest {
public void setUp() throws Exception {
MockitoAnnotations.initMocks(this);

bytes = new byte[] { (byte) 0 };
bytes = new byte[] { (byte) 0x0 };
outputStream = new ByteArrayOutputStream();

file = folder.newFile();
Files.write(file.toPath(), bytes);

try (FileOutputStream fileStream = new FileOutputStream(file)) {
fileStream.write(bytes);
}

socketStream = new ServletOutputStream() {
@Override
public void write(int b) throws IOException {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -52,11 +52,11 @@ public class InputStreamDownloadTest {
public void setUp() throws Exception {
MockitoAnnotations.initMocks(this);

bytes = new byte[] { (byte) 0 };
this.inputStream = new ByteArrayInputStream(bytes);
this.outputStream = new ByteArrayOutputStream();
bytes = new byte[] { (byte) 0x0 };
inputStream = new ByteArrayInputStream(bytes);
outputStream = new ByteArrayOutputStream();

this.socketStream = new ServletOutputStream() {
socketStream = new ServletOutputStream() {
@Override
public void write(int b) throws IOException {
outputStream.write(b);
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,78 @@
/***
* Copyright (c) 2009 Caelum - www.caelum.com.br/opensource All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package br.com.caelum.vraptor.observer.download;

import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;

import java.io.IOException;
import java.nio.file.NoSuchFileException;
import java.nio.file.Path;
import java.nio.file.Paths;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;

import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.junit.rules.TemporaryFolder;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;

public class ZipDownloadTest {

@Rule
public ExpectedException thrown = ExpectedException.none();

@Rule
public TemporaryFolder folder = new TemporaryFolder();

private Path inpuFile0;
private Path inpuFile1;

private @Mock HttpServletResponse response;
private @Mock ServletOutputStream socketStream;

@Before
public void setUp() throws Exception {
MockitoAnnotations.initMocks(this);

inpuFile0 = folder.newFile().toPath();
inpuFile1 = folder.newFile().toPath();

when(response.getOutputStream()).thenReturn(socketStream);
}

@Test
public void builderShouldThrowsExceptionIfFileDoesntExists() throws Exception {
thrown.expect(NoSuchFileException.class);

Download download = new ZipDownload("file.zip", Paths.get("/path/that/doesnt/exists/picture.jpg"));
download.write(response);
}

@Test
public void shouldUseHeadersToHttpResponse() throws IOException {
Download fd = new ZipDownload("download.zip", inpuFile0, inpuFile1);
fd.write(response);

verify(response, times(1)).setHeader("Content-type", "application/zip");
verify(response, times(1)).setHeader("Content-disposition", "attachment; filename=download.zip");
}
}
12 changes: 12 additions & 0 deletions vraptor-site/content/en/docs/download-and-upload.html
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,18 @@
}
~~~

You can also put a list of files to download, so will sent to the browser compressed as Zip archive.

~~~
#!java
public Download pictures() {
Path pic01 = new File("/path/to/the/pic01.jpg").toPath();
Path pic02 = new File("/path/to/the/pic02.jpg").toPath();
return new ZipDownload("pics.zip", pic01, pic02);
}
~~~


##Using DownloadBuilder

`DownloadBuilder` is a class to help you to create instances for `Download`, using a fluent interface. To create a `FileDownload` you can write this code:
Expand Down
15 changes: 14 additions & 1 deletion vraptor-site/content/pt/docs/download-e-upload.html
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@
@Controller
public class PerfilController {
public Download foto(Perfil perfil) {
File file = new File("/path/para/a/foto." + perfil.getId()+ ".jpg");
File file = new File("/caminho/para/a/foto." + perfil.getId()+ ".jpg");
String contentType = "image/jpg";
String filename = perfil.getNome() + ".jpg";

Expand Down Expand Up @@ -60,6 +60,19 @@
}
~~~

Você também pode enviar uma lista de arquivos para download, e desta forma eles serão enviados ao browser
comprimidos em um arquivo Zip.

~~~
#!java
public Download fotos() {
Path foto01 = new File("/caminho/para/a/foto01.jpg").toPath();
Path foto02 = new File("/caminho/para/a/foto02.jpg").toPath();
return new ZipDownload("fotos.zip", foto01, foto02);
}
~~~


##Using DownloadBuilder

`DownloadBuilder` é uma classe útil para ajudar você a criar instâncias da classe `Download`, usando uma interface fluente. Para criar uma instância de um `FileDownload` você pode escrever o seguinte código:
Expand Down