Example usage for org.springframework.http HttpStatus ACCEPTED

List of usage examples for org.springframework.http HttpStatus ACCEPTED

Introduction

In this page you can find the example usage for org.springframework.http HttpStatus ACCEPTED.

Prototype

HttpStatus ACCEPTED

To view the source code for org.springframework.http HttpStatus ACCEPTED.

Click Source Link

Document

202 Accepted .

Usage

From source file:com.netflix.genie.web.controllers.JobRestControllerIntegrationTests.java

/**
 * Test the job submit method for when the job is killed as it times out.
 *
 * @throws Exception If there is a problem.
 *//*from  w ww.  j  a v a 2  s .c o m*/
@Test
public void testSubmitJobMethodKillOnTimeout() throws Exception {
    Assume.assumeTrue(SystemUtils.IS_OS_UNIX);
    final String commandArgs = "-c 'sleep 60'";

    final List<ClusterCriteria> clusterCriteriaList = new ArrayList<>();
    final Set<String> clusterTags = new HashSet<>();
    clusterTags.add("localhost");
    final ClusterCriteria clusterCriteria = new ClusterCriteria(clusterTags);
    clusterCriteriaList.add(clusterCriteria);

    final Set<String> commandCriteria = new HashSet<>();
    commandCriteria.add("bash");
    final JobRequest jobRequest = new JobRequest.Builder(JOB_NAME, JOB_USER, JOB_VERSION, commandArgs,
            clusterCriteriaList, commandCriteria).withTimeout(5).withDisableLogArchival(true).build();

    final MvcResult result = this.mvc.perform(MockMvcRequestBuilders.post(JOBS_API)
            .contentType(MediaType.APPLICATION_JSON).content(objectMapper.writeValueAsBytes(jobRequest)))
            .andReturn();

    if (result.getResponse().getStatus() != HttpStatus.ACCEPTED.value()) {
        log.error("RESPONSE WASN'T 202 IT WAS: {} AND THE ERROR MESSAGE IS: {} AND THE CONTENT IS {}",
                result.getResponse().getStatus(), result.getResponse().getErrorMessage(),
                result.getResponse().getContentAsString());
        Assert.fail();
    }

    final String id = this.getIdFromLocation(result.getResponse().getHeader(HttpHeaders.LOCATION));

    this.waitForDone(id);

    this.mvc.perform(MockMvcRequestBuilders.get(JOBS_API + "/{id}", id))
            .andExpect(MockMvcResultMatchers.status().isOk())
            .andExpect(MockMvcResultMatchers.content().contentTypeCompatibleWith(MediaTypes.HAL_JSON))
            .andExpect(MockMvcResultMatchers.jsonPath(ID_PATH, Matchers.is(id)))
            .andExpect(MockMvcResultMatchers.jsonPath(STATUS_PATH, Matchers.is(JobStatus.KILLED.toString())));
}

From source file:com.vmware.bdd.cli.rest.RestClient.java

