Example usage for org.springframework.web.client HttpServerErrorException HttpServerErrorException

List of usage examples for org.springframework.web.client HttpServerErrorException HttpServerErrorException

Introduction

In this page you can find the example usage for org.springframework.web.client HttpServerErrorException HttpServerErrorException.

Prototype

public HttpServerErrorException(HttpStatus statusCode, String statusText) 

Source Link

Document

Constructor with a status code and status text.

Usage

From source file:gateway.test.EventTests.java

/**
 * Test GET /event/*  ww  w  .jav  a  2s  .  c o  m*/
 */
@Test
public void testGetEvents() {
    // Mock Response
    when(restTemplate.getForEntity(anyString(), eq(String.class)))
            .thenReturn(new ResponseEntity<String>("event", HttpStatus.OK));

    // Test
    ResponseEntity<?> response = eventController.getEvents(null, null, null, null, 0, 10, user);

    // Verify
    assertTrue(response.getBody().toString().equals("event"));
    assertTrue(response.getStatusCode().equals(HttpStatus.OK));

    // Test REST Exception
    when(restTemplate.getForEntity(anyString(), eq(String.class)))
            .thenThrow(new HttpServerErrorException(HttpStatus.INTERNAL_SERVER_ERROR, WORKFLOW_ERROR));
    response = eventController.getEvents(null, null, null, null, 0, 10, user);
    assertTrue(response.getStatusCode().equals(HttpStatus.INTERNAL_SERVER_ERROR));

    // Test General Exception
    when(restTemplate.getForEntity(anyString(), eq(String.class)))
            .thenThrow(new RestClientException("event error"));
    response = eventController.getEvents(null, null, null, null, 0, 10, user);
    assertTrue(response.getStatusCode().equals(HttpStatus.INTERNAL_SERVER_ERROR));
    assertTrue(response.getBody() instanceof ErrorResponse);
    assertTrue(((ErrorResponse) response.getBody()).message.contains("event error"));

    // Test Validation Input Exception
    when(gatewayUtil.validateInput(anyString(), any())).thenReturn("Error");
    response = eventController.getEvents(null, null, null, null, 0, 10, user);
    assertTrue(response.getStatusCode().equals(HttpStatus.BAD_REQUEST));
    assertTrue(response.getBody() instanceof ErrorResponse);
}

From source file:com.alexa.oms.service.AlexaOmsSpeechlet.java

@Override
public void onSessionStarted(final SessionStartedRequest request, final Session session)
        throws SpeechletException {
    String jwtToken = session.getUser().getAccessToken();
    LOG.info("onSessionStarted requestId={}, sessionId={}, access_token={}, userid={}", request.getRequestId(),
            session.getSessionId(), jwtToken, session.getUser().getUserId());
    if (jwtToken == null) {
        //return getResponse(RESPONSE_NOT_AUTHORIZED);            
        throw new HttpServerErrorException(HttpStatus.UNAUTHORIZED, RESPONSE_NOT_AUTHORIZED);

    }/*from   ww w .j  a  v  a2 s  .  c  om*/

    try {

        Claims claims = getClaimsFromJWT(jwtToken);
        String userId = claims.getUser_name();

        LOG.info("User Id ==> " + userId);

        Customer customer = customerRepository.findByEmail(userId);

        LOG.info("CustomerId ==> " + customer.getCustomerId());

        if (StringUtils.isBlank(userId) || customer == null) {

            throw new HttpServerErrorException(HttpStatus.UNAUTHORIZED, RESPONSE_NOT_AUTHORIZED);
        }

        session.setAttribute(CUSTOMER_ID, customer.getCustomerId());

    } catch (Exception e) {
        LOG.error("erro during cusomer identification" + e);
        throw new HttpServerErrorException(HttpStatus.UNAUTHORIZED, RESPONSE_NOT_AUTHORIZED);
    }

}

From source file:gateway.test.EventTests.java

/**
 * Test POST /event/*from ww  w .ja v  a2 s. c  om*/
 */
