Example usage for javax.servlet.http HttpServletResponse SC_ACCEPTED

List of usage examples for javax.servlet.http HttpServletResponse SC_ACCEPTED

Introduction

In this page you can find the example usage for javax.servlet.http HttpServletResponse SC_ACCEPTED.

Prototype

int SC_ACCEPTED

To view the source code for javax.servlet.http HttpServletResponse SC_ACCEPTED.

Click Source Link

Document

Status code (202) indicating that a request was accepted for processing, but was not completed.

Usage

From source file:org.dasein.cloud.azure.tests.network.AzureIpAddressSupportTest.java

@Test
public void stopForwardToServerShouldPostCorrectRequestIfNoMatchEndpointFound()
        throws CloudException, InternalException {
    final AtomicInteger putCount = new AtomicInteger(0);
    new MockUp<CloseableHttpClient>() {
        @Mock(invocations = 2)/*w  ww.  ja v  a2 s  .c o  m*/
        public CloseableHttpResponse execute(Invocation inv, HttpUriRequest request) throws IOException {
            if (request.getMethod().equals("GET")) {
                DaseinObjectToXmlEntity<PersistentVMRoleModel> daseinEntity = new DaseinObjectToXmlEntity<PersistentVMRoleModel>(
                        createPersistentVMRoleModelWithEndpoint());
                assertGet(request, EXPECTED_URL,
                        new Header[] { new BasicHeader("x-ms-version", "2012-03-01") });
                return getHttpResponseMock(getStatusLineMock(HttpServletResponse.SC_OK), daseinEntity,
                        new Header[] { new BasicHeader("x-ms-request-id", UUID.randomUUID().toString()) });
            } else if (request.getMethod().equals("PUT")) {
                putCount.incrementAndGet();
                PersistentVMRoleModel persistentVMRoleModel = createPersistentVMRoleModelWithEndpoint();
                assertPut(request, EXPECTED_URL, new Header[] { new BasicHeader("x-ms-version", "2012-03-01") },
                        persistentVMRoleModel);
                return getHttpResponseMock(getStatusLineMock(HttpServletResponse.SC_ACCEPTED), null,
                        new Header[] { new BasicHeader("x-ms-request-id", UUID.randomUUID().toString()) });
            } else {
                throw new IOException("Request is not mocked");
            }
        }
    };
    String ruleId = new AzureRuleIdParts(VM_ID, Protocol.TCP.toString(), String.valueOf(PRIVATE_PORT + 1))
            .toProviderId();
    ipAddressSupport.stopForwardToServer(ruleId, VM_ID);
    assertEquals("PUT count doesn't match", 1, putCount.get());
}

From source file:gov.nist.appvet.servlet.AppVetServlet.java