private TaskRead processResponse(ResponseEntity<String> response, HttpMethod verb, PrettyOutput... prettyOutput)
        throws Exception {

    HttpStatus responseStatus = response.getStatusCode();
    if (responseStatus == HttpStatus.ACCEPTED) {//Accepted with task in the location header
        //get task uri from response to trace progress
        HttpHeaders headers = response.getHeaders();
        URI taskURI = headers.getLocation();
        String[] taskURIs = taskURI.toString().split("/");
        String taskId = taskURIs[taskURIs.length - 1];

        TaskRead taskRead;/*from   www.j av a 2s  .c  o  m*/
        int oldProgress = 0;
        Status oldTaskStatus = null;
        Status taskStatus = null;
        int progress = 0;
        do {
            ResponseEntity<TaskRead> taskResponse = restGetById(Constants.REST_PATH_TASK, taskId,
                    TaskRead.class, false);

            //task will not return exception as it has status
            taskRead = taskResponse.getBody();

            progress = (int) (taskRead.getProgress() * 100);
            taskStatus = taskRead.getStatus();

            //fix cluster deletion exception
            Type taskType = taskRead.getType();
            if ((taskType == Type.DELETE) && (taskStatus == TaskRead.Status.COMPLETED)) {
                clearScreen();
                System.out.println(taskStatus + " " + progress + "%\n");
                break;
            }

            if (taskType == Type.SHRINK && !taskRead.getFailNodes().isEmpty()) {
                throw new CliRestException(taskRead.getFailNodes().get(0).getErrorMessage());
            }

            if ((prettyOutput != null && prettyOutput.length > 0 && prettyOutput[0].isRefresh(true))
                    || oldTaskStatus != taskStatus || oldProgress != progress) {
                //clear screen and show progress every few seconds
                clearScreen();
                //output completed task summary first in the case there are several related tasks
                if (prettyOutput != null && prettyOutput.length > 0
                        && prettyOutput[0].getCompletedTaskSummary() != null) {
                    for (String summary : prettyOutput[0].getCompletedTaskSummary()) {
                        System.out.println(summary + "\n");
                    }
                }
                System.out.println(taskStatus + " " + progress + "%\n");

                if (prettyOutput != null && prettyOutput.length > 0) {
                    // print call back customize the detailed output case by case
                    prettyOutput[0].prettyOutput();
                }

                if (oldTaskStatus != taskStatus || oldProgress != progress) {
                    oldTaskStatus = taskStatus;
                    oldProgress = progress;
                    if (taskRead.getProgressMessage() != null) {
                        System.out.println(taskRead.getProgressMessage());
                    }
                }
            }
            try {
                Thread.sleep(3 * 1000);
            } catch (InterruptedException ex) {
                //ignore
            }
        } while (taskStatus != TaskRead.Status.COMPLETED && taskStatus != TaskRead.Status.FAILED
                && taskStatus != TaskRead.Status.ABANDONED && taskStatus != TaskRead.Status.STOPPED);

        String errorMsg = taskRead.getErrorMessage();
        if (!taskRead.getStatus().equals(TaskRead.Status.COMPLETED)) {
            throw new CliRestException(errorMsg);
        } else { //completed
            if (taskRead.getType().equals(Type.VHM)) {
                logger.info("task type is vhm");
                Thread.sleep(5 * 1000);
                if (prettyOutput != null && prettyOutput.length > 0 && prettyOutput[0].isRefresh(true)) {
                    //clear screen and show progress every few seconds
                    clearScreen();
                    System.out.println(taskStatus + " " + progress + "%\n");

                    // print call back customize the detailed output case by case
                    if (prettyOutput != null && prettyOutput.length > 0) {
                        prettyOutput[0].prettyOutput();
                    }
                }
            } else {
                return taskRead;
            }
        }
    }
    return null;
}

From source file:com.vmware.bdd.rest.RestResource.java

/**
 * Create a cluster/*from  w w  w.  jav  a2  s .c o  m*/
 * @param createSpec create specification
 * @param request
 * @return Return a response with Accepted status and put task uri in the Location of header that can be used to monitor the progress
 */
@RequestMapping(value = "/clusters", method = RequestMethod.POST, consumes = "application/json")
@ResponseStatus(HttpStatus.ACCEPTED)
public void createCluster(@RequestBody ClusterCreate createSpec,
        @RequestParam(value = "skiprefreshvc", required = false) boolean skipRefreshVC,
        HttpServletRequest request, HttpServletResponse response) throws Exception {
    verifyInitialized();
    String clusterName = createSpec.getName();
    logger.info(String.format("The specified node template name for creating cluster %s is %s", clusterName,
            createSpec.getTemplateName()));
    if (!CommonUtil.validateClusterName(clusterName)) {
        throw BddException.INVALID_PARAMETER("cluster name", clusterName);
    }
    if (CommonUtil.isBlank(createSpec.getAppManager())) {
        createSpec.setAppManager(Constants.IRONFAN);
    } else {
        AppManagerEntity appManager = appManagerService.findAppManagerByName(createSpec.getAppManager());
        if (appManager == null) {
            throw BddException.NOT_FOUND("application manager", createSpec.getAppManager());
        }
    }

    BaseConfiguration params = new BaseConfiguration();
    params.addProperty(Constants.SKIP_REFRESH_VC, skipRefreshVC);

    long jobExecutionId = clusterMgr.createCluster(createSpec, params);
    redirectRequest(jobExecutionId, request, response);
}

From source file:com.vmware.bdd.rest.RestResource.java

/**
 * Configure a hadoop or hbase cluster's properties
 * @param clusterName//  w  w  w  . j a  v a2s .  c om
 * @param createSpec The existing create specification plus the configuration map supported in cluster and node group levels(please refer to a sample specification file)
 * @param request
 * @return Return a response with Accepted status and put task uri in the Location of header that can be used to monitor the progress
 */
@RequestMapping(value = "/cluster/{clusterName}/config", method = RequestMethod.PUT, consumes = "application/json")
@ResponseStatus(HttpStatus.ACCEPTED)
public void configCluster(@PathVariable("clusterName") String clusterName,
        @RequestBody ClusterCreate createSpec, HttpServletRequest request, HttpServletResponse response)
        throws Exception {
    verifyInitialized();
    if (!CommonUtil.validateClusterName(clusterName)) {
        throw BddException.INVALID_PARAMETER("cluster name", clusterName);
    }
    Long taskId = clusterMgr.configCluster(clusterName, createSpec);
    redirectRequest(taskId, request, response);
}