@Test
public void testFireEvent() {
    // Mock Response
    when(restTemplate.postForObject(anyString(), any(), eq(String.class))).thenReturn(any(String.class));

    // Test
    ResponseEntity<?> response = eventController.fireEvent(new Event(), user);

    // Verify
    assertTrue(response.getStatusCode().equals(HttpStatus.CREATED));

    // Test REST Exception
    when(restTemplate.postForObject(anyString(), any(), eq(String.class)))
            .thenThrow(new HttpServerErrorException(HttpStatus.INTERNAL_SERVER_ERROR, WORKFLOW_ERROR));
    response = eventController.fireEvent(new Event(), user);
    assertTrue(response.getStatusCode().equals(HttpStatus.INTERNAL_SERVER_ERROR));

    // Test Exception
    when(restTemplate.postForObject(anyString(), any(), eq(String.class)))
            .thenThrow(new RestClientException("event error"));
    response = eventController.fireEvent(new Event(), user);
    assertTrue(response.getStatusCode().equals(HttpStatus.INTERNAL_SERVER_ERROR));
    assertTrue(response.getBody() instanceof ErrorResponse);
    assertTrue(((ErrorResponse) response.getBody()).message.contains("event error"));
}

From source file:gateway.test.EventTests.java

/**
 * Test GET /event/{eventId}//from  w w w.  j  a v  a  2  s .  co  m
 */
@Test
public void testGetEvent() {
    // Mock Response
    when(restTemplate.getForObject(anyString(), eq(String.class))).thenReturn("event");

    // Test
    ResponseEntity<?> response = eventController.getEventInformation("eventId", user);

    // Verify
    assertTrue(response.getBody().toString().equals("event"));
    assertTrue(response.getStatusCode().equals(HttpStatus.OK));

    // Test REST Exception
    when(restTemplate.getForObject(anyString(), eq(String.class)))
            .thenThrow(new HttpServerErrorException(HttpStatus.INTERNAL_SERVER_ERROR, WORKFLOW_ERROR));
    response = eventController.getEventInformation("eventId", user);
    assertTrue(response.getStatusCode().equals(HttpStatus.INTERNAL_SERVER_ERROR));

    // Test Exception
    when(restTemplate.getForObject(anyString(), eq(String.class)))
            .thenThrow(new RestClientException("event error"));
    response = eventController.getEventInformation("eventId", user);
    assertTrue(response.getStatusCode().equals(HttpStatus.INTERNAL_SERVER_ERROR));
    assertTrue(response.getBody() instanceof ErrorResponse);
    assertTrue(((ErrorResponse) response.getBody()).message.contains("event error"));
}

From source file:org.venice.piazza.servicecontroller.controller.TaskManagedController.java

/**
 * Updates the Status for a Piazza Job./*from  ww  w  .jav a2 s.co  m*/
 * 
 * @param userName
 *            The name of the user. Used for verification.
 * @param serviceId
 *            The ID of the Service containing the Job
 * @param jobId
 *            The ID of the Job to update
 * @param statusUpdate
 *            The update contents, including status, percentage, and possibly results.
 * @return Success or error.
 */