@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) {

    AppVetServletCommand command = null;
    String commandStr = null;/*from  ww w .  j a v  a2 s  .  co  m*/
    String userName = null;
    String password = null;
    String sessionId = null;
    String toolId = null;
    String toolRisk = null;
    String appId = null;
    FileItem fileItem = null;
    String clientIpAddress = request.getRemoteAddr();
    FileItemFactory factory = null;
    ServletFileUpload upload = null;
    List<FileItem> items = null;
    Iterator<FileItem> iter = null;
    FileItem item = null;

    try {
        factory = new DiskFileItemFactory();
        upload = new ServletFileUpload(factory);
        items = upload.parseRequest(request);
        iter = items.iterator();
        String incomingParameter = null;
        String incomingValue = null;
        while (iter.hasNext()) {
            item = iter.next();
            if (item.isFormField()) {
                incomingParameter = item.getFieldName();
                incomingValue = item.getString();
                if (incomingParameter.equals("command")) {
                    commandStr = incomingValue;
                    log.debug("commandStr: " + commandStr);
                } else if (incomingParameter.equals("username")) {
                    userName = incomingValue;
                    log.debug("userName: " + userName);
                } else if (incomingParameter.equals("password")) {
                    password = incomingValue;
                    log.debug("password: " + password);
                } else if (incomingParameter.equals("sessionid")) {
                    sessionId = incomingValue;
                    log.debug("sessionId: " + sessionId);
                } else if (incomingParameter.equals("toolid")) {
                    toolId = incomingValue;
                    log.debug("toolid: " + toolId);
                } else if (incomingParameter.equals("toolrisk")) {
                    toolRisk = incomingValue;
                    log.debug("toolrisk: " + toolRisk);
                } else if (incomingParameter.equals("appid")) {
                    appId = incomingValue;
                    log.debug("appId: " + appId);
                } else {
                    log.warn("Received unknown parameter: " + incomingValue + " from IP: " + clientIpAddress);
                }
            } else {
                // item should now hold the received file
                fileItem = item;
            }
        }
        incomingParameter = null;
        incomingValue = null;

        //-------------------------- Authenticate --------------------------
        if (isAuthenticated(sessionId, userName, password, clientIpAddress, commandStr)) {
            if (sessionId != null) {
                userName = Database.getSessionUser(sessionId);
            }
        } else {
            sendHttpResponse(userName, appId, commandStr, clientIpAddress,
                    ErrorMessage.AUTHENTICATION_ERROR.getDescription(), response,
                    HttpServletResponse.SC_BAD_REQUEST, true);
            return;
        }

        //--------------------- Verify file attachment ---------------------
        if (fileItem == null) {
            sendHttpResponse(userName, appId, commandStr, clientIpAddress,
                    ErrorMessage.MISSING_FILE.getDescription(), response, HttpServletResponse.SC_BAD_REQUEST,
                    true);
            return;
        }
        if (!ValidateBase.isLegalFileName(fileItem.getName())) {
            sendHttpResponse(userName, appId, commandStr, clientIpAddress,
                    ErrorMessage.ILLEGAL_CHAR_IN_UPLOADED_FILENAME_ERROR.getDescription(), response,
                    HttpServletResponse.SC_BAD_REQUEST, true);
            return;
        }

        //------------------------- Handle command -------------------------
        AppInfo appInfo = null;
        command = AppVetServletCommand.valueOf(commandStr);
        switch (command) {
        case SUBMIT_APP:
            log.debug(userName + " invoked " + command.name() + " with file " + fileItem.getName());
            if (!ValidateBase.hasValidAppFileExtension(fileItem.getName())) {
                sendHttpResponse(userName, appId, commandStr, clientIpAddress,
                        ErrorMessage.INVALID_APP_FILE_EXTENSION.getDescription(), response,
                        HttpServletResponse.SC_BAD_REQUEST, true);
                return;
            } else {
                appInfo = createAppInfo(userName, sessionId, fileItem, clientIpAddress, request);
                if (appInfo == null)
                    return;
                else {
                    sendHttpResponse(userName, appInfo.appId, commandStr, clientIpAddress,
                            "HTTP/1.1 202 Accepted", response, HttpServletResponse.SC_ACCEPTED, false);
                    Registration registration = new Registration(appInfo);
                    registration.registerApp();
                }
            }
            break;
        case SUBMIT_REPORT:
            log.debug(userName + " invoked " + command.name() + " on app " + appId + " with report "
                    + fileItem.getName());
            if (!ValidateBase.hasValidReportFileExtension(fileItem.getName())) {
                sendHttpResponse(userName, appId, commandStr, clientIpAddress,
                        ErrorMessage.INVALID_REPORT_FILE_EXTENSION.getDescription(), response,
                        HttpServletResponse.SC_BAD_REQUEST, true);
                return;
            } else {
                sendHttpResponse(userName, appId, commandStr, clientIpAddress, "HTTP/1.1 202 Accepted",
                        response, HttpServletResponse.SC_ACCEPTED, false);
                appInfo = createAppInfo(appId, userName, commandStr, toolId, toolRisk, fileItem,
                        clientIpAddress, response);
                if (appInfo == null)
                    return;
                else
                    submitReport(userName, appInfo, response);
            }
            break;
        default:
            log.warn("Received unknown command: " + commandStr + " from IP: " + clientIpAddress);
        }
    } catch (final FileUploadException e) {
        sendHttpResponse(userName, appId, commandStr, clientIpAddress,
                ErrorMessage.FILE_UPLOAD_ERROR.getDescription(), response, HttpServletResponse.SC_BAD_REQUEST,
                true);
        return;
    } finally {
        command = null;
        commandStr = null;
        userName = null;
        password = null;
        sessionId = null;
        toolId = null;
        toolRisk = null;
        appId = null;
        fileItem = null;
        clientIpAddress = null;
        factory = null;
        upload = null;
        items = null;
        iter = null;
        item = null;
        System.gc();
    }
}

