Example usage for org.springframework.http HttpStatus INTERNAL_SERVER_ERROR

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

Introduction

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

Prototype

HttpStatus INTERNAL_SERVER_ERROR

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

Click Source Link

Document

500 Internal Server Error .

Usage

From source file:com.haulmont.restapi.controllers.FileDownloadController.java

@GetMapping("/{fileDescriptorId}")
public void downloadFile(@PathVariable String fileDescriptorId,
        @RequestParam(required = false) Boolean attachment, HttpServletResponse response) {
    UUID uuid;/*from   w w w.  jav  a2 s .  com*/
    try {
        uuid = UUID.fromString(fileDescriptorId);
    } catch (IllegalArgumentException e) {
        throw new RestAPIException("Invalid entity ID",
                String.format("Cannot convert %s into valid entity ID", fileDescriptorId),
                HttpStatus.BAD_REQUEST);
    }
    LoadContext<FileDescriptor> ctx = LoadContext.create(FileDescriptor.class).setId(uuid);
    FileDescriptor fd = dataService.load(ctx);
    if (fd == null) {
        throw new RestAPIException("File not found", "File not found. Id: " + fileDescriptorId,
                HttpStatus.NOT_FOUND);
    }

    try {
        response.setHeader("Cache-Control", "no-cache");
        response.setHeader("Pragma", "no-cache");
        response.setDateHeader("Expires", 0);
        response.setHeader("Content-Type", getContentType(fd));
        response.setHeader("Content-Disposition", (BooleanUtils.isTrue(attachment) ? "attachment" : "inline")
                + "; filename=\"" + fd.getName() + "\"");

        downloadFromMiddlewareAndWriteResponse(fd, response);
    } catch (Exception e) {
        log.error("Error on downloading the file {}", fileDescriptorId, e);
        throw new RestAPIException("Error on downloading the file", "", HttpStatus.INTERNAL_SERVER_ERROR);
    }
}

From source file:at.ac.tuwien.infosys.ArtifactBuilder.java

@RequestMapping(value = "/build", method = RequestMethod.POST)
public ResponseEntity<String> build(@RequestBody DeviceUpdateRequest updateRequest) {

    logger.info("Got request: " + updateRequest);

    if (updateRequest == null)
        return new ResponseEntity<String>(HttpStatus.BAD_REQUEST);

    updateRequest.setVersion(updateRequest.getVersion().replace(".", "_"));

    ResponseEntity<Component[]> dmsResponse = restTemplate.getForEntity(dmsURL, Component[].class,
            updateRequest.getComponent(), updateRequest.getVersion());

    logger.info("Invoked Component/Dependency-Management and received: " + dmsResponse.getStatusCode());

    if (dmsResponse.getStatusCode() != HttpStatus.OK)
        return new ResponseEntity<String>(HttpStatus.INTERNAL_SERVER_ERROR);

    Plan bundle = new Plan(dmsResponse.getBody());

    logger.info("Received following bundle: " + bundle);

    try {/*www . j  a v a  2  s  . c  om*/
        String idPrefix = updateRequest.getComponent() + "_" + updateRequest.getVersion();

        // search if an image for the respective component and version
        // already exists
        Image image = imageStorage.getUpdate(idPrefix);

        if (image == null) {
            Path imagePath = imageUtil.createImage(bundle, idPrefix);

            // Upload image to image store
            image = imageStorage.storeUpdate(updateRequest.getDeviceIds(), imageUtil.getImageId(),
                    Files.newInputStream(imagePath));

            logger.info("Finished uploading image to image-store");
        } else {
            logger.info("Image already present in image-store, reuse it!");
            if (image.getDeviceIds() == null)
                image.setDeviceIds(updateRequest.getDeviceIds());
        }

        // Invoke device manager to send image
        //
        //         Map<String, Object> map = new HashMap<String, Object>();
        //         map.put("force", updateRequest.isPush());

        ResponseEntity<String> managerResponse = restTemplate.postForEntity(managerURL, image, String.class);

        logger.info("Received request from device-manager: " + managerResponse.getStatusCode());

    } catch (IOException e) {
        e.printStackTrace();
        return new ResponseEntity<String>(HttpStatus.INTERNAL_SERVER_ERROR);
    } finally {
        if (imageUtil != null)
            try {
                imageUtil.clean();
            } catch (Exception e) {
            }
    }

    return new ResponseEntity<String>(HttpStatus.ACCEPTED);
}

From source file:com.ns.retailmgr.connector.gmaps.GMapConnectorTest.java

@Test(expected = RuntimeException.class)
public void test_getNearestShopDetails_Failure() {
    when(restTemplate.getForObject(anyString(), eq(GeoCodeLocInfo.class)))
            .thenThrow(new HttpServerErrorException(HttpStatus.INTERNAL_SERVER_ERROR));
    gmapConnector.getNearestShopDetails("12.8124,77.69");
}

From source file:com.crazyacking.learn.spring.actuator.ManagementPortAndPathSampleActuatorApplicationTests.java

@Test
public void testErrorPage() {
    @SuppressWarnings("rawtypes")
    ResponseEntity<Map> entity = new TestRestTemplate("user", getPassword())
            .getForEntity("http://localhost:" + this.port + "/error", Map.class);
    assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.INTERNAL_SERVER_ERROR);
    @SuppressWarnings("unchecked")
    Map<String, Object> body = entity.getBody();
    assertThat(body.get("status")).isEqualTo(999);
}

From source file:org.cloudfoundry.identity.uaa.codestore.CodeStoreEndpoints.java