@RequestMapping(value = {
        "/service/{serviceId}/task/{jobId}" }, method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<PiazzaResponse> updateServiceJobStatus(
        @RequestParam(value = "userName", required = true) String userName,
        @PathVariable(value = "serviceId") String serviceId, @PathVariable(value = "jobId") String jobId,
        @RequestBody StatusUpdate statusUpdate) {
    try {
        // Log the Request
        piazzaLogger.log(
                String.format("User %s Requesting to Update Job Status for Job %s for Task-Managed Service.",
                        userName, jobId),
                Severity.INFORMATIONAL);

        // Check for Access
        boolean canAccess = mongoAccessor.canUserAccessServiceQueue(serviceId, userName);
        if (!canAccess) {
            throw new ResourceAccessException("Service does not allow this user to access.");
        }

        // Simple Validation
        if ((statusUpdate.getStatus() == null) || (statusUpdate.getStatus().isEmpty())) {
            throw new HttpServerErrorException(HttpStatus.BAD_REQUEST,
                    "`status` property must be provided in Update payload.");
        }

        // Process the Update
        serviceTaskManager.processStatusUpdate(serviceId, jobId, statusUpdate);
        // Return Success
        return new ResponseEntity<>(new SuccessResponse("OK", "ServiceController"), HttpStatus.OK);
    } catch (Exception exception) {
        String error = String.format("Could not Update status for Job %s for Service %s : %s", jobId, serviceId,
                exception.getMessage());
        LOGGER.error(error, exception);
        piazzaLogger.log(error, Severity.ERROR, new AuditElement(userName, "failedToUpdateServiceJob", jobId));
        HttpStatus status = HttpStatus.INTERNAL_SERVER_ERROR;
        if (exception instanceof ResourceAccessException) {
            status = HttpStatus.UNAUTHORIZED;
        } else if (exception instanceof InvalidInputException) {
            status = HttpStatus.NOT_FOUND;
        } else if (exception instanceof HttpServerErrorException) {
            status = ((HttpServerErrorException) exception).getStatusCode();
        }
        return new ResponseEntity<>(new ErrorResponse(error, "ServiceController"), status);
    }
}

From source file:com.alexa.oms.service.AlexaOmsSpeechlet.java

@Override
public SpeechletResponse onIntent(final IntentRequest request, final Session session)
        throws SpeechletException, HttpServerErrorException {
    //LOG.debug("onIntent requestId={}, sessionId={}, access_token={}, userid={}", request.getRequestId(), session.getSessionId(), session.getUser().getAccessToken(), session.getUser().getUserId());

    int customerId;
    try {/*from   w  w w. j  a  v  a  2 s .c  om*/
        customerId = (Integer) session.getAttribute(CUSTOMER_ID);
        if (!session.getApplication().getApplicationId().equalsIgnoreCase(applicationId)) {
            //return getResponse(RESPONSE_NOT_AUTHORIZED);

            throw new HttpServerErrorException(HttpStatus.UNAUTHORIZED, RESPONSE_NOT_AUTHORIZED);

        }

        Intent intent = request.getIntent();
        String intentName = (intent != null) ? intent.getName() : null;

        IntentType reqIntent = getIntentType(intentName);

        if (reqIntent != null) {
            LOG.debug("Intent ==> " + reqIntent + " Slot Keys :  " + intent.getSlots().keySet() + "Slot Keys :"
                    + intent.getSlots().values());

            switch (reqIntent) {
            case HelloWorldIntent:
                return getResponse(RESPONSE_HELLO_INTENT);

            case OrderStatusIntent:
                return getOrderStatusIntentResponse(intent, customerId, session);

            case OrdersIntent:
                return getOrdersIntentResponse(intent, customerId, session);

            case OrderDetailIntent:
                return getOrderDetailIntentResponse(intent, customerId, session);

            case AmazonHelpIntent:
                return newAskResponse(RESPONSE_HELP_INTENT, true, RESPONSE_REPROMPT_HELP_INTENT, false);

            case AmazonCancelIntent:
                return getResponse(RESPONSE_GOODBYE, true);

            case AmazonStopIntent:
                return getResponse(RESPONSE_GOODBYE, true);

            default:
                throw new SpeechletException(RESPONSE_INVALID_INTENT);

            }
        } else {
            throw new SpeechletException(RESPONSE_INVALID_INTENT);
        }

    } catch (NumberFormatException e) {
        LOG.error("", e);
        throw new SpeechletException(RESPONSE_UNKNOWN_CUSTOMER);

    } catch (Exception e) {
        LOG.error("", e);
        throw new SpeechletException(e.getMessage());
    }

}

From source file:ingest.inspect.PointCloudInspector.java

/**
 * Executes POST request to Point Cloud to grab the Payload
 * /*from  w  ww  .j  av a 2  s. c om*/
 * @param url
 *            The URL to post for point cloud api
 * @return The PointCloudResponse object containing metadata.
 */
private PointCloudResponse postPointCloudTemplate(String url, String payload) throws IOException {
    // Setup Basic Headers
    HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.APPLICATION_JSON);

    // Create the Request template and execute post
    HttpEntity<String> request = new HttpEntity<String>(payload, headers);
    String response = "";
    try {
        logger.log("Sending Metadata Request to Point Cloud Service", Severity.INFORMATIONAL,
                new AuditElement(INGEST, "requestPointCloudMetadata", url));
        response = restTemplate.postForObject(url, request, String.class);
    } catch (HttpServerErrorException e) {
        String error = "Error occurred posting to: " + url + "\nPayload: \n" + payload
                + "\nMost likely the payload source file is not accessible.";
        // this exception will be thrown until the s3 file is accessible to external services

        LOG.error(error, e);
        throw new HttpServerErrorException(e.getStatusCode(), error);
    }

    // Parse required fields from point cloud json response
    ObjectMapper mapper = new ObjectMapper();
    JsonNode root = mapper.readTree(response);
    double maxx = root.at("/response/metadata/maxx").asDouble();
    double maxy = root.at("/response/metadata/maxy").asDouble();
    double maxz = root.at("/response/metadata/maxz").asDouble();
    double minx = root.at("/response/metadata/minx").asDouble();
    double miny = root.at("/response/metadata/miny").asDouble();
    double minz = root.at("/response/metadata/minz").asDouble();
    String spatialreference = root.at("/response/metadata/spatialreference").asText();

    // Return the new PointCloudResponse object
    return new PointCloudResponse(spatialreference, maxx, maxy, maxz, minx, miny, minz);
}