From source file:edu.stanford.epad.epadws.xnat.XNATDeletionOperations.java

private static boolean unexpectedDeletionStatusCode(int statusCode) {
    return !(statusCode == HttpServletResponse.SC_OK || statusCode == HttpServletResponse.SC_ACCEPTED);
}

From source file:edu.stanford.epad.epadws.xnat.XNATDeletionOperations.java

public static boolean successStatusCode(int statusCode) {
    return (statusCode == HttpServletResponse.SC_OK || statusCode == HttpServletResponse.SC_ACCEPTED);
}

From source file:com.imaginary.home.device.hue.HueMethod.java

public JSONObject post(@Nonnull String resource, JSONObject body) throws HueException {
    Logger std = Hue.getLogger(HueMethod.class);
    Logger wire = Hue.getWireLogger(HueMethod.class);

    if (std.isTraceEnabled()) {
        std.trace("enter - " + HueMethod.class.getName() + ".post(" + resource + ")");
    }/*from  ww w  .j  a va 2s .c  om*/
    if (wire.isDebugEnabled()) {
        wire.debug("");
        wire.debug(">>> [POST (" + (new Date()) + ")] -> " + hue.getAPIEndpoint() + resource);
    }
    try {
        HttpClient client = getClient();
        HttpPost method = new HttpPost(hue.getAPIEndpoint() + resource);

        method.addHeader("Content-Type", "application/json");

        try {
            if (body != null) {
                //noinspection deprecation
                method.setEntity(new StringEntity(body.toString(), "application/json", "UTF-8"));
            }
        } catch (UnsupportedEncodingException e) {
            throw new HueException(e);
        }
        if (wire.isDebugEnabled()) {
            wire.debug(method.getRequestLine().toString());
            for (Header header : method.getAllHeaders()) {
                wire.debug(header.getName() + ": " + header.getValue());
            }
            wire.debug("");
            if (body != null) {
                try {
                    wire.debug(EntityUtils.toString(method.getEntity()));
                } catch (IOException ignore) {
                }

                wire.debug("");
            }
        }
        HttpResponse response;
        StatusLine status;

        try {
            response = client.execute(method);
            status = response.getStatusLine();
        } catch (IOException e) {
            std.error("POST: Failed to execute HTTP request due to a cloud I/O error: " + e.getMessage());
            if (std.isTraceEnabled()) {
                e.printStackTrace();
            }
            throw new HueException(e);
        }
        if (std.isDebugEnabled()) {
            std.debug("POST: HTTP Status " + status);
        }
        Header[] headers = response.getAllHeaders();

        if (wire.isDebugEnabled()) {
            wire.debug(status.toString());
            for (Header h : headers) {
                if (h.getValue() != null) {
                    wire.debug(h.getName() + ": " + h.getValue().trim());
                } else {
                    wire.debug(h.getName() + ":");
                }
            }
            wire.debug("");
        }
        if (status.getStatusCode() != HttpServletResponse.SC_OK
                && status.getStatusCode() != HttpServletResponse.SC_CREATED
                && status.getStatusCode() != HttpServletResponse.SC_ACCEPTED) {
            std.error(
                    "POST: Expected CREATED or OK or ACCEPTED for POST request, got " + status.getStatusCode());

            HttpEntity entity = response.getEntity();

            if (entity == null) {
                throw new HueException(status.getStatusCode(), "An error was returned without explanation");
            }
            String json;

            try {
                json = EntityUtils.toString(entity);
            } catch (IOException e) {
                throw new HueException(status.getStatusCode(), e.getMessage());
            }
            if (wire.isDebugEnabled()) {
                wire.debug(json);
                wire.debug("");
            }
            throw new HueException(status.getStatusCode(), json);
        } else {
            try {
                String json = EntityUtils.toString(response.getEntity());

                if (wire.isDebugEnabled()) {
                    wire.debug(json);
                    wire.debug("");
                }
                if (json.startsWith("[")) {
                    JSONArray arr = new JSONArray(json);

                    if (arr.length() > 0) {
                        JSONObject ob = arr.getJSONObject(0);

                        if (ob.has("error")) {
                            ob = ob.getJSONObject("error");
                            if (ob.has("description")) {
                                throw new HueException(ob.getString("description"));
                            }
                        }
                        return ob;
                    }
                    return null;
                }
                return new JSONObject(json);
            } catch (IOException e) {
                throw new HueException(status.getStatusCode(), e.getMessage());
            } catch (JSONException e) {
                throw new HueException(status.getStatusCode(), e.getMessage());
            }
        }
    } finally {
        if (std.isTraceEnabled()) {
            std.trace("exit - " + HueMethod.class.getName() + ".post()");
        }
        if (wire.isDebugEnabled()) {
            wire.debug("<<< [POST (" + (new Date()) + ")] -> " + hue.getAPIEndpoint() + resource
                    + " <--------------------------------------------------------------------------------------");
            wire.debug("");
        }
    }
}

