package com.google.sps.tasks;

import com.google.appengine.tools.cloudstorage.GcsFileOptions;
import com.google.appengine.tools.cloudstorage.GcsFilename;
import com.google.appengine.tools.cloudstorage.GcsOutputChannel;
import com.google.appengine.tools.cloudstorage.GcsService;
import com.google.appengine.tools.cloudstorage.GcsServiceFactory;
import com.google.sps.workspace.Workspace;
import com.google.sps.workspace.WorkspaceFactory;
import java.io.IOException;
import java.nio.channels.Channels;
import java.util.concurrent.ExecutionException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet("/tasks/prepareDownload")
public class PrepareDownload extends HttpServlet {
  WorkspaceFactory workspaceFactory = WorkspaceFactory.getInstance();

  @Override
  protected void doPost(HttpServletRequest req, HttpServletResponse resp)
      throws ServletException, IOException {
    String body = req.getReader().lines().reduce("", (accumulator, actual) -> accumulator + actual);

    String args[] = body.split(",");
    String workspaceID = args[0];
    String downloadID = args[1];

    Workspace w = workspaceFactory.fromWorkspaceID(workspaceID);

    GcsService instance = GcsServiceFactory.createGcsService();
    GcsFileOptions options = GcsFileOptions.getDefaultInstance();
    GcsFilename filename =
        new GcsFilename("fulfillment-deco-step-2020.appspot.com", workspaceID + '/' + downloadID);
    GcsOutputChannel outputChannel = instance.createOrReplace(filename, options);

    try {
      w.getArchive().archive(Channels.newOutputStream(outputChannel));

      w.updateDownloadName(downloadID, filename.getObjectName());
    } catch (InterruptedException | ExecutionException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
  }
}

@@ -848,16 +848,24 @@
 let %7B%0A  
+private 
 Workspac
@@ -893,42 +893,230 @@
 tory
- = WorkspaceFactory.getInstance();
+;%0A  private GcsService instance;%0A%0A  @Override%0A  public void init() throws ServletException %7B%0A    super.init();%0A    workspaceFactory = WorkspaceFactory.getInstance();%0A    instance = GcsServiceFactory.createGcsService();%0A  %7D
 %0A%0A  
@@ -1521,72 +1521,8 @@
 );%0A%0A
-    GcsService instance = GcsServiceFactory.createGcsService();%0A
     

Refactor for testability.