From source file:org.mitre.mpf.mvc.controller.MediaController.java

@RequestMapping(value = "/saveURL", method = RequestMethod.POST)
@ResponseBody//w w w . j av  a 2s . co m
public Map<String, String> saveMedia(@RequestParam(value = "urls", required = true) String[] urls,
        @RequestParam(value = "desiredpath", required = true) String desiredpath, HttpServletResponse response)
        throws WfmProcessingException, MpfServiceException {
    log.debug("URL Upload to Directory:" + desiredpath + " urls:" + urls.length);

    String err = "Illegal or missing desiredpath";
    if (desiredpath == null) {
        log.error(err);
        throw new HttpServerErrorException(HttpStatus.INTERNAL_SERVER_ERROR, err);
    }
    ;
    String webTmpDirectory = propertiesUtil.getRemoteMediaCacheDirectory().getAbsolutePath();
    //verify the desired path
    File desiredPath = new File(desiredpath);
    if (!desiredPath.exists() || !desiredPath.getAbsolutePath().startsWith(webTmpDirectory)) {//make sure it is valid and within the remote-media directory
        log.error(err);
        throw new HttpServerErrorException(HttpStatus.INTERNAL_SERVER_ERROR, err);
    }

    //passing in urls as a list of Strings
    //download the media to the server
    //build a map of success or failure for each file with a custom response object
    Map<String, String> urlResultMap = new HashMap<String, String>();
    for (String enteredURL : urls) {
        enteredURL = enteredURL.trim();
        URI uri;
        try {
            uri = new URI(enteredURL);
            //the check for absolute URI determines if any scheme is present, regardless of validity
            //(which is checked in both this and the next try block)
            if (!uri.isAbsolute()) {
                uri = new URI("http://" + uri.toASCIIString());
            }
        } catch (URISyntaxException incorrectUriTranslation) {
            log.error("The string {} did not translate cleanly to a URI.", enteredURL, incorrectUriTranslation);
            urlResultMap.put(enteredURL, "String did not cleanly convert to URI");
            continue;
        }
        File newFile = null;
        String localName = null;
        try {
            URL url = uri.toURL(); //caught by MalformedURLException
            //will throw an IOException,which is already caught 
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("HEAD");
            connection.connect();
            connection.disconnect();

            String filename = url.getFile();
            if (filename.isEmpty()) {
                String err2 = "The filename does not exist when uploading from the url '" + url + "'";
                log.error(err2);
                urlResultMap.put(enteredURL, err2);
                continue;
            }

            if (!ioUtils.isApprovedFile(url)) {
                String contentType = ioUtils.getMimeType(url);
                String msg = "The media is not a supported type. Please add a whitelist." + contentType
                        + " entry to the mediaType.properties file.";
                log.error(msg + " URL:" + url);
                urlResultMap.put(enteredURL, msg);
                continue;
            }

            localName = uri.getPath();
            //we consider no path to be malformed for our purposes
            if (localName.isEmpty()) {
                throw new MalformedURLException(String.format("%s does not have valid path", uri));
            }

            //use the full path name for the filename to allow for more unique filenames
            localName = localName.substring(1);//remove the leading '/'
            localName = localName.replace("/", "-");//replace the rest of the path with -

            //get a new unique filename incase the name currently exists
            newFile = ioUtils.getNewFileName(desiredpath, localName);

            //save the file
            FileUtils.copyURLToFile(url, newFile);
            log.info("Completed write of {} to {}", uri.getPath(), newFile.getAbsolutePath());
            urlResultMap.put(enteredURL, "successful write to: " + newFile.getAbsolutePath());
        } catch (MalformedURLException badUrl) {
            log.error("URI {} could not be converted. ", uri, badUrl);
            urlResultMap.put(enteredURL, "Unable to locate media at the provided address.");
        } catch (IOException badWrite) {
            log.error("Error writing media to temp file from {}.", enteredURL, badWrite);
            urlResultMap.put(enteredURL,
                    "Unable to save media from this url. Please view the server logs for more information.");
            if (newFile != null && newFile.exists()) {
                newFile.delete();
            }
        } catch (Exception failure) { //catch the remaining exceptions
            //this is most likely a failed connection 
            log.error("Exception thrown while saving media from the url {}.", enteredURL, failure);
            urlResultMap.put(enteredURL,
                    "Error while saving media from this url. Please view the server logs for more information.");
        }
    }
    return urlResultMap;
}