From source file:org.openrepose.common.auth.openstack.AuthenticationServiceClient.java

@Override
public String getBase64EndpointsStringForHeaders(String userToken, String format, String tracingHeader)
        throws AuthServiceException {
    final Map<String, String> headers = new HashMap<>();

    //defaulting to json format
    if ("xml".equalsIgnoreCase(format)) {
        format = MediaType.APPLICATION_XML;
    } else {/*from   w w w. j  ava2  s  .c o  m*/
        format = MediaType.APPLICATION_JSON;
    }

    String rawEndpointsData;
    try {
        //telling the service what format to send the endpoints to us in
        headers.put(ACCEPT_HEADER, format);
        headers.put(AUTH_TOKEN_HEADER, getAdminToken(tracingHeader, false));
        if (tracingHeader != null) {
            headers.put(CommonHttpHeader.TRACE_GUID.toString(), tracingHeader);
        }

        ServiceClientResponse serviceClientResponse = akkaServiceClient.get(ENDPOINTS_PREFIX + userToken,
                targetHostUri + TOKENS + userToken + ENDPOINTS, headers);

        switch (serviceClientResponse.getStatus()) {
        case HttpServletResponse.SC_OK:
            rawEndpointsData = convertStreamToBase64String(serviceClientResponse.getData());
            break;
        case HttpServletResponse.SC_UNAUTHORIZED:
            LOG.error("Unable to get endpoints for user: " + serviceClientResponse.getStatus()
                    + " :admin token expired. Retrieving new admin token and retrying endpoints retrieval...");

            headers.put(AUTH_TOKEN_HEADER, getAdminToken(tracingHeader, true));
            serviceClientResponse = akkaServiceClient.get(ENDPOINTS_PREFIX + userToken,
                    targetHostUri + TOKENS + userToken + ENDPOINTS, headers);

            if (serviceClientResponse.getStatus() == HttpServletResponse.SC_ACCEPTED) {
                rawEndpointsData = convertStreamToBase64String(serviceClientResponse.getData());
            } else {
                delegationMessage.set("Unable to get endpoints for user: " + userToken
                        + " with configured admin credentials");
                LOG.error("Still unable to get endpoints: " + serviceClientResponse.getStatus());
                throw new AuthServiceException(
                        "Unable to retrieve service catalog for user with configured Admin credentials");
            }
            break;
        case HttpServletResponse.SC_REQUEST_ENTITY_TOO_LARGE:
        case FilterDirector.SC_TOO_MANY_REQUESTS: // (413 | 429)
            delegationMessage.set("Unable to get endpoints for token: " + userToken + ". Status code: "
                    + serviceClientResponse.getStatus());
            throw buildAuthServiceOverLimitException(serviceClientResponse);
        default:
            delegationMessage.set("Unable to get endpoints for token: " + userToken + ". Status code: "
                    + serviceClientResponse.getStatus());
            LOG.error("Unable to get endpoints for token. Status code: " + serviceClientResponse.getStatus());
            throw new AuthServiceException("Unable to retrieve service catalog for user. Response from "
                    + targetHostUri + ": " + serviceClientResponse.getStatus());
        }
    } catch (AkkaServiceClientException e) {
        throw new AuthServiceException("Unable to get endpoints.", e);
    }

    return rawEndpointsData;
}