From source file:com.vmware.bdd.rest.RestResource.java

/**
 * Delete a cluster//from   www.jav a 2  s.  c  o  m
 * @param clusterName
 * @param request
 * @return Return a response with Accepted status and put task uri in the Location of header that can be used to monitor the progress
 */
@RequestMapping(value = "/cluster/{clusterName}", method = RequestMethod.DELETE)
@ResponseStatus(HttpStatus.ACCEPTED)
public void deleteCluster(@PathVariable("clusterName") String clusterName, HttpServletRequest request,
        HttpServletResponse response) throws Exception {
    verifyInitialized();
    clusterName = CommonUtil.decode(clusterName);
    // make sure cluster name is valid
    if (!CommonUtil.validateClusterName(clusterName)) {
        throw BddException.INVALID_PARAMETER("cluster name", clusterName);
    }
    Long taskId = clusterMgr.deleteClusterByName(clusterName);
    redirectRequest(taskId, request, response);
}

From source file:com.vmware.bdd.rest.RestResource.java

@RequestMapping(value = "/cluster/{clusterName}", method = RequestMethod.PUT, consumes = "application/json", produces = "application/json")
public void updateCluster(@PathVariable("clusterName") String clusterName,
        @RequestBody(required = false) ClusterCreate clusterUpdate,
        @RequestParam(value = "state", required = false) String state,
        @RequestParam(value = "force", required = false, defaultValue = "false") Boolean force,
        @RequestParam(value = "ignorewarning", required = false, defaultValue = "false") boolean ignoreWarning,
        @RequestParam(value = "append", required = false, defaultValue = "false") boolean append,
        HttpServletRequest request, HttpServletResponse response) throws Exception {
    if (state != null) {
        // forward request to startStop`() for backward compatibility
        request.getRequestDispatcher(clusterName + "/action").forward(request, response);
        response.setStatus(HttpStatus.ACCEPTED.value());
        return;//from   w  w w.j ava  2s. com
    }
    verifyInitialized();
    clusterName = CommonUtil.decode(clusterName);
    if (CommonUtil.isBlank(clusterName) || !CommonUtil.validateResourceName(clusterName)) {
        throw BddException.INVALID_PARAMETER("cluster name", clusterName);
    }

    clusterMgr.updateCluster(clusterUpdate, ignoreWarning, append);
    response.setStatus(HttpStatus.OK.value());
}

From source file:com.vmware.bdd.rest.RestResource.java

/**
 * Start or stop a normal cluster, or resume a failed cluster after adjusting the resources allocated to this cluster
 * @param clusterName/*from www  .  ja v a2s  .  c  o m*/
 * @param state Can be start, stop, or resume
 * @param request
 * @return Return a response with Accepted status and put task uri in the Location of header that can be used to monitor the progress
 */
@RequestMapping(value = "/cluster/{clusterName}/action", method = RequestMethod.PUT)
@ResponseStatus(HttpStatus.ACCEPTED)
public void startStopResumeCluster(@PathVariable("clusterName") String clusterName,
        @RequestParam(value = "state", required = true) String state,
        @RequestParam(value = "force", required = false, defaultValue = "false") Boolean force,
        @RequestParam(value = "skiprefreshvc", required = false) boolean skipRefreshVC,
        HttpServletRequest request, HttpServletResponse response) throws Exception {

    verifyInitialized();
    clusterName = CommonUtil.decode(clusterName);
    if (CommonUtil.isBlank(clusterName) || !CommonUtil.validateClusterName(clusterName)) {
        throw BddException.INVALID_PARAMETER("cluster name", clusterName);
    }

    Long taskId;
    if (state.equals("stop")) {
        taskId = clusterMgr.stopCluster(clusterName);
        redirectRequest(taskId, request, response);
    } else if (state.equals("start")) {
        taskId = clusterMgr.startCluster(clusterName, force);
        redirectRequest(taskId, request, response);
    } else if (state.equals("resume")) {
        BaseConfiguration params = new BaseConfiguration();
        params.addProperty(Constants.SKIP_REFRESH_VC, skipRefreshVC);
        taskId = clusterMgr.resumeClusterCreation(clusterName, params);
        redirectRequest(taskId, request, response);
    } else {
        throw BddException.INVALID_PARAMETER("cluster state", state);
    }
}