@ExceptionHandler
public View handleException(Exception t, HttpServletRequest request) throws CodeStoreException {
    CodeStoreException e = new CodeStoreException("Unexpected error", t, HttpStatus.INTERNAL_SERVER_ERROR);
    if (t instanceof CodeStoreException) {
        e = (CodeStoreException) t;/*from  w w w.ja  va2s  .co m*/
    }
    // User can supply trace=true or just trace (unspecified) to get stack
    // traces
    boolean trace = request.getParameter("trace") != null && !request.getParameter("trace").equals("false");
    return new ConvertingExceptionView(
            new ResponseEntity<ExceptionReport>(new ExceptionReport(e, trace), e.getStatus()),
            messageConverters);
}

From source file:com.haulmont.restapi.controllers.FileUploadController.java

/**
 * Method for simple file upload. File contents are placed in the request body. Optional file name parameter is
 * passed as a query param./*from  w w  w .j  a  v  a2  s .  c  om*/
 */
@PostMapping(consumes = "!multipart/form-data")
public ResponseEntity<FileInfo> uploadFile(HttpServletRequest request,
        @RequestParam(required = false) String name) {
    try {
        String contentLength = request.getHeader("Content-Length");

        long size = 0;
        try {
            size = Long.parseLong(contentLength);
        } catch (NumberFormatException ignored) {
        }

        FileDescriptor fd = createFileDescriptor(name, size);

        ServletInputStream is = request.getInputStream();
        uploadToMiddleware(is, fd);
        saveFileDescriptor(fd);

        return createFileInfoResponseEntity(request, fd);
    } catch (Exception e) {
        log.error("File upload failed", e);
        throw new RestAPIException("File upload failed", "File upload failed",
                HttpStatus.INTERNAL_SERVER_ERROR);
    }
}

From source file:be.solidx.hot.rest.RestController.java

protected ResponseEntity<byte[]> buildErrorResponse(Exception e) {
    logger.error("", e);
    StringWriter stringWriter = new StringWriter();
    PrintWriter printWriter = new PrintWriter(stringWriter);
    e.printStackTrace(printWriter);/*from   www.j  a v  a  2s.  c o  m*/
    printWriter.flush();
    byte[] responseBytes;
    try {
        responseBytes = stringWriter.toString().getBytes(DEFAULT_CHARSET);
    } catch (UnsupportedEncodingException e1) {
        responseBytes = stringWriter.toString().getBytes();
    }
    return new ResponseEntity<byte[]>(responseBytes, HttpStatus.INTERNAL_SERVER_ERROR);
}

From source file:com.javafxpert.wikibrowser.WikiBitlyController.java

@RequestMapping(method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<Object> search(@RequestParam(value = "items", defaultValue = "") String items,
        @RequestParam(value = "lang") String lang) {
    // Example endpoint usage is bitly?items=Q24, Q30, Q23, Q16, Q20&lang=fr
    // Scrub the input, and output a string for the Bitly service similar to the following:
    // Q24,Q30,Q23,Q16,Q20
    String argStr = WikiBrowserUtils.scrubItemIds(items, false);
    log.info("argStr=" + argStr);

    BitlyResponseNear bitlyResponseNear = null;

    if (argStr.length() > 0) {
        String blat = wikiBrowserProperties.getBlat();
        String bitlyUrlPart = "https://api-ssl.bitly.com/v3/shorten?access_token=" + blat + "&longUrl=";

        String conceptMapUrlPart = null;

        try {//from  w w  w. java 2s.co m
            conceptMapUrlPart = URLEncoder.encode("http://conceptmap.io?items=" + argStr + "&lang=" + lang,
                    "UTF-8");
        } catch (UnsupportedEncodingException uee) {
            log.error("Exception whild encoding for bitly");
        }

        bitlyResponseNear = bitlyServiceResponse(bitlyUrlPart + conceptMapUrlPart);
    } else {
        log.warn("Invalid argument to WikiBitlyController /bitly endpoint: \"" + items + "\"");
    }

    return Optional.ofNullable(bitlyResponseNear).map(cr -> new ResponseEntity<>((Object) cr, HttpStatus.OK))
            .orElse(new ResponseEntity<>("Bitly request unsuccessful", HttpStatus.INTERNAL_SERVER_ERROR));
}

From source file:com.boot.pf.config.WebMvcConfig.java

@Bean
public EmbeddedServletContainerCustomizer containerCustomizer() {

    return (container -> {
        ErrorPage error401Page = new ErrorPage(HttpStatus.UNAUTHORIZED, "/401.html");
        ErrorPage error404Page = new ErrorPage(HttpStatus.NOT_FOUND, "/404.html");
        ErrorPage error500Page = new ErrorPage(HttpStatus.INTERNAL_SERVER_ERROR, "/500.html");

        container.addErrorPages(error401Page, error404Page, error500Page);
    });/*from   w ww  .  j a v  a2  s. co m*/
}

From source file:fi.hsl.parkandride.itest.ErrorHandlingITest.java

@Test
public void invalid_path_variable_type_is_reported_as_internal_error() {
    when().get(UrlSchema.FACILITIES + "/foo").then()
            .spec(assertResponse(HttpStatus.INTERNAL_SERVER_ERROR, TypeMismatchException.class))
            .body("message", is(
                    "Failed to convert value of type 'java.lang.String' to required type 'long'; nested exception is "
                            + "java.lang.NumberFormatException: For input string: \"foo\""))
            .body("violations", is(nullValue()));
}