From source file:org.apache.axis2.transport.http.AxisServlet.java

/**
 * Private method that deals with disabling of REST support.
 *
 * @param response/*from w  w w .j  av  a 2  s. c o  m*/
 * @throws IOException
 */
protected void showRestDisabledErrorMessage(HttpServletResponse response) throws IOException {
    PrintWriter writer = new PrintWriter(response.getOutputStream());
    writer.println("<html><body><h2>Please enable REST support in WEB-INF/conf/axis2.xml "
            + "and WEB-INF/web.xml</h2></body></html>");
    writer.flush();
    response.setStatus(HttpServletResponse.SC_ACCEPTED);
}

From source file:com.rmn.qa.servlet.AutomationTestRunServlet.java

/**
 * Attempts to register a new run request with the server. Returns a 201 if the request can be fulfilled but AMIs
 * must be started Returns a 202 if the request can be fulfilled Returns a 400 if the required parameters are not
 * passed in. Returns a 409 if the server is at full node capacity
 *///www  .  j  a  va2 s.  c  o m
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setContentType("text/html");
    response.setCharacterEncoding("UTF-8");

    String browserRequested = request.getParameter("browser");
    String browserVersion = request.getParameter("browserVersion");
    String osRequested = request.getParameter("os");
    String threadCount = request.getParameter("threadCount");
    String uuid = request.getParameter(AutomationConstants.UUID);
    BrowserPlatformPair browserPlatformPairRequest;
    Platform requestedPlatform;

    // Return a 400 if any of the required parameters are not passed in
    // Check for uuid first as this is the most important variable
    if (uuid == null) {
        String msg = "Parameter 'uuid' must be passed in as a query string parameter";
        log.error(msg);
        response.sendError(HttpServletResponse.SC_BAD_REQUEST, msg);
        return;
    }
    if (browserRequested == null) {
        String msg = "Parameter 'browser' must be passed in as a query string parameter";
        log.error(msg);
        response.sendError(HttpServletResponse.SC_BAD_REQUEST, msg);
        return;
    }
    if (threadCount == null) {
        String msg = "Parameter 'threadCount' must be passed in as a query string parameter";
        log.error(msg);
        response.sendError(HttpServletResponse.SC_BAD_REQUEST, msg);
        return;
    }
    if (StringUtils.isEmpty(osRequested)) {
        requestedPlatform = Platform.ANY;
    } else {
        requestedPlatform = AutomationUtils.getPlatformFromObject(osRequested);
        if (requestedPlatform == null) {
            String msg = "Parameter 'os' does not have a valid Selenium Platform equivalent: " + osRequested;
            log.error(msg);
            response.sendError(HttpServletResponse.SC_BAD_REQUEST, msg);
            return;
        }
    }

    Integer threadCountRequested = Integer.valueOf(threadCount);

    AutomationRunRequest runRequest = new AutomationRunRequest(uuid, threadCountRequested, browserRequested,
            browserVersion, requestedPlatform);
    browserPlatformPairRequest = new BrowserPlatformPair(browserRequested, requestedPlatform);

    log.info(String.format("Server request [%s] received.", runRequest));
    boolean amisNeeded;
    int amiThreadsToStart = 0;
    int currentlyAvailableNodes;
    // Synchronize this block until we've added the run to our context for other potential threads to see
    synchronized (AutomationTestRunServlet.class) {
        int remainingNodesAvailable = AutomationContext.getContext().getTotalThreadsAvailable(getProxySet());
        // If the number of nodes this grid hub can actually run is less than the number requested, this hub can not
        // fulfill this run at this time
        if (remainingNodesAvailable < runRequest.getThreadCount()) {
            log.error(String.format(
                    "Requested node count of [%d] could not be fulfilled due to hub limit. [%d] nodes available - Request UUID [%s]",
                    threadCountRequested, remainingNodesAvailable, uuid));
            response.sendError(HttpServletResponse.SC_CONFLICT,
                    "Server cannot fulfill request due to configured node limit being reached.");
            return;
        }
        // Get the number of matching, free nodes to determine if we need to start up AMIs or not
        currentlyAvailableNodes = requestMatcher.getNumFreeThreadsForParameters(getProxySet(), runRequest);
        // If the number of available nodes is less than the total number requested, we will have to spin up AMIs in
        // order to fulfill the request
        amisNeeded = currentlyAvailableNodes < threadCountRequested;
        if (amisNeeded) {
            // Get the difference which will be the number of additional nodes we need to spin up to supplement
            // existing nodes
            amiThreadsToStart = threadCountRequested - currentlyAvailableNodes;
        }
        // If the browser requested is not supported by AMIs, we need to not unnecessarily spin up AMIs
        if (amisNeeded && !AutomationUtils.browserAndPlatformSupported(browserPlatformPairRequest)) {
            response.sendError(HttpServletResponse.SC_GONE,
                    "Request cannot be fulfilled and browser and platform is not supported by AMIs");
            return;
        }
        // Add the run to our context so we can track it
        AutomationRunRequest newRunRequest = new AutomationRunRequest(uuid, threadCountRequested,
                browserRequested, browserVersion, requestedPlatform);
        boolean addSuccessful = AutomationContext.getContext().addRun(newRunRequest);
        if (!addSuccessful) {
            log.warn(String.format("Test run already exists for the same UUID [%s]", uuid));
            //                response.sendError(HttpServletResponse.SC_BAD_REQUEST, "Test run already exists with the same UUID.");
            response.setStatus(HttpServletResponse.SC_CREATED);
            return;
        }
    }
    if (amisNeeded) {
        // Start up AMIs as that will be required
        log.warn(String.format(
                "Insufficient nodes to fulfill request. New AMIs will be queued up. Requested [%s] - Available [%s] - Request UUID [%s]",
                threadCountRequested, currentlyAvailableNodes, uuid));
        try {
            AutomationTestRunServlet.startNodes(ec2, uuid, amiThreadsToStart, browserRequested,
                    requestedPlatform);
        } catch (NodesCouldNotBeStartedException e) {
            // Make sure and de-register the run if the AMI startup was not successful
            AutomationContext.getContext().deleteRun(uuid);
            String throwableMessage = e.getCause() != null ? e.getCause().getMessage() : e.getMessage();
            String msg = "Nodes could not be started: " + throwableMessage;
            response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, msg);
            return;
        }
        // Return a 201 to let the caller know AMIs will be started
        response.setStatus(HttpServletResponse.SC_CREATED);
        return;
    } else {
        // Otherwise just return a 202 letting the caller know the requested resources are available
        response.setStatus(HttpServletResponse.SC_ACCEPTED);
        return;
    }
}