From source file:com.vmware.bdd.rest.RestResource.java

/**
 * Expand the number of nodes in a node group
 * @param clusterName//  w w w  .  ja  v  a2  s . c o m
 * @param groupName
 * @param instanceNum The target instance number after resize. It can be larger/smaller than existing instance number in this node group
 * @param request
 * @return Return a response with Accepted status and put task uri in the Location of header that can be used to monitor the progress
 */
@RequestMapping(value = "/cluster/{clusterName}/nodegroup/{groupName}/instancenum", method = RequestMethod.PUT)
@ResponseStatus(HttpStatus.ACCEPTED)
public void resizeCluster(@PathVariable("clusterName") String clusterName,
        @PathVariable("groupName") String groupName, @RequestBody Integer instanceNum,
        @RequestParam(value = "force", required = false, defaultValue = "false") Boolean force,
        @RequestParam(value = "skiprefreshvc", required = false) boolean skipRefreshVC,
        HttpServletRequest request, HttpServletResponse response) throws Exception {

    verifyInitialized();

    if (CommonUtil.isBlank(clusterName) || !CommonUtil.validateClusterName(clusterName)) {
        throw BddException.INVALID_PARAMETER("cluster name", clusterName);
    }

    if (CommonUtil.isBlank(groupName) || !CommonUtil.validateNodeGroupName(groupName)) {
        throw BddException.INVALID_PARAMETER("node group name", groupName);
    }

    if (instanceNum <= 0) {
        throw BddException.INVALID_PARAMETER("node group instance number", String.valueOf(instanceNum));
    }
    BaseConfiguration params = new BaseConfiguration();
    params.addProperty(Constants.SKIP_REFRESH_VC, skipRefreshVC);

    Long taskId = clusterMgr.resizeCluster(clusterName, groupName, instanceNum, force, params);
    redirectRequest(taskId, request, response);
}

From source file:com.vmware.bdd.rest.RestResource.java

/**
 * Upgrade a cluster// w w w.j  av  a2 s  .  c  o m
 * @param clusterName
 * @param request
 * @return Return a response with Accepted status and put task uri in the Location of header that can be used to monitor the progress
 * @throws Exception
 */
@RequestMapping(value = "/cluster/{clusterName}/upgrade", method = RequestMethod.PUT)
@ResponseStatus(HttpStatus.ACCEPTED)
public void upgradeCluster(@PathVariable("clusterName") String clusterName, HttpServletRequest request,
        HttpServletResponse response) throws Exception {
    // make sure cluster name is valid
    if (!CommonUtil.validateClusterName(clusterName)) {
        throw BddException.INVALID_PARAMETER("cluster name", clusterName);
    }
    Long taskId = clusterMgr.upgradeClusterByName(clusterName);
    redirectRequest(taskId, request, response);
}

From source file:com.vmware.bdd.rest.RestResource.java

/**
 * Scale up or down the cpu and memory of each node in a node group
 * @param clusterName/*from  ww  w.  ja  v a  2 s.  com*/
 * @param groupName
 * @param scale The new cpu and memory allocated to each node in this node group
 * @param request
 * @return Return a response with Accepted status and put task uri in the Location of header that can be used to monitor the progress
 */
@RequestMapping(value = "/cluster/{clusterName}/nodegroup/{groupName}/scale", method = RequestMethod.PUT)
@ResponseStatus(HttpStatus.ACCEPTED)
public void scale(@PathVariable("clusterName") String clusterName, @PathVariable("groupName") String groupName,
        @RequestBody ResourceScale scale, HttpServletRequest request, HttpServletResponse response)
        throws Exception {

    verifyInitialized();

    if (CommonUtil.isBlank(clusterName) || !CommonUtil.validateClusterName(clusterName)) {
        throw BddException.INVALID_PARAMETER("cluster name", clusterName);
    }

    if (CommonUtil.isBlank(groupName) || !CommonUtil.validateNodeGroupName(groupName)) {
        throw BddException.INVALID_PARAMETER("node group name", groupName);
    }

    if (scale.getCpuNumber() <= 0 && scale.getMemory() < Constants.MIN_MEM_SIZE) {
        throw BddException.INVALID_PARAMETER_WITHOUT_EQUALS_SIGN(
                "node group scale parameter. The number of CPUs must be greater than zero, and the memory size in MB must be greater than or equal to "
                        + Constants.MIN_MEM_SIZE + ":",
                scale);
    }
    logger.info("scale cluster: " + scale.toString());
    Long taskId = scaleMgr.scaleNodeGroupResource(scale);
    redirectRequest(taskId, request, response);
}