From source file:org.alfresco.rest.api.tests.TestDownloads.java

/**
 * Tests deleting a download node using the /nodes API:
 *
 * <p>DELETE:</p>//w ww  .  ja va  2  s .  c  o  m
 * {@literal <host>:<port>/alfresco/api/<networkId>/public/alfresco/versions/1/nodes/<nodeId>}
 * 
 */
@Test
public void test005DeleteDownloadNode() throws Exception {

    //test deleting a download node
    Download download = createDownload(HttpServletResponse.SC_ACCEPTED, zippableDocId1);

    assertDoneDownload(download, 1, 13);

    deleteNode(download.getId(), true, HttpServletResponse.SC_NO_CONTENT);

    getDownload(download.getId(), HttpServletResponse.SC_NOT_FOUND);

    //test user2 deleting a download node created by user1
    download = createDownload(HttpServletResponse.SC_ACCEPTED, zippableDocId1);

    assertDoneDownload(download, 1, 13);

    setRequestContext(user2);

    deleteNode(download.getId(), true, HttpServletResponse.SC_FORBIDDEN);

    assertDoneDownload(download, 1, 13);
}

From source file:org.energyos.espi.datacustodian.web.api.BatchRESTController.java

/**
 * Provide a Bulk delivery of information. The Third Party is provided with
 * the XML representation of the Bulk.//from   ww  w. j  a v  a2  s  . c  om
 * 
 * RESTful Pattern: /espi/1_1/resource/Batch/Subscription/{subscriptionId}
 * 
 * Requires Authorization: Bearer [{data_custodian_access_token} |
 * {client_access_token}]
 * 
 * @param request
 *            HTTP Servlet Request
 * @param response
 *            HTTP Servlet Response
 * @param bulkId
 *            Long identifying the BR={bulkId} within the
 *            Authorization.scope string
 * @param params
 *            HTTP Query Parameters
 * @throws IOException
 * @throws FeedException
 * 
 * @usage GET /espi/1_1/resource/Batch/Bulk/{bulkId}
 */
@RequestMapping(value = Routes.BATCH_BULK_MEMBER, method = RequestMethod.GET, produces = "application/atom+xml")
@ResponseBody
public void bulk(HttpServletRequest request, HttpServletResponse response, @PathVariable Long bulkId,
        @RequestParam Map<String, String> params) throws IOException, FeedException {

    // check to see if SFTP (or XML Caching) is turned on for this bulkId.
    //
    if (isSFTP(request)) {
        if (isInCache(request, bulkId)) {
            // make sure the sftpd is running
            // send back a 302 and queue up a notification
            // to initiate the SFTP (may want to log this)
        } else {
            // build the file stream
            // in parallel
            // generate the xml to a file
            // return 302 response code
            // TODO: make SFTP cache location an configuration
            File destinationFile = new File("/var/greenbutton/export-cache/" + bulkId);
            FileOutputStream fileOutputStream = new FileOutputStream(destinationFile);

            try {
                try {
                    exportService.exportBatchBulk(bulkId, getAuthorizationThirdParty(request), fileOutputStream,
                            new ExportFilter(params));

                } catch (Exception e) {
                    response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
                }
            } catch (Exception e) {
                throw new RuntimeException(e);
            } finally {
                if (destinationFile != null) {
                    try {
                        fileOutputStream.close();
                        response.setStatus(HttpServletResponse.SC_ACCEPTED);
                    } catch (IOException e) {
                        // Ignore issues during closing
                    }
                }
            }

        }
    } else {
        // not SFTP, use HTTPS as bulk response

        response.setContentType(MediaType.APPLICATION_ATOM_XML_VALUE);
        // note this default to a file just in case the handler doesn't want
        // to directly
        // parse the incoming stream.

        response.addHeader("Content-Disposition", "attachment; filename=GreenButtonDownload.xml");

        try {
            exportService.exportBatchBulk(bulkId, getAuthorizationThirdParty(request),
                    response.getOutputStream(), new ExportFilter(params));

        } catch (Exception e) {
            response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        }

    }

}